Skip to content

MCP server stdio pipe torn down when plugin entrypoint is rewritten mid-call, dropping in-flight tool calls ("Connection closed") #68514

Description

@dcerisano

Summary

When a file in a watched plugin directory (specifically the plugin entrypoint dist/index.js) is rewritten while an MCP stdio tool call is in flight, opencode tears down the MCP stdio transport, dropping the in-flight call with Connection closed. The server (Serena) then exits with anyio.BrokenResourceError on its stdin reader, and opencode auto-reconnects ~2s later. The underlying tool subprocess is not killed — only the MCP round-trip is lost, so the work is silently discarded from the caller's perspective.

Environment

  • opencode v2.4.3
  • Serena MCP server (uvx, stdio transport), 30 tools
  • Linux
  • Plugins loaded from a local watched directory containing dist/index.js

Symptom

An in-flight execute_shell_command MCP call fails with:

MCP tool "execute_shell_command" on server "serena" failed: Connection closed

opencode logs WARN failed to call MCP tool ... error="Connection closed", followed by a watcher/plugin-reload burst, then mcp connected server=serena tools=30 ~2.1–2.2s later. The shell subprocess itself completes; only the MCP round-trip is lost.

Serena-side, the MCP server exits 1 with a traceback ending in anyio.BrokenResourceError from mcp/server/stdio.py stdin_reader — i.e. the host closed the stdio pipe, the server's in-process stream was closed underneath it.

Minimal reproduction

All calls made through the same MCP stdio connection. Baseline controls first, then the trigger:

# Command Result
1 echo BASELINE_OK OK 66 ms
2 sleep 15; echo done OK 15027 ms
3 sleep 25; echo done OK 25034 ms
4 seq 1 20000 (~50k chars output) OK 52 ms
5 22 s shell call + background touch AGENTS.md at 3 s OK 22207 ms
6 22 s shell call + background touch dist/index.js at 3 s DISCONNECT at 5250 ms
7 (confirm) 10 s shell call + touch dist/index.js at 2 s DISCONNECT at 4162 ms

Duration and output size are not sufficient triggers (rows 1–5 succeed). The trigger is overlap with a write to the watched plugin directory (dist/index.js), which is repeatable (rows 6, 7).

Minimal trigger:

# while a long MCP tool call is in flight, in another shell:
touch dist/index.js   # plugin entrypoint inside a watched plugin dir

Expected vs actual

  • Expected: rewriting a plugin file may reload the plugin, but an in-flight MCP tool call should either be allowed to drain, or the caller should get a clear "server restarting, retry" signal — not a silent Connection closed with the request abandoned.
  • Actual: the stdio transport is closed mid-call; the in-flight request fails with Connection closed; the server exits non-zero; opencode reconnects unconditionally ~2s later. The tool's subprocess keeps running, so the result is lost and the caller cannot tell whether the work completed.

Log signature

opencode:

WARN failed to call MCP tool server=serena error="Connection closed"
... watcher/plugin-reload burst (command.updated / provider.updated / model.updated) ...
INFO mcp connected server=serena tools=30      # ~2.1-2.2 s later

Serena:

ERROR MCP server process exited with code 1
anyio.BrokenResourceError  (mcp/server/stdio.py: stdin_reader -> ...)

Relation to existing issues

Distinct part not covered by the above

There is no plugin-side hook to veto or pause the reload, nor to drain in-flight MCP calls before reconnect. The MCP lifecycle is host-owned; reconnect is unconditional. A way to (a) suppress reload for a known-watched dir, or (b) drain/park in-flight MCP tool calls across a reload, would resolve this.

Impact

  • In-flight MCP tool calls fail with an opaque Connection closed while their subprocess keeps running — silent work loss / duplicate execution risk.
  • Recovers only by client auto-reconnect (~2s), during which all MCP calls fail.

Evidence gathered via bounded, controlled experiments; not claiming a specific internal cause beyond "host closes the stdio pipe during a plugin-reload overlap".

Activity

  1. added
    area/mcp
    type/bug
    version/v2
    on Dec 5, 2026
  2. opencodejr commented on Dec 5, 2026

    @opencodejr
    Contributor

    I couldn't reproduce this on 2.4.3 (Linux). My setup was a minimal stdio MCP server with a 12 s tool and a local plugin with entrypoint dist/index.js. I tried the plugin in .opencode/plugins/, listed in plugins in the project's opencode.json, and at the project root. In each case, touching dist/index.js during the call reloaded the plugin, but the MCP server kept running (same pid, no stdin EOF) and the call returned normally. That fits the code: a reload only restarts MCP servers whose config changed.

    Your log shows provider.updated / model.updated during the reload, so what your plugin does when it loads probably matters. These would help:

    • What the plugin's setup registers or changes: providers, models, commands, and especially anything that touches MCP config (ctx.mcp.transform, or values that differ on each load).
    • How Serena is defined (config vs plugin), and the debug log (--log-level debug) around one touch, filtered for mcp and plugin.
  3. opencodejr commented on Dec 5, 2026

    @opencodejr
    Contributor

    Closing this as not planned: I could not reproduce the problem with what the report gives. Replying here reopens the issue.

  4. dcerisano commented on Dec 6, 2026

    @dcerisano
    Author

    Reopening with a reproduction that includes the missing ingredient.

    The earlier attempt did not reproduce because its minimal plugin never disposed its own registrations. This plugin's setup() returns a cleanup that explicitly calls registration.dispose(). That explicit disposal is what tears down the MCP pipe; the transform's values are constant, so this is not a config-diff restart.

    Mechanism (short): during a plugin reload the host closes the old activation and loads the replacement inside a State.batch. But a registration disposed from the plugin's own cleanup runs through the Promise adapter's captured setup-time runtime (packages/plugin/src/promise/adapter.ts), whose State.batch is already inactive. So registration.remove() -> changed -> notify runs immediately instead of joining the reload batch. The rebuilt MCP map has no serena entry because the new setup has not registered its transform yet (it awaits session.list() first). Reconcile then sees servers.get("serena") === undefined, fails the guard at packages/core/src/mcp/index.ts (isDeepStrictEqual(entry.config, updated)), and stops the stdio connection.

    Minimal plugin (reproduces)

    // index.js in a directory listed in opencode.json "plugins"
    export default {
      id: "repro-explicit-dispose",
      async setup(ctx) {
        await new Promise((resolve) => setTimeout(resolve, 500))
    
        const registration = await ctx.mcp.transform((mcp) => {
          mcp.set("serena", {
            type: "local",
            command: [
              "uvx", "-p", "3.13", "--from", "serena-agent",
              "serena", "start-mcp-server",
              "--project-from-cwd", "--open-web-dashboard=False",
            ],
            cwd: ctx.location.directory,
            disabled: false,
            timeout: { startup: 120000 },
          })
        })
    
        // Explicit disposal: this escapes the reload batch and drops the server.
        return () => {
          void registration.dispose()
        }
      },
    }

    Control (does not reproduce)

    Same transform values, but leave disposal to the host scope (do not call registration.dispose() in the cleanup):

    return () => {}

    Steps

    1. opencode.json:
      {
        "plugins": ["/absolute/path/to/this/plugin"],
        "experimental": { "todo": true }
      }
    2. Start opencode in that project.
    3. Run a long call through Serena: sleep 22; echo LONG_DONE.
    4. While it is in flight: touch /absolute/path/to/this/plugin/index.js (or dist/index.js).

    Observed (explicit-dispose plugin): MCP tool "execute_shell_command" on server "serena" failed: Connection closed, then mcp connected server=serena tools=30 about 2 s later; the sleep keeps running and its result is lost.

    Observed (control): the call returns normally; the reload does not drop the in-flight request.

    Why this matches #55934/#66471: build output under a watched plugin directory still triggers the reload; watcher.ignore is the user-side workaround, but the reload path itself still drops calls.

  5. opencodejr commented on Dec 6, 2026

    @opencodejr
    Contributor

    Seen with a simulated model or a mock server, not a real provider; a maintainer should confirm.

    This still happens on the latest dev (045e9e3), and also on 2.4.3. Thanks for the plugin that triggers it.

    What I saw: a Promise plugin listed in plugins waits 500 ms, registers a stdio server through ctx.mcp.transform with fixed values, and calls registration.dispose() in its cleanup. I started a 12 s MCP call and touched dist/index.js 3 s in. About 1 ms after the plugin's cleanup ran, OpenCode closed the server's stdin, and a new server process started about 0.5 s later. The call failed with MCP tool "sleep" on server "sleepy" failed: Connection closed. With a cleanup that doesn't call dispose(), the same server process stayed up and the call returned normally.

    A small Node MCP server stood in for Serena, and the simulated model made the tool call. The script and recording below show both runs.

    Likely cause (not confirmed): in packages/plugin/src/promise/adapter.ts (register, around line 250), dispose runs with the runtime captured at setup. That runtime still carries the original State.batch, which is no longer active (packages/core/src/state.ts batch()). The removal therefore takes effect immediately instead of joining the reload, so the MCP reconcile in packages/core/src/mcp/index.ts sees the server as removed and stops it.

    Workaround until it's fixed: leave disposal to the plugin scope (return a cleanup that doesn't call dispose()).

    https://anoma.ly/team/github-bot/media/f3df63924c5ae77fed9381c8ee76d841de7f12e20e149d7787eede4c5d1f2961.mp4

    Screenshot

    Reproduction script (drive.ts)
    // Repro for #68514: touching a local plugin entrypoint during an in-flight MCP stdio call.
    import { Effect, Stream } from "effect"
    import { Llm, OpenCodeDriver } from "opencode-drive"
    import fs from "node:fs"
    import path from "node:path"
    
    const LOG = "/workspace/repro/mcp.log"
    const SERVER = `
    import fs from "node:fs"; import readline from "node:readline"
    const LOG = ${JSON.stringify(LOG)}
    const log = (m) => fs.appendFileSync(LOG, new Date().toISOString() + " pid=" + process.pid + " " + m + "\\n")
    log("START")
    const send = (o) => process.stdout.write(JSON.stringify(o) + "\\n")
    readline.createInterface({ input: process.stdin }).on("line", (line) => {
      let msg; try { msg = JSON.parse(line) } catch { return }
      if (msg.id === undefined) return
      if (msg.method === "initialize") return send({ jsonrpc: "2.0", id: msg.id, result: { protocolVersion: msg.params?.protocolVersion ?? "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "sleepy", version: "1.0.0" } } })
      if (msg.method === "tools/list") return send({ jsonrpc: "2.0", id: msg.id, result: { tools: [{ name: "sleep", description: "sleep N seconds", inputSchema: { type: "object", properties: { seconds: { type: "number" } } } }] } })
      if (msg.method === "tools/call") { const s = msg.params?.arguments?.seconds ?? 10; log("CALL sleep " + s); return setTimeout(() => { log("CALL done"); send({ jsonrpc: "2.0", id: msg.id, result: { content: [{ type: "text", text: "slept " + s }] } }) }, s * 1000) }
      send({ jsonrpc: "2.0", id: msg.id, result: {} })
    })
    process.stdin.on("end", () => { log("STDIN EOF (host closed pipe)"); process.exit(1) })
    process.on("SIGTERM", () => { log("SIGTERM"); process.exit(0) })
    `
    const PDIR = process.env.PDIR ?? "myplug"
    // Plugin shaped like the reporter's: waits, registers the MCP server via ctx.mcp.transform with constant
    // values, and (unless CONTROL=1) disposes that registration itself in its cleanup.
    const PLUGIN = `import fs from "node:fs"
    const log = (m) => fs.appendFileSync(${JSON.stringify(LOG)}, new Date().toISOString() + " " + m + "\\n")
    export default {
      id: "repro-explicit-dispose",
      async setup(ctx) {
        log("PLUGIN setup")
        await new Promise((r) => setTimeout(r, 500))
        const registration = await ctx.mcp.transform((mcp) => {
          mcp.set("sleepy", { type: "local", command: ["node", "/workspace/repro/sleepy-mcp.mjs"], codemode: false })
        })
        log("PLUGIN transform registered")
        return () => { log("PLUGIN cleanup${process.env.CONTROL ? " (no dispose)" : " -> registration.dispose()"}")${process.env.CONTROL ? "" : "; void registration.dispose()"} }
      },
    }
    `
    const TOUCH = process.env.TOUCH ?? `${PDIR}/dist/index.js`
    
    export default OpenCodeDriver.use(
      {
        ...(process.env.OC_DEV ? { opencode: { dev: process.env.OC_DEV } } : {}),
        tui: { recording: true },
        project: {
          git: true,
          files: {
            "AGENTS.md": "# notes\n",
            "opencode.json": JSON.stringify({ plugins: ["./" + PDIR] }),
            [`${PDIR}/package.json`]: JSON.stringify({ name: "myplug", version: "1.0.0", type: "module", exports: { ".": "./dist/index.js" } }),
            [`${PDIR}/dist/index.js`]: PLUGIN,
          },
        },
        setup: () =>
          Effect.sync(() => {
            fs.writeFileSync(LOG, "")
            fs.writeFileSync("/workspace/repro/sleepy-mcp.mjs", SERVER)
                  }),
      },
      ({ ui, llm, directory }) =>
        Effect.gen(function* () {
          yield* Effect.sleep(6000) // let MCP connect
          // 1st model turn: call the MCP tool. 2nd turn: echo the tool result OpenCode sent back, so it shows on screen.
          yield* llm.serve((request, index) => {
            if (index === 0)
              return Stream.make(
                Llm.toolCall({ index: 0, id: "call_sleep", name: "sleepy_sleep", input: { seconds: 12 } }),
                Llm.finish("tool-calls"),
              )
            const body = JSON.stringify(request)
            const result = body.replace(/\\+"/g, "'").match(/MCP tool[^"]*/)?.[0]?.split("'}")[0] ?? body.match(/slept \d+/)?.[0] ?? "no tool result found"
            fs.appendFileSync(LOG, `${new Date().toISOString()} TOOL RESULT seen by model: ${result}\n`)
            return Stream.make(Llm.text(`Tool result: ${result}`))
          })
          yield* ui.submit("Call the sleepy sleep tool for 12 seconds")
          yield* Effect.sleep(3000)
          const target = path.join(directory, TOUCH)
          yield* Effect.sync(() => { const t = new Date(); fs.utimesSync(target, t, t); fs.appendFileSync(LOG, `${t.toISOString()} DRIVER touched ${TOUCH}\n`) })
          yield* ui.waitFor("Tool result:", { timeout: 20000 })
          yield* Effect.sleep(1500)
          yield* ui.screenshot("after")
          yield* Effect.log(fs.readFileSync(LOG, "utf8"))
        }),
    )

    Run it with opencode-drive: opencode-drive run ./drive.ts. It drives opencode from your PATH; set OC_DEV to the path of an OpenCode checkout to run that from source instead.

  6. added
    status/repro-simulated
    on Dec 6, 2026
  7. opencodejr commented on Dec 6, 2026

    @opencodejr
    Contributor

    I opened a pull request with a fix: #68589. A maintainer will review it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area/mcpplatform/linuxstatus/repro-simulatedtype/bugversion/v2

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions