From 50735ef4404bf7670fdff8678ed671beff1aecd0 Mon Sep 17 00:00:00 2001 From: Aiden Cline Date: Wed, 4 Nov 2026 12:45:54 -0600 Subject: [PATCH] fix(core): keep MCP status and tool calls consistent during reconnects --- packages/core/src/mcp/connection.ts | 137 +++++++++++++++++----------- packages/core/src/mcp/index.ts | 111 +++++++--------------- packages/core/test/mcp.test.ts | 118 ++++++++++++++++++++++++ 3 files changed, 232 insertions(+), 134 deletions(-) diff --git a/packages/core/src/mcp/connection.ts b/packages/core/src/mcp/connection.ts index bfbd9df7fea..50de27a741a 100644 --- a/packages/core/src/mcp/connection.ts +++ b/packages/core/src/mcp/connection.ts @@ -2,25 +2,42 @@ export * as McpConnection from "./connection.js" import type { OAuthClientProvider } from "@modelcontextprotocol/client" import type { Mcp } from "@opencode/schema/mcp" -import { Cause, Effect, Exit, Scope } from "effect" +import { Cause, Clock, Effect, Exit, Latch, Scope } from "effect" import { FetchHttpClient } from "effect/http" import { Environment } from "../environment/index.js" import type { McpClient } from "./client.js" export type Failure = Extract +type Disabled = Extract + +/** Where one server stands. Only `connected` holds a client, so readers never see a connected server without one. */ +export type State = + | Disabled + /** An attempt is connecting. `settled` opens once the server leaves this state. */ + | { readonly status: "pending"; readonly started: number; readonly settled: Latch.Latch } + | { + readonly status: "connected" + readonly scope: Scope.Closeable + readonly client: McpClient.Connection + /** The server's tool list as listed. Each refresh replaces the array. */ + readonly tools: ReadonlyArray + readonly prompts: ReadonlyArray + } + | Failure + +export const status = (state: State): Mcp.Status => + state.status === "pending" || state.status === "connected" ? { status: state.status } : state /** * What a connection reports to its owner. Each runs inline, in order, so the owner can keep its own * state and publish in step with the connection. */ export interface Events { - /** An attempt is about to connect. */ + /** An attempt is about to connect; the server is pending. */ readonly connecting: Effect.Effect /** The attempt connected and listed its tools. */ readonly connected: Effect.Effect readonly failed: (failure: Failure) => Effect.Effect - /** The attempt ended, however it ended. */ - readonly settled: Effect.Effect /** A live connection was torn down. */ readonly stopped: Effect.Effect /** The live connection closed on its own. Runs under the lock; the owner decides how to stop. */ @@ -33,6 +50,8 @@ export interface Events { export interface Input { readonly name: string readonly config: Mcp.ServerConfig + /** When the server was created. A server pending from creation keeps the startup window that began then. */ + readonly started: number readonly directory: string readonly clientInfo?: { readonly name: string; readonly version: string } /** Read on every attempt, so a credential change applies to the next one. */ @@ -62,13 +81,14 @@ export interface Catalog { /** One server connection, reconnected in place, with the catalogs it listed. */ export interface Connection { + readonly state: State readonly client: McpClient.Connection | undefined - /** The server's tool list as listed. Each refresh replaces the array. */ readonly tools: ReadonlyArray | undefined readonly prompts: ReadonlyArray | undefined - /** Connects and lists tools; a failure is reported through `failed`. */ + /** Replaces any live connection, then connects and lists tools; a failure is reported through `failed`. */ readonly start: Effect.Effect - readonly stop: Effect.Effect + /** Tears down the live connection or abandons a pending one, leaving the server disabled or failed. */ + readonly stop: (next?: Disabled | Failure) => Effect.Effect /** * Runs a request against `client` and, if that request observed a session expiry, reconnects and * runs it once more against the replacement. Any other failure passes through. @@ -81,12 +101,32 @@ export interface Connection { } export function make(input: Input): Connection { - const state: { - scope?: Scope.Closeable - client?: McpClient.Connection - tools?: ReadonlyArray - prompts?: ReadonlyArray - } = {} + let state: State = input.config.disabled + ? { status: "disabled" } + : { status: "pending", started: input.started, settled: Latch.makeUnsafe() } + + // Every move to another state goes through here, so leaving `pending` always releases its waiters + // and leaving `connected` always closes its scope. + const set = (next: State) => + Effect.gen(function* () { + const previous = state + state = next + if (previous.status === "pending") yield* previous.settled.open + if (previous.status !== "connected") return + yield* Scope.close(previous.scope, Exit.void) + yield* input.events.stopped + }) + + // Tool and prompt refreshes keep the connection, so they update it in place. + const update = ( + client: McpClient.Connection, + lists: { tools?: ReadonlyArray; prompts?: ReadonlyArray }, + ) => + Effect.sync(() => { + if (state.status === "connected" && state.client === client) state = { ...state, ...lists } + }) + + const fail = (failure: Failure) => set(failure).pipe(Effect.andThen(input.events.failed(failure))) // Runs a connection callback under the lock, dropping it if the connection is no longer the live // client, so late SDK callbacks cannot commit obsolete state. @@ -94,22 +134,19 @@ export function make(input: Input): Connection { (client: McpClient.Connection) => (effect: Effect.Effect) => input.callbacks( - Effect.suspend(() => (state.client === client ? effect : Effect.void)).pipe(input.lock, Effect.ignore), + Effect.suspend(() => (state.status === "connected" && state.client === client ? effect : Effect.void)).pipe( + input.lock, + Effect.ignore, + ), ) const refreshTools = (client: McpClient.Connection) => - client.tools().pipe( - Effect.map((tools) => { - state.tools = tools - }), - ) + client.tools().pipe(Effect.flatMap((tools) => update(client, { tools }))) const refreshPrompts = (client: McpClient.Connection) => client.prompts().pipe( Effect.orElseSucceed(() => []), - Effect.map((prompts) => { - state.prompts = prompts - }), + Effect.flatMap((prompts) => update(client, { prompts })), Effect.andThen(input.events.promptsChanged), ) @@ -117,9 +154,8 @@ export function make(input: Input): Connection { // replaced it while this one waited for the lock. const recover = (client: McpClient.Connection) => Effect.gen(function* () { - if (state.client !== client) return + if (state.status !== "connected" || state.client !== client) return yield* Effect.logInfo("mcp session expired, reconnecting", { server: input.name }) - yield* stop yield* start }).pipe(input.lock) @@ -131,7 +167,10 @@ export function make(input: Input): Connection { Effect.catchIf( // The client module is loaded lazily, so match the tagged error by tag rather than class. (error) => "_tag" in error && error._tag === "MCP.SessionExpiredError", - (error) => recover(client).pipe(Effect.flatMap(() => (state.client ? run(state.client) : Effect.fail(error)))), + (error) => + recover(client).pipe( + Effect.flatMap(() => (state.status === "connected" ? run(state.client) : Effect.fail(error))), + ), ), ) @@ -148,14 +187,15 @@ export function make(input: Input): Connection { const start: Effect.Effect = Effect.suspend(() => Effect.gen(function* () { + if (state.status !== "pending") + yield* set({ status: "pending", started: yield* Clock.currentTimeMillis, settled: Latch.makeUnsafe() }) yield* input.events.connecting // Checked before the OAuth provider is built, which parses the URL too. if (input.config.type === "remote" && !URL.canParse(input.config.url)) - return yield* input.events.failed({ status: "failed", error: `Invalid MCP server URL: ${input.config.url}` }) - const scope = yield* Scope.fork(input.scope) - state.scope = scope + return yield* fail({ status: "failed", error: `Invalid MCP server URL: ${input.config.url}` }) const authProvider = yield* input.authProvider const { McpClient } = yield* Effect.promise(() => import("./client.js")) + const scope = yield* Scope.fork(input.scope) // List tools as part of connect so a failure here marks the server failed rather than // leaving it connected with a silently empty tool list and no path to recover. const result = yield* McpClient.connect( @@ -171,54 +211,41 @@ export function make(input: Input): Connection { Effect.provideService(FetchHttpClient.Fetch, input.fetch), Scope.provide(scope), input.handshake, + Effect.onError(() => Scope.close(scope, Exit.void)), Effect.exit, ) if (Exit.isSuccess(result)) { - state.client = result.value.client - state.tools = result.value.tools - state.prompts = [] - watch(result.value.client) + const client = result.value.client + yield* set({ status: "connected", scope, client, tools: result.value.tools, prompts: [] }) + watch(client) yield* input.events.connected - whenLive(result.value.client)(refreshPrompts(result.value.client)) + whenLive(client)(refreshPrompts(client)) return } - yield* Scope.close(scope, Exit.void) - state.scope = undefined const error = Cause.squash(result.cause) - yield* input.events.failed( + yield* fail( error instanceof McpClient.NeedsAuthError ? { status: "needs_auth", error: error.message } : { status: "failed", error: error instanceof Error ? error.message : String(error) }, ) - }).pipe( - Effect.ensuring(input.events.settled), - Effect.annotateLogs({ server: input.name, directory: input.directory, connectionID: crypto.randomUUID() }), - ), + }).pipe(Effect.annotateLogs({ server: input.name, directory: input.directory, connectionID: crypto.randomUUID() })), ) - const stop = Effect.gen(function* () { - const scope = state.scope - if (!scope) return - state.scope = undefined - state.client = undefined - state.tools = undefined - state.prompts = undefined - yield* Scope.close(scope, Exit.void) - yield* input.events.stopped - }) - return { + get state() { + return state + }, get client() { - return state.client + return state.status === "connected" ? state.client : undefined }, get tools() { - return state.tools + return state.status === "connected" ? state.tools : undefined }, get prompts() { - return state.prompts + return state.status === "connected" ? state.prompts : undefined }, start, - stop, + stop: (next = { status: "disabled" }) => set(next), recovering, catalog: (client) => recovering(client, (client) => diff --git a/packages/core/src/mcp/index.ts b/packages/core/src/mcp/index.ts index fff6b726f40..7cd8b51bfb0 100644 --- a/packages/core/src/mcp/index.ts +++ b/packages/core/src/mcp/index.ts @@ -7,21 +7,7 @@ import type { Session } from "@opencode/schema/session" import type { Transport } from "@modelcontextprotocol/client" import { createHash } from "node:crypto" import { isDeepStrictEqual } from "node:util" -import { - Clock, - Context, - Effect, - Exit, - Fiber, - FiberSet, - Latch, - Layer, - Schema, - Scope, - Semaphore, - Stream, - Types, -} from "effect" +import { Clock, Context, Effect, Exit, Fiber, FiberSet, Layer, Schema, Scope, Semaphore, Stream, Types } from "effect" import { FetchHttpClient } from "effect/http" import { makeLocationNode } from "@opencode/util/effect/app-node" import { httpFetch } from "@opencode/util/effect/app-node-platform" @@ -80,12 +66,12 @@ export class ToolCallError extends Schema.TaggedError()("MCP.Tool message: Schema.String, }) {} -const unavailable = (server: ServerName, status: Status) => { - switch (status.status) { +const unavailable = (server: ServerName, state: McpConnection.State) => { + switch (state.status) { case "failed": - return `MCP server "${server}" is not connected: ${status.error}. Reconnect it from /mcps.` + return `MCP server "${server}" is not connected: ${state.error}. Reconnect it from /mcps.` case "needs_auth": - return `MCP server "${server}" needs authentication: ${status.error}. Sign in from /mcps.` + return `MCP server "${server}" needs authentication: ${state.error}. Sign in from /mcps.` case "disabled": return `MCP server "${server}" is disabled.` default: @@ -95,10 +81,6 @@ const unavailable = (server: ServerName, status: Status) => { type ServerEntry = { readonly config: Mcp.ServerConfig - status: Status - readonly startup: Latch.Latch - // The connection attempt in flight: when it began and a latch that opens once it settles. - attempt?: { readonly started: number; readonly settled: Latch.Latch } readonly connection: McpConnection.Connection // The connection's tool list tagged for this server, rebuilt only when the connection lists again. tagged?: { readonly source: ReadonlyArray; readonly tools: ReadonlyArray } @@ -280,9 +262,16 @@ export const layer = (options?: Options) => if (!entry) return yield* new NotFoundError({ server: name }) return entry }) + // Waits for a connecting server until it settles or its startup window ends. + const settling = Effect.fnUntraced(function* (state: McpConnection.State) { + if (state.status !== "pending") return + const remaining = state.started + STARTUP_GRACE_MS - (yield* Clock.currentTimeMillis) + if (remaining > 0) yield* state.settled.await.pipe(Effect.raceFirst(Effect.sleep(remaining))) + }) + // A server that is connecting, at startup or during a reconnect, gets the same brief wait as a model call. const connected = Effect.fnUntraced(function* (name: ServerName) { const entry = yield* requireServer(name) - yield* entry.startup.await + yield* settling(entry.connection.state) return { entry, client: entry.connection.client } }) @@ -371,12 +360,10 @@ export const layer = (options?: Options) => const makeEntry = (name: ServerName, config: Mcp.ServerConfig, started: number): ServerEntry => { const entry: ServerEntry = { config, - status: { status: "pending" }, - startup: Latch.makeUnsafe(), - attempt: { started, settled: Latch.makeUnsafe() }, connection: McpConnection.make({ name, config, + started, directory: location.directory, clientInfo: options?.clientInfo, authProvider: Effect.suspend(() => connectProvider(entry)), @@ -389,17 +376,10 @@ export const layer = (options?: Options) => callbacks, fork, events: { - connecting: Effect.gen(function* () { - // A server still pending from creation keeps the window that started with its entry. - if (!entry.attempt || entry.status.status !== "pending") - entry.attempt = { started: yield* Clock.currentTimeMillis, settled: Latch.makeUnsafe() } - // Announce the handshake so connect() and credential reconnects don't show a stale - // disabled/failed status for the duration of the connection attempt. - entry.status = { status: "pending" } - yield* bus.publish(McpEvent.StatusChanged, { server: name }) - }), + // Announce the handshake so connect() and credential reconnects don't show a stale + // disabled/failed status for the duration of the connection attempt. + connecting: bus.publish(McpEvent.StatusChanged, { server: name }), connected: Effect.gen(function* () { - entry.status = { status: "connected" } yield* Effect.logInfo("mcp connected", { server: name, tools: entry.connection.tools?.length }) // The tool registry reads on this event; a late-connecting server has no other way to appear. yield* bus.publish(McpEvent.ToolsChanged, { server: name }) @@ -408,16 +388,9 @@ export const layer = (options?: Options) => }), failed: (failure) => Effect.gen(function* () { - entry.status = failure - yield* Effect.logWarning("mcp connect failed", { server: name, status: entry.status }) + yield* Effect.logWarning("mcp connect failed", { server: name, status: failure }) yield* bus.publish(McpEvent.StatusChanged, { server: name }) }), - // Every start runs under the server lock, so the attempt read here is the one it began. - settled: Effect.suspend(() => { - const attempt = entry.attempt - entry.attempt = undefined - return (attempt ? attempt.settled.open : Effect.void).pipe(Effect.ensuring(entry.startup.open)) - }), stopped: Effect.gen(function* () { yield* bus.publish(McpEvent.ToolsChanged, { server: name }) yield* bus.publish(McpEvent.ResourcesChanged, { server: name }) @@ -425,8 +398,7 @@ export const layer = (options?: Options) => }), closed: (reason) => Effect.gen(function* () { - entry.status = { status: "failed", error: reason } - yield* entry.connection.stop + yield* entry.connection.stop({ status: "failed", error: reason }) yield* bus.publish(McpEvent.StatusChanged, { server: name }) }), toolsChanged: bus.publish(McpEvent.ToolsChanged, { server: name }), @@ -480,7 +452,7 @@ export const layer = (options?: Options) => }) const disposeServer = Effect.fnUntraced(function* (entry: ServerEntry) { - yield* entry.connection.stop + yield* entry.connection.stop() if (entry.registration) yield* entry.registration.dispose }) @@ -490,18 +462,9 @@ export const layer = (options?: Options) => // Readers that arrive while the previous connection closes wait for this one instead of using that one. entries.set(name, entry) if (previous) yield* disposeServer(previous) - yield* Effect.gen(function* () { - yield* register(name, entry) - if (serverConfig.disabled) { - entry.status = { status: "disabled" } - yield* bus.publish(McpEvent.StatusChanged, { server: name }) - return - } - yield* entry.connection.start - }).pipe( - // Settle startup even when registration fails or replacement is interrupted, so readers cannot hang. - Effect.ensuring(entry.startup.open), - ) + yield* register(name, entry) + if (serverConfig.disabled) return yield* bus.publish(McpEvent.StatusChanged, { server: name }) + yield* entry.connection.start }) const removeServer = Effect.fnUntraced(function* (name: ServerName, entry: ServerEntry) { @@ -624,15 +587,13 @@ export const layer = (options?: Options) => // Initial connections stay asynchronous so one slow server does not block Location startup. for (const [name, entry] of entries) { if (entry.config.disabled) { - entry.status = { status: "disabled" } - entry.startup.openUnsafe() yield* bus.publish(McpEvent.StatusChanged, { server: name }) continue } fork( Effect.gen(function* () { // connect() or disconnect() may have settled the server while this startup waited to run. - if (entry.status.status !== "pending") return yield* entry.startup.open + if (entry.connection.state.status !== "pending") return yield* entry.connection.start }).pipe(locks.withLock(name)), ) @@ -661,8 +622,7 @@ export const layer = (options?: Options) => // add() or remove() may have replaced or deleted the entry while we waited for the lock. const entry = entries.get(name) if (!entry || entry.integrationID !== integrationID) return - if (entry.status.status === "disabled") return - yield* entry.connection.stop + if (entry.connection.state.status === "disabled") return yield* entry.connection.start }).pipe(locks.withLock(name)) }) @@ -708,7 +668,7 @@ export const layer = (options?: Options) => .map( ([name, entry]): ServerInfo => ({ name, - status: entry.status, + status: McpConnection.status(entry.connection.state), title: entry.connection.client?.title, integrationID: entry.integrationID, }), @@ -724,7 +684,6 @@ export const layer = (options?: Options) => yield* transition( Effect.gen(function* () { const entry = yield* requireServer(name) - yield* entry.connection.stop yield* entry.connection.start }).pipe(locks.withLock(name)), ) @@ -734,8 +693,7 @@ export const layer = (options?: Options) => yield* transition( Effect.gen(function* () { const entry = yield* requireServer(name) - yield* entry.connection.stop - entry.status = { status: "disabled" } + yield* entry.connection.stop() yield* bus.publish(McpEvent.StatusChanged, { server: name }) }).pipe(locks.withLock(name)), ) @@ -762,15 +720,10 @@ export const layer = (options?: Options) => ].toSorted((a, b) => a.server.localeCompare(b.server) || a.name.localeCompare(b.name)) }), awaitStartup: Effect.fn("MCP.awaitStartup")(function* () { - const now = yield* Clock.currentTimeMillis - yield* Effect.all( - Array.from(entries.values()).flatMap((entry) => { - if (entry.status.status !== "pending" || !entry.attempt) return [] - const remaining = entry.attempt.started + STARTUP_GRACE_MS - now - return remaining > 0 ? [entry.attempt.settled.await.pipe(Effect.raceFirst(Effect.sleep(remaining)))] : [] - }), - { concurrency: "unbounded", discard: true }, - ) + yield* Effect.forEach(entries.values(), (entry) => settling(entry.connection.state), { + concurrency: "unbounded", + discard: true, + }) }), callTool: Effect.fn("MCP.callTool")(function* (input) { const server = ServerName.make(input.server) @@ -795,7 +748,7 @@ export const layer = (options?: Options) => return yield* new ToolCallError({ server, tool: input.name, - message: unavailable(server, target.entry.status), + message: unavailable(server, target.entry.connection.state), }) return yield* target.entry.connection.recovering(target.client, call).pipe(failed("server")) }), diff --git a/packages/core/test/mcp.test.ts b/packages/core/test/mcp.test.ts index 2d6044a7f0c..7343bd9f152 100644 --- a/packages/core/test/mcp.test.ts +++ b/packages/core/test/mcp.test.ts @@ -34,6 +34,7 @@ import { EnvironmentUnavailable } from "@opencode/core/environment/unavailable" import { Location } from "@opencode/core/location" import { Mcp } from "@opencode/core/mcp/index" import { McpClient } from "@opencode/core/mcp/client" +import { McpConnection } from "@opencode/core/mcp/connection" import { McpStdio } from "@opencode/core/mcp/stdio" import { Permission } from "@opencode/core/permission" import { AbsolutePath } from "@opencode/core/schema" @@ -1176,6 +1177,123 @@ test("reconnects and retries a tool call after the MCP session expires", async ( ) }) +test("a tool call during a reconnect waits for it instead of failing", async () => { + await Effect.runPromise( + Effect.scoped( + Effect.gen(function* () { + const started = yield* Deferred.make() + const release = yield* Deferred.make() + const gate = { closed: false } + const server = yield* resourceServer({ + modern: true, + respond: (request) => + !gate.closed || request.method !== "POST" + ? undefined + : Effect.runPromise( + Deferred.succeed(started, undefined).pipe( + Effect.andThen(Deferred.await(release)), + Effect.as(undefined), + ), + ), + }) + yield* Effect.gen(function* () { + const service = yield* Mcp.Service + yield* settled(service) + // The prompt refresh after connecting also POSTs, so let it finish before gating the handshake. + yield* service.prompts().pipe( + Effect.filterOrFail((prompts) => prompts.length > 0), + Effect.retry(Schedule.spaced("10 millis")), + ) + gate.closed = true + const reconnect = yield* service.connect("resources").pipe(Effect.forkChild({ startImmediately: true })) + yield* Deferred.await(started) + expect((yield* service.servers())[0]?.status).toEqual({ status: "pending" }) + + const call = yield* service + .callTool({ server: "resources", name: "echo", args: { n: 1 } }) + .pipe(Effect.forkChild({ startImmediately: true })) + yield* Effect.yieldNow + expect(call.pollUnsafe()).toBeUndefined() + + yield* Deferred.succeed(release, undefined) + yield* Fiber.join(reconnect) + expect((yield* Fiber.join(call)).isError).toBe(false) + expect(server.state.toolCalls).toHaveLength(1) + }).pipe( + Effect.ensuring(Deferred.succeed(release, undefined)), + Effect.provide( + resourceMcpLayer( + new ConfigMCP.Remote({ type: "remote", url: server.url, oauth: false, protocol: "2026-07-28" }), + ), + ), + ) + }), + ), + ) +}) + +testEffect(resourceMcpLayer(new ConfigMCP.Local({ type: "local", command: ["unused"], disabled: true }))).effect( + "a disabled MCP server never holds up startup or a tool call", + () => + Effect.gen(function* () { + const service = yield* Mcp.Service + // The test clock never advances, so any wait on the disabled server would hang here. + yield* service.awaitStartup() + const error = yield* service.callTool({ server: "resources", name: "echo" }).pipe(Effect.flip) + expect(error.message).toBe('MCP server "resources" is disabled.') + }), +) + +test("starting an MCP connection again closes the one it replaces", async () => { + await Effect.runPromise( + Effect.scoped( + Effect.gen(function* () { + const terminated: Array = [] + const server = yield* resourceServer({ + respond: (request) => { + if (request.method === "DELETE") terminated.push(request.headers.get("mcp-session-id")) + return undefined + }, + }) + const connection = McpConnection.make({ + name: "resources", + config: new ConfigMCP.Remote({ type: "remote", url: server.url, oauth: false }), + started: 0, + directory: import.meta.dir, + authProvider: Effect.succeed(undefined), + elicitation: { create: () => Effect.die("unused"), complete: () => Effect.void }, + environment: yield* Environment.Service, + fetch: globalThis.fetch, + scope: yield* Effect.scope, + lock: (effect) => effect, + handshake: (effect) => effect, + callbacks: (effect) => Effect.runFork(effect), + fork: (effect) => Effect.runFork(effect), + events: { + connecting: Effect.void, + connected: Effect.void, + failed: () => Effect.void, + stopped: Effect.void, + closed: () => Effect.void, + toolsChanged: Effect.void, + promptsChanged: Effect.void, + resourcesChanged: Effect.void, + }, + }) + yield* connection.start + const first = connection.client + // The fixture serves one legacy session per transport, so the second connection needs a fresh one. + yield* Effect.promise(server.restart) + yield* connection.start + + expect(terminated).toEqual([server.state.sessions[0]]) + expect(connection.client).not.toBe(first) + expect(connection.state.status).toBe("connected") + }).pipe(Effect.provide(hostEnvironmentLayer)), + ), + ) +}) + describe.each([ ["legacy", undefined], ["modern", "2026-07-28"],