export * as McpPool from "./pool.js" import type { OAuthClientProvider } from "@modelcontextprotocol/client" import type { Mcp } from "@opencode/schema/mcp" import { CrossSpawnSpawner } from "@opencode/util/cross-spawn-spawner" import { makeGlobalNode } from "@opencode/util/effect/app-node" import { httpFetch } from "@opencode/util/effect/app-node-platform" import { Cause, Context, Deferred, Effect, Exit, Fiber, FiberSet, Layer, Scope, Semaphore } from "effect" import { FetchHttpClient } from "effect/http" import { ChildProcessSpawner } from "effect/process/ChildProcessSpawner" import { Environment } from "../environment/index.js" import { SharedCache } from "../shared-cache.js" import type { McpClient } from "./client.js" import { McpConnection } from "./connection.js" export interface Input extends McpConnection.Input { /** * Run once per start: what tells this connection apart from every other one to the same server (see `key`), * and the OAuth provider to open it with. Both come from one credential selection, so a slot's key and the * account it connects as can't disagree. */ readonly select: Effect.Effect } export interface Selection { readonly key: string readonly authProvider: Effect.Effect } export interface Interface { /** * A Location's connection to a server that may be shared. Each start joins the connection other * Locations hold under the same key, or opens it, and each stop lets go of it; the last to let go * closes it. A server that negotiates the legacy protocol, or that answers but refuses or breaks the * pooled handshake, is never shared: the Location connects on its own, exactly as it would unpooled, * and every later start for that key skips straight to that. */ readonly connection: (input: Input) => McpConnection.Connection } export class Service extends Context.Service()("@opencode/McpPool") {} /** * Everything that could make two connections behave differently, so only identical ones are shared. * The server's name is left out; each Location keeps its own. Secrets appear only as fingerprints. */ export const key = (input: { readonly config: Mcp.ServerConfig /** Local only: the directory the server runs in, as `McpStdio.resolveCwd` resolves it for the spawn. */ readonly cwd?: string /** The active OAuth credential's ID, which a token refresh keeps and a sign-in replaces. */ readonly credential?: string readonly clientInfo?: { readonly name: string; readonly version: string } }) => { const config = input.config const common = [config.protocol, config.timeout ?? null, input.clientInfo ?? null] if (config.type === "remote") return JSON.stringify([ "remote", config.url, fingerprint(config.headers), config.oauth ? { ...config.oauth, client_secret: fingerprint(config.oauth.client_secret) } : config.oauth, // A remote server's URL gains ?codemode=false unless Code Mode is off. config.codemode !== false, input.credential ?? null, ...common, ]) // Only Locations on this host share local servers, so the execution plane is always the host. return JSON.stringify([ "local", "host", config.command, input.cwd ?? null, fingerprint(config.environment), ...common, ]) } function fingerprint(secret: string | Record | undefined) { if (secret === undefined) return null return SharedCache.fingerprint( typeof secret === "string" ? secret : JSON.stringify(Object.entries(secret).toSorted(([a], [b]) => a.localeCompare(b))), ) } // A Location holding a shared connection. The pool reaches Locations only through the holders // registered right now, never through the one that opened the connection. interface Holder { readonly authProvider: Effect.Effect readonly elicitation: McpClient.ElicitationHandler["create"] readonly closed: (reason: string) => void readonly changed: (kind: McpConnection.Kind) => void } type Outcome = "connected" | "private" | McpConnection.Failure interface Slot { readonly connection: McpConnection.Connection readonly holders: Set readonly lock: Semaphore.Semaphore readonly outcome: Deferred.Deferred start?: Fiber.Fiber connected: boolean } export const layer = Layer.effect( Service, Effect.gen(function* () { const scope = yield* Effect.scope const run = yield* FiberSet.makeRuntime() const driver = Environment.makeLocalDriver(yield* ChildProcessSpawner) const host = Environment.Service.of({ files: Environment.makeFiles(driver), spawner: driver.spawner }) const fetch = yield* FetchHttpClient.Fetch const slots = new Map() // Keys whose server negotiated legacy or refused the pooled handshake. Kept for the life of the process. const unpoolable = new Set() // The subset that negotiated legacy. Their private connections skip the 2026-07-28 probe; a refusal // proves nothing about the protocol, so those keep the configured one. const legacy = new Set() // Names of local servers already warned about for having no cwd, which keeps each project's folder in the key. const unfixed = new Set() // Takes only data from the Location that opens it: the connection outlives that Location's claim. const open = (key: string, input: Pick) => { const slot: Slot = { holders: new Set(), lock: Semaphore.makeUnsafe(1), outcome: Deferred.makeUnsafe(), connected: false, connection: McpConnection.make({ name: input.name, config: input.config, directory: input.directory, shared: true, clientInfo: input.clientInfo, // Every holder of a key presents the same credential, so any of them can build the provider. authProvider: Effect.suspend(() => slot.holders.values().next().value?.authProvider ?? Effect.undefined), elicitation: { // Elicitations a request carries reach that request's Location. Any other one, which the // server could not tie to a request, goes to every holder and the first answer wins; the // others are interrupted, which cancels their forms. create: (request) => Effect.suspend(() => { const holders = Array.from(slot.holders) if (holders.length === 0) return Effect.succeed({ action: "cancel" as const }) return Effect.raceAll(holders.map((holder) => holder.elicitation(request))) }), complete: () => Effect.void, }, environment: host, fetch, scope, lock: (effect) => slot.lock.withPermit(effect), callbacks: run, fork: run, events: { connecting: Effect.void, connected: Effect.void, // A server that answered but refused the pooled handshake, such as one that wants roots, may // still accept the Location's own connection; anything unreachable would only fail again. failed: (failure, answered) => Effect.gen(function* () { detach(key, slot) if (answered) { unpoolable.add(key) yield* Effect.logWarning("mcp pool ignored: server refused the shared connection", { server: input.name, error: failure.error, }) } yield* Deferred.succeed(slot.outcome, answered ? "private" : failure) }), legacy: (version) => Effect.gen(function* () { detach(key, slot) unpoolable.add(key) legacy.add(key) yield* Effect.logWarning("mcp pool ignored: server speaks an older protocol", { server: input.name, version, }) yield* Deferred.succeed(slot.outcome, "private") }), settled: Effect.void, closed: (reason) => Effect.gen(function* () { detach(key, slot) const holders = Array.from(slot.holders) slot.holders.clear() yield* slot.connection.stop for (const holder of holders) holder.closed(reason) }), changed: (kind) => Effect.sync(() => { if (slot.connected) for (const holder of slot.holders) holder.changed(kind) }), }, }), } slots.set(key, slot) return slot } const connect = (key: string, slot: Slot) => Effect.gen(function* () { yield* slot.connection.start // A failed or legacy start already settled the outcome. if (!slot.connection.client) return slot.connected = true yield* Deferred.succeed(slot.outcome, "connected") }).pipe( slot.lock.withPermit, // Holders wait on the outcome, so an attempt that dies still settles it. Effect.onError((cause) => Effect.suspend(() => { detach(key, slot) return Deferred.succeed(slot.outcome, { status: "failed", error: String(Cause.squash(cause)) }) }), ), ) const detach = (key: string, slot: Slot) => { if (slots.get(key) === slot) slots.delete(key) } // Closes as soon as the last holder lets go, interrupting a start nobody waits for anymore. const release = (key: string, slot: Slot, holder: Holder) => Effect.suspend(() => { slot.holders.delete(holder) if (slot.holders.size > 0) return Effect.void detach(key, slot) return Effect.gen(function* () { if (slot.start) yield* Fiber.interrupt(slot.start) yield* slot.connection.stop.pipe(slot.lock.withPermit) }) }) const acquire = Effect.fnUntraced(function* (key: string, input: Input, holder: Holder) { if (unpoolable.has(key)) return "private" as const const slot = slots.get(key) ?? open(key, { name: input.name, config: input.config, directory: input.directory, clientInfo: input.clientInfo }) yield* Effect.acquireRelease( Effect.sync(() => slot.holders.add(holder)), () => release(key, slot, holder), ) // Started once a holder is registered: the attempt reads its OAuth provider from the holders. slot.start ??= run(connect(key, slot)) const outcome = yield* Deferred.await(slot.outcome) return outcome === "connected" ? slot.connection : outcome }) const connection = (input: Input): McpConnection.Connection => { const state: { claim?: Scope.Closeable holder?: Holder shared?: McpConnection.Connection own?: McpConnection.Connection // This start's credential selection, which a private connection opens with as well. selected?: Selection } = {} // A private connection, used when the key can't be shared, with the configured protocol or plain legacy. const privately = (config: Mcp.ServerConfig) => McpConnection.make({ ...input, config, authProvider: Effect.suspend(() => state.selected?.authProvider ?? input.authProvider), }) const configured = privately(input.config) const older = privately({ ...input.config, protocol: "legacy" }) const live = () => state.shared ?? state.own ?? configured // The shared connection carries the name of the Location that opened it; forms show this Location's. const elicit: McpClient.ElicitationHandler["create"] = (request) => input.elicitation.create({ ...request, server: input.name }) // Holder callbacks run in the Location's own callback runtime, under its lock, and only while the // claim they belong to is the current one. const current = (holder: Holder, effect: () => Effect.Effect) => input.callbacks( Effect.suspend(() => (state.holder === holder ? effect() : Effect.void)).pipe(input.lock, Effect.ignore), ) const clear = Effect.suspend(() => { const claim = state.claim state.claim = undefined state.holder = undefined state.shared = undefined return claim ? Scope.close(claim, Exit.void) : Effect.void }) // Resolves false when the key can't be shared, leaving the start to the Location's own connection. const join = (selected: Selection) => Effect.gen(function* () { yield* input.events.connecting const claim = yield* Scope.fork(input.scope) const holder: Holder = { authProvider: selected.authProvider, elicitation: elicit, closed: (reason) => current(holder, () => input.events.closed(reason)), changed: (kind) => current(holder, () => input.events.changed(kind)), } state.claim = claim state.holder = holder const outcome = yield* acquire(selected.key, input, holder).pipe( Scope.provide(claim), Effect.onInterrupt(() => clear), ) if (outcome === "private") { yield* clear return false } if ("status" in outcome) { yield* clear yield* input.events.failed(outcome, false) return true } state.shared = outcome yield* input.events.connected return true }).pipe(Effect.onExit((exit) => (Exit.isSuccess(exit) && !exit.value ? Effect.void : input.events.settled))) // Requests through a shared connection bring this Location's elicitation handler along. const bind = (client: McpClient.Connection): McpClient.Connection => ({ ...client, callTool: (request) => client.callTool({ elicitation: elicit, ...request }), prompt: (request) => client.prompt({ elicitation: elicit, ...request }), readResource: (request) => client.readResource({ elicitation: elicit, ...request }), }) return { get client() { return live().client }, get tools() { return live().tools }, get prompts() { return live().prompts }, start: Effect.gen(function* () { if (input.config.type === "local" && input.config.cwd === undefined && !unfixed.has(input.name)) { unfixed.add(input.name) yield* Effect.logWarning( "mcp pool ignored: local server has no fixed cwd, so each directory runs its own", { server: input.name, }, ) } const selected = yield* input.select state.selected = selected if (!unpoolable.has(selected.key) && (yield* join(selected))) return state.own = legacy.has(selected.key) ? older : configured yield* state.own.start }), stop: Effect.gen(function* () { if (!state.claim) return yield* (state.own ?? configured).stop yield* clear yield* input.events.changed("tools") yield* input.events.changed("resources") yield* input.events.changed("prompts") }), recovering: (client, request) => state.shared ? state.shared.recovering(client, (client) => request(bind(client))) : (state.own ?? configured).recovering(client, request), catalog: (client) => live().catalog(client), } } return Service.of({ connection }) }), ) export const node = makeGlobalNode({ service: Service, layer, deps: [CrossSpawnSpawner.node, httpFetch] })