Skip to content

Commit 60c13a2

Browse files
fix(mcp): drop a connect that a newer add, connect, disconnect or remove superseded
createAndStore committed its result on resume without checking whether the server had changed while it connected, so a remove brought the server back and an older config overwrote a newer one. Each call now takes a per-server generation; a connect that resumes behind a newer one closes its own client instead of committing. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_0172qrhMa5TQgETASi5hxMqD
1 parent e3d6e0a commit 60c13a2

2 files changed

Lines changed: 137 additions & 2 deletions

File tree

‎packages/opencode/src/mcp/index.ts‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,9 @@ interface State {
297297
// in the same statement as `defs` so a reader never pairs one listing's tools
298298
// with another's report (see Interface.snapshot).
299299
meta: Record<string, Record<string, unknown> | undefined>
300+
// Bumped by every add, connect, disconnect and remove of a server, so a connect
301+
// that resumes after a newer call for the same server knows it was superseded.
302+
generation: Record<string, number>
300303
// altimate_change end
301304
}
302305

@@ -817,8 +820,9 @@ export const layer = Layer.effect(
817820
status: {},
818821
clients: {},
819822
defs: {},
820-
// altimate_change start — see State.meta
823+
// altimate_change start — see State.meta and State.generation
821824
meta: {},
825+
generation: {},
822826
// altimate_change end
823827
}
824828

@@ -916,6 +920,12 @@ export const layer = Layer.effect(
916920
}),
917921
)
918922

923+
// altimate_change start — see State.generation
924+
function supersede(s: State, name: string) {
925+
return (s.generation[name] = (s.generation[name] ?? 0) + 1)
926+
}
927+
// altimate_change end
928+
919929
function closeClient(s: State, name: string) {
920930
const client = s.clients[name]
921931
delete s.clients[name]
@@ -998,7 +1008,17 @@ export const layer = Layer.effect(
9981008

9991009
const createAndStore = Effect.fn("MCP.createAndStore")(function* (name: string, mcp: ConfigMCPV1.Info) {
10001010
const s = yield* InstanceState.get(state)
1011+
// altimate_change start — a remove, disconnect or newer add/connect that runs while
1012+
// this one is connecting supersedes it: committing then would bring a removed server
1013+
// back or overwrite the newer config, so this attempt closes its own client instead.
1014+
const mine = supersede(s, name)
10011015
const result = yield* create(name, mcp)
1016+
if (s.generation[name] !== mine) {
1017+
const stale = result.mcpClient
1018+
if (stale) yield* Effect.tryPromise(() => stale.close()).pipe(Effect.ignore)
1019+
return result.status
1020+
}
1021+
// altimate_change end
10021022

10031023
s.status[name] = result.status
10041024
if (!result.mcpClient) {
@@ -1030,6 +1050,9 @@ export const layer = Layer.effect(
10301050
const disconnect = Effect.fn("MCP.disconnect")(function* (name: string) {
10311051
yield* requireMcpConfig(name)
10321052
const s = yield* InstanceState.get(state)
1053+
// altimate_change start — see createAndStore
1054+
supersede(s, name)
1055+
// altimate_change end
10331056
// altimate_change start — telemetry: explicit disconnect
10341057
const transport: TransportLabel =
10351058
s.clients[name]?.transport instanceof StdioClientTransport ? "stdio" : "streamable-http"
@@ -1057,6 +1080,7 @@ export const layer = Layer.effect(
10571080
// ToolsChanged, so the agent keeps offering tools from a removed server until the next restart.
10581081
const remove = Effect.fn("MCP.remove")(function* (name: string) {
10591082
const s = yield* InstanceState.get(state)
1083+
supersede(s, name)
10601084
yield* closeClient(s, name)
10611085
delete s.clients[name]
10621086
delete s.status[name]

‎packages/opencode/test/mcp/lifecycle.test.ts‎

Lines changed: 112 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import os, { tmpdir } from "node:os"
44
import { pathToFileURL } from "node:url"
55
import { expect, mock, beforeEach, afterEach, spyOn } from "bun:test"
66
import { ListRootsRequestSchema, ToolListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js"
7-
import { Cause, Effect, Exit } from "effect"
7+
import { Cause, Effect, Exit, Fiber } from "effect"
88
import type { MCP as MCPNS } from "../../src/mcp/index"
99
import { testEffect } from "../lib/effect"
1010
import { TestInstance } from "../fixture/fixture"
@@ -50,6 +50,17 @@ const clientStates = new Map<string, MockClientState>()
5050
let lastCreatedClientName: string | undefined
5151
let connectShouldFail = false
5252
let connectShouldHang = false
53+
// altimate_change start — hold exactly one connect until the test releases it
54+
let connectGate: { taken: () => void; release: Promise<void> } | undefined
55+
const createdClients: Array<{ closedSelf: boolean; transport: any }> = []
56+
function gateNextConnect() {
57+
let taken!: () => void
58+
let release!: () => void
59+
const wasTaken = new Promise<void>((resolve) => (taken = resolve))
60+
connectGate = { taken: () => taken(), release: new Promise<void>((resolve) => (release = resolve)) }
61+
return { wasTaken, release: () => release() }
62+
}
63+
// altimate_change end
5364
let connectError = "Mock transport cannot connect"
5465
// Tracks how many Client instances were created (detects leaks)
5566
let clientCreateCount = 0
@@ -92,10 +103,24 @@ function getOrCreateClientState(name?: string): MockClientState {
92103
class MockStdioTransport {
93104
stderr: null = null
94105
pid = 12345
106+
// altimate_change start — kept per instance, so a test can tell two connects apart
107+
opts: any
108+
// altimate_change end
95109
constructor(opts: any) {
96110
if (lastCreatedClientName) stdioOptsByName.set(lastCreatedClientName, opts)
111+
// altimate_change start
112+
this.opts = opts
113+
// altimate_change end
97114
}
98115
async start() {
116+
// altimate_change start — see connectGate
117+
const gate = connectGate
118+
connectGate = undefined
119+
if (gate) {
120+
gate.taken()
121+
await gate.release
122+
}
123+
// altimate_change end
99124
if (connectShouldHang) return new Promise<void>(() => {}) // never resolves
100125
if (connectShouldFail) throw new Error(connectError)
101126
}
@@ -154,9 +179,15 @@ void mock.module("@modelcontextprotocol/sdk/client/index.js", () => ({
154179
Client: class MockClient {
155180
_state!: MockClientState
156181
transport: any
182+
// altimate_change start — closed per instance; `_state.closed` is shared by name
183+
closedSelf = false
184+
// altimate_change end
157185

158186
constructor(_info: any, options?: MockClientState["clientOptions"]) {
159187
clientCreateCount++
188+
// altimate_change start
189+
createdClients.push(this)
190+
// altimate_change end
160191
this._state = getOrCreateClientState(lastCreatedClientName)
161192
this._state.clientOptions = options
162193
}
@@ -238,6 +269,9 @@ void mock.module("@modelcontextprotocol/sdk/client/index.js", () => ({
238269

239270
async close() {
240271
if (this._state) this._state.closed = true
272+
// altimate_change start
273+
this.closedSelf = true
274+
// altimate_change end
241275
}
242276
},
243277
}))
@@ -259,6 +293,10 @@ beforeEach(() => {
259293
lastCreatedClientName = undefined
260294
connectShouldFail = false
261295
connectShouldHang = false
296+
// altimate_change start
297+
connectGate = undefined
298+
createdClients.length = 0
299+
// altimate_change end
262300
connectError = "Mock transport cannot connect"
263301
clientCreateCount = 0
264302
transportCloseCount = 0
@@ -526,6 +564,79 @@ it.instance(
526564
},
527565
)
528566

567+
// altimate_change start — a connect that resumes after a newer call for the same server
568+
// must not commit: it would bring a removed server back or overwrite a newer config. (review)
569+
it.instance(
570+
"a server removed while it is still connecting stays removed, and the late client is closed",
571+
() =>
572+
MCP.Service.use((mcp: MCPNS.Interface) =>
573+
Effect.gen(function* () {
574+
lastCreatedClientName = "late-server"
575+
const gate = gateNextConnect()
576+
const adding = yield* Effect.forkChild(mcp.add("late-server", { type: "local", command: ["echo", "a"] }))
577+
yield* Effect.promise(() => gate.wasTaken)
578+
579+
yield* mcp.remove("late-server")
580+
gate.release()
581+
yield* Fiber.join(adding)
582+
583+
expect((yield* mcp.status())["late-server"]).toBeUndefined()
584+
expect((yield* mcp.clients())["late-server"]).toBeUndefined()
585+
expect(createdClients).toHaveLength(1)
586+
expect(createdClients[0].closedSelf).toBe(true)
587+
}),
588+
),
589+
{ config: { mcp: {} } },
590+
)
591+
592+
it.instance(
593+
"a server disconnected while it is still connecting stays disabled",
594+
() =>
595+
MCP.Service.use((mcp: MCPNS.Interface) =>
596+
Effect.gen(function* () {
597+
lastCreatedClientName = "late-disc"
598+
const gate = gateNextConnect()
599+
const adding = yield* Effect.forkChild(mcp.add("late-disc", { type: "local", command: ["echo", "a"] }))
600+
yield* Effect.promise(() => gate.wasTaken)
601+
602+
yield* mcp.disconnect("late-disc")
603+
gate.release()
604+
yield* Fiber.join(adding)
605+
606+
expect((yield* mcp.status())["late-disc"]?.status).toBe("disabled")
607+
expect((yield* mcp.clients())["late-disc"]).toBeUndefined()
608+
expect(createdClients[0].closedSelf).toBe(true)
609+
}),
610+
),
611+
{ config: { mcp: {} } },
612+
)
613+
614+
it.instance(
615+
"a newer config added while an older one is still connecting is the one kept",
616+
() =>
617+
MCP.Service.use((mcp: MCPNS.Interface) =>
618+
Effect.gen(function* () {
619+
lastCreatedClientName = "late-swap"
620+
const gate = gateNextConnect()
621+
const older = yield* Effect.forkChild(mcp.add("late-swap", { type: "local", command: ["echo", "older"] }))
622+
yield* Effect.promise(() => gate.wasTaken)
623+
624+
yield* mcp.add("late-swap", { type: "local", command: ["echo", "newer"] })
625+
gate.release()
626+
yield* Fiber.join(older)
627+
628+
const [first, second] = createdClients
629+
expect((yield* mcp.status())["late-swap"]?.status).toBe("connected")
630+
expect((yield* mcp.clients())["late-swap"]).toBe(second as any)
631+
expect(second.transport.opts.args).toEqual(["newer"])
632+
expect(second.closedSelf).toBe(false)
633+
expect(first.closedSelf).toBe(true)
634+
}),
635+
),
636+
{ config: { mcp: {} } },
637+
)
638+
// altimate_change end
639+
529640
// altimate_change start — remove forgets the runtime config
530641
it.instance(
531642
"remove forgets the key entirely, so it no longer reports as disabled",

0 commit comments

Comments
 (0)