You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
mcp: no reconnect when a legacy HTTP server answers an expired session with 400 "No valid session ID provided" #66073
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
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.
Call a tool once. It works.
Restart the server (or let the session expire).
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.
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.
// 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"constMCP="http://127.0.0.1:47811"constTOOL=process.env.TOOL??"legacy_echo"letcalls=0// POST /reset forgets every session, as a server restart or idle expiry would.constsessions=newSet<string>()constlog=(...a: unknown[])=>console.log(newDate().toISOString(), ...a)constmcpServer=Bun.serve({port: 47811,asyncfetch(req){consturl=newURL(req.url)if(url.pathname==="/reset"){sessions.clear();log("RESET: all sessions forgotten");returnnewResponse("ok")}if(url.pathname!=="/mcp")returnnewResponse("not found",{status: 404})if(req.method==="GET")returnnewResponse("Method Not Allowed",{status: 405})if(req.method==="DELETE"){sessions.delete(req.headers.get("mcp-session-id")??"");returnnewResponse(null,{status: 200})}constbody=awaitreq.json()asanyconstsid=req.headers.get("mcp-session-id")log(req.method,body.method,"session:",sid)if(body.method==="initialize"){constid=crypto.randomUUID()sessions.add(id)returnResponse.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")returnResponse.json({jsonrpc: "2.0",error: {code: -32001,message: "Session not found"},id: null},{status: 404})returnResponse.json({jsonrpc: "2.0",error: {code: -32000,message: "Bad Request: No valid session ID provided"},id: null},{status: 400})}if(body.id===undefined)returnnewResponse(null,{status: 202})if(body.method==="tools/list")returnResponse.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")returnResponse.json({jsonrpc: "2.0",id: body.id,result: {content: [{type: "text",text: "echo: "+body.params.arguments.text}]}})returnResponse.json({jsonrpc: "2.0",id: body.id,result: {}})},})log("legacy MCP server on",47811)constcall=()=>Stream.make(Llm.toolCall({index: 0,id: `call_echo_${++calls}`,name: TOOL,input: {text: `hello ${calls}`}}),Llm.finish("tool-calls"),)exportdefaultOpenCodeDriver.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"}}},}asany,},({ ui, llm })=>Effect.gen(function*(){yield*llm.serve((request)=>{constbody=(requestasany).body??requestconsttext=JSON.stringify(body)if(text.includes("You name conversations"))returnStream.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)))constmessages=body.messages??[]constlast=messages[messages.length-1]// After a tool result, finish the turn with text; otherwise call the MCP tool.if(last?.role==="tool"){constresult=typeoflast.content==="string" ? last.content : JSON.stringify(last.content)console.log(`TOOL RESULT ${calls}: ${result}`)returnStream.make(Llm.text(`Tool turn ${calls} done. Result: ${result.slice(0,300)}`))}returncall()})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.
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.
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.
Activity
opencodejr commentedon Nov 24, 2026
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:
Mcp-Session-Idwith HTTP 400Bad Request: No valid session ID provided. It is added as a remote server withprotocol: "legacy", and the simulated model in our test harness made the tool calls.legacy_echocall worked. After the mock forgot its sessions (standing in for a restart or idle expiry), the next two calls both failed withMCP 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.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
Reproduction script (drive.ts)
Run it with opencode-drive:
opencode-drive run ./drive.ts. It drivesopencodefrom yourPATH; setOC_DEVto the path of an OpenCode checkout to run that from source instead.liwenjie200543 commentedon Nov 24, 2026
I'd like to take this one.
The classification in
packages/core/src/mcp/client.tsonly recognises the400body "Bad Request: Server not initialized". A legacy server that answers a forgottenMcp-Session-Idwith "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.
shaojunying commentedon Nov 24, 2026
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.
fix(mcp): reconnect when a legacy server answers an expired session w…
fix(mcp): reconnect when a legacy server answers an expired session w…