GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(server): Copilot threads load optional T3 tools on demand (#34245) · Pipyakas/t3code@144f305

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • apps/server/src
    • mcp
      • McpHttpServer.test.ts
      • McpHttpServer.ts
      • McpToolExposure.ts
      • toolkits/toolSearch
        • handlers.ts
        • tools.ts
    • orchestration-v2/Adapters
      • AcpRegistryAdapterV2.test.ts
  • packages
    • provider-acp-registry/src/server
      • adapter.ts
    • provider-acp/src/server
      • adapter.ts
    • provider-core/src/server
      • mcpSession.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

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

Copy file name to clipboardExpand all lines: apps/server/src/mcp/McpHttpServer.test.ts
+126Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1861,3 +1861,129 @@ it.effect(
18611861
}),
18621862
).pipe(Effect.provide(NodeHttpServer.layerTest)),
18631863
);
1864+
1865+
it.effect("lists optional tools to a deferring client only after tool_search loads them", () =>
1866+
Effect.scoped(
1867+
Effect.gen(function* () {
1868+
const scopeFor = (token: string): McpInvocationContext.McpThreadInvocationScope => ({
1869+
environmentId,
1870+
requestNamespace: token,
1871+
thread: {
1872+
threadId: ThreadId.make(`thread-${token}`),
1873+
providerSessionId: token,
1874+
providerInstanceId: ProviderInstanceId.make("copilot"),
1875+
},
1876+
client: undefined,
1877+
capabilities: new Set(["orchestration"]),
1878+
issuedAt: 1,
1879+
});
1880+
const scopes = new Map([
1881+
["deferringToken", scopeFor("deferringToken")],
1882+
["otherToken", scopeFor("otherToken")],
1883+
]);
1884+
const tool = (name: string, description: string) =>
1885+
Tool.make(name, {
1886+
description,
1887+
success: Schema.Struct({}),
1888+
failure: OrchestratorMcpFailure,
1889+
failureMode: "return",
1890+
});
1891+
const OptionalToolkit = Toolkit.make(
1892+
tool("delegate_task", "Delegates a task."),
1893+
tool("preview_open", "Opens a browser preview."),
1894+
tool("schedule_task", "Schedules a task."),
1895+
);
1896+
const reads = McpToolAccess.reads(() => Effect.succeed({}));
1897+
const serverLayer = McpHttpServer.layerMcpTransport(
1898+
Layer.mergeAll(
1899+
McpHttpServer.toolkitRegistration(
1900+
OptionalToolkit,
1901+
McpToolAccess.toLayer(OptionalToolkit, {
1902+
delegate_task: reads,
1903+
preview_open: reads,
1904+
schedule_task: reads,
1905+
}),
1906+
),
1907+
McpHttpServer.layerToolSearch,
1908+
),
1909+
).pipe(
1910+
Layer.provide(ServerSettings.layerTest()),
1911+
Layer.provide(McpToolAccessTestkit.liveThreadsLayer),
1912+
Layer.provide(
1913+
Layer.mock(McpSessionRegistry.McpSessionRegistry)({
1914+
resolve: (token) => Effect.succeed(scopes.get(token)),
1915+
}),
1916+
),
1917+
);
1918+
yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe(
1919+
Layer.build,
1920+
);
1921+
const httpClient = yield* HttpClient.HttpClient;
1922+
const session = (token: string, deferred: boolean) =>
1923+
Effect.gen(function* () {
1924+
const headers = {
1925+
accept: "application/json, text/event-stream",
1926+
authorization: `Bearer ${token}`,
1927+
...(deferred ? { "t3-tool-exposure": "deferred" } : {}),
1928+
};
1929+
const initialize = yield* httpClient.post("/mcp", {
1930+
headers,
1931+
body: HttpBody.text(
1932+
`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
1933+
"application/json",
1934+
),
1935+
});
1936+
const rpc = (method: string, params: object) =>
1937+
httpClient
1938+
.post("/mcp", {
1939+
headers: {
1940+
...headers,
1941+
"mcp-session-id": initialize.headers["mcp-session-id"]!,
1942+
"mcp-protocol-version": "2025-06-18",
1943+
},
1944+
body: HttpBody.text(
1945+
JSON.stringify({ jsonrpc: "2.0", id: 2, method, params }),
1946+
"application/json",
1947+
),
1948+
})
1949+
.pipe(
1950+
Effect.flatMap((response) => response.text),
1951+
// tool_search answers over SSE, after its list_changed notification.
1952+
Effect.map((text): unknown =>
1953+
text
1954+
.split("\n")
1955+
.filter((line) => line.startsWith("data: ") || line.startsWith("{"))
1956+
.map((line) => JSON.parse(line.replace(/^data: /u, "")) as { id?: number })
1957+
.find((message) => message.id === 2),
1958+
),
1959+
);
1960+
return {
1961+
listed: rpc("tools/list", {}).pipe(
1962+
Effect.map((body) =>
1963+
(body as { result: { tools: ReadonlyArray<{ name: string }> } }).result.tools
1964+
.map((listed) => listed.name)
1965+
.sort(),
1966+
),
1967+
),
1968+
call: (name: string, args: object) =>
1969+
rpc("tools/call", { name, arguments: args }).pipe(
1970+
Effect.map((body) => (body as { result: { structuredContent?: unknown } }).result),
1971+
),
1972+
};
1973+
});
1974+
1975+
const deferring = yield* session("deferringToken", true);
1976+
const other = yield* session("otherToken", false);
1977+
expect(yield* deferring.listed).toEqual(["delegate_task", "tool_search"]);
1978+
expect(yield* other.listed).toEqual(["delegate_task", "preview_open", "schedule_task"]);
1979+
// Unlisted tools stay callable.
1980+
expect((yield* deferring.call("schedule_task", {})).structuredContent).toEqual({});
1981+
1982+
expect(
1983+
(yield* deferring.call("tool_search", { query: "browser" })).structuredContent,
1984+
).toEqual({ tools: [{ name: "preview_open", description: "Opens a browser preview." }] });
1985+
expect(yield* deferring.listed).toEqual(["delegate_task", "preview_open", "tool_search"]);
1986+
expect(yield* other.listed).toEqual(["delegate_task", "preview_open", "schedule_task"]);
1987+
}),
1988+
).pipe(Effect.provide(NodeHttpServer.layerTest)),
1989+
);
Collapse file

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

Copy file name to clipboardExpand all lines: apps/server/src/mcp/McpHttpServer.ts
+45-1Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,8 @@ import {
4545
import { advertisedJsonSchema } from "./advertisedJsonSchema.ts";
4646
import * as McpInvocationContext from "./McpInvocationContext.ts";
4747
import * as McpToolAccess from "./McpToolAccess.ts";
48+
import * as McpToolExposure from "./McpToolExposure.ts";
49+
import { MCP_TOOL_EXPOSURE_HEADER } from "@t3tools/provider-core/server/mcpSession";
4850
import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";
4951
import { PreviewControlsToolkit } from "./toolkits/previewControls/tools.ts";
5052
import * as PreviewControlsHandlers from "./toolkits/previewControls/handlers.ts";
@@ -71,6 +73,8 @@ import * as WorktreeHandlers from "./toolkits/worktree/handlers.ts";
7173
import { WorktreeToolkit } from "./toolkits/worktree/tools.ts";
7274
import * as WorktreeMcpService from "./WorktreeMcpService.ts";
7375
import * as PullRequestsHandlers from "./toolkits/pullRequests/handlers.ts";
76+
import * as ToolSearchHandlers from "./toolkits/toolSearch/handlers.ts";
77+
import { ToolSearchToolkit } from "./toolkits/toolSearch/tools.ts";
7478
import { PullRequestsToolkit } from "./toolkits/pullRequests/tools.ts";
7579
import * as DeviceHandlers from "./toolkits/device/handlers.ts";
7680
import {
@@ -1299,4 +1303,44 @@ export const layerTools = Layer.mergeAll(
12991303
layerHtmlToolkit,
13001304
);
13011305

1302-
export const layer = layerMcpTransport(layerTools);
1306+
const layerToolExposure = Layer.effect(
1307+
McpToolExposure.McpToolExposure,
1308+
Effect.gen(function* () {
1309+
const server = yield* McpServer.McpServer;
1310+
return McpToolExposure.make(
1311+
() =>
1312+
server.tools.map(({ tool }) => ({ name: tool.name, description: tool.description ?? "" })),
1313+
() => server.notifications["notifications/tools/list_changed"]({}),
1314+
);
1315+
}),
1316+
);
1317+
1318+
/**
1319+
* A provider session that sends `MCP_TOOL_EXPOSURE_HEADER: deferred` lists only
1320+
* the direct tools and what its `tool_search` calls loaded. Calls are never
1321+
* gated, and every other client lists everything but `tool_search`.
1322+
*/
1323+
const layerDeferredListing = McpServer.visibility(
1324+
Effect.gen(function* () {
1325+
const exposure = yield* McpToolExposure.McpToolExposure;
1326+
// Untraced: it runs once per tool on every list request.
1327+
return Effect.fnUntraced(function* ({ method, target, headers }: McpServer.MiddlewareOptions) {
1328+
if (method !== "tools/list") return true;
1329+
const scope = yield* Effect.serviceOption(McpInvocationContext.McpInvocationContext);
1330+
const providerSessionId = Option.getOrUndefined(scope)?.thread?.providerSessionId;
1331+
if (headers[MCP_TOOL_EXPOSURE_HEADER] !== "deferred" || providerSessionId === undefined) {
1332+
return target !== McpToolExposure.TOOL_SEARCH;
1333+
}
1334+
return exposure.isListed(providerSessionId, target);
1335+
});
1336+
}),
1337+
{ global: true },
1338+
);
1339+
1340+
/** Outside layerTools: the clients its budget measures never list `tool_search`. */
1341+
export const layerToolSearch = Layer.mergeAll(
1342+
toolkitRegistration(ToolSearchToolkit, ToolSearchHandlers.layer),
1343+
layerDeferredListing,
1344+
).pipe(Layer.provide(layerToolExposure));
1345+
1346+
export const layer = layerMcpTransport(Layer.mergeAll(layerTools, layerToolSearch));
Collapse file

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

Copy file name to clipboard
+87Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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+
};
Collapse file

‎apps/server/src/mcp/toolkits/toolSearch/handlers.ts‎

Copy file name to clipboard
+18Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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+
});
Collapse file

‎apps/server/src/mcp/toolkits/toolSearch/tools.ts‎

Copy file name to clipboard
+22Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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);
Collapse file

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

Copy file name to clipboardExpand all lines: apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts
+4-1Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1266,7 +1266,10 @@ describe("AcpRegistryAdapterV2", () => {
12661266
type: "http",
12671267
name: "t3-code",
12681268
url: endpoint,
1269-
headers: [{ name: "Authorization", value: authorization }],
1269+
headers: [
1270+
{ name: "Authorization", value: authorization },
1271+
{ name: "t3-tool-exposure", value: "deferred" },
1272+
],
12701273
},
12711274
];
12721275
const stdio = (authorization: string) => [
Collapse file

‎packages/provider-acp-registry/src/server/adapter.ts‎

Copy file name to clipboardExpand all lines: packages/provider-acp-registry/src/server/adapter.ts
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,7 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu
269269
clientCapabilitiesMeta: copilotClientCapabilitiesMeta,
270270
// Copilot CLI 1.0.105 rejects stdio MCP servers from the client.
271271
mcpOverHttp: true,
272+
deferMcpTools: true,
272273
registerExtensions: copilotRouting.registerExtensions,
273274
normalizeSessionUpdate: copilotRouting.normalizeSessionUpdate,
274275
extractSubagentUpdate: extractCopilotSubagentUpdate,
Collapse file

‎packages/provider-acp/src/server/adapter.ts‎

Copy file name to clipboardExpand all lines: packages/provider-acp/src/server/adapter.ts
+15-3Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -363,6 +363,8 @@ export interface AcpAdapterV2Flavor {
363363
EffectAcpSchema.InitializeRequest["clientCapabilities"]
364364
>["_meta"];
365365
readonly mcpOverHttp?: boolean;
366+
/** The agent has no tool search of its own, so T3 lists optional tools on demand. */
367+
readonly deferMcpTools?: boolean;
366368
readonly normalizeSessionUpdate?: (
367369
notification: EffectAcpSchema.SessionNotification,
368370
) => EffectAcpSchema.SessionNotification;
@@ -868,6 +870,7 @@ function acpMcpContext(
868870
session: McpProviderSession.McpProviderSessionConfig | undefined,
869871
self: SelfInvocation,
870872
mcpOverHttp: boolean | undefined,
873+
deferMcpTools: boolean | undefined,
871874
): AcpMcpContext {
872875
if (session === undefined) {
873876
return { servers: [], acpServers: [], httpServers: [] };
@@ -894,7 +897,12 @@ function acpMcpContext(
894897
type: "http",
895898
name: "t3-code",
896899
url: session.endpoint,
897-
headers: [{ name: "Authorization", value: session.authorizationHeader }],
900+
headers: [
901+
{ name: "Authorization", value: session.authorizationHeader },
902+
...(deferMcpTools === true
903+
? [{ name: McpProviderSession.MCP_TOOL_EXPOSURE_HEADER, value: "deferred" }]
904+
: []),
905+
],
898906
},
899907
]
900908
: [],
@@ -1749,10 +1757,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
17491757
const { flavor, selfInvocation: self } = options;
17501758
const readMcpContext = (threadId: ThreadId | null) =>
17511759
threadId === null
1752-
? Effect.succeed(acpMcpContext(undefined, self, flavor.mcpOverHttp))
1760+
? Effect.succeed(acpMcpContext(undefined, self, flavor.mcpOverHttp, flavor.deferMcpTools))
17531761
: mcpSessions
17541762
.read(threadId)
1755-
.pipe(Effect.map((session) => acpMcpContext(session, self, flavor.mcpOverHttp)));
1763+
.pipe(
1764+
Effect.map((session) =>
1765+
acpMcpContext(session, self, flavor.mcpOverHttp, flavor.deferMcpTools),
1766+
),
1767+
);
17561768
const driver = flavor.driver;
17571769
const continuationRequests = options.continuationRequests;
17581770
const postSettleContinuationEnabled =

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.