Skip to content

Commit 6a05cb9

Browse files
narcisoafclaude
andcommitted
fix(mcp): address CodeRabbit review on shared MCP servers
- On an external OpenCode 1 server, shared servers are registered under per-thread names and disconnected when the session closes, since that server is shared by every client and outlives the session. - The Pi extension and the ACP bridge lowercase a shared server's header names before the protocol's own, so a user `Accept` or `Content-Type` can't be merged into an invalid value. - The web form stays open when saving fails, so nothing typed is lost. - A failed settings read logs a warning before sessions fall back to no shared servers. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent efb06ba commit 6a05cb9

10 files changed

Lines changed: 148 additions & 44 deletions

‎apps/server/src/mcp/AcpMcpStdioBridge.test.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ describe("AcpMcpStdioBridge", () => {
157157
const seen: Array<{ readonly method: string; readonly headers: Headers }> = [];
158158
const result = yield* probeMcpServer({
159159
endpoint: "http://127.0.0.1:1/mcp",
160-
headers: { "X-Api-Key": "k-123" },
160+
headers: { "X-Api-Key": "k-123", "Content-Type": "text/plain" },
161161
fetchImplementation: async (_url, init) => {
162162
const body = JSON.parse(String(init?.body)) as { id?: string; method: string };
163163
seen.push({ method: body.method, headers: new Headers(init?.headers) });
@@ -180,6 +180,8 @@ describe("AcpMcpStdioBridge", () => {
180180
"tools/list",
181181
]);
182182
expect(seen[0]?.headers.get("x-api-key")).toBe("k-123");
183+
// The protocol's own Content-Type wins over a user header with another casing.
184+
expect(seen[0]?.headers.get("content-type")).toBe("application/json");
183185
expect(seen[0]?.headers.has("authorization")).toBe(false);
184186
}),
185187
);

‎apps/server/src/mcp/AcpMcpStdioBridge.ts‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,13 @@ interface JsonRpcEnvelope {
4242

4343
const MCP_PROTOCOL_VERSION = "2025-06-18";
4444

45+
const lowercaseHeaders = (
46+
headers: Readonly<Record<string, string>> | undefined,
47+
): Record<string, string> =>
48+
Object.fromEntries(
49+
Object.entries(headers ?? {}).map(([name, value]) => [name.toLowerCase(), value]),
50+
);
51+
4552
export interface AcpMcpStdioBridgeOptions {
4653
readonly endpoint: string;
4754
readonly authorization: string;
@@ -193,9 +200,11 @@ function mcpRequest(
193200
fetchImplementation(options.endpoint, {
194201
method: "POST",
195202
headers: {
203+
// First and lowercased, so a user's `Accept` or `Content-Type`
204+
// can't sit beside the protocol's own and get merged by fetch.
205+
...lowercaseHeaders(options.headers),
196206
"content-type": "application/json",
197207
accept: "application/json, text/event-stream",
198-
...options.headers,
199208
// Empty for shared servers, which T3 does not authenticate.
200209
...(options.authorization ? { authorization: options.authorization } : {}),
201210
...(sessionId === null ? {} : { "mcp-session-id": sessionId }),
@@ -300,9 +309,11 @@ export function runAcpMcpStdioBridge(options: AcpMcpStdioBridgeOptions): Effect.
300309
fetchImplementation(options.endpoint, {
301310
method: "POST",
302311
headers: {
312+
// First and lowercased, so a user's `Accept` or `Content-Type`
313+
// can't sit beside the protocol's own and get merged by fetch.
314+
...lowercaseHeaders(options.headers),
303315
"content-type": "application/json",
304316
accept: "application/json, text/event-stream",
305-
...options.headers,
306317
// Empty for shared servers, which T3 does not authenticate.
307318
...(options.authorization ? { authorization: options.authorization } : {}),
308319
...(sessionId === null ? {} : { "mcp-session-id": sessionId }),

‎apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -45,12 +45,8 @@ import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
4545
import * as IdAllocator from "../IdAllocator.ts";
4646
import type { ProviderContinuationRequest } from "../ProviderContinuationRequests.ts";
4747
import * as ProviderContinuationRequests from "../ProviderContinuationRequests.ts";
48-
import { OPENCODE_PROVIDER } from "./OpenCodeAdapterV2.ts";
49-
import {
50-
OPENCODE_2_STILL_STOPPING,
51-
sharedMcpServerName,
52-
t3McpServerName,
53-
} from "./OpenCode2AdapterV2.ts";
48+
import { OPENCODE_PROVIDER, sharedMcpServerName } from "./OpenCodeAdapterV2.ts";
49+
import { OPENCODE_2_STILL_STOPPING, t3McpServerName } from "./OpenCode2AdapterV2.ts";
5450
import { openCode2ReplayRuntime } from "./OpenCode2AdapterV2.testkit.ts";
5551

5652
const SESSION = "ses_f148ca2deffeJcwCnRQtb0YFNX";

‎apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.ts‎

Lines changed: 6 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,12 @@ import {
9797
} from "../SubagentProjection.ts";
9898
import * as ProviderAdapter from "../ProviderAdapter.ts";
9999
import { turnScopedSelectionTransition } from "../ProviderSelectionTransition.ts";
100-
import { OPENCODE_PROVIDER, openCodePermissionRequestKind } from "./OpenCodeAdapterV2.ts";
100+
import {
101+
OPENCODE_PROVIDER,
102+
openCodePermissionRequestKind,
103+
sharedMcpServerName,
104+
sharedMcpServerPrefix,
105+
} from "./OpenCodeAdapterV2.ts";
101106
import { openCodeToolTurnItem } from "./OpenCodeToolItems.ts";
102107

103108
const OpenCode2ProviderCapabilities = {
@@ -480,22 +485,6 @@ export const t3McpServerName = (threadId: string) => {
480485
* this thread's own is allowed again, in every mode. A subagent's session
481486
* inherits the thread's.
482487
*/
483-
/**
484-
* A shared MCP server (Settings → Integrations) is registered per thread next
485-
* to T3's, as `t3-shared-<thread>_<server>`. A distinct prefix keeps its tools
486-
* out of T3's blanket allow. Like `t3McpServerName`, a thread id that would
487-
* push the name past OpenCode's 64 characters (with the longest, 24-character
488-
* server name) is replaced by a digest of it.
489-
*/
490-
const sharedMcpServerPrefix = (threadId: string) => {
491-
const prefix = `t3-shared-${threadId.replaceAll(/[^a-zA-Z0-9_-]/g, "_")}`;
492-
if (prefix.length <= 39) return prefix;
493-
const digest = NodeCrypto.createHash("sha256").update(threadId).digest("hex");
494-
return `t3-shared-${digest.slice(0, 16)}`;
495-
};
496-
497-
export const sharedMcpServerName = (threadId: string, server: string) =>
498-
`${sharedMcpServerPrefix(threadId)}_${server}`;
499488

500489
/**
501490
* Other threads' shared entries are denied like their T3 servers. This

‎apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.test.ts‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
33
import type { OpencodeClient, ToolPart } from "@opencode-ai/sdk/v2";
44
import {
55
CheckpointId,
6+
EnvironmentId,
67
NodeId,
78
OpenCodeSettings,
89
ProjectId,
@@ -32,11 +33,13 @@ import * as Stream from "effect/Stream";
3233
import * as TestClock from "effect/testing/TestClock";
3334

3435
import * as ServerConfig from "../../config.ts";
36+
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
3537
import type { EventNdjsonLogger } from "../../provider/EventNdjsonLogger.ts";
3638
import type { OpenCodeRuntimeShape } from "../../provider/opencodeRuntime.ts";
3739
import * as IdAllocator from "../IdAllocator.ts";
3840

3941
import {
42+
sharedMcpServerName,
4043
advanceOpenCodePromptAdmission,
4144
cancelOpenCodePromptAdmission,
4245
openCodeBoundaryAfterProviderTurn,
@@ -494,6 +497,60 @@ describe("OpenCodeAdapterV2", () => {
494497
}).pipe(Effect.provide(IdAllocator.layer), Effect.scoped),
495498
);
496499

500+
it.effect(
501+
"adds shared MCP servers under the thread's names on an external server and disconnects them",
502+
() =>
503+
Effect.gen(function* () {
504+
const scope = yield* Scope.make();
505+
const threadId = ThreadId.make("thread-opencode-shared");
506+
McpProviderSession.setMcpProviderSession({
507+
environmentId: EnvironmentId.make("environment-opencode-shared"),
508+
threadId,
509+
providerSessionId: "mcp-session-opencode-shared",
510+
providerInstanceId: ProviderInstanceId.make("opencode-shared"),
511+
endpoint: "http://127.0.0.1:43123/mcp",
512+
authorizationHeader: "Bearer thread-credential",
513+
browserToolsAvailable: false,
514+
sharedServers: [
515+
{ name: "gateway", url: "http://127.0.0.1:3050/mcp", enabled: true, headers: {} },
516+
{ name: "broken", url: "http://127.0.0.1:1/mcp", enabled: true, headers: {} },
517+
],
518+
});
519+
yield* Effect.addFinalizer(() =>
520+
Effect.sync(() => McpProviderSession.clearMcpProviderSession(threadId)),
521+
);
522+
const calls: string[] = [];
523+
yield* makeOpenCodeRuntimeHarness("shared", "root", {
524+
event: { subscribe: async () => ({ stream: asyncEventStream().stream }) },
525+
session: {
526+
create: async () => ({ data: { id: "root", time: { created: 1, updated: 1 } } }),
527+
abort: async () => ({ data: true }),
528+
children: async () => ({ data: [] }),
529+
},
530+
mcp: {
531+
add: async ({ name }: { name: string }) => {
532+
calls.push(`add:${name}`);
533+
if (name.endsWith("_broken")) throw new Error("unreachable");
534+
return { data: {} };
535+
},
536+
disconnect: async ({ name }: { name: string }) => {
537+
calls.push(`disconnect:${name}`);
538+
return { data: true };
539+
},
540+
},
541+
}).pipe(Effect.provideService(Scope.Scope, scope));
542+
yield* Scope.close(scope, Exit.void);
543+
544+
const gateway = sharedMcpServerName(threadId, "gateway");
545+
// T3's own server is skipped on an external server; only the shared one that was added is disconnected.
546+
assert.deepEqual(calls, [
547+
`add:${gateway}`,
548+
`add:${sharedMcpServerName(threadId, "broken")}`,
549+
`disconnect:${gateway}`,
550+
]);
551+
}).pipe(Effect.provide(IdAllocator.layer), Effect.scoped),
552+
);
553+
497554
it.effect.each(["enumeration", "abort", "not-found", "timeout"] as const)(
498555
"reports descendant cleanup %s",
499556
(failure) =>

‎apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts‎

Lines changed: 42 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import * as NodeCrypto from "node:crypto";
12
import type {
23
Event as OpenCodeEvent,
34
Message as OpenCodeMessage,
@@ -83,6 +84,23 @@ import { openCodeToolTurnItem } from "./OpenCodeToolItems.ts";
8384

8485
export { openCodeToolProjectionKind } from "./OpenCodeToolItems.ts";
8586

87+
/**
88+
* A shared MCP server (Settings → Integrations) is registered per thread next
89+
* to T3's, as `t3-shared-<thread>_<server>`. A distinct prefix keeps its tools
90+
* out of T3's blanket allow. Like OpenCode 2's `t3McpServerName`, a thread id that would
91+
* push the name past OpenCode's 64 characters (with the longest, 24-character
92+
* server name) is replaced by a digest of it.
93+
*/
94+
export const sharedMcpServerPrefix = (threadId: string) => {
95+
const prefix = `t3-shared-${threadId.replaceAll(/[^a-zA-Z0-9_-]/g, "_")}`;
96+
if (prefix.length <= 39) return prefix;
97+
const digest = NodeCrypto.createHash("sha256").update(threadId).digest("hex");
98+
return `t3-shared-${digest.slice(0, 16)}`;
99+
};
100+
101+
export const sharedMcpServerName = (threadId: string, server: string) =>
102+
`${sharedMcpServerPrefix(threadId)}_${server}`;
103+
86104
export const OPENCODE_PROVIDER = ProviderDriverKind.make("opencode");
87105
export const OPENCODE_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(OPENCODE_PROVIDER);
88106
export const OPENCODE_SDK_PROTOCOL = "opencode-sdk.sse" as const;
@@ -988,12 +1006,18 @@ export function makeOpenCodeAdapterV2(
9881006
}
9891007
// Shared servers carry their own URLs and headers, so an external
9901008
// OpenCode server gets them even though it cannot reach T3's endpoint.
1009+
// There they are shared by every client and outlive this session, so
1010+
// each thread registers its own names and disconnects them on close.
9911011
// Each is an addition: one OpenCode cannot register (unreachable
9921012
// gateway, bad URL) must not fail the session.
1013+
const sharedNames: Array<string> = [];
9931014
for (const server of mcpSession?.sharedServers ?? []) {
994-
yield* OpenCodeRuntime.runOpenCodeSdk("mcp.add", () =>
1015+
const name = connection.external
1016+
? sharedMcpServerName(input.threadId, server.name)
1017+
: server.name;
1018+
const added = yield* OpenCodeRuntime.runOpenCodeSdk("mcp.add", () =>
9951019
client.mcp.add({
996-
name: server.name,
1020+
name,
9971021
config: {
9981022
type: "remote",
9991023
url: server.url,
@@ -1002,11 +1026,26 @@ export function makeOpenCodeAdapterV2(
10021026
},
10031027
}),
10041028
).pipe(
1029+
Effect.as(true),
10051030
Effect.catchCause((cause) =>
10061031
Effect.logWarning("Could not add a shared MCP server to OpenCode.", {
10071032
server: server.name,
10081033
cause,
1009-
}),
1034+
}).pipe(Effect.as(false)),
1035+
),
1036+
);
1037+
if (added) sharedNames.push(name);
1038+
}
1039+
if (connection.external && sharedNames.length > 0) {
1040+
yield* Scope.addFinalizer(
1041+
scope,
1042+
Effect.forEach(
1043+
sharedNames,
1044+
(name) =>
1045+
OpenCodeRuntime.runOpenCodeSdk("mcp.disconnect", () =>
1046+
client.mcp.disconnect({ name }),
1047+
).pipe(Effect.timeout("1 second"), Effect.ignore({ log: true })),
1048+
{ discard: true },
10101049
),
10111050
);
10121051
}

‎apps/server/src/orchestration-v2/Adapters/piT3McpExtensionSource.test.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ describe("Pi shared MCP servers", () => {
9797
{
9898
name: "gateway",
9999
url: "http://127.0.0.1:3050/mcp",
100-
headers: { Authorization: "Bearer gateway-token" },
100+
headers: { Authorization: "Bearer gateway-token", "Content-Type": "text/plain" },
101101
},
102102
]),
103103
},
@@ -117,10 +117,12 @@ describe("Pi shared MCP servers", () => {
117117
const call = requests.find((request) => request.body.method === "tools/call");
118118
assert.equal(call?.url, "http://127.0.0.1:3050/mcp");
119119
assert.deepEqual(call?.body.params, { name: "search", arguments: { q: "x" } });
120-
// The gateway gets its own header and never T3's credential.
120+
// The gateway gets its own header, never T3's credential, and a user
121+
// header can't sit beside the protocol's own under another casing.
121122
for (const request of requests.filter((entry) => entry.url.includes("3050"))) {
122-
assert.equal(request.headers.Authorization, "Bearer gateway-token");
123-
assert.isUndefined(request.headers.authorization);
123+
assert.equal(request.headers.authorization, "Bearer gateway-token");
124+
assert.equal(request.headers["content-type"], "application/json");
125+
assert.isUndefined(request.headers["Content-Type"]);
124126
}
125127
});
126128
});

‎apps/server/src/orchestration-v2/Adapters/piT3McpExtensionSource.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,8 +157,12 @@ function createMcpClient(endpoint: string, requestHeaders: Record<string, string
157157
let sessionId: string | undefined;
158158
159159
const headers = (): Record<string, string> => {
160+
// Lowercased, so a shared server's \`Accept\` or \`Content-Type\` is
161+
// replaced by the protocol's own instead of merged with it.
160162
const next: Record<string, string> = {
161-
...requestHeaders,
163+
...Object.fromEntries(
164+
Object.entries(requestHeaders).map(([name, value]) => [name.toLowerCase(), value]),
165+
),
162166
accept: "application/json, text/event-stream",
163167
"content-type": "application/json",
164168
// Effect's HTTP MCP rejects post-initialize requests without this

‎apps/server/src/orchestration-v2/ProviderSessionManager.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -336,7 +336,11 @@ export const layerWithOptions = (
336336
? Effect.succeed([])
337337
: serverSettings.value.getSettings.pipe(
338338
Effect.map((settings) => settings.sharedMcpServers.filter((server) => server.enabled)),
339-
Effect.orElseSucceed(() => []),
339+
Effect.catch((cause) =>
340+
Effect.logWarning("Could not read shared MCP servers; sessions get none.", {
341+
cause,
342+
}).pipe(Effect.as([])),
343+
),
340344
);
341345
const agentAccessSettings = Effect.fn("ProviderSessionManagerV2.agentAccessSettings")(
342346
function* (threadId: ThreadId) {

‎apps/web/src/components/settings/SharedMcpServersSettings.tsx‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -106,12 +106,18 @@ function SharedMcpServerRows({
106106
const [saving, setSaving] = useState(false);
107107
const save = async (sharedMcpServers: ReadonlyArray<SharedMcpServer>) => {
108108
setSaving(true);
109-
await updateSettings({
109+
const result = await updateSettings({
110110
environmentId: environment.environmentId,
111111
input: { patch: { sharedMcpServers: [...sharedMcpServers] } },
112112
});
113113
setSaving(false);
114+
return result._tag === "Success";
114115
};
116+
// A failed save keeps the form open, so nothing typed is lost.
117+
const saveAndClose = (sharedMcpServers: ReadonlyArray<SharedMcpServer>) =>
118+
void save(sharedMcpServers).then((saved) => {
119+
if (saved) onFormChange(null);
120+
});
115121

116122
return (
117123
<>
@@ -129,10 +135,7 @@ function SharedMcpServerRows({
129135
editing={server}
130136
onCancel={() => onFormChange(null)}
131137
saving={saving}
132-
onSave={(next) => {
133-
void save(upsertSharedMcpServer(servers, next, server));
134-
onFormChange(null);
135-
}}
138+
onSave={(next) => saveAndClose(upsertSharedMcpServer(servers, next, server))}
136139
/>
137140
) : (
138141
<SharedMcpServerRow
@@ -155,10 +158,7 @@ function SharedMcpServerRows({
155158
servers={servers}
156159
saving={saving}
157160
onCancel={() => onFormChange(null)}
158-
onSave={(next) => {
159-
void save(upsertSharedMcpServer(servers, next));
160-
onFormChange(null);
161-
}}
161+
onSave={(next) => saveAndClose(upsertSharedMcpServer(servers, next))}
162162
/>
163163
) : null}
164164
</>

0 commit comments

Comments
 (0)