mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-21 04:12:08 +03:00
fix(core): finish MCP connect and disconnect when the caller is interrupted (#61806)
This commit is contained in:
@@ -7,7 +7,21 @@ 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, FiberSet, Latch, Layer, Schema, Scope, Semaphore, Stream, Types } from "effect"
|
||||
import {
|
||||
Clock,
|
||||
Context,
|
||||
Effect,
|
||||
Exit,
|
||||
Fiber,
|
||||
FiberSet,
|
||||
Latch,
|
||||
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"
|
||||
@@ -208,6 +222,12 @@ export const layer = (options?: Options) =>
|
||||
// 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<ServerName>()
|
||||
// Runs a requested lifecycle operation to the end even if its caller is interrupted, such as by a
|
||||
// client dropping the HTTP request. Stopped halfway, a server stays "pending" after a cancelled
|
||||
// connect, or "connected" with no connection after a cancelled disconnect. Location shutdown
|
||||
// still interrupts it.
|
||||
const transition = <E>(effect: Effect.Effect<void, E>) =>
|
||||
Effect.forkIn(effect, root, { startImmediately: true }).pipe(Effect.flatMap(Fiber.join))
|
||||
// Attached connections lock separately so a configured server of the same name never contends.
|
||||
const attachedLocks = KeyedMutex.makeUnsafe<ServerName>()
|
||||
// Legacy era only: pending URL-mode elicitation forms, settled by notifications/elicitation/complete.
|
||||
@@ -701,20 +721,24 @@ export const layer = (options?: Options) =>
|
||||
}),
|
||||
connect: Effect.fn("MCP.connect")(function* (server) {
|
||||
const name = ServerName.make(server)
|
||||
yield* Effect.gen(function* () {
|
||||
const entry = yield* requireServer(name)
|
||||
yield* entry.connection.stop
|
||||
yield* entry.connection.start
|
||||
}).pipe(locks.withLock(name))
|
||||
yield* transition(
|
||||
Effect.gen(function* () {
|
||||
const entry = yield* requireServer(name)
|
||||
yield* entry.connection.stop
|
||||
yield* entry.connection.start
|
||||
}).pipe(locks.withLock(name)),
|
||||
)
|
||||
}),
|
||||
disconnect: Effect.fn("MCP.disconnect")(function* (server) {
|
||||
const name = ServerName.make(server)
|
||||
yield* Effect.gen(function* () {
|
||||
const entry = yield* requireServer(name)
|
||||
yield* entry.connection.stop
|
||||
entry.status = { status: "disabled" }
|
||||
yield* bus.publish(McpEvent.StatusChanged, { server: name })
|
||||
}).pipe(locks.withLock(name))
|
||||
yield* transition(
|
||||
Effect.gen(function* () {
|
||||
const entry = yield* requireServer(name)
|
||||
yield* entry.connection.stop
|
||||
entry.status = { status: "disabled" }
|
||||
yield* bus.publish(McpEvent.StatusChanged, { server: name })
|
||||
}).pipe(locks.withLock(name)),
|
||||
)
|
||||
}),
|
||||
remove: Effect.fn("MCP.remove")(function* (server) {
|
||||
const name = ServerName.make(server)
|
||||
|
||||
@@ -2406,6 +2406,74 @@ test("serializes concurrent MCP lifecycle operations", async () => {
|
||||
)
|
||||
})
|
||||
|
||||
const awaitStatus = (service: Mcp.Interface, status: Mcp.Status["status"]) =>
|
||||
service.servers().pipe(
|
||||
Effect.map((servers) => servers.find((server) => server.name === "resources")?.status),
|
||||
Effect.filterOrFail(
|
||||
(current) => current?.status === status,
|
||||
(current) => new Error(`MCP server status is ${JSON.stringify(current)}, expected ${status}`),
|
||||
),
|
||||
Effect.retry({ schedule: Schedule.spaced("10 millis") }),
|
||||
Effect.timeout("5 seconds"),
|
||||
)
|
||||
|
||||
testEffect(Layer.empty).live("finishes an MCP connect whose caller is interrupted during the handshake", () =>
|
||||
Effect.gen(function* () {
|
||||
const started = yield* Deferred.make<void>()
|
||||
const release = yield* Deferred.make<void>()
|
||||
const server = yield* resourceServer({
|
||||
respond: async (request) => {
|
||||
if (request.method !== "POST") return undefined
|
||||
const body: unknown = await request.clone().json()
|
||||
if (typeof body !== "object" || body === null || !("method" in body) || body.method !== "initialize")
|
||||
return undefined
|
||||
await Effect.runPromise(Deferred.succeed(started, undefined).pipe(Effect.andThen(Deferred.await(release))))
|
||||
return undefined
|
||||
},
|
||||
})
|
||||
yield* Effect.gen(function* () {
|
||||
const service = yield* Mcp.Service
|
||||
const connecting = yield* service.connect("resources").pipe(Effect.forkChild({ startImmediately: true }))
|
||||
yield* Deferred.await(started)
|
||||
yield* Fiber.interrupt(connecting)
|
||||
yield* Deferred.succeed(release, undefined)
|
||||
|
||||
yield* awaitStatus(service, "connected")
|
||||
expect((yield* service.tools()).length).toBeGreaterThan(0)
|
||||
}).pipe(
|
||||
Effect.ensuring(Deferred.succeed(release, undefined)),
|
||||
Effect.provide(
|
||||
resourceMcpLayer(new ConfigMCP.Remote({ type: "remote", url: server.url, oauth: false, disabled: true })),
|
||||
),
|
||||
)
|
||||
}),
|
||||
)
|
||||
|
||||
testEffect(Layer.empty).live("finishes an MCP disconnect whose caller is interrupted while the session ends", () =>
|
||||
Effect.gen(function* () {
|
||||
const started = yield* Deferred.make<void>()
|
||||
const release = yield* Deferred.make<void>()
|
||||
const server = yield* resourceServer({
|
||||
respond: async (request) => {
|
||||
if (request.method !== "DELETE") return undefined
|
||||
await Effect.runPromise(Deferred.succeed(started, undefined).pipe(Effect.andThen(Deferred.await(release))))
|
||||
return undefined
|
||||
},
|
||||
})
|
||||
yield* Effect.gen(function* () {
|
||||
const service = yield* Mcp.Service
|
||||
expect(yield* settled(service)).toEqual({ status: "connected" })
|
||||
const disconnecting = yield* service.disconnect("resources").pipe(Effect.forkChild({ startImmediately: true }))
|
||||
yield* Deferred.await(started)
|
||||
yield* Fiber.interrupt(disconnecting)
|
||||
yield* Deferred.succeed(release, undefined)
|
||||
|
||||
yield* awaitStatus(service, "disabled")
|
||||
expect(yield* service.tools()).toEqual([])
|
||||
}).pipe(Effect.ensuring(Deferred.succeed(release, undefined)), Effect.provide(resourceMcpLayer(server.url)))
|
||||
}),
|
||||
)
|
||||
|
||||
testEffect(Layer.empty).live("preserves plugin transforms through MCP catalog updates", () =>
|
||||
Effect.gen(function* () {
|
||||
const tool = (server: string, name: string, description = name) =>
|
||||
|
||||
Reference in New Issue
Block a user