Skip to content

Commit 9e968b1

Browse files
fix(opencode): pre-register MCP in the thread's runtime directory for every new thread
Review follow-ups on the first-turn MCP registration: - Register in the thread's runtime policy cwd, not the server launch directory. OpenCode MCP registrations are directory-scoped and the native session is created in runtimePolicy.cwd, so a pre-registration anywhere else never entered that session's tool catalog. - Pre-register before every session.create and session.fork, not only in openSession: a provider session reused for a second app thread, and native thread forks, reached session creation before any mcp.add and still started their first turn without a T3 catalog. - Stop unconditionally deleting the registeredMcp entry in prepareTurn: when the defensive re-add fails, the live server is now left tracked so the session finalizer can still remove it instead of leaking the per-thread server and credential on the shared OpenCode process. New test covers registration in the runtime directory; suite passes (129 tests) and package typecheck is clean.
1 parent bd66aae commit 9e968b1

2 files changed

Lines changed: 84 additions & 13 deletions

File tree

‎packages/provider-opencode/src/server/v2/adapter.test.ts‎

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,11 @@ const runtimePolicy = () =>
8686
cwd: "/workspace",
8787
});
8888

89-
const openFor = (adapter: ProviderAdapter.ProviderAdapterV2["Service"], threadId: ThreadId) =>
89+
const openFor = (
90+
adapter: ProviderAdapter.ProviderAdapterV2["Service"],
91+
threadId: ThreadId,
92+
cwd?: string,
93+
) =>
9094
adapter.openSession({
9195
threadId,
9296
providerSessionId: ProviderSessionId.make(`provider-session-${threadId}`),
@@ -95,7 +99,14 @@ const openFor = (adapter: ProviderAdapter.ProviderAdapterV2["Service"], threadId
9599
model: "anthropic/claude-sonnet",
96100
options: [],
97101
},
98-
runtimePolicy: runtimePolicy(),
102+
runtimePolicy:
103+
cwd === undefined
104+
? runtimePolicy()
105+
: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
106+
runtimeMode: "full-access",
107+
interactionMode: "default",
108+
cwd,
109+
}),
99110
});
100111

101112
it.effect(
@@ -120,6 +131,28 @@ it.effect(
120131
},
121132
);
122133

134+
it.effect(
135+
"registers the server in the thread's runtime directory, not the server launch directory",
136+
() => {
137+
const calls: Array<RecordedCall> = [];
138+
return Effect.gen(function* () {
139+
const threadId = ThreadId.make("thread-490f020d");
140+
const adapter = yield* make(ProviderInstanceId.make("opencode-test"));
141+
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
142+
yield* mcpSessions.set(mcpConfig(threadId));
143+
144+
// OpenCode MCP registrations are directory-scoped, and the native
145+
// session is created in the runtime policy's cwd — a server registered
146+
// anywhere else never enters that session's tool catalog.
147+
yield* openFor(adapter, threadId, "/projects/app-worktree");
148+
149+
const adds = calls.filter((call) => call.op === "mcp.add");
150+
assert.strictEqual(adds.length, 1);
151+
assert.deepStrictEqual(adds[0]!.args.location, { directory: "/projects/app-worktree" });
152+
}).pipe(Effect.provide(makeLayers(calls)));
153+
},
154+
);
155+
123156
it.effect(
124157
"two concurrent threads register distinct servers and keep only their own routing rules",
125158
() => {

‎packages/provider-opencode/src/server/v2/adapter.ts‎

Lines changed: 49 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ import {
3636
type ProviderInstanceId,
3737
type RunId,
3838
type RuntimeRequestId,
39+
type ThreadId,
3940
} from "@t3tools/contracts";
4041
import type * as Cause from "effect/Cause";
4142
import * as DateTime from "effect/DateTime";
@@ -3089,16 +3090,29 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
30893090
* session manager before `openSession`, so the config is normally ready.
30903091
*/
30913092
const registeredMcp = new Map<
3092-
string,
3093+
ThreadId,
30933094
{ readonly name: string; readonly directory: string; readonly credential: string }
30943095
>();
3095-
const mcpSession = yield* mcpSessions.read(input.threadId);
3096-
if (mcpSession !== undefined && !connection.external) {
3097-
const name = yield* mcpServerNameFor(input.threadId);
3096+
/**
3097+
* Registers the thread's MCP server in a specific directory, before that
3098+
* thread's native session exists. OpenCode MCP registrations are
3099+
* directory-scoped, and a session's tool catalog is built from the
3100+
* directory the session is created in, so `directory` must be the same
3101+
* runtime directory the session will be created or forked in — not the
3102+
* server launch directory.
3103+
*/
3104+
const preRegisterMcp = Effect.fn("OpenCode2Adapter.preRegisterMcp")(function* (
3105+
threadId: ThreadId,
3106+
directory: string,
3107+
) {
3108+
if (connection.external || registeredMcp.has(threadId)) return;
3109+
const mcpSession = yield* mcpSessions.read(threadId);
3110+
if (mcpSession === undefined) return;
3111+
const name = yield* mcpServerNameFor(threadId);
30983112
const added = yield* client.mcp
30993113
.add({
31003114
server: name,
3101-
location: { directory: host.paths.cwd },
3115+
location: { directory },
31023116
config: new Mcp.RemoteConfig({
31033117
type: "remote",
31043118
url: mcpSession.endpoint,
@@ -3116,13 +3130,18 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
31163130
),
31173131
);
31183132
if (added) {
3119-
registeredMcp.set(input.threadId, {
3133+
registeredMcp.set(threadId, {
31203134
name,
3121-
directory: host.paths.cwd,
3135+
directory,
31223136
credential: mcpSession.authorizationHeader,
31233137
});
31243138
}
3125-
}
3139+
});
3140+
3141+
// The session's first thread is prepared by the session manager with this
3142+
// same runtime policy before `openSession`, so register in the directory
3143+
// its native session will be created in.
3144+
yield* preRegisterMcp(input.threadId, input.runtimePolicy.cwd ?? host.paths.cwd);
31263145

31273146
yield* Effect.addFinalizer(() =>
31283147
Effect.forEach(
@@ -3150,7 +3169,9 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
31503169
: { name, directory, credential: mcpSession.authorizationHeader };
31513170
// A server registered before the thread's first turn lives in
31523171
// `registeredMcp`: no ThreadState existed yet. Removal decisions must see
3153-
// it, and once this turn records it on the state, the map copy goes away.
3172+
// it, and ownership moves to the state only once this turn's add
3173+
// succeeds — a failed or timed-out re-add leaves the map entry in place
3174+
// so the finalizer can still remove the live server.
31543175
const known = state.mcp ?? registeredMcp.get(turnInput.threadId);
31553176
if (
31563177
known !== undefined &&
@@ -3160,8 +3181,10 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
31603181
) {
31613182
yield* removeMcp(known);
31623183
if (state.mcp === known) state.mcp = undefined;
3184+
if (registeredMcp.get(turnInput.threadId) === known) {
3185+
registeredMcp.delete(turnInput.threadId);
3186+
}
31633187
}
3164-
registeredMcp.delete(turnInput.threadId);
31653188
// Idle Location eviction drops runtime MCP servers without clearing T3's cache.
31663189
// Re-adding an unchanged config keeps its existing connection.
31673190
let mcpAvailable = false;
@@ -3186,7 +3209,11 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
31863209
),
31873210
),
31883211
);
3189-
if (mcpAvailable) state.mcp = wanted;
3212+
if (mcpAvailable) {
3213+
state.mcp = wanted;
3214+
// Ownership of any pre-registration moved onto the state.
3215+
registeredMcp.delete(turnInput.threadId);
3216+
}
31903217
}
31913218
const instructions = [
31923219
buildRuntimeInstructions({ harness: "OpenCode", model: turnInput.modelSelection.model }),
@@ -3528,6 +3555,9 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
35283555
threadInput.threadId,
35293556
);
35303557
const title = threadInput.title?.trim() || undefined;
3558+
// The catalog is built from this directory at `session.create`, so
3559+
// the thread's own MCP server must already be registered there.
3560+
yield* preRegisterMcp(threadInput.threadId, directory);
35313561
// A session created with a title is never titled by OpenCode's own model.
35323562
const created = yield* client.session.create({
35333563
location: Location.PublicRef.make({ directory: AbsolutePath.make(directory) }),
@@ -4125,6 +4155,14 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
41254155
yield* userMessages(sourceId),
41264156
);
41274157
// A fork copies the source's history, model, location and rules; its
4158+
// catalog is built at `session.fork`, so the target's own MCP server
4159+
// must already be registered in the directory the forked session
4160+
// starts in — a fork's inherited source server is denied by the
4161+
// target thread's rules.
4162+
yield* preRegisterMcp(
4163+
forkInput.targetThreadId,
4164+
forkInput.runtimePolicy?.cwd ?? ownerOf(sourceId)?.directory ?? host.paths.cwd,
4165+
);
41284166
const forked = yield* client.session.fork({
41294167
sessionID: Session.ID.make(sourceId),
41304168
...(before === null ? {} : { before: SessionMessage.ID.make(before) }),

0 commit comments

Comments
 (0)