typespec-http-mcp 0.8.1 → 0.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.
- package/README.md +48 -10
- package/dist/src/runtime.d.ts +226 -3
- package/dist/src/runtime.js +175 -0
- package/dist/src/tools.js +105 -20
- package/package.json +5 -4
- package/src/runtime.ts +389 -3
package/README.md
CHANGED
|
@@ -107,21 +107,59 @@ What the model receives follows from the document:
|
|
|
107
107
|
- `structuredContent` carries the body when its schema is the tool's `outputSchema`;
|
|
108
108
|
- response headers are carried in `_meta["typespec-http-mcp/response-headers"]`, keyed by wire name.
|
|
109
109
|
|
|
110
|
+
## Long-running tools and MCP Tasks
|
|
111
|
+
|
|
112
|
+
Some tools finish long after the request that started them: an export, a reply a person has to give,
|
|
113
|
+
a job on a queue. A client that supports the
|
|
114
|
+
[MCP Tasks extension](https://github.com/modelcontextprotocol/ext-tasks) can take a task handle at
|
|
115
|
+
once and poll for the result.
|
|
116
|
+
|
|
117
|
+
**Which tools may do that is decided where you wire them, never in the spec.** The extension has no
|
|
118
|
+
per-tool declaration, and whether work outlives a request is a fact about where you run it, not
|
|
119
|
+
about the operation. Add a `tasks` policy to `deps`, and attach the runtime's `TasksExtension`,
|
|
120
|
+
over a store of yours, to the server:
|
|
121
|
+
|
|
122
|
+
```ts
|
|
123
|
+
import { registerTools, type ToolCall } from "./generated/mcp.gen.js";
|
|
124
|
+
import { TasksExtension, type ToolDeps } from "./generated/mcp-runtime.gen.js";
|
|
125
|
+
|
|
126
|
+
const tasks = new TasksExtension(store); // your TaskStore: a Durable Object, a Workflow, a table
|
|
127
|
+
|
|
128
|
+
// in the factory above
|
|
129
|
+
const deps: ToolDeps<AuthInfo, ToolCall> = {
|
|
130
|
+
// permits, context and noContext, as above, and:
|
|
131
|
+
tasks: {
|
|
132
|
+
operations: ["exportCatalog"],
|
|
133
|
+
create: (call, caller, serverContext) =>
|
|
134
|
+
tasks.create(serverContext, { context: { call, caller: caller.clientId } }),
|
|
135
|
+
},
|
|
136
|
+
};
|
|
137
|
+
const server = new McpServer({ name: "bookshop", version: "1.0.0" });
|
|
138
|
+
tasks.attach(server);
|
|
139
|
+
registerTools(server, () => handlers, deps);
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
The work behind a task runs the same handler through `runTool(handlers, call, caller)`, which
|
|
143
|
+
answers exactly what the tool would have, so a completed task holds the blocking call's result. A
|
|
144
|
+
client that did not declare the extension is answered inline, as before. See
|
|
145
|
+
[the guide](docs/guides.md#running-long-tools-as-mcp-tasks) and
|
|
146
|
+
[the reference](docs/reference.md#tasks).
|
|
147
|
+
|
|
110
148
|
## What is derived, and from what
|
|
111
149
|
|
|
112
150
|
Nothing is invented. Every field of a tool comes from something the document already states, or from
|
|
113
151
|
a published specification:
|
|
114
152
|
|
|
115
|
-
| tool field | derived from
|
|
116
|
-
| ---------------------------- |
|
|
117
|
-
| `name` | the operation id the document publishes
|
|
118
|
-
| `title` | `@summary`
|
|
119
|
-
| `description` | `@doc`
|
|
120
|
-
| `inputSchema` | the emitted Zod schema, **input** projection
|
|
121
|
-
| `outputSchema` | the body every 2xx and 3xx status shares
|
|
122
|
-
| `annotations.readOnlyHint` | the method's safety, per IANA's HTTP Method Registry
|
|
123
|
-
| `annotations.idempotentHint` | the method's idempotence, same source
|
|
124
|
-
| which operations are tools | `@tag`, which `@typespec/openapi3` publishes
|
|
153
|
+
| tool field | derived from |
|
|
154
|
+
| ---------------------------- | -------------------------------------------------------------------------------- |
|
|
155
|
+
| `name` | the operation id the document publishes |
|
|
156
|
+
| `title` | `@summary` |
|
|
157
|
+
| `description` | `@doc` |
|
|
158
|
+
| `inputSchema` | the emitted Zod schema, **input** projection |
|
|
159
|
+
| `outputSchema` | the body every 2xx and 3xx status shares, unless the tool may answer with a task |
|
|
160
|
+
| `annotations.readOnlyHint` | the method's safety, per IANA's HTTP Method Registry |
|
|
161
|
+
| `annotations.idempotentHint` | the method's idempotence, same source |
|
|
162
|
+
| which operations are tools | `@tag`, which `@typespec/openapi3` publishes |
|
|
125
163
|
|
|
126
164
|
There are **no decorators**. A decorator would let a spec state something the OpenAPI document
|
|
127
165
|
cannot publish, so the emitted surface would enforce a rule no reader of the contract can see.
|
package/dist/src/runtime.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type
|
|
2
|
-
import type
|
|
1
|
+
import { type CallToolResult, type McpServer, type ServerContext } from "@modelcontextprotocol/server";
|
|
2
|
+
import { type ZodError, type ZodType } from "zod";
|
|
3
3
|
/**
|
|
4
4
|
* **What generated code imports at run time -- and the only thing this package puts in its output.**
|
|
5
5
|
*
|
|
@@ -179,7 +179,7 @@ export declare function toolResult(declared: ToolResponses, operationId: string,
|
|
|
179
179
|
* **`C` is the caller context, and `registerTools` INFERS it from `context`.** An application whose
|
|
180
180
|
* `context` returns a `Caller` has handlers typed `(ctx: Caller, input)`, with nothing to declare.
|
|
181
181
|
*/
|
|
182
|
-
export interface ToolDeps<C = unknown> {
|
|
182
|
+
export interface ToolDeps<C = unknown, Call extends ToolCallShape = never> {
|
|
183
183
|
/**
|
|
184
184
|
* Whether the caller this server was built for may SEE this tool.
|
|
185
185
|
*
|
|
@@ -217,4 +217,227 @@ export interface ToolDeps<C = unknown> {
|
|
|
217
217
|
readonly context: (context: ServerContext, authentication: "none" | "optional" | "required") => C | null;
|
|
218
218
|
/** The result when {@link context} returns `null`. The application's to decide. */
|
|
219
219
|
readonly noContext: (context: ServerContext) => CallToolResult;
|
|
220
|
+
/**
|
|
221
|
+
* Which tools may answer with an MCP task, and how a task is created. Absent, no tool ever does.
|
|
222
|
+
*
|
|
223
|
+
* **The application's to decide, because the document cannot say it.** The Tasks extension has
|
|
224
|
+
* no per-tool declaration: the server decides on each request whether to answer with a task.
|
|
225
|
+
* Whether a tool's work outlives a request is a fact about where the application runs it, not
|
|
226
|
+
* about the operation.
|
|
227
|
+
*
|
|
228
|
+
* **Typed by the generated `ToolCall`, so write `ToolDeps<Caller, ToolCall>` to set it.** The
|
|
229
|
+
* policy names operations, and only the generated module knows which exist. `ToolDeps<Caller>`
|
|
230
|
+
* names none, so it admits no operation, and wiring written before tasks existed compiles as it
|
|
231
|
+
* did.
|
|
232
|
+
*/
|
|
233
|
+
readonly tasks?: ToolTasks<C, Call>;
|
|
234
|
+
}
|
|
235
|
+
/** What a tool call is, to the code that runs it later: the operation and its validated input. */
|
|
236
|
+
export interface ToolCallShape {
|
|
237
|
+
readonly operationId: string;
|
|
238
|
+
readonly input: unknown;
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* The application's task policy for the tools one `registerTools` call registers.
|
|
242
|
+
*
|
|
243
|
+
* **`decide` and `create` are METHOD signatures, deliberately.** That keeps the policy covariant in
|
|
244
|
+
* `Call`, so `ToolDeps<Caller>`, which lists no operation, is still a `ToolDeps<Caller, ToolCall>`.
|
|
245
|
+
* With property signatures the two would be unrelated, and every wiring written before tasks existed
|
|
246
|
+
* would stop compiling.
|
|
247
|
+
*
|
|
248
|
+
* **A request that did not declare the Tasks extension never reaches this policy.** It is answered
|
|
249
|
+
* inline, as if no policy were configured, because the extension forbids answering it with a task.
|
|
250
|
+
*/
|
|
251
|
+
export interface ToolTasks<C, Call extends ToolCallShape> {
|
|
252
|
+
/**
|
|
253
|
+
* The operations that may answer with a task.
|
|
254
|
+
*
|
|
255
|
+
* **Read at REGISTRATION, like `permits`**, because it changes what is published: a tool listed
|
|
256
|
+
* here publishes no `outputSchema`. The SDK refuses a task from a tool that publishes one, so a
|
|
257
|
+
* task tool is an ordinary tool without it, on every request.
|
|
258
|
+
*/
|
|
259
|
+
readonly operations: readonly Call["operationId"][];
|
|
260
|
+
/**
|
|
261
|
+
* Whether THIS call becomes a task or runs inline. Consulted only for a listed operation and a
|
|
262
|
+
* request that declared the extension. Absent, every such call becomes a task.
|
|
263
|
+
*
|
|
264
|
+
* Receives the validated input and the caller, so the answer can depend on the application's own
|
|
265
|
+
* state: work that is already finished can be answered at once.
|
|
266
|
+
*
|
|
267
|
+
* Type `call` as the whole `ToolCall` and narrow on `operationId`: as a method, this accepts a
|
|
268
|
+
* narrower parameter without complaint, and receives every listed operation's call regardless.
|
|
269
|
+
*/
|
|
270
|
+
decide?(call: Call, caller: C, context: ServerContext): Awaitable<"task" | "inline">;
|
|
271
|
+
/**
|
|
272
|
+
* Create the task and answer with its handle. In practice
|
|
273
|
+
* `(call, caller, context) => tasks.create(context, { context: { ...call, ... } })`, where the
|
|
274
|
+
* application chooses what the store needs to find or start the work: the call, an identifier
|
|
275
|
+
* for the caller, a service name when one store serves several services.
|
|
276
|
+
*/
|
|
277
|
+
create(call: Call, caller: C, context: ServerContext): Promise<TaskToolResult>;
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* The result McpServer answers when a tool callback throws: the message as text, marked as an error.
|
|
281
|
+
*
|
|
282
|
+
* Exported so the work behind a task settles a thrown error exactly as the blocking call would have
|
|
283
|
+
* answered it. The Tasks extension requires a tool error to complete the task with that result,
|
|
284
|
+
* and reserves `failed` for a protocol error.
|
|
285
|
+
*/
|
|
286
|
+
export declare function toolError(error: unknown): CallToolResult;
|
|
287
|
+
/**
|
|
288
|
+
* Refuses a task policy on a server no {@link TasksExtension} is attached to. A tool there would
|
|
289
|
+
* answer with a task the server does not advertise and nobody can poll: `tasks/get` would be an
|
|
290
|
+
* unknown method. Called by `registerTools` when the policy lists an operation.
|
|
291
|
+
*/
|
|
292
|
+
export declare function requireTasksAttached(server: McpServer): void;
|
|
293
|
+
/**
|
|
294
|
+
* A tool's answer as the 2026-07-28 wire carries it, so as a completed task holds it: with the
|
|
295
|
+
* `resultType: "complete"` every result of that revision carries.
|
|
296
|
+
*
|
|
297
|
+
* **A task's result is exactly what the call would have answered**, and McpServer adds the
|
|
298
|
+
* discriminator to a blocking answer on its way out. A task's result reaches the client inside
|
|
299
|
+
* `tasks/get` instead, where nothing adds it, and the Tasks extension's reference client refuses a
|
|
300
|
+
* completed result without it.
|
|
301
|
+
*/
|
|
302
|
+
export declare function completed(result: CallToolResult): CallToolResult;
|
|
303
|
+
/**
|
|
304
|
+
* The MCP Tasks extension (`io.modelcontextprotocol/tasks`) lets a server answer `tools/call` with a
|
|
305
|
+
* task handle, which the client polls with `tasks/get`, answers with `tasks/update` and stops with
|
|
306
|
+
* `tasks/cancel`.
|
|
307
|
+
*
|
|
308
|
+
* **The declarations below have the shape of the SDK's own Tasks extension**, which is not yet in a
|
|
309
|
+
* release. A store written against them satisfies the SDK's `TaskStore` as well, so adopting the
|
|
310
|
+
* SDK's extension replaces one import and one `attach` call, and nothing else.
|
|
311
|
+
*/
|
|
312
|
+
export declare const TASKS_EXTENSION_ID = "io.modelcontextprotocol/tasks";
|
|
313
|
+
/**
|
|
314
|
+
* A task's state, as every task-related message carries it.
|
|
315
|
+
*
|
|
316
|
+
* **A type, not an interface, and its optional members admit `undefined`**, so a task typed by the
|
|
317
|
+
* SDK's own extension, an open object whose optional members do, is one of these and the reverse.
|
|
318
|
+
*/
|
|
319
|
+
export type Task = {
|
|
320
|
+
readonly taskId: string;
|
|
321
|
+
readonly status: "working" | "input_required" | "completed" | "cancelled" | "failed";
|
|
322
|
+
readonly statusMessage?: string | undefined;
|
|
323
|
+
/** ISO 8601. */
|
|
324
|
+
readonly createdAt: string;
|
|
325
|
+
/** ISO 8601. */
|
|
326
|
+
readonly lastUpdatedAt: string;
|
|
327
|
+
/** Retention from creation, in milliseconds; `null` is unlimited. */
|
|
328
|
+
readonly ttlMs: number | null;
|
|
329
|
+
/** How often a client should poll, in milliseconds. */
|
|
330
|
+
readonly pollIntervalMs?: number | undefined;
|
|
331
|
+
};
|
|
332
|
+
/** A request a task makes of the client while it waits, such as `elicitation/create`. */
|
|
333
|
+
export type TaskInputRequest = {
|
|
334
|
+
readonly method: string;
|
|
335
|
+
readonly params?: Readonly<Record<string, unknown>> | undefined;
|
|
336
|
+
};
|
|
337
|
+
/**
|
|
338
|
+
* What `tasks/get` answers: the task, with what its status carries.
|
|
339
|
+
*
|
|
340
|
+
* **`completed` carries the `CallToolResult` the call would have returned, `isError` included.**
|
|
341
|
+
* `failed` is only for a protocol error during execution, never for a tool that answered an error.
|
|
342
|
+
*/
|
|
343
|
+
export type DetailedTask = (Task & {
|
|
344
|
+
readonly status: "working";
|
|
345
|
+
}) | (Task & {
|
|
346
|
+
readonly status: "input_required";
|
|
347
|
+
readonly inputRequests: Readonly<Record<string, TaskInputRequest>>;
|
|
348
|
+
}) | (Task & {
|
|
349
|
+
readonly status: "completed";
|
|
350
|
+
readonly result: Readonly<Record<string, unknown>>;
|
|
351
|
+
}) | (Task & {
|
|
352
|
+
readonly status: "failed";
|
|
353
|
+
readonly error: Readonly<Record<string, unknown>>;
|
|
354
|
+
}) | (Task & {
|
|
355
|
+
readonly status: "cancelled";
|
|
356
|
+
});
|
|
357
|
+
/** A tool's answer when its work continues as a task. */
|
|
358
|
+
export type CreateTaskResult = Task & {
|
|
359
|
+
readonly resultType: "task";
|
|
360
|
+
};
|
|
361
|
+
/** The handle a tool callback returns in place of a `CallToolResult`. */
|
|
362
|
+
export type TaskToolResult = CallToolResult & CreateTaskResult;
|
|
363
|
+
/** What the extension asks a store to create. */
|
|
364
|
+
export interface CreateTaskParams {
|
|
365
|
+
/** Retention from creation, in milliseconds; `null` is unlimited. */
|
|
366
|
+
readonly ttlMs: number | null;
|
|
367
|
+
readonly pollIntervalMs?: number;
|
|
368
|
+
/**
|
|
369
|
+
* The identity of the request that created the task. A store MUST refuse every later access
|
|
370
|
+
* from a different principal, answering as for an unknown task.
|
|
371
|
+
*/
|
|
372
|
+
readonly principal?: string;
|
|
373
|
+
/** The store's own: whatever its execution needs to find or start the work. */
|
|
374
|
+
readonly context?: Readonly<Record<string, unknown>>;
|
|
375
|
+
}
|
|
376
|
+
/** The identity presented on a `tasks/*` request. */
|
|
377
|
+
export interface TaskAccess {
|
|
378
|
+
readonly principal?: string;
|
|
379
|
+
}
|
|
380
|
+
/**
|
|
381
|
+
* Where tasks live and how their work is found. The extension owns the protocol; the store owns the
|
|
382
|
+
* state, and the application owns the execution behind it: a queue, a workflow, a durable object.
|
|
383
|
+
*
|
|
384
|
+
* - `create` MUST NOT resolve before a following `get` would find the task.
|
|
385
|
+
* - `get`, `update` and `cancel` answer `undefined` or `false` for a task that is unknown, expired
|
|
386
|
+
* or another principal's, and the extension answers all three alike.
|
|
387
|
+
* - `cancel` is cooperative and idempotent on a finished task.
|
|
388
|
+
* - Task ids MUST be unguessable.
|
|
389
|
+
*/
|
|
390
|
+
export interface TaskStore {
|
|
391
|
+
create(params: CreateTaskParams): Promise<Task>;
|
|
392
|
+
get(taskId: string, access?: TaskAccess): Promise<DetailedTask | undefined>;
|
|
393
|
+
update(taskId: string, inputResponses: Readonly<Record<string, unknown>>, access?: TaskAccess): Promise<boolean>;
|
|
394
|
+
cancel(taskId: string, access?: TaskAccess): Promise<boolean>;
|
|
395
|
+
}
|
|
396
|
+
export interface TasksExtensionOptions {
|
|
397
|
+
/** Retention when `create` is given none, in milliseconds; `null` is unlimited. Default 24 hours. */
|
|
398
|
+
readonly defaultTtlMs?: number | null;
|
|
399
|
+
/** The polling hint when `create` is given none, in milliseconds. Default 5000. */
|
|
400
|
+
readonly defaultPollIntervalMs?: number;
|
|
401
|
+
/**
|
|
402
|
+
* The identity a task is bound to. Default: the OAuth client id, with the token subject when
|
|
403
|
+
* the token verifier puts one at `authInfo.extra.sub`. With no authentication it is `undefined`,
|
|
404
|
+
* and a task's id is then the only credential for it.
|
|
405
|
+
*/
|
|
406
|
+
readonly principal?: (context: ServerContext) => string | undefined;
|
|
407
|
+
}
|
|
408
|
+
export interface CreateTaskOptions {
|
|
409
|
+
readonly ttlMs?: number | null;
|
|
410
|
+
readonly pollIntervalMs?: number;
|
|
411
|
+
readonly context?: Readonly<Record<string, unknown>>;
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Whether THIS request declared the Tasks extension. A task may be returned only to a request that
|
|
415
|
+
* did, whatever an earlier request declared.
|
|
416
|
+
*/
|
|
417
|
+
export declare function declaresTasks(context: ServerContext): boolean;
|
|
418
|
+
/**
|
|
419
|
+
* Serves the Tasks extension: its capability, `tasks/get`, `tasks/update` and `tasks/cancel`, over
|
|
420
|
+
* the {@link TaskStore} the application supplies. A tool answers with a task through
|
|
421
|
+
* {@link TasksExtension.create}.
|
|
422
|
+
*
|
|
423
|
+
* One instance serves any number of servers; {@link TasksExtension.attach} each one before it
|
|
424
|
+
* connects. Under `createMcpHandler`, which builds a server per request, create the extension
|
|
425
|
+
* once and attach it in the factory.
|
|
426
|
+
*/
|
|
427
|
+
export declare class TasksExtension {
|
|
428
|
+
#private;
|
|
429
|
+
readonly id = "io.modelcontextprotocol/tasks";
|
|
430
|
+
readonly store: TaskStore;
|
|
431
|
+
constructor(store: TaskStore, options?: TasksExtensionOptions);
|
|
432
|
+
/**
|
|
433
|
+
* Create a task for the current `tools/call`, bound to the caller, and return the handle the tool
|
|
434
|
+
* answers with. Refuses with `-32021` when the request did not declare the extension.
|
|
435
|
+
*/
|
|
436
|
+
create(context: ServerContext, options?: CreateTaskOptions): Promise<TaskToolResult>;
|
|
437
|
+
/**
|
|
438
|
+
* Serve the extension on `server`. Must run before it connects. Attaching this extension to the
|
|
439
|
+
* same server again does nothing; attaching a second Tasks extension throws and leaves the server
|
|
440
|
+
* as it was, because its `tasks/*` handlers would silently replace the first one's.
|
|
441
|
+
*/
|
|
442
|
+
attach(server: McpServer): void;
|
|
220
443
|
}
|
package/dist/src/runtime.js
CHANGED
|
@@ -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
|
+
}
|
package/dist/src/tools.js
CHANGED
|
@@ -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
|
|
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
|
-
*
|
|
439
|
-
*
|
|
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
|
|
442
|
-
|
|
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
|
-
:
|
|
451
|
-
const
|
|
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,6 +479,7 @@ 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}
|
|
@@ -476,10 +489,17 @@ export function renderTools(entries, declaredOperationIds, options) {
|
|
|
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(
|
|
482
|
-
await handlersFor(context).${
|
|
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.
|
|
3
|
+
"version": "0.9.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.
|
|
54
|
-
"@modelcontextprotocol/
|
|
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.
|
|
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",
|
package/src/runtime.ts
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
1
|
+
import {
|
|
2
|
+
type CallToolResult,
|
|
3
|
+
type McpServer,
|
|
4
|
+
MissingRequiredClientCapabilityError,
|
|
5
|
+
ProtocolError,
|
|
6
|
+
ProtocolErrorCode,
|
|
7
|
+
type ServerContext,
|
|
8
|
+
} from "@modelcontextprotocol/server";
|
|
9
|
+
import { z, type ZodError, type ZodType } from "zod";
|
|
3
10
|
|
|
4
11
|
/**
|
|
5
12
|
* **What generated code imports at run time -- and the only thing this package puts in its output.**
|
|
@@ -528,7 +535,7 @@ export async function toolResult(
|
|
|
528
535
|
* **`C` is the caller context, and `registerTools` INFERS it from `context`.** An application whose
|
|
529
536
|
* `context` returns a `Caller` has handlers typed `(ctx: Caller, input)`, with nothing to declare.
|
|
530
537
|
*/
|
|
531
|
-
export interface ToolDeps<C = unknown> {
|
|
538
|
+
export interface ToolDeps<C = unknown, Call extends ToolCallShape = never> {
|
|
532
539
|
/**
|
|
533
540
|
* Whether the caller this server was built for may SEE this tool.
|
|
534
541
|
*
|
|
@@ -571,4 +578,383 @@ export interface ToolDeps<C = unknown> {
|
|
|
571
578
|
|
|
572
579
|
/** The result when {@link context} returns `null`. The application's to decide. */
|
|
573
580
|
readonly noContext: (context: ServerContext) => CallToolResult;
|
|
581
|
+
|
|
582
|
+
/**
|
|
583
|
+
* Which tools may answer with an MCP task, and how a task is created. Absent, no tool ever does.
|
|
584
|
+
*
|
|
585
|
+
* **The application's to decide, because the document cannot say it.** The Tasks extension has
|
|
586
|
+
* no per-tool declaration: the server decides on each request whether to answer with a task.
|
|
587
|
+
* Whether a tool's work outlives a request is a fact about where the application runs it, not
|
|
588
|
+
* about the operation.
|
|
589
|
+
*
|
|
590
|
+
* **Typed by the generated `ToolCall`, so write `ToolDeps<Caller, ToolCall>` to set it.** The
|
|
591
|
+
* policy names operations, and only the generated module knows which exist. `ToolDeps<Caller>`
|
|
592
|
+
* names none, so it admits no operation, and wiring written before tasks existed compiles as it
|
|
593
|
+
* did.
|
|
594
|
+
*/
|
|
595
|
+
readonly tasks?: ToolTasks<C, Call>;
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/** What a tool call is, to the code that runs it later: the operation and its validated input. */
|
|
599
|
+
export interface ToolCallShape {
|
|
600
|
+
readonly operationId: string;
|
|
601
|
+
readonly input: unknown;
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/**
|
|
605
|
+
* The application's task policy for the tools one `registerTools` call registers.
|
|
606
|
+
*
|
|
607
|
+
* **`decide` and `create` are METHOD signatures, deliberately.** That keeps the policy covariant in
|
|
608
|
+
* `Call`, so `ToolDeps<Caller>`, which lists no operation, is still a `ToolDeps<Caller, ToolCall>`.
|
|
609
|
+
* With property signatures the two would be unrelated, and every wiring written before tasks existed
|
|
610
|
+
* would stop compiling.
|
|
611
|
+
*
|
|
612
|
+
* **A request that did not declare the Tasks extension never reaches this policy.** It is answered
|
|
613
|
+
* inline, as if no policy were configured, because the extension forbids answering it with a task.
|
|
614
|
+
*/
|
|
615
|
+
export interface ToolTasks<C, Call extends ToolCallShape> {
|
|
616
|
+
/**
|
|
617
|
+
* The operations that may answer with a task.
|
|
618
|
+
*
|
|
619
|
+
* **Read at REGISTRATION, like `permits`**, because it changes what is published: a tool listed
|
|
620
|
+
* here publishes no `outputSchema`. The SDK refuses a task from a tool that publishes one, so a
|
|
621
|
+
* task tool is an ordinary tool without it, on every request.
|
|
622
|
+
*/
|
|
623
|
+
readonly operations: readonly Call["operationId"][];
|
|
624
|
+
|
|
625
|
+
/**
|
|
626
|
+
* Whether THIS call becomes a task or runs inline. Consulted only for a listed operation and a
|
|
627
|
+
* request that declared the extension. Absent, every such call becomes a task.
|
|
628
|
+
*
|
|
629
|
+
* Receives the validated input and the caller, so the answer can depend on the application's own
|
|
630
|
+
* state: work that is already finished can be answered at once.
|
|
631
|
+
*
|
|
632
|
+
* Type `call` as the whole `ToolCall` and narrow on `operationId`: as a method, this accepts a
|
|
633
|
+
* narrower parameter without complaint, and receives every listed operation's call regardless.
|
|
634
|
+
*/
|
|
635
|
+
decide?(call: Call, caller: C, context: ServerContext): Awaitable<"task" | "inline">;
|
|
636
|
+
|
|
637
|
+
/**
|
|
638
|
+
* Create the task and answer with its handle. In practice
|
|
639
|
+
* `(call, caller, context) => tasks.create(context, { context: { ...call, ... } })`, where the
|
|
640
|
+
* application chooses what the store needs to find or start the work: the call, an identifier
|
|
641
|
+
* for the caller, a service name when one store serves several services.
|
|
642
|
+
*/
|
|
643
|
+
create(call: Call, caller: C, context: ServerContext): Promise<TaskToolResult>;
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/**
|
|
647
|
+
* The result McpServer answers when a tool callback throws: the message as text, marked as an error.
|
|
648
|
+
*
|
|
649
|
+
* Exported so the work behind a task settles a thrown error exactly as the blocking call would have
|
|
650
|
+
* answered it. The Tasks extension requires a tool error to complete the task with that result,
|
|
651
|
+
* and reserves `failed` for a protocol error.
|
|
652
|
+
*/
|
|
653
|
+
export function toolError(error: unknown): CallToolResult {
|
|
654
|
+
return {
|
|
655
|
+
content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }],
|
|
656
|
+
isError: true,
|
|
657
|
+
};
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
/**
|
|
661
|
+
* Refuses a task policy on a server no {@link TasksExtension} is attached to. A tool there would
|
|
662
|
+
* answer with a task the server does not advertise and nobody can poll: `tasks/get` would be an
|
|
663
|
+
* unknown method. Called by `registerTools` when the policy lists an operation.
|
|
664
|
+
*/
|
|
665
|
+
export function requireTasksAttached(server: McpServer): void {
|
|
666
|
+
if (server.server.getCapabilities().extensions?.[TASKS_EXTENSION_ID] === undefined) {
|
|
667
|
+
throw new Error(
|
|
668
|
+
"deps.tasks lists operations, but no Tasks extension is attached to this server. " +
|
|
669
|
+
"Call attach(server) on a TasksExtension before registerTools, or the tasks it creates cannot be polled.",
|
|
670
|
+
);
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
/**
|
|
675
|
+
* A tool's answer as the 2026-07-28 wire carries it, so as a completed task holds it: with the
|
|
676
|
+
* `resultType: "complete"` every result of that revision carries.
|
|
677
|
+
*
|
|
678
|
+
* **A task's result is exactly what the call would have answered**, and McpServer adds the
|
|
679
|
+
* discriminator to a blocking answer on its way out. A task's result reaches the client inside
|
|
680
|
+
* `tasks/get` instead, where nothing adds it, and the Tasks extension's reference client refuses a
|
|
681
|
+
* completed result without it.
|
|
682
|
+
*/
|
|
683
|
+
export function completed(result: CallToolResult): CallToolResult {
|
|
684
|
+
return { ...result, resultType: "complete" };
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
/**
|
|
688
|
+
* The MCP Tasks extension (`io.modelcontextprotocol/tasks`) lets a server answer `tools/call` with a
|
|
689
|
+
* task handle, which the client polls with `tasks/get`, answers with `tasks/update` and stops with
|
|
690
|
+
* `tasks/cancel`.
|
|
691
|
+
*
|
|
692
|
+
* **The declarations below have the shape of the SDK's own Tasks extension**, which is not yet in a
|
|
693
|
+
* release. A store written against them satisfies the SDK's `TaskStore` as well, so adopting the
|
|
694
|
+
* SDK's extension replaces one import and one `attach` call, and nothing else.
|
|
695
|
+
*/
|
|
696
|
+
export const TASKS_EXTENSION_ID = "io.modelcontextprotocol/tasks";
|
|
697
|
+
|
|
698
|
+
/**
|
|
699
|
+
* A task's state, as every task-related message carries it.
|
|
700
|
+
*
|
|
701
|
+
* **A type, not an interface, and its optional members admit `undefined`**, so a task typed by the
|
|
702
|
+
* SDK's own extension, an open object whose optional members do, is one of these and the reverse.
|
|
703
|
+
*/
|
|
704
|
+
export type Task = {
|
|
705
|
+
readonly taskId: string;
|
|
706
|
+
readonly status: "working" | "input_required" | "completed" | "cancelled" | "failed";
|
|
707
|
+
readonly statusMessage?: string | undefined;
|
|
708
|
+
/** ISO 8601. */
|
|
709
|
+
readonly createdAt: string;
|
|
710
|
+
/** ISO 8601. */
|
|
711
|
+
readonly lastUpdatedAt: string;
|
|
712
|
+
/** Retention from creation, in milliseconds; `null` is unlimited. */
|
|
713
|
+
readonly ttlMs: number | null;
|
|
714
|
+
/** How often a client should poll, in milliseconds. */
|
|
715
|
+
readonly pollIntervalMs?: number | undefined;
|
|
716
|
+
};
|
|
717
|
+
|
|
718
|
+
/** A request a task makes of the client while it waits, such as `elicitation/create`. */
|
|
719
|
+
export type TaskInputRequest = {
|
|
720
|
+
readonly method: string;
|
|
721
|
+
readonly params?: Readonly<Record<string, unknown>> | undefined;
|
|
722
|
+
};
|
|
723
|
+
|
|
724
|
+
/**
|
|
725
|
+
* What `tasks/get` answers: the task, with what its status carries.
|
|
726
|
+
*
|
|
727
|
+
* **`completed` carries the `CallToolResult` the call would have returned, `isError` included.**
|
|
728
|
+
* `failed` is only for a protocol error during execution, never for a tool that answered an error.
|
|
729
|
+
*/
|
|
730
|
+
export type DetailedTask =
|
|
731
|
+
| (Task & { readonly status: "working" })
|
|
732
|
+
| (Task & {
|
|
733
|
+
readonly status: "input_required";
|
|
734
|
+
readonly inputRequests: Readonly<Record<string, TaskInputRequest>>;
|
|
735
|
+
})
|
|
736
|
+
| (Task & { readonly status: "completed"; readonly result: Readonly<Record<string, unknown>> })
|
|
737
|
+
| (Task & { readonly status: "failed"; readonly error: Readonly<Record<string, unknown>> })
|
|
738
|
+
| (Task & { readonly status: "cancelled" });
|
|
739
|
+
|
|
740
|
+
/** A tool's answer when its work continues as a task. */
|
|
741
|
+
export type CreateTaskResult = Task & { readonly resultType: "task" };
|
|
742
|
+
|
|
743
|
+
/** The handle a tool callback returns in place of a `CallToolResult`. */
|
|
744
|
+
export type TaskToolResult = CallToolResult & CreateTaskResult;
|
|
745
|
+
|
|
746
|
+
/** What the extension asks a store to create. */
|
|
747
|
+
export interface CreateTaskParams {
|
|
748
|
+
/** Retention from creation, in milliseconds; `null` is unlimited. */
|
|
749
|
+
readonly ttlMs: number | null;
|
|
750
|
+
readonly pollIntervalMs?: number;
|
|
751
|
+
/**
|
|
752
|
+
* The identity of the request that created the task. A store MUST refuse every later access
|
|
753
|
+
* from a different principal, answering as for an unknown task.
|
|
754
|
+
*/
|
|
755
|
+
readonly principal?: string;
|
|
756
|
+
/** The store's own: whatever its execution needs to find or start the work. */
|
|
757
|
+
readonly context?: Readonly<Record<string, unknown>>;
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
/** The identity presented on a `tasks/*` request. */
|
|
761
|
+
export interface TaskAccess {
|
|
762
|
+
readonly principal?: string;
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
/**
|
|
766
|
+
* Where tasks live and how their work is found. The extension owns the protocol; the store owns the
|
|
767
|
+
* state, and the application owns the execution behind it: a queue, a workflow, a durable object.
|
|
768
|
+
*
|
|
769
|
+
* - `create` MUST NOT resolve before a following `get` would find the task.
|
|
770
|
+
* - `get`, `update` and `cancel` answer `undefined` or `false` for a task that is unknown, expired
|
|
771
|
+
* or another principal's, and the extension answers all three alike.
|
|
772
|
+
* - `cancel` is cooperative and idempotent on a finished task.
|
|
773
|
+
* - Task ids MUST be unguessable.
|
|
774
|
+
*/
|
|
775
|
+
export interface TaskStore {
|
|
776
|
+
create(params: CreateTaskParams): Promise<Task>;
|
|
777
|
+
get(taskId: string, access?: TaskAccess): Promise<DetailedTask | undefined>;
|
|
778
|
+
update(
|
|
779
|
+
taskId: string,
|
|
780
|
+
inputResponses: Readonly<Record<string, unknown>>,
|
|
781
|
+
access?: TaskAccess,
|
|
782
|
+
): Promise<boolean>;
|
|
783
|
+
cancel(taskId: string, access?: TaskAccess): Promise<boolean>;
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
export interface TasksExtensionOptions {
|
|
787
|
+
/** Retention when `create` is given none, in milliseconds; `null` is unlimited. Default 24 hours. */
|
|
788
|
+
readonly defaultTtlMs?: number | null;
|
|
789
|
+
/** The polling hint when `create` is given none, in milliseconds. Default 5000. */
|
|
790
|
+
readonly defaultPollIntervalMs?: number;
|
|
791
|
+
/**
|
|
792
|
+
* The identity a task is bound to. Default: the OAuth client id, with the token subject when
|
|
793
|
+
* the token verifier puts one at `authInfo.extra.sub`. With no authentication it is `undefined`,
|
|
794
|
+
* and a task's id is then the only credential for it.
|
|
795
|
+
*/
|
|
796
|
+
readonly principal?: (context: ServerContext) => string | undefined;
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
export interface CreateTaskOptions {
|
|
800
|
+
readonly ttlMs?: number | null;
|
|
801
|
+
readonly pollIntervalMs?: number;
|
|
802
|
+
readonly context?: Readonly<Record<string, unknown>>;
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
const CLIENT_CAPABILITIES = "io.modelcontextprotocol/clientCapabilities";
|
|
806
|
+
|
|
807
|
+
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
|
808
|
+
typeof value === "object" && value !== null && !Array.isArray(value);
|
|
809
|
+
|
|
810
|
+
/**
|
|
811
|
+
* Whether THIS request declared the Tasks extension. A task may be returned only to a request that
|
|
812
|
+
* did, whatever an earlier request declared.
|
|
813
|
+
*/
|
|
814
|
+
export function declaresTasks(context: ServerContext): boolean {
|
|
815
|
+
const envelope: unknown = context.mcpReq.envelope;
|
|
816
|
+
const capabilities = isRecord(envelope) ? envelope[CLIENT_CAPABILITIES] : undefined;
|
|
817
|
+
const extensions = isRecord(capabilities) ? capabilities["extensions"] : undefined;
|
|
818
|
+
return isRecord(extensions) && TASKS_EXTENSION_ID in extensions;
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
function requireTasks(context: ServerContext, what: string): void {
|
|
822
|
+
if (declaresTasks(context)) return;
|
|
823
|
+
throw new MissingRequiredClientCapabilityError(
|
|
824
|
+
{ requiredCapabilities: { extensions: { [TASKS_EXTENSION_ID]: {} } } },
|
|
825
|
+
`${what} requires the request to declare the "${TASKS_EXTENSION_ID}" extension`,
|
|
826
|
+
);
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
/** On 2025-11-25, which carries no envelope, `tasks/get` and `tasks/cancel` named other methods. */
|
|
830
|
+
function requireModern(context: ServerContext): void {
|
|
831
|
+
if (context.mcpReq.envelope === undefined) {
|
|
832
|
+
throw new ProtocolError(ProtocolErrorCode.MethodNotFound, "Method not found");
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
function taskNotFound(): never {
|
|
837
|
+
throw new ProtocolError(ProtocolErrorCode.InvalidParams, "Task not found");
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
function defaultPrincipal(context: ServerContext): string | undefined {
|
|
841
|
+
const authInfo = context.http?.authInfo;
|
|
842
|
+
if (authInfo === undefined) return undefined;
|
|
843
|
+
const subject = authInfo.extra?.["sub"];
|
|
844
|
+
return typeof subject === "string"
|
|
845
|
+
? JSON.stringify([authInfo.clientId, subject])
|
|
846
|
+
: authInfo.clientId;
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
const taskParams = z.object({ taskId: z.string() });
|
|
850
|
+
const updateParams = taskParams.extend({
|
|
851
|
+
inputResponses: z.record(z.string(), z.unknown()).optional(),
|
|
852
|
+
});
|
|
853
|
+
|
|
854
|
+
/**
|
|
855
|
+
* Serves the Tasks extension: its capability, `tasks/get`, `tasks/update` and `tasks/cancel`, over
|
|
856
|
+
* the {@link TaskStore} the application supplies. A tool answers with a task through
|
|
857
|
+
* {@link TasksExtension.create}.
|
|
858
|
+
*
|
|
859
|
+
* One instance serves any number of servers; {@link TasksExtension.attach} each one before it
|
|
860
|
+
* connects. Under `createMcpHandler`, which builds a server per request, create the extension
|
|
861
|
+
* once and attach it in the factory.
|
|
862
|
+
*/
|
|
863
|
+
export class TasksExtension {
|
|
864
|
+
readonly id = TASKS_EXTENSION_ID;
|
|
865
|
+
readonly store: TaskStore;
|
|
866
|
+
readonly #defaultTtlMs: number | null;
|
|
867
|
+
readonly #defaultPollIntervalMs: number;
|
|
868
|
+
readonly #principal: (context: ServerContext) => string | undefined;
|
|
869
|
+
readonly #attached = new WeakSet<McpServer>();
|
|
870
|
+
|
|
871
|
+
constructor(store: TaskStore, options: TasksExtensionOptions = {}) {
|
|
872
|
+
this.store = store;
|
|
873
|
+
this.#defaultTtlMs = options.defaultTtlMs === undefined ? 86_400_000 : options.defaultTtlMs;
|
|
874
|
+
this.#defaultPollIntervalMs = options.defaultPollIntervalMs ?? 5000;
|
|
875
|
+
this.#principal = options.principal ?? defaultPrincipal;
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
/**
|
|
879
|
+
* Create a task for the current `tools/call`, bound to the caller, and return the handle the tool
|
|
880
|
+
* answers with. Refuses with `-32021` when the request did not declare the extension.
|
|
881
|
+
*/
|
|
882
|
+
async create(context: ServerContext, options: CreateTaskOptions = {}): Promise<TaskToolResult> {
|
|
883
|
+
requireTasks(context, "Answering with a task");
|
|
884
|
+
const principal = this.#principal(context);
|
|
885
|
+
const pollIntervalMs = options.pollIntervalMs ?? this.#defaultPollIntervalMs;
|
|
886
|
+
const task = await this.store.create({
|
|
887
|
+
ttlMs: options.ttlMs === undefined ? this.#defaultTtlMs : options.ttlMs,
|
|
888
|
+
pollIntervalMs,
|
|
889
|
+
...(principal === undefined ? {} : { principal }),
|
|
890
|
+
...(options.context === undefined ? {} : { context: options.context }),
|
|
891
|
+
});
|
|
892
|
+
return { resultType: "task", ...task } as TaskToolResult;
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
/**
|
|
896
|
+
* Serve the extension on `server`. Must run before it connects. Attaching this extension to the
|
|
897
|
+
* same server again does nothing; attaching a second Tasks extension throws and leaves the server
|
|
898
|
+
* as it was, because its `tasks/*` handlers would silently replace the first one's.
|
|
899
|
+
*/
|
|
900
|
+
attach(server: McpServer): void {
|
|
901
|
+
if (this.#attached.has(server)) return;
|
|
902
|
+
const protocol = server.server;
|
|
903
|
+
if (protocol.getCapabilities().extensions?.[TASKS_EXTENSION_ID] !== undefined) {
|
|
904
|
+
throw new Error(
|
|
905
|
+
`A Tasks extension is already attached to this server; one server serves one task store.`,
|
|
906
|
+
);
|
|
907
|
+
}
|
|
908
|
+
// Every method checked before any is registered, so a refusal leaves the server as it was.
|
|
909
|
+
for (const method of ["tasks/get", "tasks/update", "tasks/cancel"]) {
|
|
910
|
+
protocol.assertCanSetRequestHandler(method);
|
|
911
|
+
}
|
|
912
|
+
protocol.registerCapabilities({ extensions: { [TASKS_EXTENSION_ID]: {} } });
|
|
913
|
+
|
|
914
|
+
const access = (context: ServerContext): TaskAccess => {
|
|
915
|
+
const principal = this.#principal(context);
|
|
916
|
+
return principal === undefined ? {} : { principal };
|
|
917
|
+
};
|
|
918
|
+
|
|
919
|
+
protocol.setRequestHandler("tasks/get", { params: taskParams }, async (params, context) => {
|
|
920
|
+
requireModern(context);
|
|
921
|
+
requireTasks(context, "tasks/get");
|
|
922
|
+
const task = await this.store.get(params.taskId, access(context));
|
|
923
|
+
return task === undefined ? taskNotFound() : { resultType: "complete", ...task };
|
|
924
|
+
});
|
|
925
|
+
|
|
926
|
+
protocol.setRequestHandler(
|
|
927
|
+
"tasks/update",
|
|
928
|
+
{ params: updateParams },
|
|
929
|
+
async (params, context) => {
|
|
930
|
+
requireModern(context);
|
|
931
|
+
requireTasks(context, "tasks/update");
|
|
932
|
+
const dropped = context.mcpReq.droppedInputResponseKeys ?? [];
|
|
933
|
+
if (dropped.length > 0) {
|
|
934
|
+
throw new ProtocolError(
|
|
935
|
+
ProtocolErrorCode.InvalidParams,
|
|
936
|
+
`inputResponses entries must be bare results; refused: ${dropped.join(", ")}`,
|
|
937
|
+
);
|
|
938
|
+
}
|
|
939
|
+
const inputResponses = context.mcpReq.inputResponses ?? params.inputResponses;
|
|
940
|
+
if (inputResponses === undefined) {
|
|
941
|
+
throw new ProtocolError(
|
|
942
|
+
ProtocolErrorCode.InvalidParams,
|
|
943
|
+
"tasks/update requires inputResponses",
|
|
944
|
+
);
|
|
945
|
+
}
|
|
946
|
+
const found = await this.store.update(params.taskId, inputResponses, access(context));
|
|
947
|
+
return found ? { resultType: "complete" } : taskNotFound();
|
|
948
|
+
},
|
|
949
|
+
);
|
|
950
|
+
|
|
951
|
+
protocol.setRequestHandler("tasks/cancel", { params: taskParams }, async (params, context) => {
|
|
952
|
+
requireModern(context);
|
|
953
|
+
requireTasks(context, "tasks/cancel");
|
|
954
|
+
const found = await this.store.cancel(params.taskId, access(context));
|
|
955
|
+
return found ? { resultType: "complete" } : taskNotFound();
|
|
956
|
+
});
|
|
957
|
+
|
|
958
|
+
this.#attached.add(server);
|
|
959
|
+
}
|
|
574
960
|
}
|