Skip to content

Commit 6c29c70

Browse files
committed
fix(core): keep MCP event watches open until they're cancelled
events/stream no longer uses the tool-call execution timeout. A watch reopens a stream the server closes from the last cursor, and stops (waking the session) after three closes in a row without an event. An event without a cursor keeps the previous one.
1 parent ee3eb17 commit 6c29c70

3 files changed

Lines changed: 116 additions & 30 deletions

File tree

‎packages/core/src/mcp/client.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,9 @@ const isTransient = (error: unknown) =>
6868
const EVENTS = "io.modelcontextprotocol/events"
6969
const SUBSCRIPTION_ID = "io.modelcontextprotocol/subscriptionId"
7070
const STREAM = "ai.opencode/stream"
71+
// A stream stays open until it's cancelled. The SDK has no unlimited timeout, and setTimeout turns anything past
72+
// 2^31 - 1 ms (about 24.8 days) into 1 ms.
73+
const STREAM_TIMEOUT = 2 ** 31 - 1
7174
const Subscribed = { _meta: Schema.Struct({ [SUBSCRIPTION_ID]: Schema.Union([Schema.String, Schema.Number]) }) }
7275

7376
const EventType = Schema.Struct({
@@ -504,10 +507,7 @@ export const connect = Effect.fnUntraced(function* (options: ConnectOptions) {
504507
client.request(
505508
{ method: "events/stream", params: { ...input, _meta: { [STREAM]: token } } },
506509
StreamResult,
507-
{
508-
signal,
509-
timeout: execution,
510-
},
510+
{ signal, timeout: STREAM_TIMEOUT },
511511
),
512512
).pipe(
513513
Effect.matchEffect({

‎packages/core/src/tool/plugin/mcp-events.ts‎

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -100,18 +100,33 @@ export const Plugin = {
100100

101101
const sessionID = context.sessionID
102102
let cursor: string | null | undefined = input.cursor
103-
const follow = () => events.stream({ name, arguments: input.arguments, cursor })
103+
let closes = 0
104+
// A server that closes the stream itself, as when it restarts in place, is followed from the last
105+
// cursor, unless it keeps closing it without sending anything.
106+
const follow = (): ReturnType<typeof events.stream> =>
107+
events
108+
.stream({ name, arguments: input.arguments, cursor })
109+
.pipe(
110+
Stream.concat(
111+
Stream.unwrap(
112+
Effect.suspend(() =>
113+
++closes > 3
114+
? Effect.fail(new Error("the server kept closing the stream"))
115+
: Effect.sleep("500 millis").pipe(Effect.as(follow())),
116+
),
117+
),
118+
),
119+
)
104120
const deleted = ctx.event.subscribe({ types: ["session.deleted"] }).pipe(
105121
Stream.filter((event) => event.data.sessionID === sessionID),
106122
Stream.runHead,
107123
)
108124
yield* follow().pipe(
109-
// A server that closes the stream itself, as when it restarts in place, is followed once more.
110-
Stream.concat(Stream.suspend(follow)),
111125
(stream) => (input.once === false ? stream : Stream.take(stream, 1)),
112126
Stream.interruptWhen(deleted),
113127
Stream.runForEach((event) => {
114-
cursor = event.cursor
128+
closes = 0
129+
if (event.cursor !== undefined) cursor = event.cursor
115130
return ctx.session.synthetic({
116131
sessionID,
117132
// A replayed event maps to the same message, which is admitted once.

‎packages/core/test/mcp-events.test.ts‎

Lines changed: 93 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
import { describe, expect } from "bun:test"
22
import { InMemoryTransport, type JSONRPCMessage } from "@modelcontextprotocol/client"
3+
import { ConfigMCP } from "@opencode/schema/config/mcp"
34
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
45
import { Flag } from "@opencode/core/flag"
56
import { Mcp } from "@opencode/core/mcp/index"
67
import { McpClient } from "@opencode/core/mcp/client"
78
import { Session } from "@opencode/core/session"
89
import { Tool } from "@opencode/core/tool"
910
import { McpEventTools } from "@opencode/core/tool/plugin/mcp-events"
10-
import { Effect, Layer, PubSub, Stream } from "effect"
11+
import { Effect, Fiber, Layer, Option, PubSub, Stream } from "effect"
1112
import { hostEnvironmentLayer } from "./fixture/environment"
1213
import { testEffect } from "./lib/effect"
1314
import { permissionLayer } from "./lib/permission"
@@ -58,7 +59,7 @@ const eventServer = Effect.fnUntraced(function* () {
5859
config: { type: "attached", transport: client },
5960
directory: import.meta.dir,
6061
}).pipe(Effect.provide(hostEnvironmentLayer)),
61-
event: (id: string | number, eventId: string, cursor: string) =>
62+
event: (id: string | number, eventId: string, cursor?: string) =>
6263
notify("notifications/events/event", id, {
6364
eventId,
6465
name: "job.finished",
@@ -155,44 +156,114 @@ describe("watch_mcp_event", () => {
155156
}),
156157
)
157158

158-
it.live("gives a replayed event the same message, follows a closed stream from its cursor once, and stops", () =>
159+
it.live("gives a replayed event the same message, follows closed streams from their cursor, and stops", () =>
159160
Effect.gen(function* () {
160161
const { state, wakes, watch, event, close, terminate, deleted } = yield* setup()
162+
const stopped = (reason: string) => ({
163+
sessionID,
164+
description: "jobs job.finished watch stopped",
165+
text: `Watching jobs job.finished stopped: ${reason}`,
166+
metadata: { source: "mcp.event", server: "jobs", event: "job.finished" },
167+
})
161168
yield* watch({ server: "jobs", event: "job.finished", once: false })
162169
yield* until(() => state.streams.length === 1)
163170
const first = state.streams[0].id
164171
yield* event(first, "e1", "c1")
165172
yield* event(first, "e1", "c1")
166173
yield* event(first, "e2", "c2")
167-
yield* until(() => wakes.length === 3)
174+
// An event without a cursor keeps the last one.
175+
yield* event(first, "e3")
176+
yield* until(() => wakes.length === 4)
168177
expect(wakes[1].id).toBe(wakes[0].id)
169178
expect(wakes[2].id).not.toBe(wakes[0].id)
170179

171-
// The server ends the stream itself, as when it restarts in place: follow it from the last event.
172-
yield* close(first)
173-
yield* until(() => state.streams.length === 2)
174-
expect(state.streams[1].params).toMatchObject({ name: "job.finished", cursor: "c2" })
180+
// The server ends the stream itself, as when it restarts in place: follow it from the last cursor, until
181+
// it has closed it three times in a row without an event.
182+
for (const index of [0, 1, 2, 3, 4, 5]) {
183+
if (index === 3) yield* event(state.streams[3].id, "e4", "c4")
184+
yield* close(state.streams[index].id)
185+
yield* until(() => state.streams.length === index + 2)
186+
expect(state.streams[index + 1].params).toMatchObject({ cursor: index < 3 ? "c2" : "c4" })
187+
}
188+
yield* close(state.streams[6].id)
189+
yield* until(() => wakes.length === 6)
190+
expect(wakes[5]).toEqual(stopped("the server kept closing the stream"))
191+
expect(state.streams).toHaveLength(7)
192+
175193
// Deleting the session cancels its stream.
194+
yield* watch({ server: "jobs", event: "job.finished", once: false })
195+
yield* until(() => state.streams.length === 8)
176196
yield* PubSub.publish(deleted, { type: "session.deleted", data: { sessionID } })
177-
yield* until(() => state.cancelled.includes(state.streams[1].id))
197+
yield* until(() => state.cancelled.includes(state.streams[7].id))
178198

179199
// A terminated stream ends the watch and wakes the session to say so, once.
180200
yield* watch({ server: "jobs", event: "job.finished", once: false })
181-
yield* until(() => state.streams.length === 3)
182-
const third = state.streams[2].id
183-
yield* terminate(third)
184-
yield* event(third, "e3", "c3")
185-
yield* until(() => wakes.length === 4)
201+
yield* until(() => state.streams.length === 9)
202+
const last = state.streams[8].id
203+
yield* terminate(last)
204+
yield* event(last, "e5", "c5")
205+
yield* until(() => wakes.length === 7)
186206
yield* Effect.sleep("20 millis")
187-
expect(wakes.slice(3)).toEqual([
188-
{
189-
sessionID,
190-
description: "jobs job.finished watch stopped",
191-
text: "Watching jobs job.finished stopped: Forbidden",
192-
metadata: { source: "mcp.event", server: "jobs", event: "job.finished" },
207+
expect(wakes.slice(6)).toEqual([stopped("Forbidden")])
208+
expect(state.streams).toHaveLength(9)
209+
}),
210+
)
211+
212+
it.live("keeps a stream open past the server's execution timeout", () =>
213+
Effect.gen(function* () {
214+
// A Streamable HTTP server that holds `events/stream` open as SSE and sends one event when told to.
215+
const opened: Array<(event: Record<string, unknown>) => void> = []
216+
const http = Bun.serve({
217+
port: 0,
218+
fetch: async (request) => {
219+
if (request.method !== "POST") return new Response(null, { status: 405 })
220+
const message = (await request.json()) as {
221+
id?: string | number
222+
method: string
223+
params: { protocolVersion?: string }
224+
}
225+
if (message.id === undefined) return new Response(null, { status: 202 })
226+
if (message.method === "initialize")
227+
return Response.json({
228+
jsonrpc: "2.0",
229+
id: message.id,
230+
result: {
231+
protocolVersion: message.params.protocolVersion,
232+
capabilities: { extensions: { "io.modelcontextprotocol/events": {} } },
233+
serverInfo: { name: "jobs", version: "1.0.0" },
234+
},
235+
})
236+
const body = new ReadableStream({
237+
start: (controller) =>
238+
void opened.push((params) =>
239+
controller.enqueue(
240+
new TextEncoder().encode(
241+
`data: ${JSON.stringify({ jsonrpc: "2.0", method: "notifications/events/event", params: { ...params, _meta: { "io.modelcontextprotocol/subscriptionId": message.id } } })}\n\n`,
242+
),
243+
),
244+
),
245+
})
246+
return new Response(body, { headers: { "content-type": "text/event-stream" } })
193247
},
194-
])
195-
expect(state.streams).toHaveLength(3)
248+
})
249+
yield* Effect.addFinalizer(() => Effect.promise(() => http.stop(true)))
250+
const connection = yield* McpClient.connect({
251+
server: "jobs",
252+
config: new ConfigMCP.Remote({
253+
type: "remote",
254+
url: http.url.href,
255+
oauth: false,
256+
timeout: new ConfigMCP.Timeout({ execution: 50 }),
257+
}),
258+
directory: import.meta.dir,
259+
}).pipe(Effect.provide(hostEnvironmentLayer))
260+
const next = yield* Effect.forkChild(Stream.runHead(connection.events!.stream({ name: "job.finished" })), {
261+
startImmediately: true,
262+
})
263+
yield* until(() => opened.length === 1)
264+
yield* Effect.sleep("150 millis")
265+
opened[0]({ eventId: "e1", name: "job.finished", timestamp: "2026-11-10T00:00:00Z", data: {}, cursor: "c1" })
266+
expect(Option.getOrThrow(yield* Fiber.join(next))).toMatchObject({ eventId: "e1", cursor: "c1" })
196267
}),
197268
)
198269

0 commit comments

Comments
 (0)