The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 22:15 UTC
fix(server): Copilot threads load optional T3 tools on demand (#34245)
Julius Marminge committed
Nov 11, 2026 at 11:58 UTC
cdd1c6a2af4e48811f8549caea17e73dedda30bf
9 files changed
+324
-5
apps/server/src/mcp/McpHttpServer.test.ts
+126
@@ -1603,3 +1603,129 @@ it.effect(
1603
}),
1604
).pipe(Effect.provide(NodeHttpServer.layerTest)),
1605
);
1606
+
1607
+it.effect("lists optional tools to a deferring client only after tool_search loads them", () =>
1608
+ Effect.scoped(
1609
+ Effect.gen(function* () {
1610
+ const scopeFor = (token: string): McpInvocationContext.McpThreadInvocationScope => ({
1611
+ environmentId,
1612
+ requestNamespace: token,
1613
+ thread: {
1614
+ threadId: ThreadId.make(`thread-${token}`),
1615
+ providerSessionId: token,
1616
+ providerInstanceId: ProviderInstanceId.make("copilot"),
1617
+ },
1618
+ client: undefined,
1619
+ capabilities: new Set(["orchestration"]),
1620
+ issuedAt: 1,
1621
+ });
1622
+ const scopes = new Map([
1623
+ ["deferringToken", scopeFor("deferringToken")],
1624
+ ["otherToken", scopeFor("otherToken")],
1625
+ ]);
1626
+ const tool = (name: string, description: string) =>
1627
+ Tool.make(name, {
1628
+ description,
1629
+ success: Schema.Struct({}),
1630
+ failure: OrchestratorMcpFailure,
1631
+ failureMode: "return",
1632
+ });
1633
+ const OptionalToolkit = Toolkit.make(
1634
+ tool("delegate_task", "Delegates a task."),
1635
+ tool("preview_open", "Opens a browser preview."),
1636
+ tool("schedule_task", "Schedules a task."),
1637
+ );
1638
+ const reads = McpToolAccess.reads(() => Effect.succeed({}));
1639
+ const serverLayer = McpHttpServer.layerMcpTransport(
1640
+ Layer.mergeAll(
1641
+ McpHttpServer.toolkitRegistration(
1642
+ OptionalToolkit,
1643
+ McpToolAccess.toLayer(OptionalToolkit, {
1644
+ delegate_task: reads,
1645
+ preview_open: reads,
1646
+ schedule_task: reads,
1647
+ }),
1648
+ ),
1649
+ McpHttpServer.layerToolSearch,
1650
+ ),
1651
+ ).pipe(
1652
+ Layer.provide(ServerSettings.layerTest()),
1653
+ Layer.provide(McpToolAccessTestkit.liveThreadsLayer),
1654
+ Layer.provide(
1655
+ Layer.mock(McpSessionRegistry.McpSessionRegistry)({
1656
+ resolve: (token) => Effect.succeed(scopes.get(token)),
1657
+ }),
1658
+ ),
1659
+ );
1660
+ yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe(
1661
+ Layer.build,
1662
+ );
1663
+ const httpClient = yield* HttpClient.HttpClient;
1664
+ const session = (token: string, deferred: boolean) =>
1665
+ Effect.gen(function* () {
1666
+ const headers = {
1667
+ accept: "application/json, text/event-stream",
1668
+ authorization: `Bearer ${token}`,
1669
+ ...(deferred ? { "t3-tool-exposure": "deferred" } : {}),
1670
+ };
1671
+ const initialize = yield* httpClient.post("/mcp", {
1672
+ headers,
1673
+ body: HttpBody.text(
1674
+ `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
1675
+ "application/json",
1676
+ ),
1677
+ });
1678
+ const rpc = (method: string, params: object) =>
1679
+ httpClient
1680
+ .post("/mcp", {
1681
+ headers: {
1682
+ ...headers,
1683
+ "mcp-session-id": initialize.headers["mcp-session-id"]!,
1684
+ "mcp-protocol-version": "2025-06-18",
1685
+ },
1686
+ body: HttpBody.text(
1687
+ JSON.stringify({ jsonrpc: "2.0", id: 2, method, params }),
1688
+ "application/json",
1689
+ ),
1690
+ })
1691
+ .pipe(
1692
+ Effect.flatMap((response) => response.text),
1693
+ // tool_search answers over SSE, after its list_changed notification.
1694
+ Effect.map((text): unknown =>
1695
+ text
1696
+ .split("\n")
1697
+ .filter((line) => line.startsWith("data: ") || line.startsWith("{"))
1698
+ .map((line) => JSON.parse(line.replace(/^data: /u, "")) as { id?: number })
1699
+ .find((message) => message.id === 2),
1700
+ ),
1701
+ );
1702
+ return {
1703
+ listed: rpc("tools/list", {}).pipe(
1704
+ Effect.map((body) =>
1705
+ (body as { result: { tools: ReadonlyArray<{ name: string }> } }).result.tools
1706
+ .map((listed) => listed.name)
1707
+ .sort(),
1708
+ ),
1709
+ ),
1710
+ call: (name: string, args: object) =>
1711
+ rpc("tools/call", { name, arguments: args }).pipe(
1712
+ Effect.map((body) => (body as { result: { structuredContent?: unknown } }).result),
1713
+ ),
1714
+ };
1715
+ });
1716
+
1717
+ const deferring = yield* session("deferringToken", true);
1718
+ const other = yield* session("otherToken", false);
1719
+ expect(yield* deferring.listed).toEqual(["delegate_task", "tool_search"]);
1720
+ expect(yield* other.listed).toEqual(["delegate_task", "preview_open", "schedule_task"]);
1721
+ // Unlisted tools stay callable.
1722
+ expect((yield* deferring.call("schedule_task", {})).structuredContent).toEqual({});
1723
+
1724
+ expect(
1725
+ (yield* deferring.call("tool_search", { query: "browser" })).structuredContent,
1726
+ ).toEqual({ tools: [{ name: "preview_open", description: "Opens a browser preview." }] });
1727
+ expect(yield* deferring.listed).toEqual(["delegate_task", "preview_open", "tool_search"]);
1728
+ expect(yield* other.listed).toEqual(["delegate_task", "preview_open", "schedule_task"]);
1729
+ }),
1730
+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),
1731
+);
apps/server/src/mcp/McpHttpServer.ts
+45
-1
@@ -44,6 +44,8 @@ import {
44
import { advertisedJsonSchema } from "./advertisedJsonSchema.ts";
45
import * as McpInvocationContext from "./McpInvocationContext.ts";
46
import * as McpToolAccess from "./McpToolAccess.ts";
47
+import * as McpToolExposure from "./McpToolExposure.ts";
48
+import { MCP_TOOL_EXPOSURE_HEADER } from "@t3tools/provider-core/server/mcpSession";
49
import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";
50
import { PreviewControlsToolkit } from "./toolkits/previewControls/tools.ts";
51
import * as PreviewControlsHandlers from "./toolkits/previewControls/handlers.ts";
@@ -70,6 +72,8 @@ import * as WorktreeHandlers from "./toolkits/worktree/handlers.ts";
72
import { WorktreeToolkit } from "./toolkits/worktree/tools.ts";
73
import * as WorktreeMcpService from "./WorktreeMcpService.ts";
74
import * as PullRequestsHandlers from "./toolkits/pullRequests/handlers.ts";
75
+import * as ToolSearchHandlers from "./toolkits/toolSearch/handlers.ts";
76
+import { ToolSearchToolkit } from "./toolkits/toolSearch/tools.ts";
77
import { PullRequestsToolkit } from "./toolkits/pullRequests/tools.ts";
78
import * as DeviceHandlers from "./toolkits/device/handlers.ts";
79
import {
@@ -1294,4 +1298,44 @@ export const layerTools = Layer.mergeAll(
1298
layerHtmlToolkit,
1299
);
1300
1297
-export const layer = layerMcpTransport(layerTools);
1301
+const layerToolExposure = Layer.effect(
1302
+ McpToolExposure.McpToolExposure,
1303
+ Effect.gen(function* () {
1304
+ const server = yield* McpServer.McpServer;
1305
+ return McpToolExposure.make(
1306
+ () =>
1307
+ server.tools.map(({ tool }) => ({ name: tool.name, description: tool.description ?? "" })),
1308
+ () => server.notifications["notifications/tools/list_changed"]({}),
1309
+ );
1310
+ }),
1311
+);
1312
+
1313
+/**
1314
+ * A provider session that sends `MCP_TOOL_EXPOSURE_HEADER: deferred` lists only
1315
+ * the direct tools and what its `tool_search` calls loaded. Calls are never
1316
+ * gated, and every other client lists everything but `tool_search`.
1317
+ */
1318
+const layerDeferredListing = McpServer.visibility(
1319
+ Effect.gen(function* () {
1320
+ const exposure = yield* McpToolExposure.McpToolExposure;
1321
+ // Untraced: it runs once per tool on every list request.
1322
+ return Effect.fnUntraced(function* ({ method, target, headers }: McpServer.MiddlewareOptions) {
1323
+ if (method !== "tools/list") return true;
1324
+ const scope = yield* Effect.serviceOption(McpInvocationContext.McpInvocationContext);
1325
+ const providerSessionId = Option.getOrUndefined(scope)?.thread?.providerSessionId;
1326
+ if (headers[MCP_TOOL_EXPOSURE_HEADER] !== "deferred" || providerSessionId === undefined) {
1327
+ return target !== McpToolExposure.TOOL_SEARCH;
1328
+ }
1329
+ return exposure.isListed(providerSessionId, target);
1330
+ });
1331
+ }),
1332
+ { global: true },
1333
+);
1334
+
1335
+/** Outside layerTools: the clients its budget measures never list `tool_search`. */
1336
+export const layerToolSearch = Layer.mergeAll(
1337
+ toolkitRegistration(ToolSearchToolkit, ToolSearchHandlers.layer),
1338
+ layerDeferredListing,
1339
+).pipe(Layer.provide(layerToolExposure));
1340
+
1341
+export const layer = layerMcpTransport(Layer.mergeAll(layerTools, layerToolSearch));
apps/server/src/mcp/McpToolExposure.ts
new
+87
@@ -0,0 +1,87 @@
1
+import * as Context from "effect/Context";
2
+import * as Effect from "effect/Effect";
3
+
4
+export const TOOL_SEARCH = "tool_search";
5
+
6
+/** What a deferring client lists before it searches. Pi's extension declares the same three. */
7
+const DIRECT_TOOLS: ReadonlySet<string> = new Set([
8
+ "orchestrator_capabilities",
9
+ "delegate_task",
10
+ "task_status",
11
+ TOOL_SEARCH,
12
+]);
13
+
14
+const MAX_RESULTS = 10;
15
+// Sessions that ended are never reported here, so keep only the newest.
16
+const MAX_SESSIONS = 256;
17
+
18
+export interface ListedTool {
19
+ readonly name: string;
20
+ readonly description: string;
21
+}
22
+
23
+export class McpToolExposure extends Context.Service<
24
+ McpToolExposure,
25
+ {
26
+ /** Finds tools for the query and lists them to the session from now on. */
27
+ readonly search: (
28
+ providerSessionId: string,
29
+ query: string,
30
+ ) => Effect.Effect<ReadonlyArray<ListedTool>>;
31
+ readonly isListed: (providerSessionId: string, tool: string) => boolean;
32
+ }
33
+>()("t3/mcp/McpToolExposure") {}
34
+
35
+const score = (tool: ListedTool, terms: ReadonlyArray<string>) => {
36
+ const name = tool.name.toLowerCase();
37
+ const description = tool.description.toLowerCase();
38
+ let total = 0;
39
+ for (const term of terms) {
40
+ if (term === name) total += 100;
41
+ else if (name.includes(term)) total += 3;
42
+ else if (description.includes(term)) total += 1;
43
+ }
44
+ return total;
45
+};
46
+
47
+export const make = (
48
+ tools: () => ReadonlyArray<ListedTool>,
49
+ announceListChanged: () => Effect.Effect<void>,
50
+) => {
51
+ const loaded = new Map<string, Set<string>>();
52
+ const load = (providerSessionId: string, names: ReadonlyArray<string>) => {
53
+ const listed = loaded.get(providerSessionId) ?? new Set<string>();
54
+ loaded.delete(providerSessionId);
55
+ loaded.set(providerSessionId, listed);
56
+ for (const name of names) listed.add(name);
57
+ for (const oldest of loaded.keys()) {
58
+ if (loaded.size <= MAX_SESSIONS) break;
59
+ loaded.delete(oldest);
60
+ }
61
+ };
62
+ return McpToolExposure.of({
63
+ search: Effect.fn("McpToolExposure.search")(function* (providerSessionId, query) {
64
+ const terms = query
65
+ .toLowerCase()
66
+ .split(/[^a-z0-9_]+/u)
67
+ .filter(Boolean);
68
+ const found = tools()
69
+ .filter((tool) => tool.name !== TOOL_SEARCH)
70
+ .map((tool) => ({ tool, score: score(tool, terms) }))
71
+ .filter((match) => match.score > 0)
72
+ .sort((a, b) => b.score - a.score)
73
+ .slice(0, MAX_RESULTS)
74
+ .map((match) => match.tool);
75
+ if (found.length > 0) {
76
+ load(
77
+ providerSessionId,
78
+ found.map((tool) => tool.name),
79
+ );
80
+ yield* announceListChanged();
81
+ }
82
+ return found;
83
+ }),
84
+ isListed: (providerSessionId, tool) =>
85
+ DIRECT_TOOLS.has(tool) || loaded.get(providerSessionId)?.has(tool) === true,
86
+ });
87
+};
apps/server/src/mcp/toolkits/toolSearch/handlers.ts
new
+18
@@ -0,0 +1,18 @@
1
+import * as Effect from "effect/Effect";
2
+
3
+import * as McpInvocationContext from "../../McpInvocationContext.ts";
4
+import * as McpToolAccess from "../../McpToolAccess.ts";
5
+import * as McpToolExposure from "../../McpToolExposure.ts";
6
+import { ToolSearchToolkit } from "./tools.ts";
7
+
8
+export const layer = McpToolAccess.toLayer(ToolSearchToolkit, {
9
+ tool_search: McpToolAccess.readsAsCaller(({ query }) =>
10
+ Effect.gen(function* () {
11
+ const { thread } = yield* McpInvocationContext.McpInvocationContext.pipe(
12
+ Effect.flatMap((scope) => McpInvocationContext.requireThreadScope(scope, "tool_search")),
13
+ );
14
+ const exposure = yield* McpToolExposure.McpToolExposure;
15
+ return { tools: yield* exposure.search(thread.providerSessionId, query) };
16
+ }),
17
+ ),
18
+});
apps/server/src/mcp/toolkits/toolSearch/tools.ts
new
+22
@@ -0,0 +1,22 @@
1
+import { OrchestratorMcpFailure } from "@t3tools/contracts";
2
+import * as Schema from "effect/Schema";
3
+import { Tool, Toolkit } from "effect/ai";
4
+
5
+import * as McpInvocationContext from "../../McpInvocationContext.ts";
6
+import * as McpToolExposure from "../../McpToolExposure.ts";
7
+
8
+const ToolSearchTool = Tool.make(McpToolExposure.TOOL_SEARCH, {
9
+ description:
10
+ "Load T3 Code tools you do not have yet, then call them by name. Search by name or purpose: threads (t3_thread_*), projects (t3_project_*), worktrees, preview_* browser, device_*, html_preview/html_render, schedule_task, pull requests and guides, attachments, request_secret, environment links. Exact names work too.",
11
+ parameters: Schema.Struct({ query: Schema.String.check(Schema.isMaxLength(500)) }),
12
+ success: Schema.Struct({
13
+ tools: Schema.Array(Schema.Struct({ name: Schema.String, description: Schema.String })),
14
+ }),
15
+ failure: OrchestratorMcpFailure,
16
+ failureMode: "return",
17
+ dependencies: [McpInvocationContext.McpInvocationContext, McpToolExposure.McpToolExposure],
18
+})
19
+ .annotate(Tool.Readonly, true)
20
+ .annotate(Tool.Destructive, false);
21
+
22
+export const ToolSearchToolkit = Toolkit.make(ToolSearchTool);
apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts
+4
-1
@@ -1210,7 +1210,10 @@ describe("AcpRegistryAdapterV2", () => {
1210
type: "http",
1211
name: "t3-code",
1212
url: endpoint,
1213
- headers: [{ name: "Authorization", value: authorization }],
1213
+ headers: [
1214
+ { name: "Authorization", value: authorization },
1215
+ { name: "t3-tool-exposure", value: "deferred" },
1216
+ ],
1217
},
1218
];
1219
const stdio = (authorization: string) => [
packages/provider-acp-registry/src/server/adapter.ts
+1
@@ -253,6 +253,7 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu
253
clientCapabilitiesMeta: copilotClientCapabilitiesMeta,
254
// Copilot CLI 1.0.105 rejects stdio MCP servers from the client.
255
mcpOverHttp: true,
256
+ deferMcpTools: true,
257
registerExtensions: copilotRouting.registerExtensions,
258
normalizeSessionUpdate: copilotRouting.normalizeSessionUpdate,
259
extractSubagentUpdate: extractCopilotSubagentUpdate,
packages/provider-acp/src/server/adapter.ts
+15
-3
@@ -333,6 +333,8 @@ export interface AcpAdapterV2Flavor {
333
EffectAcpSchema.InitializeRequest["clientCapabilities"]
334
>["_meta"];
335
readonly mcpOverHttp?: boolean;
336
+ /** The agent has no tool search of its own, so T3 lists optional tools on demand. */
337
+ readonly deferMcpTools?: boolean;
338
readonly normalizeSessionUpdate?: (
339
notification: EffectAcpSchema.SessionNotification,
340
) => EffectAcpSchema.SessionNotification;
@@ -838,6 +840,7 @@ function acpMcpContext(
840
session: McpProviderSession.McpProviderSessionConfig | undefined,
841
self: SelfInvocation,
842
mcpOverHttp: boolean | undefined,
843
+ deferMcpTools: boolean | undefined,
844
): AcpMcpContext {
845
if (session === undefined) {
846
return { servers: [], acpServers: [], httpServers: [] };
@@ -864,7 +867,12 @@ function acpMcpContext(
867
type: "http",
868
name: "t3-code",
869
url: session.endpoint,
867
- headers: [{ name: "Authorization", value: session.authorizationHeader }],
870
+ headers: [
871
+ { name: "Authorization", value: session.authorizationHeader },
872
+ ...(deferMcpTools === true
873
+ ? [{ name: McpProviderSession.MCP_TOOL_EXPOSURE_HEADER, value: "deferred" }]
874
+ : []),
875
+ ],
876
},
877
]
878
: [],
@@ -1698,10 +1706,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
1706
const { flavor, selfInvocation: self } = options;
1707
const readMcpContext = (threadId: ThreadId | null) =>
1708
threadId === null
1701
- ? Effect.succeed(acpMcpContext(undefined, self, flavor.mcpOverHttp))
1709
+ ? Effect.succeed(acpMcpContext(undefined, self, flavor.mcpOverHttp, flavor.deferMcpTools))
1710
: mcpSessions
1711
.read(threadId)
1704
- .pipe(Effect.map((session) => acpMcpContext(session, self, flavor.mcpOverHttp)));
1712
+ .pipe(
1713
+ Effect.map((session) =>
1714
+ acpMcpContext(session, self, flavor.mcpOverHttp, flavor.deferMcpTools),
1715
+ ),
1716
+ );
1717
const driver = flavor.driver;
1718
const continuationRequests = options.continuationRequests;
1719
const postSettleContinuationEnabled =
packages/provider-core/src/server/mcpSession.ts
+6
@@ -1,5 +1,11 @@
1
import type { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
2
3
+/**
4
+ * Sent by MCP clients that cannot defer tools themselves. The T3 MCP server then
5
+ * lists only a core set plus `tool_search`, which lists the rest on demand.
6
+ */
7
+export const MCP_TOOL_EXPOSURE_HEADER = "t3-tool-exposure";
8
+
9
export interface McpProviderSessionConfig {
10
readonly environmentId: EnvironmentId;
11
readonly threadId: ThreadId;