From c8d762184661599a4a8abcf44749216f273c03d7 Mon Sep 17 00:00:00 2001 From: Effect Bot Date: Fri, 27 Nov 2026 01:23:22 +0000 Subject: [PATCH 1/6] test(ai): add reproduction tests for request-scoped MCP tool sources --- .../McpServer/LayerHttpRequestScoped.test.ts | 85 +++++++++++ .../test/ai/McpServer/McpServer.test.ts | 135 ++++++++++++++++++ packages/effect/typetest/ai/McpServer.tst.ts | 26 ++++ 3 files changed, 246 insertions(+) diff --git a/packages/effect/test/ai/McpServer/LayerHttpRequestScoped.test.ts b/packages/effect/test/ai/McpServer/LayerHttpRequestScoped.test.ts index f2fb320244a..48707394bf7 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,88 @@ 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..d958222a81d 100644 --- a/packages/effect/test/ai/McpServer/McpServer.test.ts +++ b/packages/effect/test/ai/McpServer/McpServer.test.ts @@ -4356,4 +4356,139 @@ 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 }] }) + + 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"] + 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.sync(() => dynamicNames.map(descriptor)), + call: (name, args) => + name === "Unknown" + ? Effect.fail(new Cause.NoSuchElementError()) + : Effect.succeed(textResult(`first:${name}:${JSON.stringify(args)}`)) + })), + 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( + ((yield* harness.sendRequest("tools/call", { name: "Search", arguments: {} })).result as any).content[0].text, + "static" + ) + assert.deepStrictEqual( + (yield* harness.sendRequest("tools/call", { name: "HiddenStatic", arguments: {} })).error, + { code: -32602, message: "Tool 'HiddenStatic' not found" } + ) + assert.strictEqual( + ((yield* harness.sendRequest("tools/call", { name: "Status", arguments: { id: 1 } })).result as any).content[0] + .text, + "first:Status:{\"id\":1}" + ) + assert.strictEqual( + ((yield* harness.sendRequest("tools/call", { name: "Logs", arguments: { id: 2 } })).result as any).content[0] + .text, + "second:Logs:{\"id\":2}" + ) + // NoSuchElementError maps to ToolNotFound without falling through to later sources. + assert.deepStrictEqual( + (yield* harness.sendRequest("tools/call", { name: "Unknown", arguments: {} })).error, + { code: -32602, message: "Tool 'Unknown' not found" } + ) + + assert.deepStrictEqual( + ((yield* harness.sendRequest("tools/list")).result as any).tools.map((t: { readonly name: string }) => t.name), + ["Search", "Deploy", "Status", "Logs"] + ) + dynamicNames = ["Deploy", "Extra"] + assert.deepStrictEqual( + ((yield* harness.sendRequest("tools/list")).result as any).tools.map((t: { readonly name: string }) => t.name), + ["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: (name) => + Effect.flatMap(CurrentUser, (user) => + name === "Invalid" + ? Effect.fail(new McpSchema.InvalidParams({ message: "Missing id" })) + : name === "Broken" + ? Effect.fail(new McpSchema.InternalError({ message: "Upstream failed" })) + : Effect.succeed(textResult(`${user}:${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( + ((yield* harness.sendRequest("tools/list")).result as any).tools.map((t: { readonly name: string }) => t.name), + ["Deploy"] + ) + assert.deepStrictEqual( + (yield* harness.sendRequest("tools/call", { name: "AdminReset", arguments: {} })).error, + { code: -32602, message: "Tool 'AdminReset' not found" } + ) + + state.user = "admin" + assert.deepStrictEqual( + ((yield* harness.sendRequest("tools/list")).result as any).tools.map((t: { readonly name: string }) => t.name), + ["Deploy", "AdminReset"] + ) + assert.strictEqual( + ((yield* harness.sendRequest("tools/call", { name: "AdminReset", arguments: {} })).result as any).content[0] + .text, + "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..556ad3535a9 100644 --- a/packages/effect/typetest/ai/McpServer.tst.ts +++ b/packages/effect/typetest/ai/McpServer.tst.ts @@ -511,4 +511,30 @@ 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: (_name: string, _args: Readonly>) => + Effect.gen(function*() { + 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() + }) + }) }) From aab40d033d5af4cc4b145a2dcb80bbc3dd526956 Mon Sep 17 00:00:00 2001 From: Effect Bot Date: Fri, 27 Nov 2026 01:42:33 +0000 Subject: [PATCH 2/6] feat(ai): support request-scoped MCP tool sources Co-authored-by: Rhys Sullivan <39114868+RhysSullivan@users.noreply.github.com> --- .changeset/mcp-tool-source.md | 5 + packages/effect/MCP.md | 39 +++ packages/effect/src/ai/McpServer.ts | 232 +++++++++++++++--- packages/effect/src/ai/internal/mcpCore.ts | 62 ++++- .../McpServer/LayerHttpRequestScoped.test.ts | 4 +- .../test/ai/McpServer/McpServer.test.ts | 45 ++-- 6 files changed, 325 insertions(+), 62 deletions(-) create mode 100644 .changeset/mcp-tool-source.md diff --git a/.changeset/mcp-tool-source.md b/.changeset/mcp-tool-source.md new file mode 100644 index 00000000000..b53bb721d26 --- /dev/null +++ b/.changeset/mcp-tool-source.md @@ -0,0 +1,5 @@ +--- +"effect": minor +--- + +Add `McpServer.toolSource` and `McpServer.registerToolSource` to resolve and invoke MCP tools per request without mutating server-wide registrations. diff --git a/packages/effect/MCP.md b/packages/effect/MCP.md index 6521080ac2c..f88fecb23c6 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 are discovered per +request or vary by caller, such as proxying an upstream MCP server with the caller's credentials. +`list` runs on every `tools/list` without caching between requests, and `call` handles +unregistered tool names accepted by `owns` (by default, all unregistered names). + +```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)) +``` + +Statically registered tools always take precedence over sourced tools (even when hidden by +visibility), and a sourced tool is listed only from the first source whose `owns` accepts its name. +Non-visibility middleware wraps `list` with `target: ""` and per-tool visibility filters the +returned tools by name. Fail `call` with `Cause.NoSuchElementError` to return unknown-tool +(`-32602`) without falling through to later sources. Because the server has no input schema at call +time, it skips argument validation and `2026-07-28` parameter-header checks; the source validates +its own inputs. + ## Request-level dependencies Some services only exist per request, such as the user a request is made for. A tool declares them diff --git a/packages/effect/src/ai/McpServer.ts b/packages/effect/src/ai/McpServer.ts index 7c4f4f0d76f..f926b165e76 100644 --- a/packages/effect/src/ai/McpServer.ts +++ b/packages/effect/src/ai/McpServer.ts @@ -356,14 +356,17 @@ 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 + * for each registration it wraps, or when it wraps a {@link toolSource}. For + * visibility checks, `target` is the tool name, the resource URI, the URI + * template or the prompt name of that registration, and `payload` is + * `undefined`. For a tool source's `list` effect, non-visibility middleware + * runs once with `target: ""` and `payload: undefined`, then visibility checks + * run per returned tool with that tool's name. `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` @@ -952,6 +955,23 @@ const makeInvoke = ( ).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 so it receives + // request services without running visibility gates against an empty target. + const invokeList = ( + handler: Effect.Effect, McpErrorBase, any>, + invocation: McpCore.McpInvocation + ): Effect.Effect, McpCore.RequestRejected> => + runMiddleware( + services.mapUnsafe.size === 0 + ? handler + : Effect.updateContext(handler, (context: Context.Context) => Context.merge(services, context)), + middlewareStack(localMiddleware, globalMiddleware).filter((fn) => !gates.has(fn)), + invocation, + { method: "tools/list", target: "", payload: undefined } + ).pipe( + catchHidden(() => Effect.succeed(Arr.empty())), + 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 +985,7 @@ const makeInvoke = ( catchHidden(() => Effect.succeed(false)) ) } - return { invoke, visible } + return { invoke, invokeList, visible } } // Applies the `EnabledWhen` annotation of a registration. @@ -981,6 +1001,39 @@ const isEnabled = (annotations: Context.Context) => { const rejectedError = (rejected: McpCore.RequestRejected) => Effect.fail(rejected.error) +const toolOutcome = (name: string, invocation: McpCore.McpInvocation) => +( + self: Effect.Effect< + CallToolResult | McpSchema.InputRequired, + InternalError | InvalidParams | Cause.NoSuchElementError | McpCore.ToolNotFound | McpCore.RequestRejected + > +): Effect.Effect< + McpCore.OperationOutcome, + | McpCore.ToolNotFound + | McpCore.InvalidToolInput + | McpCore.InvalidToolContinuation + | McpCore.ToolExecutionError + | McpCore.RequestRejected +> => + self.pipe( + Effect.catchTags({ + NoSuchElementError: () => Effect.fail(new McpCore.ToolNotFound({ name })), + 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. @@ -1267,32 +1320,7 @@ export class McpServer extends Context.Service - 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 - }) - ) - }), - Effect.map((result) => - Predicate.isTagged(result, "InputRequired") - ? McpCore.OperationOutcome.InputRequired(result) - : McpCore.OperationOutcome.Complete(result) - ) - ) + }).pipe(toolOutcome(options.tool.name, invocation)) }) yield* notifications.client["notifications/tools/list_changed"]({}) }), @@ -3692,6 +3720,140 @@ export const toolkit = , Names extends ke options?: ToolkitOptions ): Layer.Layer> => Layer.effectDiscard(registerToolkit(toolkit, options)) +/** + * The requirements of a tool source registration: services read by `list` and + * `call`, other than `McpRequestContext`, are request-level. + * + * @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` and returns the source's complete list for + * the current request; nothing is cached between requests. `call` runs for a + * `tools/call` whose name is not statically registered when `owns` accepts the + * name (by default, every unregistered name). Fail `call` with + * `Cause.NoSuchElementError` to report an unknown tool (`ToolNotFound`). + * + * @stability unstable + * @category models + * @since 4.2.0 + */ +export interface ToolSourceOptions< + EList extends McpErrorBase = never, + RList = never, + ECall extends InternalError | InvalidParams | Cause.NoSuchElementError = never, + RCall = never +> { + readonly list: Effect.Effect, EList, RList> + readonly call: ( + name: string, + payload: Readonly> + ) => Effect.Effect + readonly owns?: ((name: string) => boolean) | undefined +} + +/** + * Registers a per-request tool source with the `McpServer`. + * + * **Details** + * + * Services read by `list` and `call`, other than `McpRequestContext`, are + * request-level and must be provided by MCP middleware or the transport. + * Statically registered tools always take precedence over sourced tools, even + * when hidden by visibility. A listed tool appears only from the first source + * whose `owns` accepts its name, matching `tools/call` routing without + * requiring a preceding `tools/list`. + * + * Non-visibility middleware wraps `list` with `target: ""`, and visibility + * checks then filter each returned tool by name. Failures from `list` fail the + * `tools/list` request with their JSON-RPC error code and message. Failures + * from `call` map like `addTool`, except `Cause.NoSuchElementError` maps to + * unknown-tool (`ToolNotFound`) without falling through to later sources. + * + * The server has no input schema for a sourced tool at call time, so it skips + * argument validation and `2026-07-28` parameter-header validation; the source + * must validate its own inputs. + * + * @see {@link toolSource} for the layer-based registration wrapper + * + * @stability unstable + * @category handlers + * @since 4.2.0 + */ +export const registerToolSource = < + EList extends McpErrorBase = never, + RList = never, + ECall extends InternalError | InvalidParams | Cause.NoSuchElementError = never, + RCall = never +>( + options: ToolSourceOptions +): Effect.Effect> => + Effect.gen(function*() { + const registry = yield* McpServer + const { core, globalMiddleware } = internalState.get(registry)! + const services = yield* Effect.context() + const { invoke, invokeList, visible } = makeInvoke(services, globalMiddleware) + yield* core.tools.registerSource({ + owns: options.owns ?? (() => true), + list: (invocation) => + invokeList(options.list, invocation).pipe( + Effect.flatMap((tools) => + Effect.filter(tools, (tool) => visible("tools/list", tool.name)(invocation)).pipe( + Effect.map((visibleTools) => + visibleTools.map((tool) => + tool.title === undefined && tool.annotations?.title !== undefined + ? new McpTool({ ...tool, title: tool.annotations.title }) + : tool + ) + ) + ) + ) + ), + handle: (call, invocation) => + invoke(Effect.suspend(() => options.call(call.name, call.arguments ?? {})), invocation, { + method: "tools/call", + target: call.name, + payload: call + }).pipe(toolOutcome(call.name, invocation)) + }) + yield* registry.notifications["notifications/tools/list_changed"]({}) + }) as any + +/** + * Creates a layer that registers a per-request tool source with the + * `McpServer`. + * + * **Details** + * + * Services read by `list` and `call` are request-level, so providing them with + * `Layer.provide` doesn't satisfy them. Read construction-time services in an + * enclosing `Layer.unwrap` and close over them, and provide per-request + * services with MCP middleware. + * + * @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 = < + EList extends McpErrorBase = never, + RList = never, + ECall extends InternalError | InvalidParams | Cause.NoSuchElementError = never, + RCall = never +>( + 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..f9bbb92c04c 100644 --- a/packages/effect/src/ai/internal/mcpCore.ts +++ b/packages/effect/src/ai/internal/mcpCore.ts @@ -193,6 +193,25 @@ export interface ToolRegistration { > } +/** + * Tools resolved per request: `list` runs on every `tools/list`, and calls for + * unregistered names reach `handle` when `owns` accepts them. + * + * @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< + OperationOutcome, + ToolNotFound | InvalidToolInput | InvalidToolContinuation | ToolExecutionError | RequestRejected, + never + > +} + /** * @internal */ @@ -200,6 +219,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 +557,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() @@ -569,12 +592,45 @@ export const make: Effect.Effect = Effect.sync(() => { Effect.sync(() => { registrations.set(registration.descriptor.name, registration) }), - list: (invocation) => filterList(registrations.values(), invocation), + registerSource: (source) => + Effect.sync(() => { + toolSources.push(source) + }), + list: (invocation) => + Effect.suspend(() => { + if (toolSources.length === 0) { + return filterList(registrations.values(), invocation) + } + const sources = toolSources.slice() + return Effect.map( + Effect.all([ + filterList(registrations.values(), invocation), + Effect.forEach(sources, (source) => source.list(invocation), { concurrency: "unbounded" }) + ], { concurrency: "unbounded" }), + ([registered, sourced]) => { + // A sourced tool is listed only from the source its calls route to, + // and registered tools always take precedence (even when hidden). + const tools = Array.from(registered) + const seen = new Set() + sourced.forEach((listed, index) => { + const source = sources[index] + for (const tool of listed) { + if (registrations.has(tool.name) || seen.has(tool.name)) continue + if (sources.find((candidate) => candidate.owns(tool.name)) !== source) continue + seen.add(tool.name) + tools.push(tool) + } + }) + return tools + } + ) + }), 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 = toolSources.find((source) => source.owns(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 +774,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 48707394bf7..cf53d850bfc 100644 --- a/packages/effect/test/ai/McpServer/LayerHttpRequestScoped.test.ts +++ b/packages/effect/test/ai/McpServer/LayerHttpRequestScoped.test.ts @@ -421,7 +421,9 @@ describe("McpServer.layerHttpRequestScoped", () => { call: (name) => Effect.flatMap(CurrentCaller, (caller) => name === `${caller}_tool` - ? Effect.succeed(new McpSchema.CallToolResult({ content: [{ type: "text", text: `${caller}:${name}` }] })) + ? Effect.succeed( + new McpSchema.CallToolResult({ content: [{ type: "text", text: `${caller}:${name}` }] }) + ) : Effect.fail(new Cause.NoSuchElementError()) ) }).pipe(Layer.provide(Auth.layer)) diff --git a/packages/effect/test/ai/McpServer/McpServer.test.ts b/packages/effect/test/ai/McpServer/McpServer.test.ts index d958222a81d..dcf8651f439 100644 --- a/packages/effect/test/ai/McpServer/McpServer.test.ts +++ b/packages/effect/test/ai/McpServer/McpServer.test.ts @@ -4360,6 +4360,10 @@ describe("McpServer", () => { 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*() { @@ -4392,7 +4396,7 @@ describe("McpServer", () => { // Direct calls work without a prior list; static and hidden static never fall through. assert.strictEqual( - ((yield* harness.sendRequest("tools/call", { name: "Search", arguments: {} })).result as any).content[0].text, + callText(yield* harness.sendRequest("tools/call", { name: "Search", arguments: {} })), "static" ) assert.deepStrictEqual( @@ -4400,13 +4404,11 @@ describe("McpServer", () => { { code: -32602, message: "Tool 'HiddenStatic' not found" } ) assert.strictEqual( - ((yield* harness.sendRequest("tools/call", { name: "Status", arguments: { id: 1 } })).result as any).content[0] - .text, + callText(yield* harness.sendRequest("tools/call", { name: "Status", arguments: { id: 1 } })), "first:Status:{\"id\":1}" ) assert.strictEqual( - ((yield* harness.sendRequest("tools/call", { name: "Logs", arguments: { id: 2 } })).result as any).content[0] - .text, + 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. @@ -4415,15 +4417,19 @@ describe("McpServer", () => { { code: -32602, message: "Tool 'Unknown' not found" } ) - assert.deepStrictEqual( - ((yield* harness.sendRequest("tools/list")).result as any).tools.map((t: { readonly name: string }) => t.name), - ["Search", "Deploy", "Status", "Logs"] - ) + assert.deepStrictEqual(listedNames(yield* harness.sendRequest("tools/list")), [ + "Search", + "Deploy", + "Status", + "Logs" + ]) dynamicNames = ["Deploy", "Extra"] - assert.deepStrictEqual( - ((yield* harness.sendRequest("tools/list")).result as any).tools.map((t: { readonly name: string }) => t.name), - ["Search", "Deploy", "Extra", "Logs"] - ) + 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", () => @@ -4456,23 +4462,16 @@ describe("McpServer", () => { const initialized = yield* harness.initialize() assert.deepStrictEqual((initialized.result as any).capabilities.tools, { listChanged: true }) - assert.deepStrictEqual( - ((yield* harness.sendRequest("tools/list")).result as any).tools.map((t: { readonly name: string }) => t.name), - ["Deploy"] - ) + 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( - ((yield* harness.sendRequest("tools/list")).result as any).tools.map((t: { readonly name: string }) => t.name), - ["Deploy", "AdminReset"] - ) + assert.deepStrictEqual(listedNames(yield* harness.sendRequest("tools/list")), ["Deploy", "AdminReset"]) assert.strictEqual( - ((yield* harness.sendRequest("tools/call", { name: "AdminReset", arguments: {} })).result as any).content[0] - .text, + callText(yield* harness.sendRequest("tools/call", { name: "AdminReset", arguments: {} })), "admin:AdminReset" ) assert.deepStrictEqual( From 2a3696f0242587848fcab19da7d2f01c8af82f98 Mon Sep 17 00:00:00 2001 From: Effect Bot Date: Fri, 27 Nov 2026 02:03:51 +0000 Subject: [PATCH 3/6] refactor(ai): simplify MCP tool source internals - Route list and call through one `toolSource` lookup in mcpCore and merge source lists without the index bookkeeping. - Share the captured-services merge and the title fallback instead of repeating them, and drop the unreachable `Hidden` recovery. - Infer only the services of a tool source; its error types are fixed. - Fix the tool source tests under `pnpm check` and apply dprint. Co-authored-by: Rhys Sullivan <39114868+RhysSullivan@users.noreply.github.com> --- packages/effect/MCP.md | 3 +- packages/effect/src/ai/McpServer.ts | 136 ++++++++---------- packages/effect/src/ai/internal/mcpCore.ts | 60 ++++---- .../McpServer/LayerHttpRequestScoped.test.ts | 3 +- .../test/ai/McpServer/McpServer.test.ts | 20 +-- packages/effect/typetest/ai/McpServer.tst.ts | 9 +- 6 files changed, 102 insertions(+), 129 deletions(-) diff --git a/packages/effect/MCP.md b/packages/effect/MCP.md index f88fecb23c6..2adb0a17b1d 100644 --- a/packages/effect/MCP.md +++ b/packages/effect/MCP.md @@ -290,8 +290,7 @@ const Upstream = McpServer.toolSource({ 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()) - ) + : Effect.fail(new Cause.NoSuchElementError())) }).pipe(Layer.provide(Auth.layer)) ``` diff --git a/packages/effect/src/ai/McpServer.ts b/packages/effect/src/ai/McpServer.ts index f926b165e76..1a2c6229a2a 100644 --- a/packages/effect/src/ai/McpServer.ts +++ b/packages/effect/src/ai/McpServer.ts @@ -936,6 +936,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, @@ -946,30 +950,26 @@ 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 so it receives - // request services without running visibility gates against an empty target. + // Runs a tool source's `list` inside its middleware, which provides the + // request services. Visibility gates are left out: they have no target here, + // and check each listed tool by name instead. const invokeList = ( - handler: Effect.Effect, McpErrorBase, any>, + handler: Effect.Effect, invocation: McpCore.McpInvocation - ): Effect.Effect, McpCore.RequestRejected> => + ): Effect.Effect => runMiddleware( - services.mapUnsafe.size === 0 - ? handler - : Effect.updateContext(handler, (context: Context.Context) => Context.merge(services, context)), + provideServices(handler), middlewareStack(localMiddleware, globalMiddleware).filter((fn) => !gates.has(fn)), invocation, { method: "tools/list", target: "", payload: undefined } ).pipe( - catchHidden(() => Effect.succeed(Arr.empty())), Effect.catch((error) => error instanceof McpCore.RequestRejected ? Effect.fail(error) : rejectWith(error)) ) // On list requests only the middleware outside the innermost visibility runs. @@ -1001,20 +1001,24 @@ const isEnabled = (annotations: Context.Context) => { const rejectedError = (rejected: McpCore.RequestRejected) => Effect.fail(rejected.error) -const toolOutcome = (name: string, invocation: McpCore.McpInvocation) => -( +// The top-level title of a listed tool falls back to its annotation title. +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 }) +} + +// Maps the result of a tool handler, or of a tool source's `call`, to a core outcome. +const toolOutcome = ( self: Effect.Effect< CallToolResult | McpSchema.InputRequired, InternalError | InvalidParams | Cause.NoSuchElementError | McpCore.ToolNotFound | McpCore.RequestRejected - > -): Effect.Effect< - McpCore.OperationOutcome, - | McpCore.ToolNotFound - | McpCore.InvalidToolInput - | McpCore.InvalidToolContinuation - | McpCore.ToolExecutionError - | McpCore.RequestRejected -> => + >, + name: string, + invocation: McpCore.McpInvocation +): Effect.Effect, McpCore.ToolError> => self.pipe( Effect.catchTags({ NoSuchElementError: () => Effect.fail(new McpCore.ToolNotFound({ name })), @@ -1307,20 +1311,20 @@ export class McpServer extends Context.Service - invoke(Effect.andThen(beforeHandle, () => options.handle(call.arguments)), invocation, { - method: "tools/call", - target: call.name, - payload: call - }).pipe(toolOutcome(options.tool.name, invocation)) + toolOutcome( + invoke(Effect.andThen(beforeHandle, () => options.handle(call.arguments)), invocation, { + method: "tools/call", + target: call.name, + payload: call + }), + options.tool.name, + invocation + ) }) yield* notifications.client["notifications/tools/list_changed"]({}) }), @@ -3745,17 +3749,16 @@ export type ToolSourceRequirements = RegistrationRequirements * @category models * @since 4.2.0 */ -export interface ToolSourceOptions< - EList extends McpErrorBase = never, - RList = never, - ECall extends InternalError | InvalidParams | Cause.NoSuchElementError = never, - RCall = never -> { - readonly list: Effect.Effect, EList, RList> +export interface ToolSourceOptions { + readonly list: Effect.Effect, McpErrorBase, RList> readonly call: ( name: string, payload: Readonly> - ) => Effect.Effect + ) => Effect.Effect< + CallToolResult | McpSchema.InputRequired, + InternalError | InvalidParams | Cause.NoSuchElementError, + RCall + > readonly owns?: ((name: string) => boolean) | undefined } @@ -3787,44 +3790,33 @@ export interface ToolSourceOptions< * @category handlers * @since 4.2.0 */ -export const registerToolSource = < - EList extends McpErrorBase = never, - RList = never, - ECall extends InternalError | InvalidParams | Cause.NoSuchElementError = never, - RCall = never ->( - options: ToolSourceOptions +export const registerToolSource = ( + options: ToolSourceOptions ): Effect.Effect> => Effect.gen(function*() { const registry = yield* McpServer const { core, globalMiddleware } = internalState.get(registry)! - const services = yield* Effect.context() - const { invoke, invokeList, visible } = makeInvoke(services, globalMiddleware) + 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((tools) => - Effect.filter(tools, (tool) => visible("tools/list", tool.name)(invocation)).pipe( - Effect.map((visibleTools) => - visibleTools.map((tool) => - tool.title === undefined && tool.annotations?.title !== undefined - ? new McpTool({ ...tool, title: tool.annotations.title }) - : tool - ) - ) - ) - ) + Effect.flatMap(Effect.filter((tool) => visible("tools/list", tool.name)(invocation))), + Effect.map(Arr.map(withAnnotationTitle)) ), handle: (call, invocation) => - invoke(Effect.suspend(() => options.call(call.name, call.arguments ?? {})), invocation, { - method: "tools/call", - target: call.name, - payload: call - }).pipe(toolOutcome(call.name, invocation)) + toolOutcome( + invoke(Effect.suspend(() => options.call(call.name, call.arguments ?? {})), invocation, { + method: "tools/call", + target: call.name, + payload: call + }), + call.name, + invocation + ) }) yield* registry.notifications["notifications/tools/list_changed"]({}) - }) as any + }) /** * Creates a layer that registers a per-request tool source with the @@ -3844,15 +3836,9 @@ export const registerToolSource = < * @category layers * @since 4.2.0 */ -export const toolSource = < - EList extends McpErrorBase = never, - RList = never, - ECall extends InternalError | InvalidParams | Cause.NoSuchElementError = never, - RCall = never ->( - options: ToolSourceOptions -): Layer.Layer> => - Layer.effectDiscard(registerToolSource(options)) +export const toolSource = ( + options: ToolSourceOptions +): Layer.Layer> => Layer.effectDiscard(registerToolSource(options)) /** * Utility type that validates a completion-handler record against the allowed diff --git a/packages/effect/src/ai/internal/mcpCore.ts b/packages/effect/src/ai/internal/mcpCore.ts index f9bbb92c04c..37dbd213011 100644 --- a/packages/effect/src/ai/internal/mcpCore.ts +++ b/packages/effect/src/ai/internal/mcpCore.ts @@ -205,11 +205,7 @@ export interface ToolSourceRegistration { readonly handle: ( call: typeof McpSchema.CallTool.payloadSchema.Type, invocation: McpInvocation - ) => Effect.Effect< - OperationOutcome, - ToolNotFound | InvalidToolInput | InvalidToolContinuation | ToolExecutionError | RequestRejected, - never - > + ) => Effect.Effect, ToolError> } /** @@ -587,6 +583,9 @@ export const make: Effect.Effect = Effect.sync(() => { (entries) => entries.map((entry) => entry.descriptor) ) + // The source that calls of an unregistered tool name go to. + const toolSource = (name: string) => toolSources.find((source) => source.owns(name)) + const tools: Tools = { register: (registration) => Effect.sync(() => { @@ -596,40 +595,31 @@ export const make: Effect.Effect = Effect.sync(() => { Effect.sync(() => { toolSources.push(source) }), - list: (invocation) => - Effect.suspend(() => { - if (toolSources.length === 0) { - return filterList(registrations.values(), invocation) - } - const sources = toolSources.slice() - return Effect.map( - Effect.all([ - filterList(registrations.values(), invocation), - Effect.forEach(sources, (source) => source.list(invocation), { concurrency: "unbounded" }) - ], { concurrency: "unbounded" }), - ([registered, sourced]) => { - // A sourced tool is listed only from the source its calls route to, - // and registered tools always take precedence (even when hidden). - const tools = Array.from(registered) - const seen = new Set() - sourced.forEach((listed, index) => { - const source = sources[index] - for (const tool of listed) { - if (registrations.has(tool.name) || seen.has(tool.name)) continue - if (sources.find((candidate) => candidate.owns(tool.name)) !== source) continue - seen.add(tool.name) - tools.push(tool) - } - }) - return tools - } - ) - }), + list: (invocation) => { + const registered = filterList(registrations.values(), invocation) + if (toolSources.length === 0) { + return registered + } + return Effect.map( + Effect.all([ + registered, + // A sourced tool is listed only by the source its calls go to. A + // registered tool shadows it, even when hidden. + ...toolSources.map((source) => + Effect.map( + source.list(invocation), + (tools) => tools.filter(({ name }) => !registrations.has(name) && toolSource(name) === source) + ) + ) + ], { concurrency: "unbounded" }), + Arr.flatten + ) + }, call: (call, invocation, beforeHandle) => Effect.suspend((): Effect.Effect, ToolError> => { const registration = registrations.get(call.name) if (registration === undefined) { - const source = toolSources.find((source) => source.owns(call.name)) + const source = toolSource(call.name) return source === undefined ? new ToolNotFound({ name: call.name }) : source.handle(call, invocation) } if (!registration.isVisible(invocation.protocol)) { diff --git a/packages/effect/test/ai/McpServer/LayerHttpRequestScoped.test.ts b/packages/effect/test/ai/McpServer/LayerHttpRequestScoped.test.ts index cf53d850bfc..f29bcfe21dd 100644 --- a/packages/effect/test/ai/McpServer/LayerHttpRequestScoped.test.ts +++ b/packages/effect/test/ai/McpServer/LayerHttpRequestScoped.test.ts @@ -424,8 +424,7 @@ describe("McpServer.layerHttpRequestScoped", () => { ? Effect.succeed( new McpSchema.CallToolResult({ content: [{ type: "text", text: `${caller}:${name}` }] }) ) - : Effect.fail(new Cause.NoSuchElementError()) - ) + : Effect.fail(new Cause.NoSuchElementError())) }).pipe(Layer.provide(Auth.layer)) ) const harness = yield* makeHttpHarness( diff --git a/packages/effect/test/ai/McpServer/McpServer.test.ts b/packages/effect/test/ai/McpServer/McpServer.test.ts index dcf8651f439..89ea2b624b1 100644 --- a/packages/effect/test/ai/McpServer/McpServer.test.ts +++ b/packages/effect/test/ai/McpServer/McpServer.test.ts @@ -4446,16 +4446,16 @@ describe("McpServer", () => { list: Effect.flatMap(CurrentUser, () => state.failList ? Effect.fail(new McpSchema.InternalError({ message: "Upstream unavailable" })) - : Effect.succeed(["Deploy", "AdminReset"].map(descriptor)) - ), - call: (name) => - Effect.flatMap(CurrentUser, (user) => - name === "Invalid" - ? Effect.fail(new McpSchema.InvalidParams({ message: "Missing id" })) - : name === "Broken" - ? Effect.fail(new McpSchema.InternalError({ message: "Upstream failed" })) - : Effect.succeed(textResult(`${user}:${name}`)) - ) + : 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) diff --git a/packages/effect/typetest/ai/McpServer.tst.ts b/packages/effect/typetest/ai/McpServer.tst.ts index 556ad3535a9..cf8c9ff90d0 100644 --- a/packages/effect/typetest/ai/McpServer.tst.ts +++ b/packages/effect/typetest/ai/McpServer.tst.ts @@ -523,11 +523,10 @@ describe("McpServer", () => { yield* McpSchema.McpRequestContext return [] as ReadonlyArray }), - call: (_name: string, _args: Readonly>) => - Effect.gen(function*() { - yield* AuditLog - return hole() - }) + call: Effect.fnUntraced(function*(_name: string) { + yield* AuditLog + return hole() + }) } const registered = McpServer.registerToolSource(options) const layer = McpServer.toolSource(options) From bc35d160cfec6d7218097fac94a49ab914f14d6a Mon Sep 17 00:00:00 2001 From: Effect Bot Date: Fri, 27 Nov 2026 02:35:44 +0000 Subject: [PATCH 4/6] docs(ai): tighten MCP tool source docs, comments, and changeset --- .changeset/mcp-tool-source.md | 2 +- packages/effect/MCP.md | 22 +++---- packages/effect/src/ai/McpServer.ts | 69 +++++++++------------- packages/effect/src/ai/internal/mcpCore.ts | 7 +-- 4 files changed, 41 insertions(+), 59 deletions(-) diff --git a/.changeset/mcp-tool-source.md b/.changeset/mcp-tool-source.md index b53bb721d26..6186198abf2 100644 --- a/.changeset/mcp-tool-source.md +++ b/.changeset/mcp-tool-source.md @@ -2,4 +2,4 @@ "effect": minor --- -Add `McpServer.toolSource` and `McpServer.registerToolSource` to resolve and invoke MCP tools per request without mutating server-wide registrations. +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 2adb0a17b1d..3d663bd7bd7 100644 --- a/packages/effect/MCP.md +++ b/packages/effect/MCP.md @@ -266,10 +266,8 @@ is `false` or unset. ### Tools known per request -Use `McpServer.toolSource` (or `McpServer.registerToolSource`) when tools are discovered per -request or vary by caller, such as proxying an upstream MCP server with the caller's credentials. -`list` runs on every `tools/list` without caching between requests, and `call` handles -unregistered tool names accepted by `owns` (by default, all unregistered names). +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" @@ -294,13 +292,15 @@ const Upstream = McpServer.toolSource({ }).pipe(Layer.provide(Auth.layer)) ``` -Statically registered tools always take precedence over sourced tools (even when hidden by -visibility), and a sourced tool is listed only from the first source whose `owns` accepts its name. -Non-visibility middleware wraps `list` with `target: ""` and per-tool visibility filters the -returned tools by name. Fail `call` with `Cause.NoSuchElementError` to return unknown-tool -(`-32602`) without falling through to later sources. Because the server has no input schema at call -time, it skips argument validation and `2026-07-28` parameter-header checks; the source validates -its own inputs. +- `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. +- Non-visibility middleware wraps `list` with `target: ""`; visibility checks filter each returned + tool by name. +- Fail `call` with `Cause.NoSuchElementError` to return unknown-tool (`-32602`) without falling + through to later sources. +- Argument validation and `2026-07-28` parameter-header checks are skipped for sourced tools. ## Request-level dependencies diff --git a/packages/effect/src/ai/McpServer.ts b/packages/effect/src/ai/McpServer.ts index 1a2c6229a2a..0931aca7c75 100644 --- a/packages/effect/src/ai/McpServer.ts +++ b/packages/effect/src/ai/McpServer.ts @@ -356,17 +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 when it wraps a {@link visibility}, once - * for each registration it wraps, or when it wraps a {@link toolSource}. For - * visibility checks, `target` is the tool name, the resource URI, the URI - * template or the prompt name of that registration, and `payload` is - * `undefined`. For a tool source's `list` effect, non-visibility middleware - * runs once with `target: ""` and `payload: undefined`, then visibility checks - * run per returned tool with that tool's name. `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 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` @@ -957,9 +956,8 @@ const makeInvoke = ( ).pipe( catchHidden(() => Effect.fail(notFound(request.method, request.target) as NotFoundErrors[M])) ) as Effect.Effect - // Runs a tool source's `list` inside its middleware, which provides the - // request services. Visibility gates are left out: they have no target here, - // and check each listed tool by name instead. + // 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 @@ -1001,7 +999,6 @@ const isEnabled = (annotations: Context.Context) => { const rejectedError = (rejected: McpCore.RequestRejected) => Effect.fail(rejected.error) -// The top-level title of a listed tool falls back to its annotation title. const withAnnotationTitle = (tool: McpTool): McpTool => { const title = tool.title ?? tool.annotations?.title // Reuse a validated descriptor whose title is already resolved. @@ -1010,7 +1007,6 @@ const withAnnotationTitle = (tool: McpTool): McpTool => { : new McpTool({ ...tool, title }) } -// Maps the result of a tool handler, or of a tool source's `call`, to a core outcome. const toolOutcome = ( self: Effect.Effect< CallToolResult | McpSchema.InputRequired, @@ -3725,8 +3721,8 @@ export const toolkit = , Names extends ke ): Layer.Layer> => Layer.effectDiscard(registerToolkit(toolkit, options)) /** - * The requirements of a tool source registration: services read by `list` and - * `call`, other than `McpRequestContext`, are request-level. + * Request-level requirements of a tool source: services read by `list` and + * `call`, other than `McpRequestContext`, become `McpRequest` markers. * * @stability unstable * @category utility types @@ -3739,11 +3735,12 @@ export type ToolSourceRequirements = RegistrationRequirements * * **Details** * - * `list` runs on every `tools/list` and returns the source's complete list for - * the current request; nothing is cached between requests. `call` runs for a - * `tools/call` whose name is not statically registered when `owns` accepts the - * name (by default, every unregistered name). Fail `call` with - * `Cause.NoSuchElementError` to report an unknown tool (`ToolNotFound`). + * - `list`: runs on every `tools/list` (uncached). Failures fail the list + * request as JSON-RPC errors. + * - `call`: handles unregistered tool names accepted by `owns`. Fail with + * `Cause.NoSuchElementError` to report an unknown tool (`ToolNotFound`). + * - `owns`: selects which unregistered names this source handles (defaults to + * all). * * @stability unstable * @category models @@ -3767,22 +3764,14 @@ export interface ToolSourceOptions { * * **Details** * - * Services read by `list` and `call`, other than `McpRequestContext`, are - * request-level and must be provided by MCP middleware or the transport. - * Statically registered tools always take precedence over sourced tools, even - * when hidden by visibility. A listed tool appears only from the first source - * whose `owns` accepts its name, matching `tools/call` routing without - * requiring a preceding `tools/list`. + * 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: ""`, and visibility - * checks then filter each returned tool by name. Failures from `list` fail the - * `tools/list` request with their JSON-RPC error code and message. Failures - * from `call` map like `addTool`, except `Cause.NoSuchElementError` maps to - * unknown-tool (`ToolNotFound`) without falling through to later sources. - * - * The server has no input schema for a sourced tool at call time, so it skips - * argument validation and `2026-07-28` parameter-header validation; the source - * must validate its own inputs. + * checks filter each returned tool by name. 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 * @@ -3824,10 +3813,8 @@ export const registerToolSource = ( * * **Details** * - * Services read by `list` and `call` are request-level, so providing them with - * `Layer.provide` doesn't satisfy them. Read construction-time services in an - * enclosing `Layer.unwrap` and close over them, and provide per-request - * services with MCP middleware. + * 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 diff --git a/packages/effect/src/ai/internal/mcpCore.ts b/packages/effect/src/ai/internal/mcpCore.ts index 37dbd213011..8aaa0bd2c7c 100644 --- a/packages/effect/src/ai/internal/mcpCore.ts +++ b/packages/effect/src/ai/internal/mcpCore.ts @@ -194,9 +194,6 @@ export interface ToolRegistration { } /** - * Tools resolved per request: `list` runs on every `tools/list`, and calls for - * unregistered names reach `handle` when `owns` accepts them. - * * @internal */ export interface ToolSourceRegistration { @@ -583,7 +580,6 @@ export const make: Effect.Effect = Effect.sync(() => { (entries) => entries.map((entry) => entry.descriptor) ) - // The source that calls of an unregistered tool name go to. const toolSource = (name: string) => toolSources.find((source) => source.owns(name)) const tools: Tools = { @@ -603,8 +599,7 @@ export const make: Effect.Effect = Effect.sync(() => { return Effect.map( Effect.all([ registered, - // A sourced tool is listed only by the source its calls go to. A - // registered tool shadows it, even when hidden. + // Registered tools (even hidden) take precedence; list only tools this source owns. ...toolSources.map((source) => Effect.map( source.list(invocation), From 0e38a87d2fc53b60abc733dfaa70270dbf451363 Mon Sep 17 00:00:00 2001 From: Effect Bot Date: Fri, 27 Nov 2026 03:35:45 +0000 Subject: [PATCH 5/6] fix(ai): address MCP tool source review findings - Translate a source's `NoSuchElementError` inside the middleware boundary, so middleware sees an MCP error with code -32602 as it does for a hidden tool. - Shadow sourced tools against the registry as it was when the list started, so a tool registered during discovery is not dropped. - List each sourced name once. - Correct the middleware and visibility docs for tool source lists. Co-authored-by: Rhys Sullivan <39114868+RhysSullivan@users.noreply.github.com> --- packages/effect/MCP.md | 14 +++-- packages/effect/src/ai/McpServer.ts | 57 +++++++++++-------- packages/effect/src/ai/internal/mcpCore.ts | 12 +++- .../test/ai/McpServer/McpServer.test.ts | 27 +++++++-- 4 files changed, 74 insertions(+), 36 deletions(-) diff --git a/packages/effect/MCP.md b/packages/effect/MCP.md index 3d663bd7bd7..ee0b8f510a5 100644 --- a/packages/effect/MCP.md +++ b/packages/effect/MCP.md @@ -295,11 +295,12 @@ const Upstream = McpServer.toolSource({ - `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. -- Non-visibility middleware wraps `list` with `target: ""`; visibility checks filter each returned - tool by name. + 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. + 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 @@ -433,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 0931aca7c75..188e29f5e1d 100644 --- a/packages/effect/src/ai/McpServer.ts +++ b/packages/effect/src/ai/McpServer.ts @@ -360,12 +360,12 @@ export type MiddlewareMethod = * 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 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. + * 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` @@ -463,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) * @@ -582,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. @@ -669,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 @@ -1010,14 +1014,13 @@ const withAnnotationTitle = (tool: McpTool): McpTool => { const toolOutcome = ( self: Effect.Effect< CallToolResult | McpSchema.InputRequired, - InternalError | InvalidParams | Cause.NoSuchElementError | McpCore.ToolNotFound | McpCore.RequestRejected + InternalError | InvalidParams | McpCore.ToolNotFound | McpCore.RequestRejected >, name: string, invocation: McpCore.McpInvocation ): Effect.Effect, McpCore.ToolError> => self.pipe( Effect.catchTags({ - NoSuchElementError: () => Effect.fail(new McpCore.ToolNotFound({ name })), InternalError: (error) => Effect.fail(new McpCore.ToolExecutionError({ name, message: error.message })), InvalidParams: (error) => Effect.fail( @@ -3736,9 +3739,10 @@ export type ToolSourceRequirements = RegistrationRequirements * **Details** * * - `list`: runs on every `tools/list` (uncached). Failures fail the list - * request as JSON-RPC errors. + * 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 (`ToolNotFound`). + * `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). * @@ -3768,10 +3772,11 @@ export interface ToolSourceOptions { * 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: ""`, and visibility - * checks filter each returned tool by name. 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. + * 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 * @@ -3795,11 +3800,15 @@ export const registerToolSource = ( ), handle: (call, invocation) => toolOutcome( - invoke(Effect.suspend(() => options.call(call.name, call.arguments ?? {})), invocation, { - method: "tools/call", - target: call.name, - payload: call - }), + 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 ) diff --git a/packages/effect/src/ai/internal/mcpCore.ts b/packages/effect/src/ai/internal/mcpCore.ts index 8aaa0bd2c7c..869129c9744 100644 --- a/packages/effect/src/ai/internal/mcpCore.ts +++ b/packages/effect/src/ai/internal/mcpCore.ts @@ -596,14 +596,22 @@ export const make: Effect.Effect = Effect.sync(() => { 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, - // Registered tools (even hidden) take precedence; list only tools this source owns. ...toolSources.map((source) => Effect.map( source.list(invocation), - (tools) => tools.filter(({ name }) => !registrations.has(name) && toolSource(name) === source) + Arr.filter(({ name }) => { + if (seen.has(name) || toolSource(name) !== source) { + return false + } + seen.add(name) + return true + }) ) ) ], { concurrency: "unbounded" }), diff --git a/packages/effect/test/ai/McpServer/McpServer.test.ts b/packages/effect/test/ai/McpServer/McpServer.test.ts index 89ea2b624b1..117b40471fc 100644 --- a/packages/effect/test/ai/McpServer/McpServer.test.ts +++ b/packages/effect/test/ai/McpServer/McpServer.test.ts @@ -4369,7 +4369,12 @@ describe("McpServer", () => { 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"] + 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") })) @@ -4380,12 +4385,12 @@ describe("McpServer", () => { ), Layer.effectDiscard(McpServer.registerToolSource({ owns: (name) => name !== "Logs", - list: Effect.sync(() => dynamicNames.map(descriptor)), + 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)}`)) @@ -4411,11 +4416,13 @@ describe("McpServer", () => { 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. + // 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", @@ -4430,6 +4437,18 @@ describe("McpServer", () => { "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", () => From d673b32ce22a8c0366c392ae28599ad05ab53a13 Mon Sep 17 00:00:00 2001 From: Effect Bot Date: Sat, 28 Nov 2026 06:21:38 +0000 Subject: [PATCH 6/6] chore(changeset): mark MCP tool sources changeset as patch --- .changeset/mcp-tool-source.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/mcp-tool-source.md b/.changeset/mcp-tool-source.md index 6186198abf2..9562e45ef66 100644 --- a/.changeset/mcp-tool-source.md +++ b/.changeset/mcp-tool-source.md @@ -1,5 +1,5 @@ --- -"effect": minor +"effect": patch --- Add `McpServer.toolSource` and `McpServer.registerToolSource` for per-request MCP tool resolution and dispatch.