GeezerVison is showing github.com — fix(server): Copilot threads can call optional T3 tools again · pingdotgg/t3code@6bb8383
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: apps/server/src/mcp/McpHttpServer.test.ts +108-28Lines changed: 108 additions & 28 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -1931,7 +1931,7 @@ it.effect( | 1931 | 1931 | ).pipe(Effect.provide(NodeHttpServer.layerTest)), | 1932 | 1932 | ); | 1933 | 1933 |
| 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", () => | 1935 | 1935 | Effect.scoped( | 1936 | 1936 | Effect.gen(function* () { | 1937 | 1937 | const scopeFor = (token: string): McpInvocationContext.McpThreadInvocationScope => ({ | @@ -1950,17 +1950,29 @@ it.effect("lists optional tools to a deferring client only after tool_search loa | 1950 | 1950 | ["deferringToken", scopeFor("deferringToken")], | 1951 | 1951 | ["otherToken", scopeFor("otherToken")], | 1952 | 1952 | ]); | 1953 | | - const tool = (name: string, description: string) => | | 1953 | + const tool = <const Name extends string>(name: Name, description: string) => | 1954 | 1954 | Tool.make(name, { | 1955 | 1955 | description, | 1956 | 1956 | success: Schema.Struct({}), | 1957 | 1957 | failure: OrchestratorMcpFailure, | 1958 | 1958 | failureMode: "return", | 1959 | 1959 | }); | | 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 | + }); | 1960 | 1968 | const OptionalToolkit = Toolkit.make( | 1961 | 1969 | 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 | + ), | 1964 | 1976 | ); | 1965 | 1977 | const reads = McpToolAccess.reads(() => Effect.succeed({})); | 1966 | 1978 | const serverLayer = McpHttpServer.layerMcpTransport( | @@ -1969,11 +1981,18 @@ it.effect("lists optional tools to a deferring client only after tool_search loa | 1969 | 1981 | OptionalToolkit, | 1970 | 1982 | McpToolAccess.toLayer(OptionalToolkit, { | 1971 | 1983 | 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, | 1974 | 1993 | }), | 1975 | 1994 | ), | 1976 | | - McpHttpServer.layerToolSearch, | | 1995 | + McpHttpServer.layerToolGateway, | 1977 | 1996 | ), | 1978 | 1997 | ).pipe( | 1979 | 1998 | Layer.provide(ServerSettings.layerTest()), | @@ -1988,36 +2007,56 @@ it.effect("lists optional tools to a deferring client only after tool_search loa | 1988 | 2007 | Layer.build, | 1989 | 2008 | ); | 1990 | 2009 | 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) => | 1992 | 2017 | Effect.gen(function* () { | 1993 | 2018 | const headers = { | 1994 | 2019 | accept: "application/json, text/event-stream", | 1995 | 2020 | authorization: `Bearer ${token}`, | 1996 | 2021 | ...(deferred ? { "t3-tool-exposure": "deferred" } : {}), | 1997 | 2022 | }; | 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 | + }; | 2005 | 2035 | const rpc = (method: string, params: object) => | 2006 | 2036 | httpClient | 2007 | 2037 | .post("/mcp", { | 2008 | 2038 | headers: { | 2009 | 2039 | ...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 | + : {}), | 2012 | 2047 | }, | 2013 | 2048 | 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 | + }), | 2015 | 2055 | "application/json", | 2016 | 2056 | ), | 2017 | 2057 | }) | 2018 | 2058 | .pipe( | 2019 | 2059 | Effect.flatMap((response) => response.text), | 2020 | | - // tool_search answers over SSE, after its list_changed notification. | 2021 | 2060 | Effect.map((text): unknown => | 2022 | 2061 | text | 2023 | 2062 | .split("\n") | @@ -2036,23 +2075,64 @@ it.effect("lists optional tools to a deferring client only after tool_search loa | 2036 | 2075 | ), | 2037 | 2076 | call: (name: string, args: object) => | 2038 | 2077 | 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 | + ), | 2040 | 2090 | ), | 2041 | 2091 | }; | 2042 | 2092 | }); | 2043 | 2093 |
| 2044 | 2094 | const deferring = yield* session("deferringToken", true); | 2045 | 2095 | 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:"); | 2050 | 2113 |
| | 2114 | + // The wrapped tool returns its own result and sees the caller. | 2051 | 2115 | 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); | 2056 | 2136 | }), | 2057 | 2137 | ).pipe(Effect.provide(NodeHttpServer.layerTest)), | 2058 | 2138 | ); |
Collapse file Copy file name to clipboardExpand all lines: apps/server/src/mcp/McpHttpServer.ts +118-29Lines changed: 118 additions & 29 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -46,7 +46,7 @@ import { | 46 | 46 | import { advertisedJsonSchema } from "./advertisedJsonSchema.ts"; | 47 | 47 | import * as McpInvocationContext from "./McpInvocationContext.ts"; | 48 | 48 | import * as McpToolAccess from "./McpToolAccess.ts"; | 49 | | -import * as McpToolExposure from "./McpToolExposure.ts"; | | 49 | +import * as McpToolGroups from "./McpToolGroups.ts"; | 50 | 50 | import { MCP_TOOL_EXPOSURE_HEADER } from "@t3tools/provider-core/server/mcpSession"; | 51 | 51 | import * as OrchestratorMcpService from "./OrchestratorMcpService.ts"; | 52 | 52 | import { PreviewControlsToolkit } from "./toolkits/previewControls/tools.ts"; | @@ -76,8 +76,8 @@ import * as WorktreeHandlers from "./toolkits/worktree/handlers.ts"; | 76 | 76 | import { WorktreeToolkit } from "./toolkits/worktree/tools.ts"; | 77 | 77 | import * as WorktreeMcpService from "./WorktreeMcpService.ts"; | 78 | 78 | 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"; | 81 | 81 | import { PullRequestsToolkit } from "./toolkits/pullRequests/tools.ts"; | 82 | 82 | import * as DeviceHandlers from "./toolkits/device/handlers.ts"; | 83 | 83 | import { | @@ -1355,44 +1355,133 @@ export const layerTools = Layer.mergeAll( | 1355 | 1355 | layerMessageToolkit, | 1356 | 1356 | ); | 1357 | 1357 |
| 1358 | | -const layerToolExposure = Layer.effect( | 1359 | | - McpToolExposure.McpToolExposure, | | 1358 | +const layerToolCatalog = Layer.effect( | | 1359 | + McpToolGroups.McpToolCatalog, | 1360 | 1360 | Effect.gen(function* () { | 1361 | 1361 | 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 | + }); | 1367 | 1390 | }), | 1368 | 1391 | ); | 1369 | 1392 |
| | 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 | + | 1370 | 1460 | /** | 1371 | 1461 | * 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. | 1374 | 1464 | */ | 1375 | 1465 | 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); | 1388 | 1476 | }), | 1389 | 1477 | { global: true }, | 1390 | 1478 | ); | 1391 | 1479 |
| 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())), | 1395 | 1484 | layerDeferredListing, | 1396 | | -).pipe(Layer.provide(layerToolExposure)); | | 1485 | +).pipe(Layer.provide(McpServer.McpServer.layer)); | 1397 | 1486 |
| 1398 | | -export const layer = layerMcpTransport(Layer.mergeAll(layerTools, layerToolSearch)); | | 1487 | +export const layer = layerMcpTransport(Layer.mergeAll(layerTools, layerToolGateway)); |
|