/** * Builds Model Context Protocol (MCP) servers with Effect. * * The `McpServer` service stores the tools, resources, resource templates, * prompts, completions, and outgoing notifications exposed by a server. This * module also includes the server runner, custom protocol, * stdio, and HTTP layers, registration helpers, and APIs that let handlers ask * the connected client for structured input or read its advertised * capabilities. * * @stability unstable * @since 4.0.0 */ import * as Arr from "../Array.ts"; import * as Cause from "../Cause.ts"; import * as Context from "../Context.ts"; import * as Effect from "../Effect.ts"; import * as HttpRouter from "../http/HttpRouter.ts"; import * as Layer from "../Layer.ts"; import * as RpcClient from "../rpc/RpcClient.ts"; import type * as RpcGroup from "../rpc/RpcGroup.ts"; import * as RpcServer from "../rpc/RpcServer.ts"; import * as Schema from "../Schema.ts"; import * as Scope from "../Scope.ts"; import type { Stdio } from "../Stdio.ts"; import type * as McpProtocol from "./McpProtocol.ts"; import * as McpSchema from "./McpSchema.ts"; import { CallToolResult, ElicitationDeclined, GetPromptResult, InternalError, InvalidParams, McpRequestContext, McpServerClient, Prompt, Resource, ResourceTemplate, Tool as McpTool } from "./McpSchema.ts"; import type { CallTool, ClientCapabilities, Complete, CompleteResult, GetPrompt, McpErrorBase, Param, PromptMessage, ReadResourceResult, ServerCapabilities } from "./McpSchema.ts"; import * as Tool from "./Tool.ts"; import * as Toolkit from "./Toolkit.ts"; type CompletionContext = typeof Complete.payloadSchema.Type["context"]; type ServerExtensions = NonNullable; declare const BroadcastServerNotificationRpcs: RpcGroup.RpcGroup; declare const McpServer_base: Context.ServiceClass>; readonly notifyElicitationComplete: (options: { readonly clientId: number; readonly elicitationId: string; }) => Effect.Effect; readonly tools: ReadonlyArray<{ readonly tool: McpTool; readonly annotations: Context.Context; }>; readonly addTool: (options: { readonly tool: McpTool; readonly annotations: Context.Context; readonly handle: (payload: any) => Effect.Effect; }) => Effect.Effect; readonly callTool: (requests: typeof CallTool.payloadSchema.Type) => Effect.Effect; readonly resources: ReadonlyArray<{ readonly resource: Resource; readonly annotations: Context.Context; }>; readonly addResource: (options: { readonly resource: Resource; readonly annotations: Context.Context; readonly handle: Effect.Effect; }) => Effect.Effect; readonly resourceTemplates: ReadonlyArray<{ readonly template: ResourceTemplate; readonly annotations: Context.Context; }>; readonly addResourceTemplate: (options: { readonly template: ResourceTemplate; readonly annotations: Context.Context; readonly routerPath: string; readonly completions: Record Effect.Effect>; readonly handle: (uri: string, params: Array) => Effect.Effect; }) => Effect.Effect; readonly findResource: (uri: string) => Effect.Effect; readonly prompts: ReadonlyArray<{ readonly prompt: Prompt; readonly annotations: Context.Context; }>; readonly addPrompt: (options: { readonly prompt: Prompt; readonly annotations: Context.Context; readonly completions: Record Effect.Effect>; readonly handle: (params: Record) => Effect.Effect; }) => Effect.Effect; readonly getPromptResult: (request: typeof GetPrompt.payloadSchema.Type) => Effect.Effect; readonly completion: (complete: typeof Complete.payloadSchema.Type) => Effect.Effect; }>; /** * Service that stores and serves an MCP server's registered tools, resources, * prompts, completions, and outgoing notifications. * * **Details** * * Handlers use this service to register capabilities and resolve incoming MCP * requests. * * @stability unstable * @category services * @since 4.0.0 */ export declare class McpServer extends McpServer_base { /** * Builds an MCP server service from registered tools, prompts, resources, and completions. * * @stability unstable * @since 4.0.0 */ static readonly make: Effect.Effect<{ readonly notifications: RpcClient.RpcClient>; readonly notifyElicitationComplete: (options: { readonly clientId: number; readonly elicitationId: string; }) => Effect.Effect; readonly tools: ReadonlyArray<{ readonly tool: McpTool; readonly annotations: Context.Context; }>; readonly addTool: (options: { readonly tool: McpTool; readonly annotations: Context.Context; readonly handle: (payload: any) => Effect.Effect; }) => Effect.Effect; readonly callTool: (requests: typeof CallTool.payloadSchema.Type) => Effect.Effect; readonly resources: ReadonlyArray<{ readonly resource: Resource; readonly annotations: Context.Context; }>; readonly addResource: (options: { readonly resource: Resource; readonly annotations: Context.Context; readonly handle: Effect.Effect; }) => Effect.Effect; readonly resourceTemplates: ReadonlyArray<{ readonly template: ResourceTemplate; readonly annotations: Context.Context; }>; readonly addResourceTemplate: (options: { readonly template: ResourceTemplate; readonly annotations: Context.Context; readonly routerPath: string; readonly completions: Record Effect.Effect>; readonly handle: (uri: string, params: Array) => Effect.Effect; }) => Effect.Effect; readonly findResource: (uri: string) => Effect.Effect; readonly prompts: ReadonlyArray<{ readonly prompt: Prompt; readonly annotations: Context.Context; }>; readonly addPrompt: (options: { readonly prompt: Prompt; readonly annotations: Context.Context; readonly completions: Record Effect.Effect>; readonly handle: (params: Record) => Effect.Effect; }) => Effect.Effect; readonly getPromptResult: (request: typeof GetPrompt.payloadSchema.Type) => Effect.Effect; readonly completion: (complete: typeof Complete.payloadSchema.Type) => Effect.Effect; }, never, Scope.Scope>; /** * Layer that provides the MCP server and client services. * * @stability unstable * @since 4.0.0 */ static readonly layer: Layer.Layer; } /** * Runs an MCP server over the current `RpcServer.Protocol`. * * **Details** * * The server serves registered tools, resources, and prompts. The selected MCP * runtime handles protocol lifecycle state and determines which clients receive * queued server notifications. * * @stability unstable * @category running * @since 4.0.0 */ export declare const run: (options: { readonly name: string; readonly version: string; readonly instructions?: string | undefined; readonly description?: string | undefined; readonly websiteUrl?: string | undefined; readonly icons?: ReadonlyArray | undefined; readonly protocols: Arr.NonEmptyReadonlyArray; readonly extensions?: ServerExtensions | undefined; }) => Effect.Effect; /** * Creates a layer that starts an MCP server over an existing * `RpcServer.Protocol` and provides `McpServer`. Request handlers receive * `McpRequestContext`; initialized legacy requests additionally receive * `McpServerClient`. * * **When to use** * * Use when you already have a custom or externally provided * `RpcServer.Protocol` and want to start an MCP server as part of a layer * graph. * * **Details** * * The returned layer forks `run(options)` in the layer scope and merges * `McpServer.layer`, so registration layers can use the `McpServer` service * while the server is running. * * **Gotchas** * * Unlike `layerStdio` and `layerHttp`, this layer does not install a concrete * transport. The surrounding layer graph must provide `RpcServer.Protocol`. * * @see {@link run} for the effect form used by this layer * @see {@link layerStdio} for a stdio-backed layer that installs the MCP protocol and NDJSON-RPC serialization * @see {@link layerHttp} for an HTTP-backed layer that registers with `HttpRouter` and installs JSON-RPC serialization * * @stability unstable * @category layers * @since 4.0.0 */ export declare const layer: (options: { readonly name: string; readonly version: string; readonly instructions?: string | undefined; readonly description?: string | undefined; readonly websiteUrl?: string | undefined; readonly icons?: ReadonlyArray | undefined; readonly protocols: Arr.NonEmptyReadonlyArray; readonly extensions?: ServerExtensions | undefined; }) => Layer.Layer; /** * Creates a layer that runs an MCP server over standard input and output. * * **When to use** * * Use when an MCP client launches the server as a subprocess and communicates * through newline-delimited JSON-RPC messages. * * **Details** * * The selected protocol adapter controls the dated RPC schemas and JSON-RPC * batch policy. The layer provides `McpServer`, supplies request-scoped * `McpRequestContext` and legacy `McpServerClient` services to handlers, and * requires `Stdio`. * * @see {@link layer} for running over an existing `RpcServer.Protocol` * @see {@link layerHttp} for the single-endpoint HTTP transport * * @stability unstable * @category layers * @since 4.0.0 */ export declare const layerStdio: (options: { readonly name: string; readonly version: string; readonly instructions?: string | undefined; readonly description?: string | undefined; readonly websiteUrl?: string | undefined; readonly icons?: ReadonlyArray | undefined; readonly protocols: Arr.NonEmptyReadonlyArray; readonly extensions?: ServerExtensions | undefined; }) => Layer.Layer; /** * Registers a Streamable HTTP MCP endpoint at `options.path`. * * **When to use** * * Use to expose an MCP server through an existing `HttpRouter`. * * **Details** * * POST serves JSON-RPC and accepted notification-only requests return `202`. * Header mismatches, unsupported protocol versions, and invalid session-header * usage return JSON-RPC errors with status `400`. * Unknown modern RPC methods return a JSON-RPC method-not-found error with * status `404`. Session requests without `MCP-Protocol-Version` use the version * negotiated at initialization. Unsupported HTTP methods return `405`. * Requests with an `Origin` header are rejected unless the exact origin * appears in `allowedOrigins`; Origin-less non-browser clients * remain valid. The surrounding HTTP server remains responsible for binding * to an appropriate interface and installing authentication. * * With `allowSessionTermination`, a DELETE carrying `Mcp-Session-Id` ends that * session with `204` and interrupts its in-flight requests; later requests with * that id get `404`. DELETE validates the session and `MCP-Protocol-Version` * headers like POST. Without the option, or when only sessionless revisions * such as `v2026_07_28` are configured, DELETE returns `405`. Any caller * holding a session id can end that session, so authenticate requests in the * surrounding router. * * Set `allowSubscriptions: false` to disable `v2026_07_28` subscriptions. * Discovery advertises `listChanged: false`, and `subscriptions/listen` returns * Method not found. Request-scoped progress and logs, legacy protocols, and * default subscription behavior are unchanged. * * The layer runs one long-lived MCP server that every POST shares. For * serverless hosts where execution must belong to each request, use * `layerHttpRequestScoped` instead. * * `layerHttp` always implements the single-endpoint Streamable HTTP topology. * Using `v2024_11_05` here is a custom compatibility transport for that * revision's schema. It does not implement the historical two-endpoint * HTTP+SSE transport, GET SSE, event resumption, or session expiry. * * **Gotchas** * * This layer starts a scoped server fiber. For sharing it across Cloudflare * Workers requests, see `HttpRouter.toWebHandler` for setup and limitations. * * @see {@link layerStdio} for exposing the server over stdio * @see {@link layer} for the base MCP server layer without a transport protocol * * @stability unstable * @category layers * @since 4.0.0 */ export declare const layerHttp: (options: { readonly name: string; readonly version: string; readonly instructions?: string | undefined; readonly description?: string | undefined; readonly websiteUrl?: string | undefined; readonly icons?: ReadonlyArray | undefined; readonly path: HttpRouter.PathInput; readonly protocols: Arr.NonEmptyReadonlyArray; readonly extensions?: ServerExtensions | undefined; readonly allowedOrigins?: ReadonlyArray | undefined; readonly allowSessionTermination?: boolean | undefined; readonly allowSubscriptions?: boolean | undefined; }) => Layer.Layer; /** * Registers a request-scoped Streamable HTTP MCP endpoint at `options.path`. * * **When to use** * * Use when serving on serverless hosts such as Cloudflare Workers, where execution must * belong to the HTTP request rather than a shared long-lived server. * * **Details** * * Each POST runs its own server in the request scope, with no background * fiber, timer, or queue consumer left after the response body completes. * Only sessionless protocols such as `v2026_07_28` are accepted. Tools, * resources, prompts, completions, multi round-trip input requests, and the * request's own progress and log notifications are supported. Legacy reverse * requests through `McpServer.elicit` are not available. * * Discovery advertises `listChanged: false`, `subscriptions/listen` returns * Method not found, and DELETE returns `405`. Request-scoped clients receive * no broadcast notifications such as list changes. Those still reach clients * of a `layerHttp` endpoint sharing the same `McpServer`, and are dropped when * no such endpoint exists. Use `layerHttp` on a long-lived host for sessions, * subscriptions, or legacy reverse requests. * * HTTP admission, origin checks, and JSON-RPC errors follow `layerHttp`. * Configuring a sessionful protocol through an untyped caller fails layer * construction with `IllegalArgumentError`. * * @see {@link layerHttp} for the long-lived HTTP transport and HTTP admission policy * * @stability unstable * @category layers * @since 4.0.0 */ export declare const layerHttpRequestScoped: (options: { readonly name: string; readonly version: string; readonly instructions?: string | undefined; readonly description?: string | undefined; readonly websiteUrl?: string | undefined; readonly icons?: ReadonlyArray | undefined; readonly path: HttpRouter.PathInput; readonly protocols: Arr.NonEmptyReadonlyArray>; readonly extensions?: ServerExtensions | undefined; readonly allowedOrigins?: ReadonlyArray | undefined; }) => Layer.Layer; /** * Registers a `Toolkit` with the `McpServer`. * * @stability unstable * @category handlers * @since 4.0.0 */ export declare const registerToolkit: >(toolkit: Toolkit.Toolkit) => Effect.Effect | Exclude, McpRequestContext>>; /** * Registers an `AiToolkit` with the `McpServer`. * * @stability unstable * @category layers * @since 4.0.0 */ export declare const toolkit: >(toolkit: Toolkit.Toolkit) => Layer.Layer | Exclude, McpRequestContext>>; /** * Utility type that validates a completion-handler record against the allowed * parameter keys. * * @stability unstable * @category utility types * @since 4.0.0 */ export type ValidateCompletions = Completions & { readonly [K in keyof Completions]: K extends Keys ? (input: string, context: CompletionContext) => any : never; }; /** * Utility type that collects the services required by the handlers of a * completion-handler record, including handlers declared as optional. * * @stability unstable * @category utility types * @since 4.0.0 */ export type CompletionServices = { [K in keyof Completions]-?: NonNullable extends (...args: any) => infer Ret ? Effect.Services : never; }[keyof Completions]; /** * Completion-handler map for a resource URI template. * * **Details** * * Each schema interpolation contributes a parameter key, using an explicit * `Param` name when present or `paramN` otherwise, and each handler returns * candidate values for that parameter. * * @stability unstable * @category models * @since 4.0.0 */ export type ResourceCompletions> = { readonly [K in Extract as Schemas[K] extends Param ? Id : `param${K}`]: (input: string, context: CompletionContext) => Effect.Effect, any, any>; }; /** * Registers an MCP resource or resource template from an Effect program. * * @see {@link resource} for the layer-based resource registration wrapper * * @stability unstable * @category handlers * @since 4.0.0 */ export declare const registerResource: { /** * Registers an MCP resource or resource template from an Effect program. * * @see {@link resource} for the layer-based resource registration wrapper * * @stability unstable * @category handlers * @since 4.0.0 */ (options: { readonly uri: string; readonly name: string; readonly description?: string | undefined; readonly mimeType?: string | undefined; readonly audience?: ReadonlyArray<"user" | "assistant"> | undefined; readonly priority?: number | undefined; readonly content: Effect.Effect; readonly annotations?: Context.Context | undefined; }): Effect.Effect | McpServer>; /** * Registers an MCP resource or resource template from an Effect program. * * @see {@link resource} for the layer-based resource registration wrapper * * @stability unstable * @category handlers * @since 4.0.0 */ >(segments: TemplateStringsArray, ...schemas: Schemas): > = {}>(options: { readonly name: string; readonly description?: string | undefined; readonly mimeType?: string | undefined; readonly audience?: ReadonlyArray<"user" | "assistant"> | undefined; readonly priority?: number | undefined; readonly completion?: ValidateCompletions> | undefined; readonly content: (uri: string, ...params: { readonly [K in keyof Schemas]: Schemas[K]["Type"]; }) => Effect.Effect; readonly annotations?: Context.Context | undefined; }) => Effect.Effect, McpRequestContext> | McpServer>; }; /** * Creates a layer that registers an MCP resource or resource template. * * @see {@link registerResource} for the Effect-level resource registration API * * @stability unstable * @category layers * @since 4.0.0 */ export declare const resource: { /** * Creates a layer that registers an MCP resource or resource template. * * @see {@link registerResource} for the Effect-level resource registration API * * @stability unstable * @category layers * @since 4.0.0 */ (options: { readonly uri: string; readonly name: string; readonly description?: string | undefined; readonly mimeType?: string | undefined; readonly audience?: ReadonlyArray<"user" | "assistant"> | undefined; readonly priority?: number | undefined; readonly content: Effect.Effect; }): Layer.Layer>; /** * Creates a layer that registers an MCP resource or resource template. * * @see {@link registerResource} for the Effect-level resource registration API * * @stability unstable * @category layers * @since 4.0.0 */ >(segments: TemplateStringsArray, ...schemas: Schemas): > = {}>(options: { readonly name: string; readonly description?: string | undefined; readonly mimeType?: string | undefined; readonly audience?: ReadonlyArray<"user" | "assistant"> | undefined; readonly priority?: number | undefined; readonly completion?: ValidateCompletions> | undefined; readonly content: (uri: string, ...params: { readonly [K in keyof Schemas]: Schemas[K]["Type"]; }) => Effect.Effect; }) => Layer.Layer, McpRequestContext>>; }; /** * Registers an MCP prompt from an Effect program. * * **Details** * * Decodes parameters and encodes completion suggestions using their schemas. * String content becomes a user text message. * * @see {@link prompt} for the layer-based prompt registration wrapper * * @stability unstable * @category handlers * @since 4.0.0 */ export declare const registerPrompt: Effect.Effect, any, any>; } = {}>(options: { readonly name: string; readonly title?: string | undefined; readonly description?: string | undefined; readonly parameters?: Params | undefined; readonly completion?: ValidateCompletions> | undefined; readonly content: (params: Schema.Struct.Type) => Effect.Effect | string, E, R>; readonly annotations?: Context.Context | undefined; }) => Effect.Effect | Params[Extract]["EncodingServices"] | R | CompletionServices, McpRequestContext> | McpServer>; /** * Creates a layer that registers an MCP prompt. * * @see {@link registerPrompt} for the Effect-level prompt registration API * * @stability unstable * @category layers * @since 4.0.0 */ export declare const prompt: Effect.Effect, any, any>; } = {}>(options: { readonly name: string; readonly title?: string | undefined; readonly description?: string | undefined; readonly parameters?: Params | undefined; readonly completion?: ValidateCompletions> | undefined; readonly content: (params: Schema.Struct.Type) => Effect.Effect | string, E, R>; readonly annotations?: Context.Context | undefined; }) => Layer.Layer | Params[Extract]["EncodingServices"] | R | CompletionServices, McpRequestContext>>; /** * Collects structured input from the current MCP client and decodes the * accepted response with `schema`. * * **Details** * * Accepted content is decoded with the supplied schema, declined requests fail * with `ElicitationDeclined`, and canceled requests interrupt the effect. * * @stability unstable * @category accessors * @since 4.0.0 */ export declare const elicit: , unknown>>(options: { readonly message: string; readonly schema: S; }) => Effect.Effect; /** * Accesses the current client's capabilities. * * @stability unstable * @category accessors * @since 4.0.0 */ export declare const clientCapabilities: Effect.Effect; export {}; //# sourceMappingURL=McpServer.d.ts.map