Skip to content

Commit bd66aae

Browse files
fix(opencode): register the thread's T3 MCP server before the first session exists
OpenCode 2 builds a session's tool catalog when the session is created, but the OpenCode 2 adapter only added T3's MCP server in prepareTurn, after session.create, so the first model request saw no T3 tools and agents concluded delegation was unavailable until a later catalog refresh. The server is now registered in openSession, before any session can be created, with the same per-thread name, and prepareTurn reuses that registration. The injected orchestration instructions also advertised a flat mcp__t3_code__ prefix, which matches no OpenCode Code Mode path: the instructions now document the per-thread t3-code-<threadId> namespace, recommend namespace-agnostic catalog discovery, and the adapter appends the exact registered name to the prompt. Done with GLM-5.3-Flash in T3 Code (OpenCode harness).
1 parent 680152e commit bd66aae

3 files changed

Lines changed: 287 additions & 11 deletions

File tree

‎packages/provider-core/src/server/orchestrationInstructions.ts‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ For stacked work, set \`baseRef\` to the intended parent branch and \`startFromO
2929
\`t3_thread_launch\` is the single-thread launch tool. Use \`create_threads\` only for a batch of threads intentionally sharing the caller's checkout: it always inherits the caller's project, branch, and worktree and has no workspace override. Asking an agent to run \`git worktree add\` or \`cd\` in its prompt does not update T3's thread binding. Select the workspace in the launch call instead. \`t3_worktree_handoff\` moves the calling thread, not another thread, and cannot move a thread already attached to a worktree.
3030
3131
\`t3_thread_launch\` has no idempotency key. Retain its returned threadId and inspect it with \`t3_thread_read\` / \`t3_thread_wait\`; preparation can still be running after acceptance. If a launch fails or its response is lost, inspect \`t3_thread_list\` before retrying, since a thread may already exist.`,
32-
`Tool names may include a harness-normalized MCP prefix, such as \`mcp__t3_code__delegate_task\`; the semantics are the same. Some harnesses attach optional MCP servers lazily: if an initial tool-catalog scan does not show T3 tools, do not conclude that cross-provider delegation is unavailable. Make one bounded direct attempt using the known T3 tool name on the next tool step. In Codex code mode, for example, call \`tools.mcp__t3_code__orchestrator_capabilities({})\` before reporting that the capability is absent. Keep polling/wait loops bounded, do not duplicate active work, and use stable \`clientRequestId\` values when retrying tools that accept them.
32+
`Tool names may include a harness-normalized MCP prefix, and some harnesses rename the server per session. In OpenCode's Code Mode, T3 registers one server per thread named \`t3-code-<threadId>\` (or \`t3-code-<digest>\` for long ids), so paths look like \`tools["t3-code-..."].delegate_task\`; in Codex code mode the prefix is flat, \`tools.mcp__t3_code__delegate_task\`. The semantics are the same. Some harnesses attach optional MCP servers lazily: if an initial tool-catalog scan does not show T3 tools, do not conclude that cross-provider delegation is unavailable. Prefer a namespace-agnostic catalog search for a T3 tool name, then make one bounded direct attempt using the discovered path on the next tool step. In Codex code mode, for example, call \`tools.mcp__t3_code__orchestrator_capabilities({})\` before reporting that the capability is absent. Keep polling/wait loops bounded, do not duplicate active work, and use stable \`clientRequestId\` values when retrying tools that accept them.
3333
3434
ACP fallback: some ACP agents accept the injected MCP server but fail to expose its tools. When the T3 tools are absent and \`T3_ACP_MCP_NODE\` is present, call the same tools through the terminal: \`ELECTRON_RUN_AS_NODE=1 "$T3_ACP_MCP_NODE" \${T3_ACP_MCP_ENTRYPOINT:+"$T3_ACP_MCP_ENTRYPOINT"} acp-mcp-call orchestrator_capabilities '{}'\` (\`T3_ACP_MCP_ENTRYPOINT\` is unset when T3 runs as a standalone executable). Delegate with \`acp-mcp-call delegate_task '{"task":"...","target":{"providerInstanceId":"...","model":"..."},"mode":"async","clientRequestId":"..."}'\`. This is the supported T3 transport fallback, not an ordinary shell-based substitute for delegation.
3535
@@ -118,6 +118,18 @@ export function t3OrchestrationPromptForFirstRun(input: {
118118
: input.prompt;
119119
}
120120

121-
export function t3OrchestrationSystemPrompt(hasT3Mcp: boolean): string | undefined {
122-
return hasT3Mcp ? T3_CODE_ORCHESTRATION_INSTRUCTIONS : undefined;
121+
export function t3OrchestrationSystemPrompt(
122+
hasT3Mcp: boolean,
123+
mcpServerName?: string,
124+
): string | undefined {
125+
if (!hasT3Mcp) return undefined;
126+
// Some harnesses rename the server per session, so the shared instructions
127+
// stay pattern-based and the adapter appends the exact name in use.
128+
const exact =
129+
mcpServerName === undefined || mcpServerName === "t3-code"
130+
? undefined
131+
: `\n\n### This session's tool namespace\n\nThis session's T3 MCP server is registered as \`${mcpServerName}\`. Call its tools as \`tools["${mcpServerName}"].<tool_name>\`, or find them with a namespace-agnostic catalog search, such as \`search({ query: "orchestrator_capabilities" })\`.`;
132+
return exact === undefined
133+
? T3_CODE_ORCHESTRATION_INSTRUCTIONS
134+
: `${T3_CODE_ORCHESTRATION_INSTRUCTIONS}${exact}`;
123135
}
Lines changed: 212 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,212 @@
1+
import { assert, describe, it } from "@effect/vitest";
2+
import * as NodeServices from "@effect/platform-node/NodeServices";
3+
import * as Effect from "effect/Effect";
4+
import * as Layer from "effect/Layer";
5+
import * as Stream from "effect/Stream";
6+
7+
import { EnvironmentId, ProviderInstanceId, ProviderSessionId, ThreadId } from "@t3tools/contracts";
8+
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
9+
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
10+
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
11+
import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
12+
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
13+
import * as orchestrationInstructions from "@t3tools/provider-core/server/orchestrationInstructions";
14+
import { mcpRules, make, t3McpServerName } from "./adapter.ts";
15+
import * as OpenCode2Server from "./OpenCode2Server.ts";
16+
17+
type RecordedCall = { readonly op: string; readonly args: Record<string, unknown> };
18+
19+
const recordingClient = (calls: Array<RecordedCall>) =>
20+
({
21+
mcp: {
22+
add: (input: Record<string, unknown>) =>
23+
Effect.sync(() => {
24+
calls.push({ op: "mcp.add", args: input });
25+
return {};
26+
}),
27+
remove: (input: Record<string, unknown>) =>
28+
Effect.sync(() => {
29+
calls.push({ op: "mcp.remove", args: input });
30+
return {};
31+
}),
32+
},
33+
session: {
34+
create: (input: Record<string, unknown>) =>
35+
Effect.sync(() => {
36+
calls.push({ op: "session.create", args: input });
37+
return { id: "ses_fake" };
38+
}),
39+
form: { list: () => Effect.succeed([]) },
40+
},
41+
model: { list: () => Effect.succeed({ data: [] }) },
42+
agent: { list: () => Effect.succeed({ data: [{ id: "build", permissions: [] }] }) },
43+
permission: { list: () => Effect.succeed([]) },
44+
message: { list: () => Effect.succeed({ data: [] }) },
45+
}) as unknown as OpenCode2Server.OpenCode2Connection["client"];
46+
47+
const makeLayers = (calls: Array<RecordedCall>) => {
48+
const connection = {
49+
client: recordingClient(calls),
50+
events: Effect.succeed(Stream.never),
51+
url: "http://127.0.0.1:4096",
52+
version: "2.1.2",
53+
external: false,
54+
} as unknown as OpenCode2Server.OpenCode2Connection;
55+
return Layer.mergeAll(
56+
Layer.succeed(OpenCode2Server.OpenCode2Server, {
57+
withConnection: <A, E, R>(
58+
use: (connection: OpenCode2Server.OpenCode2Connection) => Effect.Effect<A, E, R>,
59+
) => use(connection),
60+
} as unknown as OpenCode2Server.OpenCode2Server["Service"]),
61+
Layer.succeed(ProviderHost.ProviderHost, {
62+
paths: { cwd: "/workspace" },
63+
resolveAttachmentPath: () => null,
64+
} as unknown as ProviderHost.ProviderHost["Service"]),
65+
IdAllocator.layer,
66+
McpProviderSessions.layer,
67+
ProviderContinuationRequests.layer,
68+
).pipe(Layer.provideMerge(NodeServices.layer));
69+
};
70+
71+
const mcpConfig = (threadId: ThreadId) => ({
72+
environmentId: EnvironmentId.make("environment-test"),
73+
threadId,
74+
providerSessionId: ProviderSessionId.make("provider-session-test"),
75+
providerInstanceId: ProviderInstanceId.make("opencode-test"),
76+
endpoint: "http://127.0.0.1:4096/mcp",
77+
authorizationHeader: "Bearer test-token",
78+
browserToolsAvailable: false,
79+
capabilities: new Set(["orchestration", "worktree", "pull-requests"]),
80+
});
81+
82+
const runtimePolicy = () =>
83+
ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
84+
runtimeMode: "full-access",
85+
interactionMode: "default",
86+
cwd: "/workspace",
87+
});
88+
89+
const openFor = (adapter: ProviderAdapter.ProviderAdapterV2["Service"], threadId: ThreadId) =>
90+
adapter.openSession({
91+
threadId,
92+
providerSessionId: ProviderSessionId.make(`provider-session-${threadId}`),
93+
modelSelection: {
94+
instanceId: ProviderInstanceId.make("opencode-test"),
95+
model: "anthropic/claude-sonnet",
96+
options: [],
97+
},
98+
runtimePolicy: runtimePolicy(),
99+
});
100+
101+
it.effect(
102+
"registers the thread's T3 MCP server when the session opens, before any OpenCode session exists",
103+
() => {
104+
const calls: Array<RecordedCall> = [];
105+
return Effect.gen(function* () {
106+
const threadId = ThreadId.make("thread-490f020d");
107+
const adapter = yield* make(ProviderInstanceId.make("opencode-test"));
108+
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
109+
yield* mcpSessions.set(mcpConfig(threadId));
110+
111+
yield* openFor(adapter, threadId);
112+
113+
const adds = calls.filter((call) => call.op === "mcp.add");
114+
assert.strictEqual(adds.length, 1);
115+
assert.strictEqual(adds[0]!.args.server, `t3-code-${threadId}`);
116+
// OpenCode builds a session's tool catalog at session creation, so the
117+
// server must already be in place when the first `session.create` runs.
118+
assert.strictEqual(calls.filter((call) => call.op === "session.create").length, 0);
119+
}).pipe(Effect.provide(makeLayers(calls)));
120+
},
121+
);
122+
123+
it.effect(
124+
"two concurrent threads register distinct servers and keep only their own routing rules",
125+
() => {
126+
const calls: Array<RecordedCall> = [];
127+
return Effect.gen(function* () {
128+
const threadA = ThreadId.make("thread-aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa");
129+
const threadB = ThreadId.make("thread-bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb");
130+
const adapter = yield* make(ProviderInstanceId.make("opencode-test"));
131+
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
132+
yield* mcpSessions.set(mcpConfig(threadA));
133+
yield* mcpSessions.set(mcpConfig(threadB));
134+
135+
yield* openFor(adapter, threadA);
136+
yield* openFor(adapter, threadB);
137+
138+
const names = calls
139+
.filter((call) => call.op === "mcp.add")
140+
.map((call) => call.args.server as string);
141+
const nameA = `t3-code-${threadA}`;
142+
const nameB = `t3-code-${threadB}`;
143+
assert.deepStrictEqual([...names].sort(), [nameA, nameB].sort());
144+
assert.notStrictEqual(nameA, nameB);
145+
146+
// Each thread's rules deny every T3 server and re-allow only its own,
147+
// so one thread's agent can never route into another thread's tools.
148+
for (const [own, other] of [
149+
[nameA, nameB],
150+
[nameB, nameA],
151+
] as const) {
152+
const rules = mcpRules(own);
153+
assert.deepStrictEqual(rules, [
154+
{ action: "t3-code-*", resource: "*", effect: "deny" },
155+
{ action: `${own}_*`, resource: "*", effect: "allow" },
156+
]);
157+
const otherPrefix = other.slice(0, other.lastIndexOf("-") + 1);
158+
assert.isFalse(
159+
rules.some((entry) => entry.effect === "allow" && otherPrefix.startsWith(entry.action)),
160+
);
161+
}
162+
}).pipe(Effect.provide(makeLayers(calls)));
163+
},
164+
);
165+
166+
it.layer(NodeServices.layer)("OpenCode2Adapter MCP server names", (it) => {
167+
it.effect("replaces a thread id that exceeds OpenCode's namespace limit with a digest", () =>
168+
Effect.gen(function* () {
169+
const longA = `thread-${"a".repeat(80)}`;
170+
const longB = `thread-${"b".repeat(80)}`;
171+
const nameA = yield* t3McpServerName(longA);
172+
const nameB = yield* t3McpServerName(longB);
173+
assert.isTrue(nameA.length <= 64);
174+
assert.isTrue(nameB.length <= 64);
175+
assert.isTrue(nameA.startsWith("t3-code-"));
176+
assert.notStrictEqual(nameA, nameB);
177+
// A short id keeps its readable, sanitized form.
178+
const short = yield* t3McpServerName("thread_490f020d");
179+
assert.strictEqual(short, "t3-code-thread_490f020d");
180+
}),
181+
);
182+
});
183+
184+
describe("T3 orchestration instructions", () => {
185+
it("names the session's registered namespace when the server is thread-suffixed", () => {
186+
const prompt = orchestrationInstructions.t3OrchestrationSystemPrompt(true, "t3-code-490f020d");
187+
assert.isString(prompt);
188+
assert.include(prompt!, 'tools["t3-code-490f020d"].');
189+
assert.include(prompt!, 'search({ query: "orchestrator_capabilities" })');
190+
});
191+
192+
it("keeps the shared instructions unchanged when the server has its plain name", () => {
193+
const base = orchestrationInstructions.t3OrchestrationSystemPrompt(true);
194+
assert.strictEqual(base, orchestrationInstructions.T3_CODE_ORCHESTRATION_INSTRUCTIONS);
195+
assert.strictEqual(
196+
orchestrationInstructions.t3OrchestrationSystemPrompt(true, "t3-code"),
197+
base,
198+
);
199+
assert.strictEqual(orchestrationInstructions.t3OrchestrationSystemPrompt(false), undefined);
200+
});
201+
202+
it("documents the thread-suffixed OpenCode pattern for discovery", () => {
203+
assert.include(
204+
orchestrationInstructions.T3_CODE_ORCHESTRATION_INSTRUCTIONS,
205+
"t3-code-<threadId>",
206+
);
207+
assert.include(
208+
orchestrationInstructions.T3_CODE_ORCHESTRATION_INSTRUCTIONS,
209+
'tools["t3-code-..."]',
210+
);
211+
});
212+
});

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

Lines changed: 60 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -377,7 +377,7 @@ export const t3McpServerName = Effect.fn("t3McpServerName")(function* (threadId:
377377
* the last matching rule wins, so every thread's T3 server is denied and then
378378
* this thread's own is allowed again, in every mode.
379379
*/
380-
const mcpRules = (mcpServerName: string | null): ReadonlyArray<Rule> =>
380+
export const mcpRules = (mcpServerName: string | null): ReadonlyArray<Rule> =>
381381
mcpServerName === null
382382
? []
383383
: [
@@ -3080,9 +3080,56 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
30803080
client.mcp.remove({ server: mcp.name, location: { directory: mcp.directory } }),
30813081
).pipe(Effect.timeout("5 seconds"), Effect.ignore({ log: true }));
30823082

3083+
/**
3084+
* Servers this session registered before their thread's first turn, when no
3085+
* ThreadState exists to hold them. OpenCode builds a session's tool catalog
3086+
* when the session is created, so a server only added in `prepareTurn`
3087+
* misses the first request; registering here, before any `session.create`,
3088+
* keeps the first turn's catalog complete. Prepared per thread by the
3089+
* session manager before `openSession`, so the config is normally ready.
3090+
*/
3091+
const registeredMcp = new Map<
3092+
string,
3093+
{ readonly name: string; readonly directory: string; readonly credential: string }
3094+
>();
3095+
const mcpSession = yield* mcpSessions.read(input.threadId);
3096+
if (mcpSession !== undefined && !connection.external) {
3097+
const name = yield* mcpServerNameFor(input.threadId);
3098+
const added = yield* client.mcp
3099+
.add({
3100+
server: name,
3101+
location: { directory: host.paths.cwd },
3102+
config: new Mcp.RemoteConfig({
3103+
type: "remote",
3104+
url: mcpSession.endpoint,
3105+
headers: { Authorization: mcpSession.authorizationHeader },
3106+
oauth: false,
3107+
}),
3108+
})
3109+
.pipe(
3110+
Effect.timeout(INVENTORY_TIMEOUT),
3111+
Effect.as(true),
3112+
Effect.catchCause((cause) =>
3113+
Effect.logWarning("Could not add T3 Code's MCP server to OpenCode.", cause).pipe(
3114+
Effect.as(false),
3115+
),
3116+
),
3117+
);
3118+
if (added) {
3119+
registeredMcp.set(input.threadId, {
3120+
name,
3121+
directory: host.paths.cwd,
3122+
credential: mcpSession.authorizationHeader,
3123+
});
3124+
}
3125+
}
3126+
30833127
yield* Effect.addFinalizer(() =>
30843128
Effect.forEach(
3085-
[...threads.values()].flatMap((state) => (state.mcp === undefined ? [] : [state.mcp])),
3129+
[
3130+
...[...threads.values()].flatMap((state) => (state.mcp === undefined ? [] : [state.mcp])),
3131+
...registeredMcp.values(),
3132+
],
30863133
removeMcp,
30873134
{ concurrency: 8, discard: true },
30883135
),
@@ -3101,15 +3148,20 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
31013148
mcpSession === undefined || connection.external
31023149
? undefined
31033150
: { name, directory, credential: mcpSession.authorizationHeader };
3151+
// A server registered before the thread's first turn lives in
3152+
// `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.
3154+
const known = state.mcp ?? registeredMcp.get(turnInput.threadId);
31043155
if (
3105-
state.mcp !== undefined &&
3156+
known !== undefined &&
31063157
(wanted === undefined ||
3107-
state.mcp.directory !== wanted.directory ||
3108-
state.mcp.credential !== wanted.credential)
3158+
known.directory !== wanted.directory ||
3159+
known.credential !== wanted.credential)
31093160
) {
3110-
yield* removeMcp(state.mcp);
3111-
state.mcp = undefined;
3161+
yield* removeMcp(known);
3162+
if (state.mcp === known) state.mcp = undefined;
31123163
}
3164+
registeredMcp.delete(turnInput.threadId);
31133165
// Idle Location eviction drops runtime MCP servers without clearing T3's cache.
31143166
// Re-adding an unchanged config keeps its existing connection.
31153167
let mcpAvailable = false;
@@ -3138,7 +3190,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
31383190
}
31393191
const instructions = [
31403192
buildRuntimeInstructions({ harness: "OpenCode", model: turnInput.modelSelection.model }),
3141-
t3OrchestrationSystemPrompt(mcpAvailable),
3193+
t3OrchestrationSystemPrompt(mcpAvailable, wanted?.name),
31423194
]
31433195
.filter((part) => part !== undefined && part.length > 0)
31443196
.join("\n\n");

0 commit comments

Comments
 (0)