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

client.test.ts

681 lines25.2 KB

1// packages/ai-mcp/tests/client.test.ts
2import { describe, expect, it, vi } from 'vitest'
3import {
4 InMemoryTransport,
5 SUPPORTED_PROTOCOL_VERSIONS,
6} from '@modelcontextprotocol/client'
7import { Server } from '@modelcontextprotocol/server'
8import { toolDefinition } from '@tanstack/ai'
9import { z } from 'zod'
10import { createMCPClient, createMCPClientFromTransport } from '../src/client'
11import {
12 DuplicateToolNameError,
13 MCPConnectionError,
14 MCPTaskRequiredToolError,
15} from '../src/errors'
16import {
17 makeServerWithAnnotatedTool,
18 makeServerWithBrokenToolList,
19 makeServerWithChangingTools,
20 makeServerWithLaxOutputSchemaTool,
21 makeServerWithLoopingCursor,
22 makeServerWithPaginatedLaxSchemaTool,
23 makeServerWithPaginatedTools,
24 makeServerWithPendingTaskTool,
25 makeServerWithStructuredTool,
26 makeServerWithTaskRequiredTool,
27 makeServerWithUnsupportedTaskTool,
28 makeServerWithWeatherTool,
29} from './helpers/in-memory-server'
30import type {
31 JSONRPCMessage,
32 JsonSchemaType,
33 JsonSchemaValidator,
34 Transport,
35 jsonSchemaValidator,
36} from '@modelcontextprotocol/client'
37​
38describe('createMCPClient', () => {
39 it('connects and returns discovered tools', async () => {
40 const { clientTransport } = await makeServerWithWeatherTool()
41 await using client = await createMCPClientFromTransport(clientTransport)
42 const tools = await client.tools()
43 expect(tools.map((t) => t.name)).toContain('get_weather')
44 expect(client.capabilities).toBeDefined()
45 })
46​
47 it('binds passed toolDefinitions to the server, typed + validated', async () => {
48 const { clientTransport } = await makeServerWithWeatherTool()
49 await using client = await createMCPClientFromTransport(clientTransport)
50 const getWeather = toolDefinition({
51 name: 'get_weather',
52 description: 'Get weather for a city',
53 inputSchema: z.object({ city: z.string() }),
54 })
55 const tools = await client.tools([getWeather])
56 expect(tools).toHaveLength(1)
57 expect(tools[0].name).toBe('get_weather')
58 const result = await tools[0].execute!(
59 { city: 'Brooklyn' },
60 {
61 toolCallId: 't',
62 emitCustomEvent: () => {},
63 },
64 )
65 expect(JSON.stringify(result)).toContain('Sunny in Brooklyn')
66 })
67​
68 it('throws MCPToolNotFoundError for a definition the server lacks', async () => {
69 const { clientTransport } = await makeServerWithWeatherTool()
70 await using client = await createMCPClientFromTransport(clientTransport)
71 const ghost = toolDefinition({
72 name: 'does_not_exist',
73 description: 'A tool that does not exist on the server',
74 inputSchema: z.object({}),
75 })
76 await expect(client.tools([ghost])).rejects.toThrow(/does_not_exist/)
77 })
78​
79 it('throws DuplicateToolNameError when bound defs collide within one tools() call', async () => {
80 const { clientTransport } = await makeServerWithWeatherTool()
81 await using client = await createMCPClientFromTransport(clientTransport)
82 const getWeather = toolDefinition({
83 name: 'get_weather',
84 description: 'Get weather for a city',
85 inputSchema: z.object({ city: z.string() }),
86 })
87 // Two defs resolving to the same final tool name trip the client's own
88 // duplicate guard (single tools() call).
89 await expect(client.tools([getWeather, getWeather])).rejects.toThrow(
90 DuplicateToolNameError,
91 )
92 })
93​
94 it('applies the client prefix to bound definitions', async () => {
95 const { clientTransport } = await makeServerWithWeatherTool()
96 await using client = await createMCPClientFromTransport(
97 clientTransport,
98 'wx',
99 )
100 const getWeather = toolDefinition({
101 name: 'get_weather',
102 description: 'Get weather for a city',
103 inputSchema: z.object({ city: z.string() }),
104 })
105 const tools = await client.tools([getWeather])
106 expect(tools[0].name).toBe('wx_get_weather')
107 })
108​
109 it('stamps mcp.serverToolName + serverId on bound definitions', async () => {
110 const { clientTransport } = await makeServerWithWeatherTool()
111 await using client = await createMCPClientFromTransport(
112 clientTransport,
113 'wx',
114 )
115 const getWeather = toolDefinition({
116 name: 'get_weather',
117 description: 'Get weather for a city',
118 inputSchema: z.object({ city: z.string() }),
119 })
120 const tools = await client.tools([getWeather])
121 // The runtime name is prefixed, but the UNPREFIXED native name + serverId
122 // must be recoverable from metadata (mirrors auto-discovery).
123 expect(tools[0].metadata.mcp).toMatchObject({
124 serverToolName: 'get_weather',
125 serverId: 'wx',
126 })
127 })
128​
129 it('forwards server annotations + display title on auto-discovery', async () => {
130 const { clientTransport } = await makeServerWithAnnotatedTool()
131 await using client = await createMCPClientFromTransport(clientTransport)
132 const tool = (await client.tools()).find((t) => t.name === 'get_weather')!
133 // `tools()` returns `McpServerTool`s — the read is typed as
134 // `McpToolMetadata` with no annotation and no optional chaining.
135 const mcp = tool.metadata.mcp
136 expect(mcp.annotations).toEqual({
137 title: 'Legacy Weather Title',
138 readOnlyHint: true,
139 destructiveHint: false,
140 idempotentHint: true,
141 openWorldHint: true,
142 })
143 // Top-level `title` wins over the legacy `annotations.title`.
144 expect(mcp.title).toBe('Weather Lookup')
145 })
146​
147 it('forwards server annotations + display title on bound definitions', async () => {
148 const { clientTransport } = await makeServerWithAnnotatedTool()
149 await using client = await createMCPClientFromTransport(clientTransport)
150 const getWeather = toolDefinition({
151 name: 'get_weather',
152 description: 'Get weather for a city',
153 inputSchema: z.object({ city: z.string() }),
154 })
155 // The explicit path binds the caller's definition, but the SERVER's
156 // annotations still have to reach the host (mirrors auto-discovery).
157 const tools = await client.tools([getWeather])
158 const mcp = tools[0].metadata.mcp
159 expect(mcp.annotations?.readOnlyHint).toBe(true)
160 expect(mcp.title).toBe('Weather Lookup')
161 })
162​
163 it('discovers and executes task-required tools', async () => {
164 const { clientTransport } = await makeServerWithTaskRequiredTool()
165 await using client = await createMCPClientFromTransport(clientTransport)
166 const tools = await client.tools()
167 expect(tools.map((t) => t.name)).toEqual(['get_weather', 'research_task'])
168 const research = tools.find((tool) => tool.name === 'research_task')!
169 await expect(
170 research.execute!(
171 { query: 'MCP tasks' },
172 { toolCallId: 't', emitCustomEvent: () => {} },
173 ),
174 ).resolves.toBe('Research complete: MCP tasks')
175 })
176​
177 it('binds and executes a task-required tool definition', async () => {
178 const { clientTransport } = await makeServerWithTaskRequiredTool()
179 await using client = await createMCPClientFromTransport(clientTransport)
180 const researchTask = toolDefinition({
181 name: 'research_task',
182 description: 'A long-running tool that requires task-based execution',
183 inputSchema: z.object({ query: z.string() }),
184 })
185 const [tool] = await client.tools([researchTask])
186 await expect(
187 tool!.execute!(
188 { query: 'typed tasks' },
189 { toolCallId: 't', emitCustomEvent: () => {} },
190 ),
191 ).resolves.toBe('Research complete: typed tasks')
192 })
193​
194 it('wraps connection failures in MCPConnectionError preserving the cause', async () => {
195 const broken: Transport = {
196 start: async () => {
197 throw new Error('nope')
198 },
199 send: async () => {},
200 close: async () => {},
201 }
202 const err: unknown = await createMCPClientFromTransport(broken).catch(
203 (e: unknown) => e,
204 )
205 expect(err).toBeInstanceOf(MCPConnectionError)
206 if (!(err instanceof MCPConnectionError)) {
207 throw new Error('expected MCPConnectionError')
208 }
209 expect(err.cause).toBeInstanceOf(Error)
210 })
211​
212 it('callTool proxies directly to the server and returns CallToolResult', async () => {
213 const { clientTransport } = await makeServerWithWeatherTool()
214 await using client = await createMCPClientFromTransport(clientTransport)
215 const result = await client.callTool('get_weather', { city: 'Tokyo' })
216 expect(result.isError).toBeFalsy()
217 expect(
218 Array.isArray(result.content) &&
219 result.content.some(
220 (c: { type: string; text?: string }) =>
221 c.type === 'text' && c.text?.includes('Tokyo'),
222 ),
223 ).toBe(true)
224 })
225​
226 it('callTool executes task-required tools and returns the raw result', async () => {
227 const { clientTransport } = await makeServerWithTaskRequiredTool()
228 await using client = await createMCPClientFromTransport(clientTransport)
229 const result = await client.callTool('research_task', {
230 query: 'direct tasks',
231 })
232 expect(result.content).toEqual([
233 { type: 'text', text: 'Research complete: direct tasks' },
234 ])
235 })
236​
237 it('tools() follows tools/list pagination across pages', async () => {
238 const { clientTransport } = await makeServerWithPaginatedTools()
239 await using client = await createMCPClientFromTransport(clientTransport)
240 const tools = await client.tools()
241 expect(tools.map((t) => t.name).sort()).toEqual([
242 'first_page_tool',
243 'second_page_tool',
244 ])
245 })
246​
247 it('keeps output-schema validation for tools listed on an earlier page', async () => {
248 const { clientTransport } = await makeServerWithPaginatedLaxSchemaTool()
249 await using client = await createMCPClientFromTransport(clientTransport)
250 await client.tools()
251 // Both pages declared an outputSchema. listTools() caches the full list.
252 // Text-only content then fails structured-content validation.
253 await expect(client.callTool('first_page_tool')).rejects.toThrow()
254 await expect(client.callTool('second_page_tool')).rejects.toThrow()
255 })
256​
257 it('fails tools() when tools/list repeats a pagination cursor', async () => {
258 const { clientTransport } = await makeServerWithLoopingCursor()
259 await using client = await createMCPClientFromTransport(clientTransport)
260 await expect(client.tools()).rejects.toThrow(
261 'MCP list pagination repeated a cursor',
262 )
263 })
264​
265 it('fails tools() when tools/list passes the page cap', async () => {
266 const { clientTransport } = await makeServerWithUnendingToolList()
267 await using client = await createMCPClientFromTransport(clientTransport)
268 await expect(client.tools()).rejects.toThrow(
269 'MCP list pagination exceeded 100 pages',
270 )
271 })
272​
273 it('callTool does not re-list for a name absent from the cached list', async () => {
274 const { clientTransport, getListRequests } =
275 await makeServerWithPaginatedTools()
276 await using client = await createMCPClientFromTransport(clientTransport)
277 await client.tools()
278 const listed = getListRequests()
279 const result = await client.callTool('not_listed')
280 expect(result.content).toEqual([
281 { type: 'text', text: 'called not_listed' },
282 ])
283 await client.callTool('not_listed')
284 expect(getListRequests()).toBe(listed)
285 })
286​
287 it('callTool falls back to a plain call when tools/list fails', async () => {
288 const { clientTransport } = await makeServerWithBrokenToolList()
289 await using client = await createMCPClientFromTransport(clientTransport)
290 const result = await client.callTool('anything')
291 expect(result.content).toEqual([{ type: 'text', text: 'called anything' }])
292 })
293​
294 it('direct callTool without prior discovery stays validation-free', async () => {
295 const { clientTransport } = await makeServerWithLaxOutputSchemaTool()
296 await using client = await createMCPClientFromTransport(clientTransport)
297 // The tool declares an outputSchema but returns only text content — the
298 // raw result must come back, not the SDK's strict structured-content error.
299 const result = await client.callTool('lax_tool')
300 expect(result.content).toEqual([{ type: 'text', text: 'called lax_tool' }])
301 })
302​
303 it('excludes task-required tools when the server lacks the tasks capability', async () => {
304 const { clientTransport } = await makeServerWithUnsupportedTaskTool()
305 await using client = await createMCPClientFromTransport(clientTransport)
306 const tools = await client.tools()
307 expect(tools.map((t) => t.name)).toEqual(['plain_tool'])
308 })
309​
310 it('callTool throws MCPTaskRequiredToolError for a task-required tool the server cannot execute', async () => {
311 const { clientTransport } = await makeServerWithUnsupportedTaskTool()
312 await using client = await createMCPClientFromTransport(clientTransport)
313 await expect(client.callTool('needs_tasks')).rejects.toBeInstanceOf(
314 MCPTaskRequiredToolError,
315 )
316 // Ordinary tools on the same server keep working.
317 const result = await client.callTool('plain_tool')
318 expect(result.content).toEqual([
319 { type: 'text', text: 'called plain_tool' },
320 ])
321 })
322​
323 it('throws MCPTaskRequiredToolError when binding a task-required tool the server cannot execute', async () => {
324 const { clientTransport } = await makeServerWithUnsupportedTaskTool()
325 await using client = await createMCPClientFromTransport(clientTransport)
326 const needsTasks = toolDefinition({
327 name: 'needs_tasks',
328 description: 'Requires tasks the server cannot execute',
329 inputSchema: z.object({}),
330 })
331 await expect(client.tools([needsTasks])).rejects.toBeInstanceOf(
332 MCPTaskRequiredToolError,
333 )
334 })
335​
336 it('callTool rejects immediately when the signal is already aborted', async () => {
337 const { clientTransport } = await makeServerWithWeatherTool()
338 await using client = await createMCPClientFromTransport(clientTransport)
339 const controller = new AbortController()
340 controller.abort()
341 await expect(
342 client.callTool(
343 'get_weather',
344 { city: 'Berlin' },
345 { signal: controller.signal },
346 ),
347 ).rejects.toThrow()
348 })
349​
350 it('cancels the remote task when callTool is aborted mid-poll', async () => {
351 const { clientTransport, taskStore } = await makeServerWithPendingTaskTool()
352 const sent: Array<string> = []
353 const origSend = clientTransport.send.bind(clientTransport)
354 clientTransport.send = (message, sendOptions) => {
355 if ('method' in message && typeof message.method === 'string') {
356 sent.push(message.method)
357 }
358 return origSend(message, sendOptions)
359 }
360 await using client = await createMCPClientFromTransport(clientTransport)
361 const controller = new AbortController()
362 const pending = client.callTool(
363 'slow_task',
364 { query: 'q' },
365 { signal: controller.signal },
366 )
367 // Wait until the task exists server-side, then abort the poll loop.
368 await vi.waitFor(async () => {
369 const { tasks } = await taskStore.listTasks()
370 expect(tasks).toHaveLength(1)
371 })
372 controller.abort()
373 await expect(pending).rejects.toThrow()
374 await vi.waitFor(() => {
375 expect(sent).toContain('tasks/cancel')
376 })
377 })
378​
379 it('re-lists tools after a tools/list_changed notification', async () => {
380 const { server, clientTransport, getListRequests } =
381 await makeServerWithChangingTools()
382 await using client = await createMCPClientFromTransport(clientTransport)
383 await client.callTool('tool_a')
384 const listed = getListRequests()
385 await client.callTool('tool_a')
386 expect(getListRequests()).toBe(listed) // cached — no re-list
387 await server.sendToolListChanged()
388 await vi.waitFor(async () => {
389 await client.callTool('tool_a')
390 expect(getListRequests()).toBeGreaterThan(listed)
391 })
392 })
393​
394 it('opens subscriptions/listen on a spec 2026 server that reports tool list changes', async () => {
395 const { clientTransport, sawListen } = await makeModernChangingServer()
396 await using client = await createMCPClientFromTransport(clientTransport)
397 expect(client.capabilities).toMatchObject({
398 tools: { listChanged: true },
399 })
400 expect(sawListen()).toBe(true)
401 })
402​
403 it('still connects when subscriptions/listen fails', async () => {
404 const { clientTransport } = await makeModernChangingServer({
405 failListen: true,
406 })
407 await using client = await createMCPClientFromTransport(clientTransport)
408 const result = await client.callTool('tool_a')
409 expect(result.content).toEqual([{ type: 'text', text: 'called tool_a' }])
410 })
411​
412 it('reads tools/list once per page on a spec 2026 server', async () => {
413 const { clientTransport, getListRequests } =
414 await makeModernChangingServer()
415 await using client = await createMCPClientFromTransport(clientTransport)
416 await client.tools()
417 expect(getListRequests()).toBe(1)
418 })
419​
420 it('lists tools again after a spec 2026 tool list change', async () => {
421 const { clientTransport, notifyToolListChanged, getListRequests } =
422 await makeModernChangingServer()
423 await using client = await createMCPClientFromTransport(clientTransport)
424 await client.callTool('tool_a')
425 const listed = getListRequests()
426 await client.callTool('tool_a')
427 expect(getListRequests()).toBe(listed)
428 await notifyToolListChanged()
429 await vi.waitFor(async () => {
430 await client.callTool('tool_a')
431 expect(getListRequests()).toBeGreaterThan(listed)
432 })
433 })
434​
435 it('callTool throws MCPConnectionError when client is closed', async () => {
436 const { clientTransport } = await makeServerWithWeatherTool()
437 const client = await createMCPClientFromTransport(clientTransport)
438 await client.close()
439 await expect(
440 client.callTool('get_weather', { city: 'Tokyo' }),
441 ).rejects.toThrow(MCPConnectionError)
442 })
443​
444 it('close() is idempotent', async () => {
445 const { clientTransport } = await makeServerWithWeatherTool()
446 const client = await createMCPClientFromTransport(clientTransport)
447 await client.close()
448 await expect(client.close()).resolves.toBeUndefined()
449 })
450​
451 it('getInfo() retains no transport when createMCPClient is given a Transport instance', async () => {
452 const { clientTransport } = await makeServerWithWeatherTool()
453 await using client = await createMCPClient({
454 transport: clientTransport,
455 prefix: 'wx',
456 })
457 // A ready-made Transport instance is single-use / not reconnectable, so
458 // only serializable transport configs are retained as a descriptor.
459 expect(client.getInfo()).toEqual({ transport: undefined, prefix: 'wx' })
460 })
461​
462 it('getInfo() returns an undefined transport for a client built from a raw Transport', async () => {
463 const { clientTransport } = await makeServerWithWeatherTool()
464 await using client = await createMCPClientFromTransport(
465 clientTransport,
466 'wx',
467 )
468 expect(client.getInfo()).toEqual({ transport: undefined, prefix: 'wx' })
469 })
470​
471 it('closes on asyncDispose', async () => {
472 const { clientTransport } = await makeServerWithWeatherTool()
473 let client: Awaited<ReturnType<typeof createMCPClientFromTransport>>
474 {
475 await using c = await createMCPClientFromTransport(clientTransport)
476 client = c
477 expect(await c.tools()).toBeDefined()
478 }
479 // after scope exit the client is closed; calling tools() rejects
480 await expect(client.tools()).rejects.toThrow()
481 })
482})
483​
484describe('clientOptions', () => {
485 function recordingValidator(): {
486 schemas: Array<unknown>
487 provider: jsonSchemaValidator
488 } {
489 const schemas: Array<unknown> = []
490 return {
491 schemas,
492 provider: {
493 // The SDK type says accepted data is T. This recorder accepts every input.
494 getValidator<T>(schema: JsonSchemaType): JsonSchemaValidator<T> {
495 schemas.push(schema)
496 const validate: JsonSchemaValidator<T> = (input) => {
497 const data = input as T
498 return { valid: true, data, errorMessage: undefined }
499 }
500 return validate
501 },
502 },
503 }
504 }
505​
506 it('forwards a custom jsonSchemaValidator to the SDK client', async () => {
507 const { clientTransport } = await makeServerWithStructuredTool()
508 const { schemas, provider } = recordingValidator()
509 await using client = await createMCPClientFromTransport(
510 clientTransport,
511 undefined,
512 { jsonSchemaValidator: provider },
513 )
514​
515 // The SDK compiles each output validator from the tool list cache.
516 await client.tools()
517 await client.callTool('lookup_user', { id: 'u-1' })
518​
519 expect(schemas).toEqual([expect.objectContaining({ type: 'object' })])
520 })
521​
522 it('accepts clientOptions through createMCPClient', async () => {
523 const { clientTransport } = await makeServerWithStructuredTool()
524 const { schemas, provider } = recordingValidator()
525 await using client = await createMCPClient({
526 transport: clientTransport,
527 clientOptions: { jsonSchemaValidator: provider },
528 })
529​
530 await client.tools()
531 await client.callTool('lookup_user', { id: 'u-1' })
532​
533 expect(schemas).toHaveLength(1)
534 })
535​
536 it('falls back to the SDK default when no clientOptions are given', async () => {
537 const { clientTransport } = await makeServerWithStructuredTool()
538 await using client = await createMCPClientFromTransport(clientTransport)
539 await client.tools()
540​
541 const result = await client.callTool('lookup_user', { id: 'u-1' })
542​
543 expect(result.structuredContent).toEqual({ id: 'u-1', name: 'Ada' })
544 })
545​
546 it('reports clientOptions on getInfo so a rebuilt client keeps them', async () => {
547 // `createMcpAppCallHandler` reconnects per call from `getInfo()`. A
548 // descriptor that dropped `clientOptions` would hand the rebuilt client
549 // back to the SDK's AJV default — the exact failure this option exists to
550 // avoid, reintroduced for every MCP Apps widget call.
551 const { clientTransport } = await makeServerWithStructuredTool()
552 const { provider } = recordingValidator()
553 await using client = await createMCPClient({
554 transport: clientTransport,
555 prefix: 'weather',
556 clientOptions: { jsonSchemaValidator: provider },
557 })
558​
559 expect(client.getInfo().clientOptions).toEqual({
560 jsonSchemaValidator: provider,
561 })
562 })
563​
564 it('omits clientOptions from getInfo when none were given', async () => {
565 const { clientTransport } = await makeServerWithStructuredTool()
566 await using client = await createMCPClientFromTransport(clientTransport)
567​
568 // `toStrictEqual` rather than reading `.clientOptions`: the contract is that
569 // the key is OMITTED, and `toBeUndefined()` passes either way.
570 expect(client.getInfo()).toStrictEqual({
571 transport: undefined,
572 prefix: undefined,
573 })
574 })
575})
576​
577// tools/list always returns a new cursor, so pagination never reaches the last page.
578async function makeServerWithUnendingToolList() {
579 const [clientTransport, serverTransport] =
580 InMemoryTransport.createLinkedPair()
581 const server = new Server(
582 { name: 'unending-list', version: '1.0.0' },
583 { capabilities: { tools: {} } },
584 )
585 server.setRequestHandler('tools/list', (request) => {
586 const cursor = request.params?.cursor
587 const index = cursor === undefined ? 0 : Number(cursor)
588 return {
589 tools: [
590 {
591 name: `tool_${index}`,
592 inputSchema: { type: 'object' },
593 },
594 ],
595 nextCursor: String(index + 1),
596 }
597 })
598 await server.connect(serverTransport)
599 return { server, clientTransport }
601​
602// Spec 2026 server. Tool-list changes are sent only after subscriptions/listen.
603// The server has no public setter for the negotiated era, so the test sets it.
604async function makeModernChangingServer(options?: { failListen?: boolean }) {
605 const [clientTransport, serverTransport] =
606 InMemoryTransport.createLinkedPair()
607 const server = new Server(
608 { name: 'modern-changing', version: '1.0.0' },
609 {
610 capabilities: { tools: { listChanged: true } },
611 supportedProtocolVersions: [...SUPPORTED_PROTOCOL_VERSIONS, '2026-07-28'],
612 },
613 )
614 Object.assign(server, { _negotiatedProtocolVersion: '2026-07-28' })
615 let listRequests = 0
616 let listening = false
617 server.setRequestHandler('tools/list', () => {
618 listRequests += 1
619 return {
620 tools: [
621 {
622 name: 'tool_a',
623 description: 'A',
624 inputSchema: { type: 'object' },
625 },
626 ],
627 }
628 })
629 server.setRequestHandler('tools/call', (request) => ({
630 content: [{ type: 'text' as const, text: `called ${request.params.name}` }],
631 }))
632 await server.connect(serverTransport)
633 const previous = serverTransport.onmessage
634 serverTransport.onmessage = (message, extra) => {
635 if (!isSubscriptionsListen(message)) {
636 previous?.(message, extra)
637 return
638 }
639 if (options?.failListen) {
640 void serverTransport.send({
641 jsonrpc: '2.0',
642 id: message.id,
643 error: { code: -32603, message: 'listen failed' },
644 })
645 return
646 }
647 listening = true
648 void server.notification({
649 method: 'notifications/subscriptions/acknowledged',
650 params: {
651 _meta: {
652 'io.modelcontextprotocol/subscriptionId': message.id,
653 },
654 notifications: { toolsListChanged: true },
655 },
656 })
657 }
658 return {
659 server,
660 clientTransport,
661 getListRequests: () => listRequests,
662 sawListen: () => listening,
663 notifyToolListChanged: async () => {
664 if (!listening) return
665 await server.sendToolListChanged()
666 },
667 }
669​
670function isSubscriptionsListen(
671 message: JSONRPCMessage,
672): message is JSONRPCMessage & {
673 method: 'subscriptions/listen'
674 id: string | number
675} {
676 if (!('method' in message) || !('id' in message)) return false
677 return (
678 message.method === 'subscriptions/listen' &&
679 (typeof message.id === 'string' || typeof message.id === 'number')
680 )