typespec-http-mcp 0.8.1 → 0.10.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.
@@ -1,3 +1,5 @@
1
+ import { MissingRequiredClientCapabilityError, ProtocolError, ProtocolErrorCode, } from "@modelcontextprotocol/server";
2
+ import { z } from "zod";
1
3
  /**
2
4
  * The arm that answers for a status, in the document's own precedence order.
3
5
  *
@@ -347,3 +349,176 @@ export async function toolResult(declared, operationId, result) {
347
349
  }
348
350
  return toolAnswer;
349
351
  }
352
+ /**
353
+ * The result McpServer answers when a tool callback throws: the message as text, marked as an error.
354
+ *
355
+ * Exported so the work behind a task settles a thrown error exactly as the blocking call would have
356
+ * answered it. The Tasks extension requires a tool error to complete the task with that result,
357
+ * and reserves `failed` for a protocol error.
358
+ */
359
+ export function toolError(error) {
360
+ return {
361
+ content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }],
362
+ isError: true,
363
+ };
364
+ }
365
+ /**
366
+ * Refuses a task policy on a server no {@link TasksExtension} is attached to. A tool there would
367
+ * answer with a task the server does not advertise and nobody can poll: `tasks/get` would be an
368
+ * unknown method. Called by `registerTools` when the policy lists an operation.
369
+ */
370
+ export function requireTasksAttached(server) {
371
+ if (server.server.getCapabilities().extensions?.[TASKS_EXTENSION_ID] === undefined) {
372
+ throw new Error("deps.tasks lists operations, but no Tasks extension is attached to this server. " +
373
+ "Call attach(server) on a TasksExtension before registerTools, or the tasks it creates cannot be polled.");
374
+ }
375
+ }
376
+ /**
377
+ * A tool's answer as the 2026-07-28 wire carries it, so as a completed task holds it: with the
378
+ * `resultType: "complete"` every result of that revision carries.
379
+ *
380
+ * **A task's result is exactly what the call would have answered**, and McpServer adds the
381
+ * discriminator to a blocking answer on its way out. A task's result reaches the client inside
382
+ * `tasks/get` instead, where nothing adds it, and the Tasks extension's reference client refuses a
383
+ * completed result without it.
384
+ */
385
+ export function completed(result) {
386
+ return { ...result, resultType: "complete" };
387
+ }
388
+ /**
389
+ * The MCP Tasks extension (`io.modelcontextprotocol/tasks`) lets a server answer `tools/call` with a
390
+ * task handle, which the client polls with `tasks/get`, answers with `tasks/update` and stops with
391
+ * `tasks/cancel`.
392
+ *
393
+ * **The declarations below have the shape of the SDK's own Tasks extension**, which is not yet in a
394
+ * release. A store written against them satisfies the SDK's `TaskStore` as well, so adopting the
395
+ * SDK's extension replaces one import and one `attach` call, and nothing else.
396
+ */
397
+ export const TASKS_EXTENSION_ID = "io.modelcontextprotocol/tasks";
398
+ const CLIENT_CAPABILITIES = "io.modelcontextprotocol/clientCapabilities";
399
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
400
+ /**
401
+ * Whether THIS request declared the Tasks extension. A task may be returned only to a request that
402
+ * did, whatever an earlier request declared.
403
+ */
404
+ export function declaresTasks(context) {
405
+ const envelope = context.mcpReq.envelope;
406
+ const capabilities = isRecord(envelope) ? envelope[CLIENT_CAPABILITIES] : undefined;
407
+ const extensions = isRecord(capabilities) ? capabilities["extensions"] : undefined;
408
+ return isRecord(extensions) && TASKS_EXTENSION_ID in extensions;
409
+ }
410
+ function requireTasks(context, what) {
411
+ if (declaresTasks(context))
412
+ return;
413
+ throw new MissingRequiredClientCapabilityError({ requiredCapabilities: { extensions: { [TASKS_EXTENSION_ID]: {} } } }, `${what} requires the request to declare the "${TASKS_EXTENSION_ID}" extension`);
414
+ }
415
+ /** On 2025-11-25, which carries no envelope, `tasks/get` and `tasks/cancel` named other methods. */
416
+ function requireModern(context) {
417
+ if (context.mcpReq.envelope === undefined) {
418
+ throw new ProtocolError(ProtocolErrorCode.MethodNotFound, "Method not found");
419
+ }
420
+ }
421
+ function taskNotFound() {
422
+ throw new ProtocolError(ProtocolErrorCode.InvalidParams, "Task not found");
423
+ }
424
+ function defaultPrincipal(context) {
425
+ const authInfo = context.http?.authInfo;
426
+ if (authInfo === undefined)
427
+ return undefined;
428
+ const subject = authInfo.extra?.["sub"];
429
+ return typeof subject === "string"
430
+ ? JSON.stringify([authInfo.clientId, subject])
431
+ : authInfo.clientId;
432
+ }
433
+ const taskParams = z.object({ taskId: z.string() });
434
+ const updateParams = taskParams.extend({
435
+ inputResponses: z.record(z.string(), z.unknown()).optional(),
436
+ });
437
+ /**
438
+ * Serves the Tasks extension: its capability, `tasks/get`, `tasks/update` and `tasks/cancel`, over
439
+ * the {@link TaskStore} the application supplies. A tool answers with a task through
440
+ * {@link TasksExtension.create}.
441
+ *
442
+ * One instance serves any number of servers; {@link TasksExtension.attach} each one before it
443
+ * connects. Under `createMcpHandler`, which builds a server per request, create the extension
444
+ * once and attach it in the factory.
445
+ */
446
+ export class TasksExtension {
447
+ id = TASKS_EXTENSION_ID;
448
+ store;
449
+ #defaultTtlMs;
450
+ #defaultPollIntervalMs;
451
+ #principal;
452
+ #attached = new WeakSet();
453
+ constructor(store, options = {}) {
454
+ this.store = store;
455
+ this.#defaultTtlMs = options.defaultTtlMs === undefined ? 86_400_000 : options.defaultTtlMs;
456
+ this.#defaultPollIntervalMs = options.defaultPollIntervalMs ?? 5000;
457
+ this.#principal = options.principal ?? defaultPrincipal;
458
+ }
459
+ /**
460
+ * Create a task for the current `tools/call`, bound to the caller, and return the handle the tool
461
+ * answers with. Refuses with `-32021` when the request did not declare the extension.
462
+ */
463
+ async create(context, options = {}) {
464
+ requireTasks(context, "Answering with a task");
465
+ const principal = this.#principal(context);
466
+ const pollIntervalMs = options.pollIntervalMs ?? this.#defaultPollIntervalMs;
467
+ const task = await this.store.create({
468
+ ttlMs: options.ttlMs === undefined ? this.#defaultTtlMs : options.ttlMs,
469
+ pollIntervalMs,
470
+ ...(principal === undefined ? {} : { principal }),
471
+ ...(options.context === undefined ? {} : { context: options.context }),
472
+ });
473
+ return { resultType: "task", ...task };
474
+ }
475
+ /**
476
+ * Serve the extension on `server`. Must run before it connects. Attaching this extension to the
477
+ * same server again does nothing; attaching a second Tasks extension throws and leaves the server
478
+ * as it was, because its `tasks/*` handlers would silently replace the first one's.
479
+ */
480
+ attach(server) {
481
+ if (this.#attached.has(server))
482
+ return;
483
+ const protocol = server.server;
484
+ if (protocol.getCapabilities().extensions?.[TASKS_EXTENSION_ID] !== undefined) {
485
+ throw new Error(`A Tasks extension is already attached to this server; one server serves one task store.`);
486
+ }
487
+ // Every method checked before any is registered, so a refusal leaves the server as it was.
488
+ for (const method of ["tasks/get", "tasks/update", "tasks/cancel"]) {
489
+ protocol.assertCanSetRequestHandler(method);
490
+ }
491
+ protocol.registerCapabilities({ extensions: { [TASKS_EXTENSION_ID]: {} } });
492
+ const access = (context) => {
493
+ const principal = this.#principal(context);
494
+ return principal === undefined ? {} : { principal };
495
+ };
496
+ protocol.setRequestHandler("tasks/get", { params: taskParams }, async (params, context) => {
497
+ requireModern(context);
498
+ requireTasks(context, "tasks/get");
499
+ const task = await this.store.get(params.taskId, access(context));
500
+ return task === undefined ? taskNotFound() : { resultType: "complete", ...task };
501
+ });
502
+ protocol.setRequestHandler("tasks/update", { params: updateParams }, async (params, context) => {
503
+ requireModern(context);
504
+ requireTasks(context, "tasks/update");
505
+ const dropped = context.mcpReq.droppedInputResponseKeys ?? [];
506
+ if (dropped.length > 0) {
507
+ throw new ProtocolError(ProtocolErrorCode.InvalidParams, `inputResponses entries must be bare results; refused: ${dropped.join(", ")}`);
508
+ }
509
+ const inputResponses = context.mcpReq.inputResponses ?? params.inputResponses;
510
+ if (inputResponses === undefined) {
511
+ throw new ProtocolError(ProtocolErrorCode.InvalidParams, "tasks/update requires inputResponses");
512
+ }
513
+ const found = await this.store.update(params.taskId, inputResponses, access(context));
514
+ return found ? { resultType: "complete" } : taskNotFound();
515
+ });
516
+ protocol.setRequestHandler("tasks/cancel", { params: taskParams }, async (params, context) => {
517
+ requireModern(context);
518
+ requireTasks(context, "tasks/cancel");
519
+ const found = await this.store.cancel(params.taskId, access(context));
520
+ return found ? { resultType: "complete" } : taskNotFound();
521
+ });
522
+ this.#attached.add(server);
523
+ }
524
+ }
@@ -1,4 +1,5 @@
1
1
  import { type EmittedRoute, type RouteSchemaNames } from "typespec-http-zod";
2
+ import { type DeclaredHints } from "./annotations.js";
2
3
  import type { SecurityRequirement } from "./runtime.js";
3
4
  /**
4
5
  * Where emitted output imports its runtime from: the copy this package writes beside it.
@@ -25,6 +26,8 @@ export interface ToolEntry {
25
26
  readonly requirements: readonly SecurityRequirement[];
26
27
  readonly description: string | undefined;
27
28
  readonly title: string | undefined;
29
+ /** The hints the operation states in `x-mcp-annotations`, over those its method gives. */
30
+ readonly hints: DeclaredHints;
28
31
  }
29
32
  export interface RenderedTools {
30
33
  readonly text: string;
package/dist/src/tools.js CHANGED
@@ -20,7 +20,7 @@ function renderSecurity(requirements) {
20
20
  }
21
21
  /** The annotations as a TypeScript object literal, for the generated call site. */
22
22
  function renderAnnotations(annotations) {
23
- const entries = Object.entries(annotations).map(([key, value]) => `${key}: ${String(value)}`);
23
+ const entries = Object.entries(annotations).map(([key, value]) => `${key}: ${JSON.stringify(value)}`);
24
24
  return `{ ${entries.join(", ")} }`;
25
25
  }
26
26
  /**
@@ -360,7 +360,7 @@ export function renderTools(entries, declaredOperationIds, options) {
360
360
  * **Always the runtime this package writes beside the file.** It used to be whatever
361
361
  * `runtime-module` named, which made an application own a copy of the rules below.
362
362
  */
363
- const runtimeTypes = ["McpServer", "ServerContext", "ToolDeps"];
363
+ const runtimeTypes = ["CallToolResult", "McpServer", "ServerContext", "ToolDeps"];
364
364
  if (entries.length > 0)
365
365
  runtimeTypes.push("Awaitable");
366
366
  const usesByteStream = entries.some((entry) => membersOf(entry.route, entry.names).some((member) => {
@@ -371,7 +371,11 @@ export function renderTools(entries, declaredOperationIds, options) {
371
371
  runtimeTypes.push("ByteStream");
372
372
  const from = literal(DEFAULT_RUNTIME_MODULE);
373
373
  const runtimeImport = [
374
- ...(entries.length > 0 ? [`import { toolResult } from ${from};`] : []),
374
+ ...(entries.length > 0
375
+ ? [
376
+ `import { completed, declaresTasks, requireTasksAttached, toolError, toolResult } from ${from};`,
377
+ ]
378
+ : []),
375
379
  `import type { ${runtimeTypes.toSorted().join(", ")} } from ${from};`,
376
380
  ].join("\n");
377
381
  const schemaImport = imported.size === 0
@@ -426,29 +430,37 @@ export function renderTools(entries, declaredOperationIds, options) {
426
430
  * model's context. Route order is not stable across spec edits; a name sort is.
427
431
  */
428
432
  const ordered = [...entries].toSorted((a, b) => a.toolName.localeCompare(b.toolName));
433
+ /**
434
+ * The body kinds the runtime cannot read off an arm, only where one applies: a JSON body is known
435
+ * from its media type, and most operations answer nothing else.
436
+ */
437
+ const bodiesOf = (entry) => {
438
+ const kinds = new Map();
439
+ for (const [status, mediaType, kind] of bodyKindsOf(entry.route, entry.names)) {
440
+ kinds.set(status, [...(kinds.get(status) ?? []), `${literal(mediaType)}: ${literal(kind)}`]);
441
+ }
442
+ return kinds.size === 0
443
+ ? ""
444
+ : `, bodies: { ${[...kinds].map(([status, byType]) => `${literal(status)}: { ${byType.join(", ")} }`).join(", ")} }`;
445
+ };
429
446
  const registrations = ordered
430
447
  .map((entry) => {
448
+ const operationId = entry.route.operationId;
431
449
  const title = entry.title === undefined ? "" : `\n\t\t\t\ttitle: ${literal(entry.title)},`;
432
450
  const description = entry.description === undefined
433
451
  ? ""
434
452
  : `\n\t\t\t\tdescription: ${literal(entry.description)},`;
435
- const published = outputSchemaOf(entry);
436
- const outputSchema = published === undefined ? "" : `\n\t\t\t\toutputSchema: ${published},`;
437
453
  /**
438
- * The body kinds the runtime cannot read off an arm, only where one applies: a JSON body is
439
- * known from its media type, and most operations answer nothing else.
454
+ * **A tool the application lets answer with a task publishes no `outputSchema`.** The SDK
455
+ * turns a task from a tool that publishes one into a tool error, so a task tool is an ordinary
456
+ * tool without it, and its result carries the text alone on every request, inline or not.
440
457
  */
441
- const kinds = new Map();
442
- for (const [status, mediaType, kind] of bodyKindsOf(entry.route, entry.names)) {
443
- kinds.set(status, [
444
- ...(kinds.get(status) ?? []),
445
- `${literal(mediaType)}: ${literal(kind)}`,
446
- ]);
447
- }
448
- const bodies = kinds.size === 0
458
+ const published = outputSchemaOf(entry);
459
+ const outputSchema = published === undefined
449
460
  ? ""
450
- : `, bodies: { ${[...kinds].map(([status, byType]) => `${literal(status)}: { ${byType.join(", ")} }`).join(", ")} }`;
451
- const declared = `{ arms: ${entry.names.responses}, outputSchema: ${published ?? "undefined"}${bodies} }`;
461
+ : `\n\t\t\t\t...(deferrable ? {} : { outputSchema: ${published} }),`;
462
+ const declaredSchema = published === undefined ? "undefined" : `deferrable ? undefined : ${published}`;
463
+ const declared = `{ arms: ${entry.names.responses}, outputSchema: ${declaredSchema}${bodiesOf(entry)} }`;
452
464
  /**
453
465
  * **A parameterless tool must not DECLARE an argument it never reads.**
454
466
  *
@@ -467,19 +479,27 @@ export function renderTools(entries, declaredOperationIds, options) {
467
479
  const argument = fields.length === 0 ? "{}" : `{ ${fields.join(", ")} }`;
468
480
  const argumentName = parameterless ? "_args" : "args";
469
481
  return ` {
482
+ const deferrable = taskable.has(${literal(operationId)});
470
483
  const tool = server.registerTool(
471
484
  ${literal(entry.toolName)},
472
485
  {${title}${description}
473
486
  inputSchema: ${inputSchemaName(entry)},${outputSchema}
474
- annotations: ${renderAnnotations(annotationsFor(entry.route.verb))},
487
+ annotations: ${renderAnnotations(annotationsFor(entry.route.verb, entry.hints, entry.title))},
475
488
  },
476
489
  async (${argumentName}, context) => {
477
490
  const ctx = deps.context(context, ${literal(entry.route.authentication)});
478
491
  if (ctx === null) return deps.noContext(context);
492
+ const input: ${inputTypeOf(entry)} = ${argument};
493
+ if (deferrable && deps.tasks !== undefined && declaresTasks(context)) {
494
+ const call = { operationId: ${literal(operationId)}, input } as const;
495
+ if ((await deps.tasks.decide?.(call, ctx, context)) !== "inline") {
496
+ return deps.tasks.create(call, ctx, context);
497
+ }
498
+ }
479
499
  return toolResult(
480
500
  ${declared},
481
- ${literal(entry.route.operationId)},
482
- await handlersFor(context).${entry.route.operationId}(ctx, ${argument}),
501
+ ${literal(operationId)},
502
+ await handlersFor(context).${operationId}(ctx, input),
483
503
  );
484
504
  },
485
505
  );
@@ -491,6 +511,48 @@ export function renderTools(entries, declaredOperationIds, options) {
491
511
  }`;
492
512
  })
493
513
  .join("\n");
514
+ const toolCalls = ordered.length === 0
515
+ ? " never"
516
+ : ordered
517
+ .map((entry) => `\n\t| { readonly operationId: ${literal(entry.route.operationId)}; readonly input: ${inputTypeOf(entry)} }`)
518
+ .join("");
519
+ /**
520
+ * **The same arms and the same rules as the registered tool, with `outputSchema` withheld** as it
521
+ * is for every tool that may answer with a task, so the result is the one the blocking call gives.
522
+ */
523
+ const runCases = ordered
524
+ .map((entry) => ` case ${literal(entry.route.operationId)}:
525
+ return completed(await toolResult(
526
+ { arms: ${entry.names.responses}, outputSchema: undefined${bodiesOf(entry)} },
527
+ ${literal(entry.route.operationId)},
528
+ await handlers.${entry.route.operationId}(caller, call.input),
529
+ ));`)
530
+ .join("\n");
531
+ const unknownCall = "throw new Error(`No tool of this service runs ${JSON.stringify((call as { readonly operationId?: unknown }).operationId)}.`);";
532
+ const runTool = ordered.length === 0
533
+ ? `export async function runTool<C>(_handlers: Tools<C>, call: ToolCall, _caller: C): Promise<CallToolResult> {
534
+ ${unknownCall}
535
+ }`
536
+ : `/** Each tool's argument schema, by operation: what \`runTool\` checks a stored call against. */
537
+ const TOOL_INPUTS: ReadonlyMap<string, z.ZodType> = new Map<string, z.ZodType>([${ordered.map((entry) => `[${literal(entry.route.operationId)}, ${inputSchemaName(entry)}]`).join(", ")}]);
538
+
539
+ export async function runTool<C>(handlers: Tools<C>, call: ToolCall, caller: C): Promise<CallToolResult> {
540
+ const inputSchema = TOOL_INPUTS.get(call.operationId);
541
+ if (inputSchema === undefined) {
542
+ ${unknownCall}
543
+ }
544
+ const checked = inputSchema.safeParse(call.input);
545
+ if (!checked.success) {
546
+ throw new Error(\`The stored input of \${call.operationId} no longer meets its tool's argument schema: \${checked.error.message}\`);
547
+ }
548
+ try {
549
+ switch (call.operationId) {
550
+ ${runCases}
551
+ }
552
+ } catch (error) {
553
+ return completed(toolError(error));
554
+ }
555
+ }`;
494
556
  const text = `${generatedBanner(options.hint)}
495
557
  ${usesZod ? 'import { z } from "zod";\n' : ""}${runtimeImport}
496
558
  ${schemaImport}
@@ -566,12 +628,35 @@ export const TOOL_NAMES = [${ordered.map((entry) => literal(entry.toolName)).joi
566
628
  export function registerTools<C, T extends Tools<C>>(
567
629
  ${u}server: McpServer,
568
630
  ${u}handlersFor: (context: ServerContext) => ToolsExhaustive<T>,
569
- ${u}deps: ToolDeps<C>,
631
+ ${u}deps: ToolDeps<C, ToolCall>,
570
632
  ): readonly string[] {
571
- const registered: string[] = [];
633
+ const registered: string[] = [];${entries.length === 0 ? "" : "\n\tconst taskable = new Set<string>(deps.tasks?.operations ?? []);\n\tif (taskable.size > 0) requireTasksAttached(server);"}
572
634
  ${registrations}
573
635
  return registered;
574
636
  }
637
+
638
+ /**
639
+ * One tool call, as the work behind an MCP task receives it: the operation and the input its handler
640
+ * is given. \`deps.tasks.create\` is handed one, and passes on whatever its store needs to run it later.
641
+ */
642
+ export type ToolCall =${toolCalls};
643
+
644
+ /**
645
+ * Run one tool call through its handler and its declared responses, and answer what the tool answers
646
+ * when \`deps.tasks\` lists it, which publishes no \`outputSchema\` and so carries no
647
+ * \`structuredContent\`: the work behind a task settles with this.
648
+ *
649
+ * **Throws only for a call this service can no longer run**: one naming an operation it has no tool
650
+ * for, as a store shared by several services can hand it, or one whose stored input its tool's
651
+ * argument schema no longer accepts, as a task that outlived a deploy can. Both are faults below the
652
+ * tool: settle the task \`failed\`, not \`completed\`. The handler is not called.
653
+ *
654
+ * **Otherwise it never throws.** A thrown error, and a result the document does not declare, answer the tool error
655
+ * McpServer answers for them, so the task completes with \`isError\` exactly as the blocking call would
656
+ * have. The Tasks extension reserves a \`failed\` task for a protocol error. Every answer carries the
657
+ * \`resultType: "complete"\` the blocking answer carries on the wire.
658
+ */
659
+ ${runTool}
575
660
  `;
576
661
  return { text, emitted: entries.map((entry) => entry.route.operationId) };
577
662
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typespec-http-mcp",
3
- "version": "0.8.1",
3
+ "version": "0.10.0",
4
4
  "description": "TypeSpec emitter: generate an MCP tool surface, and the Zod validators it publishes, from an HTTP service definition, dispatching into the same handlers a generated HTTP server calls.",
5
5
  "keywords": [
6
6
  "cloudflare-workers",
@@ -50,8 +50,9 @@
50
50
  },
51
51
  "devDependencies": {
52
52
  "@hono/zod-validator": "^0.9.1",
53
- "@modelcontextprotocol/client": "2.0.0",
54
- "@modelcontextprotocol/server": "2.0.0",
53
+ "@modelcontextprotocol/client": "2.4.0",
54
+ "@modelcontextprotocol/ext-tasks": "0.2.3",
55
+ "@modelcontextprotocol/server": "2.4.0",
55
56
  "@types/node": "^26.5.1",
56
57
  "@typespec/compiler": "1.17.0",
57
58
  "@typespec/events": "0.87.0",
@@ -76,7 +77,7 @@
76
77
  "zod": "^4.6.2"
77
78
  },
78
79
  "peerDependencies": {
79
- "@modelcontextprotocol/server": "^2.0.0",
80
+ "@modelcontextprotocol/server": "^2.3.0",
80
81
  "@typespec/compiler": "^1.15.0",
81
82
  "@typespec/http": "^1.15.0",
82
83
  "@typespec/openapi": "^1.15.0",