Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

create-server.ts

1,074 lines33.6 KB

1import { convertSchemaToJsonSchema } from '@tanstack/ai'
2import type { AnyServerTool, SchemaInput } from '@tanstack/ai'
3import {
4 McpServer,
5 ProtocolError,
6 ProtocolErrorCode,
7 ResourceTemplate,
8 WebStandardStreamableHTTPServerTransport,
9 acceptedContent,
10 createMcpHandler,
11 fromJsonSchema,
12 isCallToolResult,
13 inputRequired,
14 inputResponse,
15 isLegacyRequest,
16 legacyStatelessFallback,
17 requireBearerAuth,
18} from '@modelcontextprotocol/server'
19import type {
20 AuthInfo,
21 BearerAuthOptions,
22 JsonSchemaType,
23 McpRequestContext,
24 McpServerFactory,
25 ServerContext,
26 StandardSchemaWithJSON,
27 ToolAnnotations,
28 Variables,
29} from '@modelcontextprotocol/server'
30import {
31 ToolInputRequiredError,
32 createServerToolContext,
33 inputDeclinedMessage,
34} from './context'
35import type { SampleRequest, ToolInputRequest } from './context'
36import { isServedOverStdio, rememberServerOptions } from './registry'
37import { parseToolOutput } from './output'
38import type { MCPResourceContext, MCPResourceList } from './definitions'
39import { getTask, startTask, toCallToolResult } from './tasks'
40import { inMemoryTaskStore } from './stores'
41import type { TaskStore } from './stores'
42​
43// ponytail: idle sessions close only when a later request runs the sweep.
44// A server that gets no traffic keeps them until the next request.
45const sessionIdleMs = 30 * 60 * 1000
46const inputKey = 'input'
47const sampleMaxTokens = 1024
48​
49const inputFormSchema = {
50 type: 'object' as const,
51 properties: {
52 value: { type: 'string' as const },
53 },
54 required: ['value'],
56​
57const emptyObjectSchema = fromJsonSchema({
58 type: 'object',
59 properties: {},
60})
61​
62type ProtocolYear = '2025' | '2026'
63​
64type McpResource = {
65 name: string
66 mimeType: string
67 uri?: string
68 uriTemplate?: string
69 list?: MCPResourceList
70 read: BivariantResourceRead
72​
73// A method type is bivariant, so a `read` with narrower params assigns.
74// The lint rule bans method signatures, hence the class.
75type BivariantResourceRead = BivariantResourceReadSignature['bivarianceHack']
76​
77declare abstract class BivariantResourceReadSignature {
78 abstract bivarianceHack(
79 uri: URL,
80 variables: Variables,
81 ctx: MCPResourceContext,
82 ): unknown
84​
85// A method type is bivariant. A function property is strict, so a prompt
86// with a specific input would not assign to `unknown`.
87type BivariantCallback<TInput, TOutput> = BivariantCallbackSignature<
88 TInput,
89 TOutput
90>['bivarianceHack']
91​
92declare abstract class BivariantCallbackSignature<TInput, TOutput> {
93 abstract bivarianceHack(input: TInput): TOutput
95​
96type McpPrompt = {
97 name: string
98 description: string
99 argsSchema: {
100 parse: (input: unknown) => unknown
101 }
102 render: BivariantCallback<unknown, unknown>
104​
105export type MCPServerOptions = {
106 name: string
107 version: string
108 tools?: ReadonlyArray<AnyServerTool>
109 resources?: ReadonlyArray<McpResource>
110 prompts?: ReadonlyArray<McpPrompt>
111 taskStore?: TaskStore
112 /**
113 * Bearer-token auth, in the shape the MCP SDK uses.
114 * `verifier` is an `OAuthTokenVerifier`. See `jwtVerifier` and
115 * `introspectionVerifier`. `requiredScopes` and `resourceMetadataUrl`
116 * are optional.
117 */
118 auth?: BearerAuthOptions
119 /**
120 * How to serve a spec 2025 client. `'stateless'` (the default) serves
121 * each spec 2025 request with a new server and keeps no session, so it
122 * works on a host with many instances. `'memory'` keeps sessions in this
123 * process for 30 idle minutes. `'reject'` answers every spec 2025 request
124 * with the SDK rejection. Under `serveMCPStdio`, the default is
125 * `'memory'`. Elicitation and client sampling need a
126 * session: in that mode `ctx.context.requestInput` throws, and
127 * `ctx.context.sample` calls `sample` or throws.
128 */
129 sessions?: 'memory' | 'reject' | 'stateless'
130 /**
131 * Receives errors that the SDK does not send to a tool: transport and
132 * protocol errors, and rejected requests. `serveMCPStdio` also sends its
133 * transport errors here instead of to stderr. It only reports. It does
134 * not change the response.
135 */
136 onerror?: (error: Error) => void
137 sample?: (request: SampleRequest) => Promise<unknown>
138 waitUntil?: (promise: Promise<unknown>) => void
139 /**
140 * Runs on every SDK `McpServer` this server builds, after the tools,
141 * resources, and prompts are registered and before the server connects.
142 * Declare more capabilities with `server.server.registerCapabilities` and
143 * add request handlers with `server.server.setRequestHandler`, for example
144 * to serve an MCP extension. Leave the methods this server already
145 * handles alone.
146 *
147 * It must be synchronous. The server connects as soon as it returns, so
148 * an async `setup` throws a `TypeError`.
149 */
150 setup?: (server: McpServer) => void
152​
153/**
154 * Per-request options for `server.handle`.
155 *
156 * `authInfo` is a token your own middleware already verified. The server
157 * skips its `auth` gate for that request.
158 * `context` is merged into `ctx.context` for every tool call, resource read,
159 * and resource list of that request.
160 */
161export type MCPHandleOptions = {
162 authInfo?: AuthInfo
163 context?: Record<string, unknown>
165​
166type AppContext = () => Record<string, unknown> | undefined
167​
168/**
169 * One MCP server and the definitions it serves.
170 *
171 * `tools`, `resources`, and `prompts` keep the types from the arguments.
172 * Export this object from one package and import it in another.
173 * `createMCPClient({ server })` then uses those types.
174 */
175export type MCPServer<
176 TTools extends ReadonlyArray<AnyServerTool> = ReadonlyArray<AnyServerTool>,
177 TResources extends ReadonlyArray<McpResource> = ReadonlyArray<McpResource>,
178 TPrompts extends ReadonlyArray<McpPrompt> = ReadonlyArray<McpPrompt>,
179> = {
180 readonly name: string
181 readonly version: string
182 readonly tools: TTools
183 readonly resources: TResources
184 readonly prompts: TPrompts
185 fetch: (request: Request) => Promise<Response>
186 handle: (request: Request, options?: MCPHandleOptions) => Promise<Response>
188​
189type LegacySession = {
190 transport: WebStandardStreamableHTTPServerTransport
191 server: McpServer
192 owner: string | undefined
193 lastUsed: number
194 // ponytail: the latest request's context. Two calls in flight on one
195 // session share it; both belong to the same owner.
196 context: Record<string, unknown> | undefined
198​
199type LegacySessions = Map<string, LegacySession>
200​
201/**
202 * Builds an MCP HTTP server.
203 *
204 * `options.name` and `options.version` name the server.
205 * `options.tools` is a list of `toolDefinition().server()` tools.
206 * `options.resources` uses `resourceDefinition().read()`.
207 * `options.prompts` uses `promptDefinition().render()`.
208 * `options.taskStore` keeps task records. The default store is in memory.
209 * `options.auth` checks the bearer token with the SDK gate.
210 * A missing or bad token gets a 401. A token without a required scope gets a 403.
211 * Spec 2025 sessions and tasks belong to the caller: the `clientId` of the
212 * token plus its `sub` claim. A tool reads the token as `ctx.context.authInfo`.
213 * A spec 2025 client gets no session unless `options.sessions` is `'memory'`.
214 * `options.sample` is the model adapter for `ctx.context.sample` on spec 2026.
215 * `options.waitUntil` receives the task promise so a worker can stay alive.
216 * `options.setup` gets each SDK `McpServer` before it connects, so it can add
217 * capabilities and request handlers, such as an MCP extension.
218 *
219 * The result has `fetch(request)`, `handle(request, options)`, `tools`,
220 * `resources`, and `prompts`. `handle` takes a token your own middleware
221 * verified and values for `ctx.context`.
222 * Those three lists keep the types you passed in.
223 * Export the result from one package and pass it to `createMCPClient({ server })` in another.
224 * `fetch` serves tools, resources, and prompts.
225 * It speaks spec `2026-07-28` and spec 2025.
226 * It does not serve the OAuth discovery documents. Mount
227 * `oauthMetadataResponse` at the app root for them.
228 *
229 * On spec 2025, a tool with `execution: 'task'` returns a task handle before
230 * the work ends. Spec 2026-07-28 has no tasks, so that tool runs inline there.
231 * A tool reads its hooks on `ctx.context`. Type it with `MCPToolContext`.
232 * On spec 2026, `ctx.context.sample` calls `options.sample` and does not ask the client.
233 * On spec 2025 with `sessions: 'memory'`, `ctx.context.sample` asks the MCP client.
234 * On spec 2026, `ctx.context.requestInput` stops the call until the client sends the answer.
235 * On spec 2025 with `sessions: 'memory'`, `ctx.context.requestInput` waits on the open session.
236 *
237 * @param options - Server name, version, tools, and the optional stores
238 *
239 * @example
240 * ```ts
241 * const server = createMCPServer({
242 * name: 'weather',
243 * version: '1.0.0',
244 * tools: [getWeather],
245 * })
246 *
247 * return server.fetch(request)
248 * ```
249 */
250export function createMCPServer<
251 const TTools extends ReadonlyArray<AnyServerTool> = [],
252 const TResources extends ReadonlyArray<McpResource> = [],
253 const TPrompts extends ReadonlyArray<McpPrompt> = [],
254>(
255 options: Omit<MCPServerOptions, 'tools' | 'resources' | 'prompts'> & {
256 tools?: TTools
257 resources?: TResources
258 prompts?: TPrompts
259 },
260) {
261 const taskStore = options.taskStore ?? inMemoryTaskStore()
262 const sessions: LegacySessions = new Map()
263 const tools = options.tools ?? []
264 const resources = options.resources ?? []
265 const prompts = options.prompts ?? []
266 const hasTaskTool = tools.some((tool) => tool.execution === 'task')
267 // Convert and compile each schema once. Every request reuses them.
268 const schemas = compileSchemas(tools, prompts)
269 const gate =
270 options.auth === undefined ? undefined : requireBearerAuth(options.auth)
271 // modern.fetch and legacyStatelessFallback hand the factory the same
272 // Request object that handle received.
273 const contextByRequest = new WeakMap<Request, Record<string, unknown>>()
274​
275 const factory: McpServerFactory = (ctx) => {
276 const request = ctx.requestInfo
277 return buildMcpServer({
278 options,
279 resources,
280 schemas,
281 taskStore,
282 era: ctx.era === 'modern' ? '2026' : '2025',
283 // Only the stateless leg builds a spec 2025 server here.
284 sessionless: ctx.era !== 'modern',
285 hasTaskTool,
286 owner: ownerOf(ctx.authInfo),
287 appContext: () =>
288 request === undefined ? undefined : contextByRequest.get(request),
289 })
290 }
291 const modern = createMcpHandler(factory, {
292 legacy: 'reject',
293 keepAliveMs: 0,
294 onerror: options.onerror,
295 })
296 // createMcpHandler hands its own stateless leg a clone of the request,
297 // so the context lookup would miss. Route spec 2025 here instead.
298 const stateless = legacyStatelessFallback(factory, options.onerror)
299​
300 const mcpServer = {
301 name: options.name,
302 version: options.version,
303 tools,
304 resources,
305 prompts,
306 /**
307 * Serves one MCP HTTP request. This is a plain Fetch handler.
308 *
309 * @param request - The HTTP request to the MCP route
310 */
311 fetch: (request: Request): Promise<Response> => mcpServer.handle(request),
312 /**
313 * Serves one MCP HTTP request with values from your own middleware.
314 *
315 * A spec 2026 request uses the per-request envelope.
316 * A spec 2025 request uses the session id header.
317 * When `auth` is set, a missing or invalid bearer token returns 401,
318 * and a token without a required scope returns 403.
319 * `handleOptions.authInfo` skips that gate. `handleOptions.context` reaches
320 * `ctx.context` of every tool call, resource read, and resource list of
321 * this request.
322 *
323 * @param request - The HTTP request to the MCP route
324 * @param handleOptions - A verified token and values for `ctx.context`
325 */
326 async handle(request: Request, handleOptions?: MCPHandleOptions) {
327 await closeIdleSessions(sessions)
328​
329 let authInfo = handleOptions?.authInfo
330 if (authInfo === undefined && gate !== undefined) {
331 const verdict = await gate(request)
332 if (verdict instanceof Response) return verdict
333 authInfo = verdict
334 }
335 const owner = ownerOf(authInfo)
336 const context = handleOptions?.context
337​
338 // Over stdio, one client owns the process, so sessions are the default.
339 const sessionMode =
340 options.sessions ??
341 (isServedOverStdio(mcpServer) ? 'memory' : 'stateless')
342 const legacy =
343 sessionMode !== 'reject' && (await isLegacyRequest(request))
344 if (legacy && sessionMode === 'memory') {
345 return legacyFetch(request, {
346 open: () =>
347 openLegacySession(request, {
348 sessions,
349 owner,
350 authInfo,
351 context,
352 onerror: options.onerror,
353 build: (appContext) =>
354 buildMcpServer({
355 options,
356 resources,
357 schemas,
358 taskStore,
359 era: '2025',
360 sessionless: false,
361 hasTaskTool,
362 owner,
363 appContext,
364 }),
365 }),
366 resume: (sessionId) =>
367 resumeLegacySession(request, sessionId, sessions, {
368 owner,
369 authInfo,
370 context,
371 }),
372 })
373 }
374​
375 if (context !== undefined) contextByRequest.set(request, context)
376 // The SDK passes authInfo through to the factory and to each handler.
377 const requestOptions = authInfo === undefined ? undefined : { authInfo }
378 if (legacy) return stateless(request, requestOptions)
379 if (
380 request.method === 'POST' &&
381 request.headers.get('mcp-method') === 'subscriptions/listen'
382 ) {
383 const body: unknown = await request
384 .clone()
385 .json()
386 .catch(() => undefined)
387 if (isRecord(body) && body.method === 'subscriptions/listen') {
388 return Response.json({
389 jsonrpc: '2.0',
390 id:
391 typeof body.id === 'string' || typeof body.id === 'number'
392 ? body.id
393 : null,
394 error: { code: -32601, message: 'Method not found' },
395 })
396 }
397 }
398 return modern.fetch(request, requestOptions)
399 },
400 }
401 rememberServerOptions(mcpServer, options)
402 return mcpServer
404​
405// Sessions and tasks belong to one caller: the client id plus the subject.
406function ownerOf(authInfo: McpRequestContext['authInfo']) {
407 if (authInfo === undefined) return undefined
408 const subject = authInfo.extra?.sub
409 return JSON.stringify([
410 authInfo.clientId,
411 typeof subject === 'string' ? subject : null,
412 ])
414​
415async function closeIdleSessions(sessions: LegacySessions) {
416 const cutoff = Date.now() - sessionIdleMs
417 for (const [id, session] of sessions) {
418 if (session.lastUsed > cutoff) continue
419 sessions.delete(id)
420 await session.transport.close().catch(() => undefined)
421 await session.server.close().catch(() => undefined)
422 }
424​
425type CompiledTool = {
426 tool: AnyServerTool
427 inputSchema: StandardSchemaWithJSON
428 outputSchema: StandardSchemaWithJSON | undefined
430​
431type CompiledPrompt = {
432 prompt: McpPrompt
433 argsSchema: StandardSchemaWithJSON
435​
436type CompiledSchemas = {
437 tools: ReadonlyArray<CompiledTool>
438 prompts: ReadonlyArray<CompiledPrompt>
440​
441function compileSchemas(
442 tools: ReadonlyArray<AnyServerTool>,
443 prompts: ReadonlyArray<McpPrompt>,
444): CompiledSchemas {
445 return {
446 tools: tools.map((tool) => ({
447 tool,
448 inputSchema: standardSchema(tool.inputSchema) ?? emptyObjectSchema,
449 outputSchema: outputSchemaOf(tool.outputSchema),
450 })),
451 prompts: prompts.map((prompt) => ({
452 prompt,
453 argsSchema: standardSchema(prompt.argsSchema) ?? emptyObjectSchema,
454 })),
455 }
457​
458// An output schema can have any root, like z.string(). The SDK wraps it in
459// `{ result }` for a spec 2025 client. A bare transform has no JSON Schema
460// for its output view, so that tool advertises no output schema.
461function outputSchemaOf(schema: unknown) {
462 try {
463 return standardSchema(schema, 'output')
464 } catch {
465 return undefined
466 }
468​
469function buildMcpServer(input: {
470 options: MCPServerOptions
471 resources: ReadonlyArray<McpResource>
472 schemas: CompiledSchemas
473 taskStore: TaskStore
474 era: ProtocolYear
475 sessionless: boolean
476 hasTaskTool: boolean
477 owner: string | undefined
478 appContext: AppContext
479}) {
480 const server = new McpServer(
481 { name: input.options.name, version: input.options.version },
482 serverOptions(input.era, input.hasTaskTool),
483 )
484 if (input.options.onerror !== undefined) {
485 server.server.onerror = input.options.onerror
486 }
487 for (const compiled of input.schemas.tools) {
488 registerServerTool(server, compiled, input)
489 }
490 for (const resource of input.resources) {
491 registerServerResource(server, resource, input.appContext)
492 }
493 for (const compiled of input.schemas.prompts) {
494 registerServerPrompt(server, compiled)
495 }
496 if (input.era === '2025') {
497 registerLegacyTaskMethods(server, input.taskStore, input.owner)
498 }
499 const setupResult: unknown = input.options.setup?.(server)
500 if (setupResult instanceof Promise) {
501 throw new TypeError('createMCPServer: setup must be synchronous')
502 }
503 return server
505​
506// Tasks exist on spec 2025-11-25 only. Spec 2026-07-28 has no tasks yet.
507function serverOptions(era: ProtocolYear, hasTaskTool: boolean) {
508 return {
509 capabilities: {
510 tools: { listChanged: false },
511 resources: { listChanged: false },
512 prompts: { listChanged: false },
513 ...(hasTaskTool && era === '2025'
514 ? { tasks: { requests: { tools: { call: {} } } } }
515 : {}),
516 },
517 }
519​
520function registerServerTool(
521 server: McpServer,
522 { tool, inputSchema, outputSchema: compiledOutput }: CompiledTool,
523 input: {
524 options: MCPServerOptions
525 taskStore: TaskStore
526 era: ProtocolYear
527 sessionless: boolean
528 owner: string | undefined
529 appContext: AppContext
530 },
531) {
532 // A task tool answers with a task handle, not with its output.
533 const asTask = tool.execution === 'task' && input.era === '2025'
534 const outputSchema = asTask ? undefined : compiledOutput
535 const registered = server.registerTool(
536 tool.name,
537 {
538 ...toolPresentation(tool.metadata),
539 description: tool.description,
540 inputSchema,
541 outputSchema,
542 },
543 async (args, sdkCtx) => {
544 if (asTask) {
545 return runTaskTool(tool, args, input, sdkCtx.http?.authInfo)
546 }
547 const ctx = toolCallContext(
548 input.era,
549 input.sessionless,
550 sdkCtx,
551 input.options.sample,
552 input.appContext,
553 )
554 try {
555 const output = await runTool(tool, args, ctx)
556 return toCallToolResult(output, outputSchema !== undefined)
557 } catch (error) {
558 if (error instanceof ToolInputRequiredError) {
559 return inputRequired({
560 inputRequests: {
561 [inputKey]: inputRequired.elicit({
562 message: error.request.message,
563 mode: 'form',
564 requestedSchema: inputFormSchema,
565 }),
566 },
567 })
568 }
569 throw error
570 }
571 },
572 )
573 if (asTask) {
574 registered.execution = { taskSupport: 'required' }
575 }
577​
578const annotationHints = [
579 'readOnlyHint',
580 'destructiveHint',
581 'idempotentHint',
582 'openWorldHint',
583] as const
584​
585// `metadata.title`, `metadata.annotations`, and `metadata._meta` on a tool
586// definition reach the host as the MCP tool title, annotations, and `_meta`.
587// `_meta.ui.resourceUri` links an MCP Apps view to the tool.
588function toolPresentation(metadata: Record<string, unknown> | undefined) {
589 const title = typeof metadata?.title === 'string' ? metadata.title : undefined
590 const _meta = isRecord(metadata?._meta) ? metadata._meta : undefined
591 const raw = metadata?.annotations
592 if (!isRecord(raw)) return { title, _meta }
593 const annotations: ToolAnnotations = {}
594 if (typeof raw.title === 'string') annotations.title = raw.title
595 for (const hint of annotationHints) {
596 if (typeof raw[hint] === 'boolean') annotations[hint] = raw[hint]
597 }
598 return { title, annotations, _meta }
600​
601async function runTaskTool(
602 tool: AnyServerTool,
603 args: unknown,
604 input: {
605 options: MCPServerOptions
606 taskStore: TaskStore
607 owner: string | undefined
608 appContext: AppContext
609 },
610 authInfo: AuthInfo | undefined,
611) {
612 const ctx = taskContext(input.options.sample, authInfo, input.appContext)
613 const handle = await startTask(() => runTool(tool, args, ctx), {
614 store: input.taskStore,
615 waitUntil: input.options.waitUntil,
616 owner: input.owner,
617 })
618 const polled = await getTask(handle.taskId, input.taskStore, input.owner)
619 if (polled === null) {
620 throw new Error(`Task ${handle.taskId} was not saved.`)
621 }
622 // Spec 2025-11-25 `CreateTaskResult` is `{ task }`. The SDK also needs
623 // `content` on a tools/call result, so the handle carries the task id.
624 return {
625 content: [{ type: 'text' as const, text: polled.task.taskId }],
626 task: polled.task,
627 }
629​
630// A task keeps running after tools/call answers with the task handle.
631// So it must not use that request: its signal, elicitation, or sampling.
632function taskContext(
633 sample: MCPServerOptions['sample'],
634 authInfo: AuthInfo | undefined,
635 appContext: AppContext,
636) {
637 return {
638 context: {
639 ...appContext(),
640 authInfo,
641 async requestInput(_request: ToolInputRequest): Promise<never> {
642 throw new Error(
643 'ctx.context.requestInput is not supported in an execution: "task" tool.',
644 )
645 },
646 async sample(request: SampleRequest) {
647 if (sample === undefined) {
648 throw new Error(
649 'ctx.context.sample in an execution: "task" tool needs the sample option of createMCPServer.',
650 )
651 }
652 return sample(request)
653 },
654 },
655 // ponytail: nothing aborts this signal until tasks/cancel is implemented.
656 abortSignal: new AbortController().signal,
657 emitCustomEvent() {},
658 }
660​
661async function runTool(
662 tool: AnyServerTool,
663 args: unknown,
664 ctx: ReturnType<typeof toolCallContext> | ReturnType<typeof taskContext>,
665) {
666 const execute = tool.execute
667 if (execute === undefined) {
668 throw new Error(`Tool ${tool.name} has no execute function.`)
669 }
670 const output: unknown = await execute(args ?? {}, ctx)
671 return parseToolOutput(tool, output, isCallToolResult)
673​
674// A stateless spec 2025 server never saw initialize and keeps no session,
675// so it cannot send the client a request.
676const sessionlessMessage =
677 'needs a spec 2025 session. Set sessions: "memory" in createMCPServer.'
678​
679function toolCallContext(
680 era: ProtocolYear,
681 sessionless: boolean,
682 sdkCtx: ServerContext,
683 sample: MCPServerOptions['sample'],
684 appContext: AppContext,
685) {
686 const authInfo = sdkCtx.http?.authInfo
687 const hooks =
688 era === '2025'
689 ? createServerToolContext({
690 era: '2025',
691 waitForInput: sessionless
692 ? () =>
693 Promise.reject(
694 new Error(`ctx.context.requestInput ${sessionlessMessage}`),
695 )
696 : (request) => waitForInput(sdkCtx, request),
697 clientSample: sessionless
698 ? (request) =>
699 sample === undefined
700 ? Promise.reject(
701 new Error(`ctx.context.sample ${sessionlessMessage}`),
702 )
703 : sample(request)
704 : (request) => askClientToSample(sdkCtx, request),
705 sample,
706 authInfo,
707 })
708 : createServerToolContext({
709 era: '2026',
710 inputAnswer: inputAnswer(sdkCtx),
711 inputDeclined: inputDeclined(sdkCtx),
712 sample,
713 authInfo,
714 })
715 // The hooks win over a same-named value from `handle` options.
716 return {
717 context: { ...appContext(), ...hooks },
718 abortSignal: sdkCtx.mcpReq.signal,
719 emitCustomEvent() {},
720 }
722​
723function inputAnswer(sdkCtx: ServerContext) {
724 const content = acceptedContent(sdkCtx.mcpReq.inputResponses, inputKey)
725 if (content === undefined) return undefined
726 if (typeof content.value === 'string') return content.value
727 return content
729​
730// A decline or a cancel must end the call. Without this check the tool
731// asks again, and the client shows the same question again.
732function inputDeclined(sdkCtx: ServerContext) {
733 const view = inputResponse(sdkCtx.mcpReq.inputResponses, inputKey)
734 return view.kind === 'elicit' && view.action !== 'accept'
736​
737async function waitForInput(sdkCtx: ServerContext, request: ToolInputRequest) {
738 const result = await sdkCtx.mcpReq.elicitInput({
739 message: request.message,
740 mode: 'form',
741 requestedSchema: inputFormSchema,
742 })
743 const declined = result.action !== 'accept' || result.content === undefined
744 if (declined) {
745 throw new Error(inputDeclinedMessage)
746 }
747 const content = result.content
748 if (content !== undefined && typeof content.value === 'string') {
749 return content.value
750 }
751 return content
753​
754async function askClientToSample(
755 sdkCtx: ServerContext,
756 request: SampleRequest,
757) {
758 const messages = request.messages.map((message) => ({
759 role:
760 message.role === 'assistant' ? ('assistant' as const) : ('user' as const),
761 content: { type: 'text' as const, text: message.content },
762 }))
763 const result = await sdkCtx.mcpReq.requestSampling({
764 messages,
765 maxTokens: sampleMaxTokens,
766 })
767 return textFromContent(result.content)
769​
770function textFromContent(content: unknown) {
771 if (isTextBlock(content)) return content.text
772 if (!Array.isArray(content)) {
773 throw new Error('The client sample result has no text.')
774 }
775 const blocks = content
776 for (const block of blocks) {
777 if (isTextBlock(block)) return block.text
778 }
779 throw new Error('The client sample result has no text.')
781​
782function isTextBlock(value: unknown): value is { type: 'text'; text: string } {
783 return (
784 isRecord(value) && value.type === 'text' && typeof value.text === 'string'
785 )
787​
788function registerServerResource(
789 server: McpServer,
790 resource: McpResource,
791 appContext: AppContext,
792) {
793 const metadata = { mimeType: resource.mimeType }
794 const resourceContext = (sdkCtx: ServerContext): MCPResourceContext => ({
795 context: { ...appContext(), authInfo: sdkCtx.http?.authInfo },
796 })
797 const read = async (uri: URL, variables: Variables, sdkCtx: ServerContext) =>
798 resourceContents(
799 uri.href,
800 resource.mimeType,
801 await resource.read(uri, variables, resourceContext(sdkCtx)),
802 )
803 if (resource.uri !== undefined) {
804 server.registerResource(resource.name, resource.uri, metadata, (uri, ctx) =>
805 read(uri, {}, ctx),
806 )
807 return
808 }
809 if (resource.uriTemplate === undefined) return
810 const list = resource.list
811 const template = new ResourceTemplate(resource.uriTemplate, {
812 list:
813 list === undefined
814 ? undefined
815 : (sdkCtx: ServerContext) => list(resourceContext(sdkCtx)),
816 })
817 // A template gets the variables the SDK matched in the asked-for URI.
818 server.registerResource(resource.name, template, metadata, read)
820​
821function resourceContents(uri: string, mimeType: string, body: unknown) {
822 if (isRecord(body)) {
823 // A `{ text | blob }` body can name its own MIME type: one template can
824 // serve many types. Any other object is sent as JSON with the default.
825 const own = typeof body.mimeType === 'string' ? body.mimeType : mimeType
826 if (typeof body.text === 'string') {
827 return { contents: [{ uri, mimeType: own, text: body.text }] }
828 }
829 if (typeof body.blob === 'string') {
830 return { contents: [{ uri, mimeType: own, blob: body.blob }] }
831 }
832 }
833 if (typeof body === 'string') {
834 return { contents: [{ uri, mimeType, text: body }] }
835 }
836 // JSON.stringify(undefined) is undefined. A text block needs a string.
837 return { contents: [{ uri, mimeType, text: JSON.stringify(body) ?? '' }] }
839​
840function registerServerPrompt(
841 server: McpServer,
842 { prompt, argsSchema }: CompiledPrompt,
843) {
844 server.registerPrompt(
845 prompt.name,
846 { description: prompt.description, argsSchema },
847 async (args) => {
848 const rendered = await prompt.render(args ?? {})
849 return { messages: promptMessages(rendered) }
850 },
851 )
853​
854function promptMessages(rendered: unknown) {
855 const items = Array.isArray(rendered) ? rendered.filter(isPromptMessage) : []
856 return items.map((item) => {
857 const content = { type: 'text' as const, text: item.content }
858 if (item.role === 'assistant') {
859 return { role: 'assistant' as const, content }
860 }
861 return { role: 'user' as const, content }
862 })
864​
865function isPromptMessage(
866 value: unknown,
867): value is { role: string; content: string } {
868 return (
869 isRecord(value) &&
870 typeof value.role === 'string' &&
871 typeof value.content === 'string'
872 )
874​
875const taskIdParams = {
876 '~standard': {
877 version: 1 as const,
878 vendor: 'tanstack-ai-mcp',
879 validate(value: unknown) {
880 const taskId = isRecord(value) ? value.taskId : undefined
881 if (typeof taskId !== 'string' || taskId.length === 0) {
882 return { issues: [{ message: 'taskId is required' }] }
883 }
884 return { value: { taskId } }
885 },
886 },
888​
889function registerLegacyTaskMethods(
890 server: McpServer,
891 store: TaskStore,
892 owner: string | undefined,
893) {
894 server.server.setRequestHandler(
895 'tasks/get',
896 { params: taskIdParams },
897 async (params) => {
898 const polled = await getTask(taskIdFrom(params), store, owner)
899 if (polled === null) {
900 throw new ProtocolError(
901 ProtocolErrorCode.InvalidParams,
902 'Task not found',
903 )
904 }
905 return polled.task
906 },
907 )
908 server.server.setRequestHandler(
909 'tasks/result',
910 { params: taskIdParams },
911 async (params) => {
912 const polled = await getTask(taskIdFrom(params), store, owner)
913 if (polled === null || polled.record.status !== 'completed') {
914 throw new ProtocolError(
915 ProtocolErrorCode.InvalidParams,
916 'Task result is not ready',
917 )
918 }
919 return toCallToolResult(polled.record.result)
920 },
921 )
923​
924function taskIdFrom(params: unknown) {
925 if (!isRecord(params) || typeof params.taskId !== 'string') {
926 throw new ProtocolError(
927 ProtocolErrorCode.InvalidParams,
928 'taskId is required',
929 )
930 }
931 return params.taskId
933​
934// Input schemas and prompt arguments must have an object root.
935// An output schema can have any root and uses the parsed (output) view.
936function standardSchema(schema: unknown, io: 'input' | 'output' = 'input') {
937 if (!isSchemaInput(schema)) return undefined
938 const jsonSchema = convertSchemaToJsonSchema(schema, { io })
939 if (io === 'input') {
940 return isJsonObjectSchema(jsonSchema)
941 ? fromJsonSchema(jsonSchema)
942 : undefined
943 }
944 return isJsonSchemaRoot(jsonSchema) ? fromJsonSchema(jsonSchema) : undefined
946​
947// The converter returns one JSON Schema object for a Standard Schema.
948function isJsonSchemaRoot(value: unknown): value is JsonSchemaType {
949 return isRecord(value)
951​
952function isSchemaInput(schema: unknown): schema is SchemaInput {
953 if (!isRecord(schema)) return false
954 if ('~standard' in schema) return true
955 return schema.type !== undefined
957​
958function isJsonObjectSchema(value: unknown): value is { type: 'object' } {
959 return isRecord(value) && value.type === 'object'
961​
962async function legacyFetch(
963 request: Request,
964 routes: {
965 open: () => Promise<Response>
966 resume: (sessionId: string) => Promise<Response>
967 },
968) {
969 const sessionId = request.headers.get('mcp-session-id')
970 if (sessionId !== null && sessionId.length > 0) {
971 return routes.resume(sessionId)
972 }
973 return routes.open()
975​
976async function resumeLegacySession(
977 request: Request,
978 sessionId: string,
979 sessions: LegacySessions,
980 caller: {
981 owner: string | undefined
982 authInfo: AuthInfo | undefined
983 context: Record<string, unknown> | undefined
984 },
985) {
986 const session = sessions.get(sessionId)
987 // Another caller gets the same answer as an unknown id.
988 if (session === undefined || session.owner !== caller.owner) {
989 return sessionNotFound()
990 }
991 session.lastUsed = Date.now()
992 session.context = caller.context
993 return session.transport.handleRequest(request, {
994 authInfo: caller.authInfo,
995 })
997​
998async function openLegacySession(
999 request: Request,
1000 input: {
1001 sessions: LegacySessions
1002 owner: string | undefined
1003 authInfo: AuthInfo | undefined
1004 context: Record<string, unknown> | undefined
1005 onerror: ((error: Error) => void) | undefined
1006 build: (appContext: AppContext) => McpServer
1007 },
1008) {
1009 // Before the session exists, the opening request's context applies.
1010 let session: LegacySession | undefined
1011 let server: McpServer
1012 try {
1013 server = input.build(() =>
1014 session === undefined ? input.context : session.context,
1016 } catch (error) {
1017 // `setup` runs in build. Answer the way the SDK does on the other paths.
1018 input.onerror?.(error instanceof Error ? error : new Error(String(error)))
1019 return internalError()
1021 const transport = new WebStandardStreamableHTTPServerTransport({
1022 sessionIdGenerator: () => crypto.randomUUID(),
1023 enableJsonResponse: true,
1024 keepAliveMs: 0,
1025 onsessioninitialized: (id) => {
1026 session = {
1027 transport,
1028 server,
1029 owner: input.owner,
1030 lastUsed: Date.now(),
1031 context: input.context,
1033 input.sessions.set(id, session)
1034 },
1035 onsessionclosed: (id) => {
1036 input.sessions.delete(id)
1037 },
1038 })
1039 try {
1040 await server.connect(transport)
1041 return await transport.handleRequest(request, {
1042 authInfo: input.authInfo,
1043 })
1044 } finally {
1045 // A request that never opens a session must not keep the server.
1046 if (transport.sessionId === undefined) await server.close()
1049​
1050function internalError() {
1051 return Response.json(
1053 jsonrpc: '2.0',
1054 id: null,
1055 error: { code: -32603, message: 'Internal server error' },
1056 },
1057 { status: 500 },
1060​
1061function sessionNotFound() {
1062 return Response.json(
1064 jsonrpc: '2.0',
1065 id: null,
1066 error: { code: -32001, message: 'Session not found' },
1067 },
1068 { status: 404 },
1071​
1072function isRecord(value: unknown): value is Record<string, unknown> {
1073 return typeof value === 'object' && value !== null && !Array.isArray(value)