Skip to content

mcp: no reconnect when a legacy HTTP server answers an expired session with 400 "No valid session ID provided" #66073

Backlog

Description

@shaojunying

Description

When a legacy Streamable HTTP server forgets the session (restart or idle expiry) and answers the old Mcp-Session-Id with HTTP 400 Bad Request: No valid session ID provided, opencode does not reconnect. Every later tool call on that server fails with that 400, and the server still shows connected until the user reconnects it by hand.

This was reported in #32809 (Atlassian MCP 1.12.4 after ~15-30 min idle). The bot closed it for inactivity and asked for a new issue if it is still relevant. It still happens on v2 dev.

The cause is failure() in packages/core/src/mcp/client.ts:497-512. It maps a 404 to SessionExpiredError, but a 400 only when the body contains Bad Request: Server not initialized. Older Python SDK session managers and the TypeScript SDK example servers answer an unknown session id with Bad Request: No valid session ID provided. FastMCP-based servers such as mcp-atlassian inherit this. That body falls through as a plain error, so recovering (connection.ts:139-149) never runs.

Fix idea: also treat a 400 whose body contains No valid session ID as an expired session. The check stays narrow: it only applies when the transport holds a session id, like the existing cases, so other 400s still pass through.

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

Plugins

No response

OpenCode version

dev adc958a7d7 (2.4.1)

Steps to reproduce

  1. Run a stateful legacy MCP server that answers an unknown session id with 400 {"jsonrpc":"2.0","error":{"code":-32000,"message":"Bad Request: No valid session ID provided"},"id":null}, and add it as a remote server.
  2. Call a tool once. It works.
  3. Restart the server (or let the session expire).
  4. Call the tool again. It fails with MCP tool "echo" on server "legacy" failed: Error POSTing to endpoint: {..."Bad Request: No valid session ID provided"...} (HTTP 400), and every later call fails the same way. With a 404 for the same case, opencode reconnects and the call succeeds.

I have this as a bun test in packages/core/test.

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 and the pointer to the code. I reproduced this on 2.4.1, and it still happens on the latest dev (adc958a7d797) run from source.

    What I ran:

    • A minimal stateful legacy Streamable HTTP MCP server (a mock) that answers an unknown Mcp-Session-Id with HTTP 400 Bad Request: No valid session ID provided. It is added as a remote server with protocol: "legacy", and the simulated model in our test harness made the tool calls.
    • The first legacy_echo call worked. After the mock forgot its sessions (standing in for a restart or idle expiry), the next two calls both failed with MCP tool "echo" on server "legacy" failed: Error POSTing to endpoint: {..."Bad Request: No valid session ID provided"...} (HTTP 400). Both still sent the old session id, and opencode never re-initialized.
    • With the mock answering 404 instead, opencode re-initialized and the later calls succeeded, as you described.

    The recording and screenshot below show the failing run, and the script below reproduces it. It starts the mock server itself. Related: #32809 reported the same 400 with mcp-atlassian on V1 and was closed for inactivity.

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

    Screenshot

    Reproduction script (drive.ts)
    // Reproduces anomalyco/opencode#66073: a legacy Streamable HTTP MCP server that answers a forgotten
    // Mcp-Session-Id with 400 "No valid session ID provided" is never reconnected. STATUS=404 shows the
    // reconnect path working for comparison. The mock MCP server is started by this script on :47811.
    import { Effect, Stream } from "effect"
    import { Llm, OpenCodeDriver } from "opencode-drive"
    
    const MCP = "http://127.0.0.1:47811"
    const TOOL = process.env.TOOL ?? "legacy_echo"
    let calls = 0
    
    // POST /reset forgets every session, as a server restart or idle expiry would.
    const sessions = new Set<string>()
    const log = (...a: unknown[]) => console.log(new Date().toISOString(), ...a)
    const mcpServer = Bun.serve({
      port: 47811,
      async fetch(req) {
        const url = new URL(req.url)
        if (url.pathname === "/reset") { sessions.clear(); log("RESET: all sessions forgotten"); return new Response("ok") }
        if (url.pathname !== "/mcp") return new Response("not found", { status: 404 })
        if (req.method === "GET") return new Response("Method Not Allowed", { status: 405 })
        if (req.method === "DELETE") { sessions.delete(req.headers.get("mcp-session-id") ?? ""); return new Response(null, { status: 200 }) }
        const body = await req.json() as any
        const sid = req.headers.get("mcp-session-id")
        log(req.method, body.method, "session:", sid)
        if (body.method === "initialize") {
          const id = crypto.randomUUID()
          sessions.add(id)
          return Response.json({ jsonrpc: "2.0", id: body.id, result: {
            protocolVersion: body.params?.protocolVersion ?? "2025-06-18",
            capabilities: { tools: {} }, serverInfo: { name: "legacy", version: "1.0.0" } } },
            { headers: { "mcp-session-id": id } })
        }
        if (!sid || !sessions.has(sid)) {
          log("-> 400 No valid session ID provided")
          if (process.env.STATUS === "404") return Response.json({ jsonrpc: "2.0", error: { code: -32001, message: "Session not found" }, id: null }, { status: 404 })
          return Response.json({ jsonrpc: "2.0", error: { code: -32000, message: "Bad Request: No valid session ID provided" }, id: null }, { status: 400 })
        }
        if (body.id === undefined) return new Response(null, { status: 202 })
        if (body.method === "tools/list") return Response.json({ jsonrpc: "2.0", id: body.id, result: { tools: [{
          name: "echo", description: "Echo text back", inputSchema: { type: "object", properties: { text: { type: "string" } }, required: ["text"] } }] } })
        if (body.method === "tools/call") return Response.json({ jsonrpc: "2.0", id: body.id, result: { content: [{ type: "text", text: "echo: " + body.params.arguments.text }] } })
        return Response.json({ jsonrpc: "2.0", id: body.id, result: {} })
      },
    })
    log("legacy MCP server on", 47811)
    const call = () =>
      Stream.make(
        Llm.toolCall({ index: 0, id: `call_echo_${++calls}`, name: TOOL, input: { text: `hello ${calls}` } }),
        Llm.finish("tool-calls"),
      )
    
    export default OpenCodeDriver.use(
      {
        ...(process.env.OC_DEV ? { opencode: { dev: process.env.OC_DEV } } : {}),
        tui: { recording: true },
        config: {
          mcp: { servers: { legacy: { type: "remote", url: `${MCP}/mcp`, oauth: false, codemode: false, protocol: "legacy" } } },
        } as any,
      },
      ({ ui, llm }) =>
        Effect.gen(function* () {
          yield* llm.serve((request) => {
            const body = (request as any).body ?? request
            const text = JSON.stringify(body)
            if (text.includes("You name conversations")) return Stream.make(Llm.text("MCP echo repro"))
            if (process.env.DEBUG) console.log("TOOLS", JSON.stringify((body.tools ?? []).map((t: any) => t.function?.name ?? t.name)))
            const messages = body.messages ?? []
            const last = messages[messages.length - 1]
            // After a tool result, finish the turn with text; otherwise call the MCP tool.
            if (last?.role === "tool") {
              const result = typeof last.content === "string" ? last.content : JSON.stringify(last.content)
              console.log(`TOOL RESULT ${calls}: ${result}`)
              return Stream.make(Llm.text(`Tool turn ${calls} done. Result: ${result.slice(0, 300)}`))
            }
            return call()
          })
          yield* Effect.sleep(8000)
          yield* ui.submit("Call the echo tool (1st call, session is fresh)")
          yield* ui.waitFor("Tool turn 1 done.", { timeout: 90000 })
          yield* ui.screenshot("first-call-ok")
          // Simulate the server restarting / expiring the session.
          yield* Effect.promise(() => fetch(`${MCP}/reset`, { method: "POST" }))
          yield* ui.submit("Call the echo tool again (after server forgot the session)")
          yield* Effect.sleep(10000)
          yield* ui.screenshot("second-call")
          yield* ui.submit("Call the echo tool a third time")
          yield* Effect.sleep(10000)
          yield* Effect.sleep(1500)
          yield* ui.screenshot("third-call")
          mcpServer.unref()
    
        }),
    )

    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.

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

    @liwenjie200543

    I'd like to take this one.

    The classification in packages/core/src/mcp/client.ts only recognises the 400 body "Bad Request: Server not initialized". A legacy server that answers a forgotten Mcp-Session-Id with "No valid session ID provided" falls through to a plain error, so the transport keeps the dead session id and never re-initialises.

    I have a patch that treats both messages as expiry, plus a test next to the existing 404 reconnect case (mock answers 400 for a forgotten session, then asserts the client re-initialises and the tool call succeeds). Will open a PR shortly.

  5. shaojunying commented on Nov 24, 2026

    @shaojunying
    ContributorAuthor

    Thanks @liwenjie200543 for picking this up so quickly.

    For context: I filed this issue and had a fix with a regression test on my fork: shaojunying@dbb8346869

    I compared it with #66139. The change is equivalent, and #66139's code also passes the extra cases from my branch. So I'm happy for #66139 to land. Maintainers, your call. I left the extra test cases on #66139 for reference.

  6. added 2 commits that reference this issue on Nov 28, 2026
    5c3c7c6
    eef91ec
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