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

create-server.test.ts

1,200 lines36.7 KB

1import {
2 Client,
3 StreamableHTTPClientTransport,
4} from '@modelcontextprotocol/client'
5import { OAuthError, OAuthErrorCode } from '@modelcontextprotocol/server'
6import type { OAuthTokenVerifier } from '@modelcontextprotocol/server'
7import { toolDefinition } from '@tanstack/ai'
8import { describe, expect, it, vi } from 'vitest'
9import { z } from 'zod'
10import {
11 promptDefinition,
12 resourceDefinition,
13} from '../../src/server/definitions'
14import { createMCPServer } from '../../src/server/create-server'
15import type { MCPHandleOptions } from '../../src/server/create-server'
16import type { MCPToolContext, SampleRequest } from '../../src/server/context'
17import { inMemoryTaskStore } from '../../src/server/stores'
18import { MCPInputRequiredError } from '../../src/input-required'
19import { callMcpTool } from '../../src/tools'
20​
21const serverUrl = new URL('https://mcp.example.com/mcp')
22const resourceMetadataUrl =
23 'https://mcp.example.com/.well-known/oauth-protected-resource/mcp'
24​
25const summaryRequest: SampleRequest = {
26 messages: [{ role: 'user', content: 'Draft a summary' }],
28​
29// Spec 2025-11-25 task shapes.
30const taskShape = z.looseObject({
31 taskId: z.string(),
32 status: z.string(),
33 ttl: z.null(),
34})
35const createTaskResult = z.looseObject({ task: taskShape })
36const callToolResult = z.looseObject({
37 content: z.array(z.looseObject({ type: z.string() })),
38})
39​
40function taskCall(client: Client, name: string) {
41 return client.request(
42 { method: 'tools/call', params: { name, arguments: {}, task: {} } },
43 createTaskResult,
44 )
46​
47function taskGet(client: Client, taskId: string) {
48 return client.request({ method: 'tasks/get', params: { taskId } }, taskShape)
50​
51function taskResultOf(client: Client, taskId: string) {
52 return client.request(
53 { method: 'tasks/result', params: { taskId } },
54 callToolResult,
55 )
57​
58function echoTool() {
59 return toolDefinition({
60 name: 'echo',
61 description: 'Echo text',
62 inputSchema: z.object({ text: z.string() }),
63 }).server(async (args) => args.text)
65​
66function readmeResource() {
67 return resourceDefinition({
68 uri: 'file:///readme.md',
69 name: 'readme',
70 mimeType: 'text/markdown',
71 }).read(async () => ({ text: 'hello' }))
73​
74function summarizePrompt() {
75 return promptDefinition({
76 name: 'summarize',
77 description: 'Summarize a topic',
78 argsSchema: z.object({ topic: z.string() }),
79 }).render(async (args) => [{ role: 'user', content: args.topic }])
81​
82function surfaceServer() {
83 return createMCPServer({
84 name: 'weather',
85 version: '1.0.0',
86 tools: [echoTool()],
87 resources: [readmeResource()],
88 prompts: [summarizePrompt()],
89 })
91​
92// The SDK verifier shape. Each token is its own subject on one client.
93// `accept` limits the verifier to one token.
94function tokenVerifier(accept?: string): OAuthTokenVerifier {
95 return {
96 async verifyAccessToken(token) {
97 if (accept !== undefined && token !== accept) {
98 throw new OAuthError(OAuthErrorCode.InvalidToken, 'Unknown token')
99 }
100 return {
101 token,
102 clientId: 'tester',
103 scopes: ['mcp'],
104 expiresAt: Math.floor(Date.now() / 1000) + 3600,
105 extra: { sub: token },
106 }
107 },
108 }
110​
111const subjectAuth = { verifier: tokenVerifier() }
112​
113function initializeRequest(token: string) {
114 return new Request(serverUrl, {
115 method: 'POST',
116 headers: {
117 authorization: `Bearer ${token}`,
118 'content-type': 'application/json',
119 accept: 'application/json, text/event-stream',
120 },
121 body: JSON.stringify({
122 jsonrpc: '2.0',
123 id: 1,
124 method: 'initialize',
125 params: {
126 protocolVersion: '2025-11-25',
127 capabilities: {},
128 clientInfo: { name: 'raw', version: '1.0.0' },
129 },
130 }),
131 })
133​
134function sessionRequest(token: string, sessionId: string) {
135 return new Request(serverUrl, {
136 method: 'POST',
137 headers: {
138 authorization: `Bearer ${token}`,
139 'content-type': 'application/json',
140 accept: 'application/json, text/event-stream',
141 'mcp-session-id': sessionId,
142 'mcp-protocol-version': '2025-11-25',
143 },
144 body: JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'tools/list' }),
145 })
147​
148// A spec 2026 tools/list request, with or without a bearer token.
149function mcpRequest(token: string | undefined) {
150 return new Request(serverUrl, {
151 method: 'POST',
152 headers: {
153 ...(token === undefined ? {} : { authorization: `Bearer ${token}` }),
154 'content-type': 'application/json',
155 accept: 'application/json, text/event-stream',
156 },
157 body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }),
158 })
160​
161async function openSession(
162 server: { fetch(request: Request): Promise<Response> },
163 token: string,
164) {
165 const opened = await server.fetch(initializeRequest(token))
166 const sessionId = opened.headers.get('mcp-session-id')
167 if (sessionId === null) throw new Error('The server opened no session')
168 return sessionId
170​
171function deferredText() {
172 const box: { resolve?: (value: { text: string }) => void } = {}
173 const work = new Promise<{ text: string }>((resolve) => {
174 box.resolve = resolve
175 })
176 const resolve = box.resolve
177 if (resolve === undefined) {
178 throw new Error('The deferred work has no resolve')
179 }
180 return { work, resolve }
182​
183async function withClient(
184 server: {
185 fetch(request: Request): Promise<Response>
186 handle(request: Request, options?: MCPHandleOptions): Promise<Response>
187 },
188 hooks: {
189 era: '2025' | '2026'
190 authToken?: string
191 handleOptions?: MCPHandleOptions
192 onResponse?: (text: string) => void
193 prepare?: (client: Client) => void
194 },
195 run: (
196 client: Client,
197 transport: StreamableHTTPClientTransport,
198 ) => Promise<void>,
199) {
200 const versionNegotiation =
201 hooks.era === '2026' ? { mode: { pin: '2026-07-28' } } : undefined
202 const client = new Client(
203 { name: 'tester', version: '1.0.0' },
204 {
205 versionNegotiation,
206 capabilities: { elicitation: { form: {} }, sampling: {} },
207 },
208 )
209 hooks.prepare?.(client)
210 const transport = new StreamableHTTPClientTransport(serverUrl, {
211 authProvider:
212 hooks.authToken === undefined
213 ? undefined
214 : { token: async () => hooks.authToken },
215 fetch: async (input, init) => {
216 const request = new Request(input, init)
217 const response =
218 hooks.handleOptions === undefined
219 ? await server.fetch(request)
220 : await server.handle(request, hooks.handleOptions)
221 if (hooks.onResponse !== undefined) {
222 hooks.onResponse(await response.clone().text())
223 }
224 return response
225 },
226 })
227 await client.connect(transport)
228 try {
229 await run(client, transport)
230 } finally {
231 await client.close()
232 }
234​
235describe('createMCPServer', () => {
236 it('lists and calls a tool for a spec 2026 request', async () => {
237 const server = surfaceServer()
238​
239 await withClient(server, { era: '2026' }, async (client) => {
240 const listed = await client.listTools()
241 expect(listed.tools.map((tool) => tool.name)).toEqual(['echo'])
242​
243 const echoed = await client.callTool({
244 name: 'echo',
245 arguments: { text: 'hi' },
246 })
247 expect(echoed.content).toEqual([{ type: 'text', text: 'hi' }])
248​
249 const resources = await client.listResources()
250 expect(resources.resources.map((resource) => resource.name)).toEqual([
251 'readme',
252 ])
253 const readme = await client.readResource({ uri: 'file:///readme.md' })
254 expect(readme.contents).toEqual([
255 { uri: 'file:///readme.md', mimeType: 'text/markdown', text: 'hello' },
256 ])
257​
258 const prompts = await client.listPrompts()
259 expect(prompts.prompts.map((prompt) => prompt.name)).toEqual([
260 'summarize',
261 ])
262 const summary = await client.getPrompt({
263 name: 'summarize',
264 arguments: { topic: 'weather' },
265 })
266 expect(summary.messages).toEqual([
267 { role: 'user', content: { type: 'text', text: 'weather' } },
268 ])
269 })
270 })
271​
272 it('lists and calls a tool for a spec 2025 session', async () => {
273 const server = surfaceServer()
274​
275 await withClient(server, { era: '2025' }, async (client, transport) => {
276 expect(transport.sessionId).toEqual(expect.any(String))
277​
278 const listed = await client.listTools()
279 expect(listed.tools.map((tool) => tool.name)).toEqual(['echo'])
280​
281 const echoed = await client.callTool({
282 name: 'echo',
283 arguments: { text: 'hi' },
284 })
285 expect(echoed.content).toEqual([{ type: 'text', text: 'hi' }])
286 })
287 })
288​
289 it('returns a spec 2025 task handle before the task tool finishes', async () => {
290 const taskStore = inMemoryTaskStore()
291 const gate = deferredText()
292 let finished = false
293 const calls: Array<Promise<unknown>> = []
294 const server = createMCPServer({
295 name: 'tasks',
296 version: '1.0.0',
297 taskStore,
298 waitUntil(promise) {
299 calls.push(promise)
300 },
301 tools: [
302 toolDefinition({
303 name: 'slow',
304 description: 'Slow work',
305 execution: 'task',
306 }).server(async () => {
307 const result = await gate.work
308 finished = true
309 return result
310 }),
311 ],
312 })
313​
314 await withClient(server, { era: '2025' }, async (client) => {
315 expect(client.getServerCapabilities()?.tasks).toEqual({
316 requests: { tools: { call: {} } },
317 })
318 const listed = await client.listTools()
319 expect(listed.tools[0]?.execution).toEqual({ taskSupport: 'required' })
320​
321 // Spec 2025-11-25 CreateTaskResult: the task rides under `task`.
322 const created = await taskCall(client, 'slow')
323 expect(finished).toBe(false)
324 expect(created.task).toMatchObject({ status: 'working', ttl: null })
325 const taskId = created.task.taskId
326 expect(taskId.length).toBeGreaterThan(0)
327 expect(await taskStore.get(taskId)).toEqual({
328 taskId,
329 status: 'working',
330 ttl: null,
331 createdAt: expect.any(String),
332 lastUpdatedAt: expect.any(String),
333 })
334​
335 const inflight = calls[0]
336 if (inflight === undefined) {
337 throw new Error('waitUntil did not receive a promise')
338 }
339 gate.resolve({ text: 'done' })
340 await inflight
341 expect(finished).toBe(true)
342​
343 expect(await taskGet(client, taskId)).toMatchObject({
344 taskId,
345 status: 'completed',
346 ttl: null,
347 })
348 expect(await taskResultOf(client, taskId)).toEqual({
349 content: [{ type: 'text', text: '{"text":"done"}' }],
350 structuredContent: { text: 'done' },
351 })
352 })
353 })
354​
355 it('runs a task tool inline for a spec 2026 request', async () => {
356 // Spec 2026-07-28 has no tasks. The call waits for the tool output.
357 const taskStore = inMemoryTaskStore()
358 const server = createMCPServer({
359 name: 'tasks',
360 version: '1.0.0',
361 taskStore,
362 tools: [
363 toolDefinition({
364 name: 'slow',
365 description: 'Slow work',
366 execution: 'task',
367 }).server(async () => 'done'),
368 ],
369 })
370​
371 await withClient(server, { era: '2026' }, async (client) => {
372 const listed = await client.listTools()
373 expect(listed.tools[0]?.execution).toBeUndefined()
374 const called = await client.callTool({ name: 'slow', arguments: {} })
375 expect(called.content).toEqual([{ type: 'text', text: 'done' }])
376 })
377 })
378​
379 it('ends the call when the user cancels a spec 2026 input request', async () => {
380 const server = createMCPServer({
381 name: 'weather',
382 version: '1.0.0',
383 tools: [
384 toolDefinition({
385 name: 'ask',
386 description: 'Ask for a city',
387 inputSchema: z.object({}),
388 }).server<MCPToolContext>(async (_args, ctx) => {
389 const city = await ctx.context.requestInput({
390 message: 'Which city?',
391 })
392 return `Forecast for ${String(city)}`
393 }),
394 ],
395 })
396​
397 await withClient(server, { era: '2026' }, async (client) => {
398 await expect(
399 callMcpTool(client, 'ask', {}, false),
400 ).rejects.toBeInstanceOf(MCPInputRequiredError)
401​
402 // A cancel must not ask again. The tool ends with a tool error.
403 const cancelled = await callMcpTool(client, 'ask', {}, false, undefined, {
404 status: 'cancelled',
405 })
406 expect(cancelled.isError).toBe(true)
407 expect(JSON.stringify(cancelled.content)).toContain(
408 'The user did not accept the input request.',
409 )
410​
411 const answered = await callMcpTool(client, 'ask', {}, false, undefined, {
412 status: 'resolved',
413 payload: { value: 'Paris' },
414 })
415 expect(answered.content).toEqual([
416 { type: 'text', text: 'Forecast for Paris' },
417 ])
418 })
419 })
420​
421 it('rejects a missing or bad bearer token with a spec 401', async () => {
422 const server = createMCPServer({
423 name: 'secure',
424 version: '1.0.0',
425 auth: { verifier: tokenVerifier('secret'), resourceMetadataUrl },
426 tools: [echoTool()],
427 })
428​
429 const missing = await server.fetch(mcpRequest(undefined))
430 expect(missing.status).toBe(401)
431 const challenge = missing.headers.get('WWW-Authenticate') ?? ''
432 expect(challenge).toContain('Bearer')
433 // RFC 9728: the challenge names the protected resource metadata.
434 expect(challenge).toContain(`resource_metadata="${resourceMetadataUrl}"`)
435​
436 const bad = await server.fetch(mcpRequest('nope'))
437 expect(bad.status).toBe(401)
438 expect(bad.headers.get('WWW-Authenticate')).toContain('invalid_token')
439​
440 await withClient(
441 server,
442 { era: '2026', authToken: 'secret' },
443 async (client) => {
444 const listed = await client.listTools()
445 expect(listed.tools.map((tool) => tool.name)).toEqual(['echo'])
446 },
447 )
448 })
449​
450 it('rejects a token without a required scope with 403', async () => {
451 const server = createMCPServer({
452 name: 'secure',
453 version: '1.0.0',
454 auth: { verifier: tokenVerifier(), requiredScopes: ['admin'] },
455 tools: [echoTool()],
456 })
457​
458 const denied = await server.fetch(mcpRequest('alice'))
459 expect(denied.status).toBe(403)
460 expect(denied.headers.get('WWW-Authenticate')).toContain(
461 'insufficient_scope',
462 )
463 })
464​
465 it('gives a tool the verified token as ctx.context.authInfo', async () => {
466 const server = createMCPServer({
467 name: 'secure',
468 version: '1.0.0',
469 auth: subjectAuth,
470 tools: [
471 toolDefinition({
472 name: 'whoami',
473 description: 'Who is calling',
474 inputSchema: z.object({}),
475 }).server<MCPToolContext>(async (_args, ctx) => {
476 const info = ctx.context.authInfo
477 if (info === undefined) return 'nobody'
478 return `${info.clientId}:${String(info.extra?.sub)}`
479 }),
480 ],
481 })
482​
483 for (const era of ['2026', '2025'] as const) {
484 await withClient(server, { era, authToken: 'alice' }, async (client) => {
485 const called = await client.callTool({ name: 'whoami', arguments: {} })
486 expect(called.content).toEqual([{ type: 'text', text: 'tester:alice' }])
487 })
488 }
489 })
490​
491 it('takes a verified token and a context from handle options', async () => {
492 const server = createMCPServer({
493 name: 'secure',
494 version: '1.0.0',
495 // The verifier accepts no token, so only handle options can let a call in.
496 auth: { verifier: tokenVerifier('never') },
497 tools: [
498 toolDefinition({
499 name: 'whoami',
500 description: 'Who is calling, and from which tenant',
501 inputSchema: z.object({}),
502 }).server<MCPToolContext<{ tenant: string }>>(async (_args, ctx) => {
503 return `${String(ctx.context.authInfo?.extra?.sub)}@${ctx.context.tenant}`
504 }),
505 ],
506 })
507 const authInfo = {
508 token: 'from-middleware',
509 clientId: 'app',
510 scopes: [],
511 expiresAt: Math.floor(Date.now() / 1000) + 3600,
512 extra: { sub: 'carol' },
513 }
514​
515 const gated = await server.fetch(mcpRequest(undefined))
516 expect(gated.status).toBe(401)
517​
518 for (const era of ['2026', '2025'] as const) {
519 await withClient(
520 server,
521 { era, handleOptions: { authInfo, context: { tenant: 'acme' } } },
522 async (client) => {
523 const called = await client.callTool({
524 name: 'whoami',
525 arguments: {},
526 })
527 expect(called.content).toEqual([{ type: 'text', text: 'carol@acme' }])
528 },
529 )
530 }
531 })
532​
533 it('keeps its own hooks over a same-named value in the context', async () => {
534 const server = createMCPServer({
535 name: 'plain',
536 version: '1.0.0',
537 tools: [
538 toolDefinition({
539 name: 'probe',
540 description: 'Reports whether requestInput is still a function',
541 inputSchema: z.object({}),
542 }).server<MCPToolContext>(async (_args, ctx) => {
543 return typeof ctx.context.requestInput
544 }),
545 ],
546 })
547​
548 await withClient(
549 server,
550 { era: '2026', handleOptions: { context: { requestInput: 'shadowed' } } },
551 async (client) => {
552 const called = await client.callTool({ name: 'probe', arguments: {} })
553 expect(called.content).toEqual([{ type: 'text', text: 'function' }])
554 },
555 )
556 })
557​
558 it('sends tool title and annotations from metadata to the host', async () => {
559 const server = createMCPServer({
560 name: 'library',
561 version: '1.0.0',
562 tools: [
563 toolDefinition({
564 name: 'list_notes',
565 description: 'List notes',
566 inputSchema: z.object({}),
567 metadata: {
568 title: 'List notes',
569 annotations: { readOnlyHint: true, openWorldHint: false },
570 },
571 }).server(async () => []),
572 ],
573 })
574​
575 await withClient(server, { era: '2026' }, async (client) => {
576 const listed = await client.listTools()
577 expect(listed.tools[0]?.title).toBe('List notes')
578 expect(listed.tools[0]?.annotations).toEqual({
579 readOnlyHint: true,
580 openWorldHint: false,
581 })
582 })
583 })
584​
585 it('sends a CallToolResult from a tool as is', async () => {
586 const server = createMCPServer({
587 name: 'library',
588 version: '1.0.0',
589 tools: [
590 toolDefinition({
591 name: 'shaped',
592 description: 'Builds its own result',
593 inputSchema: z.object({}),
594 }).server(async () => ({
595 content: [
596 { type: 'text' as const, text: 'Two notes.' },
597 { type: 'text' as const, text: '{"count":2}' },
598 ],
599 structuredContent: { count: 2 },
600 })),
601 ],
602 })
603​
604 await withClient(server, { era: '2026' }, async (client) => {
605 const called = await client.callTool({ name: 'shaped', arguments: {} })
606 expect(called.content).toEqual([
607 { type: 'text', text: 'Two notes.' },
608 { type: 'text', text: '{"count":2}' },
609 ])
610 expect(called.structuredContent).toEqual({ count: 2 })
611 })
612 })
613​
614 it('rejects a spec 2025 request when sessions is reject', async () => {
615 const server = createMCPServer({
616 name: 'stateless',
617 version: '1.0.0',
618 sessions: 'reject',
619 tools: [echoTool()],
620 })
621​
622 const opened = await server.fetch(initializeRequest('any'))
623 expect(opened.ok).toBe(false)
624 expect(opened.headers.get('mcp-session-id')).toBeNull()
625​
626 await withClient(server, { era: '2026' }, async (client) => {
627 const listed = await client.listTools()
628 expect(listed.tools.map((tool) => tool.name)).toEqual(['echo'])
629 })
630 })
631​
632 it('uses the sample adapter for a spec 2026 sample and does not ask the client', async () => {
633 const seen: Array<SampleRequest> = []
634 const clientAsks: Array<string> = []
635 const server = createMCPServer({
636 name: 'writer',
637 version: '1.0.0',
638 sample: async (request) => {
639 seen.push(request)
640 return 'from-adapter'
641 },
642 tools: [
643 toolDefinition({
644 name: 'draft',
645 description: 'Draft a summary',
646 }).server<MCPToolContext>(async (_args, ctx) =>
647 ctx.context.sample(summaryRequest),
648 ),
649 ],
650 })
651​
652 await withClient(
653 server,
654 {
655 era: '2026',
656 prepare(client) {
657 client.setRequestHandler('sampling/createMessage', async () => {
658 clientAsks.push('client')
659 return {
660 role: 'assistant',
661 content: { type: 'text', text: 'from-client' },
662 model: 'client',
663 }
664 })
665 },
666 },
667 async (client) => {
668 const drafted = await client.callTool({ name: 'draft', arguments: {} })
669 expect(drafted.content).toEqual([
670 { type: 'text', text: 'from-adapter' },
671 ])
672 },
673 )
674​
675 expect(seen).toEqual([summaryRequest])
676 expect(clientAsks).toEqual([])
677 })
678​
679 it('keeps a string output schema for spec 2026 and spec 2025 clients', async () => {
680 const server = createMCPServer({
681 name: 'weather',
682 version: '1.0.0',
683 tools: [
684 toolDefinition({
685 name: 'forecast',
686 description: 'Forecast text',
687 inputSchema: z.object({}),
688 outputSchema: z.string(),
689 }).server(async () => 'Sunny'),
690 ],
691 })
692​
693 await withClient(server, { era: '2026' }, async (client) => {
694 const listed = await client.listTools()
695 expect(listed.tools[0]?.outputSchema).toMatchObject({ type: 'string' })
696 const called = await client.callTool({ name: 'forecast', arguments: {} })
697 expect(called.structuredContent).toBe('Sunny')
698 })
699 await withClient(server, { era: '2025' }, async (client) => {
700 const called = await client.callTool({ name: 'forecast', arguments: {} })
701 expect(called.content).toEqual([{ type: 'text', text: 'Sunny' }])
702 })
703 })
704​
705 it('sends a text string when a tool returns nothing', async () => {
706 const server = createMCPServer({
707 name: 'weather',
708 version: '1.0.0',
709 tools: [
710 toolDefinition({
711 name: 'noop',
712 description: 'Returns nothing',
713 inputSchema: z.object({}),
714 }).server(async () => undefined),
715 ],
716 })
717​
718 await withClient(server, { era: '2026' }, async (client) => {
719 const called = await client.callTool({ name: 'noop', arguments: {} })
720 expect(called.content).toEqual([{ type: 'text', text: '' }])
721 })
722 })
723​
724 it('gives a spec 2025 session only to the subject that opened it', async () => {
725 const server = createMCPServer({
726 name: 'secure',
727 version: '1.0.0',
728 auth: subjectAuth,
729 tools: [echoTool()],
730 })
731 const sessionId = await openSession(server, 'alice')
732​
733 const own = await server.fetch(sessionRequest('alice', sessionId))
734 expect(own.status).toBe(200)
735 const other = await server.fetch(sessionRequest('bob', sessionId))
736 expect(other.status).toBe(404)
737 })
738​
739 it('closes a spec 2025 session after 30 idle minutes', async () => {
740 const server = surfaceServer()
741 const start = Date.now()
742 const now = vi.spyOn(Date, 'now').mockReturnValue(start)
743 try {
744 const opened = await server.fetch(initializeRequest('any'))
745 const sessionId = opened.headers.get('mcp-session-id')
746 if (sessionId === null) throw new Error('The server opened no session')
747​
748 now.mockReturnValue(start + 31 * 60 * 1000)
749 const late = await server.fetch(sessionRequest('any', sessionId))
750 expect(late.status).toBe(404)
751 } finally {
752 now.mockRestore()
753 }
754 })
755​
756 it('shows a task only to the subject that started it', async () => {
757 const server = createMCPServer({
758 name: 'tasks',
759 version: '1.0.0',
760 auth: subjectAuth,
761 taskStore: inMemoryTaskStore(),
762 tools: [
763 toolDefinition({
764 name: 'slow',
765 description: 'Slow work',
766 execution: 'task',
767 }).server(async () => 'done'),
768 ],
769 })
770​
771 let taskId = ''
772 await withClient(
773 server,
774 { era: '2025', authToken: 'alice' },
775 async (client) => {
776 const created = await taskCall(client, 'slow')
777 taskId = created.task.taskId
778 await vi.waitFor(async () => {
779 expect((await taskGet(client, taskId)).status).toBe('completed')
780 })
781 expect((await taskResultOf(client, taskId)).content).toEqual([
782 { type: 'text', text: 'done' },
783 ])
784 },
785 )
786​
787 await withClient(
788 server,
789 { era: '2025', authToken: 'bob' },
790 async (client) => {
791 await expect(taskGet(client, taskId)).rejects.toThrow('Task not found')
792 },
793 )
794 })
795​
796 it('gives a task tool its own context, not the finished request', async () => {
797 const seen: Array<{ aborted: boolean; message: string }> = []
798 const calls: Array<Promise<unknown>> = []
799 const server = createMCPServer({
800 name: 'tasks',
801 version: '1.0.0',
802 taskStore: inMemoryTaskStore(),
803 waitUntil(promise) {
804 calls.push(promise)
805 },
806 tools: [
807 toolDefinition({
808 name: 'ask',
809 description: 'Asks in a task',
810 execution: 'task',
811 }).server<MCPToolContext>(async (_args, ctx) => {
812 await new Promise((resolve) => setTimeout(resolve, 5))
813 const aborted = ctx.abortSignal?.aborted ?? true
814 try {
815 await ctx.context.requestInput({ message: 'City?' })
816 } catch (error) {
817 seen.push({
818 aborted,
819 message: error instanceof Error ? error.message : '',
820 })
821 }
822 return 'done'
823 }),
824 ],
825 })
826​
827 await withClient(server, { era: '2025' }, async (client) => {
828 await taskCall(client, 'ask')
829 })
830 await Promise.all(calls)
831​
832 expect(seen).toEqual([
833 {
834 aborted: false,
835 message:
836 'ctx.context.requestInput is not supported in an execution: "task" tool.',
837 },
838 ])
839 })
840​
841 it('asks a spec 2025 client for input and a sample in the same call', async () => {
842 const samples: Array<unknown> = []
843 const server = createMCPServer({
844 name: 'writer',
845 version: '1.0.0',
846 tools: [
847 toolDefinition({
848 name: 'draft',
849 description: 'Draft for a city',
850 inputSchema: z.object({}),
851 }).server<MCPToolContext>(async (_args, ctx) => {
852 ctx.emitCustomEvent('progress', {})
853 const city = await ctx.context.requestInput({ message: 'City?' })
854 const draft = await ctx.context.sample({
855 messages: [
856 { role: 'user', content: `Draft for ${String(city)}` },
857 { role: 'assistant', content: 'Sure' },
858 ],
859 })
860 return `${String(city)}: ${draft}`
861 }),
862 ],
863 })
864​
865 await withClient(
866 server,
867 {
868 era: '2025',
869 prepare(client) {
870 client.setRequestHandler('elicitation/create', async () => ({
871 action: 'accept',
872 content: { value: 'Paris' },
873 }))
874 client.setRequestHandler('sampling/createMessage', async (req) => {
875 samples.push(req.params.messages)
876 return {
877 role: 'assistant',
878 content: { type: 'text', text: 'Sunny' },
879 model: 'client',
880 }
881 })
882 },
883 },
884 async (client) => {
885 const called = await client.callTool({ name: 'draft', arguments: {} })
886 expect(called.content).toEqual([{ type: 'text', text: 'Paris: Sunny' }])
887 },
888 )
889​
890 expect(samples).toEqual([
891 [
892 { role: 'user', content: { type: 'text', text: 'Draft for Paris' } },
893 { role: 'assistant', content: { type: 'text', text: 'Sure' } },
894 ],
895 ])
896 })
897​
898 it('handles spec 2025 declines, empty answers, and text-less samples', async () => {
899 let answer: { action: 'accept' | 'decline' } = { action: 'decline' }
900 const server = createMCPServer({
901 name: 'writer',
902 version: '1.0.0',
903 tools: [
904 toolDefinition({
905 name: 'ask',
906 description: 'Ask',
907 inputSchema: z.object({}),
908 }).server<MCPToolContext>(async (_args, ctx) =>
909 JSON.stringify(await ctx.context.requestInput({ message: 'City?' })),
910 ),
911 toolDefinition({
912 name: 'draft',
913 description: 'Draft',
914 inputSchema: z.object({}),
915 }).server<MCPToolContext>(async (_args, ctx) =>
916 ctx.context.sample(summaryRequest),
917 ),
918 ],
919 })
920​
921 await withClient(
922 server,
923 {
924 era: '2025',
925 prepare(client) {
926 client.setRequestHandler('elicitation/create', async () => answer)
927 client.setRequestHandler('sampling/createMessage', async () => ({
928 role: 'assistant',
929 content: { type: 'image', data: 'AAAA', mimeType: 'image/png' },
930 model: 'client',
931 }))
932 },
933 },
934 async (client) => {
935 const declined = await client.callTool({ name: 'ask', arguments: {} })
936 expect(declined.isError).toBe(true)
937 expect(JSON.stringify(declined.content)).toContain(
938 'The user did not accept the input request.',
939 )
940​
941 answer = { action: 'accept' }
942 const empty = await client.callTool({ name: 'ask', arguments: {} })
943 expect(empty.isError).toBe(true)
944​
945 const drafted = await client.callTool({ name: 'draft', arguments: {} })
946 expect(drafted.isError).toBe(true)
947 expect(JSON.stringify(drafted.content)).toContain(
948 'The client sample result has no text.',
949 )
950 },
951 )
952 })
953​
954 it('gives a spec 2026 tool a non-string answer as the answer object', async () => {
955 const server = createMCPServer({
956 name: 'weather',
957 version: '1.0.0',
958 tools: [
959 toolDefinition({
960 name: 'ask',
961 description: 'Ask',
962 inputSchema: z.object({}),
963 }).server<MCPToolContext>(async (_args, ctx) =>
964 JSON.stringify(await ctx.context.requestInput({ message: 'City?' })),
965 ),
966 ],
967 })
968​
969 await withClient(server, { era: '2026' }, async (client) => {
970 const answered = await callMcpTool(client, 'ask', {}, false, undefined, {
971 status: 'resolved',
972 payload: { value: 3 },
973 })
974 expect(answered.content).toEqual([{ type: 'text', text: '{"value":3}' }])
975 })
976 })
977​
978 it('lets a task tool sample only with the sample option', async () => {
979 const results: Array<unknown> = []
980 const calls: Array<Promise<unknown>> = []
981 const draftTool = toolDefinition({
982 name: 'draft',
983 description: 'Draft in a task',
984 execution: 'task',
985 }).server<MCPToolContext>(async (_args, ctx) => {
986 ctx.emitCustomEvent('progress', {})
987 try {
988 results.push(await ctx.context.sample(summaryRequest))
989 } catch (error) {
990 results.push(error instanceof Error ? error.message : '')
991 }
992 return 'done'
993 })
994 for (const sample of [undefined, async () => 'from-adapter']) {
995 const server = createMCPServer({
996 name: 'tasks',
997 version: '1.0.0',
998 sample,
999 waitUntil: (promise) => calls.push(promise),
1000 tools: [draftTool],
1001 })
1002 await withClient(server, { era: '2025' }, async (client) => {
1003 await taskCall(client, 'draft')
1004 })
1006 await Promise.all(calls)
1007​
1008 expect(results).toEqual([
1009 'ctx.context.sample in an execution: "task" tool needs the sample option of createMCPServer.',
1010 'from-adapter',
1011 ])
1012 })
1013​
1014 it('fails the task call when the store loses the task', async () => {
1015 const server = createMCPServer({
1016 name: 'tasks',
1017 version: '1.0.0',
1018 taskStore: {
1019 get: async () => null,
1020 set: async () => undefined,
1021 delete: async () => undefined,
1022 },
1023 tools: [
1024 toolDefinition({
1025 name: 'slow',
1026 description: 'Slow work',
1027 execution: 'task',
1028 }).server(async () => 'done'),
1029 ],
1030 })
1031​
1032 await withClient(server, { era: '2025' }, async (client) => {
1033 const called = await client.request(
1035 method: 'tools/call',
1036 params: { name: 'slow', arguments: {}, task: {} },
1037 },
1038 callToolResult,
1040 expect(called.isError).toBe(true)
1041 expect(JSON.stringify(called.content)).toMatch(/was not saved/)
1042 })
1043 })
1044​
1045 it('rejects a bad task id and a result that is not ready', async () => {
1046 const gate = deferredText()
1047 const server = createMCPServer({
1048 name: 'tasks',
1049 version: '1.0.0',
1050 tools: [
1051 toolDefinition({
1052 name: 'slow',
1053 description: 'Slow work',
1054 execution: 'task',
1055 }).server(async () => gate.work),
1056 ],
1057 })
1058​
1059 await withClient(server, { era: '2025' }, async (client) => {
1060 await expect(taskGet(client, '')).rejects.toThrow()
1061 const created = await taskCall(client, 'slow')
1062 await expect(taskResultOf(client, created.task.taskId)).rejects.toThrow(
1063 'Task result is not ready',
1065 gate.resolve({ text: 'done' })
1066 })
1067 })
1068​
1069 it('returns a tool error for a tool without execute', async () => {
1070 const server = createMCPServer({
1071 name: 'weather',
1072 version: '1.0.0',
1073 tools: [{ ...echoTool(), execute: undefined }],
1074 })
1075​
1076 await withClient(server, { era: '2026' }, async (client) => {
1077 const called = await client.callTool({
1078 name: 'echo',
1079 arguments: { text: 'hi' },
1080 })
1081 expect(called.isError).toBe(true)
1082 expect(JSON.stringify(called.content)).toContain(
1083 'Tool echo has no execute function.',
1085 })
1086 })
1087​
1088 it('accepts a JSON Schema input schema', async () => {
1089 const server = createMCPServer({
1090 name: 'weather',
1091 version: '1.0.0',
1092 tools: [
1093 toolDefinition({
1094 name: 'city',
1095 description: 'City name',
1096 inputSchema: {
1097 type: 'object',
1098 properties: { city: { type: 'string' } },
1099 },
1100 }).server(async () => 'ok'),
1101 ],
1102 })
1103​
1104 await withClient(server, { era: '2026' }, async (client) => {
1105 const listed = await client.listTools()
1106 expect(listed.tools[0]?.inputSchema).toMatchObject({
1107 properties: { city: { type: 'string' } },
1108 })
1109 })
1110 })
1111​
1112 it('reads every resource body shape and a uri template', async () => {
1113 const resource = (name: string, body: unknown) =>
1114 resourceDefinition({
1115 uri: `file:///${name}`,
1116 name,
1117 mimeType: 'text/plain',
1118 }).read(async () => body)
1119 const server = createMCPServer({
1120 name: 'files',
1121 version: '1.0.0',
1122 resources: [
1123 resource('blob', { blob: 'AAAA' }),
1124 resource('string', 'plain'),
1125 resource('json', { a: 1 }),
1126 resource('empty', undefined),
1127 resourceDefinition({
1128 uriTemplate: 'file:///users/{id}',
1129 name: 'user',
1130 mimeType: 'text/plain',
1131 }).read(async () => 'user'),
1132 { name: 'nowhere', mimeType: 'text/plain', read: async () => 'x' },
1133 ],
1134 })
1135​
1136 await withClient(server, { era: '2026' }, async (client) => {
1137 const read = async (uri: string) =>
1138 (await client.readResource({ uri })).contents[0]
1139 expect(await read('file:///blob')).toMatchObject({ blob: 'AAAA' })
1140 expect(await read('file:///string')).toMatchObject({ text: 'plain' })
1141 expect(await read('file:///json')).toMatchObject({ text: '{"a":1}' })
1142 expect(await read('file:///empty')).toMatchObject({ text: '' })
1143 expect(await read('file:///users/7')).toMatchObject({
1144 uri: 'file:///users/7',
1145 text: 'user',
1146 })
1147 const listed = await client.listResources()
1148 expect(listed.resources.map((r) => r.name)).not.toContain('nowhere')
1149 })
1150 })
1151​
1152 it('keeps assistant prompt messages and drops invalid ones', async () => {
1153 const server = createMCPServer({
1154 name: 'prompts',
1155 version: '1.0.0',
1156 prompts: [
1157 promptDefinition({
1158 name: 'chat',
1159 description: 'Chat',
1160 argsSchema: z.object({}),
1161 }).render(async () => [
1162 { role: 'assistant', content: 'Hi' },
1163 { role: 'user', content: 'Hello' },
1164 // An invalid item from an untyped render function.
1165 JSON.parse('{"role":"user"}'),
1166 ]),
1167 ],
1168 })
1169​
1170 await withClient(server, { era: '2026' }, async (client) => {
1171 const prompt = await client.getPrompt({ name: 'chat', arguments: {} })
1172 expect(prompt.messages).toEqual([
1173 { role: 'assistant', content: { type: 'text', text: 'Hi' } },
1174 { role: 'user', content: { type: 'text', text: 'Hello' } },
1175 ])
1176 })
1177 })
1178​
1179 it('forgets a spec 2025 session that the client ends', async () => {
1180 const server = surfaceServer()
1181 let sessionId = ''
1182​
1183 await withClient(server, { era: '2025' }, async (_client, transport) => {
1184 sessionId = transport.sessionId ?? ''
1185 await transport.terminateSession()
1186 })
1187​
1188 const late = await server.fetch(sessionRequest('any', sessionId))
1189 expect(late.status).toBe(404)
1190 })
1191​
1192 it('does not keep a spec 2025 request that opens no session', async () => {
1193 const server = surfaceServer()
1194 const request = sessionRequest('any', 'x')
1195 request.headers.delete('mcp-session-id')
1196​
1197 const response = await server.fetch(request)
1198 expect(response.ok).toBe(false)
1199 })