@cogitator-ai/mcp 19.8.2 → 19.9.0

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
@@ -3,14 +3,19 @@
3
3
  *
4
4
  * Exposes Cogitator tools as an MCP server that can be used by
5
5
  * other MCP clients (e.g., Claude Desktop, other AI assistants).
6
+ * Serves clients of protocol 2026-07-28 and of 2025-11-25.
6
7
  */
7
- import { randomUUID } from 'node:crypto';
8
- import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';
9
- import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
8
+ import { createHash, randomUUID } from 'node:crypto';
9
+ import { CLIENT_CAPABILITIES_META_KEY, McpServer, MissingRequiredClientCapabilityError, ResourceTemplate, SdkError, SdkErrorCode, createMcpHandler, inputRequired, isLegacyRequest, } from '@modelcontextprotocol/server';
10
+ import { serveStdio } from '@modelcontextprotocol/server/stdio';
11
+ import { NodeStreamableHTTPServerTransport, toNodeHandler, toWebRequest, } from '@modelcontextprotocol/node';
10
12
  import { Cogitator, withParsedArguments } from '@cogitator-ai/core';
11
- import { ElicitResultSchema, ErrorCode as McpErrorCode, McpError, } from '@modelcontextprotocol/sdk/types.js';
12
13
  import { mcpOutputSchema, resultToMCPContent } from '../adapter/tool-adapter.js';
13
- import { elicitApproval } from './approval.js';
14
+ import { approvalDecision, approvalForm, elicitApproval } from './approval.js';
15
+ import { CallExecution, } from './execution.js';
16
+ import { REJECTED_STATE, callDigest, callStateCodec, randomStateKey, } from './request-state.js';
17
+ import { keepableArgs, wireArgsSchema } from './tool-args.js';
18
+ import { DEFAULT_PROMOTE_AFTER_MS, ServerTasks, TASKS_EXTENSION, parseElicitResult } from './tasks.js';
14
19
  import { z } from 'zod';
15
20
  function toServerContent(item) {
16
21
  switch (item.type) {
@@ -50,8 +55,13 @@ const PERMISSIVE_INPUT_SCHEMA = z.looseObject({});
50
55
  const DEFAULT_ELICITATION_TIMEOUT_MS = 10 * 60 * 1000;
51
56
  /** The longest delay a Node timer keeps, a longer one fires at once. */
52
57
  const MAX_TIMER_DELAY_MS = 2_147_483_647;
53
- /** The JSON-RPC error code of a request the MCP SDK gave up waiting on. */
54
- const REQUEST_TIMEOUT_CODE = McpErrorCode.RequestTimeout;
58
+ const APPROVAL_KEY = 'approval';
59
+ const TaskIdParams = z.looseObject({ taskId: z.string().min(1) });
60
+ const TaskUpdateParams = z.looseObject({
61
+ taskId: z.string().min(1),
62
+ inputResponses: z.record(z.string(), z.unknown()).optional(),
63
+ });
64
+ const AnyResult = z.looseObject({});
55
65
  /**
56
66
  * MCP Server for exposing Cogitator tools
57
67
  *
@@ -74,7 +84,7 @@ const REQUEST_TIMEOUT_CODE = McpErrorCode.RequestTimeout;
74
84
  * ```
75
85
  */
76
86
  export class MCPServer {
77
- server;
87
+ stdio;
78
88
  config;
79
89
  tools = new Map();
80
90
  resources = new Map();
@@ -82,9 +92,23 @@ export class MCPServer {
82
92
  started = false;
83
93
  ownInvoker;
84
94
  httpServer;
95
+ httpHandler;
96
+ stateKey;
97
+ parked = new Map();
98
+ tasks;
85
99
  sessions = new Map();
86
100
  constructor(config) {
87
101
  this.config = config;
102
+ this.stateKey = config.requestStateKey ?? randomStateKey();
103
+ const keyBytes = typeof this.stateKey === 'string'
104
+ ? Buffer.byteLength(this.stateKey, 'utf8')
105
+ : this.stateKey.length;
106
+ if (keyBytes < 32)
107
+ throw new RangeError('requestStateKey must be at least 32 bytes long');
108
+ this.tasks =
109
+ config.tasks === false
110
+ ? undefined
111
+ : new ServerTasks(config.tasks ?? {}, (message) => this.log('error', message), () => this.elicitationTimeout());
88
112
  }
89
113
  /**
90
114
  * Register a single Cogitator tool
@@ -93,10 +117,6 @@ export class MCPServer {
93
117
  if (this.started) {
94
118
  throw new Error('Cannot register tools after server has started');
95
119
  }
96
- if (tool.outputSchema && !mcpOutputSchema(tool)) {
97
- console.warn(`[MCPServer] The outputSchema of tool "${tool.name}" is not a z.object() schema, which MCP ` +
98
- 'needs: it is not advertised and results go out as content only');
99
- }
100
120
  this.tools.set(tool.name, tool);
101
121
  }
102
122
  /**
@@ -195,40 +215,43 @@ export class MCPServer {
195
215
  * and prompt from the local maps onto it.
196
216
  *
197
217
  * The maps are the single source of truth: registration with the SDK is
198
- * deferred until start() (stdio) or until each incoming request (HTTP), so
218
+ * deferred until a connection (stdio) or each incoming request (HTTP), so
199
219
  * unregister* calls made before start() are fully honoured and concurrent
200
220
  * HTTP requests never share a single server/transport binding.
201
221
  */
202
- buildServer(caller) {
203
- const server = new McpServer({
204
- name: this.config.name,
205
- version: this.config.version,
222
+ buildServer(scope) {
223
+ const codec = callStateCodec(this.stateKey, scope.owner, 2 * this.elicitationTimeout());
224
+ const server = new McpServer({ name: this.config.name, version: this.config.version }, {
225
+ ...(this.tasks && { capabilities: { extensions: { [TASKS_EXTENSION]: {} } } }),
226
+ requestState: { verify: codec.verify },
227
+ inputRequired: { roundTimeoutMs: this.elicitationTimeout() },
206
228
  });
229
+ scope.server = server;
207
230
  for (const tool of this.tools.values()) {
208
- this.registerMCPTool(server, tool, caller);
231
+ this.registerMCPTool(server, tool, scope, codec.mint);
209
232
  }
210
233
  for (const resource of this.resources.values()) {
211
- this.registerMCPResource(server, resource, caller);
234
+ this.registerMCPResource(server, resource, scope.caller);
212
235
  }
213
236
  for (const prompt of this.prompts.values()) {
214
- this.registerMCPPrompt(server, prompt, caller);
237
+ this.registerMCPPrompt(server, prompt, scope.caller);
215
238
  }
239
+ if (this.tasks)
240
+ this.registerTaskHandlers(server, scope, this.tasks);
216
241
  return server;
217
242
  }
218
243
  /**
219
244
  * Register a tool with the MCP server
220
245
  */
221
- registerMCPTool(server, tool, caller) {
246
+ registerMCPTool(server, tool, scope, mint) {
222
247
  const outputSchema = mcpOutputSchema(tool);
223
248
  server.registerTool(tool.name, {
224
249
  ...(tool.title !== undefined && { title: tool.title }),
225
250
  description: tool.description,
226
- inputSchema: this.buildInputSchema(tool),
251
+ inputSchema: wireArgsSchema(this.buildInputSchema(tool)),
227
252
  ...(outputSchema && { outputSchema }),
228
253
  ...(tool.annotations && { annotations: { ...tool.annotations } }),
229
- }, async (args, extra) => {
230
- return this.executeTool(tool, args, extra, caller, outputSchema);
231
- });
254
+ }, async (args, ctx) => this.handleToolCall(tool, args, ctx, scope, mint, outputSchema));
232
255
  }
233
256
  /**
234
257
  * Resolve the Zod schema the SDK uses to advertise and validate tool input.
@@ -250,39 +273,236 @@ export class MCPServer {
250
273
  return this.ownInvoker;
251
274
  }
252
275
  /**
253
- * Run a tool call through the tool invoker, the way an agent run executes it: schema
254
- * validation, approval, guardrails, sandbox and `tool.timeout`. A call that needs approval is
255
- * asked from the person at the client through elicitation; one nobody can approve does not run
256
- * and comes back as an error that says so.
276
+ * One round of a tool call. A call that needs the person at the client (an approval,
277
+ * `context.elicit()`, `context.input.ask()`) ends its round with the questions and a signed
278
+ * state, and the client calls again with the answers: on protocol 2026-07-28 the client does,
279
+ * on earlier revisions the MCP SDK asks the client and calls again itself. A call still
280
+ * running after `tasks.promoteAfterMs` becomes a task, for clients that take tasks
257
281
  */
258
- async executeTool(tool, args, extra, caller, outputSchema) {
259
- const elicit = this.canElicit()
260
- ? (request) => this.elicit(extra, request)
282
+ async handleToolCall(tool, callArgs, ctx, scope, mint, outputSchema) {
283
+ let args = callArgs.parsed;
284
+ const capabilities = this.clientCapabilities(ctx, scope);
285
+ const owner = scope.owner;
286
+ const takesTasks = scope.era === 'modern' && capabilities?.extensions?.[TASKS_EXTENSION] !== undefined;
287
+ if (capabilities?.elicitation === undefined || scope.era === 'legacy') {
288
+ const mode = capabilities?.elicitation === undefined ? 'direct' : 'legacy';
289
+ const execution = this.startExecution(tool, args, owner, '', scope.caller, outputSchema, {
290
+ mode,
291
+ elicit: (request) => this.legacyElicit(ctx, request),
292
+ });
293
+ return this.drive(execution, ctx, scope, tool, args, mint, outputSchema, takesTasks, mode);
294
+ }
295
+ const digest = callDigest(tool.name, callArgs.wire);
296
+ const verified = ctx.mcpReq.requestState();
297
+ const state = verified !== REJECTED_STATE && verified?.tool === tool.name && verified.digest === digest
298
+ ? verified
261
299
  : undefined;
300
+ if (state && 'args' in state && state.args !== undefined)
301
+ args = state.args;
302
+ const responses = elicitResults(ctx.mcpReq.inputResponses);
303
+ if (state?.kind === 'parked') {
304
+ const execution = this.parked.get(state.id);
305
+ const question = execution?.question;
306
+ if (execution?.owner !== owner || !question || execution.finished) {
307
+ return this.toolError(tool, 'The question of this call expired or was answered already: call the tool again');
308
+ }
309
+ const answered = Object.entries(responses).filter(([key, answer]) => execution.respond(key, answer));
310
+ if (answered.length === 0)
311
+ return this.askInRound(execution, question, ctx, mint);
312
+ this.parked.delete(execution.id);
313
+ return this.drive(execution, ctx, scope, tool, args, mint, outputSchema, takesTasks, 'task');
314
+ }
315
+ let approvals = state?.approvals ?? [];
316
+ let input;
317
+ if (state?.kind === 'approval') {
318
+ const reply = responses[state.key];
319
+ if (reply) {
320
+ const decision = approvalDecision(reply);
321
+ approvals = [
322
+ ...approvals.filter((granted) => granted.digest !== state.pending),
323
+ decision.approved
324
+ ? { digest: state.pending, approved: true }
325
+ : {
326
+ digest: state.pending,
327
+ approved: false,
328
+ ...(decision.reason !== undefined && { reason: decision.reason }),
329
+ },
330
+ ];
331
+ }
332
+ if (state.resume) {
333
+ input = { responses: elicitResults(state.resume.responses), state: state.resume.data };
334
+ }
335
+ }
336
+ else if (state?.kind === 'tool') {
337
+ input = { responses, state: state.data };
338
+ }
339
+ const execution = this.startExecution(tool, args, owner, digest, scope.caller, outputSchema, {
340
+ mode: 'round',
341
+ approvals,
342
+ input: {
343
+ responses: input?.responses ?? {},
344
+ state: input?.state,
345
+ stateRejected: verified === REJECTED_STATE || (verified !== undefined && state === undefined),
346
+ },
347
+ });
348
+ return this.drive(execution, ctx, scope, tool, args, mint, outputSchema, takesTasks, 'task');
349
+ }
350
+ /**
351
+ * What the round of `execution` answers: its result, its questions with the state of the call,
352
+ * or the task it became
353
+ */
354
+ async drive(execution, ctx, scope, tool, args, mint, outputSchema, takesTasks, taskMode) {
355
+ const tasks = takesTasks ? this.tasks : undefined;
356
+ let kept = false;
357
+ const onAbort = () => {
358
+ if (!kept)
359
+ execution.cancel(ctx.mcpReq.signal.reason);
360
+ };
361
+ ctx.mcpReq.signal.addEventListener('abort', onAbort, { once: true });
262
362
  try {
363
+ const step = tasks ? await execution.nextWithin(this.promoteAfter()) : await execution.next();
364
+ if (step === undefined && tasks) {
365
+ kept = true;
366
+ this.parked.delete(execution.id);
367
+ const task = await tasks.start(execution.owner, execution, (resume) => this.startExecution(tool, args, execution.owner, execution.digest, scope.caller, outputSchema, {
368
+ mode: taskMode === 'legacy' ? 'direct' : taskMode,
369
+ approvals: execution.carry.approvals,
370
+ ...(resume.input && { input: { ...resume.input, stateRejected: false } }),
371
+ }));
372
+ return taskResult(task);
373
+ }
374
+ if (step === undefined)
375
+ throw new Error('A tool call ended without a result');
376
+ if (step.kind !== 'ask')
377
+ this.parked.delete(execution.id);
378
+ return await this.roundAnswer(step, execution, ctx, mint, () => {
379
+ kept = true;
380
+ });
381
+ }
382
+ catch (error) {
383
+ return this.toolError(tool, errorMessageOf(error));
384
+ }
385
+ finally {
386
+ ctx.mcpReq.signal.removeEventListener('abort', onAbort);
387
+ }
388
+ }
389
+ async roundAnswer(step, execution, ctx, mint, keep) {
390
+ const base = {
391
+ tool: execution.tool,
392
+ digest: execution.digest,
393
+ ...(execution.carry.args !== undefined && { args: execution.carry.args }),
394
+ ...(execution.carry.approvals.length > 0 && { approvals: execution.carry.approvals }),
395
+ };
396
+ switch (step.kind) {
397
+ case 'done':
398
+ if (step.pendingApproval && execution.digest !== '') {
399
+ const carried = execution.carry.input;
400
+ const resumable = carried && (Object.keys(carried.responses).length > 0 || carried.state !== undefined);
401
+ return inputRequired({
402
+ inputRequests: { [APPROVAL_KEY]: elicitInput(approvalForm(step.pendingApproval)) },
403
+ requestState: await mint({
404
+ kind: 'approval',
405
+ ...base,
406
+ key: APPROVAL_KEY,
407
+ pending: approvalDigest(step.pendingApproval),
408
+ ...(resumable && {
409
+ resume: { responses: { ...carried.responses }, data: carried.state },
410
+ }),
411
+ }, ctx),
412
+ });
413
+ }
414
+ return step.result;
415
+ case 'ask':
416
+ keep();
417
+ return this.askInRound(execution, step, ctx, mint);
418
+ case 'input':
419
+ return inputRequired({
420
+ inputRequests: Object.fromEntries(Object.entries(step.requests).map(([key, request]) => [key, elicitInput(request)])),
421
+ requestState: await mint({ kind: 'tool', ...base, data: step.state }, ctx),
422
+ });
423
+ }
424
+ }
425
+ /** Ends the round with the question `execution` waits on, keeping it waiting for the answer */
426
+ async askInRound(execution, question, ctx, mint) {
427
+ this.parked.set(execution.id, execution);
428
+ execution.park(this.elicitationTimeout(), () => {
429
+ this.log('info', `Nobody answered the elicitation within ${this.elicitationTimeout()} ms`);
430
+ this.parked.delete(execution.id);
431
+ });
432
+ return inputRequired({
433
+ inputRequests: { [question.key]: elicitInput(question.request) },
434
+ requestState: await mint({ kind: 'parked', tool: execution.tool, digest: execution.digest, id: execution.id }, ctx),
435
+ });
436
+ }
437
+ /**
438
+ * A run of a tool call through the tool invoker, the way an agent run executes it: schema
439
+ * validation, approval, guardrails, sandbox and `tool.timeout`. In `round` mode an approval the
440
+ * round has no decision for ends the run, to be asked; in `task` mode it is asked in place; in
441
+ * `direct` mode nobody can approve and the call does not run
442
+ */
443
+ startExecution(tool, args, owner, digest, caller, outputSchema, run) {
444
+ const kept = keepableArgs(args);
445
+ const carry = {
446
+ approvals: [...(run.approvals ?? [])],
447
+ ...(kept !== undefined && { args: kept }),
448
+ ...(run.input && { input: { responses: run.input.responses, state: run.input.state } }),
449
+ };
450
+ return new CallExecution(owner, tool.name, digest, carry, async (askers) => {
451
+ let pendingApproval;
452
+ const elicit = run.mode === 'direct' ? undefined : run.mode === 'legacy' ? run.elicit : askers.elicit;
453
+ const input = run.input
454
+ ? askers.input(run.input.responses, run.input.state, run.input.stateRejected)
455
+ : undefined;
456
+ const onApproval = async (request) => {
457
+ const granted = carry.approvals.find((entry) => entry.digest === approvalDigest(request));
458
+ if (granted) {
459
+ return granted.approved
460
+ ? { approved: true }
461
+ : { approved: false, ...(granted.reason !== undefined && { reason: granted.reason }) };
462
+ }
463
+ if (run.mode === 'task' || run.mode === 'legacy')
464
+ return elicitApproval(elicit, request);
465
+ if (run.mode === 'round')
466
+ pendingApproval = request;
467
+ return undefined;
468
+ };
263
469
  const result = await this.invoker().invokeTool(withParsedArguments(tool), args ?? {}, {
264
470
  runId: `mcp_${randomUUID()}`,
265
471
  agentId: 'mcp-server',
266
- signal: extra.signal,
472
+ signal: askers.signal,
267
473
  ...(caller?.userId !== undefined && { userId: caller.userId }),
268
- ...(elicit && { context: { elicit } }),
269
- onApproval: (request) => elicitApproval(elicit, request),
474
+ ...((elicit || input) && {
475
+ context: { ...(elicit && { elicit }), ...(input && { input }) },
476
+ }),
477
+ onApproval,
270
478
  });
479
+ const asked = askers.asked();
480
+ if (asked)
481
+ return { kind: 'input', requests: asked.requests, state: asked.state };
271
482
  if (result.pendingApproval) {
272
- return this.toolError(tool, `Tool "${tool.name}" needs the user's approval, and nobody could approve this call: ` +
273
- 'the client cannot answer MCP elicitation requests (or the server has no sessions). ' +
274
- 'Use a client that supports elicitation, or decide approvals on the server with ' +
275
- 'guardrails.onToolApproval.');
483
+ return {
484
+ kind: 'done',
485
+ result: this.toolError(tool, `Tool "${tool.name}" needs the user's approval, and nobody could approve this call: ` +
486
+ 'the client cannot answer MCP elicitation requests (or the server has no sessions). ' +
487
+ 'Use a client that supports elicitation, or decide approvals on the server with ' +
488
+ 'guardrails.onToolApproval.'),
489
+ ...(pendingApproval && { pendingApproval }),
490
+ };
276
491
  }
277
- if (result.error !== undefined)
278
- return this.toolError(tool, result.error);
279
- if (outputSchema)
280
- return await this.structuredResult(tool, outputSchema, result.result);
281
- return { content: resultToMCPContent(result.result).map(toServerContent) };
282
- }
283
- catch (error) {
284
- return this.toolError(tool, errorMessageOf(error));
285
- }
492
+ if (result.error !== undefined) {
493
+ return { kind: 'done', result: this.toolError(tool, result.error) };
494
+ }
495
+ if (outputSchema) {
496
+ return {
497
+ kind: 'done',
498
+ result: await this.structuredResult(tool, outputSchema, result.result),
499
+ };
500
+ }
501
+ return {
502
+ kind: 'done',
503
+ result: { content: resultToMCPContent(result.result).map(toServerContent) },
504
+ };
505
+ });
286
506
  }
287
507
  /**
288
508
  * The result of a tool with an output schema: `structuredContent`, with its JSON as text for
@@ -310,6 +530,66 @@ export class MCPServer {
310
530
  this.log('error', `Tool ${tool.name} error: ${message}`);
311
531
  return { content: [{ type: 'text', text: `Error: ${message}` }], isError: true };
312
532
  }
533
+ /**
534
+ * Ask a client of a revision before 2026-07-28 through MCP elicitation, a request tied to the
535
+ * tool call, for as long as `elicitationTimeoutMs` allows (an answer that does not come in time
536
+ * counts as dismissed). `undefined` when the client cannot answer.
537
+ */
538
+ async legacyElicit(ctx, request) {
539
+ const timeout = this.elicitationTimeout();
540
+ try {
541
+ const result = await ctx.mcpReq.send({
542
+ method: 'elicitation/create',
543
+ params: { mode: 'form', message: request.message, requestedSchema: request.schema },
544
+ }, { timeout, signal: ctx.mcpReq.signal });
545
+ return result.action === 'accept'
546
+ ? { action: 'accept', content: { ...(result.content ?? {}) } }
547
+ : { action: result.action };
548
+ }
549
+ catch (error) {
550
+ if (error instanceof SdkError && error.code === SdkErrorCode.RequestTimeout) {
551
+ this.log('info', `Nobody answered the elicitation within ${timeout} ms`);
552
+ return { action: 'cancel' };
553
+ }
554
+ this.log('info', `Elicitation unavailable: ${errorMessageOf(error)}`);
555
+ return undefined;
556
+ }
557
+ }
558
+ /** The capabilities of the client of this request: its own on 2026-07-28, the handshake's before */
559
+ clientCapabilities(ctx, scope) {
560
+ if (scope.era === 'modern') {
561
+ const envelope = ctx.mcpReq.envelope;
562
+ const declared = envelope?.[CLIENT_CAPABILITIES_META_KEY];
563
+ return isRecord(declared) ? declared : undefined;
564
+ }
565
+ if (!scope.legacyCanAsk)
566
+ return undefined;
567
+ return scope.server?.server.getClientCapabilities();
568
+ }
569
+ registerTaskHandlers(server, scope, tasks) {
570
+ const owner = scope.owner;
571
+ const requireTasks = (ctx) => {
572
+ if (this.clientCapabilities(ctx, scope)?.extensions?.[TASKS_EXTENSION] === undefined) {
573
+ throw new MissingRequiredClientCapabilityError({
574
+ requiredCapabilities: { extensions: { [TASKS_EXTENSION]: {} } },
575
+ });
576
+ }
577
+ };
578
+ server.server.setRequestHandler('tasks/get', { params: TaskIdParams, result: AnyResult }, async (params, ctx) => {
579
+ requireTasks(ctx);
580
+ return { ...(await tasks.get(params.taskId, owner)) };
581
+ });
582
+ server.server.setRequestHandler('tasks/update', { params: TaskUpdateParams, result: AnyResult }, async (params, ctx) => {
583
+ requireTasks(ctx);
584
+ await tasks.update(params.taskId, owner, params.inputResponses ?? ctx.mcpReq.inputResponses ?? {});
585
+ return {};
586
+ });
587
+ server.server.setRequestHandler('tasks/cancel', { params: TaskIdParams, result: AnyResult }, async (params, ctx) => {
588
+ requireTasks(ctx);
589
+ await tasks.cancel(params.taskId, owner);
590
+ return {};
591
+ });
592
+ }
313
593
  /**
314
594
  * Write a diagnostic line to stderr when logging is enabled.
315
595
  *
@@ -352,11 +632,12 @@ export class MCPServer {
352
632
  throw error;
353
633
  }
354
634
  };
635
+ const metadata = {
636
+ ...(config.description !== undefined && { description: config.description }),
637
+ ...(config.mimeType !== undefined && { mimeType: config.mimeType }),
638
+ };
355
639
  if (isTemplate) {
356
- server.registerResource(config.name, new ResourceTemplate(config.uri, { list: undefined }), {
357
- description: config.description,
358
- mimeType: config.mimeType,
359
- }, async (uri, variables) => {
640
+ server.registerResource(config.name, new ResourceTemplate(config.uri, { list: undefined }), metadata, async (uri, variables) => {
360
641
  const params = {};
361
642
  for (const [key, value] of Object.entries(variables)) {
362
643
  params[key] = Array.isArray(value) ? value.join(',') : value;
@@ -365,10 +646,7 @@ export class MCPServer {
365
646
  });
366
647
  }
367
648
  else {
368
- server.registerResource(config.name, config.uri, {
369
- description: config.description,
370
- mimeType: config.mimeType,
371
- }, async (uri) => {
649
+ server.registerResource(config.name, config.uri, metadata, async (uri) => {
372
650
  return { contents: formatContents(await readResource({}), uri.href) };
373
651
  });
374
652
  }
@@ -387,7 +665,7 @@ export class MCPServer {
387
665
  throw error;
388
666
  }
389
667
  return {
390
- description: result.description,
668
+ ...(result.description !== undefined && { description: result.description }),
391
669
  messages: result.messages.map((m) => ({
392
670
  role: m.role,
393
671
  content: typeof m.content === 'string'
@@ -396,18 +674,21 @@ export class MCPServer {
396
674
  })),
397
675
  };
398
676
  };
399
- const metadata = { title: config.title || config.name, description: config.description };
677
+ const metadata = {
678
+ title: config.title || config.name,
679
+ ...(config.description !== undefined && { description: config.description }),
680
+ };
400
681
  const promptArgs = config.arguments ?? [];
401
682
  if (promptArgs.length === 0) {
402
683
  server.registerPrompt(config.name, metadata, async () => render({}));
403
684
  return;
404
685
  }
405
- const argsSchema = {};
686
+ const argsShape = {};
406
687
  for (const arg of promptArgs) {
407
688
  const base = arg.description ? z.string().describe(arg.description) : z.string();
408
- argsSchema[arg.name] = arg.required ? base : base.optional();
689
+ argsShape[arg.name] = arg.required ? base : base.optional();
409
690
  }
410
- server.registerPrompt(config.name, { ...metadata, argsSchema }, async (args) => {
691
+ server.registerPrompt(config.name, { ...metadata, argsSchema: z.object(argsShape) }, async (args) => {
411
692
  const stringArgs = {};
412
693
  for (const [key, value] of Object.entries(args ?? {})) {
413
694
  if (typeof value === 'string') {
@@ -430,9 +711,10 @@ export class MCPServer {
430
711
  this.log('info', `Registered prompts: ${this.getRegisteredPrompts().join(', ') || '(none)'}`);
431
712
  switch (this.config.transport) {
432
713
  case 'stdio': {
433
- this.server = this.buildServer();
434
- const transport = new StdioServerTransport();
435
- await this.server.connect(transport);
714
+ this.stdio = serveStdio((ctx) => this.buildServer({ era: ctx.era, caller: undefined, owner: '', legacyCanAsk: true }), {
715
+ legacy: this.config.legacyClients === false ? 'reject' : 'serve',
716
+ onerror: (error) => this.log('error', `stdio error: ${error.message}`),
717
+ });
436
718
  break;
437
719
  }
438
720
  case 'http':
@@ -441,46 +723,20 @@ export class MCPServer {
441
723
  break;
442
724
  }
443
725
  default:
444
- throw new Error(`Unknown transport: ${this.config.transport}`);
726
+ throw new Error(`Unknown transport: ${String(this.config.transport)}`);
445
727
  }
446
728
  this.started = true;
447
729
  this.log('info', `Server started on ${this.config.transport} transport`);
448
730
  }
449
- /** Elicitation needs the client's reply to reach this server: stdio, or HTTP with sessions. */
450
- canElicit() {
451
- return this.config.transport === 'stdio' || this.config.sessions === true;
452
- }
453
- /**
454
- * Ask the client's user through MCP elicitation, tied to the tool call so it
455
- * works on stateless HTTP too, for as long as `elicitationTimeoutMs` allows (an
456
- * answer that does not come in time counts as dismissed). `undefined` when the
457
- * client cannot answer.
458
- */
459
- async elicit(extra, request) {
460
- const timeout = this.elicitationTimeout();
461
- try {
462
- const result = await extra.sendRequest({
463
- method: 'elicitation/create',
464
- params: { mode: 'form', message: request.message, requestedSchema: request.schema },
465
- }, ElicitResultSchema, { timeout, signal: extra.signal });
466
- return result.action === 'accept'
467
- ? { action: 'accept', content: result.content ?? {} }
468
- : { action: result.action };
469
- }
470
- catch (error) {
471
- if (error instanceof McpError && error.code === REQUEST_TIMEOUT_CODE) {
472
- this.log('info', `Nobody answered the elicitation within ${timeout} ms`);
473
- return { action: 'cancel' };
474
- }
475
- this.log('info', `Elicitation unavailable: ${errorMessageOf(error)}`);
476
- return undefined;
477
- }
478
- }
479
731
  /** The ms an elicitation waits: `elicitationTimeoutMs`, `0` as the longest timer Node keeps. */
480
732
  elicitationTimeout() {
481
733
  const configured = this.config.elicitationTimeoutMs ?? DEFAULT_ELICITATION_TIMEOUT_MS;
482
734
  return configured > 0 ? Math.min(configured, MAX_TIMER_DELAY_MS) : MAX_TIMER_DELAY_MS;
483
735
  }
736
+ promoteAfter() {
737
+ const tasks = this.config.tasks;
738
+ return ((typeof tasks === 'object' ? tasks.promoteAfterMs : undefined) ?? DEFAULT_PROMOTE_AFTER_MS);
739
+ }
484
740
  /**
485
741
  * The caller of an HTTP request per `config.auth`: `undefined` when the
486
742
  * server has no `auth`, `null` when the request is refused.
@@ -497,11 +753,11 @@ export class MCPServer {
497
753
  }
498
754
  }
499
755
  /**
500
- * A request in session mode: a request without a session id starts a
501
- * session (an `initialize`), the others go to their session's transport.
502
- * A session belongs to the caller that started it.
756
+ * A request of a 2025-era client in session mode: a request without a session id starts a
757
+ * session (an `initialize`), the others go to their session's transport. A session belongs to
758
+ * the caller that started it.
503
759
  */
504
- async handleSessionRequest(req, res, body, caller, Transport) {
760
+ async handleSessionRequest(req, res, body, caller, owner) {
505
761
  const header = req.headers['mcp-session-id'];
506
762
  const sessionId = Array.isArray(header) ? header[0] : header;
507
763
  if (sessionId) {
@@ -510,18 +766,18 @@ export class MCPServer {
510
766
  writeJsonRpcError(res, 404, -32001, 'Session not found');
511
767
  return;
512
768
  }
513
- if (session.caller?.userId !== caller?.userId) {
769
+ if (session.owner !== owner) {
514
770
  writeJsonRpcError(res, 403, -32001, 'The session belongs to another caller');
515
771
  return;
516
772
  }
517
773
  await session.transport.handleRequest(req, res, body);
518
774
  return;
519
775
  }
520
- const server = this.buildServer(caller);
521
- const transport = new Transport({
776
+ const server = this.buildServer({ era: 'legacy', caller, owner, legacyCanAsk: true });
777
+ const transport = new NodeStreamableHTTPServerTransport({
522
778
  sessionIdGenerator: () => randomUUID(),
523
779
  onsessioninitialized: (id) => {
524
- this.sessions.set(id, { transport, server, caller });
780
+ this.sessions.set(id, { transport, server, caller, owner });
525
781
  },
526
782
  });
527
783
  transport.onclose = () => {
@@ -532,27 +788,71 @@ export class MCPServer {
532
788
  await server.connect(transport);
533
789
  await transport.handleRequest(req, res, body);
534
790
  }
791
+ /** A request of a 2025-era client without sessions: served on its own */
792
+ async handleStatelessLegacyRequest(req, res, body, caller, owner) {
793
+ const server = this.buildServer({ era: 'legacy', caller, owner, legacyCanAsk: false });
794
+ const transport = new NodeStreamableHTTPServerTransport({ sessionIdGenerator: undefined });
795
+ res.on('close', () => {
796
+ transport.close().catch(() => { });
797
+ server.close().catch(() => { });
798
+ });
799
+ await server.connect(transport);
800
+ await transport.handleRequest(req, res, body);
801
+ }
802
+ /** The origins browsers may call the server from, undefined for any */
803
+ allowedOrigins() {
804
+ if (this.config.allowedOrigins)
805
+ return this.config.allowedOrigins;
806
+ const corsOrigin = this.config.corsOrigin ?? '*';
807
+ return corsOrigin === '*' ? undefined : [corsOrigin];
808
+ }
535
809
  /**
536
810
  * Start HTTP server for MCP
537
811
  */
538
812
  async startHttpServer() {
539
813
  const { createServer } = await import('node:http');
540
- const { StreamableHTTPServerTransport } = await import('@modelcontextprotocol/sdk/server/streamableHttp.js');
541
814
  const port = this.config.port ?? 3000;
542
815
  const host = this.config.host ?? 'localhost';
543
816
  const maxBodySize = this.config.maxBodySize ?? 10 * 1024 * 1024;
544
817
  const corsOrigin = this.config.corsOrigin ?? '*';
818
+ const allowedOrigins = this.allowedOrigins();
819
+ const modern = createMcpHandler((ctx) => this.buildServer({
820
+ era: 'modern',
821
+ caller: callerOf(ctx.authInfo),
822
+ owner: ownerOfAuthInfo(ctx.authInfo),
823
+ legacyCanAsk: false,
824
+ }), {
825
+ legacy: 'reject',
826
+ maxRequestBodySize: maxBodySize,
827
+ onerror: (error) => this.log('error', `HTTP error: ${error.message}`),
828
+ });
829
+ this.httpHandler = modern;
830
+ const serveModern = toNodeHandler(modern, {
831
+ maxRequestBodySize: maxBodySize,
832
+ onerror: (error) => this.log('error', `HTTP error: ${error.message}`),
833
+ });
545
834
  this.httpServer = createServer(async (req, res) => {
835
+ const origin = req.headers.origin;
546
836
  res.setHeader('Access-Control-Allow-Origin', corsOrigin);
547
837
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS');
548
- res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, Mcp-Session-Id');
549
- res.setHeader('Access-Control-Expose-Headers', 'Mcp-Session-Id');
838
+ res.setHeader('Access-Control-Allow-Headers', allowedHeaders(req));
839
+ res.setHeader('Access-Control-Expose-Headers', 'Mcp-Session-Id, MCP-Protocol-Version');
840
+ if (origin !== undefined && !originAllowed(origin, allowedOrigins, host)) {
841
+ writeJsonRpcError(res, 403, -32001, 'Forbidden: this origin may not call the server');
842
+ return;
843
+ }
550
844
  if (req.method === 'OPTIONS') {
551
845
  res.writeHead(204);
552
846
  res.end();
553
847
  return;
554
848
  }
555
849
  const pathname = new URL(req.url ?? '/', 'http://localhost').pathname;
850
+ const protectedResource = this.config.protectedResource;
851
+ if (protectedResource && pathname.startsWith(PRM_PATH) && req.method === 'GET') {
852
+ res.writeHead(200, { 'Content-Type': 'application/json' });
853
+ res.end(JSON.stringify(protectedResourceMetadata(protectedResource, req)));
854
+ return;
855
+ }
556
856
  if (pathname !== '/mcp') {
557
857
  res.writeHead(404);
558
858
  res.end('Not Found');
@@ -560,7 +860,12 @@ export class MCPServer {
560
860
  }
561
861
  const caller = await this.authenticate(req);
562
862
  if (caller === null) {
563
- res.writeHead(401, { 'Content-Type': 'application/json', 'WWW-Authenticate': 'Bearer' });
863
+ res.writeHead(401, {
864
+ 'Content-Type': 'application/json',
865
+ 'WWW-Authenticate': protectedResource
866
+ ? `Bearer resource_metadata="${requestOrigin(req)}${PRM_PATH}/mcp"`
867
+ : 'Bearer',
868
+ });
564
869
  res.end(JSON.stringify({
565
870
  jsonrpc: '2.0',
566
871
  error: { code: -32001, message: 'Unauthorized' },
@@ -574,21 +879,26 @@ export class MCPServer {
574
879
  res.end('Method Not Allowed');
575
880
  return;
576
881
  }
882
+ const owner = ownerOf(caller, req, this.config.auth !== undefined);
883
+ if (owner === undefined) {
884
+ writeJsonRpcError(res, 401, -32001, 'Unauthorized: auth gave no userId and the request has no credential to tell callers apart');
885
+ return;
886
+ }
577
887
  const body = req.method === 'POST' ? await readJsonBody(req, res, maxBodySize) : undefined;
578
888
  if (body === null)
579
889
  return;
890
+ req.auth = authInfoOf(caller, owner);
891
+ const legacy = this.config.legacyClients !== false &&
892
+ (await isLegacyRequest(await toWebRequest(req, body), body));
893
+ if (!legacy) {
894
+ await serveModern(req, res, body);
895
+ return;
896
+ }
580
897
  if (this.config.sessions) {
581
- await this.handleSessionRequest(req, res, body, caller, StreamableHTTPServerTransport);
898
+ await this.handleSessionRequest(req, res, body, caller, owner);
582
899
  return;
583
900
  }
584
- const server = this.buildServer(caller);
585
- const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
586
- res.on('close', () => {
587
- transport.close().catch(() => { });
588
- server.close().catch(() => { });
589
- });
590
- await server.connect(transport);
591
- await transport.handleRequest(req, res, body);
901
+ await this.handleStatelessLegacyRequest(req, res, body, caller, owner);
592
902
  }
593
903
  catch (error) {
594
904
  this.log('error', `HTTP request error: ${errorMessageOf(error)}`);
@@ -610,6 +920,8 @@ export class MCPServer {
610
920
  }
611
921
  catch (error) {
612
922
  this.httpServer = undefined;
923
+ await modern.close().catch(() => { });
924
+ this.httpHandler = undefined;
613
925
  throw error;
614
926
  }
615
927
  this.log('info', `HTTP server listening on http://${host}:${this.getPort() ?? port}/mcp`);
@@ -633,6 +945,13 @@ export class MCPServer {
633
945
  const sessions = [...this.sessions.values()];
634
946
  this.sessions.clear();
635
947
  await Promise.all(sessions.map(({ transport }) => transport.close().catch(() => { })));
948
+ for (const execution of this.parked.values())
949
+ execution.cancel(new Error('The server stopped'));
950
+ this.parked.clear();
951
+ this.tasks?.closeAll();
952
+ const handler = this.httpHandler;
953
+ this.httpHandler = undefined;
954
+ await handler?.close().catch(() => { });
636
955
  const httpServer = this.httpServer;
637
956
  if (httpServer) {
638
957
  this.httpServer = undefined;
@@ -643,13 +962,13 @@ export class MCPServer {
643
962
  }
644
963
  }
645
964
  finally {
646
- const server = this.server;
647
- this.server = undefined;
965
+ const stdio = this.stdio;
966
+ this.stdio = undefined;
648
967
  this.started = false;
649
968
  const own = this.ownInvoker;
650
969
  this.ownInvoker = undefined;
651
- if (server) {
652
- await server.close();
970
+ if (stdio) {
971
+ await stdio.close();
653
972
  }
654
973
  await own?.close();
655
974
  }
@@ -680,6 +999,118 @@ export async function serveMCPTools(tools, config) {
680
999
  await server.start();
681
1000
  return server;
682
1001
  }
1002
+ /** A task as the result of `tools/call` (`resultType: "task"`) */
1003
+ function taskResult(task) {
1004
+ return { content: [], ...task, resultType: 'task' };
1005
+ }
1006
+ /** The digest an approval is kept by: the tool and arguments of the request it decides */
1007
+ function approvalDigest(request) {
1008
+ return callDigest(request.toolName, request.arguments);
1009
+ }
1010
+ /** An elicitation form as an input request of `InputRequiredResult` */
1011
+ function elicitInput(request) {
1012
+ return inputRequired.elicit({
1013
+ message: request.message,
1014
+ requestedSchema: request.schema,
1015
+ });
1016
+ }
1017
+ /** The answers of a round, the entries that are elicitation results */
1018
+ function elicitResults(responses) {
1019
+ const results = {};
1020
+ for (const [key, value] of Object.entries(responses ?? {})) {
1021
+ const parsed = parseElicitResult(value);
1022
+ if (parsed)
1023
+ results[key] = parsed;
1024
+ }
1025
+ return results;
1026
+ }
1027
+ /**
1028
+ * Whom the tasks, waiting runs and round states of a request belong to: everyone alike on a
1029
+ * server without `auth`, else the caller's `userId`, else the credential the request carries (a
1030
+ * digest of its `Authorization` or `Cookie` header). Undefined for a caller `auth` let in that
1031
+ * nothing tells apart from other callers, a request the server refuses
1032
+ */
1033
+ function ownerOf(caller, req, hasAuth) {
1034
+ if (!hasAuth)
1035
+ return '';
1036
+ if (caller?.userId !== undefined)
1037
+ return `user:${caller.userId}`;
1038
+ const credential = req.headers.authorization ?? req.headers.cookie;
1039
+ if (!credential)
1040
+ return undefined;
1041
+ return `credential:${createHash('sha256').update(credential).digest('base64url')}`;
1042
+ }
1043
+ /** The `AuthInfo` the MCP SDK carries for a caller to the server it builds for the request */
1044
+ function authInfoOf(caller, owner) {
1045
+ return {
1046
+ token: '',
1047
+ clientId: caller?.userId ?? 'anonymous',
1048
+ scopes: caller?.scopes ?? [],
1049
+ extra: { ...(caller && { caller }), owner },
1050
+ };
1051
+ }
1052
+ function callerOf(authInfo) {
1053
+ const caller = authInfo?.extra?.caller;
1054
+ return isRecord(caller) ? caller : undefined;
1055
+ }
1056
+ function ownerOfAuthInfo(authInfo) {
1057
+ const owner = authInfo?.extra?.owner;
1058
+ return typeof owner === 'string' ? owner : '';
1059
+ }
1060
+ const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]', '::1']);
1061
+ function isLoopbackHost(host) {
1062
+ return LOOPBACK_HOSTS.has(host) || host.startsWith('127.') || host.endsWith('.localhost');
1063
+ }
1064
+ /**
1065
+ * Whether a browser of `origin` may call the server: one of `allowed` when it is set, else a
1066
+ * loopback origin when the server listens on a loopback host (so a web page cannot reach a local
1067
+ * server through DNS rebinding), else any origin
1068
+ */
1069
+ function originAllowed(origin, allowed, host) {
1070
+ if (allowed)
1071
+ return allowed.includes(origin);
1072
+ if (!isLoopbackHost(host))
1073
+ return true;
1074
+ try {
1075
+ return isLoopbackHost(new URL(origin).hostname);
1076
+ }
1077
+ catch {
1078
+ return false;
1079
+ }
1080
+ }
1081
+ const PRM_PATH = '/.well-known/oauth-protected-resource';
1082
+ /** The origin a request reached the server at, from its `Host` header */
1083
+ function requestOrigin(req) {
1084
+ const forwarded = req.headers['x-forwarded-proto'];
1085
+ const proto = (Array.isArray(forwarded) ? forwarded[0] : forwarded) ?? 'http';
1086
+ return `${proto}://${req.headers.host ?? 'localhost'}`;
1087
+ }
1088
+ /** The OAuth Protected Resource Metadata of the server (RFC 9728) */
1089
+ function protectedResourceMetadata(config, req) {
1090
+ return {
1091
+ resource: config.resource ?? `${requestOrigin(req)}/mcp`,
1092
+ authorization_servers: [...config.authorizationServers],
1093
+ bearer_methods_supported: ['header'],
1094
+ ...(config.scopesSupported && { scopes_supported: [...config.scopesSupported] }),
1095
+ ...(config.resourceName && { resource_name: config.resourceName }),
1096
+ };
1097
+ }
1098
+ const STANDARD_HEADERS = 'Content-Type, Authorization, Mcp-Session-Id, MCP-Protocol-Version, Mcp-Method, Mcp-Name, Last-Event-ID';
1099
+ /**
1100
+ * The headers a browser may send: the standard MCP ones and whatever the preflight asks for,
1101
+ * since the `Mcp-Param-*` headers of tool arguments are named by the tools
1102
+ */
1103
+ function allowedHeaders(req) {
1104
+ const requested = req.headers['access-control-request-headers'];
1105
+ const asked = (Array.isArray(requested) ? requested.join(',') : (requested ?? ''))
1106
+ .split(',')
1107
+ .map((name) => name.trim())
1108
+ .filter((name) => /^mcp-param-[!#$%&'*+.^_`|~0-9a-z-]+$/i.test(name));
1109
+ return asked.length > 0 ? `${STANDARD_HEADERS}, ${asked.join(', ')}` : STANDARD_HEADERS;
1110
+ }
1111
+ function isRecord(value) {
1112
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
1113
+ }
683
1114
  /** The JSON body of a POST, or `null` when the request was answered (too large, invalid JSON). */
684
1115
  async function readJsonBody(req, res, maxBodySize) {
685
1116
  const chunks = [];