Skip to content

Commit 9768663

Browse files
narcisoafclaude
andcommitted
fix(mcp): address second CodeRabbit review on shared MCP servers
- OpenCode 1 bounds adding a shared server (cancellable, 5s timeout), so a server that never answers can't hold the session open. - OpenCode 2 retries a shared server OpenCode refused on the next turn, as it does T3's own server. - OpenCode 2 keeps its MCP inventory when reconnecting to an external server, which still holds the registrations, so closing the session still removes them and the headers they carry. - The web form closes only if it is the one that started the save. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent 6a05cb9 commit 9768663

4 files changed

Lines changed: 198 additions & 87 deletions

File tree

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

Lines changed: 128 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -2712,7 +2712,104 @@ describe("OpenCode2 adapter", () => {
27122712
}).pipe(Effect.scoped),
27132713
);
27142714

2715-
it.effect("adds the thread's shared MCP servers next to T3's and removes them with it", () =>
2715+
it.effect(
2716+
"adds the thread's shared MCP servers next to T3's, retries a refused one, and removes them with it",
2717+
() =>
2718+
Effect.gen(function* () {
2719+
McpProviderSession.setMcpProviderSession({
2720+
environmentId: EnvironmentId.make("environment:opencode2-adapter"),
2721+
threadId,
2722+
providerSessionId: "mcp:opencode2-adapter",
2723+
providerInstanceId: instanceId,
2724+
endpoint: "http://127.0.0.1:3773/mcp",
2725+
authorizationHeader: "Bearer thread-credential",
2726+
browserToolsAvailable: false,
2727+
sharedServers: [
2728+
{
2729+
name: "gateway",
2730+
url: "http://127.0.0.1:3050/mcp",
2731+
enabled: true,
2732+
headers: { Authorization: "Bearer gateway-token" },
2733+
},
2734+
{ name: "broken", url: "http://127.0.0.1:1/mcp", enabled: true, headers: {} },
2735+
],
2736+
});
2737+
yield* Effect.addFinalizer(() =>
2738+
Effect.sync(() => McpProviderSession.clearMcpProviderSession(threadId)),
2739+
);
2740+
const server = "t3-code-thread_opencode2-adapter";
2741+
const gateway = "t3-shared-thread_opencode2-adapter_gateway";
2742+
const broken = "t3-shared-thread_opencode2-adapter_broken";
2743+
const { runtime, thread } = yield* resumed([
2744+
out("mcp.add", { server, "location[directory]": WORK, config: "<any>" }),
2745+
reply("mcp.add", null),
2746+
out("mcp.add", {
2747+
server: gateway,
2748+
"location[directory]": WORK,
2749+
config: {
2750+
type: "remote",
2751+
url: "http://127.0.0.1:3050/mcp",
2752+
headers: { Authorization: "Bearer gateway-token" },
2753+
oauth: false,
2754+
},
2755+
}),
2756+
reply("mcp.add", null),
2757+
// A shared server OpenCode refuses is skipped; the turn still runs.
2758+
out("mcp.add", {
2759+
server: broken,
2760+
"location[directory]": WORK,
2761+
config: { type: "remote", url: "http://127.0.0.1:1/mcp", oauth: false },
2762+
}),
2763+
reply("mcp.add", { status: 500, body: { _tag: "UnknownError", message: "add failed" } }),
2764+
out("session.prompt", { sessionID: SESSION, text: "<any>" }),
2765+
promptAccepted,
2766+
event("session.execution.succeeded", { sessionID: SESSION }),
2767+
// The next turn retries the one OpenCode refused, as it would T3's own.
2768+
out("mcp.add", {
2769+
server: broken,
2770+
"location[directory]": WORK,
2771+
config: { type: "remote", url: "http://127.0.0.1:1/mcp", oauth: false },
2772+
}),
2773+
reply("mcp.add", null),
2774+
out("session.prompt", { sessionID: SESSION, text: "<any>" }),
2775+
promptAccepted,
2776+
event("session.execution.succeeded", { sessionID: SESSION }),
2777+
out("mcp.remove", { server, "location[directory]": WORK }),
2778+
reply("mcp.remove", null),
2779+
out("mcp.remove", { server: gateway, "location[directory]": WORK }),
2780+
reply("mcp.remove", null),
2781+
out("mcp.remove", { server: broken, "location[directory]": WORK }),
2782+
reply("mcp.remove", null),
2783+
]);
2784+
const firstEnded = yield* Deferred.make<void>();
2785+
const ended = yield* runtime.events.pipe(
2786+
Stream.filter(
2787+
(event): event is Extract<ProviderAdapterV2Event, { type: "turn.terminal" }> =>
2788+
event.type === "turn.terminal",
2789+
),
2790+
Stream.tap(() => Deferred.succeed(firstEnded, undefined)),
2791+
Stream.take(2),
2792+
Stream.runCollect,
2793+
Effect.forkScoped,
2794+
);
2795+
yield* runtime.startTurn(turnInput(thread));
2796+
yield* Deferred.await(firstEnded);
2797+
yield* runtime.startTurn({
2798+
...turnInput(thread),
2799+
runId: RunId.make("run:opencode2-adapter:2"),
2800+
runOrdinal: 2,
2801+
providerTurnOrdinal: 2,
2802+
attemptId: RunAttemptId.make("attempt:opencode2-adapter:2"),
2803+
});
2804+
assert.deepEqual(
2805+
[...(yield* Fiber.join(ended))].map((terminal) => terminal.status),
2806+
["completed", "completed"],
2807+
);
2808+
yield* runtime.unloadThread!({ providerThread: thread });
2809+
}).pipe(Effect.scoped),
2810+
);
2811+
2812+
it.effect("adds shared MCP servers on an external server, which skips T3's own", () =>
27162813
Effect.gen(function* () {
27172814
McpProviderSession.setMcpProviderSession({
27182815
environmentId: EnvironmentId.make("environment:opencode2-adapter"),
@@ -2723,57 +2820,37 @@ describe("OpenCode2 adapter", () => {
27232820
authorizationHeader: "Bearer thread-credential",
27242821
browserToolsAvailable: false,
27252822
sharedServers: [
2726-
{
2727-
name: "gateway",
2728-
url: "http://127.0.0.1:3050/mcp",
2729-
enabled: true,
2730-
headers: { Authorization: "Bearer gateway-token" },
2731-
},
2732-
{ name: "broken", url: "http://127.0.0.1:1/mcp", enabled: true, headers: {} },
2823+
{ name: "gateway", url: "https://mcp.example.com/mcp", enabled: true, headers: {} },
27332824
],
27342825
});
27352826
yield* Effect.addFinalizer(() =>
27362827
Effect.sync(() => McpProviderSession.clearMcpProviderSession(threadId)),
27372828
);
2738-
const server = "t3-code-thread_opencode2-adapter";
27392829
const gateway = "t3-shared-thread_opencode2-adapter_gateway";
2740-
const { runtime, thread } = yield* resumed([
2741-
out("mcp.add", { server, "location[directory]": WORK, config: "<any>" }),
2742-
reply("mcp.add", null),
2743-
out("mcp.add", {
2744-
server: gateway,
2745-
"location[directory]": WORK,
2746-
config: {
2747-
type: "remote",
2748-
url: "http://127.0.0.1:3050/mcp",
2749-
headers: { Authorization: "Bearer gateway-token" },
2750-
oauth: false,
2751-
},
2752-
}),
2753-
reply("mcp.add", null),
2754-
// A shared server OpenCode refuses is skipped; the turn still runs.
2755-
out("mcp.add", {
2756-
server: "t3-shared-thread_opencode2-adapter_broken",
2757-
"location[directory]": WORK,
2758-
config: { type: "remote", url: "http://127.0.0.1:1/mcp", oauth: false },
2759-
}),
2760-
reply("mcp.add", { status: 500, body: { _tag: "UnknownError", message: "add failed" } }),
2761-
out("session.prompt", { sessionID: SESSION, text: "<any>" }),
2762-
promptAccepted,
2763-
event("session.execution.succeeded", { sessionID: SESSION }),
2764-
out("mcp.remove", { server, "location[directory]": WORK }),
2765-
reply("mcp.remove", null),
2766-
out("mcp.remove", { server: gateway, "location[directory]": WORK }),
2767-
reply("mcp.remove", null),
2768-
]);
2830+
const { runtime, thread } = yield* resumed(
2831+
[
2832+
out("mcp.add", {
2833+
server: gateway,
2834+
"location[directory]": WORK,
2835+
config: { type: "remote", url: "https://mcp.example.com/mcp", oauth: false },
2836+
}),
2837+
reply("mcp.add", null),
2838+
out("session.prompt", { sessionID: SESSION, text: "<any>" }),
2839+
promptAccepted,
2840+
event("session.execution.succeeded", { sessionID: SESSION }),
2841+
out("mcp.remove", { server: gateway, "location[directory]": WORK }),
2842+
reply("mcp.remove", null),
2843+
],
2844+
{ external: true },
2845+
);
27692846
const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
27702847
yield* runtime.startTurn(turnInput(thread));
27712848
assert.equal((yield* Fiber.join(terminal))?.status, "completed");
27722849
yield* runtime.unloadThread!({ providerThread: thread });
27732850
}).pipe(Effect.scoped),
27742851
);
27752852

2776-
it.effect("adds shared MCP servers on an external server, which skips T3's own", () =>
2853+
it.effect("keeps an external server's shared MCP registrations through a reconnect", () =>
27772854
Effect.gen(function* () {
27782855
McpProviderSession.setMcpProviderSession({
27792856
environmentId: EnvironmentId.make("environment:opencode2-adapter"),
@@ -2784,7 +2861,12 @@ describe("OpenCode2 adapter", () => {
27842861
authorizationHeader: "Bearer thread-credential",
27852862
browserToolsAvailable: false,
27862863
sharedServers: [
2787-
{ name: "gateway", url: "https://mcp.example.com/mcp", enabled: true, headers: {} },
2864+
{
2865+
name: "gateway",
2866+
url: "https://mcp.example.com/mcp",
2867+
enabled: true,
2868+
headers: { Authorization: "Bearer gateway-token" },
2869+
},
27882870
],
27892871
});
27902872
yield* Effect.addFinalizer(() =>
@@ -2793,15 +2875,15 @@ describe("OpenCode2 adapter", () => {
27932875
const gateway = "t3-shared-thread_opencode2-adapter_gateway";
27942876
const { runtime, thread } = yield* resumed(
27952877
[
2796-
out("mcp.add", {
2797-
server: gateway,
2798-
"location[directory]": WORK,
2799-
config: { type: "remote", url: "https://mcp.example.com/mcp", oauth: false },
2800-
}),
2878+
out("mcp.add", { server: gateway, "location[directory]": WORK, config: "<any>" }),
28012879
reply("mcp.add", null),
2802-
out("session.prompt", { sessionID: SESSION, text: "<any>" }),
2880+
out("session.prompt", { sessionID: SESSION, id: PROMPT_ID, text: "<any>" }),
28032881
promptAccepted,
2882+
// The event stream drops mid-turn; the external server is the same one after.
2883+
...reconnected({ [SESSION]: { type: "running" } }),
2884+
...openRequests([]),
28042885
event("session.execution.succeeded", { sessionID: SESSION }),
2886+
// Its registration is still known, so unloading still removes it, headers and all.
28052887
out("mcp.remove", { server: gateway, "location[directory]": WORK }),
28062888
reply("mcp.remove", null),
28072889
],

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

Lines changed: 44 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -416,6 +416,8 @@ interface ThreadState {
416416
/** Whether T3's own server is among `names`, which gates its instructions. */
417417
readonly t3: boolean;
418418
readonly names: ReadonlyArray<string>;
419+
/** Shared servers OpenCode refused, retried on the next turn. */
420+
readonly missing: ReadonlyArray<SharedMcpServer>;
419421
}
420422
| undefined;
421423
instructions: string | undefined;
@@ -2868,8 +2870,10 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
28682870
client = next.client;
28692871
currentScope = scope;
28702872
yield* Scope.close(previous, Exit.void);
2871-
// A restarted server forgot T3's MCP servers; the next turn adds them again.
2872-
for (const state of threads.values()) state.mcp = undefined;
2873+
// A restarted server forgot T3's MCP servers; the next turn adds them
2874+
// again. An external server is the same one, still holding them, so
2875+
// keep the inventory that cleanup removes them by.
2876+
if (!next.external) for (const state of threads.values()) state.mcp = undefined;
28732877
yield* lock.withPermit(reconcile).pipe(Effect.timeout(RECONCILE_TIMEOUT));
28742878
return stream;
28752879
}).pipe(
@@ -3327,30 +3331,45 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
33273331
}),
33283332
"T3 Code's MCP server",
33293333
);
3334+
const addShared = (server: SharedMcpServer) =>
3335+
addMcp(
3336+
sharedMcpServerName(turnInput.threadId, server.name),
3337+
new Mcp.RemoteConfig({
3338+
type: "remote",
3339+
url: server.url,
3340+
...(Object.keys(server.headers).length === 0 ? {} : { headers: server.headers }),
3341+
oauth: false,
3342+
}),
3343+
`shared MCP server ${server.name}`,
3344+
);
3345+
// Shared servers carry their own URLs and headers, so they are added even
3346+
// where T3's own server is not. One that fails is retried next turn, as
3347+
// T3's own is.
3348+
const addAll = (t3Wanted: boolean, shared: ReadonlyArray<SharedMcpServer>) =>
3349+
Effect.gen(function* () {
3350+
const t3 = t3Wanted ? yield* addT3() : false;
3351+
const names: Array<string> = t3 ? [name] : [];
3352+
const missing: Array<SharedMcpServer> = [];
3353+
for (const server of shared) {
3354+
if (yield* addShared(server)) {
3355+
names.push(sharedMcpServerName(turnInput.threadId, server.name));
3356+
} else missing.push(server);
3357+
}
3358+
return { t3, names, missing };
3359+
});
33303360
if (wanted !== undefined && state.mcp === undefined) {
3331-
const t3 = yield* addT3();
3332-
const names = t3 ? [name] : [];
3333-
// Shared servers carry their own URLs and headers, so they are added
3334-
// even where T3's own server is not.
3335-
for (const server of sharedServers) {
3336-
const sharedName = sharedMcpServerName(turnInput.threadId, server.name);
3337-
const added = yield* addMcp(
3338-
sharedName,
3339-
new Mcp.RemoteConfig({
3340-
type: "remote",
3341-
url: server.url,
3342-
...(Object.keys(server.headers).length === 0 ? {} : { headers: server.headers }),
3343-
oauth: false,
3344-
}),
3345-
`shared MCP server ${server.name}`,
3346-
);
3347-
if (added) names.push(sharedName);
3348-
}
3349-
state.mcp = { ...wanted, t3, names };
3350-
} else if (state.mcp !== undefined && !state.mcp.t3 && !connection.external) {
3351-
// Retry only T3's own server, so a failing one doesn't re-add the shared ones every turn.
3352-
if (yield* addT3())
3353-
state.mcp = { ...state.mcp, t3: true, names: [name, ...state.mcp.names] };
3361+
state.mcp = { ...wanted, ...(yield* addAll(true, sharedServers)) };
3362+
} else if (
3363+
state.mcp !== undefined &&
3364+
((!state.mcp.t3 && !connection.external) || state.mcp.missing.length > 0)
3365+
) {
3366+
const retried = yield* addAll(!state.mcp.t3, state.mcp.missing);
3367+
state.mcp = {
3368+
...state.mcp,
3369+
t3: state.mcp.t3 || retried.t3,
3370+
names: [...state.mcp.names, ...retried.names],
3371+
missing: retried.missing,
3372+
};
33543373
}
33553374
const instructions = [
33563375
buildRuntimeInstructions({ harness: "OpenCode", model: turnInput.modelSelection.model }),

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

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,8 @@ export { openCodeToolProjectionKind } from "./OpenCodeToolItems.ts";
9191
* push the name past OpenCode's 64 characters (with the longest, 24-character
9292
* server name) is replaced by a digest of it.
9393
*/
94+
const SHARED_MCP_ADD_TIMEOUT = "5 seconds";
95+
9496
export const sharedMcpServerPrefix = (threadId: string) => {
9597
const prefix = `t3-shared-${threadId.replaceAll(/[^a-zA-Z0-9_-]/g, "_")}`;
9698
if (prefix.length <= 39) return prefix;
@@ -1015,17 +1017,22 @@ export function makeOpenCodeAdapterV2(
10151017
const name = connection.external
10161018
? sharedMcpServerName(input.threadId, server.name)
10171019
: server.name;
1018-
const added = yield* OpenCodeRuntime.runOpenCodeSdk("mcp.add", () =>
1019-
client.mcp.add({
1020-
name,
1021-
config: {
1022-
type: "remote",
1023-
url: server.url,
1024-
...(Object.keys(server.headers).length === 0 ? {} : { headers: server.headers }),
1025-
oauth: false,
1020+
const added = yield* OpenCodeRuntime.runOpenCodeSdk("mcp.add", (signal) =>
1021+
client.mcp.add(
1022+
{
1023+
name,
1024+
config: {
1025+
type: "remote",
1026+
url: server.url,
1027+
...(Object.keys(server.headers).length === 0 ? {} : { headers: server.headers }),
1028+
oauth: false,
1029+
},
10261030
},
1027-
}),
1031+
{ signal },
1032+
),
10281033
).pipe(
1034+
// Bounded, so a server that never answers can't hold the session open.
1035+
Effect.timeout(SHARED_MCP_ADD_TIMEOUT),
10291036
Effect.as(true),
10301037
Effect.catchCause((cause) =>
10311038
Effect.logWarning("Could not add a shared MCP server to OpenCode.", {
@@ -1042,8 +1049,8 @@ export function makeOpenCodeAdapterV2(
10421049
Effect.forEach(
10431050
sharedNames,
10441051
(name) =>
1045-
OpenCodeRuntime.runOpenCodeSdk("mcp.disconnect", () =>
1046-
client.mcp.disconnect({ name }),
1052+
OpenCodeRuntime.runOpenCodeSdk("mcp.disconnect", (signal) =>
1053+
client.mcp.disconnect({ name }, { signal }),
10471054
).pipe(Effect.timeout("1 second"), Effect.ignore({ log: true })),
10481055
{ discard: true },
10491056
),

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

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import {
1010
squashAtomCommandFailure,
1111
} from "@t3tools/client-runtime/state/runtime";
1212
import { MoreHorizontalIcon, PencilIcon, PlugZapIcon, PlusIcon, Trash2Icon } from "lucide-react";
13-
import { useState } from "react";
13+
import { type Dispatch, type SetStateAction, useState } from "react";
1414

1515
import { useEnvironmentSettings } from "../../hooks/useSettings";
1616
import type { EnvironmentPresentation } from "../../state/environments";
@@ -92,7 +92,7 @@ function SharedMcpServerRows({
9292
}: {
9393
readonly environment: EnvironmentPresentation;
9494
readonly form: FormState;
95-
readonly onFormChange: (form: FormState) => void;
95+
readonly onFormChange: Dispatch<SetStateAction<FormState>>;
9696
}) {
9797
const servers = useEnvironmentSettings(
9898
environment.environmentId,
@@ -113,11 +113,14 @@ function SharedMcpServerRows({
113113
setSaving(false);
114114
return result._tag === "Success";
115115
};
116-
// A failed save keeps the form open, so nothing typed is lost.
117-
const saveAndClose = (sharedMcpServers: ReadonlyArray<SharedMcpServer>) =>
116+
// A failed save keeps the form open, so nothing typed is lost; a late one
117+
// closes only the form that started it, not one opened since.
118+
const saveAndClose = (sharedMcpServers: ReadonlyArray<SharedMcpServer>) => {
119+
const started = form;
118120
void save(sharedMcpServers).then((saved) => {
119-
if (saved) onFormChange(null);
121+
if (saved) onFormChange((current) => (current === started ? null : current));
120122
});
123+
};
121124

122125
return (
123126
<>

0 commit comments

Comments
 (0)