@cogitator-ai/mcp 19.8.3 → 19.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +130 -8
  2. package/dist/adapter/tool-adapter.d.ts +8 -8
  3. package/dist/adapter/tool-adapter.d.ts.map +1 -1
  4. package/dist/adapter/tool-adapter.js +21 -16
  5. package/dist/adapter/tool-adapter.js.map +1 -1
  6. package/dist/client/input.d.ts +47 -0
  7. package/dist/client/input.d.ts.map +1 -0
  8. package/dist/client/input.js +125 -0
  9. package/dist/client/input.js.map +1 -0
  10. package/dist/client/mcp-client.d.ts +84 -8
  11. package/dist/client/mcp-client.d.ts.map +1 -1
  12. package/dist/client/mcp-client.js +614 -112
  13. package/dist/client/mcp-client.js.map +1 -1
  14. package/dist/client/oauth.d.ts +42 -0
  15. package/dist/client/oauth.d.ts.map +1 -0
  16. package/dist/client/oauth.js +171 -0
  17. package/dist/client/oauth.js.map +1 -0
  18. package/dist/client/param-headers.d.ts +10 -0
  19. package/dist/client/param-headers.d.ts.map +1 -0
  20. package/dist/client/param-headers.js +65 -0
  21. package/dist/client/param-headers.js.map +1 -0
  22. package/dist/client/raw-dispatch.d.ts +40 -0
  23. package/dist/client/raw-dispatch.d.ts.map +1 -0
  24. package/dist/client/raw-dispatch.js +148 -0
  25. package/dist/client/raw-dispatch.js.map +1 -0
  26. package/dist/client/rounds.d.ts +14 -0
  27. package/dist/client/rounds.d.ts.map +1 -0
  28. package/dist/client/rounds.js +33 -0
  29. package/dist/client/rounds.js.map +1 -0
  30. package/dist/client/tasks.d.ts +70 -0
  31. package/dist/client/tasks.d.ts.map +1 -0
  32. package/dist/client/tasks.js +186 -0
  33. package/dist/client/tasks.js.map +1 -0
  34. package/dist/client/transports.d.ts +5 -3
  35. package/dist/client/transports.d.ts.map +1 -1
  36. package/dist/client/transports.js +9 -8
  37. package/dist/client/transports.js.map +1 -1
  38. package/dist/digest.d.ts +8 -0
  39. package/dist/digest.d.ts.map +1 -0
  40. package/dist/digest.js +25 -0
  41. package/dist/digest.js.map +1 -0
  42. package/dist/index.d.ts +7 -3
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +6 -2
  45. package/dist/index.js.map +1 -1
  46. package/dist/server/approval.d.ts +17 -5
  47. package/dist/server/approval.d.ts.map +1 -1
  48. package/dist/server/approval.js +26 -12
  49. package/dist/server/approval.js.map +1 -1
  50. package/dist/server/execution.d.ts +134 -0
  51. package/dist/server/execution.d.ts.map +1 -0
  52. package/dist/server/execution.js +185 -0
  53. package/dist/server/execution.js.map +1 -0
  54. package/dist/server/mcp-server.d.ts +45 -19
  55. package/dist/server/mcp-server.d.ts.map +1 -1
  56. package/dist/server/mcp-server.js +551 -120
  57. package/dist/server/mcp-server.js.map +1 -1
  58. package/dist/server/questions.d.ts +19 -2
  59. package/dist/server/questions.d.ts.map +1 -1
  60. package/dist/server/questions.js +38 -21
  61. package/dist/server/questions.js.map +1 -1
  62. package/dist/server/request-state.d.ts +55 -0
  63. package/dist/server/request-state.d.ts.map +1 -0
  64. package/dist/server/request-state.js +66 -0
  65. package/dist/server/request-state.js.map +1 -0
  66. package/dist/server/serve-agents.d.ts.map +1 -1
  67. package/dist/server/serve-agents.js +203 -18
  68. package/dist/server/serve-agents.js.map +1 -1
  69. package/dist/server/tasks.d.ts +75 -0
  70. package/dist/server/tasks.d.ts.map +1 -0
  71. package/dist/server/tasks.js +280 -0
  72. package/dist/server/tasks.js.map +1 -0
  73. package/dist/server/tool-args.d.ts +24 -0
  74. package/dist/server/tool-args.d.ts.map +1 -0
  75. package/dist/server/tool-args.js +58 -0
  76. package/dist/server/tool-args.js.map +1 -0
  77. package/dist/types.d.ts +341 -11
  78. package/dist/types.d.ts.map +1 -1
  79. package/package.json +8 -5
@@ -2,12 +2,20 @@
2
2
  * MCP Client
3
3
  *
4
4
  * Connects to external MCP servers and provides access to their tools,
5
- * resources, and prompts.
5
+ * resources, and prompts. Speaks protocol 2026-07-28 to servers that do and
6
+ * 2025-11-25 to older ones.
6
7
  */
7
- import { Client } from '@modelcontextprotocol/sdk/client/index.js';
8
- import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';
8
+ import { Client, ProtocolError, ProtocolErrorCode, SdkError, SdkErrorCode, UnauthorizedError, isCallToolResult, isInputRequiredResult, } from '@modelcontextprotocol/client';
9
+ import { AjvJsonSchemaValidator } from '@modelcontextprotocol/client/validators/ajv';
9
10
  import { createStdioTransport, createHttpTransport, createSseTransport } from './transports.js';
10
11
  import { wrapMCPTools, mcpContentToResult } from '../adapter/tool-adapter.js';
12
+ import { RawDispatcher } from './raw-dispatch.js';
13
+ import { mcpParamHeaders } from './param-headers.js';
14
+ import { answerElicitation, answerInputRequests, answerPlanned, planInputRequests, toElicitRequest, } from './input.js';
15
+ import { DEFAULT_ROUND_TTL_MS, InMemoryMCPClientRoundStore } from './rounds.js';
16
+ import { callDigest } from '../digest.js';
17
+ import { DEFAULT_MAX_POLL_INTERVAL_MS, InMemoryMCPClientTaskStore, TASKS_EXTENSION, TaskSchema, settleTask, } from './tasks.js';
18
+ import { createMCPOAuthProvider } from './oauth.js';
11
19
  const DEFAULT_RETRY_CONFIG = {
12
20
  maxRetries: 3,
13
21
  initialDelay: 1000,
@@ -15,8 +23,9 @@ const DEFAULT_RETRY_CONFIG = {
15
23
  backoffMultiplier: 2,
16
24
  retryOnConnectionLoss: true,
17
25
  };
18
- const CONNECTION_CLOSED_CODE = ErrorCode.ConnectionClosed;
19
- const REQUEST_TIMEOUT_CODE = ErrorCode.RequestTimeout;
26
+ const DEFAULT_MAX_INPUT_ROUNDS = 10;
27
+ const CLIENT_CAPABILITIES_KEY = 'io.modelcontextprotocol/clientCapabilities';
28
+ const DEFAULT_PROBE_TIMEOUT_MS = 30_000;
20
29
  function sleep(ms) {
21
30
  return new Promise((resolve) => setTimeout(resolve, ms));
22
31
  }
@@ -49,7 +58,9 @@ export class MCPToolInterruptedError extends Error {
49
58
  constructor(toolName, reason, cause) {
50
59
  const what = reason === 'timeout'
51
60
  ? `MCP tool "${toolName}" timed out${timeoutOf(cause)}`
52
- : `The connection to the MCP server was lost during a call of tool "${toolName}"`;
61
+ : reason === 'task-lost'
62
+ ? `The server no longer knows the task an earlier run of a call of tool "${toolName}" started (it may have expired)`
63
+ : `The connection to the MCP server was lost during a call of tool "${toolName}"`;
53
64
  super(`${what}. It was not called again, since the server may have run it and the tool is ` +
54
65
  'not marked idempotent or read-only.', { cause });
55
66
  this.name = 'MCPToolInterruptedError';
@@ -58,19 +69,33 @@ export class MCPToolInterruptedError extends Error {
58
69
  }
59
70
  }
60
71
  function timeoutOf(error) {
61
- if (!(error instanceof McpError) || typeof error.data !== 'object' || error.data === null) {
72
+ if (!(error instanceof SdkError) || typeof error.data !== 'object' || error.data === null) {
62
73
  return '';
63
74
  }
64
75
  const timeout = error.data.timeout;
65
76
  return typeof timeout === 'number' ? ` after ${timeout}ms` : '';
66
77
  }
67
78
  function isRequestTimeout(error) {
68
- return error instanceof McpError && error.code === REQUEST_TIMEOUT_CODE;
79
+ return error instanceof SdkError && error.code === SdkErrorCode.RequestTimeout;
80
+ }
81
+ /**
82
+ * Whether `error` is the signal `context.interrupt()` throws to pause the calling run (core's
83
+ * `ToolInterruptSignal`, recognized by shape so the client does not load core). It must reach the
84
+ * run unchanged: its message is the question, which may well say "connection" or "closed"
85
+ */
86
+ function isRunInterrupt(error) {
87
+ return error instanceof Error && error.name === 'ToolInterruptSignal' && 'interrupt' in error;
69
88
  }
70
89
  function isConnectionError(error) {
71
- if (error instanceof McpError) {
72
- return error.code === CONNECTION_CLOSED_CODE;
90
+ if (isRunInterrupt(error))
91
+ return false;
92
+ if (error instanceof SdkError) {
93
+ return (error.code === SdkErrorCode.ConnectionClosed ||
94
+ error.code === SdkErrorCode.NotConnected ||
95
+ error.code === SdkErrorCode.SendFailed);
73
96
  }
97
+ if (error instanceof ProtocolError)
98
+ return false;
74
99
  if (error instanceof Error) {
75
100
  const msg = error.message.toLowerCase();
76
101
  return (msg.includes('connection') ||
@@ -83,13 +108,14 @@ function isConnectionError(error) {
83
108
  return false;
84
109
  }
85
110
  function isRetryableError(error) {
86
- if (error instanceof MCPToolError) {
111
+ if (isRunInterrupt(error))
87
112
  return false;
113
+ if (error instanceof MCPToolError || error instanceof ProtocolError)
114
+ return false;
115
+ if (error instanceof SdkError) {
116
+ return isConnectionError(error) || error.code === SdkErrorCode.RequestTimeout;
88
117
  }
89
- if (error instanceof McpError) {
90
- return error.code === CONNECTION_CLOSED_CODE || error.code === REQUEST_TIMEOUT_CODE;
91
- }
92
- return true;
118
+ return !(error instanceof Error && error.name === 'MCPTaskEndedError');
93
119
  }
94
120
  /**
95
121
  * MCP Client for connecting to external MCP servers
@@ -125,29 +151,109 @@ export class MCPClient {
125
151
  config;
126
152
  retryConfig;
127
153
  serverCapabilities = {};
128
- constructor(client, transport, config) {
129
- this.client = client;
130
- this.transport = transport;
154
+ authProvider;
155
+ dispatcher;
156
+ taskStore;
157
+ roundStore;
158
+ toolDefinitions = new Map();
159
+ listeners = new Set();
160
+ connectionWatchers = new Set();
161
+ /**
162
+ * How many open legacy subscriptions follow each resource: the server keeps one subscription
163
+ * per connection and URI, so it is unsubscribed only once the last of them closes
164
+ */
165
+ resourceRefs = new Map();
166
+ validator = new AjvJsonSchemaValidator();
167
+ prior;
168
+ negotiatedVersion;
169
+ serverTakesTasks = false;
170
+ constructor(config) {
131
171
  this.config = config;
132
172
  this.retryConfig = { ...DEFAULT_RETRY_CONFIG, ...config.retry };
173
+ this.authProvider =
174
+ config.auth === undefined
175
+ ? undefined
176
+ : isOAuthClientProvider(config.auth)
177
+ ? config.auth
178
+ : createMCPOAuthProvider(config.auth, {
179
+ resource: config.url ?? 'mcp://unknown',
180
+ clientName: config.clientName ?? 'cogitator-mcp-client',
181
+ });
182
+ this.dispatcher = new RawDispatcher(() => this.requestMeta());
183
+ const tasks = typeof config.tasks === 'object' ? config.tasks : undefined;
184
+ this.taskStore = tasks?.store ?? new InMemoryMCPClientTaskStore();
185
+ this.roundStore = config.rounds?.store ?? new InMemoryMCPClientRoundStore();
186
+ this.client = this.createSdkClient();
187
+ this.transport = this.createTransport();
133
188
  }
134
189
  /**
135
190
  * Connect to an MCP server
136
191
  */
137
192
  static async connect(config) {
138
- const client = new Client({
139
- name: config.clientName ?? 'cogitator-mcp-client',
140
- version: config.clientVersion ?? '1.0.0',
141
- });
142
- const transport = MCPClient.createTransport(config);
143
- const mcpClient = new MCPClient(client, transport, config);
193
+ const mcpClient = new MCPClient(config);
144
194
  await mcpClient.initialize(config.timeout);
145
195
  return mcpClient;
146
196
  }
197
+ createSdkClient() {
198
+ const elicitation = this.config.elicitation;
199
+ const capabilities = typeof elicitation === 'function' ? { elicitation: { form: {}, url: {} } } : {};
200
+ const client = new Client({
201
+ name: this.config.clientName ?? 'cogitator-mcp-client',
202
+ version: this.config.clientVersion ?? '1.0.0',
203
+ }, {
204
+ capabilities,
205
+ versionNegotiation: {
206
+ mode: negotiationMode(this.config),
207
+ probe: { timeoutMs: this.config.timeout ?? DEFAULT_PROBE_TIMEOUT_MS },
208
+ },
209
+ inputRequired: { autoFulfill: false },
210
+ });
211
+ if (typeof elicitation === 'function') {
212
+ const handler = elicitation;
213
+ client.setRequestHandler('elicitation/create', async (request) => {
214
+ const answerer = {
215
+ source: { server: this.serverName ?? '' },
216
+ handler,
217
+ ledger: [],
218
+ consumed: new Set(),
219
+ };
220
+ const answer = await answerElicitation(toElicitRequest(request.params), answerer);
221
+ return answer.action === 'accept'
222
+ ? { action: 'accept', content: answer.content }
223
+ : { action: answer.action };
224
+ });
225
+ }
226
+ client.setNotificationHandler('notifications/tools/list_changed', () => {
227
+ this.toolDefinitions.clear();
228
+ this.notify('toolsListChanged', (handlers) => handlers.onToolsChanged?.());
229
+ });
230
+ client.setNotificationHandler('notifications/prompts/list_changed', () => {
231
+ this.notify('promptsListChanged', (handlers) => handlers.onPromptsChanged?.());
232
+ });
233
+ client.setNotificationHandler('notifications/resources/list_changed', () => {
234
+ this.notify('resourcesListChanged', (handlers) => handlers.onResourcesChanged?.());
235
+ });
236
+ client.setNotificationHandler('notifications/resources/updated', (notification) => {
237
+ const uri = notification.params.uri;
238
+ for (const { filter, handlers } of this.listeners) {
239
+ if (filter.resourceSubscriptions?.includes(uri))
240
+ handlers.onResourceUpdated?.(uri);
241
+ }
242
+ });
243
+ client.onclose = () => {
244
+ this.connected = false;
245
+ const watchers = [...this.connectionWatchers];
246
+ this.connectionWatchers.clear();
247
+ for (const watcher of watchers)
248
+ watcher();
249
+ };
250
+ return client;
251
+ }
147
252
  /**
148
253
  * Create transport based on configuration
149
254
  */
150
- static createTransport(config) {
255
+ createTransport() {
256
+ const config = this.config;
151
257
  switch (config.transport) {
152
258
  case 'stdio':
153
259
  if (!config.command) {
@@ -167,6 +273,7 @@ export class MCPClient {
167
273
  return createHttpTransport({
168
274
  url: config.url,
169
275
  headers: config.headers,
276
+ ...(this.authProvider && { authProvider: this.authProvider }),
170
277
  });
171
278
  case 'legacy-sse':
172
279
  if (!config.url) {
@@ -175,16 +282,38 @@ export class MCPClient {
175
282
  return createSseTransport({
176
283
  url: config.url,
177
284
  headers: config.headers,
285
+ ...(this.authProvider && { authProvider: this.authProvider }),
178
286
  });
179
287
  default:
180
- throw new Error(`Unknown transport type: ${config.transport}`);
288
+ throw new Error(`Unknown transport type: ${String(config.transport)}`);
181
289
  }
182
290
  }
183
291
  /**
184
- * Initialize connection and capabilities
292
+ * Initialize connection and capabilities. A server that asks for OAuth sends the person to
293
+ * authorize once (`auth.authorize`), then the client connects again
185
294
  */
186
295
  async initialize(timeout) {
187
- const connectPromise = this.client.connect(this.transport);
296
+ try {
297
+ await this.connectOnce(timeout);
298
+ }
299
+ catch (error) {
300
+ const provider = this.authProvider;
301
+ if (!(error instanceof UnauthorizedError) || !isMCPOAuthProvider(provider))
302
+ throw error;
303
+ const callback = await provider.completeAuthorization();
304
+ if (!callback)
305
+ throw error;
306
+ const transport = this.transport;
307
+ await transport.finishAuth(callback);
308
+ this.client = this.createSdkClient();
309
+ this.transport = this.createTransport();
310
+ await this.connectOnce(timeout);
311
+ }
312
+ }
313
+ async connectOnce(timeout) {
314
+ const connectPromise = this.client.connect(this.transport, {
315
+ ...(this.prior && { prior: this.prior }),
316
+ });
188
317
  let timer;
189
318
  try {
190
319
  if (timeout) {
@@ -209,12 +338,18 @@ export class MCPClient {
209
338
  }
210
339
  }
211
340
  this.connected = true;
341
+ this.dispatcher.attach(this.transport);
342
+ this.negotiatedVersion = this.client.getNegotiatedProtocolVersion();
343
+ const discover = this.client.getDiscoverResult();
344
+ this.prior = discover ? { kind: 'modern', discover } : { kind: 'legacy' };
212
345
  const serverInfo = this.client.getServerCapabilities();
213
346
  this.serverCapabilities = {
214
347
  tools: !!serverInfo?.tools,
215
348
  resources: !!serverInfo?.resources,
216
349
  prompts: !!serverInfo?.prompts,
217
350
  };
351
+ this.serverTakesTasks =
352
+ discover !== undefined && serverInfo?.extensions?.[TASKS_EXTENSION] !== undefined;
218
353
  }
219
354
  /**
220
355
  * Check if connected to server
@@ -228,6 +363,32 @@ export class MCPClient {
228
363
  getCapabilities() {
229
364
  return { ...this.serverCapabilities };
230
365
  }
366
+ /** The protocol revision the connection speaks, such as `2026-07-28` */
367
+ get protocolVersion() {
368
+ return this.negotiatedVersion;
369
+ }
370
+ /** `modern` for protocol 2026-07-28 and later, `legacy` for a server of an earlier revision */
371
+ get era() {
372
+ return this.client.getDiscoverResult() ? 'modern' : 'legacy';
373
+ }
374
+ /** What the server tells the model about using it, if anything */
375
+ get instructions() {
376
+ return this.client.getInstructions();
377
+ }
378
+ /** What the server says of itself: revision, capabilities, instructions and name */
379
+ discover() {
380
+ const discover = this.client.getDiscoverResult();
381
+ const version = this.client.getServerVersion();
382
+ const instructions = this.client.getInstructions();
383
+ return {
384
+ protocolVersion: this.negotiatedVersion ?? '',
385
+ era: discover ? 'modern' : 'legacy',
386
+ ...(discover && { supportedVersions: [...discover.supportedVersions] }),
387
+ capabilities: { ...(this.client.getServerCapabilities() ?? {}) },
388
+ ...(instructions !== undefined && { instructions }),
389
+ ...(version && { serverInfo: { name: version.name, version: version.version } }),
390
+ };
391
+ }
231
392
  /**
232
393
  * Check if currently reconnecting
233
394
  */
@@ -239,7 +400,8 @@ export class MCPClient {
239
400
  *
240
401
  * Concurrent callers share the same in-flight reconnection, so parallel
241
402
  * operations that all observe a dropped connection wait for one reconnect
242
- * instead of failing.
403
+ * instead of failing. The revision found on the first connect is kept, so a
404
+ * reconnect does not ask the server again.
243
405
  */
244
406
  reconnect() {
245
407
  if (this.closed) {
@@ -262,12 +424,10 @@ export class MCPClient {
262
424
  }
263
425
  this.config.onReconnecting?.(attempt);
264
426
  try {
427
+ this.dispatcher.detach();
265
428
  await this.client.close().catch(() => { });
266
- this.client = new Client({
267
- name: this.config.clientName ?? 'cogitator-mcp-client',
268
- version: this.config.clientVersion ?? '1.0.0',
269
- });
270
- this.transport = MCPClient.createTransport(this.config);
429
+ this.client = this.createSdkClient();
430
+ this.transport = this.createTransport();
271
431
  await this.initialize(this.config.timeout);
272
432
  if (this.closed) {
273
433
  this.connected = false;
@@ -278,7 +438,10 @@ export class MCPClient {
278
438
  return;
279
439
  }
280
440
  catch (error) {
441
+ if (isRunInterrupt(error))
442
+ throw error;
281
443
  lastError = error instanceof Error ? error : new Error(String(error));
444
+ this.prior = undefined;
282
445
  if (this.closed) {
283
446
  throw lastError;
284
447
  }
@@ -349,24 +512,20 @@ export class MCPClient {
349
512
  return [];
350
513
  }
351
514
  return this.withRetry(async () => {
352
- const tools = [];
353
- let cursor;
354
- do {
355
- const result = await this.client.listTools(cursor ? { cursor } : {});
356
- for (const tool of result.tools) {
357
- tools.push({
358
- name: tool.name,
359
- ...(tool.title !== undefined && { title: tool.title }),
360
- description: tool.description ?? '',
361
- inputSchema: tool.inputSchema,
362
- ...(tool.outputSchema && {
363
- outputSchema: tool.outputSchema,
364
- }),
365
- ...(tool.annotations && { annotations: tool.annotations }),
366
- });
367
- }
368
- cursor = result.nextCursor;
369
- } while (cursor);
515
+ const result = await this.client.listTools();
516
+ const tools = result.tools.map((tool) => ({
517
+ name: tool.name,
518
+ ...(tool.title !== undefined && { title: tool.title }),
519
+ description: tool.description ?? '',
520
+ inputSchema: tool.inputSchema,
521
+ ...(tool.outputSchema && {
522
+ outputSchema: tool.outputSchema,
523
+ }),
524
+ ...(tool.annotations && { annotations: tool.annotations }),
525
+ }));
526
+ this.toolDefinitions.clear();
527
+ for (const tool of tools)
528
+ this.toolDefinitions.set(tool.name, tool);
370
529
  return tools;
371
530
  }, 'listToolDefinitions');
372
531
  }
@@ -390,39 +549,245 @@ export class MCPClient {
390
549
  * value(s) of text content, or a `toolContent()` result when the content holds images, audio
391
550
  * or binary resources. Throws {@link MCPToolError} when the server reports `isError: true`.
392
551
  *
552
+ * A server may ask for input during the call (elicitation): it is asked through the run of
553
+ * the call (`options.interrupt`), else from the `elicitation` handler, else declined. A server
554
+ * may answer with a task, which is polled until it ends, and cancelled when `signal` aborts.
555
+ *
393
556
  * A call is sent once. Only with `idempotent: true` (a read-only or idempotent tool) is it sent
394
557
  * again after a timeout or a lost connection, otherwise those throw
395
558
  * {@link MCPToolInterruptedError}, since the server may have run the call. A connection that was
396
- * already lost is restored before the call is sent.
559
+ * already lost is restored before the call is sent. A task survives a lost connection: its
560
+ * polling goes on once the connection is back.
397
561
  */
398
562
  async callTool(name, args, options) {
399
- const call = async () => {
400
- const result = await this.client.callTool({ name, arguments: args }, undefined, {
401
- signal: options?.signal,
402
- timeout: options?.timeout,
403
- });
404
- const content = toToolContent(Array.isArray(result.content) ? result.content : []);
405
- if (result.isError) {
406
- throw new MCPToolError(name, content);
563
+ const call = async () => toolResultValue(name, await this.callToolResult(name, args, options));
564
+ if (options?.idempotent === true) {
565
+ return this.withRetry(call, `callTool:${name}`, options.signal);
566
+ }
567
+ return this.callOnce(call, name);
568
+ }
569
+ /**
570
+ * Call a tool and return the server's result as it is: content, `structuredContent` and
571
+ * `isError`. Input requests and tasks are handled as for {@link callTool}
572
+ */
573
+ async callToolResult(name, args, options = {}) {
574
+ const answerer = this.answererFor(name, options);
575
+ const reattached = await this.reattachTask(name, answerer, options);
576
+ if (reattached)
577
+ return reattached;
578
+ const maxRounds = this.config.maxInputRounds ?? DEFAULT_MAX_INPUT_ROUNDS;
579
+ const roundKey = answerer.interrupt ? options.toolCallId : undefined;
580
+ const digest = callDigest(name, args);
581
+ let inputResponses;
582
+ let requestState;
583
+ const pending = roundKey ? await this.roundStore.get(roundKey) : undefined;
584
+ if (pending?.tool === name && pending.digest === digest) {
585
+ answerer.ledger.push(...pending.asked);
586
+ inputResponses = await answerPlanned(pending.round, answerer);
587
+ requestState = pending.requestState;
588
+ }
589
+ for (let round = 0;; round++) {
590
+ let reply;
591
+ try {
592
+ reply = await this.sendToolCall(name, args, inputResponses, requestState, options);
407
593
  }
408
- if (content.length > 0 && hasMedia(content)) {
409
- return mcpContentToResult(content);
594
+ catch (error) {
595
+ if (roundKey)
596
+ await this.roundStore.delete(roundKey);
597
+ throw error;
410
598
  }
411
- if (result.structuredContent !== undefined) {
412
- return result.structuredContent;
599
+ if (reply.kind !== 'input_required') {
600
+ if (roundKey)
601
+ await this.roundStore.delete(roundKey);
602
+ if (reply.kind === 'complete')
603
+ return reply.result;
604
+ return this.toolResultOf(name, await this.settle(reply.task, name, answerer, options));
413
605
  }
414
- if (content.length > 0) {
415
- return mcpContentToResult(content);
606
+ if (round >= maxRounds) {
607
+ if (roundKey)
608
+ await this.roundStore.delete(roundKey);
609
+ throw new ProtocolError(ProtocolErrorCode.InternalError, `MCP tool "${name}" kept asking for input: ${maxRounds} rounds without a result`);
416
610
  }
417
- if ('toolResult' in result) {
418
- return result.toolResult;
611
+ const planned = planInputRequests(reply.inputRequests, answerer);
612
+ if (roundKey) {
613
+ await this.roundStore.set(roundKey, {
614
+ tool: name,
615
+ digest,
616
+ ...(reply.requestState !== undefined && { requestState: reply.requestState }),
617
+ round: planned.map(({ key, asked }) => ({ key, asked })),
618
+ asked: [...answerer.ledger],
619
+ expiresAt: Date.now() + (this.config.rounds?.ttlMs ?? DEFAULT_ROUND_TTL_MS),
620
+ });
419
621
  }
420
- return null;
622
+ inputResponses = await answerPlanned(planned, answerer);
623
+ requestState = reply.requestState;
624
+ }
625
+ }
626
+ answererFor(name, options) {
627
+ const handler = typeof this.config.elicitation === 'function' ? this.config.elicitation : undefined;
628
+ return {
629
+ source: { server: this.serverName ?? '', tool: name },
630
+ ...(this.config.elicitation !== false &&
631
+ options.interrupt && { interrupt: options.interrupt }),
632
+ ...(handler && { handler }),
633
+ ledger: [],
634
+ consumed: new Set(),
421
635
  };
422
- if (options?.idempotent === true) {
423
- return this.withRetry(call, `callTool:${name}`, options.signal);
636
+ }
637
+ /** The task an earlier run of the same tool call started, polled again, if there is one */
638
+ async reattachTask(name, answerer, options) {
639
+ const key = options.toolCallId;
640
+ if (!key || !this.takesTasks())
641
+ return undefined;
642
+ const record = await this.taskStore.get(key);
643
+ if (record?.tool !== name)
644
+ return undefined;
645
+ let task;
646
+ try {
647
+ task = TaskSchema.parse(await this.dispatcher.request('tasks/get', { taskId: record.taskId }, { signal: options.signal }));
424
648
  }
425
- return this.callOnce(call, name);
649
+ catch (error) {
650
+ if (error instanceof ProtocolError) {
651
+ await this.taskStore.delete(key);
652
+ if (options.idempotent === true)
653
+ return undefined;
654
+ throw new MCPToolInterruptedError(name, 'task-lost', error);
655
+ }
656
+ throw error;
657
+ }
658
+ answerer.ledger.push(...record.asked);
659
+ return this.toolResultOf(name, await this.settle(task, name, answerer, options));
660
+ }
661
+ settle(task, name, answerer, options) {
662
+ const tasks = typeof this.config.tasks === 'object' ? this.config.tasks : undefined;
663
+ const host = {
664
+ request: (method, params, signal) => this.dispatcher.request(method, params, signal ? { signal } : {}),
665
+ restore: async (error) => {
666
+ if (!isConnectionError(error) || this.config.autoReconnect === false)
667
+ return false;
668
+ await this.reconnect();
669
+ return true;
670
+ },
671
+ };
672
+ const update = options.update;
673
+ return settleTask(task, {
674
+ host,
675
+ toolName: name,
676
+ answerer,
677
+ store: this.taskStore,
678
+ ...(options.toolCallId && { storeKey: options.toolCallId }),
679
+ maxPollIntervalMs: tasks?.maxPollIntervalMs ?? DEFAULT_MAX_POLL_INTERVAL_MS,
680
+ ...(options.signal && { signal: options.signal }),
681
+ ...(update && {
682
+ update: (statusMessage) => update({ details: { statusMessage } }),
683
+ }),
684
+ });
685
+ }
686
+ /** Whether calls go out with the tasks extension: the server takes tasks and the client does */
687
+ takesTasks() {
688
+ return this.config.tasks !== false && this.serverTakesTasks;
689
+ }
690
+ async sendToolCall(name, args, inputResponses, requestState, options) {
691
+ const canAnswer = this.canAnswer(options);
692
+ const params = {
693
+ name,
694
+ arguments: args,
695
+ ...(inputResponses && { inputResponses }),
696
+ ...(requestState !== undefined && { requestState }),
697
+ };
698
+ if (this.takesTasks())
699
+ return this.sendRawToolCall(params, options, canAnswer);
700
+ const call = this.era === 'modern'
701
+ ? { ...params, _meta: { [CLIENT_CAPABILITIES_KEY]: this.capabilities(canAnswer) } }
702
+ : params;
703
+ const result = await this.client.callTool(call, {
704
+ ...(options.signal && { signal: options.signal }),
705
+ ...(options.timeout !== undefined && { timeout: options.timeout }),
706
+ allowInputRequired: true,
707
+ });
708
+ if (isInputRequiredResult(result)) {
709
+ return {
710
+ kind: 'input_required',
711
+ inputRequests: { ...(result.inputRequests ?? {}) },
712
+ ...(result.requestState !== undefined && { requestState: result.requestState }),
713
+ };
714
+ }
715
+ return { kind: 'complete', result: toCallResult(result) };
716
+ }
717
+ /**
718
+ * `tools/call` sent past the SDK client, which cannot read a task: with the tasks extension
719
+ * in the request's capabilities and the `Mcp-Param-*` headers of the tool's arguments
720
+ */
721
+ async sendRawToolCall(params, options, canAnswer) {
722
+ const tool = await this.toolDefinition(params.name);
723
+ const headers = tool ? mcpParamHeaders(tool.inputSchema, params.arguments) : {};
724
+ const framed = {
725
+ ...params,
726
+ _meta: { [CLIENT_CAPABILITIES_KEY]: this.capabilities(canAnswer) },
727
+ };
728
+ const result = await this.dispatcher.request('tools/call', framed, {
729
+ ...(options.signal && { signal: options.signal }),
730
+ ...(options.timeout !== undefined && { timeout: options.timeout }),
731
+ ...(Object.keys(headers).length > 0 && { headers }),
732
+ });
733
+ if (result.resultType === 'task')
734
+ return { kind: 'task', task: TaskSchema.parse(result) };
735
+ if (isInputRequiredResult(result)) {
736
+ return {
737
+ kind: 'input_required',
738
+ inputRequests: { ...(result.inputRequests ?? {}) },
739
+ ...(result.requestState !== undefined && { requestState: result.requestState }),
740
+ };
741
+ }
742
+ return { kind: 'complete', result: this.toolResultOf(params.name, result) };
743
+ }
744
+ /** A tool result as the server sent it, checked against the tool's output schema */
745
+ toolResultOf(name, result) {
746
+ if (!isCallToolResult(result)) {
747
+ throw new ProtocolError(ProtocolErrorCode.InvalidParams, `MCP tool "${name}" answered with something that is no tool result`);
748
+ }
749
+ const call = toCallResult(result);
750
+ const schema = this.toolDefinitions.get(name)?.outputSchema;
751
+ if (schema && !call.isError && call.structuredContent !== undefined) {
752
+ const check = this.validator.getValidator(schema)(call.structuredContent);
753
+ if (!check.valid) {
754
+ throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Structured content of MCP tool "${name}" does not match its output schema: ${check.errorMessage}`);
755
+ }
756
+ }
757
+ return call;
758
+ }
759
+ async toolDefinition(name) {
760
+ if (!this.toolDefinitions.has(name))
761
+ await this.listToolDefinitions().catch(() => []);
762
+ return this.toolDefinitions.get(name);
763
+ }
764
+ /** Whether someone can answer the elicitation requests of a call: its run or the handler */
765
+ canAnswer(options) {
766
+ const elicitation = this.config.elicitation;
767
+ if (elicitation === false)
768
+ return false;
769
+ return typeof elicitation === 'function' || options.interrupt !== undefined;
770
+ }
771
+ /**
772
+ * The capabilities a request declares (protocol 2026-07-28 declares them per request):
773
+ * elicitation when someone can answer, and the tasks extension when the client takes tasks
774
+ */
775
+ capabilities(canAnswer) {
776
+ return {
777
+ ...(canAnswer && { elicitation: { form: {}, url: {} } }),
778
+ ...(this.takesTasks() && { extensions: { [TASKS_EXTENSION]: {} } }),
779
+ };
780
+ }
781
+ /** The `_meta` of a request sent past the SDK client */
782
+ requestMeta() {
783
+ return {
784
+ 'io.modelcontextprotocol/protocolVersion': this.negotiatedVersion,
785
+ 'io.modelcontextprotocol/clientInfo': {
786
+ name: this.config.clientName ?? 'cogitator-mcp-client',
787
+ version: this.config.clientVersion ?? '1.0.0',
788
+ },
789
+ [CLIENT_CAPABILITIES_KEY]: this.capabilities(typeof this.config.elicitation === 'function'),
790
+ };
426
791
  }
427
792
  /** A call that must not run twice: sent once, on a connection restored beforehand if needed. */
428
793
  async callOnce(operation, toolName) {
@@ -438,7 +803,7 @@ export class MCPClient {
438
803
  return await operation();
439
804
  }
440
805
  catch (error) {
441
- if (error instanceof MCPToolError)
806
+ if (error instanceof MCPToolError || isRunInterrupt(error))
442
807
  throw error;
443
808
  if (isConnectionError(error)) {
444
809
  this.connected = false;
@@ -450,6 +815,94 @@ export class MCPClient {
450
815
  throw error;
451
816
  }
452
817
  }
818
+ /**
819
+ * Hear of the server's changes: its tool, prompt or resource lists, or updates of resources.
820
+ * On protocol 2026-07-28 this opens a `subscriptions/listen` stream, on earlier revisions the
821
+ * server sends list changes on its own and resources are subscribed one by one. The filter of
822
+ * the subscription is what the server agreed to
823
+ */
824
+ async subscribe(filter, handlers) {
825
+ if (this.era === 'modern') {
826
+ const subscription = await this.client.listen(filter);
827
+ const honored = { ...subscription.honoredFilter };
828
+ const listener = { filter: honored, handlers };
829
+ this.listeners.add(listener);
830
+ return {
831
+ filter: honored,
832
+ closed: subscription.closed.then((how) => {
833
+ this.listeners.delete(listener);
834
+ return how;
835
+ }),
836
+ close: () => subscription.close(),
837
+ };
838
+ }
839
+ const capabilities = this.client.getServerCapabilities();
840
+ const uris = capabilities?.resources?.subscribe
841
+ ? [...new Set(filter.resourceSubscriptions ?? [])]
842
+ : [];
843
+ for (const uri of uris) {
844
+ const refs = this.resourceRefs.get(uri) ?? 0;
845
+ if (refs === 0)
846
+ await this.client.subscribeResource({ uri });
847
+ this.resourceRefs.set(uri, refs + 1);
848
+ }
849
+ const release = () => {
850
+ const last = [];
851
+ for (const uri of uris) {
852
+ const refs = (this.resourceRefs.get(uri) ?? 1) - 1;
853
+ if (refs > 0) {
854
+ this.resourceRefs.set(uri, refs);
855
+ }
856
+ else {
857
+ this.resourceRefs.delete(uri);
858
+ last.push(uri);
859
+ }
860
+ }
861
+ return last;
862
+ };
863
+ const honored = {
864
+ ...(filter.toolsListChanged &&
865
+ capabilities?.tools?.listChanged && { toolsListChanged: true }),
866
+ ...(filter.promptsListChanged &&
867
+ capabilities?.prompts?.listChanged && { promptsListChanged: true }),
868
+ ...(filter.resourcesListChanged &&
869
+ capabilities?.resources?.listChanged && { resourcesListChanged: true }),
870
+ ...(uris.length > 0 && { resourceSubscriptions: [...uris] }),
871
+ };
872
+ const listener = { filter: honored, handlers };
873
+ this.listeners.add(listener);
874
+ let end = () => { };
875
+ const closed = new Promise((resolve) => {
876
+ end = (how) => {
877
+ this.listeners.delete(listener);
878
+ this.connectionWatchers.delete(onDrop);
879
+ resolve(how);
880
+ };
881
+ });
882
+ const onDrop = () => {
883
+ release();
884
+ end('remote');
885
+ };
886
+ this.connectionWatchers.add(onDrop);
887
+ return {
888
+ filter: honored,
889
+ closed,
890
+ close: async () => {
891
+ if (!this.listeners.has(listener))
892
+ return;
893
+ end('local');
894
+ for (const uri of release()) {
895
+ await this.client.unsubscribeResource({ uri }).catch(() => undefined);
896
+ }
897
+ },
898
+ };
899
+ }
900
+ notify(kind, call) {
901
+ for (const { filter, handlers } of this.listeners) {
902
+ if (filter[kind])
903
+ call(handlers);
904
+ }
905
+ }
453
906
  /**
454
907
  * List available resources from the MCP server with automatic retry
455
908
  */
@@ -458,21 +911,13 @@ export class MCPClient {
458
911
  return [];
459
912
  }
460
913
  return this.withRetry(async () => {
461
- const resources = [];
462
- let cursor;
463
- do {
464
- const result = await this.client.listResources(cursor ? { cursor } : {});
465
- for (const resource of result.resources) {
466
- resources.push({
467
- uri: resource.uri,
468
- name: resource.name,
469
- description: resource.description,
470
- mimeType: resource.mimeType,
471
- });
472
- }
473
- cursor = result.nextCursor;
474
- } while (cursor);
475
- return resources;
914
+ const result = await this.client.listResources();
915
+ return result.resources.map((resource) => ({
916
+ uri: resource.uri,
917
+ name: resource.name,
918
+ description: resource.description,
919
+ mimeType: resource.mimeType,
920
+ }));
476
921
  }, 'listResources');
477
922
  }
478
923
  /**
@@ -488,7 +933,9 @@ export class MCPClient {
488
933
  */
489
934
  async readResourceContents(uri) {
490
935
  return this.withRetry(async () => {
491
- const result = await this.client.readResource({ uri });
936
+ const result = await this.withInput(`resource ${uri}`, (input) => this.client.readResource({ uri, ...input }, {
937
+ allowInputRequired: true,
938
+ }));
492
939
  return (result.contents ?? []).map((content) => ({
493
940
  uri: content.uri,
494
941
  mimeType: content.mimeType,
@@ -505,24 +952,16 @@ export class MCPClient {
505
952
  return [];
506
953
  }
507
954
  return this.withRetry(async () => {
508
- const prompts = [];
509
- let cursor;
510
- do {
511
- const result = await this.client.listPrompts(cursor ? { cursor } : {});
512
- for (const prompt of result.prompts) {
513
- prompts.push({
514
- name: prompt.name,
515
- description: prompt.description,
516
- arguments: prompt.arguments?.map((arg) => ({
517
- name: arg.name,
518
- description: arg.description,
519
- required: arg.required,
520
- })),
521
- });
522
- }
523
- cursor = result.nextCursor;
524
- } while (cursor);
525
- return prompts;
955
+ const result = await this.client.listPrompts();
956
+ return result.prompts.map((prompt) => ({
957
+ name: prompt.name,
958
+ description: prompt.description,
959
+ arguments: prompt.arguments?.map((arg) => ({
960
+ name: arg.name,
961
+ description: arg.description,
962
+ required: arg.required,
963
+ })),
964
+ }));
526
965
  }, 'listPrompts');
527
966
  }
528
967
  /**
@@ -530,10 +969,7 @@ export class MCPClient {
530
969
  */
531
970
  async getPrompt(name, args) {
532
971
  return this.withRetry(async () => {
533
- const result = await this.client.getPrompt({
534
- name,
535
- arguments: args ?? {},
536
- });
972
+ const result = await this.withInput(`prompt ${name}`, (input) => this.client.getPrompt({ name, arguments: args ?? {}, ...input }, { allowInputRequired: true }));
537
973
  return result.messages.map((msg) => {
538
974
  const content = msg.content;
539
975
  return {
@@ -543,6 +979,27 @@ export class MCPClient {
543
979
  });
544
980
  }, `getPrompt:${name}`);
545
981
  }
982
+ /**
983
+ * A request that a server of protocol 2026-07-28 may answer with input requests, sent again
984
+ * with the answers of the elicitation handler until it completes
985
+ */
986
+ async withInput(what, send) {
987
+ const maxRounds = this.config.maxInputRounds ?? DEFAULT_MAX_INPUT_ROUNDS;
988
+ const answerer = this.answererFor(what, {});
989
+ let input = {};
990
+ for (let round = 0;; round++) {
991
+ const result = await send(input);
992
+ if (!isInputRequiredResult(result))
993
+ return result;
994
+ if (round >= maxRounds) {
995
+ throw new ProtocolError(ProtocolErrorCode.InternalError, `The MCP server kept asking for input for ${what}: ${maxRounds} rounds without a result`);
996
+ }
997
+ input = {
998
+ inputResponses: await answerInputRequests({ ...(result.inputRequests ?? {}) }, answerer),
999
+ ...(result.requestState !== undefined && { requestState: result.requestState }),
1000
+ };
1001
+ }
1002
+ }
546
1003
  /**
547
1004
  * Close the connection to the MCP server
548
1005
  */
@@ -552,6 +1009,7 @@ export class MCPClient {
552
1009
  }
553
1010
  this.closed = true;
554
1011
  try {
1012
+ this.dispatcher.detach();
555
1013
  await this.client.close();
556
1014
  }
557
1015
  finally {
@@ -559,6 +1017,50 @@ export class MCPClient {
559
1017
  }
560
1018
  }
561
1019
  }
1020
+ function negotiationMode(config) {
1021
+ const protocol = config.protocol ?? 'auto';
1022
+ if (config.transport === 'legacy-sse')
1023
+ return 'legacy';
1024
+ return protocol;
1025
+ }
1026
+ function isOAuthClientProvider(value) {
1027
+ return (typeof value === 'object' &&
1028
+ value !== null &&
1029
+ 'tokens' in value &&
1030
+ typeof value.tokens === 'function');
1031
+ }
1032
+ function isMCPOAuthProvider(value) {
1033
+ return value !== undefined && 'completeAuthorization' in value;
1034
+ }
1035
+ function toCallResult(result) {
1036
+ const content = toToolContent(Array.isArray(result.content) ? result.content : []);
1037
+ return {
1038
+ content,
1039
+ ...(result.structuredContent !== undefined && { structuredContent: result.structuredContent }),
1040
+ ...(result.isError === true && { isError: true }),
1041
+ ...('toolResult' in result && { toolResult: result.toolResult }),
1042
+ };
1043
+ }
1044
+ /** What `callTool` returns for a tool result */
1045
+ function toolResultValue(name, result) {
1046
+ const content = result.content;
1047
+ if (result.isError) {
1048
+ throw new MCPToolError(name, content);
1049
+ }
1050
+ if (content.length > 0 && hasMedia(content)) {
1051
+ return mcpContentToResult(content);
1052
+ }
1053
+ if (result.structuredContent !== undefined) {
1054
+ return result.structuredContent;
1055
+ }
1056
+ if (content.length > 0) {
1057
+ return mcpContentToResult(content);
1058
+ }
1059
+ if (result.toolResult !== undefined) {
1060
+ return result.toolResult;
1061
+ }
1062
+ return null;
1063
+ }
562
1064
  /** The content blocks of a tool result; a link to a resource becomes a line of text. */
563
1065
  function toToolContent(content) {
564
1066
  return content.map((block) => {