Skip to content

Commit 06fa22e

Browse files
committed
feat: add MCP auto-reconnect patch for stale remote sessions
When a remote MCP server restarts, the old session ID becomes invalid. Tool calls fail at the transport layer with HTTP 404 / session errors. Previously required a manual MCP toggle (ctrl+p) or OpenCode restart. The patch wraps remote MCP tool execution with try/catch that detects transport errors, closes the stale client, creates a fresh transport + client, refreshes tool definitions, and retries the call once. Addresses: anomalyco/opencode#15247
1 parent 4917208 commit 06fa22e

5 files changed

Lines changed: 179 additions & 15 deletions

File tree

‎.github/workflows/build-release.yml‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -173,15 +173,16 @@ jobs:
173173
uses: softprops/action-gh-release@v2
174174
with:
175175
tag_name: v${{ inputs.version }}-patched
176-
name: OpenCode v${{ inputs.version }} with Caching + Vim + Tool Fix
176+
name: OpenCode v${{ inputs.version }} with Caching + Vim + Tool Fix + MCP Reconnect
177177
body: |
178-
# OpenCode v${{ inputs.version }} with Caching + Vim + Tool Fix
178+
# OpenCode v${{ inputs.version }} with Caching + Vim + Tool Fix + MCP Reconnect
179179
180-
This release applies three patches to OpenCode v${{ inputs.version }}:
180+
This release applies four patches to OpenCode v${{ inputs.version }}:
181181
182182
1. **Prompt caching improvements** from [PR #5422](https://github.com/anomalyco/opencode/pull/5422) (via [opencode-cached](https://github.com/johnnymo87/opencode-cached))
183183
2. **Vim keybindings** from [PR #12679](https://github.com/anomalyco/opencode/pull/12679)
184184
3. **Tool use/result mismatch fix** from [PR #16751](https://github.com/anomalyco/opencode/pull/16751)
185+
4. **MCP auto-reconnect** from [Issue #15247](https://github.com/anomalyco/opencode/issues/15247)
185186
186187
## Caching Improvements
187188
@@ -204,6 +205,10 @@ jobs:
204205
205206
Fixes the widespread `tool_use ids were found without tool_result blocks` error ([#16749](https://github.com/anomalyco/opencode/issues/16749)) that corrupts sessions when stream errors cause lost step boundaries. Injects synthetic step-start boundaries at reconstruction time to prevent interleaved tool_use/text in assistant messages.
206207
208+
## MCP Auto-Reconnect
209+
210+
Automatically reconnects remote MCP servers when the server restarts and the session becomes stale. Without this, tool calls fail with transport errors requiring a manual MCP toggle or OpenCode restart.
211+
207212
## Installation
208213
209214
### Linux (arm64)
@@ -236,6 +241,7 @@ jobs:
236241
**Caching patch**: [opencode-cached](https://github.com/johnnymo87/opencode-cached) / [PR #5422](https://github.com/anomalyco/opencode/pull/5422)
237242
**Vim patch**: [PR #12679](https://github.com/anomalyco/opencode/pull/12679)
238243
**Tool fix patch**: [PR #16751](https://github.com/anomalyco/opencode/pull/16751)
244+
**MCP reconnect**: [Issue #15247](https://github.com/anomalyco/opencode/issues/15247)
239245
files: |
240246
artifacts/opencode-linux-arm64.tar.gz
241247
artifacts/opencode-linux-x64.tar.gz
@@ -261,7 +267,7 @@ jobs:
261267
const body = `
262268
## Build Failure: v${version}
263269
264-
The automated build for OpenCode v${version} with caching + vim + tool fix patches failed.
270+
The automated build for OpenCode v${version} with caching + vim + tool fix + mcp reconnect patches failed.
265271
266272
**Workflow Run**: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
267273
@@ -270,7 +276,8 @@ jobs:
270276
1. **Caching patch conflict**: The caching patch (fetched from opencode-cached) may not apply to v${version}
271277
2. **Vim patch conflict**: The local vim.patch may not apply to v${version}
272278
3. **Tool fix patch conflict**: The local tool-fix.patch may not apply to v${version}
273-
4. **Build failure**: OpenCode build process may have changed
279+
4. **MCP reconnect patch conflict**: The local mcp-reconnect.patch may not apply to v${version}
280+
5. **Build failure**: OpenCode build process may have changed
274281
275282
### Action Required
276283
@@ -286,7 +293,8 @@ jobs:
286293
gh pr diff 16751 --repo anomalyco/opencode > patches/tool-fix.patch
287294
# Review changes, commit and push
288295
\`\`\`
289-
5. Re-run: \`gh workflow run build-release.yml --field version=${version}\`
296+
5. If MCP reconnect patch failed, review upstream changes to \`mcp/index.ts\` and update manually
297+
6. Re-run: \`gh workflow run build-release.yml --field version=${version}\`
290298
`;
291299
292300
const issues = await github.rest.issues.listForRepo({

‎.github/workflows/check-sunset.yml‎

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,17 +41,29 @@ jobs:
4141
env:
4242
GH_TOKEN: ${{ github.token }}
4343

44+
- name: Check issue #15247 (MCP reconnect) status
45+
id: check_mcp_reconnect
46+
run: |
47+
# No upstream PR -- track the issue instead. When it's closed,
48+
# upstream likely shipped the feature and this patch can be dropped.
49+
ISSUE_STATE=$(gh issue view 15247 --repo anomalyco/opencode --json state --jq .state 2>/dev/null || echo "UNKNOWN")
50+
echo "state=$ISSUE_STATE" >> $GITHUB_OUTPUT
51+
echo "MCP reconnect issue #15247: $ISSUE_STATE"
52+
env:
53+
GH_TOKEN: ${{ github.token }}
54+
4455
- name: Create sunset recommendation
45-
if: steps.check_caching_pr.outputs.state == 'MERGED' || steps.check_vim_pr.outputs.state == 'MERGED' || steps.check_tool_fix_pr.outputs.state == 'MERGED'
56+
if: steps.check_caching_pr.outputs.state == 'MERGED' || steps.check_vim_pr.outputs.state == 'MERGED' || steps.check_tool_fix_pr.outputs.state == 'MERGED' || steps.check_mcp_reconnect.outputs.state == 'CLOSED'
4657
uses: actions/github-script@v7
4758
with:
4859
script: |
4960
const cachingState = '${{ steps.check_caching_pr.outputs.state }}';
5061
const vimState = '${{ steps.check_vim_pr.outputs.state }}';
5162
const toolFixState = '${{ steps.check_tool_fix_pr.outputs.state }}';
52-
const allMerged = cachingState === 'MERGED' && vimState === 'MERGED' && toolFixState === 'MERGED';
63+
const mcpReconnectState = '${{ steps.check_mcp_reconnect.outputs.state }}';
64+
const allMerged = cachingState === 'MERGED' && vimState === 'MERGED' && toolFixState === 'MERGED' && mcpReconnectState === 'CLOSED';
5365
54-
// Collect which PRs merged
66+
// Collect which PRs/issues are resolved
5567
const merged = [];
5668
const remaining = [];
5769
if (cachingState === 'MERGED') merged.push('Caching PR #5422');
@@ -60,6 +72,8 @@ jobs:
6072
else remaining.push('Vim PR #12679');
6173
if (toolFixState === 'MERGED') merged.push('Tool fix PR #16751');
6274
else remaining.push('Tool fix PR #16751');
75+
if (mcpReconnectState === 'CLOSED') merged.push('MCP reconnect #15247');
76+
else remaining.push('MCP reconnect #15247');
6377
6478
let title, body;
6579
@@ -71,6 +85,7 @@ jobs:
7185
- **Caching PR #5422**: MERGED
7286
- **Vim PR #12679**: MERGED
7387
- **Tool fix PR #16751**: MERGED
88+
- **MCP reconnect #15247**: CLOSED
7489
7590
All patches are now available in official OpenCode releases. This repo can be archived.
7691
@@ -89,6 +104,7 @@ jobs:
89104
- **Caching PR #5422**: ${cachingState}
90105
- **Vim PR #12679**: ${vimState}
91106
- **Tool fix PR #16751**: ${toolFixState}
107+
- **MCP reconnect #15247**: ${mcpReconnectState}
92108
93109
Merged: ${merged.join(', ')}
94110
Remaining: ${remaining.join(', ')}
@@ -117,7 +133,7 @@ jobs:
117133
owner: context.repo.owner,
118134
repo: context.repo.repo,
119135
issue_number: existingIssue.number,
120-
body: `Monthly check (${new Date().toISOString().split('T')[0]}): Caching PR: ${cachingState}, Vim PR: ${vimState}, Tool fix PR: ${toolFixState}`
136+
body: `Monthly check (${new Date().toISOString().split('T')[0]}): Caching PR: ${cachingState}, Vim PR: ${vimState}, Tool fix PR: ${toolFixState}, MCP reconnect: ${mcpReconnectState}`
121137
});
122138
} else {
123139
await github.rest.issues.create({
@@ -136,3 +152,4 @@ jobs:
136152
echo "Caching PR #5422: ${{ steps.check_caching_pr.outputs.state }}"
137153
echo "Vim PR #12679: ${{ steps.check_vim_pr.outputs.state }}"
138154
echo "Tool fix PR #16751: ${{ steps.check_tool_fix_pr.outputs.state }}"
155+
echo "MCP reconnect #15247: ${{ steps.check_mcp_reconnect.outputs.state }}"

‎README.md‎

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
# opencode-patched
22

3-
**OpenCode with [prompt caching](https://github.com/anomalyco/opencode/pull/5422) + [vim keybindings](https://github.com/anomalyco/opencode/pull/12679) + [tool use/result fix](https://github.com/anomalyco/opencode/pull/16751)**
3+
**OpenCode with [prompt caching](https://github.com/anomalyco/opencode/pull/5422) + [vim keybindings](https://github.com/anomalyco/opencode/pull/12679) + [tool use/result fix](https://github.com/anomalyco/opencode/pull/16751) + [MCP auto-reconnect](https://github.com/anomalyco/opencode/issues/15247)**
44

5-
This repository combines three unmerged upstream patches into a single OpenCode binary, built automatically for 4 platforms.
5+
This repository combines four patches into a single OpenCode binary, built automatically for 4 platforms.
66

77
## Patches Included
88

@@ -26,6 +26,12 @@ Supported motions:
2626

2727
Stored locally as `patches/tool-fix.patch`. Fixes the widespread `tool_use ids were found without tool_result blocks` error ([#16749](https://github.com/anomalyco/opencode/issues/16749)) that corrupts sessions when stream errors cause lost step boundaries. Injects synthetic step-start boundaries at message reconstruction time to prevent interleaved tool_use/text in assistant messages that the Anthropic API rejects.
2828

29+
### 4. MCP Auto-Reconnect ([Issue #15247](https://github.com/anomalyco/opencode/issues/15247))
30+
31+
Stored locally as `patches/mcp-reconnect.patch`. Automatically reconnects remote MCP servers when the server restarts and the session becomes stale. Without this patch, `callTool` fails at the transport layer with "Session not found" / HTTP 404 errors, requiring a manual MCP toggle (ctrl+p) or full OpenCode restart.
32+
33+
The patch wraps remote MCP tool execution with a try/catch that detects transport-level errors (stale sessions, connection refused, etc.), closes the stale client, creates a fresh transport + client, refreshes tool definitions, and retries the call once.
34+
2935
## Installation
3036

3137
### Linux (arm64)
@@ -75,7 +81,7 @@ Timing Chain (every 8 hours):
7581
|-> builds v{VER}-cached -- applies caching patch, publishes
7682
7783
:01 opencode-patched/sync-cached -- detects new -cached release
78-
|-> builds v{VER}-patched -- applies caching + vim + tool fix patches, publishes
84+
|-> builds v{VER}-patched -- applies caching + vim + tool fix + mcp reconnect patches, publishes
7985
:01 opencode-patched/sync-vim-pr -- checks PR #12679 for changes
8086
:01 opencode-patched/sync-tool-fix-pr -- checks PR #16751 for changes
8187
@@ -86,16 +92,17 @@ Timing Chain (every 8 hours):
8692

8793
1. Clone upstream OpenCode at the release tag
8894
2. Fetch `caching.patch` from [opencode-cached](https://github.com/johnnymo87/opencode-cached) (always latest from `main`)
89-
3. Apply `caching.patch`, then local `vim.patch`, then local `tool-fix.patch`
95+
3. Apply `caching.patch`, then local `vim.patch`, then `tool-fix.patch`, then `mcp-reconnect.patch`
9096
4. Build with Bun for 4 platforms (linux/darwin x arm64/x64)
9197
5. Publish release as `v{VERSION}-patched`
9298

9399
### Patch Independence
94100

95-
The three patches modify completely different areas of the codebase:
101+
The four patches modify completely different areas of the codebase:
96102
- **Caching**: `provider/config.ts`, `provider/transform.ts`, `session/prompt.ts`, `config/config.ts`
97103
- **Vim**: `cli/cmd/tui/component/vim/*`, `cli/cmd/tui/component/prompt/index.tsx`, `cli/cmd/tui/app.tsx`
98104
- **Tool fix**: `session/message-v2.ts`, `test/session/message-v2.test.ts`
105+
- **MCP reconnect**: `mcp/index.ts`
99106

100107
Zero file overlap between any pair of patches.
101108

@@ -141,6 +148,17 @@ If the hashes differ, it opens a GitHub issue labeled `patch-drift`.
141148
publication is blocked. The drift issue is a prompt to review what changed upstream and
142149
decide whether to adopt it.
143150

151+
### When the MCP Reconnect Patch Breaks (Build Failure)
152+
153+
The build fails and creates a GitHub issue automatically. This blocks publication.
154+
155+
1. Review the upstream changes to `packages/opencode/src/mcp/index.ts`
156+
2. Regenerate or manually update `patches/mcp-reconnect.patch`
157+
3. Review, commit, push
158+
4. Re-trigger: `gh workflow run build-release.yml --field version=X.Y.Z`
159+
160+
**Sunset**: This patch can be dropped when [issue #15247](https://github.com/anomalyco/opencode/issues/15247) is resolved upstream. Unlike the other patches, this one has no upstream PR to track -- it is original work. If an upstream PR appears, add a sync workflow for it.
161+
144162
### Sunset Criteria
145163

146164
Monthly automated check (`check-sunset.yml`) monitors all upstream PRs:
@@ -154,6 +172,7 @@ Monthly automated check (`check-sunset.yml`) monitors all upstream PRs:
154172
- **Caching builds**: [opencode-cached](https://github.com/johnnymo87/opencode-cached)
155173
- **Vim PR**: [PR #12679](https://github.com/anomalyco/opencode/pull/12679) by [@leohenon](https://github.com/leohenon)
156174
- **Tool fix PR**: [PR #16751](https://github.com/anomalyco/opencode/pull/16751) by [@altendky](https://github.com/altendky)
175+
- **MCP reconnect**: [Issue #15247](https://github.com/anomalyco/opencode/issues/15247) — original patch
157176

158177
## License
159178

‎patches/apply.sh‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ SOURCE_DIR="$1"
1717
SCRIPT_DIR="$(dirname "$0")"
1818
VIM_PATCH="$SCRIPT_DIR/vim.patch"
1919
TOOL_FIX_PATCH="$SCRIPT_DIR/tool-fix.patch"
20+
MCP_RECONNECT_PATCH="$SCRIPT_DIR/mcp-reconnect.patch"
2021
CACHING_PATCH_URL="https://raw.githubusercontent.com/johnnymo87/opencode-cached/main/patches/caching.patch"
2122

2223
if [ ! -d "$SOURCE_DIR" ]; then
@@ -34,6 +35,11 @@ if [ ! -f "$TOOL_FIX_PATCH" ]; then
3435
exit 1
3536
fi
3637

38+
if [ ! -f "$MCP_RECONNECT_PATCH" ]; then
39+
echo "Error: MCP reconnect patch not found: $MCP_RECONNECT_PATCH"
40+
exit 1
41+
fi
42+
3743
cd "$SOURCE_DIR"
3844

3945
# --- Patch 1: Caching (fetched from opencode-cached) ---
@@ -113,6 +119,27 @@ fi
113119
git apply "$TOOL_FIX_PATCH"
114120
echo "✓ Tool fix patch applied"
115121

122+
# --- Patch 4: MCP auto-reconnect (local) ---
123+
124+
echo "Applying mcp-reconnect.patch..."
125+
if ! git apply --check "$MCP_RECONNECT_PATCH" 2>/dev/null; then
126+
echo ""
127+
echo "❌ MCP RECONNECT PATCH FAILED TO APPLY"
128+
echo ""
129+
echo "Attempting to apply for diagnostics..."
130+
git apply "$MCP_RECONNECT_PATCH" 2>&1 || true
131+
echo ""
132+
echo "Failed files:"
133+
find . -name "*.rej" -type f 2>/dev/null || echo " None found"
134+
echo ""
135+
echo "The MCP reconnect patch may need updating for this upstream version."
136+
echo "Issue: https://github.com/anomalyco/opencode/issues/15247"
137+
exit 1
138+
fi
139+
140+
git apply "$MCP_RECONNECT_PATCH"
141+
echo "✓ MCP reconnect patch applied"
142+
116143
# --- Summary ---
117144

118145
echo ""

‎patches/mcp-reconnect.patch‎

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
diff --git a/packages/opencode/src/mcp/index.ts b/packages/opencode/src/mcp/index.ts
2+
index 8c92bb6b2..ec36962d0 100644
3+
--- a/packages/opencode/src/mcp/index.ts
4+
+++ b/packages/opencode/src/mcp/index.ts
5+
@@ -129,6 +129,24 @@ export namespace MCP {
6+
7+
const sanitize = (s: string) => s.replace(/[^a-zA-Z0-9_-]/g, "_")
8+
9+
+ /**
10+
+ * Detect transport-level errors that indicate a stale MCP session.
11+
+ * These occur when the MCP server restarts (invalidating session IDs)
12+
+ * or becomes unreachable, and warrant an automatic reconnect attempt.
13+
+ */
14+
+ function isTransportError(err: unknown): boolean {
15+
+ if (!(err instanceof Error)) return false
16+
+ const msg = err.message.toLowerCase()
17+
+ return (
18+
+ msg.includes("session") ||
19+
+ msg.includes("status: 404") ||
20+
+ msg.includes("status: 410") ||
21+
+ msg.includes("econnrefused") ||
22+
+ msg.includes("econnreset") ||
23+
+ msg.includes("fetch failed")
24+
+ )
25+
+ }
26+
+
27+
// Convert MCP tool definition to AI SDK Tool type
28+
function convertMcpTool(mcpTool: MCPToolDef, client: MCPClient, timeout?: number): Tool {
29+
const inputSchema = mcpTool.inputSchema
30+
@@ -635,7 +653,62 @@ export namespace MCP {
31+
32+
const timeout = entry?.timeout ?? defaultTimeout
33+
for (const mcpTool of listed) {
34+
- result[sanitize(clientName) + "_" + sanitize(mcpTool.name)] = convertMcpTool(mcpTool, client, timeout)
35+
+ const baseTool = convertMcpTool(mcpTool, client, timeout)
36+
+
37+
+ // Wrap remote MCP tools with auto-reconnect on stale sessions.
38+
+ // When the MCP server restarts, the old session ID becomes invalid
39+
+ // and callTool fails at the transport layer. This catches that error,
40+
+ // creates a fresh transport + client, and retries once.
41+
+ if (entry?.type === "remote" && baseTool.execute) {
42+
+ const origExecute = baseTool.execute
43+
+ const cName = clientName
44+
+ const mcp = entry
45+
+ const toolDef = mcpTool
46+
+ baseTool.execute = async (args: unknown) => {
47+
+ try {
48+
+ return await origExecute(args)
49+
+ } catch (err) {
50+
+ if (!isTransportError(err)) throw err
51+
+ log.warn("MCP tool call failed with transport error, reconnecting", {
52+
+ clientName: cName,
53+
+ tool: toolDef.name,
54+
+ error: err instanceof Error ? err.message : String(err),
55+
+ })
56+
+ try {
57+
+ const stale = s.clients[cName]
58+
+ if (stale) {
59+
+ try {
60+
+ await stale.close()
61+
+ } catch {}
62+
+ }
63+
+ const transport = new StreamableHTTPClientTransport(
64+
+ new URL(mcp.url),
65+
+ mcp.headers ? { requestInit: { headers: mcp.headers } } : undefined,
66+
+ )
67+
+ const fresh = new Client({ name: "opencode", version: Installation.VERSION })
68+
+ await withTimeout(fresh.connect(transport), timeout ?? DEFAULT_TIMEOUT)
69+
+ s.clients[cName] = fresh
70+
+ s.status[cName] = { status: "connected" }
71+
+ const refreshed = await withTimeout(fresh.listTools(), timeout ?? DEFAULT_TIMEOUT)
72+
+ s.defs[cName] = refreshed.tools
73+
+ watch(s, cName, fresh, timeout)
74+
+ return await fresh.callTool(
75+
+ { name: toolDef.name, arguments: (args || {}) as Record<string, unknown> },
76+
+ CallToolResultSchema,
77+
+ { resetTimeoutOnProgress: true, timeout },
78+
+ )
79+
+ } catch (reconnectErr) {
80+
+ log.error("MCP reconnect failed, propagating original error", {
81+
+ clientName: cName,
82+
+ error: reconnectErr instanceof Error ? reconnectErr.message : String(reconnectErr),
83+
+ })
84+
+ throw err
85+
+ }
86+
+ }
87+
+ }
88+
+ }
89+
+
90+
+ result[sanitize(clientName) + "_" + sanitize(mcpTool.name)] = baseTool
91+
}
92+
}),
93+
{ concurrency: "unbounded" },

0 commit comments

Comments
 (0)