Skip to content

mcp: list_changed stops for good once the modern subscriptions/listen stream ends #66072

Backlog

Description

@shaojunying

Description

On a 2026-07-28 (modern) MCP connection, tools/list_changed, prompts/list_changed and resources/list_changed arrive on the subscriptions/listen stream that the SDK opens during connect. If that stream ends (server redeploy, proxy idle timeout, serverless response limit, network blip), opencode never opens it again. The server still shows connected, but its tool list is frozen until the user reconnects it by hand.

The SDK leaves this to the caller. Its listen() docs say "No automatic re-listen — call listen() again to re-establish."

opencode already does this for the MCP Events listen stream in packages/core/src/mcp/client.ts:945-972 (reopen with the reopen backoff, then relist). The list-changed stream has no equivalent:

  • client.ts:348-358 and client.ts:415-420 register the list-changed handlers and let the SDK auto-open the stream.
  • Nothing watches client.autoOpenedSubscription?.closed, so connection.ts:157 (onToolsChanged) never fires again after the stream ends.
  • If the auto-open fails during connect, the SDK only reports it to onerror, and there is no retry either.

Fix idea: on a modern connection, watch autoOpenedSubscription.closed (or open the subscription ourselves) and reopen it with the same backoff as the events stream. After each reopen, run the tools/prompts/resources changed callbacks once, to pick up changes missed while the stream was down.

I can send a PR with a test if this approach is OK.

Plugins

No response

OpenCode version

dev adc958a7d7 (2.4.1)

Steps to reproduce

  1. Run a modern MCP server (createMcpHandler from @modelcontextprotocol/server, legacy: "reject") with tools: { listChanged: true }, and add it as a remote server.
  2. After connect, end the subscriptions/listen response stream right after the notifications/subscriptions/acknowledged event.
  3. Wait a few seconds, then add a tool on the server and call notify.toolsChanged().
  4. Mcp.tools() still returns only the old tools. The server saw one subscriptions/listen request in total. With the stream left open, the new tool shows up as expected.

I have this as a bun test in packages/core/test (control case passes, cut-stream case fails).

Screenshot

No response

Operating System

Windows 11

Terminal

No response

Activity

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

    @opencodejr
    Contributor

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

    Thanks for the detailed report. I reproduced this with the released 2.4.1 and on the latest dev (adc958a7d7).

    What I did: I ran opencode serve with a remote MCP server that uses the modern protocol (createMcpHandler, legacy: "reject", tools: { listChanged: true }). That server ended the subscriptions/listen response right after notifications/subscriptions/acknowledged. About 10 seconds after connect, I added a tool and called notify.toolsChanged().

    • Stream left open: opencode fetched tools/list again about a second after the change notification.
    • Stream ended: the server only ever saw one subscriptions/listen and no tools/list after the change. /api/mcp still reported the server as connected, so the tool list stayed stale.

    The only stand-in is the test MCP server that ends the stream, which is the situation your report starts from. No model was involved. The script below runs both cases (sh repro.sh cut or sh repro.sh control).

    In the code, the MCP Events listen stream in packages/core/src/mcp/client.ts is reopened with backoff and then relisted. I found nothing that does the same for the list-changed subscription, which fits what you described. A maintainer will look at the fix you proposed.

    Reproduction script (repro.sh)
    #!/bin/sh
    # Reproduces #66072: after the modern subscriptions/listen stream ends, opencode never reopens it,
    # so tools/list_changed is lost and the tool list is never refreshed.
    # Usage: sh repro.sh <cut|control>   (needs bun and curl)
    # OC_CMD overrides the opencode command (e.g. to run from a source checkout).
    set -e
    MODE=${1:-cut}
    DIR=$(mktemp -d)
    (cd "$DIR" && bun init -y >/dev/null 2>&1 && bun add @modelcontextprotocol/[email protected] >/dev/null 2>&1)
    cat > "$DIR/mcp-server.ts" <<'SERVER_EOF'
    // Modern (2026-07-28) MCP server for issue #66072.
    // CUT=1 ends each subscriptions/listen response right after the acknowledged notification.
    // POST /admin/add-tool adds a tool and sends notifications/tools/list_changed.
    import { createMcpHandler, Server } from "@modelcontextprotocol/server"
    
    const cut = process.env.CUT === "1"
    const tools = [{ name: "old_tool", inputSchema: { type: "object" as const, properties: {} } }]
    const counts: Record<string, number> = {}
    
    const server = () => {
      const protocol = new Server({ name: "repro", version: "1.0.0" }, { capabilities: { tools: { listChanged: true } } })
      protocol.setRequestHandler("tools/list", () => Promise.resolve({ tools }))
      protocol.setRequestHandler("tools/call", () => Promise.resolve({ content: [] }))
      return protocol
    }
    const modern = createMcpHandler(server, { legacy: "reject" })
    
    function cutAfterAck(response: Response): Response {
      if (!response.body) return response
      const reader = response.body.getReader()
      const decoder = new TextDecoder()
      let seen = ""
      const body = new ReadableStream<Uint8Array>({
        async pull(controller) {
          const { done, value } = await reader.read()
          if (done) return controller.close()
          controller.enqueue(value)
          seen += decoder.decode(value, { stream: true })
          if (seen.includes("notifications/subscriptions/acknowledged")) {
            console.log(`[server] cutting subscriptions/listen stream after ack`)
            await reader.cancel().catch(() => {})
            controller.close()
          }
        },
      })
      return new Response(body, { status: response.status, headers: response.headers })
    }
    
    const http = Bun.serve({
      port: Number(process.env.PORT ?? 4555),
      idleTimeout: 0,
      fetch: async (request) => {
        const url = new URL(request.url)
        if (url.pathname === "/admin/add-tool") {
          tools.push({ name: `new_tool_${tools.length}`, inputSchema: { type: "object", properties: {} } })
          await modern.notify.toolsChanged()
          console.log(`[server] added tool, sent tools/list_changed; tools=${tools.map((t) => t.name).join(",")}`)
          return Response.json({ tools: tools.map((t) => t.name) })
        }
        if (url.pathname === "/admin/counts") return Response.json(counts)
        let method: string | undefined
        if (request.method === "POST") {
          const body = (await request.clone().json().catch(() => undefined)) as { method?: string } | undefined
          method = body?.method
          if (method) {
            counts[method] = (counts[method] ?? 0) + 1
            console.log(`[server] ${new Date().toISOString()} request ${method} (#${counts[method]})`)
          }
        }
        const response = await modern.fetch(request)
        return cut && method === "subscriptions/listen" ? cutAfterAck(response) : response
      },
    })
    console.log(`[server] listening on ${http.url} cut=${cut}`)
    SERVER_EOF
    OC_CMD=${OC_CMD:-opencode}
    PROJECT=$(mktemp -d)
    cat > "$PROJECT/opencode.jsonc" <<'EOF'
    { "mcp": { "servers": { "repro": { "type": "remote", "url": "http://127.0.0.1:4555/mcp", "oauth": false } } } }
    EOF
    CUT=0; [ "$MODE" = cut ] && CUT=1
    CUT=$CUT bun "$DIR/mcp-server.ts" > /tmp/repro-srv.log 2>&1 &
    SRV=$!
    sleep 1
    (cd "$PROJECT" && $OC_CMD serve --port ${OC_PORT:-4097} --hostname 127.0.0.1 > /tmp/repro-oc.log 2>&1) &
    OC=$!
    trap 'kill $SRV $OC 2>/dev/null' EXIT
    for i in $(seq 1 60); do grep -q "server password" /tmp/repro-oc.log 2>/dev/null && break; sleep 1; done
    PW=$(grep "server password" /tmp/repro-oc.log | awk '{print $3}')
    API="curl -s -u opencode:$PW -G http://127.0.0.1:${OC_PORT:-4097}/api/mcp --data-urlencode location[directory]=$PROJECT"
    $API > /dev/null            # load the location, which connects the MCP server
    sleep 10
    echo "status before change: $($API)"
    curl -s -X POST http://127.0.0.1:4555/admin/add-tool; echo
    sleep 20
    echo "status after change:  $($API)"
    echo "requests seen by MCP server: $(curl -s http://127.0.0.1:4555/admin/counts)"
    echo "--- server log ---"; cat /tmp/repro-srv.log

    Run it: sh repro.sh

  3. added
    status/repro-simulated
    on Nov 24, 2026
  4. Guembri01 commented on Nov 24, 2026

    @Guembri01

    Happy to write this if you would rather not — your analysis is the map here, so the credit is yours either way.

    The shape I would follow, from the code:

    • The list-changed handlers are registered with autoRefresh: false and let the SDK open the stream (packages/core/src/mcp/client.ts:348-358, :416-420), so nothing survives that stream ending — which matches your read.
    • The Events extension right above it already does the reopen: a scoped client.listen(filter) whose closed promise is awaited, Effect.retry(reopen) while the failure is not a ProtocolError, and a relist queued after each reopen (:933-973). That is the pattern I would copy.
    • After each reopen I would fire the tools/prompts/resources callbacks once, so a change the server announced while the stream was down is not lost.

    One thing worth settling before the diff: in the installed @modelcontextprotocol/client (2.4.0 in bun.lock), I could not find autoOpenedSubscription in the shipped types — the client package only has bundled dist, so it may be private or renamed. If it is not reachable, the fix has to open the subscription itself (as the Events path does) whenever the server negotiates the modern protocol, rather than watching something the SDK owns. Which way it lands changes the diff, not the behaviour.

    If you are already on it, say so and I will leave it alone.

  5. Guembri01 commented on Nov 24, 2026

    @Guembri01

    Correction to my previous comment, since I checked wrongly: autoOpenedSubscription is public — get autoOpenedSubscription(): McpSubscription | undefined in @modelcontextprotocol/[email protected] (dist/client-BTIWJvaF.d.mts:1006), returning honoredFilter plus closed: Promise<'local' | 'graceful' | 'remote'>. My grep only matched .d.ts and the package ships .d.mts, so I missed it. Your approach works as written.

    So the diff is the small one: hold the auto-opened subscription, wait on closed, reopen with client.listen(honoredFilter) under the existing reopen schedule (ProtocolError not retried), and fire the tools/prompts/resources callbacks once after each reopen so a change announced while the stream was down is not lost. Stopping only on 'local' (our own close), not on 'graceful' — a server shutdown should still be followed when it comes back.

    I am writing it now against your test shape (cut the subscriptions/listen response after the ack, then notify.toolsChanged()). If you already have the branch, say so and I will drop mine rather than race you.

  6. Guembri01 commented on Nov 24, 2026

    @Guembri01

    Written up as #66170, with your diagnosis credited in the PR body: the auto-opened subscription is followed, reopened with honoredFilter under the existing reopen backoff, 'local' stops the loop, and the callbacks fire once after each reopen so a change announced while the stream was down is not lost.

    The test is your shape: a raw 2026-07-28 server over InMemoryTransport that acks the auto-opened subscriptions/listen, ends it the way a shutdown does (the empty listen result), then asserts the stream comes back with the same filter, that the reopen refreshes once, and that a notifications/tools/list_changed on the reopened stream reaches the consumer. Without the change it times out waiting for the second listen; with it, 3/3 runs pass, and the MCP suites are 139 pass / 0 fail.

    If you were already on a branch, say so and I will close mine — yours would be the one to land.

  7. shaojunying commented on Nov 24, 2026

    @shaojunying
    ContributorAuthor

    Thanks @Guembri01 for writing this up, and for the credit in #66170.

    I had a fix with tests on my fork too, so I ran my test cases against #66170 at a2114d4. Spacing of reopens when the server ends every stream: passes. MCP pool > fans tool list changes out to every Location: passes on my Windows machine.

    One case is still open. If the listen stream fails to open at connect, for example a 503 on the first subscriptions/listen, the SDK only reports it to onerror and autoOpenedSubscription stays undefined. #66170 starts the reopen loop only when autoOpenedSubscription exists, so that connection never gets a stream and never sees a tool change.

    My branch handles it by watching the SDK's stream first, and opening its own when there is none or after it ends. It does not close the SDK's stream at connect, so a connection does not do an extra listen and relist.

    Maintainers, your call on which to take. I'm also happy for @Guembri01 to fold the failed-open case into #66170.

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/windowsstatus/repro-simulatedtype/bugversion/v2

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions