import { type CallToolResult, type McpServer, type ServerContext } from "@modelcontextprotocol/server"; import { type ZodError, type ZodType } from "zod"; /** * **What generated code imports at run time -- and the only thing this package puts in its output.** * * **Kept deliberately tiny, and deliberately free of every TypeSpec import.** The main entry point * is an emitter: it pulls in `@typespec/compiler` and exists at build time. This module is what an * *application* touches, and making it reach the compiler would put a build-time dependency into a * server's runtime graph for the sake of a few declarations. typespec-http-mcp's packaging suite asserts the * separation rather than trusting it. * * **Always emitted, never substituted.** `runtime-module` used to point the generated file at a * module of the application's own, which made the application own a copy of the arm selection and * the result rules below. Nothing it was for needs it now: the caller context is inferred from * `deps.context`, and what a handler returns is the union of the responses the document declares. */ /** * The SDK types the generated signatures name, re-exported so emitted code has ONE specifier. * * **`export type`, not `export`.** Measured: `McpServer`, `ServerContext` and `CallToolResult` are * type-only exports of `@modelcontextprotocol/server`; only `isCallToolResult` is a runtime value * among them. A value re-export of any of these compiles and then fails at run time with * `SyntaxError: The requested module does not provide an export named ...`. */ export type { CallToolResult, McpServer, ServerContext }; /** * One status an operation may answer with, and what the document publishes for it. * * **Declared here rather than imported from `typespec-http-zod`, deliberately.** Emitted output must * never import this emitter or the library it runs -- a consumer installs both as devDependencies, * so a runtime import of either is a broken install. typespec-http-mcp's packaging suite asserts that. The * emitted `schemas.gen.ts` declares the same shape locally, so it depends on no runtime at all. * * The cost is a second declaration of one shape, and typespec-http-mcp's runtime parity suite is what stops the * two drifting: it grades this `armFor` against the library's own for every arm shape. * * **The arms arrive in OpenAPI's precedence order, so the FIRST match is the right one** -- an exact * code, then a range, then the catch-all. `schema: undefined` is a statement rather than an absence: * a response the document says carries no body has no validator. */ export interface ResponseArm { /** Every media type this response offers, including a single one. Absent where there is no body. */ readonly contentTypes?: readonly string[]; /** * The headers this response declares, by the WIRE name the response sets. `optional` is the * document's `required: false`. Absent where the response declares none. */ readonly headers?: readonly { readonly name: string; readonly optional: boolean; }[]; readonly status: number | "default" | `${1 | 2 | 3 | 4 | 5}XX`; readonly schema: ZodType | undefined; } /** * The arm that answers for a status, in the document's own precedence order. * * Exact code, then the `NXX` range, then `default`. Sorting the rule out once here is what stops * every application re-deriving it, and getting it silently wrong when a `404` and a `4XX` both apply. */ export declare function armFor(arms: readonly ResponseArm[], status: number): ResponseArm | undefined; /** An OpenAPI security requirement: scheme name to the scopes it demands. */ export type SecurityRequirement = Readonly>; export type Awaitable = T | Promise; /** What the document declares a tool may answer with, handed to {@link toolResult}. */ export interface ToolResponses { /** The operation's declared responses, in OpenAPI's precedence order. */ readonly arms: readonly ResponseArm[]; /** * The schema this tool PUBLISHED, or `undefined` where it published none. * * Carried separately from the arms because MCP obliges a tool declaring an `outputSchema` to * return conforming `structuredContent`, and which arm's schema was published is a decision the * emitter made rather than something readable off the arms. */ readonly outputSchema: ZodType | undefined; /** * How a body is answered where its media type does not say, keyed by the arm's status key * (`"200"`, `"4XX"`, `"default"`) and then by the media type as the arm declares it, and present * only where one applies. * * **Carried because an arm cannot say it.** The arm names the media types and the schema, and * neither tells a string body apart from raw bytes or from a model the handler serialised: an * `image/png` body and an `application/xml` one both arrive as a schema and a non-JSON type. The * emitter knows, from what the document declares the body to be. **By media type as well as by * status**, because one status may offer one model as XML, the text the handler writes, and as * `application/octet-stream`, its bytes. * * - `"text"`: a string, parsed against the arm's schema and answered as a `text` block; * - `"binary"`: raw bytes, answered as an `image` or `audio` block, or as an embedded resource * under any other type, a file declared `application/json` included. * * A media type with no entry answers a JSON body as JSON, and any other body as the text the * handler supplied, unvalidated. */ readonly bodies?: { readonly [status: string]: { readonly [mediaType: string]: "text" | "binary"; }; }; } /** * A response body that does not match the schema the document publishes for its status. * * **Thrown, so the application decides what a contract failure answers with**, the same class and * the same fields as the sibling server emitter's. The MCP server turns a thrown error into a * tool-execution error; an application that wants something else catches it around `registerTools`' * handlers. * * `issues` are Zod's, so they carry paths and codes. They also carry the offending VALUES; an * application that logs them should decide whether its results may contain anything it would not * log. */ export declare class ResponseContractError extends Error { readonly operationId: string; readonly status: number; readonly issues: ZodError["issues"]; /** * Fields declared and assigned rather than written as parameter properties, which are not * erasable syntax: a consumer building with `erasableSyntaxOnly` could not compile this file. */ constructor(operationId: string, status: number, issues: ZodError["issues"]); } /** * A handler answered with a status its operation does not declare. * * **Unreachable from a typed handler.** The generated `Tools` interface types every result as the * union of the declared statuses, so a literal outside it does not compile. This is what a CAST * produces, or a result that crossed a boundary the type system cannot see into. Thrown rather than * answered, because answering would publish a status the contract does not state. */ export declare class UndeclaredStatusError extends Error { readonly operationId: string; readonly result: unknown; constructor(operationId: string, result: unknown); } /** * **A stream of bytes, as every platform's `ReadableStream` satisfies it.** * * The same structural type `typespec-http-zod` publishes in `requests.gen.ts` and `typespec-hono` * declares in its runtime, so a value typed by the framework-free contract can be returned from a * handler as it is. Declared here rather than imported because this file is copied into a * consumer's Worker, where the emitter packages are not installed; the agreement test holds the * declarations identical. */ export interface ByteStream { getReader(): { read(): Promise<{ readonly done: boolean; readonly value?: Uint8Array | undefined; }>; releaseLock(): void; cancel?(reason?: unknown): Promise; }; } /** * The MCP result for what a handler returned: `{ status, body, headers }` for a response the * document declares. * * **In the runtime rather than in `deps`, on the same test the sibling emitter applies**: every rule * below is published -- by the document (the arms, their bodies, their headers) or by the MCP * specification (the result shape, its content blocks, `isError`, the text mirror). An application * forced to supply this would be re-implementing two standards, and getting either wrong differently * from everybody else. * * **What is answered is the PARSED body, not the one the handler returned**, as on the HTTP surface: * a schema that strips undeclared keys strips them here too, so a field the document does not publish * does not reach a model. * * Asynchronous because a binary body may be a stream, which is read to its end before it is answered. */ export declare function toolResult(declared: ToolResponses, operationId: string, result: unknown): Promise; /** * What the emitter cannot derive from the document, and the application must answer. * * The admission test for a member is the sibling emitter's: *the generated code cannot proceed * without an answer*. Everything derivable lives above, in the runtime. * * **`C` is the caller context, and `registerTools` INFERS it from `context`.** An application whose * `context` returns a `Caller` has handlers typed `(ctx: Caller, input)`, with nothing to declare. */ export interface ToolDeps { /** * Whether the caller this server was built for may SEE this tool. * * **Consulted at REGISTRATION, not at call time.** The MCP specification says the tool set may * vary by the authorisation presented on the request, since credentials are per-request input * rather than connection state -- so the idiomatic gesture is that a caller does not see a tool * they cannot call, rather than being refused after calling it. That is a genuine divergence * from an HTTP surface, where a 403 is the right answer and middleware is the right shape. * * Receives the `security` the document publishes for the operation: satisfying ANY ONE requirement * authorises, and every scheme WITHIN a requirement must be satisfied together. An anonymous * alternative is the empty requirement `{}`, which every caller satisfies: `@useAuth(NoAuth)` is * `[{}]` and `NoAuth | BearerAuth` is `[{}, { BearerAuth: [] }]`. An operation declaring no auth * at all is `[]`. Both are facts rather than absences, because an application may still choose to * hide a public tool from an anonymous caller. * * A grant that selects nothing is not an error: nothing is registered and `tools/list` answers * with a well-formed empty list. `registerTools` returns the names it did register, which is how * an application observes that. */ readonly permits: (requirements: readonly SecurityRequirement[]) => boolean; /** * The caller's context, or `null` when there is none to establish. * * `authentication` is what the DOCUMENT says and only that, decided at generation time: * * - `"none"`: no alternative asks for anything, `@useAuth(NoAuth)` or no auth at all; * - `"optional"`: an anonymous alternative sits beside a real one, `NoAuth | BearerAuth`, so a * caller presenting a credential is recognised and one presenting none is still admitted; * - `"required"`: every alternative asks for something. * * Nothing richer is offered, because nothing richer is published -- the sibling emitter once * invented a distinction from whether a path had parameters, which no OpenAPI keyword expresses. */ readonly context: (context: ServerContext, authentication: "none" | "optional" | "required") => C | null; /** The result when {@link context} returns `null`. The application's to decide. */ readonly noContext: (context: ServerContext) => CallToolResult; /** * Which tools may answer with an MCP task, and how a task is created. Absent, no tool ever does. * * **The application's to decide, because the document cannot say it.** The Tasks extension has * no per-tool declaration: the server decides on each request whether to answer with a task. * Whether a tool's work outlives a request is a fact about where the application runs it, not * about the operation. * * **Typed by the generated `ToolCall`, so write `ToolDeps` to set it.** The * policy names operations, and only the generated module knows which exist. `ToolDeps` * names none, so it admits no operation, and wiring written before tasks existed compiles as it * did. */ readonly tasks?: ToolTasks; } /** What a tool call is, to the code that runs it later: the operation and its validated input. */ export interface ToolCallShape { readonly operationId: string; readonly input: unknown; } /** * The application's task policy for the tools one `registerTools` call registers. * * **`decide` and `create` are METHOD signatures, deliberately.** That keeps the policy covariant in * `Call`, so `ToolDeps`, which lists no operation, is still a `ToolDeps`. * With property signatures the two would be unrelated, and every wiring written before tasks existed * would stop compiling. * * **A request that did not declare the Tasks extension never reaches this policy.** It is answered * inline, as if no policy were configured, because the extension forbids answering it with a task. */ export interface ToolTasks { /** * The operations that may answer with a task. * * **Read at REGISTRATION, like `permits`**, because it changes what is published: a tool listed * here publishes no `outputSchema`. The SDK refuses a task from a tool that publishes one, so a * task tool is an ordinary tool without it, on every request. */ readonly operations: readonly Call["operationId"][]; /** * Whether THIS call becomes a task or runs inline. Consulted only for a listed operation and a * request that declared the extension. Absent, every such call becomes a task. * * Receives the validated input and the caller, so the answer can depend on the application's own * state: work that is already finished can be answered at once. * * Type `call` as the whole `ToolCall` and narrow on `operationId`: as a method, this accepts a * narrower parameter without complaint, and receives every listed operation's call regardless. */ decide?(call: Call, caller: C, context: ServerContext): Awaitable<"task" | "inline">; /** * Create the task and answer with its handle. In practice * `(call, caller, context) => tasks.create(context, { context: { ...call, ... } })`, where the * application chooses what the store needs to find or start the work: the call, an identifier * for the caller, a service name when one store serves several services. */ create(call: Call, caller: C, context: ServerContext): Promise; } /** * The result McpServer answers when a tool callback throws: the message as text, marked as an error. * * Exported so the work behind a task settles a thrown error exactly as the blocking call would have * answered it. The Tasks extension requires a tool error to complete the task with that result, * and reserves `failed` for a protocol error. */ export declare function toolError(error: unknown): CallToolResult; /** * Refuses a task policy on a server no {@link TasksExtension} is attached to. A tool there would * answer with a task the server does not advertise and nobody can poll: `tasks/get` would be an * unknown method. Called by `registerTools` when the policy lists an operation. */ export declare function requireTasksAttached(server: McpServer): void; /** * A tool's answer as the 2026-07-28 wire carries it, so as a completed task holds it: with the * `resultType: "complete"` every result of that revision carries. * * **A task's result is exactly what the call would have answered**, and McpServer adds the * discriminator to a blocking answer on its way out. A task's result reaches the client inside * `tasks/get` instead, where nothing adds it, and the Tasks extension's reference client refuses a * completed result without it. */ export declare function completed(result: CallToolResult): CallToolResult; /** * The MCP Tasks extension (`io.modelcontextprotocol/tasks`) lets a server answer `tools/call` with a * task handle, which the client polls with `tasks/get`, answers with `tasks/update` and stops with * `tasks/cancel`. * * **The declarations below have the shape of the SDK's own Tasks extension**, which is not yet in a * release. A store written against them satisfies the SDK's `TaskStore` as well, so adopting the * SDK's extension replaces one import and one `attach` call, and nothing else. */ export declare const TASKS_EXTENSION_ID = "io.modelcontextprotocol/tasks"; /** * A task's state, as every task-related message carries it. * * **A type, not an interface, and its optional members admit `undefined`**, so a task typed by the * SDK's own extension, an open object whose optional members do, is one of these and the reverse. */ export type Task = { readonly taskId: string; readonly status: "working" | "input_required" | "completed" | "cancelled" | "failed"; readonly statusMessage?: string | undefined; /** ISO 8601. */ readonly createdAt: string; /** ISO 8601. */ readonly lastUpdatedAt: string; /** Retention from creation, in milliseconds; `null` is unlimited. */ readonly ttlMs: number | null; /** How often a client should poll, in milliseconds. */ readonly pollIntervalMs?: number | undefined; }; /** A request a task makes of the client while it waits, such as `elicitation/create`. */ export type TaskInputRequest = { readonly method: string; readonly params?: Readonly> | undefined; }; /** * What `tasks/get` answers: the task, with what its status carries. * * **`completed` carries the `CallToolResult` the call would have returned, `isError` included.** * `failed` is only for a protocol error during execution, never for a tool that answered an error. */ export type DetailedTask = (Task & { readonly status: "working"; }) | (Task & { readonly status: "input_required"; readonly inputRequests: Readonly>; }) | (Task & { readonly status: "completed"; readonly result: Readonly>; }) | (Task & { readonly status: "failed"; readonly error: Readonly>; }) | (Task & { readonly status: "cancelled"; }); /** A tool's answer when its work continues as a task. */ export type CreateTaskResult = Task & { readonly resultType: "task"; }; /** The handle a tool callback returns in place of a `CallToolResult`. */ export type TaskToolResult = CallToolResult & CreateTaskResult; /** What the extension asks a store to create. */ export interface CreateTaskParams { /** Retention from creation, in milliseconds; `null` is unlimited. */ readonly ttlMs: number | null; readonly pollIntervalMs?: number; /** * The identity of the request that created the task. A store MUST refuse every later access * from a different principal, answering as for an unknown task. */ readonly principal?: string; /** The store's own: whatever its execution needs to find or start the work. */ readonly context?: Readonly>; } /** The identity presented on a `tasks/*` request. */ export interface TaskAccess { readonly principal?: string; } /** * Where tasks live and how their work is found. The extension owns the protocol; the store owns the * state, and the application owns the execution behind it: a queue, a workflow, a durable object. * * - `create` MUST NOT resolve before a following `get` would find the task. * - `get`, `update` and `cancel` answer `undefined` or `false` for a task that is unknown, expired * or another principal's, and the extension answers all three alike. * - `cancel` is cooperative and idempotent on a finished task. * - Task ids MUST be unguessable. */ export interface TaskStore { create(params: CreateTaskParams): Promise; get(taskId: string, access?: TaskAccess): Promise; update(taskId: string, inputResponses: Readonly>, access?: TaskAccess): Promise; cancel(taskId: string, access?: TaskAccess): Promise; } export interface TasksExtensionOptions { /** Retention when `create` is given none, in milliseconds; `null` is unlimited. Default 24 hours. */ readonly defaultTtlMs?: number | null; /** The polling hint when `create` is given none, in milliseconds. Default 5000. */ readonly defaultPollIntervalMs?: number; /** * The identity a task is bound to. Default: the OAuth client id, with the token subject when * the token verifier puts one at `authInfo.extra.sub`. With no authentication it is `undefined`, * and a task's id is then the only credential for it. */ readonly principal?: (context: ServerContext) => string | undefined; } export interface CreateTaskOptions { readonly ttlMs?: number | null; readonly pollIntervalMs?: number; readonly context?: Readonly>; } /** * Whether THIS request declared the Tasks extension. A task may be returned only to a request that * did, whatever an earlier request declared. */ export declare function declaresTasks(context: ServerContext): boolean; /** * Serves the Tasks extension: its capability, `tasks/get`, `tasks/update` and `tasks/cancel`, over * the {@link TaskStore} the application supplies. A tool answers with a task through * {@link TasksExtension.create}. * * One instance serves any number of servers; {@link TasksExtension.attach} each one before it * connects. Under `createMcpHandler`, which builds a server per request, create the extension * once and attach it in the factory. */ export declare class TasksExtension { #private; readonly id = "io.modelcontextprotocol/tasks"; readonly store: TaskStore; constructor(store: TaskStore, options?: TasksExtensionOptions); /** * Create a task for the current `tools/call`, bound to the caller, and return the handle the tool * answers with. Refuses with `-32021` when the request did not declare the extension. */ create(context: ServerContext, options?: CreateTaskOptions): Promise; /** * Serve the extension on `server`. Must run before it connects. Attaching this extension to the * same server again does nothing; attaching a second Tasks extension throws and leaves the server * as it was, because its `tasks/*` handlers would silently replace the first one's. */ attach(server: McpServer): void; }