/** * 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 Clock from "../Clock.ts" import * as Context from "../Context.ts" import * as Digest from "../crypto/Digest.ts" import * as Data from "../Data.ts" import * as Deferred from "../Deferred.ts" import * as Duration from "../Duration.ts" import * as Effect from "../Effect.ts" import * as ErrorReporter from "../ErrorReporter.ts" import * as Exit from "../Exit.ts" import * as Fiber from "../Fiber.ts" import * as FindMyWay from "../http/FindMyWay.ts" import * as Headers from "../http/Headers.ts" import { appendPreResponseHandlerUnsafe } from "../http/HttpEffect.ts" import * as HttpRouter from "../http/HttpRouter.ts" import * as HttpServerRequest from "../http/HttpServerRequest.ts" import * as HttpServerResponse from "../http/HttpServerResponse.ts" import * as HttpTraceContext from "../http/HttpTraceContext.ts" import type * as JsonSchema from "../JsonSchema.ts" import * as Latch from "../Latch.ts" import * as Layer from "../Layer.ts" import * as Option from "../Option.ts" import * as Predicate from "../Predicate.ts" import * as PubSub from "../PubSub.ts" import * as Queue from "../Queue.ts" import * as RcMap from "../RcMap.ts" import { CurrentLogLevel, Scheduler } from "../References.ts" import * as Result from "../Result.ts" import * as Rpc from "../rpc/Rpc.ts" import * as RpcClient from "../rpc/RpcClient.ts" import type * as RpcGroup from "../rpc/RpcGroup.ts" import * as RpcMessage from "../rpc/RpcMessage.ts" import * as RpcSerialization from "../rpc/RpcSerialization.ts" import * as RpcServer from "../rpc/RpcServer.ts" import * as Schema from "../Schema.ts" import * as SchemaAST from "../SchemaAST.ts" import * as Scope from "../Scope.ts" import type { Stdio } from "../Stdio.ts" import * as Stream from "../Stream.ts" import * as Tracer from "../Tracer.ts" import type * as Types from "../Types.ts" import * as AiError from "./AiError.ts" import * as McpCore from "./internal/mcpCore.ts" import * as McpProtocolInternal from "./internal/mcpProtocol.ts" import * as McpRuntime from "./internal/mcpRuntime.ts" import * as McpSkills from "./internal/mcpSkills.ts" import * as InternalStructuredOutput from "./internal/structured-output.ts" import type * as McpProtocol from "./McpProtocol.ts" import * as McpSchema from "./McpSchema.ts" import { CallToolResult, ElicitationDeclined, EnabledWhen, GetPromptResult, InternalError, InvalidParams, InvalidRequest, isParam, McpRequestContext, McpServerClient, McpServerClientMiddleware, MethodNotFound, Prompt, Resource, ResourceTemplate, ServerNotificationRpcs, TextContent, Tool as McpTool, ToolJson } from "./McpSchema.ts" import type { CallTool, ClientCapabilities, Complete, CompleteResult, GetPrompt, McpErrorBase, Param, PromptArgument, 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"] interface QueuedServerNotification { readonly notification: McpCore.ServerNotification listChangeRevision?: number | undefined readonly targetClientId?: number | undefined readonly delivered: Deferred.Deferred readonly requestContext?: McpRequestContext["Service"] | undefined readonly requestHeaders?: Headers.Headers | undefined readonly requestLiveness?: { active: boolean } | undefined } const internalState = new WeakMap readonly notificationDelivery: { consumers: number; listChangeRevision: number; requestEndpoints: number } readonly globalMiddleware: Array> }>() // Request-scoped HTTP servers deliver a request's own notifications through // that request's server instead of the shared notification queue. const RequestNotificationQueue = Context.Reference | undefined>( "effect/ai/McpServer/RequestNotificationQueue", { defaultValue: () => undefined } ) const RequestLiveness = Context.Reference<{ active: boolean } | undefined>( "effect/ai/McpServer/RequestLiveness", { defaultValue: () => undefined } ) // Progress and logs belong to the request that emitted them. const isRequestNotification = (notification: McpCore.ServerNotification) => notification._tag === "Progress" || notification._tag === "LoggingMessage" type ServerExtensions = NonNullable type ServerNotificationRequest< R extends Rpc.Any = RpcGroup.Rpcs > = R extends Rpc.Any ? RpcMessage.Request : never const BroadcastServerNotificationRpcs = ServerNotificationRpcs.omit("notifications/elicitation/complete") const isLoggingLevel = Schema.is(McpSchema.LoggingLevel) const toInternalServerNotification = ( message: ServerNotificationRequest ): McpCore.ServerNotification | undefined => { switch (message.tag) { case "notifications/cancelled": return McpCore.ServerNotification.Cancelled({ requestId: message.payload.requestId, reason: message.payload.reason, metadata: message.payload._meta }) case "notifications/progress": return McpCore.ServerNotification.Progress({ progressToken: message.payload.progressToken, progress: message.payload.progress, total: message.payload.total, message: message.payload.message, metadata: message.payload._meta }) case "notifications/message": return McpCore.ServerNotification.LoggingMessage({ level: message.payload.level, logger: message.payload.logger, data: message.payload.data, metadata: message.payload._meta }) case "notifications/resources/updated": return McpCore.ServerNotification.ResourceUpdated({ uri: message.payload.uri, metadata: message.payload._meta }) case "notifications/resources/list_changed": return McpCore.ServerNotification.ResourcesChanged({ metadata: message.payload?._meta }) case "notifications/tools/list_changed": return McpCore.ServerNotification.ToolsChanged({ metadata: message.payload?._meta }) case "notifications/prompts/list_changed": return McpCore.ServerNotification.PromptsChanged({ metadata: message.payload?._meta }) default: return undefined } } const middlewareKeyPrefix = "effect/ai/McpServer/Middleware-" // Do not capture request services or middleware stacks at registration. const requestServiceKeys = new Set([ McpRequestContext.key, McpServerClient.key, HttpServerRequest.HttpServerRequest.key, HttpServerRequest.ParsedSearchParams.key, HttpRouter.RouteContext.key, CurrentLogLevel.key, Scope.Scope.key, Tracer.ParentSpan.key ]) const omitRequestServices = (context: Context.Context): Context.Context => { const services = new Map() for (const [key, value] of context.mapUnsafe) { if (!requestServiceKeys.has(key) && !key.startsWith(middlewareKeyPrefix)) { services.set(key, value) } } return Context.makeUnsafe(services) } const provideInvocationContext = ( effect: Effect.Effect, invocation: McpCore.McpInvocation ): Effect.Effect> => { let provided = Effect.provideService(effect, McpRequestContext, invocation.requestContext) const requestMetadata = invocation.requestContext.requestMetadata const logLevel = Predicate.hasProperty(requestMetadata, "io.modelcontextprotocol/logLevel") ? requestMetadata["io.modelcontextprotocol/logLevel"] : undefined if (isLoggingLevel(logLevel)) { provided = Effect.provideService( provided, CurrentLogLevel, McpProtocolInternal.mcpLogLevels[logLevel].effect ) } return (invocation.serverClient === undefined ? provided : Effect.provideService(provided, McpServerClient, invocation.serverClient)) as Effect.Effect< A, E, Exclude > } // ----------------------------------------------------------------------------- // Request-level dependencies // ----------------------------------------------------------------------------- /** * Marks a request-level dependency of an MCP registration or middleware. * * **Details** * * Registrations carry handler dependencies as `McpRequest<"Requires", S>`. * MCP middleware and transports discharge these markers; providing `S` with * `Layer.provide` or `Effect.provide` does not. * * `layerHttp` and `layerHttpRequestScoped` convert the markers they don't * discharge into `HttpRouter.Request` markers, so `HttpRouter.middleware` can * satisfy them. On stdio and custom transports an undischarged marker is a * compile error. * * @see {@link middleware} for discharging request-level dependencies * * @stability unstable * @category utility types * @since 4.0.0 */ export interface McpRequest { readonly _: unique symbol readonly kind: Kind readonly type: T } /** * Helper types for `McpRequest` markers. * * @stability unstable * @category utility types * @since 4.0.0 */ export declare namespace McpRequest { /** * Wraps each member of a union in an `McpRequest` marker of the supplied kind. * * @stability unstable * @category utility types * @since 4.0.0 */ export type From = R extends infer T ? McpRequest : never /** * Extracts the services from `McpRequest` markers of the supplied kind. * * @stability unstable * @category utility types * @since 4.0.0 */ export type Only = A extends McpRequest ? T : never /** * Removes `McpRequest` markers from a union. * * @stability unstable * @category utility types * @since 4.0.0 */ export type Without = A extends McpRequest ? never : A } /** * Opaque handler result. Middleware can wrap execution and provide services, * but cannot inspect or replace the result. * * @stability unstable * @category middleware * @since 4.0.0 */ export interface MiddlewareSuccess { readonly _: unique symbol } /** * The request methods that run MCP middleware. More methods may be added, so * don't `switch` on it exhaustively without a default case. * * @stability unstable * @category middleware * @since 4.0.0 */ export type MiddlewareMethod = | "tools/call" | "resources/read" | "prompts/get" | "completion/complete" | "tools/list" | "resources/list" | "resources/templates/list" | "prompts/list" | "skills/list" | "skills/get" | "resources/directory/read" /** * Request metadata passed to MCP middleware. * * **Details** * * `target` is the tool name, the requested resource URI, or the prompt name. * For `completion/complete` it is the prompt name, or the URI template of the * resource template being completed. For `skills/get` it is the URI of the * skill's `SKILL.md`. `payload` holds the request parameters. * * On list requests, middleware runs only when it wraps a {@link visibility}, * once for each registration it wraps. `target` is then the tool name, the * resource URI, the URI template or the prompt name of that registration, and * `payload` is `undefined`. `skills/list` and `resources/directory/read` are * list requests whose `target` is the `SKILL.md` URI of each skill; a * directory read checks only the skills that have the directory. A skill's * files are resources, checked as `resources/list` and `resources/read` with * their own URIs. * * `headers` are the HTTP request headers. They are empty on stdio, on custom * transports and for in-process calls. `sessionId` is the `Mcp-Session-Id` * header, so it is `undefined` outside sessionful HTTP. * * @stability unstable * @category middleware * @since 4.0.0 */ export interface MiddlewareOptions { readonly method: MiddlewareMethod readonly target: string readonly payload: unknown readonly requestContext: McpRequestContext["Service"] readonly headers: Headers.Headers readonly sessionId: string | undefined } const MiddlewareTypeId = "~effect/ai/McpServer/Middleware" type MiddlewareConfig = { provides: any error: McpErrorBase requires: any layerError: any layerRequires: any } type MiddlewareLayer = Layer.Layer< McpRequest.From<"Requires", Config["provides"]>, Config["layerError"], R | Config["layerRequires"] | McpRequest.From<"Requires", Config["requires"]> > /** * Composable MCP middleware. * * **Details** * * Provide `layer` to registration layers, or to the Effect form of a * registration, to run the middleware for those registrations. Use * `layerGlobal` to run it for every request on the server. * * Services the middleware reads per request are `McpRequest<"Requires", S>` * requirements of `layer` and `layerGlobal`, like the request-level * dependencies of a registration. A middleware that provides `S` meets them * when it runs outside this one: `a.combine(b)` runs `b` outside `a`, and so * does providing `b.layer` or `b.layerGlobal` outside `a.layer`, though * `layerGlobal` installs `b` for the whole server. The transport discharges * the services it supplies, and `layerHttp` turns the rest into * `HttpRouter.Request` requirements that an `HttpRouter.middleware` can meet. * * @see {@link middleware} for creating MCP middleware * * @stability unstable * @category middleware * @since 4.0.0 */ export interface Middleware { readonly [MiddlewareTypeId]: Config readonly layer: MiddlewareLayer readonly layerGlobal: MiddlewareLayer readonly combine: (other: Middleware) => Middleware<{ provides: Config2["provides"] | Config["provides"] error: Config2["error"] | Config["error"] requires: Exclude | Config2["requires"] layerError: Config["layerError"] | Config2["layerError"] layerRequires: Config["layerRequires"] | Config2["layerRequires"] }> } /** * Creates MCP middleware that runs around `tools/call`, `resources/read`, * `prompts/get` and `completion/complete` requests. * * **Details** * * Middleware is how request-level dependencies are satisfied: declare the * services it provides with `middleware<{ provides: S }>()` and provide them to * the handler effect. It receives the request headers, session id and request * context, so it can resolve the current user per request. * * Pass a function, or an Effect that builds the function. Services the Effect * reads are requirements of the middleware layer. Services the function reads * per request, other than `McpRequestContext`, are per-request requirements * of the result; see {@link Middleware} for how they are met. * * Failures must be `McpErrorBase` values. A middleware failure is sent as a * JSON-RPC error with its `code`, `message` and `data`, never as a tool * result. Pick custom codes from the implementation-defined range * (-32000 to -32019): any numeric `code` is sent as is. Defects are logged, * reported to the `ErrorReporter` and sent as `InternalError("Internal error")`. * Interruption propagates. * * Local middleware runs inside global middleware, and middleware provided both * locally and globally runs once. Middleware never runs for `initialize`. It * runs for list requests only when it wraps a {@link visibility}, so that the * visibility check can read the services it provides. * * **Example** (Resolving the current user per request) * * ```ts * import { Context, Effect, Layer, Schema } from "effect" * import { McpSchema, McpServer, Tool, Toolkit } from "effect/ai" * * class CurrentUser extends Context.Service()("CurrentUser") {} * * class Unauthorized extends Schema.Error("Unauthorized")({ * ...McpSchema.McpErrorBase.fields, * _tag: Schema.tag("Unauthorized"), * code: Schema.tag(-32001) * }) {} * * const WhoAmI = Tool.make("WhoAmI", { success: Schema.String, dependencies: [CurrentUser] }) * const Tools = Toolkit.make(WhoAmI) * * const Auth = McpServer.middleware<{ provides: CurrentUser }>()((effect, { headers }) => { * const token = headers["authorization"] * return token === undefined * ? Effect.fail(new Unauthorized({ message: "Missing credentials" })) * : Effect.provideService(effect, CurrentUser, { id: token }) * }) * * const Registrations = McpServer.toolkit(Tools).pipe( * Layer.provide(Auth.layer), * Layer.provide(Tools.toLayer({ * WhoAmI: () => Effect.map(CurrentUser, (user) => user.id) * })) * ) * ``` * * @stability unstable * @category middleware * @since 4.0.0 */ export const middleware: & middleware.Make & (() => middleware.Make< Config extends { provides: infer P } ? P : never >) = function() { if (arguments.length === 0) { return makeMiddleware as any } return makeMiddleware(arguments[0], arguments[1]) as any } /** * Types used by `middleware`. * * @stability unstable * @category middleware * @since 4.0.0 */ export declare namespace middleware { /** * The middleware function. * * @stability unstable * @category middleware * @since 4.0.0 */ export type Fn = ( effect: Effect.Effect>, options: MiddlewareOptions ) => Effect.Effect /** * The overloads of a middleware constructor. * * @stability unstable * @category middleware * @since 4.0.0 */ export type Make = { ( middleware: Effect.Effect, EX, RX>, options?: { readonly global?: Global | undefined } ): Made layerError: EX layerRequires: Exclude }> ( middleware: Fn, options?: { readonly global?: Global | undefined } ): Made layerError: never layerRequires: never }> } } /** * Creates middleware that hides registrations per request. * * **Details** * * The check runs for every registration the middleware is provided to, on list * requests and on calls, reads, gets and completions. When it returns `false` * the registration is left out of list results, and requests for it fail as if * it was not registered. * * The result is a `Middleware` and composes like one. The check receives the * same {@link MiddlewareOptions} as middleware, and services it reads per * request, other than `McpRequestContext`, are met the same way. Scope a * visibility to some tools by providing its layer to their toolkit only, or * branch on `target`. * * On a list request, the check and the middleware outside the innermost * visibility run once for each registration. Middleware inside it does not * run. A failure of that middleware or of a check fails the whole list * request. It never hides a registration. * * Unlike `EnabledWhen`, a visibility runs the middleware around it on list * requests, and middleware sees requests for hidden registrations. * * **Example** (Hiding admin tools from other users) * * ```ts * import { Context, Effect, Layer, Schema } from "effect" * import { McpServer, Tool, Toolkit } from "effect/ai" * * class CurrentUser extends Context.Service()("CurrentUser") {} * * const AdminTools = Toolkit.make(Tool.make("DeleteUser", { success: Schema.String })) * * const Auth = McpServer.middleware<{ provides: CurrentUser }>()((effect, { headers }) => * Effect.provideService(effect, CurrentUser, { isAdmin: headers["x-role"] === "admin" }) * ) * const AdminOnly = McpServer.visibility(() => Effect.map(CurrentUser, (user) => user.isAdmin)) * * const Registrations = McpServer.toolkit(AdminTools).pipe( * Layer.provide(AdminOnly.combine(Auth).layer), * Layer.provide(AdminTools.toLayer({ DeleteUser: () => Effect.succeed("deleted") })) * ) * ``` * * @see {@link middleware} for providing the services a check reads * * @stability unstable * @category middleware * @since 4.0.0 */ export const visibility: visibility.Make = (( check: AnyVisibilityCheck | Effect.Effect, options?: { readonly global?: boolean | undefined } ) => makeMiddleware(Effect.isEffect(check) ? Effect.map(check, makeGate) : makeGate(check), options)) as any /** * Types used by `visibility`. * * @stability unstable * @category middleware * @since 4.0.0 */ export declare namespace visibility { /** * The visibility check. * * @stability unstable * @category middleware * @since 4.0.0 */ export type Check = (options: MiddlewareOptions) => Effect.Effect /** * The overloads of `visibility`. * * @stability unstable * @category middleware * @since 4.0.0 */ export type Make = { ( check: Effect.Effect, EX, RX>, options?: { readonly global?: Global | undefined } ): Made layerError: EX layerRequires: Exclude }> ( check: Check, options?: { readonly global?: Global | undefined } ): Made layerError: never layerRequires: never }> } } type AnyVisibilityCheck = visibility.Check // Raised by a visibility gate. It is left out of the types because `makeInvoke` // replaces it with the not-found error of the request. It still has the shape // of an MCP error, since middleware outside the gate sees it as one. class Hidden extends Data.TaggedError("effect/ai/McpServer/Hidden")<{ readonly code: number readonly message: string }> {} const failHidden = Effect.fail( new Hidden({ code: McpSchema.INVALID_PARAMS_ERROR_CODE, message: "Not found" }) ) as Effect.Effect // Marks the middleware functions created by `visibility`. const gates = new WeakSet() const makeGate = (check: AnyVisibilityCheck): AnyMiddlewareFn => { const gate: AnyMiddlewareFn = (effect, options) => Effect.flatMap(check(options), (visible) => visible ? effect : failHidden) gates.add(gate) return gate } type Made = Global extends true ? MiddlewareLayer : Middleware type AnyMiddlewareFn = middleware.Fn class MiddlewareFn extends Context.Service()("effect/ai/McpServer/MiddlewareFn") {} const makeMiddleware = ( fn: AnyMiddlewareFn | Effect.Effect, options?: { readonly global?: boolean | undefined } ) => { const middleware = new MiddlewareImpl( Effect.isEffect(fn) ? Layer.effect(MiddlewareFn)(fn) : Layer.succeed(MiddlewareFn, fn) ) return options?.global ? middleware.layerGlobal : middleware } let middlewareId = 0 class MiddlewareImpl { readonly [MiddlewareTypeId] = {} as any readonly layer: Layer.Layer readonly layerGlobal: Layer.Layer readonly layerFn: Layer.Layer readonly dependencies: Layer.Layer | undefined constructor( layerFn: Layer.Layer, dependencies?: Layer.Layer | undefined ) { this.layerFn = layerFn this.dependencies = dependencies const contextKey = `${middlewareKeyPrefix}${++middlewareId}` this.layer = Layer.effectContext(Effect.gen(function*() { const stack: Array = [yield* MiddlewareFn] if (dependencies) { const memoMap = yield* Layer.CurrentMemoMap const scope = yield* Effect.scope stack.push(...getMiddleware(yield* Layer.buildWithMemoMap(dependencies, memoMap, scope))) } return Context.makeUnsafe(new Map([[contextKey, stack]])) })).pipe(Layer.provide(layerFn)) this.layerGlobal = Layer.effectDiscard(Effect.gen(function*() { const stack: ReadonlyArray = Context.getOrUndefinedUnsafe( yield* Effect.context(), contextKey as any )! const { globalMiddleware } = internalState.get(yield* McpServer)! yield* Effect.acquireRelease( Effect.sync(() => { globalMiddleware.push(...stack) }), () => Effect.sync(() => { for (const fn of stack) { const index = globalMiddleware.indexOf(fn) if (index !== -1) globalMiddleware.splice(index, 1) } }) ) })).pipe(Layer.provide(this.layer)) } combine(other: Middleware): Middleware { return new MiddlewareImpl( this.layerFn, this.dependencies ? Layer.provideMerge(this.dependencies, other.layer as any) : other.layer as any ) as any } } // The innermost middleware comes first. Each stack keeps its own order, and // where that leaves the order open, stacks provided further outside, which come // first in the context, run further outside. Stacks that order the same // middleware both ways have no common order, so insertion order decides. const getMiddleware = (context: Context.Context): ReadonlyArray => { // The middleware directly inside each middleware, and how many of those // directly outside it are still unplaced. const inners = new Map>() const unplacedOuters = new Map() for (const [key, stack] of context.mapUnsafe) { if (!key.startsWith(middlewareKeyPrefix)) continue for (let i = stack.length - 1; i >= 0; i--) { const fn = stack[i] if (!inners.has(fn)) { inners.set(fn, []) unplacedOuters.set(fn, 0) } const outer = stack[i + 1] if (outer !== undefined && outer !== fn) { inners.get(outer)!.push(fn) unplacedOuters.set(fn, unplacedOuters.get(fn)! + 1) } } } // Repeatedly places the first middleware with nothing left to place outside it. const outermostFirst: Array = [] while (unplacedOuters.size > 0) { let next = unplacedOuters.keys().next().value! for (const [fn, count] of unplacedOuters) { if (count === 0) { next = fn break } } unplacedOuters.delete(next) outermostFirst.push(next) for (const fn of inners.get(next)!) { const count = unplacedOuters.get(fn) if (count !== undefined) unplacedOuters.set(fn, count - 1) } } return outermostFirst.reverse() } const isMcpError = (error: unknown): error is McpErrorBase => Predicate.hasProperty(error, "code") && typeof error.code === "number" && Predicate.hasProperty(error, "message") && typeof error.message === "string" // Distinguishes handler failures from failures raised or rewritten by middleware. const HandlerFailure = Context.Reference("effect/ai/McpServer/HandlerFailure", { defaultValue: () => false }) const handlerFailure = Context.make(HandlerFailure, true) const internalError = new InternalError({ message: "Internal error" }) const rejectWith = (error: McpErrorBase) => Effect.fail(new McpCore.RequestRejected({ code: error.code, message: error.message, data: error.data, error })) type CallMethod = "tools/call" | "resources/read" | "prompts/get" | "completion/complete" | "skills/get" type ListMethod = Exclude interface NotFoundErrors { readonly "tools/call": McpCore.ToolNotFound readonly "resources/read": McpCore.ResourceNotFound readonly "prompts/get": McpCore.PromptNotFound readonly "completion/complete": InvalidParams readonly "skills/get": McpCore.SkillNotFound } const notFound = (method: CallMethod, target: string): NotFoundErrors[CallMethod] => { switch (method) { case "tools/call": return new McpCore.ToolNotFound({ name: target }) case "resources/read": return new McpCore.ResourceNotFound({ uri: target }) case "prompts/get": return new McpCore.PromptNotFound({ name: target }) case "completion/complete": return new InvalidParams({ message: "Unknown completion reference or argument" }) case "skills/get": return new McpCore.SkillNotFound({ uri: target }) } } const isHidden = (error: unknown): error is Hidden => error instanceof Hidden // Recovers a request rejected by a visibility gate. Any other cause, including // one that also holds an interrupt, is propagated unchanged. const catchHidden = (onHidden: () => Effect.Effect) => (self: Effect.Effect): Effect.Effect() => { const router = FindMyWay.make({ ignoreTrailingSlash: true, ignoreDuplicateSlashes: true, caseSensitive: true }) const add = (uri: string, value: A) => { router.on("GET", `/${uri}`, value) } const find = (uri: string) => router.find("GET", `/${uri}`) return { add, find } as const } const compileUriTemplate = (segments: TemplateStringsArray, ...schemas: ReadonlyArray) => { let routerPath = segments[0].replace(":", "::") let uriPath = segments[0] const params: Record = Object.create(null) let pathSchema = Schema.Tuple([]) as Schema.Top if (schemas.length > 0) { const arr: Array = [] for (let i = 0; i < schemas.length; i++) { const toCodecStringTree = Schema.toCodecStringTree(schemas[i]) const segment = segments[i + 1] const key = String(i) arr.push(toCodecStringTree) routerPath += `:${key}${segment.replace(":", "::")}` const schema = schemas[i] const paramName = isParam(schema) ? (schema as Param).name : `param${key}` params[paramName] = toCodecStringTree uriPath += `{${paramName}}${segment}` } pathSchema = Schema.Tuple(arr) } return { routerPath, uriPath, schema: pathSchema, params } as const } const resolveResourceContent = ( uri: string, mimeType: string | undefined, content: ReadResourceResult | string | Uint8Array ): ReadResourceResult => { if (typeof content === "string") { return { contents: [mimeType === undefined ? { uri, text: content } : { uri, mimeType, text: content }] } } else if (content instanceof Uint8Array) { return { contents: [mimeType === undefined ? { uri, blob: content } : { uri, mimeType, blob: content }] } } return content } const InvalidBatchExit = Schema.TaggedStruct("Exit", { requestId: Schema.Null, exit: Schema.TaggedStruct("Failure", { cause: Schema.Unknown }) }) const decodeInvalidBatchExit = Schema.decodeUnknownResult(InvalidBatchExit) const isProtocolVersion = (version: string): version is McpProtocol.ProtocolVersion => version === "2024-11-05" || version === "2025-03-26" || version === "2025-06-18" || version === "2025-11-25" || version === "2026-07-28"