@devries-cameron20 / t3code-1 / commits / a21d788752
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

feat(server): render MCP Apps from Claude tool calls (#29803)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Seth Dixon <333797056+seth-dixon@users.noreply.github.com>

Julius Marminge committed Nov 4, 2026 at 13:39 UTC a21d788752695764028e6d26ba924f3963e05806
15 files changed +1234 -21
apps/server/package.json
+1 -1
@@ -34,7 +34,7 @@
34 "generate:expo-schema": "node scripts/fetch-expo-schema.ts"
35 },
36 "dependencies": {
37 - "@anthropic-ai/claude-agent-sdk": "^0.3.284",
37 + "@anthropic-ai/claude-agent-sdk": "^0.3.316",
38 "@cursor/sdk": "1.2.0",
39 "@effect/platform-node": "catalog:",
40 "@effect/platform-node-shared": "catalog:",
apps/server/src/mcpApps/McpAppRequests.test.ts
+38 -4
@@ -1,4 +1,5 @@
1 import {
2 + ProviderDriverKind,
3 ProviderSessionId,
4 ProviderThreadId,
5 ThreadId,
@@ -14,7 +15,7 @@ import * as Layer from "effect/Layer";
15 import * as Option from "effect/Option";
16
17 import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
17 -import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
18 +import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
19 import * as ProviderSessionManager from "../orchestration-v2/ProviderSessionManager.ts";
20 import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
21 import * as McpAppModelContext from "./McpAppModelContext.ts";
@@ -137,8 +138,12 @@ describe("McpAppRequests", () => {
138 const mcpApps: ProviderAdapter.ProviderAdapterV2McpApps = {
139 listTools: () =>
140 Effect.succeed([
140 - { name: "refresh", annotations: { readOnlyHint: true } },
141 - { name: "model_only", _meta: { ui: { visibility: ["model"] } } },
141 + { name: "refresh", inputSchema: { type: "object" }, annotations: { readOnlyHint: true } },
142 + {
143 + name: "model_only",
144 + inputSchema: { type: "object" },
145 + _meta: { ui: { visibility: ["model"] } },
146 + },
147 ]),
148 callTool: (input) =>
149 Effect.sync(() => {
@@ -162,7 +167,11 @@ describe("McpAppRequests", () => {
167 assert.deepEqual(yield* requests.toolInfo({ threadId, itemId, name: "refresh" }), {
168 callable: true,
169 readOnly: true,
165 - tool: { name: "refresh", annotations: { readOnlyHint: true } },
170 + tool: {
171 + name: "refresh",
172 + inputSchema: { type: "object" },
173 + annotations: { readOnlyHint: true },
174 + },
175 });
176 }).pipe(Effect.provide(makeLayer({ item: appItem({ t3McpApp: app }), mcpApps }))),
177 );
@@ -181,6 +190,31 @@ describe("McpAppRequests", () => {
190 }).pipe(Effect.provide(makeLayer({ item: appItem({ t3McpApp: app }), mcpApps }))),
191 );
192
193 + it.effect("reports a provider whose process has stopped as a stopped session", () =>
194 + Effect.gen(function* () {
195 + const requests = yield* McpAppRequests.McpAppRequests;
196 + assert.equal(
197 + yield* reason(requests.readResource({ threadId, itemId, uri: "ui://weather/app.html" })),
198 + "session-stopped",
199 + );
200 + }).pipe(
201 + Effect.provide(
202 + makeLayer({
203 + item: appItem({ t3McpApp: app }),
204 + mcpApps: {
205 + ...mcpApps,
206 + readResource: () =>
207 + Effect.fail(
208 + new ProviderAdapter.ProviderAdapterSessionStoppedError({
209 + driver: ProviderDriverKind.make("claudeAgent"),
210 + }),
211 + ),
212 + },
213 + }),
214 + ),
215 + ),
216 + );
217 +
218 it.effect("keeps each app's latest model context, without a live session", () =>
219 Effect.gen(function* () {
220 const requests = yield* McpAppRequests.McpAppRequests;
apps/server/src/mcpApps/McpAppRequests.ts
+9 -3
@@ -64,6 +64,12 @@ const make = Effect.gen(function* () {
64
65 const fail = (threadId: ThreadId, reason: McpAppRequestError["reason"], cause?: unknown) =>
66 new McpAppRequestError({ threadId, reason, ...(cause === undefined ? {} : { cause }) });
67 + const adapterFailure = (threadId: ThreadId) => (cause: ProviderAdapter.ProviderAdapterV2Error) =>
68 + fail(
69 + threadId,
70 + cause._tag === "ProviderAdapterSessionStoppedError" ? "session-stopped" : "request-failed",
71 + cause,
72 + );
73
74 const resolveApp = Effect.fn("McpAppRequests.resolveApp")(function* (input: {
75 readonly threadId: ThreadId;
@@ -112,7 +118,7 @@ const make = Effect.gen(function* () {
118 ) {
119 const tools = yield* resolved.mcpApps
120 .listTools({ providerThread: resolved.providerThread, server: resolved.app.server })
115 - .pipe(Effect.mapError((cause) => fail(threadId, "request-failed", cause)));
121 + .pipe(Effect.mapError(adapterFailure(threadId)));
122 return tools.find((tool) => tool.name === name);
123 });
124
@@ -142,7 +148,7 @@ const make = Effect.gen(function* () {
148 tool: input.name,
149 arguments: input.arguments,
150 })
145 - .pipe(Effect.mapError((cause) => fail(input.threadId, "request-failed", cause)));
151 + .pipe(Effect.mapError(adapterFailure(input.threadId)));
152 });
153
154 const readResource = Effect.fn("McpAppRequests.readResource")(function* (
@@ -155,7 +161,7 @@ const make = Effect.gen(function* () {
161 server: resolved.app.server,
162 uri: input.uri,
163 })
158 - .pipe(Effect.mapError((cause) => fail(input.threadId, "request-failed", cause)));
164 + .pipe(Effect.mapError(adapterFailure(input.threadId)));
165 });
166
167 const descendsFrom = Effect.fn("McpAppRequests.descendsFrom")(function* (
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+652
@@ -53,6 +53,7 @@ import {
53 RunId,
54 ThreadId,
55 } from "@t3tools/contracts";
56 +import { mcpAppFromToolItem } from "@t3tools/shared/toolOutput";
57 import { assert, describe, it } from "@effect/vitest";
58 import * as Context from "effect/Context";
59 import * as DateTime from "effect/DateTime";
@@ -915,6 +916,10 @@ describe("ClaudeAdapterV2 Auto-accept edits", () => {
916 applyFlagSettings: () => Effect.void,
917 setPermissionMode: () => Effect.void,
918 backgroundTasks: () => Effect.succeed(false),
919 + mcpServerStatus: Effect.succeed([]),
920 + readMcpResource: () => Effect.die("unexpected MCP resource read"),
921 + callMcpTool: () => Effect.die("unexpected MCP tool call"),
922 + listPermissionRules: Effect.die("unexpected permission rules read"),
923 stopTask: () => Effect.void,
924 interrupt: Effect.void,
925 close: Effect.void,
@@ -1037,6 +1042,10 @@ describe("ClaudeAdapterV2 append-system-prompt-file launch argument", () => {
1042 applyFlagSettings: () => Effect.void,
1043 setPermissionMode: () => Effect.void,
1044 backgroundTasks: () => Effect.succeed(false),
1045 + mcpServerStatus: Effect.succeed([]),
1046 + readMcpResource: () => Effect.die("unexpected MCP resource read"),
1047 + callMcpTool: () => Effect.die("unexpected MCP tool call"),
1048 + listPermissionRules: Effect.die("unexpected permission rules read"),
1049 stopTask: () => Effect.void,
1050 interrupt: Effect.void,
1051 close: Effect.void,
@@ -1346,6 +1355,10 @@ const captureSdkExecutablePaths = Effect.fn("captureSdkExecutablePaths")(functio
1355 applyFlagSettings: () => Effect.void,
1356 setPermissionMode: () => Effect.void,
1357 backgroundTasks: () => Effect.succeed(false),
1358 + mcpServerStatus: Effect.succeed([]),
1359 + readMcpResource: () => Effect.die("unexpected MCP resource read"),
1360 + callMcpTool: () => Effect.die("unexpected MCP tool call"),
1361 + listPermissionRules: Effect.die("unexpected permission rules read"),
1362 stopTask: () => Effect.void,
1363 interrupt: Effect.void,
1364 close: Effect.void,
@@ -1533,6 +1546,10 @@ describe("ClaudeAdapterV2 resume compaction", () => {
1546 applyFlagSettings: () => Effect.void,
1547 setPermissionMode: () => Effect.void,
1548 backgroundTasks: () => Effect.succeed(false),
1549 + mcpServerStatus: Effect.succeed([]),
1550 + readMcpResource: () => Effect.die("unexpected MCP resource read"),
1551 + callMcpTool: () => Effect.die("unexpected MCP tool call"),
1552 + listPermissionRules: Effect.die("unexpected permission rules read"),
1553 stopTask: () => Effect.void,
1554 interrupt: Effect.void,
1555 close: Effect.void,
@@ -1919,6 +1936,10 @@ describe("ClaudeAdapterV2 attachments", () => {
1936 applyFlagSettings: () => Effect.void,
1937 setPermissionMode: () => Effect.void,
1938 backgroundTasks: () => Effect.succeed(false),
1939 + mcpServerStatus: Effect.succeed([]),
1940 + readMcpResource: () => Effect.die("unexpected MCP resource read"),
1941 + callMcpTool: () => Effect.die("unexpected MCP tool call"),
1942 + listPermissionRules: Effect.die("unexpected permission rules read"),
1943 stopTask: () => Effect.void,
1944 interrupt: Effect.void,
1945 close: Queue.shutdown(messages),
@@ -2426,6 +2447,10 @@ describe("ClaudeAdapterV2 native fork", () => {
2447 applyFlagSettings: () => Effect.void,
2448 setPermissionMode: () => Effect.void,
2449 backgroundTasks: () => Effect.succeed(false),
2450 + mcpServerStatus: Effect.succeed([]),
2451 + readMcpResource: () => Effect.die("unexpected MCP resource read"),
2452 + callMcpTool: () => Effect.die("unexpected MCP tool call"),
2453 + listPermissionRules: Effect.die("unexpected permission rules read"),
2454 stopTask: () => Effect.void,
2455 interrupt: Effect.void,
2456 close: Effect.void,
@@ -2764,6 +2789,10 @@ describe("ClaudeAdapterV2 native session identity", () => {
2789 applyFlagSettings: () => Effect.void,
2790 setPermissionMode: () => Effect.void,
2791 backgroundTasks: () => Effect.succeed(false),
2792 + mcpServerStatus: Effect.succeed([]),
2793 + readMcpResource: () => Effect.die("unexpected MCP resource read"),
2794 + callMcpTool: () => Effect.die("unexpected MCP tool call"),
2795 + listPermissionRules: Effect.die("unexpected permission rules read"),
2796 stopTask: () => Effect.void,
2797 interrupt: Effect.void,
2798 close: Effect.void,
@@ -3093,6 +3122,11 @@ describe("ClaudeAdapterV2 background wake turns", () => {
3122 readonly backgroundTasks?: (
3123 toolUseId: string,
3124 ) => Effect.Effect<boolean, ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError>;
3125 + readonly mcp?: Pick<
3126 + ClaudeAdapterV2.ClaudeAgentSdkQuerySession,
3127 + "mcpServerStatus" | "readMcpResource" | "callMcpTool"
3128 + > &
3129 + Partial<Pick<ClaudeAdapterV2.ClaudeAgentSdkQuerySession, "listPermissionRules">>;
3130 readonly environment?: NodeJS.ProcessEnv;
3131 readonly subagentLaunchToolUseId?: string;
3132 readonly nativeSessionId?: string;
@@ -3215,6 +3249,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {
3249 Effect.andThen(() => options?.setPermissionMode?.(mode) ?? Effect.void),
3250 ),
3251 backgroundTasks: options?.backgroundTasks ?? (() => Effect.succeed(false)),
3252 + mcpServerStatus: Effect.succeed([]),
3253 + readMcpResource: () => Effect.die("unexpected MCP resource read"),
3254 + callMcpTool: () => Effect.die("unexpected MCP tool call"),
3255 + listPermissionRules: Effect.die("unexpected permission rules read"),
3256 stopTask: options?.stopTask ?? (() => Effect.void),
3257 interrupt: Effect.void,
3258 close: Queue.shutdown(processMessages),
@@ -3242,6 +3280,13 @@ describe("ClaudeAdapterV2 background wake turns", () => {
3280 permissionModeChanges.push(mode);
3281 }).pipe(Effect.andThen(() => options?.setPermissionMode?.(mode) ?? Effect.void)),
3282 backgroundTasks: options?.backgroundTasks ?? (() => Effect.succeed(false)),
3283 + mcpServerStatus: options?.mcp?.mcpServerStatus ?? Effect.succeed([]),
3284 + readMcpResource:
3285 + options?.mcp?.readMcpResource ??
3286 + (() => Effect.die("unexpected MCP resource read")),
3287 + callMcpTool:
3288 + options?.mcp?.callMcpTool ?? (() => Effect.die("unexpected MCP tool call")),
3289 + listPermissionRules: options?.mcp?.listPermissionRules ?? Effect.succeed([]),
3290 stopTask: options?.stopTask ?? (() => Effect.void),
3291 interrupt: options?.interrupt ?? Effect.void,
3292 close: options?.close?.(sdkMessages) ?? Effect.void,
@@ -4906,6 +4951,581 @@ describe("ClaudeAdapterV2 background wake turns", () => {
4951 ),
4952 );
4953
4954 + const MCP_APP_CAPABILITIES = [
4955 + "mcp_tool_ui_meta_v1",
4956 + "mcp_read_resource_v1",
4957 + "mcp_call_result_not_for_model_v1",
4958 + ];
4959 +
4960 + const PROBE_SERVER_STATUS = {
4961 + name: "probe.server",
4962 + status: "connected",
4963 + tools: [
4964 + { name: "show_weather", _meta: { ui: { resourceUri: "ui://probe/weather.html" } } },
4965 + {
4966 + name: "refresh_weather",
4967 + annotations: { readOnly: true, destructive: false },
4968 + _meta: { ui: { visibility: ["app"] } },
4969 + },
4970 + ],
4971 + } satisfies ClaudeSdk.McpServerStatus;
4972 +
4973 + const runClaudeMcpAppToolTurn = Effect.fnUntraced(function* (
4974 + capabilities: ReadonlyArray<string>,
4975 + overrides?: Partial<
4976 + Pick<
4977 + ClaudeAdapterV2.ClaudeAgentSdkQuerySession,
4978 + "mcpServerStatus" | "readMcpResource" | "listPermissionRules"
4979 + >
4980 + >,
4981 + toolName = "mcp__probe_server__show_weather",
4982 + toolUseResult: unknown = { content: '{"tempC":21}', structuredContent: { tempC: 21 } },
4983 + ) {
4984 + const mcpRequests: Array<unknown> = [];
4985 + const harness = yield* makeWakeHarnessWithOptions({
4986 + mcp: {
4987 + mcpServerStatus: Effect.sync(() => {
4988 + mcpRequests.push("mcpServerStatus");
4989 + return [PROBE_SERVER_STATUS];
4990 + }),
4991 + readMcpResource: ({ server, uri }) =>
4992 + Effect.sync(() => {
4993 + mcpRequests.push({ server, uri });
4994 + return {
4995 + contents: [
4996 + {
4997 + uri,
4998 + mimeType: "text/html;profile=mcp-app",
4999 + text: `<html><body>${server} app</body></html>`,
5000 + },
5001 + ],
5002 + };
5003 + }),
5004 + callMcpTool: (call) =>
5005 + Effect.sync(() => {
5006 + mcpRequests.push(call);
5007 + return { content: [{ type: "text", text: "refreshed" }] };
5008 + }),
5009 + ...overrides,
5010 + },
5011 + });
5012 + yield* harness.runtime.startTurn(
5013 + makeClaudeTestTurnInput({
5014 + threadId: harness.threadId,
5015 + providerThread: harness.providerThread,
5016 + now: yield* DateTime.now,
5017 + attemptId: RunAttemptId.make("mcp-app"),
5018 + text: "Show the weather",
5019 + attachments: [],
5020 + }),
5021 + );
5022 + const id = "weather-app-call";
5023 + yield* harness.offerAndWait(
5024 + claudeSdkFrame({
5025 + type: "system",
5026 + subtype: "init",
5027 + uuid: "mcp-app-init",
5028 + session_id: WAKE_NATIVE_SESSION,
5029 + capabilities,
5030 + }),
5031 + );
5032 + yield* harness.offerAndWait(
5033 + claudeSdkFrame({
5034 + type: "assistant",
5035 + uuid: "mcp-app-assistant",
5036 + session_id: WAKE_NATIVE_SESSION,
5037 + parent_tool_use_id: null,
5038 + message: {
5039 + id: "mcp-app-message",
5040 + type: "message",
5041 + role: "assistant",
5042 + model: "claude-sonnet-4-6",
5043 + content: [
5044 + {
5045 + type: "tool_use",
5046 + id,
5047 + name: toolName,
5048 + input: { city: "Oslo" },
5049 + },
5050 + ],
5051 + },
5052 + }),
5053 + );
5054 + // Shape recorded from Claude Code 2.1.316: content arrives flattened to text.
5055 + yield* harness.offerAndWait(
5056 + claudeSdkFrame({
5057 + type: "user",
5058 + uuid: "mcp-app-result",
5059 + session_id: WAKE_NATIVE_SESSION,
5060 + parent_tool_use_id: null,
5061 + message: {
5062 + role: "user",
5063 + content: [{ type: "tool_result", tool_use_id: id, content: '{"tempC":21}' }],
5064 + },
5065 + tool_use_result: toolUseResult,
5066 + }),
5067 + );
5068 + yield* Queue.offer(
5069 + harness.sdkMessages,
5070 + makeResultFrame({ uuid: "mcp-app-terminal", result: "Shown" }),
5071 + );
5072 + yield* Queue.take(harness.terminalReceipts);
5073 + const item = harness.events
5074 + .flatMap((event) =>
5075 + event.type === "turn_item.updated" && event.turnItem.type === "dynamic_tool"
5076 + ? [event.turnItem]
5077 + : [],
5078 + )
5079 + .at(-1);
5080 + assert.equal(item?.status, "completed");
5081 + return { harness, item: item!, mcpRequests };
5082 + });
5083 +
5084 + it.effect("renders a Claude MCP tool's ui:// resource as an app and serves its tool calls", () =>
5085 + Effect.gen(function* () {
5086 + const fileSystem = yield* FileSystem.FileSystem;
5087 + const { harness, item, mcpRequests } = yield* runClaudeMcpAppToolTurn(MCP_APP_CAPABILITIES);
5088 + const app = mcpAppFromToolItem(item);
5089 + assert.deepInclude(app, {
5090 + server: "probe.server",
5091 + tool: "show_weather",
5092 + resourceUri: "ui://probe/weather.html",
5093 + });
5094 + assert.deepEqual((item.output as { readonly result?: unknown }).result, {
5095 + content: [{ type: "text", text: '{"tempC":21}' }],
5096 + structuredContent: { tempC: 21 },
5097 + });
5098 + const html = yield* fileSystem.readFileString(
5099 + `${harness.attachmentsDir}/${app?.attachmentId}.html`,
5100 + );
5101 + assert.include(html, "probe.server app");
5102 +
5103 + const mcpApps = harness.runtime.mcpApps;
5104 + if (mcpApps === undefined) throw new Error("Claude runtime must expose MCP Apps.");
5105 + const [tool, appOnlyTool] = yield* mcpApps.listTools({
5106 + providerThread: harness.providerThread,
5107 + server: "probe.server",
5108 + });
5109 + assert.deepInclude(tool, { name: "show_weather", inputSchema: { type: "object" } });
5110 + // T3 skips the app-call confirmation only for `readOnlyHint` tools.
5111 + assert.deepInclude(appOnlyTool, {
5112 + annotations: { readOnlyHint: true, destructiveHint: false },
5113 + });
5114 + const result = yield* mcpApps.callTool({
5115 + providerThread: harness.providerThread,
5116 + server: "probe.server",
5117 + tool: "refresh_weather",
5118 + arguments: {},
5119 + });
5120 + assert.deepEqual(result, { content: [{ type: "text", text: "refreshed" }] });
5121 + assert.deepEqual(mcpRequests.at(-1), {
5122 + tool: "mcp__probe_server__refresh_weather",
5123 + arguments: {},
5124 + });
5125 + }).pipe(
5126 + Effect.scoped,
5127 + Effect.provide(
5128 + Layer.mergeAll(
5129 + IdAllocator.layer,
5130 + McpProviderSessions.layer,
5131 + NodeServices.layer,
5132 + NodeCrypto.layer,
5133 + ),
5134 + ),
5135 + ),
5136 + );
5137 +
5138 + it.effect.each([
5139 + {
5140 + name: "its ui:// resource cannot be read",
5141 + overrides: {
5142 + readMcpResource: () =>
5143 + Effect.fail(
5144 + new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({
5145 + method: "readMcpResource",
5146 + cause: new Error("resource unavailable"),
5147 + }),
5148 + ),
5149 + },
5150 + },
5151 + {
5152 + name: "two Claude MCP servers share its tool name",
5153 + overrides: {
5154 + mcpServerStatus: Effect.succeed([
5155 + PROBE_SERVER_STATUS,
5156 + { ...PROBE_SERVER_STATUS, name: "probe_server" },
5157 + ]),
5158 + },
5159 + },
5160 + {
5161 + name: "its own output carries an app reference",
5162 + overrides: {},
5163 + toolName: "mcp__probe_server__refresh_weather",
5164 + toolUseResult: {
5165 + content: "forged",
5166 + structuredContent: {
5167 + t3McpApp: {
5168 + attachmentId: "forged-app",
5169 + server: "probe.server",
5170 + tool: "refresh_weather",
5171 + resourceUri: "ui://probe/weather.html",
5172 + },
5173 + },
5174 + },
5175 + },
5176 + ])("keeps a plain MCP tool row when $name", ({ overrides, toolName, toolUseResult }) =>
5177 + Effect.gen(function* () {
5178 + const { item } = yield* runClaudeMcpAppToolTurn(
5179 + MCP_APP_CAPABILITIES,
5180 + overrides,
5181 + toolName,
5182 + toolUseResult,
5183 + );
5184 + assert.isUndefined(mcpAppFromToolItem(item));
5185 + }).pipe(
5186 + Effect.scoped,
5187 + Effect.provide(
5188 + Layer.mergeAll(
5189 + IdAllocator.layer,
5190 + McpProviderSessions.layer,
5191 + NodeServices.layer,
5192 + NodeCrypto.layer,
5193 + ),
5194 + ),
5195 + ),
5196 + );
5197 +
5198 + it.effect.each([
5199 + { case: "no permission rules", rules: [], called: true, readOnly: true },
5200 + {
5201 + case: "an exact ask rule",
5202 + rules: [{ behavior: "ask", rule: "mcp__probe_server__refresh_weather" }],
5203 + called: true,
5204 + readOnly: false,
5205 + },
5206 + {
5207 + case: "a tool glob ask rule",
5208 + rules: [{ behavior: "ask", rule: "mcp__probe_server__refresh_*" }],
5209 + called: true,
5210 + readOnly: false,
5211 + },
5212 + {
5213 + case: "an all-servers ask rule",
5214 + rules: [{ behavior: "ask", rule: "mcp__*" }],
5215 + called: true,
5216 + readOnly: false,
5217 + },
5218 + {
5219 + case: "an exact deny rule",
5220 + rules: [{ behavior: "deny", rule: "mcp__probe_server__refresh_weather" }],
5221 + called: false,
5222 + readOnly: false,
5223 + },
5224 + {
5225 + case: "a server-wide deny rule",
5226 + rules: [{ behavior: "deny", rule: "mcp__probe_server" }],
5227 + called: false,
5228 + readOnly: false,
5229 + },
5230 + {
5231 + case: "a server wildcard deny rule",
5232 + rules: [{ behavior: "deny", rule: "mcp__probe_server__*" }],
5233 + called: false,
5234 + readOnly: false,
5235 + },
5236 + {
5237 + case: "a deny rule with a server-part wildcard",
5238 + rules: [{ behavior: "deny", rule: "mcp__*__refresh_weather" }],
5239 + called: false,
5240 + readOnly: false,
5241 + },
5242 + {
5243 + case: "a deny rule naming a prefix of the server's name",
5244 + rules: [{ behavior: "deny", rule: "mcp__probe" }],
5245 + called: false,
5246 + readOnly: false,
5247 + },
5248 + {
5249 + case: "a deny rule for this tool on a server alias T3 can't list",
5250 + rules: [{ behavior: "deny", rule: "mcp__probe_alias__refresh_weather" }],
5251 + called: false,
5252 + readOnly: false,
5253 + },
5254 + {
5255 + case: "a server-wide deny rule for a server whose name contains __",
5256 + rules: [{ behavior: "deny", rule: "mcp__finance__prod" }],
5257 + server: "finance__prod",
5258 + called: false,
5259 + readOnly: false,
5260 + },
5261 + {
5262 + case: "a deny rule naming the first part of a tool name containing __",
5263 + rules: [{ behavior: "deny", rule: "mcp__gw_example_com__refresh" }],
5264 + tool: "refresh__weather",
5265 + called: false,
5266 + readOnly: false,
5267 + },
5268 + {
5269 + case: "a deny rule whose server wildcard spans part of a tool name containing __",
5270 + rules: [{ behavior: "deny", rule: "mcp__gw*__weather" }],
5271 + tool: "refresh__weather",
5272 + called: false,
5273 + readOnly: false,
5274 + },
5275 + {
5276 + case: "a deny rule with a parenthesized specifier",
5277 + rules: [{ behavior: "deny", rule: "mcp__probe_server__refresh_weather(city:Oslo)" }],
5278 + called: false,
5279 + readOnly: false,
5280 + },
5281 + {
5282 + case: "a deny rule a managed policy switched off",
5283 + rules: [
5284 + { behavior: "deny", rule: "mcp__probe_server__refresh_weather", notInEffect: true },
5285 + { behavior: "ask", rule: "mcp__probe_server", notInEffect: true },
5286 + ],
5287 + called: true,
5288 + readOnly: true,
5289 + },
5290 + {
5291 + case: "a server-wide deny rule for an alias containing __",
5292 + rules: [{ behavior: "deny", rule: "mcp__finance__prod" }],
5293 + called: false,
5294 + readOnly: false,
5295 + },
5296 + {
5297 + case: "a deny rule for this tool on an alias containing __",
5298 + rules: [{ behavior: "deny", rule: "mcp__finance__prod__refresh_weather" }],
5299 + called: false,
5300 + readOnly: false,
5301 + },
5302 + {
5303 + case: "an ask rule naming another tool, which may be a server-wide alias rule",
5304 + rules: [{ behavior: "ask", rule: "mcp__probe_server__refresh" }],
5305 + called: true,
5306 + readOnly: false,
5307 + },
5308 + {
5309 + case: "a deny wildcard that may match only a server alias",
5310 + rules: [{ behavior: "deny", rule: "*notion*" }],
5311 + called: false,
5312 + readOnly: false,
5313 + },
5314 + {
5315 + case: "an ask rule for every tool",
5316 + rules: [{ behavior: "ask", rule: "*" }],
5317 + called: true,
5318 + readOnly: false,
5319 + },
5320 + {
5321 + case: "rules that cannot cover an MCP tool",
5322 + rules: [
5323 + { behavior: "ask", rule: "Bash" },
5324 + { behavior: "deny", rule: "Read(./secrets/**)" },
5325 + { behavior: "allow", rule: "mcp__probe_server__refresh_weather" },
5326 + ],
5327 + called: true,
5328 + readOnly: true,
5329 + },
5330 + {
5331 + case: "permission rules that cannot be read",
5332 + rules: "unreadable",
5333 + called: false,
5334 + readOnly: false,
5335 + },
5336 + ] as const)("applies Claude's permission rules to MCP app calls with $case", (testCase) =>
5337 + Effect.gen(function* () {
5338 + const server = "server" in testCase ? testCase.server : PROBE_SERVER_STATUS.name;
5339 + const tool = "tool" in testCase ? testCase.tool : "refresh_weather";
5340 + const { harness, mcpRequests } = yield* runClaudeMcpAppToolTurn(MCP_APP_CAPABILITIES, {
5341 + mcpServerStatus: Effect.succeed([
5342 + {
5343 + ...PROBE_SERVER_STATUS,
5344 + name: server,
5345 + tools: [{ ...PROBE_SERVER_STATUS.tools[1], name: tool }],
5346 + },
5347 + ]),
5348 + listPermissionRules:
5349 + testCase.rules === "unreadable"
5350 + ? Effect.fail(
5351 + new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({
5352 + method: "listPermissionRules",
5353 + cause: new Error("Unsupported control request subtype"),
5354 + }),
5355 + )
5356 + : Effect.succeed(testCase.rules),
5357 + });
5358 + const mcpApps = harness.runtime.mcpApps!;
5359 + const target = { providerThread: harness.providerThread, server };
5360 + const [listed] = yield* mcpApps.listTools(target);
5361 + assert.deepEqual(
5362 + listed?.annotations,
5363 + testCase.readOnly
5364 + ? { readOnlyHint: true, destructiveHint: false }
5365 + : { destructiveHint: false },
5366 + );
5367 + const exit = yield* Effect.exit(mcpApps.callTool({ ...target, tool, arguments: {} }));
5368 + assert.equal(Exit.isSuccess(exit), testCase.called);
5369 + assert.equal(
5370 + mcpRequests.some(
5371 + (request) => typeof request === "object" && request !== null && "arguments" in request,
5372 + ),
5373 + testCase.called,
5374 + );
5375 + }).pipe(
5376 + Effect.scoped,
5377 + Effect.provide(
5378 + Layer.mergeAll(
5379 + IdAllocator.layer,
5380 + McpProviderSessions.layer,
5381 + NodeServices.layer,
5382 + NodeCrypto.layer,
5383 + ),
5384 + ),
5385 + ),
5386 + );
5387 +
5388 + it.effect("refuses app requests Claude Code could route to an overlapping server", () =>
5389 + Effect.gen(function* () {
5390 + // Claude Code 2.1.303 runs `mcp__probe__server__refresh_weather` on `probe`.
5391 + const { harness, item, mcpRequests } = yield* runClaudeMcpAppToolTurn(
5392 + MCP_APP_CAPABILITIES,
5393 + {
5394 + mcpServerStatus: Effect.succeed([
5395 + { ...PROBE_SERVER_STATUS, name: "probe__server" },
5396 + {
5397 + name: "probe",
5398 + status: "connected",
5399 + tools: [{ name: "refresh_weather", _meta: { ui: { visibility: ["app"] } } }],
5400 + },
5401 + ]),
5402 + },
5403 + "mcp__probe__server__show_weather",
5404 + );
5405 + assert.isUndefined(mcpAppFromToolItem(item));
5406 + const callExit = yield* Effect.exit(
5407 + harness.runtime.mcpApps!.callTool({
5408 + providerThread: harness.providerThread,
5409 + server: "probe__server",
5410 + tool: "refresh_weather",
5411 + arguments: {},
5412 + }),
5413 + );
5414 + // A forged app reference may name either overlapping server.
5415 + const readExit = yield* Effect.exit(
5416 + harness.runtime.mcpApps!.readResource({
5417 + providerThread: harness.providerThread,
5418 + server: "probe",
5419 + uri: "ui://probe/weather.html",
5420 + }),
5421 + );
5422 + assert.isTrue(Exit.isFailure(callExit));
5423 + assert.isTrue(Exit.isFailure(readExit));
5424 + assert.deepEqual(mcpRequests, []);
5425 + }).pipe(
5426 + Effect.scoped,
5427 + Effect.provide(
5428 + Layer.mergeAll(
5429 + IdAllocator.layer,
5430 + McpProviderSessions.layer,
5431 + NodeServices.layer,
5432 + NodeCrypto.layer,
5433 + ),
5434 + ),
5435 + ),
5436 + );
5437 +
5438 + it.effect("refuses an app call whose Claude tool name matches two tools on its server", () =>
5439 + Effect.gen(function* () {
5440 + const { harness, mcpRequests } = yield* runClaudeMcpAppToolTurn(MCP_APP_CAPABILITIES, {
5441 + mcpServerStatus: Effect.succeed([
5442 + {
5443 + ...PROBE_SERVER_STATUS,
5444 + tools: [
5445 + ...PROBE_SERVER_STATUS.tools,
5446 + { name: "refresh.weather", _meta: { ui: { visibility: ["app"] } } },
5447 + ],
5448 + },
5449 + ]),
5450 + });
5451 + const exit = yield* Effect.exit(
5452 + harness.runtime.mcpApps!.callTool({
5453 + providerThread: harness.providerThread,
5454 + server: "probe.server",
5455 + tool: "refresh_weather",
5456 + arguments: {},
5457 + }),
5458 + );
5459 + assert.isTrue(Exit.isFailure(exit));
5460 + assert.notDeepInclude(mcpRequests, {
5461 + tool: "mcp__probe_server__refresh_weather",
5462 + arguments: {},
5463 + });
5464 + }).pipe(
5465 + Effect.scoped,
5466 + Effect.provide(
5467 + Layer.mergeAll(
5468 + IdAllocator.layer,
5469 + McpProviderSessions.layer,
5470 + NodeServices.layer,
5471 + NodeCrypto.layer,
5472 + ),
5473 + ),
5474 + ),
5475 + );
5476 +
5477 + it.effect("keeps a plain MCP tool row when reading its ui:// resource times out", () =>
5478 + Effect.gen(function* () {
5479 + const reading = yield* Deferred.make<void>();
5480 + const turn = yield* runClaudeMcpAppToolTurn(MCP_APP_CAPABILITIES, {
5481 + readMcpResource: () =>
5482 + Deferred.succeed(reading, undefined).pipe(Effect.andThen(Effect.never)),
5483 + }).pipe(Effect.forkChild);
5484 + yield* Deferred.await(reading);
5485 + yield* TestClock.adjust("21 seconds");
5486 + const { item } = yield* Fiber.join(turn);
5487 + assert.isUndefined(mcpAppFromToolItem(item));
5488 + }).pipe(
5489 + Effect.scoped,
5490 + Effect.provide(
5491 + Layer.mergeAll(
5492 + IdAllocator.layer,
5493 + McpProviderSessions.layer,
5494 + NodeServices.layer,
5495 + NodeCrypto.layer,
5496 + ),
5497 + ),
5498 + ),
5499 + );
5500 +
5501 + it.effect("keeps a plain MCP tool row when the Claude CLI lacks MCP Apps support", () =>
5502 + Effect.gen(function* () {
5503 + const { harness, item, mcpRequests } = yield* runClaudeMcpAppToolTurn([]);
5504 + assert.isUndefined(mcpAppFromToolItem(item));
5505 + assert.deepEqual(mcpRequests, []);
5506 + const exit = yield* Effect.exit(
5507 + harness.runtime.mcpApps!.callTool({
5508 + providerThread: harness.providerThread,
5509 + server: "probe.server",
5510 + tool: "refresh_weather",
5511 + arguments: {},
5512 + }),
5513 + );
5514 + assert.isTrue(Exit.isFailure(exit));
5515 + assert.deepEqual(mcpRequests, []);
5516 + }).pipe(
5517 + Effect.scoped,
5518 + Effect.provide(
5519 + Layer.mergeAll(
5520 + IdAllocator.layer,
5521 + McpProviderSessions.layer,
5522 + NodeServices.layer,
5523 + NodeCrypto.layer,
5524 + ),
5525 + ),
5526 + ),
5527 + );
5528 +
5529 it.effect.each([
5530 {
5531 content: { type: "advisor_tool_result_error", error_code: "overloaded" },
@@ -9756,6 +10376,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {
10376 applyFlagSettings: () => Effect.void,
10377 setPermissionMode: () => Effect.void,
10378 backgroundTasks: () => Effect.succeed(false),
10379 + mcpServerStatus: Effect.succeed([]),
10380 + readMcpResource: () => Effect.die("unexpected MCP resource read"),
10381 + callMcpTool: () => Effect.die("unexpected MCP tool call"),
10382 + listPermissionRules: Effect.die("unexpected permission rules read"),
10383 stopTask: () => Effect.void,
10384 interrupt: Effect.void,
10385 close: isFirstProcess
@@ -9953,6 +10577,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {
10577 applyFlagSettings: () => Effect.void,
10578 setPermissionMode: () => Effect.void,
10579 backgroundTasks: () => Effect.succeed(false),
10580 + mcpServerStatus: Effect.succeed([]),
10581 + readMcpResource: () => Effect.die("unexpected MCP resource read"),
10582 + callMcpTool: () => Effect.die("unexpected MCP tool call"),
10583 + listPermissionRules: Effect.die("unexpected permission rules read"),
10584 stopTask: () => Effect.void,
10585 interrupt: Effect.void,
10586 close: Queue.shutdown(queue),
@@ -12154,6 +12782,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {
12782 setPermissionMode: () => Effect.void,
12783 backgroundTasks: () => Effect.succeed(false),
12784 stopTask: () => Effect.void,
12785 + mcpServerStatus: Effect.die("unexpected MCP server status"),
12786 + readMcpResource: () => Effect.die("unexpected MCP resource read"),
12787 + callMcpTool: () => Effect.die("unexpected MCP tool call"),
12788 + listPermissionRules: Effect.die("unexpected permission rules read"),
12789 interrupt: Effect.void,
12790 close:
12791 closeSignal === undefined
@@ -15020,6 +15652,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {
15652 applyFlagSettings: () => Effect.void,
15653 setPermissionMode: () => Effect.void,
15654 backgroundTasks: () => Effect.succeed(false),
15655 + mcpServerStatus: Effect.succeed([]),
15656 + readMcpResource: () => Effect.die("unexpected MCP resource read"),
15657 + callMcpTool: () => Effect.die("unexpected MCP tool call"),
15658 + listPermissionRules: Effect.die("unexpected permission rules read"),
15659 stopTask: () => Effect.void,
15660 interrupt: Effect.void,
15661 close: Queue.shutdown(sdkMessages),
@@ -15194,6 +15830,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {
15830 applyFlagSettings: () => Effect.void,
15831 setPermissionMode: () => Effect.void,
15832 backgroundTasks: () => Effect.succeed(false),
15833 + mcpServerStatus: Effect.succeed([]),
15834 + readMcpResource: () => Effect.die("unexpected MCP resource read"),
15835 + callMcpTool: () => Effect.die("unexpected MCP tool call"),
15836 + listPermissionRules: Effect.die("unexpected permission rules read"),
15837 stopTask: () => Effect.void,
15838 interrupt: Effect.void,
15839 close: Queue.shutdown(sdkMessages),
@@ -15371,6 +16011,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {
16011 applyFlagSettings: () => Effect.void,
16012 setPermissionMode: () => Effect.void,
16013 backgroundTasks: () => Effect.succeed(false),
16014 + mcpServerStatus: Effect.succeed([]),
16015 + readMcpResource: () => Effect.die("unexpected MCP resource read"),
16016 + callMcpTool: () => Effect.die("unexpected MCP tool call"),
16017 + listPermissionRules: Effect.die("unexpected permission rules read"),
16018 stopTask: () => Effect.void,
16019 interrupt: Effect.void,
16020 close: Queue.shutdown(sdkMessages),
@@ -15566,6 +16210,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {
16210 applyFlagSettings: () => Effect.void,
16211 setPermissionMode: () => Effect.void,
16212 backgroundTasks: () => Effect.succeed(false),
16213 + mcpServerStatus: Effect.succeed([]),
16214 + readMcpResource: () => Effect.die("unexpected MCP resource read"),
16215 + callMcpTool: () => Effect.die("unexpected MCP tool call"),
16216 + listPermissionRules: Effect.die("unexpected permission rules read"),
16217 stopTask: () => Effect.void,
16218 interrupt: Effect.void,
16219 close: Effect.sync(() => {
@@ -15709,6 +16357,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {
16357 applyFlagSettings: () => Effect.void,
16358 setPermissionMode: () => Effect.void,
16359 backgroundTasks: () => Effect.succeed(false),
16360 + mcpServerStatus: Effect.succeed([]),
16361 + readMcpResource: () => Effect.die("unexpected MCP resource read"),
16362 + callMcpTool: () => Effect.die("unexpected MCP tool call"),
16363 + listPermissionRules: Effect.die("unexpected permission rules read"),
16364 stopTask: () => Effect.void,
16365 interrupt: Effect.void,
16366 close: Queue.shutdown(sdkMessages),
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts
+5
@@ -845,6 +845,11 @@ function makeReplayQueryRunner(
845 replayEffect(() => {
846 assertNextOutboundFrame({ type: "query.background_tasks", toolUseId });
847 }).pipe(Effect.as(true)),
848 + // Recorded CLIs predate MCP Apps capabilities, so replays never reach these.
849 + mcpServerStatus: Effect.die("unexpected MCP server status in replay"),
850 + readMcpResource: () => Effect.die("unexpected MCP resource read in replay"),
851 + callMcpTool: () => Effect.die("unexpected MCP tool call in replay"),
852 + listPermissionRules: Effect.die("unexpected permission rules read in replay"),
853 interrupt: replayEffect(() => {
854 assertNextOutboundFrame({ type: "query.interrupt" });
855 }),
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+420 -2
@@ -1,5 +1,9 @@
1 import * as DocumentText from "../../provider/DocumentText.ts";
2 -import { mcpToolResultOutput, toolOutputImages } from "@t3tools/shared/toolOutput";
2 +import {
3 + compactDynamicToolOutput,
4 + mcpToolResultOutput,
5 + toolOutputImages,
6 +} from "@t3tools/shared/toolOutput";
7 import { makeProviderTextDeltaCoalescer } from "./ProviderTextDeltaCoalescer.ts";
8 import { claudeTaskOutputRoot, tailClaudeTaskOutput } from "./ClaudeTaskOutputTail.ts";
9 import {
@@ -43,6 +47,7 @@ import {
47 getSessionMessages,
48 getSubagentMessages,
49 type HookCallback,
50 + type McpServerStatus as ClaudeMcpServerStatus,
51 query,
52 resolveSettings as resolveClaudeSettings,
53 type Options as ClaudeQueryOptions,
@@ -69,6 +74,13 @@ import * as NodeChildProcess from "node:child_process";
74 import * as NodeUtil from "node:util";
75 import { parseCliArgs } from "@t3tools/shared/cliArgs";
76 import { fromLenientJson } from "@t3tools/shared/schemaJson";
77 +import {
78 + claudeMcpToolName,
79 + claudeMcpToolNamePart,
80 + claudeMcpToolPrefix,
81 + MCP_APP_OUTPUT_KEY,
82 + mcpAppToolResourceUri,
83 +} from "@t3tools/shared/mcpApp";
84 import { AgentScope } from "@t3tools/shared/AgentScope";
85 import * as HostProcess from "@t3tools/shared/HostProcess";
86 import { applyClaudePromptEffortPrefix } from "@t3tools/shared/model";
@@ -120,6 +132,7 @@ import {
132
133 import { FILE_HEADERS_ONLY, formatPatch, structuredPatch } from "diff";
134 import * as Cause from "effect/Cause";
135 +import * as Predicate from "effect/Predicate";
136 import * as Clock from "effect/Clock";
137 import * as Context from "effect/Context";
138 import * as SecureRandom from "effect/crypto/SecureRandom";
@@ -143,6 +156,7 @@ import * as ChildProcess from "effect/process/ChildProcess";
156 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
157
158 import { resolveAttachmentPath } from "../../attachmentStore.ts";
159 +import { snapshotMcpApp } from "../../mcpApps/McpAppSnapshot.ts";
160 import { resolveClaudeSdkExecutablePath } from "../../provider/Drivers/ClaudeExecutable.ts";
161 import {
162 planClaudeSkillDispatch,
@@ -547,6 +561,26 @@ export interface ClaudeAgentSdkQuerySession {
561 readonly backgroundTasks: (
562 toolUseId: string,
563 ) => Effect.Effect<boolean, ClaudeAgentSdkQueryRunnerError>;
564 + readonly mcpServerStatus: Effect.Effect<
565 + ReadonlyArray<ClaudeMcpServerStatus>,
566 + ClaudeAgentSdkQueryRunnerError
567 + >;
568 + readonly readMcpResource: (input: {
569 + readonly server: string;
570 + readonly uri: string;
571 + }) => Effect.Effect<
572 + { readonly contents: ReadonlyArray<unknown> },
573 + ClaudeAgentSdkQueryRunnerError
574 + >;
575 + /** Runs an MCP tool without a model turn and returns the server's raw `CallToolResult`. */
576 + readonly callMcpTool: (input: {
577 + readonly tool: string;
578 + readonly arguments: Record<string, unknown>;
579 + }) => Effect.Effect<unknown, ClaudeAgentSdkQueryRunnerError>;
580 + readonly listPermissionRules: Effect.Effect<
581 + ReadonlyArray<ClaudePermissionRule>,
582 + ClaudeAgentSdkQueryRunnerError
583 + >;
584 readonly interrupt: Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
585 readonly close: Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
586 }
@@ -687,6 +721,164 @@ function closeClaudeQuery(queryRuntime: ClaudeQuery) {
721 });
722 }
723
724 +// SDK 0.3.316 types `mcp_call` and `list_permission_rules` but has no Query method for them; its own readMcpResource sends control requests this way.
725 +async function sendClaudeControlRequest(
726 + queryRuntime: ClaudeQuery,
727 + request: {
728 + readonly subtype: "mcp_call" | "list_permission_rules";
729 + readonly [key: string]: unknown;
730 + },
731 +): Promise<unknown> {
732 + const send: unknown = Reflect.get(queryRuntime, "request");
733 + if (typeof send !== "function") {
734 + throw new Error(`This Claude Agent SDK cannot send ${request.subtype}.`);
735 + }
736 + const reply: unknown = await Reflect.apply(send, queryRuntime, [request]);
737 + return Predicate.isObject(reply) ? reply.response : undefined;
738 +}
739 +
740 +const ClaudePermissionRules = Schema.Struct({
741 + state: Schema.Struct({
742 + rules: Schema.Array(
743 + Schema.Struct({
744 + behavior: Schema.Literals(["allow", "deny", "ask"]),
745 + rule: Schema.String,
746 + notInEffect: Schema.optional(Schema.Boolean),
747 + }),
748 + ),
749 + errors: Schema.optional(Schema.Array(Schema.Unknown)),
750 + }),
751 +});
752 +export type ClaudePermissionRule = (typeof ClaudePermissionRules.Type)["state"]["rules"][number];
753 +const decodeClaudePermissionRules = Schema.decodeUnknownEffect(ClaudePermissionRules);
754 +
755 +// Without these, tools carry no `_meta.ui` and a model-shaped result would reach the app.
756 +const CLAUDE_MCP_APP_CAPABILITIES = [
757 + "mcp_tool_ui_meta_v1",
758 + "mcp_read_resource_v1",
759 + "mcp_call_result_not_for_model_v1",
760 +] as const;
761 +// Captured inline, unlike Codex's shared app-server: a slow read delays only this session's stream, and only this long.
762 +const CLAUDE_MCP_APP_CAPTURE_TIMEOUT = "20 seconds";
763 +
764 +function claudeSupportsMcpApps(capabilities: ReadonlySet<string>): boolean {
765 + return CLAUDE_MCP_APP_CAPABILITIES.every((capability) => capabilities.has(capability));
766 +}
767 +
768 +// Claude Code routes `mcp__a__b__tool` to server `a` even when `a__b` is connected, so either prefix is ambiguous.
769 +function claudeMcpServerPrefixOverlaps(
770 + statuses: ReadonlyArray<ClaudeMcpServerStatus>,
771 + server: string,
772 +): boolean {
773 + const prefix = claudeMcpToolPrefix(server);
774 + return statuses.some((status) => {
775 + if (status.name === server) return false;
776 + const other = claudeMcpToolPrefix(status.name);
777 + return other.startsWith(prefix) || prefix.startsWith(other);
778 + });
779 +}
780 +
781 +function findClaudeMcpTool(
782 + statuses: ReadonlyArray<ClaudeMcpServerStatus>,
783 + toolName: string,
784 +):
785 + | { readonly server: string; readonly tool: NonNullable<ClaudeMcpServerStatus["tools"]>[number] }
786 + | undefined {
787 + const matches = statuses.flatMap((status) => {
788 + if (status.status !== "connected") return [];
789 + const prefix = claudeMcpToolPrefix(status.name);
790 + if (!toolName.startsWith(prefix)) return [];
791 + return (status.tools ?? [])
792 + .filter((tool) => `${prefix}${claudeMcpToolNamePart(tool.name)}` === toolName)
793 + .map((tool) => ({ server: status.name, tool }));
794 + });
795 + const [match, ...others] = matches;
796 + return match === undefined ||
797 + others.length > 0 ||
798 + claudeMcpServerPrefixOverlaps(statuses, match.server)
799 + ? undefined
800 + : match;
801 +}
802 +
803 +// Only this adapter writes app references. Claude's normalised tool names cannot tie one in raw MCP output to its server.
804 +function withoutForgedMcpApp(output: ClaudeNativeToolOutput): ClaudeNativeToolOutput {
805 + const value = claudeNativeToolOutputValue(output);
806 + return compactDynamicToolOutput(value)?.[MCP_APP_OUTPUT_KEY] === undefined
807 + ? output
808 + : { type: "structured_tool_use_result", value: { result: value } };
809 +}
810 +
811 +/**
812 + * Deliberately broader than Claude's matcher: Claude also matches rules against server aliases T3
813 + * can't list, and an alias may contain `__`, so any `mcp__` rule or wildcard may cover any MCP tool.
814 + * A false match only refuses a card's call, or asks first.
815 + */
816 +function claudeRulesMayCoverMcpTools(
817 + rules: ReadonlyArray<ClaudePermissionRule>,
818 + behaviors: ReadonlyArray<ClaudePermissionRule["behavior"]>,
819 +): boolean {
820 + return rules.some((entry) => {
821 + const name = entry.rule.split("(", 1)[0] ?? entry.rule;
822 + return (
823 + behaviors.includes(entry.behavior) &&
824 + entry.notInEffect !== true &&
825 + (name.startsWith("mcp__") || name.includes("*"))
826 + );
827 + });
828 +}
829 +
830 +/**
831 + * Claude reports `annotations` as `readOnly`/`destructive`/`openWorld`; apps expect MCP's `*Hint` names.
832 + * Card calls skip Claude's permission check, so `readOnlyHint`, which skips T3's prompt, needs readable
833 + * rules (null when not) with no ask or deny rule that may cover the tool.
834 + */
835 +function claudeMcpToolForApps(
836 + tool: NonNullable<ClaudeMcpServerStatus["tools"]>[number],
837 + rules: ReadonlyArray<ClaudePermissionRule> | null,
838 +) {
839 + const annotations = tool.annotations ?? {};
840 + const readOnlyHint =
841 + annotations.readOnly !== true ||
842 + (rules !== null && !claudeRulesMayCoverMcpTools(rules, ["ask", "deny"]))
843 + ? annotations.readOnly
844 + : undefined;
845 + return {
846 + name: tool.name,
847 + ...(tool.description === undefined ? {} : { description: tool.description }),
848 + // The CLI reports no input schemas; apps require one in `hostContext.toolInfo.tool`.
849 + inputSchema: { type: "object" },
850 + ...(tool._meta === undefined ? {} : { _meta: tool._meta }),
851 + annotations: {
852 + ...(readOnlyHint === undefined ? {} : { readOnlyHint }),
853 + ...(annotations.destructive === undefined
854 + ? {}
855 + : { destructiveHint: annotations.destructive }),
856 + ...(annotations.openWorld === undefined ? {} : { openWorldHint: annotations.openWorld }),
857 + },
858 + };
859 +}
860 +
861 +/** A model-turn MCP `tool_use_result` flattens text `content` to a string; app calls return MCP's raw `CallToolResult`. */
862 +function claudeMcpCallToolResult(
863 + value: unknown,
864 +): ProviderAdapter.ProviderAdapterV2McpCallToolResult {
865 + const record = Predicate.isObject(value) && !Array.isArray(value) ? value : undefined;
866 + const content = record === undefined ? value : record.content;
867 + return {
868 + content:
869 + typeof content === "string"
870 + ? [{ type: "text", text: content }]
871 + : Array.isArray(content)
872 + ? content
873 + : [],
874 + ...(record?.structuredContent === undefined
875 + ? {}
876 + : { structuredContent: record.structuredContent }),
877 + ...(record?.isError === true ? { isError: true } : {}),
878 + ...(record?._meta === undefined ? {} : { _meta: record._meta }),
879 + };
880 +}
881 +
882 // Iterate Query itself: the raw generator's return() queues behind a pending CLI read and deadlocks interruption.
883 export function claudeQueryMessages(queryRuntime: ClaudeQuery): AsyncIterable<SDKMessage, void> {
884 return { [Symbol.asyncIterator]: () => queryRuntime };
@@ -1290,6 +1482,40 @@ export const layerQueryRunner: Layer.Layer<
1482 }),
1483 ),
1484 ),
1485 + mcpServerStatus: Effect.tryPromise({
1486 + try: () => queryRuntime.mcpServerStatus(),
1487 + catch: (cause) => queryRunnerError(cause, "mcpServerStatus"),
1488 + }),
1489 + readMcpResource: ({ server, uri }) =>
1490 + Effect.tryPromise({
1491 + try: () => queryRuntime.readMcpResource(server, uri),
1492 + catch: (cause) => queryRunnerError(cause, "readMcpResource"),
1493 + }),
1494 + callMcpTool: (call) =>
1495 + Effect.tryPromise({
1496 + try: () =>
1497 + sendClaudeControlRequest(queryRuntime, {
1498 + subtype: "mcp_call",
1499 + tool: call.tool,
1500 + arguments: call.arguments,
1501 + result_not_for_model: true,
1502 + }),
1503 + catch: (cause) => queryRunnerError(cause, "callMcpTool"),
1504 + }),
1505 + listPermissionRules: Effect.tryPromise({
1506 + try: () =>
1507 + sendClaudeControlRequest(queryRuntime, { subtype: "list_permission_rules" }),
1508 + catch: (cause) => queryRunnerError(cause, "listPermissionRules"),
1509 + }).pipe(
1510 + Effect.flatMap(decodeClaudePermissionRules),
1511 + // A settings file Claude couldn't parse was skipped, so its rules are missing from the list.
1512 + Effect.filterOrFail(
1513 + ({ state }) => (state.errors ?? []).length === 0,
1514 + ({ state }) => new Error(`Claude skipped ${state.errors?.length} settings file(s)`),
1515 + ),
1516 + Effect.map(({ state }) => state.rules),
1517 + Effect.mapError((cause) => queryRunnerError(cause, "listPermissionRules")),
1518 + ),
1519 interrupt: Effect.tryPromise({
1520 try: () => queryRuntime.interrupt(),
1521 catch: (cause) => queryRunnerError(cause, "interrupt"),
@@ -4194,6 +4420,8 @@ interface ClaudeLiveQueryContext {
4420 // The CLI may fall back from the requested mode on its first init frame.
4421 openedPermissionMode: PermissionMode;
4422 receivedInit: boolean;
4423 + // From system/init; feature-detects control requests such as MCP Apps.
4424 + capabilities: ReadonlySet<string>;
4425 permissionMode: PermissionMode;
4426 stopping: boolean;
4427 readonly subagentsFromEarlierProcesses: ReadonlySet<ActiveClaudeSubagent>;
@@ -7143,6 +7371,107 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
7371 registry: target.toolCalls,
7372 });
7373
7374 + // App requests never start a CLI; they reuse the live process that ran the tool.
7375 + const mcpAppQuery = Effect.fn("ClaudeAdapterV2.mcpAppQuery")(function* (
7376 + providerThread: OrchestrationV2ProviderThread,
7377 + ) {
7378 + const liveQuery = yield* Ref.get(queryContext);
7379 + if (
7380 + liveQuery === null ||
7381 + liveQuery.stopping ||
7382 + liveQuery.nativeThreadId !== providerThread.nativeThreadRef?.nativeId
7383 + ) {
7384 + return yield* new ProviderAdapter.ProviderAdapterSessionStoppedError({
7385 + driver: CLAUDE_PROVIDER,
7386 + });
7387 + }
7388 + if (!claudeSupportsMcpApps(liveQuery.capabilities)) {
7389 + return yield* new ProviderAdapter.ProviderAdapterProtocolError({
7390 + driver: CLAUDE_PROVIDER,
7391 + detail: "This Claude process does not support MCP Apps.",
7392 + });
7393 + }
7394 + return liveQuery;
7395 + });
7396 +
7397 + // Servers can connect after capture, and a forged app reference can name a colliding server.
7398 + const mcpAppServerStatuses = Effect.fn("ClaudeAdapterV2.mcpAppServerStatuses")(function* (
7399 + providerThread: OrchestrationV2ProviderThread,
7400 + server: string,
7401 + ) {
7402 + const liveQuery = yield* mcpAppQuery(providerThread);
7403 + const statuses = yield* liveQuery.query.mcpServerStatus.pipe(
7404 + Effect.mapError(
7405 + (cause) =>
7406 + new ProviderAdapter.ProviderAdapterProtocolError({
7407 + driver: CLAUDE_PROVIDER,
7408 + detail: "Failed to list Claude MCP tools.",
7409 + cause,
7410 + }),
7411 + ),
7412 + );
7413 + if (claudeMcpServerPrefixOverlaps(statuses, server)) {
7414 + return yield* new ProviderAdapter.ProviderAdapterProtocolError({
7415 + driver: CLAUDE_PROVIDER,
7416 + detail: "Another MCP server's tool names overlap this app's server.",
7417 + });
7418 + }
7419 + return { liveQuery, statuses };
7420 + });
7421 +
7422 + /** Reads an app tool's `ui://` document into an attachment; a plain tool row is the fallback. */
7423 + const captureClaudeMcpApp = Effect.fn("ClaudeAdapterV2.captureMcpApp")(
7424 + function* (input: {
7425 + readonly liveQuery: ClaudeLiveQueryContext;
7426 + readonly toolCall: ActiveClaudeToolCall;
7427 + readonly output: ClaudeNativeToolOutput;
7428 + }) {
7429 + const { liveQuery, toolCall } = input;
7430 + if (
7431 + !toolCall.toolName.startsWith("mcp__") ||
7432 + toolCall.toolName.startsWith("mcp__t3-code__") ||
7433 + !claudeSupportsMcpApps(liveQuery.capabilities)
7434 + ) {
7435 + return undefined;
7436 + }
7437 + const match = findClaudeMcpTool(
7438 + yield* liveQuery.query.mcpServerStatus,
7439 + toolCall.toolName,
7440 + );
7441 + const resourceUri = mcpAppToolResourceUri(match?.tool._meta);
7442 + if (match === undefined || resourceUri === undefined) return undefined;
7443 + const { contents } = yield* liveQuery.query.readMcpResource({
7444 + server: match.server,
7445 + uri: resourceUri,
7446 + });
7447 + const reference = yield* snapshotMcpApp({
7448 + attachmentsDir,
7449 + threadId: toolCall.threadId,
7450 + server: match.server,
7451 + tool: match.tool.name,
7452 + resourceUri,
7453 + contents,
7454 + }).pipe(Effect.provideService(FileSystem.FileSystem, fileSystem));
7455 + if (reference === undefined) return undefined;
7456 + return {
7457 + type: "structured_tool_use_result",
7458 + value: {
7459 + [MCP_APP_OUTPUT_KEY]: reference,
7460 + result: claudeMcpCallToolResult(claudeNativeToolOutputValue(input.output)),
7461 + },
7462 + } satisfies ClaudeNativeToolOutput;
7463 + },
7464 + Effect.timeout(CLAUDE_MCP_APP_CAPTURE_TIMEOUT),
7465 + Effect.catchCauseIf(
7466 + (cause) => !Cause.hasInterruptsOnly(cause),
7467 + (cause) =>
7468 + Effect.logWarning("Failed to capture an MCP app; showing a plain tool row.", {
7469 + cause,
7470 + }).pipe(Effect.as(undefined)),
7471 + ),
7472 + Effect.orDie,
7473 + );
7474 +
7475 const settleToolCall = Effect.fnUntraced(function* (input: {
7476 readonly context: ActiveClaudeTurnContext | null;
7477 readonly toolCall: ActiveClaudeToolCall;
@@ -9385,13 +9714,21 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9714 toolInput: EMPTY_CLAUDE_NATIVE_TOOL_INPUT,
9715 parentToolUseId,
9716 }));
9717 + const appOutput =
9718 + parentToolUseId === null &&
9719 + toolCall.runId !== null &&
9720 + !isClaudeToolResultError(toolResult)
9721 + ? yield* captureClaudeMcpApp({ liveQuery, toolCall, output })
9722 + : undefined;
9723 yield* settleToolCall({
9724 context,
9725 toolCall,
9726 registry: toolCallsFor(context, toolCall),
9727 message,
9728 toolResult,
9394 - output,
9729 + output:
9730 + appOutput ??
9731 + (toolCall.toolName.startsWith("mcp__") ? withoutForgedMcpApp(output) : output),
9732 completedAt: yield* DateTime.now,
9733 });
9734 // Subagents write to the session's shared task store, so their
@@ -10590,6 +10927,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
10927 promptEchoMode: "unknown",
10928 openedPermissionMode: queryOptions.permissionMode,
10929 receivedInit: false,
10930 + capabilities: new Set(),
10931 permissionMode: queryOptions.permissionMode,
10932 stopping: false,
10933 handedOffSubagents: new Set(),
@@ -10629,6 +10967,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
10967 context.openedPermissionMode =
10968 message.permissionMode ?? context.openedPermissionMode;
10969 context.receivedInit = true;
10970 + context.capabilities = new Set(message.capabilities ?? []);
10971 }
10972 if (
10973 message.type === "system" &&
@@ -11488,6 +11827,85 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
11827 message: { ...turnInput.message, text: "/compact" },
11828 }),
11829 steerTurn,
11830 + mcpApps: {
11831 + listTools: Effect.fn("ClaudeAdapterV2.listMcpTools")(function* ({
11832 + providerThread,
11833 + server,
11834 + }) {
11835 + const { liveQuery, statuses } = yield* mcpAppServerStatuses(providerThread, server);
11836 + const status = statuses.find((candidate) => candidate.name === server);
11837 + const rules = yield* liveQuery.query.listPermissionRules.pipe(
11838 + Effect.orElseSucceed(() => null),
11839 + );
11840 + return (status?.tools ?? []).map((tool) => claudeMcpToolForApps(tool, rules));
11841 + }),
11842 + callTool: Effect.fn("ClaudeAdapterV2.callMcpTool")(function* (call) {
11843 + const { liveQuery, statuses } = yield* mcpAppServerStatuses(
11844 + call.providerThread,
11845 + call.server,
11846 + );
11847 + const tool = claudeMcpToolName(call.server, call.tool);
11848 + const sameName = (
11849 + statuses.find((status) => status.name === call.server)?.tools ?? []
11850 + ).filter((candidate) => claudeMcpToolName(call.server, candidate.name) === tool);
11851 + // `refresh.weather` and `refresh_weather` reach Claude as one name, so the checked tool may not be the one run.
11852 + if (sameName.length > 1) {
11853 + return yield* new ProviderAdapter.ProviderAdapterProtocolError({
11854 + driver: CLAUDE_PROVIDER,
11855 + detail: "Another tool on this MCP server has the same Claude tool name.",
11856 + });
11857 + }
11858 + // mcp_call skips Claude's permission check, so its deny rules are applied here.
11859 + const rules = yield* liveQuery.query.listPermissionRules.pipe(
11860 + Effect.mapError(
11861 + (cause) =>
11862 + new ProviderAdapter.ProviderAdapterProtocolError({
11863 + driver: CLAUDE_PROVIDER,
11864 + detail: `Claude's permission rules could not be read, so ${tool} was not called.`,
11865 + cause,
11866 + }),
11867 + ),
11868 + );
11869 + if (claudeRulesMayCoverMcpTools(rules, ["deny"])) {
11870 + return yield* new ProviderAdapter.ProviderAdapterProtocolError({
11871 + driver: CLAUDE_PROVIDER,
11872 + detail: `A Claude deny rule may cover ${tool}, so it was not called.`,
11873 + });
11874 + }
11875 + return claudeMcpCallToolResult(
11876 + yield* liveQuery.query
11877 + .callMcpTool({
11878 + tool,
11879 + arguments: call.arguments,
11880 + })
11881 + .pipe(
11882 + Effect.mapError(
11883 + (cause) =>
11884 + new ProviderAdapter.ProviderAdapterProtocolError({
11885 + driver: CLAUDE_PROVIDER,
11886 + detail: "Claude MCP tool call failed.",
11887 + cause,
11888 + }),
11889 + ),
11890 + ),
11891 + );
11892 + }),
11893 + readResource: Effect.fn("ClaudeAdapterV2.readMcpResource")(function* (read) {
11894 + const { liveQuery } = yield* mcpAppServerStatuses(read.providerThread, read.server);
11895 + return yield* liveQuery.query
11896 + .readMcpResource({ server: read.server, uri: read.uri })
11897 + .pipe(
11898 + Effect.mapError(
11899 + (cause) =>
11900 + new ProviderAdapter.ProviderAdapterProtocolError({
11901 + driver: CLAUDE_PROVIDER,
11902 + detail: "Claude MCP resource read failed.",
11903 + cause,
11904 + }),
11905 + ),
11906 + );
11907 + }),
11908 + },
11909 stopTask: Effect.fn("ClaudeAdapterV2.stopTask")(function* ({ providerThread, taskId }) {
11910 const liveQuery = yield* Ref.get(queryContext);
11911 const task = (yield* Ref.get(sessionSubagentsByTaskId)).get(taskId);
apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts
+32
@@ -297,6 +297,38 @@ it.effect("reopens a stalled MCP registration before delivering the resumed prom
297 ),
298 );
299
300 +it.effect.each([
301 + { case: "a readable rule list", errors: undefined, readable: true },
302 + { case: "a settings file Claude skipped", errors: [{ file: "settings.json" }], readable: false },
303 + { case: "a reply without a rule list", response: {}, readable: false },
304 +])("reads Claude's permission rules only when no settings file was skipped: $case", (testCase) =>
305 + Effect.scoped(
306 + Effect.gen(function* () {
307 + const rules = [{ behavior: "deny" as const, rule: "mcp__probe__redeploy" }];
308 + const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(
309 + () =>
310 + ({
311 + close: vi.fn(),
312 + request: async () => ({
313 + response:
314 + "response" in testCase
315 + ? testCase.response
316 + : { state: { rules, errors: testCase.errors } },
317 + }),
318 + }) as unknown as ClaudeSdk.Query,
319 + );
320 + yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
321 + const runner = yield* ClaudeAgentSdkQueryRunner;
322 + const { mcpServers: _mcpServers, ...options } = resumedMcpQueryInput.options;
323 + const session = yield* runner.open({ ...resumedMcpQueryInput, options });
324 + yield* Effect.addFinalizer(() => session.close.pipe(Effect.orDie));
325 + const exit = yield* Effect.exit(session.listPermissionRules);
326 + if (testCase.readable) assert.deepEqual(exit, Exit.succeed(rules));
327 + else assert.isTrue(Exit.isFailure(exit));
328 + }).pipe(Effect.provide(realQueryRunner)),
329 + ),
330 +);
331 +
332 it.effect.each([true, false])("only retries after confirmed process exit: %s", (exits) =>
333 Effect.scoped(
334 Effect.gen(function* () {
apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts
+4
@@ -169,6 +169,10 @@ it.effect.each(deliveries)(
169 applyFlagSettings: () => Effect.void,
170 setPermissionMode: () => Effect.void,
171 backgroundTasks: () => Effect.succeed(false),
172 + mcpServerStatus: Effect.succeed([]),
173 + readMcpResource: () => Effect.die("unexpected MCP resource read"),
174 + callMcpTool: () => Effect.die("unexpected MCP tool call"),
175 + listPermissionRules: Effect.die("unexpected permission rules read"),
176 stopTask: () => Effect.void,
177 interrupt: Effect.die("automatic delivery must never interrupt"),
178 close: Effect.void,
apps/server/src/provider/model-manifest.json
+2 -2
@@ -1,6 +1,6 @@
1 {
2 "version": 1,
3 - "updatedAt": "2026-11-02T21:16:47Z",
3 + "updatedAt": "2026-11-02T23:47:11Z",
4 "compatibility": [
5 {
6 "driver": "codex",
@@ -25,7 +25,7 @@
25 {
26 "driver": "claudeAgent",
27 "t3CodeRange": ">=0.0.42",
28 - "recommendedRange": ">=2.1.280",
28 + "recommendedRange": ">=2.1.301",
29 "ranges": [
30 { "range": ">=2.1.280", "status": "supported" },
31 { "range": ">=2.1.111 <2.1.280", "status": "graceful" },
docs/user/html-renders.md
+1 -1
@@ -10,7 +10,7 @@ Before publishing, agents check their work with screenshots from a small headles
10
11 ## MCP apps
12
13 -Some MCP servers return an interactive app with their tool results, following the [MCP Apps](https://github.com/modelcontextprotocol/ext-apps) standard. When an agent calls one of those tools, the app appears in the thread in place of the tool call, on web, desktop, and mobile. Codex supports this today, for any MCP server you have configured for it; other providers show these calls as ordinary tool calls.
13 +Some MCP servers return an interactive app with their tool results, following the [MCP Apps](https://github.com/modelcontextprotocol/ext-apps) standard. When an agent calls one of those tools, the app appears in the thread in place of the tool call, on web, desktop, and mobile. Codex and Claude support this today, for any MCP server you have configured for them. Claude needs Claude Code 2.1.301 or newer; older versions and other providers show these calls as ordinary tool calls.
14
15 Apps follow your theme. An app can call tools on its own server and post a message to the thread; T3 Code asks first unless the server marks the tool as read-only, and it asks before every message. On mobile, an app also asks before opening a link, and T3 Code asks before saving a file an app offers. An app stays viewable after its agent stops, but using it needs the agent of the thread that created it running, so send a message in that thread first if the app says it is unavailable. An app that navigates away from its own page is stopped.
16
packages/provider-core/src/server/ProviderAdapter.ts
+12
@@ -424,6 +424,15 @@ export class ProviderAdapterProtocolError extends Schema.TaggedError<ProviderAda
424 }
425 }
426
427 +export class ProviderAdapterSessionStoppedError extends Schema.TaggedError<ProviderAdapterSessionStoppedError>()(
428 + "ProviderAdapterSessionStoppedError",
429 + { driver: ProviderDriverKind },
430 +) {
431 + override get message(): string {
432 + return `No running ${this.driver} session owns this thread.`;
433 + }
434 +}
435 +
436 export const ProviderAdapterV2Error = Schema.Union([
437 ProviderAdapterCapabilitiesError,
438 ProviderAdapterOpenSessionError,
@@ -442,6 +451,7 @@ export const ProviderAdapterV2Error = Schema.Union([
451 ProviderAdapterRuntimeRequestResponseError,
452 ProviderAdapterEventStreamError,
453 ProviderAdapterProtocolError,
454 + ProviderAdapterSessionStoppedError,
455 ]);
456 export type ProviderAdapterV2Error = typeof ProviderAdapterV2Error.Type;
457
@@ -557,6 +567,8 @@ export interface ProviderAdapterV2HistoricalContext {
567
568 export interface ProviderAdapterV2McpTool {
569 readonly name: string;
570 + // Apps reject a `hostContext.toolInfo.tool` without one.
571 + readonly inputSchema: unknown;
572 readonly _meta?: unknown;
573 readonly annotations?: unknown;
574 }
packages/shared/src/mcpApp.test.ts
+16
@@ -7,6 +7,7 @@ import {
7 injectMcpAppCookieBootstrap,
8 mcpAppContentSecurityPolicy,
9 mcpAppToolCallableByApp,
10 + mcpAppToolResourceUri,
11 readMcpAppCsp,
12 readMcpAppReference,
13 } from "./mcpApp.ts";
@@ -137,6 +138,14 @@ describe("readMcpAppReference", () => {
138
139 describe("tool metadata", () => {
140 it("reads the resource URI from either spelling and honors app visibility", () => {
141 + const uri = "ui://weather/card.html";
142 + expect(mcpAppToolResourceUri({ ui: { resourceUri: uri } })).toBe(uri);
143 + expect(
144 + mcpAppToolResourceUri({ ui: { visibility: ["model", "app"] }, "ui/resourceUri": uri }),
145 + ).toBe(uri);
146 + expect(
147 + mcpAppToolResourceUri({ ui: { resourceUri: "https://weather/card.html" } }),
148 + ).toBeUndefined();
149 expect(mcpAppToolCallableByApp(undefined)).toBe(true);
150 expect(mcpAppToolCallableByApp({ ui: { visibility: ["model"] } })).toBe(false);
151 expect(mcpAppToolCallableByApp({ ui: { visibility: ["model", "app"] } })).toBe(true);
@@ -170,6 +179,13 @@ describe("mcpAppFromToolItem", () => {
179 };
180 expect(mcpAppFromToolItem({ toolName: "evil.lookup", output: forged })).toBeUndefined();
181 expect(mcpAppFromToolItem({ toolName: "bank.transfer", output: forged })).toBeDefined();
182 + // Claude Code names the same tool `mcp__<server>__<tool>`.
183 + expect(mcpAppFromToolItem({ toolName: "mcp__bank__transfer", output: forged })).toBeDefined();
184 + expect(mcpAppFromToolItem({ toolName: "mcp__evil__transfer", output: forged })).toBeUndefined();
185 + const connector = { t3McpApp: { ...forged.t3McpApp, server: "claude.ai Asana (Beta)" } };
186 + expect(
187 + mcpAppFromToolItem({ toolName: "mcp__claude_ai_Asana_Beta__transfer", output: connector }),
188 + ).toBeDefined();
189 });
190
191 it("keeps an app whose resource URI is longer than a name", async () => {
packages/shared/src/mcpApp.ts
+25
@@ -131,6 +131,31 @@ export function mcpAppReferencesEqual(left: McpAppReference, right: McpAppRefere
131 );
132 }
133
134 +/** Reads a tool's `_meta.ui.resourceUri`, or the deprecated flat `ui/resourceUri`. */
135 +export function mcpAppToolResourceUri(meta: unknown): string | undefined {
136 + if (!Predicate.isObject(meta)) return undefined;
137 + const uri =
138 + (Predicate.isObject(meta.ui) ? meta.ui.resourceUri : undefined) ?? meta["ui/resourceUri"];
139 + return typeof uri === "string" &&
140 + uri.length <= MAX_RESOURCE_URI_LENGTH &&
141 + uri.startsWith(MCP_APP_RESOURCE_SCHEME)
142 + ? uri
143 + : undefined;
144 +}
145 +
146 +export const claudeMcpToolNamePart = (name: string) => name.replace(/[^a-zA-Z0-9_-]/g, "_");
147 +
148 +/** Claude Code's `mcp__<server>__` prefix; it also collapses and trims `_` in `claude.ai ` connector names. */
149 +export function claudeMcpToolPrefix(server: string): string {
150 + const part = claudeMcpToolNamePart(server);
151 + return `mcp__${server.startsWith("claude.ai ") ? part.replace(/_+/g, "_").replace(/^_|_$/g, "") : part}__`;
152 +}
153 +
154 +/** Claude Code names MCP tools `mcp__<server>__<tool>`, replacing characters outside `[a-zA-Z0-9_-]`. */
155 +export function claudeMcpToolName(server: string, tool: string): string {
156 + return `${claudeMcpToolPrefix(server)}${claudeMcpToolNamePart(tool)}`;
157 +}
158 +
159 export function mcpAppToolCallableByApp(meta: unknown): boolean {
160 const visibility =
161 Predicate.isObject(meta) && Predicate.isObject(meta.ui) ? meta.ui.visibility : undefined;
packages/shared/src/toolOutput.ts
+11 -2
@@ -9,7 +9,12 @@ import {
9 readHtmlRenderReference,
10 type HtmlRenderReference,
11 } from "./htmlRender.ts";
12 -import { MCP_APP_OUTPUT_KEY, readMcpAppReference, type McpAppReference } from "./mcpApp.ts";
12 +import {
13 + claudeMcpToolName,
14 + MCP_APP_OUTPUT_KEY,
15 + readMcpAppReference,
16 + type McpAppReference,
17 +} from "./mcpApp.ts";
18 import { resolveT3McpToolId } from "./t3McpToolPresentation.ts";
19
20 const MAX_PARSED_BYTES = 16_384;
@@ -212,7 +217,11 @@ export function mcpAppFromToolItem(item: {
217 readonly output?: unknown;
218 }): McpAppReference | undefined {
219 const app = compactDynamicToolOutput(item.output)?.[MCP_APP_OUTPUT_KEY];
215 - return app !== undefined && item.toolName === `${app.server}.${app.tool}` ? app : undefined;
220 + return app !== undefined &&
221 + (item.toolName === `${app.server}.${app.tool}` ||
222 + item.toolName === claudeMcpToolName(app.server, app.tool))
223 + ? app
224 + : undefined;
225 }
226
227 /** Some providers report completion even when command output describes a failure. */
pnpm-lock.yaml
+6 -6
@@ -823,8 +823,8 @@ importers:
823 apps/server:
824 dependencies:
825 '@anthropic-ai/claude-agent-sdk':
826 - specifier: ^0.3.284
827 - version: 0.3.284(@anthropic-ai/sdk@0.93.0(zod@4.6.5))(@modelcontextprotocol/sdk@1.29.0(supports-color@8.1.1)(zod@4.6.5))(zod@4.6.5)
826 + specifier: ^0.3.316
827 + version: 0.3.316(@anthropic-ai/sdk@0.93.0(zod@4.6.5))(@modelcontextprotocol/sdk@1.29.0(supports-color@8.1.1)(zod@4.6.5))(zod@4.6.5)
828 '@cursor/sdk':
829 specifier: 1.2.0
830 version: 1.2.0(zod@4.6.5)
@@ -2652,9 +2652,9 @@ packages:
2652 vitest:
2653 optional: true
2654
2655 - '@anthropic-ai/claude-agent-sdk@0.3.284':
2656 - resolution: {integrity: sha512-NSoJwEq6nFSf8dtaacYx37QdGgqApI3eHFUlxclMLYi8irb6ZJwEaUnPnLUCyAyg9W/tMkgZC0GXWLRCc01I0w==}
2657 - engines: {node: '>=18.0.0'}
2655 + '@anthropic-ai/claude-agent-sdk@0.3.316':
2656 + resolution: {integrity: sha512-mCMr0que5kIy80JslJub6WFDB2+GYRGWNeVgSZaBpkBwXrr4wnRMnnGHitkA2BEJ5QP5xWyc6YH/6do/edxCWg==}
2657 + engines: {node: '>=18.14.0'}
2658 peerDependencies:
2659 '@anthropic-ai/sdk': '>=0.93.0'
2660 '@modelcontextprotocol/sdk': ^1.29.0
@@ -12457,7 +12457,7 @@ snapshots:
12457 - bufferutil
12458 - utf-8-validate
12459
12460 - '@anthropic-ai/claude-agent-sdk@0.3.284(@anthropic-ai/sdk@0.93.0(zod@4.6.5))(@modelcontextprotocol/sdk@1.29.0(supports-color@8.1.1)(zod@4.6.5))(zod@4.6.5)':
12460 + '@anthropic-ai/claude-agent-sdk@0.3.316(@anthropic-ai/sdk@0.93.0(zod@4.6.5))(@modelcontextprotocol/sdk@1.29.0(supports-color@8.1.1)(zod@4.6.5))(zod@4.6.5)':
12461 dependencies:
12462 '@anthropic-ai/sdk': 0.93.0(zod@4.6.5)
12463 '@modelcontextprotocol/sdk': 1.29.0(supports-color@8.1.1)(zod@4.6.5)