diff --git a/.changeset/mcp-tool-source.md b/.changeset/mcp-tool-source.md new file mode 100644 index 00000000000..9562e45ef66 --- /dev/null +++ b/.changeset/mcp-tool-source.md @@ -0,0 +1,5 @@ +--- +"effect": patch +--- + +Add `McpServer.toolSource` and `McpServer.registerToolSource` for per-request MCP tool resolution and dispatch. diff --git a/packages/effect/MCP.md b/packages/effect/MCP.md index 6521080ac2c..ee0b8f510a5 100644 --- a/packages/effect/MCP.md +++ b/packages/effect/MCP.md @@ -264,6 +264,45 @@ In `tools/list`, an explicit `Tool.Destructive` value takes precedence. Otherwis `destructiveHint` is `false` when `Tool.Readonly` is `true`, and `true` when `Tool.Readonly` is `false` or unset. +### Tools known per request + +Use `McpServer.toolSource` (or `McpServer.registerToolSource`) when tools vary by caller or are +discovered per request, such as proxying an upstream MCP server. + +```typescript +import { Cause, Context, Effect, Layer } from "effect" +import { McpSchema, McpServer } from "effect/ai" + +class CurrentUser extends Context.Service()("CurrentUser") {} + +const Auth = McpServer.middleware<{ provides: CurrentUser }>()((effect, { headers }) => + Effect.provideService(effect, CurrentUser, { id: headers["x-user"] ?? "anonymous" }) +) + +const Upstream = McpServer.toolSource({ + owns: (name) => name.startsWith("upstream_"), + list: Effect.map(CurrentUser, (user) => [ + new McpSchema.Tool({ name: `upstream_${user.id}`, inputSchema: { type: "object" } }) + ]), + call: (name, args) => + Effect.flatMap(CurrentUser, (user) => + name === `upstream_${user.id}` + ? Effect.succeed(new McpSchema.CallToolResult({ content: [{ type: "text", text: JSON.stringify(args) }] })) + : Effect.fail(new Cause.NoSuchElementError())) +}).pipe(Layer.provide(Auth.layer)) +``` + +- `list` runs on every `tools/list` without caching; `call` handles unregistered names accepted by + `owns` (all unregistered names by default) without a prior list. +- Registered tools always take precedence (even when hidden), and a tool is listed only from the + first source whose `owns` accepts it, once per name. +- Non-visibility middleware wraps `list` with `target: ""`. Visibility checks then filter each + returned tool by name, and the middleware outside a check runs again for each of those tools. +- Fail `call` with `Cause.NoSuchElementError` to return unknown-tool (`-32602`) without falling + through to later sources. Middleware sees that failure as an error with code `-32602`, as it + does for a hidden tool. +- Argument validation and `2026-07-28` parameter-header checks are skipped for sourced tools. + ## Request-level dependencies Some services only exist per request, such as the user a request is made for. A tool declares them @@ -395,8 +434,9 @@ const Registrations = Layer.mergeAll( - On list requests only the middleware outside the innermost visibility runs, once for each registration, with that registration as `target` and an `undefined` `payload`. `audit.combine(adminOnly)` keeps `audit` off list requests and `adminOnly.combine(audit)` runs it - there. Middleware wrapping no visibility never runs on list requests. Cache expensive lookups, - such as resolving the user from a token, in the middleware itself. + there. Middleware wrapping no visibility never runs on list requests, except around the `list` + of a [tool source](#tools-known-per-request). Cache expensive lookups, such as resolving the + user from a token, in the middleware itself. - A failure of that middleware or of a check fails the whole list request rather than hiding anything. A global visibility makes global middleware such as authentication run on every list request, so make it succeed for anonymous clients if they should still see public registrations. diff --git a/packages/effect/src/ai/McpServer.ts b/packages/effect/src/ai/McpServer.ts index 7c4f4f0d76f..188e29f5e1d 100644 --- a/packages/effect/src/ai/McpServer.ts +++ b/packages/effect/src/ai/McpServer.ts @@ -356,14 +356,16 @@ export type MiddlewareMethod = * 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. + * On list requests, middleware runs when it wraps a {@link visibility} (once + * per registration) or a {@link toolSource}. For visibility checks, `target` + * is the tool name, resource URI, URI template, or prompt name, and `payload` + * is `undefined`. For a tool source's `list`, non-visibility middleware runs + * once with `target: ""` and `payload: undefined`, then visibility checks and + * the middleware outside them run per returned tool. `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` @@ -461,7 +463,8 @@ export interface Middleware { * 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. + * visibility check can read the services it provides, or when it is provided + * to a {@link toolSource}, around its `list`. * * **Example** (Resolving the current user per request) * @@ -580,7 +583,9 @@ export declare namespace middleware { * 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. + * request. It never hides a registration. For a {@link toolSource} they run + * once for each tool its `list` returns, after all of its other middleware + * has run once around `list`. * * Unlike `EnabledWhen`, a visibility runs the middleware around it on list * requests, and middleware sees requests for hidden registrations. @@ -667,9 +672,10 @@ export declare namespace visibility { 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. +// Raised by a visibility gate, and by a tool source that does not know a tool. +// 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 the middleware around it sees it as one. class Hidden extends Data.TaggedError("effect/ai/McpServer/Hidden")<{ readonly code: number readonly message: string @@ -933,6 +939,10 @@ const makeInvoke = ( const { localMiddleware, services } = context === undefined ? { services: Context.empty(), localMiddleware: [] } : prepareContext(context) + const provideServices = (handler: Effect.Effect): Effect.Effect => + services.mapUnsafe.size === 0 + ? handler + : Effect.updateContext(handler, (context: Context.Context) => Context.merge(services, context)) const invoke = ( handler: Effect.Effect, invocation: McpCore.McpInvocation, @@ -943,15 +953,27 @@ const makeInvoke = ( } ): Effect.Effect => runMiddleware( - services.mapUnsafe.size === 0 - ? handler - : Effect.updateContext(handler, (context: Context.Context) => Context.merge(services, context)), + provideServices(handler), middlewareStack(localMiddleware, globalMiddleware), invocation, request ).pipe( catchHidden(() => Effect.fail(notFound(request.method, request.target) as NotFoundErrors[M])) ) as Effect.Effect + // Runs a tool source's `list` inside non-visibility middleware; visibility + // gates check each returned tool by name instead of an empty target. + const invokeList = ( + handler: Effect.Effect, + invocation: McpCore.McpInvocation + ): Effect.Effect => + runMiddleware( + provideServices(handler), + middlewareStack(localMiddleware, globalMiddleware).filter((fn) => !gates.has(fn)), + invocation, + { method: "tools/list", target: "", payload: undefined } + ).pipe( + Effect.catch((error) => error instanceof McpCore.RequestRejected ? Effect.fail(error) : rejectWith(error)) + ) // On list requests only the middleware outside the innermost visibility runs. const visible = (method: ListMethod, target: string): McpCore.Visible => (invocation) => { const middleware = middlewareStack(localMiddleware, globalMiddleware) @@ -965,7 +987,7 @@ const makeInvoke = ( catchHidden(() => Effect.succeed(false)) ) } - return { invoke, visible } + return { invoke, invokeList, visible } } // Applies the `EnabledWhen` annotation of a registration. @@ -981,6 +1003,40 @@ const isEnabled = (annotations: Context.Context) => { const rejectedError = (rejected: McpCore.RequestRejected) => Effect.fail(rejected.error) +const withAnnotationTitle = (tool: McpTool): McpTool => { + const title = tool.title ?? tool.annotations?.title + // Reuse a validated descriptor whose title is already resolved. + return tool instanceof McpTool && title === tool.title + ? tool + : new McpTool({ ...tool, title }) +} + +const toolOutcome = ( + self: Effect.Effect< + CallToolResult | McpSchema.InputRequired, + InternalError | InvalidParams | McpCore.ToolNotFound | McpCore.RequestRejected + >, + name: string, + invocation: McpCore.McpInvocation +): Effect.Effect, McpCore.ToolError> => + self.pipe( + Effect.catchTags({ + InternalError: (error) => Effect.fail(new McpCore.ToolExecutionError({ name, message: error.message })), + InvalidParams: (error) => + Effect.fail( + new (invocation.requestContext.requestState === undefined && + invocation.requestContext.inputResponses === undefined + ? McpCore.InvalidToolInput + : McpCore.InvalidToolContinuation)({ name, message: error.message }) + ) + }), + Effect.map((result) => + Predicate.isTagged(result, "InputRequired") + ? McpCore.OperationOutcome.InputRequired(result) + : McpCore.OperationOutcome.Complete(result) + ) + ) + /** * Service that stores and serves an MCP server's registered tools, resources, * prompts, completions, and outgoing notifications. @@ -1254,44 +1310,19 @@ export class McpServer extends Context.Service - invoke(Effect.andThen(beforeHandle, () => options.handle(call.arguments)), invocation, { - method: "tools/call", - target: call.name, - payload: call - }).pipe( - Effect.catchTags({ - InternalError: (error) => - Effect.fail( - new McpCore.ToolExecutionError({ - name: options.tool.name, - message: error.message - }) - ), - InvalidParams: (error) => - Effect.fail( - new (invocation.requestContext.requestState === undefined && - invocation.requestContext.inputResponses === undefined - ? McpCore.InvalidToolInput - : McpCore.InvalidToolContinuation)({ - name: options.tool.name, - message: error.message - }) - ) + toolOutcome( + invoke(Effect.andThen(beforeHandle, () => options.handle(call.arguments)), invocation, { + method: "tools/call", + target: call.name, + payload: call }), - Effect.map((result) => - Predicate.isTagged(result, "InputRequired") - ? McpCore.OperationOutcome.InputRequired(result) - : McpCore.OperationOutcome.Complete(result) - ) + options.tool.name, + invocation ) }) yield* notifications.client["notifications/tools/list_changed"]({}) @@ -3692,6 +3723,119 @@ export const toolkit = , Names extends ke options?: ToolkitOptions ): Layer.Layer> => Layer.effectDiscard(registerToolkit(toolkit, options)) +/** + * Request-level requirements of a tool source: services read by `list` and + * `call`, other than `McpRequestContext`, become `McpRequest` markers. + * + * @stability unstable + * @category utility types + * @since 4.2.0 + */ +export type ToolSourceRequirements = RegistrationRequirements + +/** + * Options for {@link registerToolSource} and {@link toolSource}. + * + * **Details** + * + * - `list`: runs on every `tools/list` (uncached). Failures fail the list + * request as JSON-RPC errors. A name returned more than once is listed once. + * - `call`: handles unregistered tool names accepted by `owns`. Fail with + * `Cause.NoSuchElementError` to report an unknown tool. Middleware sees that + * failure as an error with code `-32602`, as it does for a hidden tool. + * - `owns`: selects which unregistered names this source handles (defaults to + * all). + * + * @stability unstable + * @category models + * @since 4.2.0 + */ +export interface ToolSourceOptions { + readonly list: Effect.Effect, McpErrorBase, RList> + readonly call: ( + name: string, + payload: Readonly> + ) => Effect.Effect< + CallToolResult | McpSchema.InputRequired, + InternalError | InvalidParams | Cause.NoSuchElementError, + RCall + > + readonly owns?: ((name: string) => boolean) | undefined +} + +/** + * Registers a per-request tool source with the `McpServer`. + * + * **Details** + * + * Registered tools always take precedence over sourced tools (even when + * hidden). Each listed tool appears only from the first source whose `owns` + * accepts its name, matching `tools/call` routing without a prior list. + * + * Non-visibility middleware wraps `list` with `target: ""`. Visibility checks + * then filter each returned tool by name, and the middleware outside a check + * runs again for each of those tools. Because the server has no input schema + * at call time, argument and `2026-07-28` parameter-header validation are + * skipped; the source validates its own inputs. + * + * @see {@link toolSource} for the layer-based registration wrapper + * + * @stability unstable + * @category handlers + * @since 4.2.0 + */ +export const registerToolSource = ( + options: ToolSourceOptions +): Effect.Effect> => + Effect.gen(function*() { + const registry = yield* McpServer + const { core, globalMiddleware } = internalState.get(registry)! + const { invoke, invokeList, visible } = makeInvoke(yield* Effect.context(), globalMiddleware) + yield* core.tools.registerSource({ + owns: options.owns ?? (() => true), + list: (invocation) => + invokeList(options.list, invocation).pipe( + Effect.flatMap(Effect.filter((tool) => visible("tools/list", tool.name)(invocation))), + Effect.map(Arr.map(withAnnotationTitle)) + ), + handle: (call, invocation) => + toolOutcome( + invoke( + Effect.catchTag( + Effect.suspend(() => options.call(call.name, call.arguments ?? {})), + "NoSuchElementError", + () => failHidden + ), + invocation, + { method: "tools/call", target: call.name, payload: call } + ), + call.name, + invocation + ) + }) + yield* registry.notifications["notifications/tools/list_changed"]({}) + }) + +/** + * Creates a layer that registers a per-request tool source with the + * `McpServer`. + * + * **Details** + * + * Services read by `list` and `call` are request-level; provide them with MCP + * middleware and close over construction-time services via `Layer.unwrap`. + * + * @see {@link registerToolSource} for the Effect-level registration API + * @see {@link middleware} for providing request-level dependencies + * + * @stability unstable + * @category layers + * @since 4.2.0 + */ +export const toolSource = ( + options: ToolSourceOptions +): Layer.Layer> => Layer.effectDiscard(registerToolSource(options)) + /** * Utility type that validates a completion-handler record against the allowed * parameter keys. diff --git a/packages/effect/src/ai/internal/mcpCore.ts b/packages/effect/src/ai/internal/mcpCore.ts index 643982d6121..869129c9744 100644 --- a/packages/effect/src/ai/internal/mcpCore.ts +++ b/packages/effect/src/ai/internal/mcpCore.ts @@ -193,6 +193,18 @@ export interface ToolRegistration { > } +/** + * @internal + */ +export interface ToolSourceRegistration { + readonly owns: (name: string) => boolean + readonly list: (invocation: McpInvocation) => Effect.Effect, RequestRejected> + readonly handle: ( + call: typeof McpSchema.CallTool.payloadSchema.Type, + invocation: McpInvocation + ) => Effect.Effect, ToolError> +} + /** * @internal */ @@ -200,6 +212,9 @@ export interface Tools { readonly register: ( registration: ToolRegistration ) => Effect.Effect + readonly registerSource: ( + source: ToolSourceRegistration + ) => Effect.Effect readonly list: ( invocation: McpInvocation ) => Effect.Effect, RequestRejected> @@ -535,6 +550,7 @@ const skillsOverlap = (a: string, b: string): boolean => { */ export const make: Effect.Effect = Effect.sync(() => { const registrations = new Map() + const toolSources: Array = [] const resourceRegistrations: Array = [] const resourceTemplateRegistrations: Array = [] const promptRegistrations = new Map() @@ -564,17 +580,50 @@ export const make: Effect.Effect = Effect.sync(() => { (entries) => entries.map((entry) => entry.descriptor) ) + const toolSource = (name: string) => toolSources.find((source) => source.owns(name)) + const tools: Tools = { register: (registration) => Effect.sync(() => { registrations.set(registration.descriptor.name, registration) }), - list: (invocation) => filterList(registrations.values(), invocation), + registerSource: (source) => + Effect.sync(() => { + toolSources.push(source) + }), + list: (invocation) => { + const registered = filterList(registrations.values(), invocation) + if (toolSources.length === 0) { + return registered + } + // Tools registered at this point (even hidden) take precedence over the + // sources, and each name is listed once. + const seen = new Set(registrations.keys()) + return Effect.map( + Effect.all([ + registered, + ...toolSources.map((source) => + Effect.map( + source.list(invocation), + Arr.filter(({ name }) => { + if (seen.has(name) || toolSource(name) !== source) { + return false + } + seen.add(name) + return true + }) + ) + ) + ], { concurrency: "unbounded" }), + Arr.flatten + ) + }, call: (call, invocation, beforeHandle) => Effect.suspend((): Effect.Effect, ToolError> => { const registration = registrations.get(call.name) if (registration === undefined) { - return new ToolNotFound({ name: call.name }) + const source = toolSource(call.name) + return source === undefined ? new ToolNotFound({ name: call.name }) : source.handle(call, invocation) } if (!registration.isVisible(invocation.protocol)) { return new ToolNotFound({ name: call.name }) @@ -718,7 +767,7 @@ export const make: Effect.Effect = Effect.sync(() => { } const registrationPresence = Effect.sync(() => ({ - tools: registrations.size > 0, + tools: registrations.size > 0 || toolSources.length > 0, resources: resourceRegistrations.length > 0 || resourceTemplateRegistrations.length > 0, prompts: promptRegistrations.size > 0, skills: skillRegistrations.size > 0 diff --git a/packages/effect/test/ai/McpServer/LayerHttpRequestScoped.test.ts b/packages/effect/test/ai/McpServer/LayerHttpRequestScoped.test.ts index f2fb320244a..f29bcfe21dd 100644 --- a/packages/effect/test/ai/McpServer/LayerHttpRequestScoped.test.ts +++ b/packages/effect/test/ai/McpServer/LayerHttpRequestScoped.test.ts @@ -4,6 +4,7 @@ import * as McpSchema from "effect/ai/McpSchema" import * as McpServer from "effect/ai/McpServer" import * as Tool from "effect/ai/Tool" import * as Toolkit from "effect/ai/Toolkit" +import * as Cause from "effect/Cause" import * as Context from "effect/Context" import * as Deferred from "effect/Deferred" import * as Effect from "effect/Effect" @@ -394,4 +395,89 @@ describe("McpServer.layerHttpRequestScoped", () => { ], path) } }).pipe(Effect.timeout("2 seconds"))) + + it.live("lists and calls caller-specific tools from a tool source across overlapping requests", () => + Effect.gen(function*() { + class CurrentCaller extends Context.Service()("test/RequestScoped/CurrentCaller") {} + const Auth = McpServer.middleware<{ provides: CurrentCaller }>()((effect, { headers }) => + Effect.provideService(effect, CurrentCaller, String(headers["x-caller"] ?? "anonymous")) + ) + const arrived = { alice: yield* Deferred.make(), bob: yield* Deferred.make() } + const StaticTools = Toolkit.make(Tool.make("Static", { success: Schema.String })) + const registrations = Layer.mergeAll( + McpServer.toolkit(StaticTools).pipe( + Layer.provide(StaticTools.toLayer({ Static: () => Effect.succeed("static") })) + ), + McpServer.toolSource({ + list: Effect.gen(function*() { + const caller = yield* CurrentCaller + if (caller === "alice" || caller === "bob") { + // Hold both callers in flight so their list requests overlap. + yield* Deferred.succeed(arrived[caller], undefined) + yield* Deferred.await(arrived[caller === "alice" ? "bob" : "alice"]) + } + return [new McpSchema.Tool({ name: `${caller}_tool`, inputSchema: { type: "object" } })] + }), + call: (name) => + Effect.flatMap(CurrentCaller, (caller) => + name === `${caller}_tool` + ? Effect.succeed( + new McpSchema.CallToolResult({ content: [{ type: "text", text: `${caller}:${name}` }] }) + ) + : Effect.fail(new Cause.NoSuchElementError())) + }).pipe(Layer.provide(Auth.layer)) + ) + const harness = yield* makeHttpHarness( + McpServer.layerHttpRequestScoped({ + name: "PerCallerSources", + version: "1.0.0", + path: "/mcp", + protocols: [protocol], + registrations + }) + ) + const post = (caller: string, method: "tools/list" | "tools/call", params: Record = {}) => + harness.post({ + jsonrpc: "2.0", + id: 1, + method, + params: { + ...params, + _meta: { + "io.modelcontextprotocol/protocolVersion": protocol.protocolVersion, + "io.modelcontextprotocol/clientCapabilities": {}, + "io.modelcontextprotocol/clientInfo": { name: "test", version: "1.0.0" } + } + } + }, { + "MCP-Protocol-Version": protocol.protocolVersion, + "Mcp-Method": method, + ...(typeof params.name === "string" ? { "Mcp-Name": params.name } : {}), + "x-caller": caller + }).pipe( + Effect.flatMap(readMcpHttpResponse), + Effect.map((message) => message as { readonly result?: any; readonly error?: any }) + ) + + const [aliceList, bobList] = yield* Effect.all( + [post("alice", "tools/list"), post("bob", "tools/list")], + { concurrency: "unbounded" } + ) + assert.deepStrictEqual( + aliceList.result.tools.map((tool: { readonly name: string }) => tool.name), + ["Static", "alice_tool"] + ) + assert.deepStrictEqual( + bobList.result.tools.map((tool: { readonly name: string }) => tool.name), + ["Static", "bob_tool"] + ) + + // Direct call for a caller that never listed first. + const carolCall = yield* post("carol", "tools/call", { name: "carol_tool", arguments: {} }) + assert.strictEqual(carolCall.result.content[0].text, "carol:carol_tool") + + // A caller cannot invoke another caller's tool. + const crossCall = yield* post("alice", "tools/call", { name: "bob_tool", arguments: {} }) + assert.deepStrictEqual(crossCall.error, { code: -32602, message: "Tool 'bob_tool' not found" }) + }).pipe(Effect.timeout("2 seconds"))) }) diff --git a/packages/effect/test/ai/McpServer/McpServer.test.ts b/packages/effect/test/ai/McpServer/McpServer.test.ts index 02c7fd17dbb..117b40471fc 100644 --- a/packages/effect/test/ai/McpServer/McpServer.test.ts +++ b/packages/effect/test/ai/McpServer/McpServer.test.ts @@ -4356,4 +4356,157 @@ describe("McpServer", () => { assert.strictEqual(span.attributes.get("error.type"), "-32603") })) }) + + describe("toolSource", () => { + const descriptor = (name: string) => new McpSchema.Tool({ name, inputSchema: { type: "object" } }) + const textResult = (text: string) => new McpSchema.CallToolResult({ content: [{ type: "text", text }] }) + const listedNames = (message: { readonly result?: unknown }) => + (message.result as { readonly tools: ReadonlyArray<{ readonly name: string }> }).tools.map((tool) => tool.name) + const callText = (message: { readonly result?: unknown }) => + (message.result as { readonly content: ReadonlyArray<{ readonly text: string }> }).content[0].text + + it.effect("applies static precedence, owns routing, and per-request listing", () => + Effect.gen(function*() { + const StaticVisible = Toolkit.make(Tool.make("Search", { success: Schema.String })) + const StaticHidden = Toolkit.make(Tool.make("HiddenStatic", { success: Schema.String })) + let dynamicNames = ["Search", "HiddenStatic", "Deploy", "Status", "Deploy"] + let duringList: Effect.Effect = Effect.void + const failureCodes: Array = [] + const Observe = McpServer.middleware()((effect) => + Effect.tapError(effect, (error) => Effect.sync(() => failureCodes.push(error.code))) + ) + const registrations = Layer.mergeAll( + McpServer.toolkit(StaticVisible).pipe( + Layer.provide(StaticVisible.toLayer({ Search: () => Effect.succeed("static") })) + ), + McpServer.toolkit(StaticHidden).pipe( + Layer.provide(McpServer.visibility(() => Effect.succeed(false)).layer), + Layer.provide(StaticHidden.toLayer({ HiddenStatic: () => Effect.succeed("hidden") })) + ), + Layer.effectDiscard(McpServer.registerToolSource({ + owns: (name) => name !== "Logs", + list: Effect.suspend(() => Effect.as(duringList, dynamicNames.map(descriptor))), + call: (name, args) => + name === "Unknown" + ? Effect.fail(new Cause.NoSuchElementError()) + : Effect.succeed(textResult(`first:${name}:${JSON.stringify(args)}`)) + })).pipe(Layer.provide(Observe.layer)), + McpServer.toolSource({ + list: Effect.succeed(["Status", "Logs"].map(descriptor)), + call: (name, args) => Effect.succeed(textResult(`second:${name}:${JSON.stringify(args)}`)) + }) + ) + const harness = yield* makeMcpStdioHarness(McpProtocol.v2025_11_25, [McpProtocol.v2025_11_25], registrations) + yield* harness.initialize() + + // Direct calls work without a prior list; static and hidden static never fall through. + assert.strictEqual( + callText(yield* harness.sendRequest("tools/call", { name: "Search", arguments: {} })), + "static" + ) + assert.deepStrictEqual( + (yield* harness.sendRequest("tools/call", { name: "HiddenStatic", arguments: {} })).error, + { code: -32602, message: "Tool 'HiddenStatic' not found" } + ) + assert.strictEqual( + callText(yield* harness.sendRequest("tools/call", { name: "Status", arguments: { id: 1 } })), + "first:Status:{\"id\":1}" + ) + assert.strictEqual( + callText(yield* harness.sendRequest("tools/call", { name: "Logs", arguments: { id: 2 } })), + "second:Logs:{\"id\":2}" + ) + // NoSuchElementError maps to ToolNotFound without falling through to later sources, + // and reaches middleware as an MCP error. + assert.deepStrictEqual( + (yield* harness.sendRequest("tools/call", { name: "Unknown", arguments: {} })).error, + { code: -32602, message: "Tool 'Unknown' not found" } + ) + assert.deepStrictEqual(failureCodes, [-32602]) + + assert.deepStrictEqual(listedNames(yield* harness.sendRequest("tools/list")), [ + "Search", + "Deploy", + "Status", + "Logs" + ]) + dynamicNames = ["Deploy", "Extra"] + assert.deepStrictEqual(listedNames(yield* harness.sendRequest("tools/list")), [ + "Search", + "Deploy", + "Extra", + "Logs" + ]) + // A tool registered during discovery does not shadow the source in that response. + duringList = harness.server.addTool({ + tool: descriptor("Extra"), + annotations: Context.empty(), + handle: () => Effect.succeed(textResult("static")) + }) + assert.deepStrictEqual(listedNames(yield* harness.sendRequest("tools/list")), [ + "Search", + "Deploy", + "Extra", + "Logs" + ]) + })) + + it.effect("advertises tools capability, runs middleware and allowlist visibility, and maps errors", () => + Effect.gen(function*() { + class CurrentUser extends Context.Service()("test/ToolSource/CurrentUser") {} + const state = { user: "guest", failList: false } + const Auth = McpServer.middleware<{ provides: CurrentUser }>()((effect) => + Effect.provideService(effect, CurrentUser, state.user) + ) + const AllowList = McpServer.visibility(({ target }) => + Effect.map(CurrentUser, (user) => user === "admin" || target === "Deploy") + ) + const registrations = McpServer.toolSource({ + list: Effect.flatMap(CurrentUser, () => + state.failList + ? Effect.fail(new McpSchema.InternalError({ message: "Upstream unavailable" })) + : Effect.succeed(["Deploy", "AdminReset"].map(descriptor))), + call: Effect.fnUntraced(function*(name) { + if (name === "Invalid") { + return yield* new McpSchema.InvalidParams({ message: "Missing id" }) + } + if (name === "Broken") { + return yield* new McpSchema.InternalError({ message: "Upstream failed" }) + } + return textResult(`${yield* CurrentUser}:${name}`) + }) + }).pipe(Layer.provide(AllowList.combine(Auth).layer)) + + const harness = yield* makeMcpStdioHarness(McpProtocol.v2025_11_25, [McpProtocol.v2025_11_25], registrations) + const initialized = yield* harness.initialize() + assert.deepStrictEqual((initialized.result as any).capabilities.tools, { listChanged: true }) + + assert.deepStrictEqual(listedNames(yield* harness.sendRequest("tools/list")), ["Deploy"]) + assert.deepStrictEqual( + (yield* harness.sendRequest("tools/call", { name: "AdminReset", arguments: {} })).error, + { code: -32602, message: "Tool 'AdminReset' not found" } + ) + + state.user = "admin" + assert.deepStrictEqual(listedNames(yield* harness.sendRequest("tools/list")), ["Deploy", "AdminReset"]) + assert.strictEqual( + callText(yield* harness.sendRequest("tools/call", { name: "AdminReset", arguments: {} })), + "admin:AdminReset" + ) + assert.deepStrictEqual( + (yield* harness.sendRequest("tools/call", { name: "Invalid", arguments: {} })).result, + { content: [{ type: "text", text: "Missing id" }], isError: true } + ) + assert.deepStrictEqual( + (yield* harness.sendRequest("tools/call", { name: "Broken", arguments: {} })).result, + { content: [{ type: "text", text: "Upstream failed" }], isError: true } + ) + + state.failList = true + assert.deepInclude( + (yield* harness.sendRequest("tools/list")).error, + { code: -32603, message: "Upstream unavailable" } + ) + })) + }) }) diff --git a/packages/effect/typetest/ai/McpServer.tst.ts b/packages/effect/typetest/ai/McpServer.tst.ts index da9b3db45ef..cf8c9ff90d0 100644 --- a/packages/effect/typetest/ai/McpServer.tst.ts +++ b/packages/effect/typetest/ai/McpServer.tst.ts @@ -511,4 +511,29 @@ describe("McpServer", () => { expect>().type.toBe<[options: McpServer.SkillOptions]>() }) }) + + describe("toolSource", () => { + class CurrentUser extends Context.Service()("CurrentUser") {} + class AuditLog extends Context.Service void }>()("AuditLog") {} + + it("should lift list and call services to McpRequest requirements", () => { + const options = { + list: Effect.gen(function*() { + yield* CurrentUser + yield* McpSchema.McpRequestContext + return [] as ReadonlyArray + }), + call: Effect.fnUntraced(function*(_name: string) { + yield* AuditLog + return hole() + }) + } + const registered = McpServer.registerToolSource(options) + const layer = McpServer.toolSource(options) + type Requirements = McpServer.McpServer | Requires | Requires + + expect>().type.toBe() + expect>().type.toBe() + }) + }) })