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 can call optional T3 tools again · pingdotgg/t3code@6bb8383

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • apps/server/src
    • mcp
      • McpHttpServer.test.ts
      • McpHttpServer.ts
      • McpToolExposure.ts
      • McpToolGroups.ts
      • toolkits
        • gateway
          • handlers.ts
          • tools.ts
        • toolSearch
          • handlers.ts
          • tools.ts
    • provider
      • AgentContextBudget.test.ts
  • docs/orchestration-v2
    • orchestrator-mcp-server.md
  • packages
    • client-runtime/src
      • t3ToolSummary.ts
    • provider-acp/src/server
      • adapter.ts
      • runtimeModel.test.ts
      • runtimeModel.ts
    • provider-core/src/server
      • mcpSession.ts
    • shared/src
      • t3McpToolPresentation.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
+108-28Lines changed: 108 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1931,7 +1931,7 @@ it.effect(
19311931
).pipe(Effect.provide(NodeHttpServer.layerTest)),
19321932
);
19331933

1934-
it.effect("lists optional tools to a deferring client only after tool_search loads them", () =>
1934+
it.effect("gives a deferring client a fixed tool list and runs the rest through t3_call", () =>
19351935
Effect.scoped(
19361936
Effect.gen(function* () {
19371937
const scopeFor = (token: string): McpInvocationContext.McpThreadInvocationScope => ({
@@ -1950,17 +1950,29 @@ it.effect("lists optional tools to a deferring client only after tool_search loa
19501950
["deferringToken", scopeFor("deferringToken")],
19511951
["otherToken", scopeFor("otherToken")],
19521952
]);
1953-
const tool = (name: string, description: string) =>
1953+
const tool = <const Name extends string>(name: Name, description: string) =>
19541954
Tool.make(name, {
19551955
description,
19561956
success: Schema.Struct({}),
19571957
failure: OrchestratorMcpFailure,
19581958
failureMode: "return",
19591959
});
1960+
const ThemeSetTool = Tool.make("t3_theme_set", {
1961+
description: "Sets the theme.",
1962+
parameters: Schema.Struct({ themeId: Schema.String }),
1963+
success: Schema.Struct({ themeId: Schema.String, caller: Schema.String }),
1964+
failure: OrchestratorMcpFailure,
1965+
failureMode: "return",
1966+
dependencies: [McpInvocationContext.McpInvocationContext],
1967+
});
19601968
const OptionalToolkit = Toolkit.make(
19611969
tool("delegate_task", "Delegates a task."),
1962-
tool("preview_open", "Opens a browser preview."),
1963-
tool("schedule_task", "Schedules a task."),
1970+
tool("t3_theme_read", "Reads themes."),
1971+
ThemeSetTool,
1972+
tool("t3_environment_link", "Links an environment.").annotate(
1973+
McpSchema.EnabledWhen,
1974+
McpInvocationContext.hiddenWhileLinksOff,
1975+
),
19641976
);
19651977
const reads = McpToolAccess.reads(() => Effect.succeed({}));
19661978
const serverLayer = McpHttpServer.layerMcpTransport(
@@ -1969,11 +1981,18 @@ it.effect("lists optional tools to a deferring client only after tool_search loa
19691981
OptionalToolkit,
19701982
McpToolAccess.toLayer(OptionalToolkit, {
19711983
delegate_task: reads,
1972-
preview_open: reads,
1973-
schedule_task: reads,
1984+
t3_theme_read: reads,
1985+
// Proves the wrapped call runs as the calling thread.
1986+
t3_theme_set: McpToolAccess.reads(({ themeId }) =>
1987+
Effect.map(McpInvocationContext.McpInvocationContext, (scope) => ({
1988+
themeId,
1989+
caller: scope.thread?.threadId ?? "none",
1990+
})),
1991+
),
1992+
t3_environment_link: reads,
19741993
}),
19751994
),
1976-
McpHttpServer.layerToolSearch,
1995+
McpHttpServer.layerToolGateway,
19771996
),
19781997
).pipe(
19791998
Layer.provide(ServerSettings.layerTest()),
@@ -1988,36 +2007,56 @@ it.effect("lists optional tools to a deferring client only after tool_search loa
19882007
Layer.build,
19892008
);
19902009
const httpClient = yield* HttpClient.HttpClient;
1991-
const session = (token: string, deferred: boolean) =>
2010+
// Copilot CLI speaks the stateless protocol: no `initialize`, and the client profile rides on each request.
2011+
const statelessMeta = {
2012+
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
2013+
"io.modelcontextprotocol/clientCapabilities": {},
2014+
"io.modelcontextprotocol/clientInfo": { name: "probe", version: "1.0.0" },
2015+
};
2016+
const session = (token: string, deferred: boolean, stateless = false) =>
19922017
Effect.gen(function* () {
19932018
const headers = {
19942019
accept: "application/json, text/event-stream",
19952020
authorization: `Bearer ${token}`,
19962021
...(deferred ? { "t3-tool-exposure": "deferred" } : {}),
19972022
};
1998-
const initialize = yield* httpClient.post("/mcp", {
1999-
headers,
2000-
body: HttpBody.text(
2001-
`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
2002-
"application/json",
2003-
),
2004-
});
2023+
const protocolHeaders = stateless
2024+
? { "mcp-protocol-version": "2026-07-28" }
2025+
: {
2026+
"mcp-session-id": (yield* httpClient.post("/mcp", {
2027+
headers,
2028+
body: HttpBody.text(
2029+
`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
2030+
"application/json",
2031+
),
2032+
})).headers["mcp-session-id"]!,
2033+
"mcp-protocol-version": "2025-06-18",
2034+
};
20052035
const rpc = (method: string, params: object) =>
20062036
httpClient
20072037
.post("/mcp", {
20082038
headers: {
20092039
...headers,
2010-
"mcp-session-id": initialize.headers["mcp-session-id"]!,
2011-
"mcp-protocol-version": "2025-06-18",
2040+
...protocolHeaders,
2041+
...(stateless
2042+
? {
2043+
"mcp-method": method,
2044+
...("name" in params ? { "mcp-name": String(params.name) } : {}),
2045+
}
2046+
: {}),
20122047
},
20132048
body: HttpBody.text(
2014-
JSON.stringify({ jsonrpc: "2.0", id: 2, method, params }),
2049+
JSON.stringify({
2050+
jsonrpc: "2.0",
2051+
id: 2,
2052+
method,
2053+
params: stateless ? { ...params, _meta: statelessMeta } : params,
2054+
}),
20152055
"application/json",
20162056
),
20172057
})
20182058
.pipe(
20192059
Effect.flatMap((response) => response.text),
2020-
// tool_search answers over SSE, after its list_changed notification.
20212060
Effect.map((text): unknown =>
20222061
text
20232062
.split("\n")
@@ -2036,23 +2075,64 @@ it.effect("lists optional tools to a deferring client only after tool_search loa
20362075
),
20372076
call: (name: string, args: object) =>
20382077
rpc("tools/call", { name, arguments: args }).pipe(
2039-
Effect.map((body) => (body as { result: { structuredContent?: unknown } }).result),
2078+
Effect.map(
2079+
(body) =>
2080+
(
2081+
body as {
2082+
result: {
2083+
structuredContent?: unknown;
2084+
isError?: boolean;
2085+
content?: ReadonlyArray<{ text?: string }>;
2086+
};
2087+
}
2088+
).result,
2089+
),
20402090
),
20412091
};
20422092
});
20432093

20442094
const deferring = yield* session("deferringToken", true);
20452095
const other = yield* session("otherToken", false);
2046-
expect(yield* deferring.listed).toEqual(["delegate_task", "tool_search"]);
2047-
expect(yield* other.listed).toEqual(["delegate_task", "preview_open", "schedule_task"]);
2048-
// Unlisted tools stay callable.
2049-
expect((yield* deferring.call("schedule_task", {})).structuredContent).toEqual({});
2096+
// Linked environments are off here, so `t3_environment_link` is hidden from both.
2097+
const everything = ["delegate_task", "t3_theme_read", "t3_theme_set"];
2098+
expect(yield* deferring.listed).toEqual(["delegate_task", "t3_call", "t3_help"]);
2099+
expect(yield* other.listed).toEqual(everything);
2100+
2101+
// A group returns its tools with their schemas, and a tool name returns that tool.
2102+
const theme = (yield* deferring.call("t3_help", { path: "theme" })).structuredContent as {
2103+
tools: ReadonlyArray<{ name: string; inputSchema: { required?: ReadonlyArray<string> } }>;
2104+
};
2105+
expect(theme.tools.map((listed) => listed.name)).toEqual(["t3_theme_read", "t3_theme_set"]);
2106+
expect(theme.tools[1]?.inputSchema.required).toEqual(["themeId"]);
2107+
expect(
2108+
(yield* deferring.call("t3_help", { path: "t3_theme_read" })).structuredContent,
2109+
).toMatchObject({ tools: [{ name: "t3_theme_read", description: "Reads themes." }] });
2110+
const hiddenGroup = yield* deferring.call("t3_help", { path: "environment" });
2111+
expect(hiddenGroup.isError).toBe(true);
2112+
expect(hiddenGroup.content?.[0]?.text).toContain("Groups:");
20502113

2114+
// The wrapped tool returns its own result and sees the caller.
20512115
expect(
2052-
(yield* deferring.call("tool_search", { query: "browser" })).structuredContent,
2053-
).toEqual({ tools: [{ name: "preview_open", description: "Opens a browser preview." }] });
2054-
expect(yield* deferring.listed).toEqual(["delegate_task", "preview_open", "tool_search"]);
2055-
expect(yield* other.listed).toEqual(["delegate_task", "preview_open", "schedule_task"]);
2116+
(yield* deferring.call("t3_call", { tool: "t3_theme_set", arguments: { themeId: "dusk" } }))
2117+
.structuredContent,
2118+
).toEqual({ themeId: "dusk", caller: "thread-deferringToken" });
2119+
const badArguments = yield* deferring.call("t3_call", { tool: "t3_theme_set" });
2120+
expect(badArguments.isError).toBe(true);
2121+
expect(badArguments.content?.[0]?.text).toContain('"required":["themeId"]');
2122+
const unknownTool = yield* deferring.call("t3_call", { tool: "t3_call" });
2123+
expect(unknownTool.isError).toBe(true);
2124+
expect(unknownTool.content?.[0]?.text).toContain('No T3 tool is named "t3_call"');
2125+
2126+
const stateless = yield* session("deferringToken", true, true);
2127+
expect(yield* stateless.listed).toEqual(["delegate_task", "t3_call", "t3_help"]);
2128+
expect(
2129+
(yield* stateless.call("t3_call", { tool: "t3_theme_set", arguments: { themeId: "dusk" } }))
2130+
.structuredContent,
2131+
).toEqual({ themeId: "dusk", caller: "thread-deferringToken" });
2132+
2133+
// Nothing a call does changes either list.
2134+
expect(yield* deferring.listed).toEqual(["delegate_task", "t3_call", "t3_help"]);
2135+
expect(yield* other.listed).toEqual(everything);
20562136
}),
20572137
).pipe(Effect.provide(NodeHttpServer.layerTest)),
20582138
);
Collapse file

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

Copy file name to clipboardExpand all lines: apps/server/src/mcp/McpHttpServer.ts
+118-29Lines changed: 118 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ import {
4646
import { advertisedJsonSchema } from "./advertisedJsonSchema.ts";
4747
import * as McpInvocationContext from "./McpInvocationContext.ts";
4848
import * as McpToolAccess from "./McpToolAccess.ts";
49-
import * as McpToolExposure from "./McpToolExposure.ts";
49+
import * as McpToolGroups from "./McpToolGroups.ts";
5050
import { MCP_TOOL_EXPOSURE_HEADER } from "@t3tools/provider-core/server/mcpSession";
5151
import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";
5252
import { PreviewControlsToolkit } from "./toolkits/previewControls/tools.ts";
@@ -76,8 +76,8 @@ import * as WorktreeHandlers from "./toolkits/worktree/handlers.ts";
7676
import { WorktreeToolkit } from "./toolkits/worktree/tools.ts";
7777
import * as WorktreeMcpService from "./WorktreeMcpService.ts";
7878
import * as PullRequestsHandlers from "./toolkits/pullRequests/handlers.ts";
79-
import * as ToolSearchHandlers from "./toolkits/toolSearch/handlers.ts";
80-
import { ToolSearchToolkit } from "./toolkits/toolSearch/tools.ts";
79+
import * as GatewayHandlers from "./toolkits/gateway/handlers.ts";
80+
import { CallTool, HelpToolkit } from "./toolkits/gateway/tools.ts";
8181
import { PullRequestsToolkit } from "./toolkits/pullRequests/tools.ts";
8282
import * as DeviceHandlers from "./toolkits/device/handlers.ts";
8383
import {
@@ -1355,44 +1355,133 @@ export const layerTools = Layer.mergeAll(
13551355
layerMessageToolkit,
13561356
);
13571357

1358-
const layerToolExposure = Layer.effect(
1359-
McpToolExposure.McpToolExposure,
1358+
const layerToolCatalog = Layer.effect(
1359+
McpToolGroups.McpToolCatalog,
13601360
Effect.gen(function* () {
13611361
const server = yield* McpServer.McpServer;
1362-
return McpToolExposure.make(
1363-
() =>
1364-
server.tools.map(({ tool }) => ({ name: tool.name, description: tool.description ?? "" })),
1365-
() => server.notifications["notifications/tools/list_changed"]({}),
1366-
);
1362+
return McpToolGroups.McpToolCatalog.of({
1363+
listed: Effect.fn("McpToolCatalog.listed")(function* (names) {
1364+
// The server gives every tool handler its request context.
1365+
const request = yield* Effect.serviceOption(McpSchema.McpRequestContext).pipe(
1366+
Effect.flatMap(Effect.fromOption),
1367+
Effect.orDie,
1368+
);
1369+
return server.tools
1370+
.filter(({ tool, annotations }) => {
1371+
const enabledWhen = Context.getOrUndefined(annotations, McpSchema.EnabledWhen);
1372+
return (
1373+
names.includes(tool.name) &&
1374+
!McpToolGroups.isGatewayTool(tool.name) &&
1375+
(enabledWhen === undefined ||
1376+
enabledWhen({
1377+
protocolVersion: request.protocolVersion,
1378+
capabilities: request.clientCapabilities,
1379+
clientInfo: request.clientInfo,
1380+
}))
1381+
);
1382+
})
1383+
.map(({ tool }) => ({
1384+
name: tool.name,
1385+
description: tool.description ?? "",
1386+
inputSchema: tool.inputSchema,
1387+
}));
1388+
}),
1389+
});
13671390
}),
13681391
);
13691392

1393+
const decodeToolCall = Schema.decodeUnknownOption(CallTool.parametersSchema);
1394+
const isInvalidParams = Schema.is(McpSchema.InvalidParams);
1395+
const toolCallFailed = (text: string) =>
1396+
new McpSchema.CallToolResult({ isError: true, content: [{ type: "text", text }] });
1397+
1398+
/**
1399+
* `t3_call` declares no access of its own: the server runs the named tool as it
1400+
* runs any call, so that tool's access checks, middleware, and analytics apply.
1401+
*/
1402+
const registerToolCall = Effect.fn("McpHttpServer.registerToolCall")(function* () {
1403+
const server = yield* McpServer.McpServer;
1404+
yield* server.addTool({
1405+
tool: new McpSchema.Tool({
1406+
name: CallTool.name,
1407+
description: Tool.getDescription(CallTool),
1408+
inputSchema: advertisedJsonSchema(CallTool),
1409+
}),
1410+
annotations: CallTool.annotations,
1411+
handle: Effect.fnUntraced(function* (payload) {
1412+
const call = Option.getOrUndefined(decodeToolCall(payload));
1413+
if (call === undefined) {
1414+
return toolCallFailed(
1415+
`${CallTool.name} takes \`tool\`, a tool name, and \`arguments\`, an object.`,
1416+
);
1417+
}
1418+
const target = server.tools.find(({ tool }) => tool.name === call.tool)?.tool;
1419+
if (target === undefined || McpToolGroups.isGatewayTool(call.tool)) {
1420+
return toolCallFailed(
1421+
`No T3 tool is named "${call.tool}". Call ${McpToolGroups.T3_HELP} with a group to list its tools: ${McpToolGroups.TOOL_GROUP_NAMES}.`,
1422+
);
1423+
}
1424+
const request = yield* McpSchema.McpRequestContext;
1425+
const session = yield* Effect.serviceOption(McpSchema.McpServerClient);
1426+
const clientInfo = request.clientInfo ?? { name: "unknown", version: "" };
1427+
// `callTool` reads the caller from a session client. A stateless request has none, so
1428+
// this one carries the request's own profile. No T3 tool sends requests back to the client.
1429+
const client = Option.getOrElse(session, () =>
1430+
McpSchema.McpServerClient.of({
1431+
clientId: request.clientId,
1432+
protocolVersion: request.protocolVersion as McpProtocol.StatefulProtocolVersion,
1433+
clientCapabilities: request.clientCapabilities,
1434+
clientInfo,
1435+
initializePayload: {
1436+
protocolVersion: request.protocolVersion,
1437+
capabilities: request.clientCapabilities,
1438+
clientInfo,
1439+
},
1440+
requestMetadata: request.requestMetadata,
1441+
getClient: Effect.die(`${CallTool.name} has no MCP session to send a client request on.`),
1442+
}),
1443+
);
1444+
return yield* server.callTool({ name: call.tool, arguments: call.arguments ?? {} }).pipe(
1445+
Effect.provideService(McpSchema.McpServerClient, client),
1446+
Effect.catch((error) =>
1447+
Effect.succeed(
1448+
toolCallFailed(
1449+
isInvalidParams(error)
1450+
? `${error.message}\nInput schema of ${call.tool}: ${JSON.stringify(target.inputSchema)}`
1451+
: error.message,
1452+
),
1453+
),
1454+
),
1455+
);
1456+
}),
1457+
});
1458+
});
1459+
13701460
/**
13711461
* A provider session that sends `MCP_TOOL_EXPOSURE_HEADER: deferred` lists only
1372-
* the direct tools and what its `tool_search` calls loaded. Calls are never
1373-
* gated, and every other client lists everything but `tool_search`.
1462+
* the direct tools, and reaches the rest through `t3_help` and `t3_call`. Calls
1463+
* are never gated, and every other client lists everything but those two.
13741464
*/
13751465
const layerDeferredListing = McpServer.visibility(
1376-
Effect.gen(function* () {
1377-
const exposure = yield* McpToolExposure.McpToolExposure;
1378-
// Untraced: it runs once per tool on every list request.
1379-
return Effect.fnUntraced(function* ({ method, target, headers }: McpServer.MiddlewareOptions) {
1380-
if (method !== "tools/list") return true;
1381-
const scope = yield* Effect.serviceOption(McpInvocationContext.McpInvocationContext);
1382-
const providerSessionId = Option.getOrUndefined(scope)?.thread?.providerSessionId;
1383-
if (headers[MCP_TOOL_EXPOSURE_HEADER] !== "deferred" || providerSessionId === undefined) {
1384-
return target !== McpToolExposure.TOOL_SEARCH;
1385-
}
1386-
return exposure.isListed(providerSessionId, target);
1387-
});
1466+
// Untraced: it runs once per tool on every list request.
1467+
Effect.fnUntraced(function* ({ method, target, headers }: McpServer.MiddlewareOptions) {
1468+
if (method !== "tools/list") return true;
1469+
const scope = yield* Effect.serviceOption(McpInvocationContext.McpInvocationContext);
1470+
const deferred =
1471+
headers[MCP_TOOL_EXPOSURE_HEADER] === "deferred" &&
1472+
Option.getOrUndefined(scope)?.thread !== undefined;
1473+
return deferred
1474+
? McpToolGroups.isListedWhenDeferred(target)
1475+
: !McpToolGroups.isGatewayTool(target);
13881476
}),
13891477
{ global: true },
13901478
);
13911479

1392-
/** Outside layerTools: the clients its budget measures never list `tool_search`. */
1393-
export const layerToolSearch = Layer.mergeAll(
1394-
toolkitRegistration(ToolSearchToolkit, ToolSearchHandlers.layer),
1480+
/** Outside layerTools: the clients its budget measures never list the gateway tools. */
1481+
export const layerToolGateway = Layer.mergeAll(
1482+
toolkitRegistration(HelpToolkit, GatewayHandlers.layer).pipe(Layer.provide(layerToolCatalog)),
1483+
Layer.effectDiscard(withToolSpans(registerToolCall())),
13951484
layerDeferredListing,
1396-
).pipe(Layer.provide(layerToolExposure));
1485+
).pipe(Layer.provide(McpServer.McpServer.layer));
13971486

1398-
export const layer = layerMcpTransport(Layer.mergeAll(layerTools, layerToolSearch));
1487+
export const layer = layerMcpTransport(Layer.mergeAll(layerTools, layerToolGateway));

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.