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