From 136583cb1189c6ee6dff2fdf445ee31c2fd79b06 Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:12:59 -0600 Subject: [PATCH] fix(core): keep MCP needs_auth and event follows through connection teardown (#66923) --- packages/core/src/mcp/connection.ts | 234 ++++++++++++++++------------ packages/core/src/mcp/index.ts | 216 +++++++++++++++++++------ packages/core/src/mcp/pool.ts | 13 +- packages/core/test/mcp.test.ts | 154 ++++++++++++++++++ 4 files changed, 461 insertions(+), 156 deletions(-) diff --git a/packages/core/src/mcp/connection.ts b/packages/core/src/mcp/connection.ts index edecc86a8b4..44e8fac400c 100644 --- a/packages/core/src/mcp/connection.ts +++ b/packages/core/src/mcp/connection.ts @@ -2,7 +2,7 @@ export * as McpConnection from "./connection.js" import type { AuthProvider } from "@modelcontextprotocol/client" import type { Mcp } from "@opencode/schema/mcp" -import { Cause, Effect, Exit, Scope } from "effect" +import { absurd, Cause, Effect, Exit, Scope } from "effect" import { FetchHttpClient } from "effect/http" import { Environment } from "../environment/index.js" import { KeyedMutex } from "../effect/keyed-mutex.js" @@ -11,8 +11,9 @@ import { McpError } from "./errors.js" export type Failure = Extract -/** A catalog the server can change: its tools, prompts, resources or skills. */ -export type Kind = "tools" | "prompts" | "resources" | "skills" +/** The catalogs a server can change, in the order a teardown announces them. */ +export const KINDS = ["tools", "resources", "prompts", "skills"] as const +export type Kind = (typeof KINDS)[number] /** * What a connection reports to its owner. Each runs inline, in order, so the owner can keep its own @@ -27,8 +28,11 @@ export interface Events { readonly failed: (failure: Failure, answered: boolean) => Effect.Effect /** The attempt ended, however it ended. */ readonly settled: Effect.Effect - /** The live connection closed on its own. Runs under the lock; the owner decides how to stop. */ - readonly closed: (reason: string) => Effect.Effect + /** + * The live connection ended on its own: it closed, or the server refused its credential. Runs under the lock; the + * owner decides how to stop. + */ + readonly closed: (failure: Failure) => Effect.Effect /** A catalog changed: the server said so, or the connection was torn down and every catalog emptied. */ readonly changed: (kind: Kind) => Effect.Effect /** @@ -115,14 +119,40 @@ export interface Connection { readonly catalog: (client: McpClient.Connection) => Effect.Effect } +interface Connected { + readonly _tag: "Connected" + readonly scope: Scope.Closeable + readonly client: McpClient.Connection + readonly tools: ReadonlyArray + readonly prompts: ReadonlyArray + readonly skills: ReadonlyArray +} + +// A connection exists only once it is connected: until then an attempt owns its scope, so no exit leaves it open. +type State = { readonly _tag: "Idle" } | Connected + +// What a handshake produced. A shared connection to a server older than 2026-07-28 stops before listing tools. +type Opened = + | { readonly _tag: "Legacy"; readonly client: McpClient.Connection } + | { readonly _tag: "Listed"; readonly client: McpClient.Connection; readonly tools: ReadonlyArray } + export function make(input: Input): Connection { - const state: { - scope?: Scope.Closeable - client?: McpClient.Connection - tools?: ReadonlyArray - prompts?: ReadonlyArray - skills?: ReadonlyArray - } = {} + let state: State = { _tag: "Idle" } + const current = (): Connected | undefined => { + switch (state._tag) { + case "Connected": + return state + case "Idle": + return undefined + default: + return absurd(state) + } + } + // Replaces a catalog listed by `client`, unless another connection has replaced it since. + const update = (client: McpClient.Connection, catalogs: Partial>) => { + const live = current() + if (live?.client === client) state = { ...live, ...catalogs } + } // 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. @@ -130,30 +160,22 @@ 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(() => (current()?.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.map((tools) => update(client, { tools }))) const refreshPrompts = (client: McpClient.Connection) => client.prompts().pipe( - Effect.map((prompts) => { - state.prompts = prompts - }), + Effect.map((prompts) => update(client, { prompts })), Effect.andThen(input.events.changed("prompts")), ) const refreshSkills = (client: McpClient.Connection) => client.skills ? client.skills.list().pipe( - Effect.map((skills) => { - state.skills = skills - }), + Effect.map((skills) => update(client, { skills })), Effect.andThen(input.events.changed("skills")), ) : Effect.void @@ -162,7 +184,7 @@ 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 (current()?.client !== client) return yield* Effect.logInfo("mcp session expired, reconnecting", { server: input.spec.name }) yield* stop yield* start @@ -171,13 +193,9 @@ export function make(input: Input): Connection { // A request the server refused for authorization ends the connection in needs_auth, as a refused connect does, so the // status says so and later calls stop refreshing a token the server will not take. const refused = (client: McpClient.Connection, message: string) => - Effect.gen(function* () { - if (state.client !== client) return - // A shared connection's holders learn of its end only through `closed`, which stops it. - if (input.shared) return yield* input.events.closed(message) - yield* stop - yield* input.events.failed({ status: "needs_auth", error: message }, false) - }).pipe(input.lock) + Effect.suspend(() => + current()?.client === client ? input.events.closed({ status: "needs_auth", error: message }) : Effect.void, + ).pipe(input.lock) const recovering = ( client: McpClient.Connection, @@ -194,14 +212,19 @@ export function make(input: Input): Connection { Effect.catchIf( (error) => error instanceof McpError.SessionExpiredError, (error) => - recover(client).pipe(Effect.flatMap(() => (state.client ? attempt(state.client) : Effect.fail(error)))), + recover(client).pipe( + Effect.flatMap(() => { + const replacement = current()?.client + return replacement ? attempt(replacement) : Effect.fail(error) + }), + ), ), ) } const watch = (client: McpClient.Connection) => { const live = whenLive(client) - client.onClose((reason) => live(input.events.closed(reason))) + client.onClose((reason) => live(input.events.closed({ status: "failed", error: reason }))) // Background refreshes (list-changed) can observe the expiry too; they do not retry, so // reconnect here for them. Foreground calls reconnect through `recovering`. client.onSessionExpired(() => input.fork(recover(client))) @@ -218,59 +241,79 @@ export function make(input: Input): Connection { const config = input.spec.config if (config.type === "remote" && !URL.canParse(config.url)) return yield* input.events.failed({ status: "failed", error: `Invalid MCP server URL: ${config.url}` }, false) - const scope = yield* Scope.fork(input.scope) - state.scope = scope - const authProvider = yield* input.authProvider - const { McpClient } = yield* Effect.promise(() => import("./client.js")) - // 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. A shared connection - // decides first: it can only be shared on 2026-07-28, so an older server is never asked to list. - const result = yield* McpClient.connect({ - ...input.spec, - server: input.spec.name, - authProvider, - elicitation: input.elicitation, - roots: !input.shared, - events: true, - }).pipe( - Effect.flatMap( - (client): Effect.Effect<{ client: McpClient.Connection; tools?: ReadonlyArray }, Error> => - input.shared && !client.modern - ? Effect.succeed({ client }) - : client.tools().pipe(Effect.map((tools) => ({ client, tools }))), - ), - Effect.provideService(Environment.Service, input.environment), - Effect.provideService(FetchHttpClient.Fetch, input.fetch), - Scope.provide(scope), - (effect) => - config.type === "remote" && !input.shared ? input.endpointLoads.withLock(config.url)(effect) : effect, - Effect.exit, - ) - if (Exit.isSuccess(result) && !result.value.tools) { - yield* Scope.close(scope, Exit.void) - state.scope = undefined - return yield* input.events.legacy?.(result.value.client.protocolVersion) ?? Effect.void + // The attempt owns its scope until a connection takes it over, and closes it on any other exit, interruption + // included, before the outcome is reported. + const result = yield* Effect.acquireUseRelease( + Scope.fork(input.scope), + (scope) => + Effect.gen(function* () { + const authProvider = yield* input.authProvider + const { McpClient } = yield* Effect.promise(() => import("./client.js")) + // 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. A shared connection + // decides first: it can only be shared on 2026-07-28, so an older server is never asked to list. + const opened = yield* McpClient.connect({ + ...input.spec, + server: input.spec.name, + authProvider, + elicitation: input.elicitation, + roots: !input.shared, + events: true, + }).pipe( + Effect.flatMap( + (client): Effect.Effect => + input.shared && !client.modern + ? Effect.succeed({ _tag: "Legacy", client }) + : client.tools().pipe(Effect.map((tools) => ({ _tag: "Listed", client, tools }) as const)), + ), + Effect.provideService(Environment.Service, input.environment), + Effect.provideService(FetchHttpClient.Fetch, input.fetch), + Scope.provide(scope), + (effect) => + config.type === "remote" && !input.shared ? input.endpointLoads.withLock(config.url)(effect) : effect, + ) + switch (opened._tag) { + case "Legacy": + return opened + case "Listed": + state = { + _tag: "Connected", + scope, + client: opened.client, + tools: opened.tools, + prompts: [], + skills: [], + } + // In the same step as the state, so no interruption can leave a live client unwatched. + watch(opened.client) + return opened + default: + return absurd(opened) + } + }), + (scope) => (current()?.scope === scope ? Effect.void : Scope.close(scope, Exit.void)), + ).pipe(Effect.exit) + if (Exit.isFailure(result)) { + const error = Cause.squash(result.cause) + return yield* input.events.failed( + error instanceof McpError.NeedsAuthError + ? { status: "needs_auth", error: error.message } + : { status: "failed", error: error instanceof Error ? error.message : String(error) }, + error instanceof McpError.ConnectError && error.answered === true, + ) } - if (Exit.isSuccess(result)) { - state.client = result.value.client - state.tools = result.value.tools - state.prompts = [] - state.skills = [] - watch(result.value.client) - yield* input.events.connected - whenLive(result.value.client)(refreshPrompts(result.value.client)) - whenLive(result.value.client)(refreshSkills(result.value.client)) - return + const opened = result.value + switch (opened._tag) { + case "Legacy": + return yield* input.events.legacy?.(opened.client.protocolVersion) ?? Effect.void + case "Listed": + yield* input.events.connected + whenLive(opened.client)(refreshPrompts(opened.client)) + whenLive(opened.client)(refreshSkills(opened.client)) + return + default: + return absurd(opened) } - yield* Scope.close(scope, Exit.void) - state.scope = undefined - const error = Cause.squash(result.cause) - yield* input.events.failed( - error instanceof McpError.NeedsAuthError - ? { status: "needs_auth", error: error.message } - : { status: "failed", error: error instanceof Error ? error.message : String(error) }, - error instanceof McpError.ConnectError && error.answered === true, - ) }).pipe( Effect.ensuring(input.events.settled), Effect.annotateLogs({ @@ -282,32 +325,25 @@ export function make(input: Input): Connection { ) const stop = Effect.gen(function* () { - const scope = state.scope + const scope = current()?.scope if (!scope) return - state.scope = undefined - state.client = undefined - state.tools = undefined - state.prompts = undefined - state.skills = undefined + state = { _tag: "Idle" } yield* Scope.close(scope, Exit.void) - yield* input.events.changed("tools") - yield* input.events.changed("resources") - yield* input.events.changed("prompts") - yield* input.events.changed("skills") + for (const kind of KINDS) yield* input.events.changed(kind) }) return { get client() { - return state.client + return current()?.client }, get tools() { - return state.tools + return current()?.tools }, get prompts() { - return state.prompts + return current()?.prompts }, get skills() { - return state.skills + return current()?.skills }, start, stop, diff --git a/packages/core/src/mcp/index.ts b/packages/core/src/mcp/index.ts index 967b50395b2..8946379110b 100644 --- a/packages/core/src/mcp/index.ts +++ b/packages/core/src/mcp/index.ts @@ -24,6 +24,7 @@ import { Semaphore, Stream, Types, + absurd, } from "effect" import { FetchHttpClient } from "effect/http" import { makeLocationNode } from "@opencode/util/effect/app-node" @@ -95,7 +96,9 @@ export class ToolCallError extends Schema.TaggedError()("MCP.Tool message: Schema.String, }) {} -const unavailable = (server: ServerName, status: Status) => { +type Offline = Exclude + +const unavailable = (server: ServerName, status: Offline) => { switch (status.status) { case "failed": return `MCP server "${server}" is not connected: ${status.error}. Reconnect it from /mcps.` @@ -103,17 +106,35 @@ const unavailable = (server: ServerName, status: Status) => { return `MCP server "${server}" needs authentication: ${status.error}. Sign in from /mcps.` case "disabled": return `MCP server "${server}" is disabled.` - default: + case "pending": return `MCP server "${server}" is not connected.` + default: + return absurd(status) } } +// Where a server stands apart from its connection. Only the connection says whether it is connected. +type Phase = + // An attempt is in flight: when it began, and a latch that opens once it settles. + | Starting + // Nothing in flight and nothing wrong: connected while the connection is live, between connections otherwise. + | { readonly _tag: "Idle" } + | { readonly _tag: "Disabled" } + | { readonly _tag: "Failed"; readonly failure: McpConnection.Failure } + +type Starting = { readonly _tag: "Starting"; readonly started: number; readonly settled: Latch.Latch } + +type Transition = + | { readonly _tag: "Connecting"; readonly attempt: Starting } + // The attempt ended without anything wrong: it connected, was interrupted, or its server went away. + | { readonly _tag: "Settled" } + | { readonly _tag: "Disabled" } + | { readonly _tag: "Failed"; readonly failure: McpConnection.Failure } + type ServerEntry = { readonly config: Mcp.ServerConfig - status: Status + phase: Phase 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 } @@ -122,6 +143,99 @@ type ServerEntry = { registration?: State.Registration } +const next = (phase: Phase, transition: Transition): Phase => { + switch (transition._tag) { + case "Connecting": + // A server still starting keeps the startup window it began with. + return starting(phase) ?? transition.attempt + case "Settled": + return starting(phase) ? { _tag: "Idle" } : phase + case "Disabled": + return { _tag: "Disabled" } + case "Failed": + return { _tag: "Failed", failure: transition.failure } + default: + return absurd(transition) + } +} + +// Every phase change goes through here. The phase changes before a latch opens, which can resume a waiter at once. +const advance = (entry: ServerEntry, transition: Transition) => { + const previous = entry.phase + entry.phase = next(previous, transition) + if (entry.phase !== previous) settle(previous) +} + +// Leaving an attempt opens its latch, so no one waits out its startup window for nothing. +const settle = (phase: Phase) => { + switch (phase._tag) { + case "Starting": + phase.settled.openUnsafe() + return + case "Idle": + case "Disabled": + case "Failed": + return + default: + return absurd(phase) + } +} + +const starting = (phase: Phase): Starting | undefined => { + switch (phase._tag) { + case "Starting": + return phase + case "Idle": + case "Disabled": + case "Failed": + return undefined + default: + return absurd(phase) + } +} + +const disabled = (phase: Phase) => { + switch (phase._tag) { + case "Disabled": + return true + case "Starting": + case "Idle": + case "Failed": + return false + default: + return absurd(phase) + } +} + +const status = (entry: ServerEntry): Status => { + const phase = entry.phase + switch (phase._tag) { + case "Idle": + return entry.connection.client ? { status: "connected" } : offline(phase) + case "Starting": + case "Disabled": + case "Failed": + return offline(phase) + default: + return absurd(phase) + } +} + +// What a server reports while it has no live connection. +const offline = (phase: Phase): Offline => { + switch (phase._tag) { + case "Starting": + case "Idle": + return { status: "pending" } + case "Disabled": + return { status: "disabled" } + case "Failed": + return phase.failure + default: + return absurd(phase) + } +} + // A client-hosted MCP server attached over a connection the client opened. Internal: never listed, // never reconciled against config, and removed entirely once its scope or connection closes. // Connections attached under one name stack; the most recent live one serves the name's tools. @@ -147,7 +261,7 @@ const changes = { resources: McpEvent.ResourcesChanged, prompts: PromptsChanged, skills: SkillsChanged, -} +} satisfies Record // Event IDs a subscription remembers to skip a duplicate the server replays. const SEEN_EVENTS = 100 @@ -250,7 +364,7 @@ export interface Interface extends State.Transformable { input: { readonly name: string readonly arguments?: Schema.JsonObject - /** Where to start; omitted or null starts from now. */ + /** Where to start; null starts from now, and omitted resumes an ended subscription or starts from now. */ readonly cursor?: string | null }, ) => Effect.Effect @@ -433,13 +547,13 @@ export const layer = (options?: Options) => input, Effect.suspend(() => { const entry = entries.get(name) - if (!entry || entry.status.status === "disabled") + if (!entry || disabled(entry.phase)) return Effect.fail( new EventsUnavailableError({ server: name, message: "The MCP server was removed or disabled." }), ) - if (entry.status.status !== "connected") - return Effect.fail(new Error(`MCP server ${name} is not connected`)) - const events = entry.connection.client?.events + const client = entry.connection.client + if (!client) return Effect.fail(new Error(`MCP server ${name} is not connected`)) + const events = client.events if (!events) return Effect.fail( new EventsUnavailableError({ server: name, message: "The MCP server offers no events." }), @@ -691,41 +805,38 @@ export const layer = (options?: Options) => 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" } + // A server still pending from creation keeps the window that started with its entry. Announce the + // handshake so connect() and credential reconnects don't show a stale disabled/failed status for the + // duration of the connection attempt. + advance(entry, { + _tag: "Connecting", + attempt: { _tag: "Starting", started: yield* Clock.currentTimeMillis, settled: Latch.makeUnsafe() }, + }) yield* bus.publish(McpEvent.StatusChanged, { server: name }) }), connected: Effect.gen(function* () { - entry.status = { status: "connected" } + advance(entry, { _tag: "Settled" }) yield* Effect.logInfo("mcp connected", { server: name, tools: entry.connection.tools?.length }) // Announce every list a consumer may read, since each reads them only on these events. A // connection another Location already holds has loaded its prompts, and no later change // would tell this one; prompts still loading read empty now and announce themselves later. - yield* bus.publish(McpEvent.ToolsChanged, { server: name }) - yield* bus.publish(McpEvent.ResourcesChanged, { server: name }) - yield* bus.publish(PromptsChanged, { server: name }) - yield* bus.publish(SkillsChanged, { server: name }) + for (const kind of McpConnection.KINDS) yield* bus.publish(changes[kind], { server: name }) yield* bus.publish(McpEvent.StatusChanged, { server: name }) }), failed: (failure) => Effect.gen(function* () { - entry.status = failure - yield* Effect.logWarning("mcp connect failed", { server: name, status: entry.status }) + advance(entry, { _tag: "Failed", failure }) + 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. + // An attempt interrupted before it reported an outcome stays pending, but no longer holds anyone up. settled: Effect.suspend(() => { - const attempt = entry.attempt - entry.attempt = undefined - return (attempt ? attempt.settled.open : Effect.void).pipe(Effect.ensuring(entry.startup.open)) + advance(entry, { _tag: "Settled" }) + return entry.startup.open }), - closed: (reason) => + closed: (failure) => Effect.gen(function* () { - entry.status = { status: "failed", error: reason } + advance(entry, { _tag: "Failed", failure }) yield* entry.connection.stop yield* bus.publish(McpEvent.StatusChanged, { server: name }) }), @@ -734,9 +845,8 @@ export const layer = (options?: Options) => } const entry: ServerEntry = { config, - status: { status: "pending" }, + phase: { _tag: "Starting", started, settled: Latch.makeUnsafe() }, startup: Latch.makeUnsafe(), - attempt: { started, settled: Latch.makeUnsafe() }, connection: pooled ? pool.connection({ ...base, @@ -807,6 +917,7 @@ export const layer = (options?: Options) => }) const disposeServer = Effect.fnUntraced(function* (entry: ServerEntry) { + advance(entry, { _tag: "Settled" }) yield* entry.connection.stop if (entry.registration) yield* entry.registration.dispose }) @@ -819,14 +930,19 @@ export const layer = (options?: Options) => yield* Effect.gen(function* () { yield* register(name, entry) if (serverConfig.disabled) { - entry.status = { status: "disabled" } + advance(entry, { _tag: "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), + Effect.ensuring( + Effect.suspend(() => { + advance(entry, { _tag: "Settled" }) + return entry.startup.open + }), + ), ) }) @@ -949,7 +1065,7 @@ 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" } + advance(entry, { _tag: "Disabled" }) entry.startup.openUnsafe() yield* bus.publish(McpEvent.StatusChanged, { server: name }) continue @@ -957,7 +1073,7 @@ export const layer = (options?: Options) => 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 (!starting(entry.phase)) return yield* entry.startup.open yield* entry.connection.start }).pipe(locks.withLock(name)), ) @@ -986,7 +1102,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 + if (disabled(entry.phase)) return yield* entry.connection.stop yield* entry.connection.start }).pipe(locks.withLock(name)) @@ -1035,7 +1151,7 @@ export const layer = (options?: Options) => .map( ([name, entry]): ServerInfo => ({ name, - status: entry.status, + status: status(entry), title: entry.connection.client?.title, integrationID: entry.integrationID, }), @@ -1062,7 +1178,7 @@ export const layer = (options?: Options) => Effect.gen(function* () { const entry = yield* requireServer(name) yield* entry.connection.stop - entry.status = { status: "disabled" } + advance(entry, { _tag: "Disabled" }) yield* bus.publish(McpEvent.StatusChanged, { server: name }) }).pipe(locks.withLock(name)), ) @@ -1092,9 +1208,10 @@ export const layer = (options?: Options) => 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)))] : [] + const attempt = starting(entry.phase) + if (!attempt) return [] + const remaining = attempt.started + STARTUP_GRACE_MS - now + return remaining > 0 ? [attempt.settled.await.pipe(Effect.raceFirst(Effect.sleep(remaining)))] : [] }), { concurrency: "unbounded", discard: true }, ) @@ -1122,7 +1239,7 @@ export const layer = (options?: Options) => return yield* new ToolCallError({ server, tool: input.name, - message: unavailable(server, target.entry.status), + message: unavailable(server, offline(target.entry.phase)), }) return yield* target.entry.connection.recovering(target.client, call).pipe(failed("server")) }), @@ -1197,7 +1314,7 @@ export const layer = (options?: Options) => getSkill: Effect.fn("MCP.getSkill")(function* (input) { const name = ServerName.make(input.server) const target = yield* connected(name) - if (!target.client) return yield* Effect.fail(new Error(unavailable(name, target.entry.status))) + if (!target.client) return yield* Effect.fail(new Error(unavailable(name, offline(target.entry.phase)))) return yield* target.entry.connection.recovering(target.client, (connection) => connection.skills ? connection.skills.get(input.uri) @@ -1207,7 +1324,7 @@ export const layer = (options?: Options) => readSkill: Effect.fn("MCP.readSkill")(function* (input) { const name = ServerName.make(input.server) const target = yield* connected(name) - if (!target.client) return yield* Effect.fail(new Error(unavailable(name, target.entry.status))) + if (!target.client) return yield* Effect.fail(new Error(unavailable(name, offline(target.entry.phase)))) return yield* target.entry.connection.recovering(target.client, (connection) => connection.skills ? connection.skills.read(input.entry, input.ref) @@ -1230,10 +1347,11 @@ export const layer = (options?: Options) => name: input.name, arguments: input.arguments, status: { status: "pending" }, - position: { - cursor: input.cursor ?? existing?.position.cursor ?? null, - seen: existing?.position.seen ?? [], - }, + // Only a resumed subscription keeps the event IDs it delivered; one given a cursor starts over from it. + position: + input.cursor === undefined + ? (existing?.position ?? { cursor: null, seen: [] }) + : { cursor: input.cursor, seen: [] }, } followed.set(id, sub) yield* bus.publish(McpEvent.ExperimentalSubscriptionChanged, { id }) diff --git a/packages/core/src/mcp/pool.ts b/packages/core/src/mcp/pool.ts index baad4f08a12..167b4784f69 100644 --- a/packages/core/src/mcp/pool.ts +++ b/packages/core/src/mcp/pool.ts @@ -129,7 +129,7 @@ function fingerprint(secret: string | Readonly> | undefin interface Holder { readonly authProvider: Effect.Effect readonly elicitation: McpClient.ElicitationHandler["create"] - readonly closed: (reason: string) => void + readonly closed: (failure: McpConnection.Failure) => void readonly changed: (kind: McpConnection.Kind) => void } @@ -230,13 +230,13 @@ export const layer = Layer.effect( yield* Deferred.succeed(slot.outcome, "private") }), settled: Effect.void, - closed: (reason) => + closed: (failure) => 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) + for (const holder of holders) holder.closed(failure) }), changed: (kind) => Effect.sync(() => { @@ -327,7 +327,7 @@ export const layer = Layer.effect( const holder: Holder = { authProvider: selected.authProvider, elicitation: elicit, - closed: (reason) => current(holder, () => input.events.closed(reason)), + closed: (failure) => current(holder, () => input.events.closed(failure)), changed: (kind) => current(holder, () => input.events.changed(kind)), } mode = { _tag: "Joining", claim, holder } @@ -407,10 +407,7 @@ export const layer = Layer.effect( return yield* own.stop } yield* clear - yield* input.events.changed("tools") - yield* input.events.changed("resources") - yield* input.events.changed("prompts") - yield* input.events.changed("skills") + for (const kind of McpConnection.KINDS) yield* input.events.changed(kind) }), recovering: (client, request) => { if (mode._tag === "Shared") return mode.connection.recovering(client, (client) => request(bind(client))) diff --git a/packages/core/test/mcp.test.ts b/packages/core/test/mcp.test.ts index 2522cfaaa9c..f2caa3ffde7 100644 --- a/packages/core/test/mcp.test.ts +++ b/packages/core/test/mcp.test.ts @@ -369,6 +369,7 @@ function resourceMcpLayer( /** The configured server's name; "resources" unless given. */ name?: string credentials?: Partial + integration?: Partial bus?: Layer.Layer /** `OPENCODE_FLAGS`, such as `-machines`. */ flags?: string @@ -462,6 +463,7 @@ function resourceMcpLayer( status: unusedIntegration, cancel: unusedIntegration, }, + ...overrides?.integration, }), Layer.mock(Credential.Service, { list: () => Effect.succeed([]), ...overrides?.credentials }), overrides?.environment ?? hostEnvironmentLayer, @@ -808,6 +810,32 @@ test("rejects sends before the stdio transport is started", async () => { ) }) +testEffect(Layer.empty).effect("stops waiting for a server whose registration failed", () => + Effect.gen(function* () { + const mcp = yield* Mcp.Service + // The failed registration fails the add too. + yield* mcp.add("remote", new ConfigMCP.Remote({ type: "remote", url: "https://mcp.example.com" })).pipe(Effect.exit) + yield* mcp.servers().pipe( + Effect.filterOrFail((servers) => servers.some((server) => server.name === "remote")), + Effect.retry({ times: 100 }), + ) + const startup = yield* mcp.awaitStartup().pipe(Effect.forkChild({ startImmediately: true })) + yield* Effect.yieldNow + expect(startup.pollUnsafe()).toBeDefined() + }).pipe( + Effect.provide( + resourceMcpLayer( + new ConfigMCP.Local({ type: "local", command: ["unused"], disabled: true }), + undefined, + undefined, + { + integration: { transform: () => Effect.die("integration unavailable") }, + }, + ), + ), + ), +) + test("joins concurrent stdio transport closes", async () => { await Effect.runPromise( Effect.scoped( @@ -3769,6 +3797,54 @@ describe("MCP pool", () => { }), ) + live("reports needs_auth in every Location when a shared connection's credential is refused", () => + Effect.gen(function* () { + const refusing = { tools: false } + const server = yield* resourceServer({ + modern: true, + resources: false, + respond: async (request) => + refusing.tools && (await toolCall(request)) ? new Response(null, { status: 401 }) : undefined, + }) + // A signed-in credential with no refresh token: a 401 can only end in a new login. + const row = (integrationID: Integration.ID) => + new Credential.Info({ + id: Credential.ID.make("cred_signed"), + integrationID, + label: "signed", + value: { + type: "oauth", + methodID: Integration.MethodID.make("signed"), + access: "signed-in", + refresh: "", + expires: Date.now() + 3_600_000, + metadata: { serverUrl: server.url, tokenType: "Bearer" }, + }, + }) + const credentials: Partial = { + list: (integrationID) => Effect.succeed([row(integrationID)]), + get: () => Effect.succeed(row(Integration.ID.make("unused"))), + } + const pool = yield* makePool + const config = pooled(server.url, { oauth: undefined }) + const a = yield* open(config, pool, directories[0], { credentials }) + const b = yield* open(config, pool, directories[1], { credentials }) + yield* a.mcp.callTool({ server: "resources", name: "echo" }) + expect(server.state.toolLists).toBe(1) + refusing.tools = true + + yield* a.mcp.callTool({ server: "resources", name: "echo" }).pipe(Effect.flip) + + for (const location of [a, b]) + expect( + yield* status(location.mcp).pipe( + Effect.filterOrFail((status) => status?.status !== "connected" && status?.status !== "pending"), + Effect.retry({ times: 200, schedule: Schedule.spaced("10 millis") }), + ), + ).toMatchObject({ status: "needs_auth" }) + }), + ) + live("connects with the credential its key was made from, even when a sign-in lands mid-start", () => Effect.gen(function* () { // The authorization header of every tool call, in order. @@ -4513,6 +4589,40 @@ describe("MCP events", () => { }), ) + testEffect(Layer.empty).live("resumes an ended subscription from its cursor unless subscribed again from now", () => + Effect.gen(function* () { + const server = yield* streamServer() + const bus = yield* workingBus + yield* Effect.gen(function* () { + const mcp = yield* Mcp.Service + expect(yield* ready(mcp)).toEqual({ status: "connected" }) + const ended = bus.until(only(mcp), (sub) => sub?.status.status === "ended") + const terminated = { error: { code: -32024, message: "Revoked" } } + yield* mcp.subscribe("resources", { name: "job.finished" }) + const first = yield* server.opened + first.send("notifications/events/active", { cursor: "c1", truncated: false, heartbeatMs: 30_000 }) + first.send("notifications/events/event", finishedEvent("e1", "c2")) + yield* bus.delivered(1) + first.send("notifications/events/terminated", terminated) + yield* ended + + yield* mcp.subscribe("resources", { name: "job.finished" }) + const resumed = yield* server.opened + expect(resumed.params).toMatchObject({ cursor: "c2" }) + resumed.send("notifications/events/terminated", terminated) + yield* ended + + // Starting over from now forgets the events delivered before, so a server replaying one delivers it again. + yield* mcp.subscribe("resources", { name: "job.finished", cursor: null }) + const fresh = yield* server.opened + expect(fresh.params).toMatchObject({ cursor: null }) + fresh.send("notifications/events/active", { cursor: "c1", truncated: false, heartbeatMs: 30_000 }) + fresh.send("notifications/events/event", finishedEvent("e1", "c2")) + expect(yield* bus.delivered(2)).toMatchObject([{ data: { eventId: "e1" } }, { data: { eventId: "e1" } }]) + }).pipe(Effect.provide(subscriptionLayer(server.url, bus.layer))) + }), + ) + testEffect(Layer.empty).live("reopens without a replay gap when cursorless, and ends when disabled", () => Effect.gen(function* () { const server = yield* streamServer() @@ -4560,6 +4670,50 @@ describe("MCP events", () => { }), ) + testEffect(Layer.empty).live("keeps following events while a reconnect tears the old connection down", () => + Effect.gen(function* () { + const server = yield* streamServer() + // Once armed, the next tool list announcement, which the old connection's teardown makes, waits for release. + const armed = { value: false } + const reached = yield* Deferred.make() + const release = yield* Deferred.make() + const statuses = yield* Queue.unbounded() + const bus = Layer.mock(Bus.Service, { + subscribe: () => Stream.never, + publish: (definition, data) => + Effect.gen(function* () { + if (definition.type === McpEvent.StatusChanged.type) yield* Queue.offer(statuses, undefined) + if (armed.value && definition.type === McpEvent.ToolsChanged.type) { + armed.value = false + yield* Deferred.succeed(reached, undefined) + yield* Deferred.await(release) + } + return { id: ID.create(), type: definition.type, data } as Payload + }), + }) + yield* Effect.gen(function* () { + const mcp = yield* Mcp.Service + // Startup announces the handshake, then the connection, after the lists it can read. + yield* Queue.take(statuses).pipe(Effect.repeat({ times: 1 })) + armed.value = true + const reconnect = yield* mcp.connect("resources").pipe(Effect.forkScoped) + yield* Deferred.await(reached) + const during = yield* Effect.all({ + status: mcp.servers().pipe(Effect.map((servers) => servers[0]?.status)), + // Following waits for the server to come back instead of ending. + follow: mcp + .follow("resources", { name: "job.finished" }) + .pipe(Stream.take(1), Stream.runCollect, Effect.exit), + }).pipe(Effect.ensuring(Deferred.succeed(release, undefined))) + expect(during.follow).toEqual(Exit.succeed([{ type: "pending" }])) + expect(during.status).toEqual({ status: "pending" }) + + yield* Fiber.join(reconnect) + expect(yield* ready(mcp)).toEqual({ status: "connected" }) + }).pipe(Effect.provide(subscriptionLayer(server.url, bus))) + }), + ) + testEffect(Layer.empty).live("offers no events from a server without them", () => Effect.gen(function* () { const plain = yield* eventServer()