From 269a66ada0ce08a899b9ff77ff1e07be59375fb5 Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Mon, 16 Nov 2026 22:10:24 -0800 Subject: [PATCH] fix(core): reuse session-owned MCP tool catalogs across steps --- packages/core/src/mcp/index.ts | 32 +++- packages/core/src/tool.ts | 202 +++++++++++------------ packages/core/src/tool/mcp.ts | 18 +- packages/core/test/mcp-attach.test.ts | 70 ++++++++ packages/core/test/tool-registry.test.ts | 35 ++++ 5 files changed, 239 insertions(+), 118 deletions(-) diff --git a/packages/core/src/mcp/index.ts b/packages/core/src/mcp/index.ts index 23565723951..74b0a303c4b 100644 --- a/packages/core/src/mcp/index.ts +++ b/packages/core/src/mcp/index.ts @@ -123,6 +123,25 @@ type AttachedEntry = { tools: ReadonlyArray } +class SessionClients extends Map { + #sources: ReadonlyArray> = [] + #tools: ReadonlyArray = [] + + tools() { + if ( + this.size === this.#sources.length && + this.values().every((stack, i) => stack.at(-1)?.tools === this.#sources[i]) + ) + return this.#tools + this.#sources = Array.from(this.values(), (stack) => stack.at(-1)!.tools) + const tools = this.#sources.flat() + // Calls resolve the current connection by owner and name, so an identical re-list or + // replacement connection needs no new tool definitions. + if (!isDeepStrictEqual(this.#tools, tools)) this.#tools = tools + return this.#tools + } +} + // How long a model call may wait for a server that is still connecting, counted from when it began. const STARTUP_GRACE_MS = 2_000 @@ -173,8 +192,8 @@ export interface Interface extends State.Transformable { transport: Transport, owner?: Session.ID, ) => Effect.Effect - /** Only the client's tools owned by this session, never the Location catalog. */ - readonly sessionTools: (owner: Session.ID) => Effect.Effect + /** Only this owner's client tools. A nonempty list keeps its identity until its contents change. */ + readonly sessionTools: (owner: Session.ID) => Effect.Effect> readonly tools: () => Effect.Effect /** * Waits for servers that are still connecting, each until it settles or until its startup grace @@ -286,7 +305,7 @@ export const layer = (options?: Options) => const entries = new Map() const attached = new Map() - const owned = new Map>() + const owned = new Map() // Serializes lifecycle operations per server. Anything taking this lock from a connection // callback must stay forked: lifecycle operations close scopes while holding it, firing onClose. const locks = KeyedMutex.makeUnsafe() @@ -809,8 +828,8 @@ export const layer = (options?: Options) => return yield* new McpClient.ConnectError({ server: name, message: "Connection closed" }) } const entry: AttachedEntry = { scope, client: result.connection, tools: toAttachedTools(name, result.tools) } - const group = owner ? (owned.get(owner) ?? new Map()) : attached - if (owner) owned.set(owner, group) + if (owner && !owned.has(owner)) owned.set(owner, new SessionClients()) + const group = owner ? owned.get(owner)! : attached group.set(name, [...(group.get(name) ?? []), entry]) const locked = (effect: Effect.Effect) => fork(effect.pipe(attachedLocks.withLock(key), Effect.ignore)) @@ -976,8 +995,7 @@ export const layer = (options?: Options) => attach: Effect.fn("MCP.attach")(function* (client, transport, owner) { yield* attach(ServerName.make(client), transport, owner) }), - sessionTools: (owner) => - Effect.sync(() => Array.from(owned.get(owner)?.values() ?? []).flatMap((stack) => stack.at(-1)?.tools ?? [])), + sessionTools: (owner) => Effect.sync(() => owned.get(owner)?.tools() ?? []), // Reads report what is connected now; servers still starting contribute once they publish a change. tools: Effect.fn("MCP.tools")(function* () { const clients = Array.from(attached.values()).flatMap((stack) => stack.at(-1)?.tools ?? []) diff --git a/packages/core/src/tool.ts b/packages/core/src/tool.ts index e9dab417a54..31f8e7c865e 100644 --- a/packages/core/src/tool.ts +++ b/packages/core/src/tool.ts @@ -39,8 +39,12 @@ type Data = { definitions: Map namespaces: Map errors: { kind: "tool" | "namespace"; name: string; namespace?: string; error: RegistrationError }[] + catalog?: { names: string; tool: Tool.Info; value: CodeModeCatalog.Inventory; definition: ToolDefinition } } +// A new base registry starts with no overlays; detaching an owner releases its weak key. +type Base = Data & { overlays: WeakMap, Data> } + export interface Interface extends State.Transformable { readonly list: () => Effect.Effect> readonly snapshot: (permissions?: Permission.Ruleset, overlay?: ReadonlyArray) => Effect.Effect @@ -195,22 +199,14 @@ const layer = Layer.effect( return yield* executeTool(selected, event.tool, event.input, context) }) - let catalog: - | { - data: Data - names: string - inventory: CodeModeTool.Inventory - value: CodeModeCatalog.Inventory - definition: ToolDefinition - } - | undefined - const state = State.create({ + const state = State.create({ name: "tool", initial: () => ({ tools: new Map(), definitions: new Map(), namespaces: new Map(), errors: [], + overlays: new WeakMap(), }), editor: (editor) => ({ list: () => Array.from(editor.tools.values()), @@ -223,10 +219,7 @@ const layer = Layer.effect( } editor.namespaces.set(namespace.name, { ...namespace }) }, - add: (tool) => { - const id = effectiveName(tool) - commit(editor, id, { ...tool, id, options: tool.options && { ...tool.options } }) - }, + add: (tool) => add(editor, tool), update: (id, update) => { const current = editor.tools.get(id) if (!current) return @@ -243,106 +236,87 @@ const layer = Layer.effect( editor.definitions.delete(id) }, }), - notify: (value) => { - catalog = undefined - return Effect.forEach( - value.errors, - ({ kind, name, namespace, error }) => - Effect.logError(`Skipping invalid ${kind} registration`, { - name, - namespace, - error: error.message, - }), - { discard: true }, - ) - }, + notify: reportErrors, }) + const withOverlay = Effect.fnUntraced(function* (base: Base, overlay: ReadonlyArray) { + const cached = base.overlays.get(overlay) + if (cached) return cached + const data: Data = { + tools: new Map(base.tools), + definitions: new Map(base.definitions), + namespaces: base.namespaces, + errors: [], + } + for (const tool of overlay) add(data, tool) + base.overlays.set(overlay, data) + yield* reportErrors(data) + return data + }) + + const catalogFor = (data: Data, visible: string[]) => { + const names = visible.join("\0") + if (data.catalog?.names === names) return data.catalog + const tools = new Map(visible.map((name) => [name, data.tools.get(name)!])) + const inventory = { tools, namespaces: data.namespaces } + const tool = CodeModeTool.create( + inventory, + (name, tool, input, context) => run(tools, tool, name, input, context), + permission, + ) + data.catalog = { names, tool, value: CodeModeTool.catalog(inventory), definition: definition(tool) } + return data.catalog + } + return Service.of({ transform: state.transform, reload: state.reload, list: () => Effect.sync(() => Array.from(state.get().tools.values())), - snapshot: Effect.fn("Tool.snapshot")((permissions, overlay) => - Effect.sync(() => { - const base = state.get() - const data = overlay?.length - ? { ...base, tools: new Map(base.tools), definitions: new Map(base.definitions), errors: [] } - : base - for (const tool of overlay ?? []) { - const id = effectiveName(tool) - commit(data, id, { ...tool, id }) - } - const active = new Map() - const rules = permissions ?? [] - for (const [name, tool] of data.tools) { - if (whollyDisabled(tool.options?.permission ?? name, rules)) continue - active.set(name, tool) - } - const codeModeEnabled = !whollyDisabled("execute", rules) - // Without Code Mode its tools would be unreachable, so expose them as direct tools instead. - const direct = codeModeEnabled - ? new Map(Array.from(active).filter(([, tool]) => tool.options?.codemode === false)) - : active - const codeModeTools = new Map(Array.from(active).filter(([, tool]) => tool.options?.codemode !== false)) - const names = Array.from(codeModeTools.keys()).join("\0") - // Discovery is immutable for a registry revision and visible tool set. Keep executors - // fresh, but share the inventory, whose prepared runtime and much larger rendered catalog - // are cached by identity, and the execute tool's definition across steps. - const cached = catalog?.data === data && catalog.names === names ? catalog : undefined - const codeModeInventory = cached?.inventory ?? { tools: codeModeTools, namespaces: data.namespaces } - const codeModeTool = codeModeEnabled - ? CodeModeTool.create( - codeModeInventory, - (name, tool, input, context) => run(codeModeInventory.tools, tool, name, input, context), - permission, - ) - : undefined - const codeModeCatalog = !codeModeEnabled - ? undefined - : (cached?.value ?? CodeModeTool.catalog(codeModeInventory)) - const codeModeDefinition = codeModeTool && (cached?.definition ?? definition(codeModeTool)) - if (data === base && codeModeCatalog && codeModeDefinition) - catalog = { - data, - names, - inventory: codeModeInventory, - value: codeModeCatalog, - definition: codeModeDefinition, + snapshot: Effect.fn("Tool.snapshot")(function* (permissions, overlay) { + const base = state.get() + const data = overlay?.length ? yield* withOverlay(base, overlay) : base + const rules = permissions ?? [] + const codeModeEnabled = !whollyDisabled("execute", rules) + const direct = new Map() + const visible: string[] = [] + for (const [name, tool] of data.tools) { + if (whollyDisabled(tool.options?.permission ?? name, rules)) continue + if (codeModeEnabled && tool.options?.codemode !== false) visible.push(name) + else direct.set(name, tool) + } + const catalog = codeModeEnabled ? catalogFor(data, visible) : undefined + return { + ...(catalog && { codeModeCatalog: catalog.value }), + definitions: [ + ...Array.from(direct.keys()) + .sort() + .map((name) => data.definitions.get(name)!), + ...(catalog ? [catalog.definition] : []), + ], + execute: Effect.fnUntraced(function* (input: Parameters[0]) { + const context: Tool.Context = { + sessionID: input.sessionID, + agent: input.agent, + messageID: input.messageID, + id: Tool.CallID.make(input.call.id), + progress: input.progress ?? (() => Effect.void), + cancel: input.cancel, } - return { - ...(codeModeCatalog === undefined ? {} : { codeModeCatalog }), - definitions: [ - ...Array.from(direct) - .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)) - .map(([name]) => data.definitions.get(name)!), - ...(codeModeDefinition ? [codeModeDefinition] : []), - ], - execute: Effect.fnUntraced(function* (input: Parameters[0]) { - const context: Tool.Context = { - sessionID: input.sessionID, - agent: input.agent, - messageID: input.messageID, - id: Tool.CallID.make(input.call.id), - progress: input.progress ?? (() => Effect.void), - cancel: input.cancel, - } - const event = yield* beforeExecute(input.call.name, input.call.input, context) - const requested = input.definitions?.get(event.tool) - // Preserve session context removal and alias resolution, now after the repair hook. - if (!requested && input.definitions && (direct.has(event.tool) || codeModeTool?.name === event.tool)) - return yield* new Tool.Error({ message: `Tool is not available for this request: ${event.tool}` }) - const name = requested?.name ?? event.tool - if (name === "execute" && codeModeTool) - return yield* executeTool(codeModeTool, name, event.input, context) - const tool = direct.get(name) - if (tool) return yield* executeTool(tool, name, event.input, context) - return yield* new Tool.Error({ - message: `No tool named "${name}" is currently available. Please use a tool from the available tool list.`, - }) - }), - } - }), - ), + const event = yield* beforeExecute(input.call.name, input.call.input, context) + const requested = input.definitions?.get(event.tool) + // Preserve session context removal and alias resolution, now after the repair hook. + if (!requested && input.definitions && (direct.has(event.tool) || catalog?.tool.name === event.tool)) + return yield* new Tool.Error({ message: `Tool is not available for this request: ${event.tool}` }) + const name = requested?.name ?? event.tool + if (name === "execute" && catalog) return yield* executeTool(catalog.tool, name, event.input, context) + const tool = direct.get(name) + if (tool) return yield* executeTool(tool, name, event.input, context) + return yield* new Tool.Error({ + message: `No tool named "${name}" is currently available. Please use a tool from the available tool list.`, + }) + }), + } + }), check: Effect.fn("Tool.check")(function* (input) { if (whollyDisabled("execute", input.permissions)) { return { @@ -382,6 +356,20 @@ const layer = Layer.effect( }), ) +function reportErrors(data: Data) { + return Effect.forEach( + data.errors, + ({ kind, name, namespace, error }) => + Effect.logError(`Skipping invalid ${kind} registration`, { name, namespace, error: error.message }), + { discard: true }, + ) +} + +function add(editor: Data, tool: Tool.Info) { + const id = effectiveName(tool) + commit(editor, id, { ...tool, id, options: tool.options && { ...tool.options } }) +} + /** Store a valid tool under its effective name, or record why it was skipped. */ function commit(editor: Data, id: string, input: Tool.Info & { readonly id: string }) { // JavaScript plugins may leave out `input` for a tool that takes none. diff --git a/packages/core/src/tool/mcp.ts b/packages/core/src/tool/mcp.ts index 5b8a29b6e93..a277ba3fa86 100644 --- a/packages/core/src/tool/mcp.ts +++ b/packages/core/src/tool/mcp.ts @@ -2,6 +2,7 @@ export * as McpTool from "./mcp.js" import { ToolFailure } from "@opencode/ai/effect" import { McpEvent } from "@opencode/schema/mcp-event" +import type { Info } from "@opencode/schema/tool" import { Context, Effect, Fiber, type JsonSchema, Layer, Option, PubSub, Schema, Semaphore, Stream } from "effect" import { makeLocationNode } from "@opencode/util/effect/app-node" import { extension } from "mime-types" @@ -26,11 +27,12 @@ export const name = (server: string, tool: string) => effectiveName({ name: tool, options: { namespace: namespace(server) } }) export interface Interface { + /** Stable owner-bound definitions for this session's current MCP list. */ + readonly sessionTools: (owner: Session.ID) => Effect.Effect> /** * Wait for the initial MCP tool registration, give servers still connecting a bounded chance to * finish, then bring the registry up to date without waiting for the debounced reload. */ - readonly sessionTools: (owner: Session.ID) => Effect.Effect[0]>> readonly flush: Effect.Effect } @@ -46,8 +48,9 @@ export const layer = Layer.effect( const toolOutput = yield* ToolOutput.Service const lock = Semaphore.makeUnsafe(1) let discovered: Mcp.Tool[] = [] + const overlays = new WeakMap, ReadonlyArray>() - const definition = (tool: Mcp.Tool, owner?: Session.ID): Parameters[0] => ({ + const definition = (tool: Mcp.Tool, owner?: Session.ID): Info => ({ name: tool.name, options: { namespace: namespace(tool.server), codemode: tool.codemode !== false }, description: tool.description ?? "", @@ -143,8 +146,15 @@ export const layer = Layer.effect( Effect.forkScoped({ startImmediately: true }), ) return Service.of({ - sessionTools: (owner) => - mcp.sessionTools(owner).pipe(Effect.map((tools) => tools.map((tool) => definition(tool, owner)))), + sessionTools: Effect.fnUntraced(function* (owner) { + const source = yield* mcp.sessionTools(owner) + if (!source.length) return [] + const cached = overlays.get(source) + if (cached) return cached + const tools = source.map((tool) => definition(tool, owner)) + overlays.set(source, tools) + return tools + }), flush: Effect.gen(function* () { yield* Fiber.await(initial) yield* mcp.awaitStartup() diff --git a/packages/core/test/mcp-attach.test.ts b/packages/core/test/mcp-attach.test.ts index 51094d629af..f0db7827b71 100644 --- a/packages/core/test/mcp-attach.test.ts +++ b/packages/core/test/mcp-attach.test.ts @@ -150,6 +150,76 @@ it.live("attaches a client MCP server and routes its tools with the session", () }), ) +it.live("reuses each owner's catalog across interleaved steps without sharing call routing", () => + Effect.gen(function* () { + const mcp = yield* Mcp.Service + const tools = yield* McpTool.Service + const registry = yield* Tool.Service + yield* tools.flush + const a = Session.ID.make("ses_client_a") + const b = Session.ID.make("ses_client_b") + const first = yield* clientServer("same", ["shared"]) + const second = yield* clientServer("same", ["shared"]) + const scope = yield* Scope.fork(yield* Scope.Scope) + yield* mcp.attach("tui", first.client, a).pipe(Scope.provide(scope)) + yield* mcp.attach("tui", second.client, b) + const snapshot = (owner: Session.ID, rules?: Permission.Ruleset) => + tools.sessionTools(owner).pipe(Effect.flatMap((overlay) => registry.snapshot(rules, overlay))) + const run = (snapshot: Tool.Snapshot, sessionID: Session.ID) => + snapshot.execute({ + sessionID, + ...toolIdentity, + call: { type: "tool-call", id: "call_shared", name: "execute", input: { code: "return tools.tui.shared({})" } }, + }) + + const directory = yield* registry.snapshot() + const left = yield* snapshot(a) + const right = yield* snapshot(b) + expect(left.definitions.map((tool) => tool.name)).toEqual(["execute"]) + expect(left.codeModeCatalog?.tools).toMatchObject([{ name: "tui", tools: [{ name: "shared" }] }]) + const repeated = yield* snapshot(a) + expect(repeated.codeModeCatalog).toBe(left.codeModeCatalog) + expect(repeated.definitions[0]).toBe(left.definitions[0]) + expect((yield* snapshot(b)).codeModeCatalog).toBe(right.codeModeCatalog) + expect((yield* registry.snapshot()).codeModeCatalog).toBe(directory.codeModeCatalog) + yield* run(repeated, a) + yield* run(right, b) + expect(first.sessions).toEqual([a]) + expect(second.sessions).toEqual([b]) + + // An identical replacement changes who handles a call, not what the owner advertises. + const replacement = yield* clientServer("same", ["shared"]) + yield* mcp.attach("tui", replacement.client, a).pipe(Scope.provide(scope)) + expect((yield* snapshot(a)).codeModeCatalog).toBe(left.codeModeCatalog) + yield* run(left, a) + expect(first.sessions).toEqual([a]) + expect(replacement.sessions).toEqual([a]) + + const changed = yield* clientServer("updated", ["shared"]) + yield* mcp.attach("tui", changed.client, a).pipe(Scope.provide(scope)) + const updated = yield* snapshot(a) + expect(updated.codeModeCatalog?.tools).toMatchObject([{ name: "tui", tools: [{ description: "updated shared" }] }]) + expect(updated.codeModeCatalog).not.toBe(left.codeModeCatalog) + expect((yield* snapshot(b)).codeModeCatalog).toBe(right.codeModeCatalog) + + const hidden = yield* snapshot(a, [{ action: "tui_shared", resource: "*", effect: "deny" }]) + expect(hidden.codeModeCatalog?.tools).toEqual([]) + const direct = yield* snapshot(a, [{ action: "execute", resource: "*", effect: "deny" }]) + expect(direct.codeModeCatalog).toBeUndefined() + expect(direct.definitions.map((tool) => tool.name)).toEqual(["tui_shared"]) + + yield* registry.transform((editor) => editor.namespace({ name: "tui", description: "New base namespace" })) + const revised = yield* snapshot(b) + expect(revised.codeModeCatalog?.tools).toMatchObject([{ name: "tui", description: "New base namespace" }]) + expect(revised.codeModeCatalog).not.toBe(right.codeModeCatalog) + yield* Scope.close(scope, Exit.void) + expect((yield* snapshot(a)).codeModeCatalog).toBe((yield* registry.snapshot()).codeModeCatalog) + expect((yield* snapshot(b)).codeModeCatalog).toBe(revised.codeModeCatalog) + expect((yield* run(left, a)).output).toMatchObject({ error: true }) + expect(second.sessions).toEqual([b]) + }), +) + it.live("removes an attached entry when its scope closes", () => Effect.gen(function* () { const mcp = yield* Mcp.Service diff --git a/packages/core/test/tool-registry.test.ts b/packages/core/test/tool-registry.test.ts index 755ad4e7872..6430f5b506f 100644 --- a/packages/core/test/tool-registry.test.ts +++ b/packages/core/test/tool-registry.test.ts @@ -639,6 +639,41 @@ describe("Tool", () => { }).pipe(Effect.provide(Logger.layer([logger]))) }) + it.effect("reports an unconvertible overlay schema once without dropping healthy tools", () => { + const output: unknown[] = [] + const logger = Logger.map(Logger.formatStructured, (entry) => output.push(entry.message)) + return Effect.gen(function* () { + const registry = yield* Tool.Service + const overlay: Info[] = [ + { ...make(), options: { codemode: false } }, + { + ...make(), + name: "broken", + options: { namespace: "client" }, + // Valid Standard Schema, but the vendor does not implement JSON Schema conversion. + input: { "~standard": { version: 1, vendor: "test", validate: (value) => ({ value }) } }, + }, + ] + const first = yield* registry.snapshot([], overlay) + yield* registry.snapshot() + const second = yield* registry.snapshot([], overlay) + expect(first.definitions.map((tool) => tool.name)).toEqual(["echo", "execute"]) + expect(first.codeModeCatalog?.tools).toEqual([]) + expect(second.definitions[0]).toBe(first.definitions[0]) + expect(output).toEqual([ + [ + "Skipping invalid tool registration", + { + name: "broken", + namespace: "client", + error: + 'Invalid tool definition client_broken: Schema vendor "test" does not support JSON Schema conversion', + }, + ], + ]) + }).pipe(Effect.provide(Logger.layer([logger]))) + }) + it.effect("skipped registrations leave existing tools and scoped cleanup intact", () => Effect.gen(function* () { const service = yield* Tool.Service