TypeScript
feat(server): render MCP Apps from Claude tool calls (#29803)
Julius Marmingea21d78875269
diff --git a/apps/server/package.json b/apps/server/package.jsonindex 53484dfc12c..c2e711e96cf 100644--- a/apps/server/package.json+++ b/apps/server/package.json@@ -34,7 +34,7 @@"generate:expo-schema": "node scripts/fetch-expo-schema.ts"},"dependencies": {- "@anthropic-ai/claude-agent-sdk": "^0.3.284",+ "@anthropic-ai/claude-agent-sdk": "^0.3.316","@cursor/sdk": "1.2.0","@effect/platform-node": "catalog:","@effect/platform-node-shared": "catalog:",diff --git a/apps/server/src/mcpApps/McpAppRequests.test.ts b/apps/server/src/mcpApps/McpAppRequests.test.tsindex 1fde091c064..8e2c9980112 100644--- a/apps/server/src/mcpApps/McpAppRequests.test.ts+++ b/apps/server/src/mcpApps/McpAppRequests.test.ts@@ -1,4 +1,5 @@import {+ ProviderDriverKind,ProviderSessionId,ProviderThreadId,ThreadId,@@ -14,7 +15,7 @@ import * as Layer from "effect/Layer";import * as Option from "effect/Option";import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";-import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";+import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";import * as ProviderSessionManager from "../orchestration-v2/ProviderSessionManager.ts";import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";import * as McpAppModelContext from "./McpAppModelContext.ts";@@ -137,8 +138,12 @@ describe("McpAppRequests", () => {const mcpApps: ProviderAdapter.ProviderAdapterV2McpApps = {listTools: () =>Effect.succeed([- { name: "refresh", annotations: { readOnlyHint: true } },- { name: "model_only", _meta: { ui: { visibility: ["model"] } } },+ { name: "refresh", inputSchema: { type: "object" }, annotations: { readOnlyHint: true } },+ {+ name: "model_only",+ inputSchema: { type: "object" },+ _meta: { ui: { visibility: ["model"] } },+ },]),callTool: (input) =>Effect.sync(() => {@@ -162,7 +167,11 @@ describe("McpAppRequests", () => {assert.deepEqual(yield* requests.toolInfo({ threadId, itemId, name: "refresh" }), {callable: true,readOnly: true,- tool: { name: "refresh", annotations: { readOnlyHint: true } },+ tool: {+ name: "refresh",+ inputSchema: { type: "object" },+ annotations: { readOnlyHint: true },+ },});}).pipe(Effect.provide(makeLayer({ item: appItem({ t3McpApp: app }), mcpApps }))),);@@ -181,6 +190,31 @@ describe("McpAppRequests", () => {}).pipe(Effect.provide(makeLayer({ item: appItem({ t3McpApp: app }), mcpApps }))),);+ it.effect("reports a provider whose process has stopped as a stopped session", () =>+ Effect.gen(function* () {+ const requests = yield* McpAppRequests.McpAppRequests;+ assert.equal(+ yield* reason(requests.readResource({ threadId, itemId, uri: "ui://weather/app.html" })),+ "session-stopped",+ );+ }).pipe(+ Effect.provide(+ makeLayer({+ item: appItem({ t3McpApp: app }),+ mcpApps: {+ ...mcpApps,+ readResource: () =>+ Effect.fail(+ new ProviderAdapter.ProviderAdapterSessionStoppedError({+ driver: ProviderDriverKind.make("claudeAgent"),+ }),+ ),+ },+ }),+ ),+ ),+ );+it.effect("keeps each app's latest model context, without a live session", () =>Effect.gen(function* () {const requests = yield* McpAppRequests.McpAppRequests;diff --git a/apps/server/src/mcpApps/McpAppRequests.ts b/apps/server/src/mcpApps/McpAppRequests.tsindex 1387cc6b20c..85451566746 100644--- a/apps/server/src/mcpApps/McpAppRequests.ts+++ b/apps/server/src/mcpApps/McpAppRequests.ts@@ -64,6 +64,12 @@ const make = Effect.gen(function* () {const fail = (threadId: ThreadId, reason: McpAppRequestError["reason"], cause?: unknown) =>new McpAppRequestError({ threadId, reason, ...(cause === undefined ? {} : { cause }) });+ const adapterFailure = (threadId: ThreadId) => (cause: ProviderAdapter.ProviderAdapterV2Error) =>+ fail(+ threadId,+ cause._tag === "ProviderAdapterSessionStoppedError" ? "session-stopped" : "request-failed",+ cause,+ );const resolveApp = Effect.fn("McpAppRequests.resolveApp")(function* (input: {readonly threadId: ThreadId;@@ -112,7 +118,7 @@ const make = Effect.gen(function* () {) {const tools = yield* resolved.mcpApps.listTools({ providerThread: resolved.providerThread, server: resolved.app.server })- .pipe(Effect.mapError((cause) => fail(threadId, "request-failed", cause)));+ .pipe(Effect.mapError(adapterFailure(threadId)));return tools.find((tool) => tool.name === name);});@@ -142,7 +148,7 @@ const make = Effect.gen(function* () {tool: input.name,arguments: input.arguments,})- .pipe(Effect.mapError((cause) => fail(input.threadId, "request-failed", cause)));+ .pipe(Effect.mapError(adapterFailure(input.threadId)));});const readResource = Effect.fn("McpAppRequests.readResource")(function* (@@ -155,7 +161,7 @@ const make = Effect.gen(function* () {server: resolved.app.server,uri: input.uri,})- .pipe(Effect.mapError((cause) => fail(input.threadId, "request-failed", cause)));+ .pipe(Effect.mapError(adapterFailure(input.threadId)));});const descendsFrom = Effect.fn("McpAppRequests.descendsFrom")(function* (diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.tsindex 3f771d6abee..bc70c5bf7a1 100644--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts@@ -53,6 +53,7 @@ import {RunId,ThreadId,} from "@t3tools/contracts";+import { mcpAppFromToolItem } from "@t3tools/shared/toolOutput";import { assert, describe, it } from "@effect/vitest";import * as Context from "effect/Context";import * as DateTime from "effect/DateTime";@@ -915,6 +916,10 @@ describe("ClaudeAdapterV2 Auto-accept edits", () => {applyFlagSettings: () => Effect.void,setPermissionMode: () => Effect.void,backgroundTasks: () => Effect.succeed(false),+ mcpServerStatus: Effect.succeed([]),+ readMcpResource: () => Effect.die("unexpected MCP resource read"),+ callMcpTool: () => Effect.die("unexpected MCP tool call"),+ listPermissionRules: Effect.die("unexpected permission rules read"),stopTask: () => Effect.void,interrupt: Effect.void,close: Effect.void,@@ -1037,6 +1042,10 @@ describe("ClaudeAdapterV2 append-system-prompt-file launch argument", () => {applyFlagSettings: () => Effect.void,setPermissionMode: () => Effect.void,backgroundTasks: () => Effect.succeed(false),+ mcpServerStatus: Effect.succeed([]),+ readMcpResource: () => Effect.die("unexpected MCP resource read"),+ callMcpTool: () => Effect.die("unexpected MCP tool call"),+ listPermissionRules: Effect.die("unexpected permission rules read"),stopTask: () => Effect.void,interrupt: Effect.void,close: Effect.void,@@ -1346,6 +1355,10 @@ const captureSdkExecutablePaths = Effect.fn("captureSdkExecutablePaths")(functioapplyFlagSettings: () => Effect.void,setPermissionMode: () => Effect.void,backgroundTasks: () => Effect.succeed(false),+ mcpServerStatus: Effect.succeed([]),+ readMcpResource: () => Effect.die("unexpected MCP resource read"),+ callMcpTool: () => Effect.die("unexpected MCP tool call"),+ listPermissionRules: Effect.die("unexpected permission rules read"),stopTask: () => Effect.void,interrupt: Effect.void,close: Effect.void,@@ -1533,6 +1546,10 @@ describe("ClaudeAdapterV2 resume compaction", () => {applyFlagSettings: () => Effect.void,setPermissionMode: () => Effect.void,backgroundTasks: () => Effect.succeed(false),+ mcpServerStatus: Effect.succeed([]),+ readMcpResource: () => Effect.die("unexpected MCP resource read"),+ callMcpTool: () => Effect.die("unexpected MCP tool call"),+ listPermissionRules: Effect.die("unexpected permission rules read"),stopTask: () => Effect.void,interrupt: Effect.void,close: Effect.void,@@ -1919,6 +1936,10 @@ describe("ClaudeAdapterV2 attachments", () => {applyFlagSettings: () => Effect.void,setPermissionMode: () => Effect.void,backgroundTasks: () => Effect.succeed(false),+ mcpServerStatus: Effect.succeed([]),+ readMcpResource: () => Effect.die("unexpected MCP resource read"),+ callMcpTool: () => Effect.die("unexpected MCP tool call"),+ listPermissionRules: Effect.die("unexpected permission rules read"),stopTask: () => Effect.void,interrupt: Effect.void,close: Queue.shutdown(messages),@@ -2426,6 +2447,10 @@ describe("ClaudeAdapterV2 native fork", () => {applyFlagSettings: () => Effect.void,setPermissionMode: () => Effect.void,backgroundTasks: () => Effect.succeed(false),+ mcpServerStatus: Effect.succeed([]),+ readMcpResource: () => Effect.die("unexpected MCP resource read"),+ callMcpTool: () => Effect.die("unexpected MCP tool call"),+ listPermissionRules: Effect.die("unexpected permission rules read"),stopTask: () => Effect.void,interrupt: Effect.void,close: Effect.void,@@ -2764,6 +2789,10 @@ describe("ClaudeAdapterV2 native session identity", () => {applyFlagSettings: () => Effect.void,setPermissionMode: () => Effect.void,backgroundTasks: () => Effect.succeed(false),+ mcpServerStatus: Effect.succeed([]),+ readMcpResource: () => Effect.die("unexpected MCP resource read"),+ callMcpTool: () => Effect.die("unexpected MCP tool call"),+ listPermissionRules: Effect.die("unexpected permission rules read"),stopTask: () => Effect.void,interrupt: Effect.void,close: Effect.void,@@ -3093,6 +3122,11 @@ describe("ClaudeAdapterV2 background wake turns", () => {readonly backgroundTasks?: (toolUseId: string,) => Effect.Effect<boolean, ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError>;+ readonly mcp?: Pick<+ ClaudeAdapterV2.ClaudeAgentSdkQuerySession,+ "mcpServerStatus" | "readMcpResource" | "callMcpTool"+ > &+ Partial<Pick<ClaudeAdapterV2.ClaudeAgentSdkQuerySession, "listPermissionRules">>;readonly environment?: NodeJS.ProcessEnv;readonly subagentLaunchToolUseId?: string;readonly nativeSessionId?: string;@@ -3215,6 +3249,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {Effect.andThen(() => options?.setPermissionMode?.(mode) ?? Effect.void),),backgroundTasks: options?.backgroundTasks ?? (() => Effect.succeed(false)),+ mcpServerStatus: Effect.succeed([]),+ readMcpResource: () => Effect.die("unexpected MCP resource read"),+ callMcpTool: () => Effect.die("unexpected MCP tool call"),+ listPermissionRules: Effect.die("unexpected permission rules read"),stopTask: options?.stopTask ?? (() => Effect.void),interrupt: Effect.void,close: Queue.shutdown(processMessages),@@ -3242,6 +3280,13 @@ describe("ClaudeAdapterV2 background wake turns", () => {permissionModeChanges.push(mode);}).pipe(Effect.andThen(() => options?.setPermissionMode?.(mode) ?? Effect.void)),backgroundTasks: options?.backgroundTasks ?? (() => Effect.succeed(false)),+ mcpServerStatus: options?.mcp?.mcpServerStatus ?? Effect.succeed([]),+ readMcpResource:+ options?.mcp?.readMcpResource ??+ (() => Effect.die("unexpected MCP resource read")),+ callMcpTool:+ options?.mcp?.callMcpTool ?? (() => Effect.die("unexpected MCP tool call")),+ listPermissionRules: options?.mcp?.listPermissionRules ?? Effect.succeed([]),stopTask: options?.stopTask ?? (() => Effect.void),interrupt: options?.interrupt ?? Effect.void,close: options?.close?.(sdkMessages) ?? Effect.void,@@ -4906,6 +4951,581 @@ describe("ClaudeAdapterV2 background wake turns", () => {),);+ const MCP_APP_CAPABILITIES = [+ "mcp_tool_ui_meta_v1",+ "mcp_read_resource_v1",+ "mcp_call_result_not_for_model_v1",+ ];++ const PROBE_SERVER_STATUS = {+ name: "probe.server",+ status: "connected",+ tools: [+ { name: "show_weather", _meta: { ui: { resourceUri: "ui://probe/weather.html" } } },+ {+ name: "refresh_weather",+ annotations: { readOnly: true, destructive: false },+ _meta: { ui: { visibility: ["app"] } },+ },+ ],+ } satisfies ClaudeSdk.McpServerStatus;++ const runClaudeMcpAppToolTurn = Effect.fnUntraced(function* (+ capabilities: ReadonlyArray<string>,+ overrides?: Partial<+ Pick<+ ClaudeAdapterV2.ClaudeAgentSdkQuerySession,+ "mcpServerStatus" | "readMcpResource" | "listPermissionRules"+ >+ >,+ toolName = "mcp__probe_server__show_weather",+ toolUseResult: unknown = { content: '{"tempC":21}', structuredContent: { tempC: 21 } },+ ) {+ const mcpRequests: Array<unknown> = [];+ const harness = yield* makeWakeHarnessWithOptions({+ mcp: {+ mcpServerStatus: Effect.sync(() => {+ mcpRequests.push("mcpServerStatus");+ return [PROBE_SERVER_STATUS];+ }),+ readMcpResource: ({ server, uri }) =>+ Effect.sync(() => {+ mcpRequests.push({ server, uri });+ return {+ contents: [+ {+ uri,+ mimeType: "text/html;profile=mcp-app",+ text: `<html><body>${server} app</body></html>`,+ },+ ],+ };+ }),+ callMcpTool: (call) =>+ Effect.sync(() => {+ mcpRequests.push(call);+ return { content: [{ type: "text", text: "refreshed" }] };+ }),+ ...overrides,+ },+ });+ yield* harness.runtime.startTurn(+ makeClaudeTestTurnInput({+ threadId: harness.threadId,+ providerThread: harness.providerThread,+ now: yield* DateTime.now,+ attemptId: RunAttemptId.make("mcp-app"),+ text: "Show the weather",+ attachments: [],+ }),+ );+ const id = "weather-app-call";+ yield* harness.offerAndWait(+ claudeSdkFrame({+ type: "system",+ subtype: "init",+ uuid: "mcp-app-init",+ session_id: WAKE_NATIVE_SESSION,+ capabilities,+ }),+ );+ yield* harness.offerAndWait(+ claudeSdkFrame({+ type: "assistant",+ uuid: "mcp-app-assistant",+ session_id: WAKE_NATIVE_SESSION,+ parent_tool_use_id: null,+ message: {+ id: "mcp-app-message",+ type: "message",+ role: "assistant",+ model: "claude-sonnet-4-6",+ content: [+ {+ type: "tool_use",+ id,+ name: toolName,+ input: { city: "Oslo" },+ },+ ],+ },+ }),+ );+ // Shape recorded from Claude Code 2.1.316: content arrives flattened to text.+ yield* harness.offerAndWait(+ claudeSdkFrame({+ type: "user",+ uuid: "mcp-app-result",+ session_id: WAKE_NATIVE_SESSION,+ parent_tool_use_id: null,+ message: {+ role: "user",+ content: [{ type: "tool_result", tool_use_id: id, content: '{"tempC":21}' }],+ },+ tool_use_result: toolUseResult,+ }),+ );+ yield* Queue.offer(+ harness.sdkMessages,+ makeResultFrame({ uuid: "mcp-app-terminal", result: "Shown" }),+ );+ yield* Queue.take(harness.terminalReceipts);+ const item = harness.events+ .flatMap((event) =>+ event.type === "turn_item.updated" && event.turnItem.type === "dynamic_tool"+ ? [event.turnItem]+ : [],+ )+ .at(-1);+ assert.equal(item?.status, "completed");+ return { harness, item: item!, mcpRequests };+ });++ it.effect("renders a Claude MCP tool's ui:// resource as an app and serves its tool calls", () =>+ Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ const { harness, item, mcpRequests } = yield* runClaudeMcpAppToolTurn(MCP_APP_CAPABILITIES);+ const app = mcpAppFromToolItem(item);+ assert.deepInclude(app, {+ server: "probe.server",+ tool: "show_weather",+ resourceUri: "ui://probe/weather.html",+ });+ assert.deepEqual((item.output as { readonly result?: unknown }).result, {+ content: [{ type: "text", text: '{"tempC":21}' }],+ structuredContent: { tempC: 21 },+ });+ const html = yield* fileSystem.readFileString(+ `${harness.attachmentsDir}/${app?.attachmentId}.html`,+ );+ assert.include(html, "probe.server app");++ const mcpApps = harness.runtime.mcpApps;+ if (mcpApps === undefined) throw new Error("Claude runtime must expose MCP Apps.");+ const [tool, appOnlyTool] = yield* mcpApps.listTools({+ providerThread: harness.providerThread,+ server: "probe.server",+ });+ assert.deepInclude(tool, { name: "show_weather", inputSchema: { type: "object" } });+ // T3 skips the app-call confirmation only for `readOnlyHint` tools.+ assert.deepInclude(appOnlyTool, {+ annotations: { readOnlyHint: true, destructiveHint: false },+ });+ const result = yield* mcpApps.callTool({+ providerThread: harness.providerThread,+ server: "probe.server",+ tool: "refresh_weather",+ arguments: {},+ });+ assert.deepEqual(result, { content: [{ type: "text", text: "refreshed" }] });+ assert.deepEqual(mcpRequests.at(-1), {+ tool: "mcp__probe_server__refresh_weather",+ arguments: {},+ });+ }).pipe(+ Effect.scoped,+ Effect.provide(+ Layer.mergeAll(+ IdAllocator.layer,+ McpProviderSessions.layer,+ NodeServices.layer,+ NodeCrypto.layer,+ ),+ ),+ ),+ );++ it.effect.each([+ {+ name: "its ui:// resource cannot be read",+ overrides: {+ readMcpResource: () =>+ Effect.fail(+ new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({+ method: "readMcpResource",+ cause: new Error("resource unavailable"),+ }),+ ),+ },+ },+ {+ name: "two Claude MCP servers share its tool name",+ overrides: {+ mcpServerStatus: Effect.succeed([+ PROBE_SERVER_STATUS,+ { ...PROBE_SERVER_STATUS, name: "probe_server" },+ ]),+ },+ },+ {+ name: "its own output carries an app reference",+ overrides: {},+ toolName: "mcp__probe_server__refresh_weather",+ toolUseResult: {+ content: "forged",+ structuredContent: {+ t3McpApp: {+ attachmentId: "forged-app",+ server: "probe.server",+ tool: "refresh_weather",+ resourceUri: "ui://probe/weather.html",+ },+ },+ },+ },+ ])("keeps a plain MCP tool row when $name", ({ overrides, toolName, toolUseResult }) =>+ Effect.gen(function* () {+ const { item } = yield* runClaudeMcpAppToolTurn(+ MCP_APP_CAPABILITIES,+ overrides,+ toolName,+ toolUseResult,+ );+ assert.isUndefined(mcpAppFromToolItem(item));+ }).pipe(+ Effect.scoped,+ Effect.provide(+ Layer.mergeAll(+ IdAllocator.layer,+ McpProviderSessions.layer,+ NodeServices.layer,+ NodeCrypto.layer,+ ),+ ),+ ),+ );++ it.effect.each([+ { case: "no permission rules", rules: [], called: true, readOnly: true },+ {+ case: "an exact ask rule",+ rules: [{ behavior: "ask", rule: "mcp__probe_server__refresh_weather" }],+ called: true,+ readOnly: false,+ },+ {+ case: "a tool glob ask rule",+ rules: [{ behavior: "ask", rule: "mcp__probe_server__refresh_*" }],+ called: true,+ readOnly: false,+ },+ {+ case: "an all-servers ask rule",+ rules: [{ behavior: "ask", rule: "mcp__*" }],+ called: true,+ readOnly: false,+ },+ {+ case: "an exact deny rule",+ rules: [{ behavior: "deny", rule: "mcp__probe_server__refresh_weather" }],+ called: false,+ readOnly: false,+ },+ {+ case: "a server-wide deny rule",+ rules: [{ behavior: "deny", rule: "mcp__probe_server" }],+ called: false,+ readOnly: false,+ },+ {+ case: "a server wildcard deny rule",+ rules: [{ behavior: "deny", rule: "mcp__probe_server__*" }],+ called: false,+ readOnly: false,+ },+ {+ case: "a deny rule with a server-part wildcard",+ rules: [{ behavior: "deny", rule: "mcp__*__refresh_weather" }],+ called: false,+ readOnly: false,+ },+ {+ case: "a deny rule naming a prefix of the server's name",+ rules: [{ behavior: "deny", rule: "mcp__probe" }],+ called: false,+ readOnly: false,+ },+ {+ case: "a deny rule for this tool on a server alias T3 can't list",+ rules: [{ behavior: "deny", rule: "mcp__probe_alias__refresh_weather" }],+ called: false,+ readOnly: false,+ },+ {+ case: "a server-wide deny rule for a server whose name contains __",+ rules: [{ behavior: "deny", rule: "mcp__finance__prod" }],+ server: "finance__prod",+ called: false,+ readOnly: false,+ },+ {+ case: "a deny rule naming the first part of a tool name containing __",+ rules: [{ behavior: "deny", rule: "mcp__gw_example_com__refresh" }],+ tool: "refresh__weather",+ called: false,+ readOnly: false,+ },+ {+ case: "a deny rule whose server wildcard spans part of a tool name containing __",+ rules: [{ behavior: "deny", rule: "mcp__gw*__weather" }],+ tool: "refresh__weather",+ called: false,+ readOnly: false,+ },+ {+ case: "a deny rule with a parenthesized specifier",+ rules: [{ behavior: "deny", rule: "mcp__probe_server__refresh_weather(city:Oslo)" }],+ called: false,+ readOnly: false,+ },+ {+ case: "a deny rule a managed policy switched off",+ rules: [+ { behavior: "deny", rule: "mcp__probe_server__refresh_weather", notInEffect: true },+ { behavior: "ask", rule: "mcp__probe_server", notInEffect: true },+ ],+ called: true,+ readOnly: true,+ },+ {+ case: "a server-wide deny rule for an alias containing __",+ rules: [{ behavior: "deny", rule: "mcp__finance__prod" }],+ called: false,+ readOnly: false,+ },+ {+ case: "a deny rule for this tool on an alias containing __",+ rules: [{ behavior: "deny", rule: "mcp__finance__prod__refresh_weather" }],+ called: false,+ readOnly: false,+ },+ {+ case: "an ask rule naming another tool, which may be a server-wide alias rule",+ rules: [{ behavior: "ask", rule: "mcp__probe_server__refresh" }],+ called: true,+ readOnly: false,+ },+ {+ case: "a deny wildcard that may match only a server alias",+ rules: [{ behavior: "deny", rule: "*notion*" }],+ called: false,+ readOnly: false,+ },+ {+ case: "an ask rule for every tool",+ rules: [{ behavior: "ask", rule: "*" }],+ called: true,+ readOnly: false,+ },+ {+ case: "rules that cannot cover an MCP tool",+ rules: [+ { behavior: "ask", rule: "Bash" },+ { behavior: "deny", rule: "Read(./secrets/**)" },+ { behavior: "allow", rule: "mcp__probe_server__refresh_weather" },+ ],+ called: true,+ readOnly: true,+ },+ {+ case: "permission rules that cannot be read",+ rules: "unreadable",+ called: false,+ readOnly: false,+ },+ ] as const)("applies Claude's permission rules to MCP app calls with $case", (testCase) =>+ Effect.gen(function* () {+ const server = "server" in testCase ? testCase.server : PROBE_SERVER_STATUS.name;+ const tool = "tool" in testCase ? testCase.tool : "refresh_weather";+ const { harness, mcpRequests } = yield* runClaudeMcpAppToolTurn(MCP_APP_CAPABILITIES, {+ mcpServerStatus: Effect.succeed([+ {+ ...PROBE_SERVER_STATUS,+ name: server,+ tools: [{ ...PROBE_SERVER_STATUS.tools[1], name: tool }],+ },+ ]),+ listPermissionRules:+ testCase.rules === "unreadable"+ ? Effect.fail(+ new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({+ method: "listPermissionRules",+ cause: new Error("Unsupported control request subtype"),+ }),+ )+ : Effect.succeed(testCase.rules),+ });+ const mcpApps = harness.runtime.mcpApps!;+ const target = { providerThread: harness.providerThread, server };+ const [listed] = yield* mcpApps.listTools(target);+ assert.deepEqual(+ listed?.annotations,+ testCase.readOnly+ ? { readOnlyHint: true, destructiveHint: false }+ : { destructiveHint: false },+ );+ const exit = yield* Effect.exit(mcpApps.callTool({ ...target, tool, arguments: {} }));+ assert.equal(Exit.isSuccess(exit), testCase.called);+ assert.equal(+ mcpRequests.some(+ (request) => typeof request === "object" && request !== null && "arguments" in request,+ ),+ testCase.called,+ );+ }).pipe(+ Effect.scoped,+ Effect.provide(+ Layer.mergeAll(+ IdAllocator.layer,+ McpProviderSessions.layer,+ NodeServices.layer,+ NodeCrypto.layer,+ ),+ ),+ ),+ );++ it.effect("refuses app requests Claude Code could route to an overlapping server", () =>+ Effect.gen(function* () {+ // Claude Code 2.1.303 runs `mcp__probe__server__refresh_weather` on `probe`.+ const { harness, item, mcpRequests } = yield* runClaudeMcpAppToolTurn(+ MCP_APP_CAPABILITIES,+ {+ mcpServerStatus: Effect.succeed([+ { ...PROBE_SERVER_STATUS, name: "probe__server" },+ {+ name: "probe",+ status: "connected",+ tools: [{ name: "refresh_weather", _meta: { ui: { visibility: ["app"] } } }],+ },+ ]),+ },+ "mcp__probe__server__show_weather",+ );+ assert.isUndefined(mcpAppFromToolItem(item));+ const callExit = yield* Effect.exit(+ harness.runtime.mcpApps!.callTool({+ providerThread: harness.providerThread,+ server: "probe__server",+ tool: "refresh_weather",+ arguments: {},+ }),+ );+ // A forged app reference may name either overlapping server.+ const readExit = yield* Effect.exit(+ harness.runtime.mcpApps!.readResource({+ providerThread: harness.providerThread,+ server: "probe",+ uri: "ui://probe/weather.html",+ }),+ );+ assert.isTrue(Exit.isFailure(callExit));+ assert.isTrue(Exit.isFailure(readExit));+ assert.deepEqual(mcpRequests, []);+ }).pipe(+ Effect.scoped,+ Effect.provide(+ Layer.mergeAll(+ IdAllocator.layer,+ McpProviderSessions.layer,+ NodeServices.layer,+ NodeCrypto.layer,+ ),+ ),+ ),+ );++ it.effect("refuses an app call whose Claude tool name matches two tools on its server", () =>+ Effect.gen(function* () {+ const { harness, mcpRequests } = yield* runClaudeMcpAppToolTurn(MCP_APP_CAPABILITIES, {+ mcpServerStatus: Effect.succeed([+ {+ ...PROBE_SERVER_STATUS,+ tools: [+ ...PROBE_SERVER_STATUS.tools,+ { name: "refresh.weather", _meta: { ui: { visibility: ["app"] } } },+ ],+ },+ ]),+ });+ const exit = yield* Effect.exit(+ harness.runtime.mcpApps!.callTool({+ providerThread: harness.providerThread,+ server: "probe.server",+ tool: "refresh_weather",+ arguments: {},+ }),+ );+ assert.isTrue(Exit.isFailure(exit));+ assert.notDeepInclude(mcpRequests, {+ tool: "mcp__probe_server__refresh_weather",+ arguments: {},+ });+ }).pipe(+ Effect.scoped,+ Effect.provide(+ Layer.mergeAll(+ IdAllocator.layer,+ McpProviderSessions.layer,+ NodeServices.layer,+ NodeCrypto.layer,+ ),+ ),+ ),+ );++ it.effect("keeps a plain MCP tool row when reading its ui:// resource times out", () =>+ Effect.gen(function* () {+ const reading = yield* Deferred.make<void>();+ const turn = yield* runClaudeMcpAppToolTurn(MCP_APP_CAPABILITIES, {+ readMcpResource: () =>+ Deferred.succeed(reading, undefined).pipe(Effect.andThen(Effect.never)),+ }).pipe(Effect.forkChild);+ yield* Deferred.await(reading);+ yield* TestClock.adjust("21 seconds");+ const { item } = yield* Fiber.join(turn);+ assert.isUndefined(mcpAppFromToolItem(item));+ }).pipe(+ Effect.scoped,+ Effect.provide(+ Layer.mergeAll(+ IdAllocator.layer,+ McpProviderSessions.layer,+ NodeServices.layer,+ NodeCrypto.layer,+ ),+ ),+ ),+ );++ it.effect("keeps a plain MCP tool row when the Claude CLI lacks MCP Apps support", () =>+ Effect.gen(function* () {+ const { harness, item, mcpRequests } = yield* runClaudeMcpAppToolTurn([]);+ assert.isUndefined(mcpAppFromToolItem(item));+ assert.deepEqual(mcpRequests, []);+ const exit = yield* Effect.exit(+ harness.runtime.mcpApps!.callTool({+ providerThread: harness.providerThread,+ server: "probe.server",+ tool: "refresh_weather",+ arguments: {},+ }),+ );+ assert.isTrue(Exit.isFailure(exit));+ assert.deepEqual(mcpRequests, []);+ }).pipe(+ Effect.scoped,+ Effect.provide(+ Layer.mergeAll(+ IdAllocator.layer,+ McpProviderSessions.layer,+ NodeServices.layer,+ NodeCrypto.layer,+ ),+ ),+ ),+ );+it.effect.each([{content: { type: "advisor_tool_result_error", error_code: "overloaded" },@@ -9756,6 +10376,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {applyFlagSettings: () => Effect.void,setPermissionMode: () => Effect.void,backgroundTasks: () => Effect.succeed(false),+ mcpServerStatus: Effect.succeed([]),+ readMcpResource: () => Effect.die("unexpected MCP resource read"),+ callMcpTool: () => Effect.die("unexpected MCP tool call"),+ listPermissionRules: Effect.die("unexpected permission rules read"),stopTask: () => Effect.void,interrupt: Effect.void,close: isFirstProcess@@ -9953,6 +10577,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {applyFlagSettings: () => Effect.void,setPermissionMode: () => Effect.void,backgroundTasks: () => Effect.succeed(false),+ mcpServerStatus: Effect.succeed([]),+ readMcpResource: () => Effect.die("unexpected MCP resource read"),+ callMcpTool: () => Effect.die("unexpected MCP tool call"),+ listPermissionRules: Effect.die("unexpected permission rules read"),stopTask: () => Effect.void,interrupt: Effect.void,close: Queue.shutdown(queue),@@ -12154,6 +12782,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {setPermissionMode: () => Effect.void,backgroundTasks: () => Effect.succeed(false),stopTask: () => Effect.void,+ mcpServerStatus: Effect.die("unexpected MCP server status"),+ readMcpResource: () => Effect.die("unexpected MCP resource read"),+ callMcpTool: () => Effect.die("unexpected MCP tool call"),+ listPermissionRules: Effect.die("unexpected permission rules read"),interrupt: Effect.void,close:closeSignal === undefined@@ -15020,6 +15652,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {applyFlagSettings: () => Effect.void,setPermissionMode: () => Effect.void,backgroundTasks: () => Effect.succeed(false),+ mcpServerStatus: Effect.succeed([]),+ readMcpResource: () => Effect.die("unexpected MCP resource read"),+ callMcpTool: () => Effect.die("unexpected MCP tool call"),+ listPermissionRules: Effect.die("unexpected permission rules read"),stopTask: () => Effect.void,interrupt: Effect.void,close: Queue.shutdown(sdkMessages),@@ -15194,6 +15830,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {applyFlagSettings: () => Effect.void,setPermissionMode: () => Effect.void,backgroundTasks: () => Effect.succeed(false),+ mcpServerStatus: Effect.succeed([]),+ readMcpResource: () => Effect.die("unexpected MCP resource read"),+ callMcpTool: () => Effect.die("unexpected MCP tool call"),+ listPermissionRules: Effect.die("unexpected permission rules read"),stopTask: () => Effect.void,interrupt: Effect.void,close: Queue.shutdown(sdkMessages),@@ -15371,6 +16011,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {applyFlagSettings: () => Effect.void,setPermissionMode: () => Effect.void,backgroundTasks: () => Effect.succeed(false),+ mcpServerStatus: Effect.succeed([]),+ readMcpResource: () => Effect.die("unexpected MCP resource read"),+ callMcpTool: () => Effect.die("unexpected MCP tool call"),+ listPermissionRules: Effect.die("unexpected permission rules read"),stopTask: () => Effect.void,interrupt: Effect.void,close: Queue.shutdown(sdkMessages),@@ -15566,6 +16210,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {applyFlagSettings: () => Effect.void,setPermissionMode: () => Effect.void,backgroundTasks: () => Effect.succeed(false),+ mcpServerStatus: Effect.succeed([]),+ readMcpResource: () => Effect.die("unexpected MCP resource read"),+ callMcpTool: () => Effect.die("unexpected MCP tool call"),+ listPermissionRules: Effect.die("unexpected permission rules read"),stopTask: () => Effect.void,interrupt: Effect.void,close: Effect.sync(() => {@@ -15709,6 +16357,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {applyFlagSettings: () => Effect.void,setPermissionMode: () => Effect.void,backgroundTasks: () => Effect.succeed(false),+ mcpServerStatus: Effect.succeed([]),+ readMcpResource: () => Effect.die("unexpected MCP resource read"),+ callMcpTool: () => Effect.die("unexpected MCP tool call"),+ listPermissionRules: Effect.die("unexpected permission rules read"),stopTask: () => Effect.void,interrupt: Effect.void,close: Queue.shutdown(sdkMessages),diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.tsindex 3926be5e180..923aa7de509 100644--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts@@ -845,6 +845,11 @@ function makeReplayQueryRunner(replayEffect(() => {assertNextOutboundFrame({ type: "query.background_tasks", toolUseId });}).pipe(Effect.as(true)),+ // Recorded CLIs predate MCP Apps capabilities, so replays never reach these.+ mcpServerStatus: Effect.die("unexpected MCP server status in replay"),+ readMcpResource: () => Effect.die("unexpected MCP resource read in replay"),+ callMcpTool: () => Effect.die("unexpected MCP tool call in replay"),+ listPermissionRules: Effect.die("unexpected permission rules read in replay"),interrupt: replayEffect(() => {assertNextOutboundFrame({ type: "query.interrupt" });}),diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.tsindex 98c920f5053..a3dea196ed3 100644--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts@@ -1,5 +1,9 @@import * as DocumentText from "../../provider/DocumentText.ts";-import { mcpToolResultOutput, toolOutputImages } from "@t3tools/shared/toolOutput";+import {+ compactDynamicToolOutput,+ mcpToolResultOutput,+ toolOutputImages,+} from "@t3tools/shared/toolOutput";import { makeProviderTextDeltaCoalescer } from "./ProviderTextDeltaCoalescer.ts";import { claudeTaskOutputRoot, tailClaudeTaskOutput } from "./ClaudeTaskOutputTail.ts";import {@@ -43,6 +47,7 @@ import {getSessionMessages,getSubagentMessages,type HookCallback,+ type McpServerStatus as ClaudeMcpServerStatus,query,resolveSettings as resolveClaudeSettings,type Options as ClaudeQueryOptions,@@ -69,6 +74,13 @@ import * as NodeChildProcess from "node:child_process";import * as NodeUtil from "node:util";import { parseCliArgs } from "@t3tools/shared/cliArgs";import { fromLenientJson } from "@t3tools/shared/schemaJson";+import {+ claudeMcpToolName,+ claudeMcpToolNamePart,+ claudeMcpToolPrefix,+ MCP_APP_OUTPUT_KEY,+ mcpAppToolResourceUri,+} from "@t3tools/shared/mcpApp";import { AgentScope } from "@t3tools/shared/AgentScope";import * as HostProcess from "@t3tools/shared/HostProcess";import { applyClaudePromptEffortPrefix } from "@t3tools/shared/model";@@ -120,6 +132,7 @@ import {import { FILE_HEADERS_ONLY, formatPatch, structuredPatch } from "diff";import * as Cause from "effect/Cause";+import * as Predicate from "effect/Predicate";import * as Clock from "effect/Clock";import * as Context from "effect/Context";import * as SecureRandom from "effect/crypto/SecureRandom";@@ -143,6 +156,7 @@ import * as ChildProcess from "effect/process/ChildProcess";import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";import { resolveAttachmentPath } from "../../attachmentStore.ts";+import { snapshotMcpApp } from "../../mcpApps/McpAppSnapshot.ts";import { resolveClaudeSdkExecutablePath } from "../../provider/Drivers/ClaudeExecutable.ts";import {planClaudeSkillDispatch,@@ -547,6 +561,26 @@ export interface ClaudeAgentSdkQuerySession {readonly backgroundTasks: (toolUseId: string,) => Effect.Effect<boolean, ClaudeAgentSdkQueryRunnerError>;+ readonly mcpServerStatus: Effect.Effect<+ ReadonlyArray<ClaudeMcpServerStatus>,+ ClaudeAgentSdkQueryRunnerError+ >;+ readonly readMcpResource: (input: {+ readonly server: string;+ readonly uri: string;+ }) => Effect.Effect<+ { readonly contents: ReadonlyArray<unknown> },+ ClaudeAgentSdkQueryRunnerError+ >;+ /** Runs an MCP tool without a model turn and returns the server's raw `CallToolResult`. */+ readonly callMcpTool: (input: {+ readonly tool: string;+ readonly arguments: Record<string, unknown>;+ }) => Effect.Effect<unknown, ClaudeAgentSdkQueryRunnerError>;+ readonly listPermissionRules: Effect.Effect<+ ReadonlyArray<ClaudePermissionRule>,+ ClaudeAgentSdkQueryRunnerError+ >;readonly interrupt: Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;readonly close: Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;}@@ -687,6 +721,164 @@ function closeClaudeQuery(queryRuntime: ClaudeQuery) {});}+// 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.+async function sendClaudeControlRequest(+ queryRuntime: ClaudeQuery,+ request: {+ readonly subtype: "mcp_call" | "list_permission_rules";+ readonly [key: string]: unknown;+ },+): Promise<unknown> {+ const send: unknown = Reflect.get(queryRuntime, "request");+ if (typeof send !== "function") {+ throw new Error(`This Claude Agent SDK cannot send ${request.subtype}.`);+ }+ const reply: unknown = await Reflect.apply(send, queryRuntime, [request]);+ return Predicate.isObject(reply) ? reply.response : undefined;+}++const ClaudePermissionRules = Schema.Struct({+ state: Schema.Struct({+ rules: Schema.Array(+ Schema.Struct({+ behavior: Schema.Literals(["allow", "deny", "ask"]),+ rule: Schema.String,+ notInEffect: Schema.optional(Schema.Boolean),+ }),+ ),+ errors: Schema.optional(Schema.Array(Schema.Unknown)),+ }),+});+export type ClaudePermissionRule = (typeof ClaudePermissionRules.Type)["state"]["rules"][number];+const decodeClaudePermissionRules = Schema.decodeUnknownEffect(ClaudePermissionRules);++// Without these, tools carry no `_meta.ui` and a model-shaped result would reach the app.+const CLAUDE_MCP_APP_CAPABILITIES = [+ "mcp_tool_ui_meta_v1",+ "mcp_read_resource_v1",+ "mcp_call_result_not_for_model_v1",+] as const;+// Captured inline, unlike Codex's shared app-server: a slow read delays only this session's stream, and only this long.+const CLAUDE_MCP_APP_CAPTURE_TIMEOUT = "20 seconds";++function claudeSupportsMcpApps(capabilities: ReadonlySet<string>): boolean {+ return CLAUDE_MCP_APP_CAPABILITIES.every((capability) => capabilities.has(capability));+}++// Claude Code routes `mcp__a__b__tool` to server `a` even when `a__b` is connected, so either prefix is ambiguous.+function claudeMcpServerPrefixOverlaps(+ statuses: ReadonlyArray<ClaudeMcpServerStatus>,+ server: string,+): boolean {+ const prefix = claudeMcpToolPrefix(server);+ return statuses.some((status) => {+ if (status.name === server) return false;+ const other = claudeMcpToolPrefix(status.name);+ return other.startsWith(prefix) || prefix.startsWith(other);+ });+}++function findClaudeMcpTool(+ statuses: ReadonlyArray<ClaudeMcpServerStatus>,+ toolName: string,+):+ | { readonly server: string; readonly tool: NonNullable<ClaudeMcpServerStatus["tools"]>[number] }+ | undefined {+ const matches = statuses.flatMap((status) => {+ if (status.status !== "connected") return [];+ const prefix = claudeMcpToolPrefix(status.name);+ if (!toolName.startsWith(prefix)) return [];+ return (status.tools ?? [])+ .filter((tool) => `${prefix}${claudeMcpToolNamePart(tool.name)}` === toolName)+ .map((tool) => ({ server: status.name, tool }));+ });+ const [match, ...others] = matches;+ return match === undefined ||+ others.length > 0 ||+ claudeMcpServerPrefixOverlaps(statuses, match.server)+ ? undefined+ : match;+}++// Only this adapter writes app references. Claude's normalised tool names cannot tie one in raw MCP output to its server.+function withoutForgedMcpApp(output: ClaudeNativeToolOutput): ClaudeNativeToolOutput {+ const value = claudeNativeToolOutputValue(output);+ return compactDynamicToolOutput(value)?.[MCP_APP_OUTPUT_KEY] === undefined+ ? output+ : { type: "structured_tool_use_result", value: { result: value } };+}++/**+ * Deliberately broader than Claude's matcher: Claude also matches rules against server aliases T3+ * can't list, and an alias may contain `__`, so any `mcp__` rule or wildcard may cover any MCP tool.+ * A false match only refuses a card's call, or asks first.+ */+function claudeRulesMayCoverMcpTools(+ rules: ReadonlyArray<ClaudePermissionRule>,+ behaviors: ReadonlyArray<ClaudePermissionRule["behavior"]>,+): boolean {+ return rules.some((entry) => {+ const name = entry.rule.split("(", 1)[0] ?? entry.rule;+ return (+ behaviors.includes(entry.behavior) &&+ entry.notInEffect !== true &&+ (name.startsWith("mcp__") || name.includes("*"))+ );+ });+}++/**+ * Claude reports `annotations` as `readOnly`/`destructive`/`openWorld`; apps expect MCP's `*Hint` names.+ * Card calls skip Claude's permission check, so `readOnlyHint`, which skips T3's prompt, needs readable+ * rules (null when not) with no ask or deny rule that may cover the tool.+ */+function claudeMcpToolForApps(+ tool: NonNullable<ClaudeMcpServerStatus["tools"]>[number],+ rules: ReadonlyArray<ClaudePermissionRule> | null,+) {+ const annotations = tool.annotations ?? {};+ const readOnlyHint =+ annotations.readOnly !== true ||+ (rules !== null && !claudeRulesMayCoverMcpTools(rules, ["ask", "deny"]))+ ? annotations.readOnly+ : undefined;+ return {+ name: tool.name,+ ...(tool.description === undefined ? {} : { description: tool.description }),+ // The CLI reports no input schemas; apps require one in `hostContext.toolInfo.tool`.+ inputSchema: { type: "object" },+ ...(tool._meta === undefined ? {} : { _meta: tool._meta }),+ annotations: {+ ...(readOnlyHint === undefined ? {} : { readOnlyHint }),+ ...(annotations.destructive === undefined+ ? {}+ : { destructiveHint: annotations.destructive }),+ ...(annotations.openWorld === undefined ? {} : { openWorldHint: annotations.openWorld }),+ },+ };+}++/** A model-turn MCP `tool_use_result` flattens text `content` to a string; app calls return MCP's raw `CallToolResult`. */+function claudeMcpCallToolResult(+ value: unknown,+): ProviderAdapter.ProviderAdapterV2McpCallToolResult {+ const record = Predicate.isObject(value) && !Array.isArray(value) ? value : undefined;+ const content = record === undefined ? value : record.content;+ return {+ content:+ typeof content === "string"+ ? [{ type: "text", text: content }]+ : Array.isArray(content)+ ? content+ : [],+ ...(record?.structuredContent === undefined+ ? {}+ : { structuredContent: record.structuredContent }),+ ...(record?.isError === true ? { isError: true } : {}),+ ...(record?._meta === undefined ? {} : { _meta: record._meta }),+ };+}+// Iterate Query itself: the raw generator's return() queues behind a pending CLI read and deadlocks interruption.export function claudeQueryMessages(queryRuntime: ClaudeQuery): AsyncIterable<SDKMessage, void> {return { [Symbol.asyncIterator]: () => queryRuntime };@@ -1290,6 +1482,40 @@ export const layerQueryRunner: Layer.Layer<}),),),+ mcpServerStatus: Effect.tryPromise({+ try: () => queryRuntime.mcpServerStatus(),+ catch: (cause) => queryRunnerError(cause, "mcpServerStatus"),+ }),+ readMcpResource: ({ server, uri }) =>+ Effect.tryPromise({+ try: () => queryRuntime.readMcpResource(server, uri),+ catch: (cause) => queryRunnerError(cause, "readMcpResource"),+ }),+ callMcpTool: (call) =>+ Effect.tryPromise({+ try: () =>+ sendClaudeControlRequest(queryRuntime, {+ subtype: "mcp_call",+ tool: call.tool,+ arguments: call.arguments,+ result_not_for_model: true,+ }),+ catch: (cause) => queryRunnerError(cause, "callMcpTool"),+ }),+ listPermissionRules: Effect.tryPromise({+ try: () =>+ sendClaudeControlRequest(queryRuntime, { subtype: "list_permission_rules" }),+ catch: (cause) => queryRunnerError(cause, "listPermissionRules"),+ }).pipe(+ Effect.flatMap(decodeClaudePermissionRules),+ // A settings file Claude couldn't parse was skipped, so its rules are missing from the list.+ Effect.filterOrFail(+ ({ state }) => (state.errors ?? []).length === 0,+ ({ state }) => new Error(`Claude skipped ${state.errors?.length} settings file(s)`),+ ),+ Effect.map(({ state }) => state.rules),+ Effect.mapError((cause) => queryRunnerError(cause, "listPermissionRules")),+ ),interrupt: Effect.tryPromise({try: () => queryRuntime.interrupt(),catch: (cause) => queryRunnerError(cause, "interrupt"),@@ -4194,6 +4420,8 @@ interface ClaudeLiveQueryContext {// The CLI may fall back from the requested mode on its first init frame.openedPermissionMode: PermissionMode;receivedInit: boolean;+ // From system/init; feature-detects control requests such as MCP Apps.+ capabilities: ReadonlySet<string>;permissionMode: PermissionMode;stopping: boolean;readonly subagentsFromEarlierProcesses: ReadonlySet<ActiveClaudeSubagent>;@@ -7143,6 +7371,107 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (registry: target.toolCalls,});+ // App requests never start a CLI; they reuse the live process that ran the tool.+ const mcpAppQuery = Effect.fn("ClaudeAdapterV2.mcpAppQuery")(function* (+ providerThread: OrchestrationV2ProviderThread,+ ) {+ const liveQuery = yield* Ref.get(queryContext);+ if (+ liveQuery === null ||+ liveQuery.stopping ||+ liveQuery.nativeThreadId !== providerThread.nativeThreadRef?.nativeId+ ) {+ return yield* new ProviderAdapter.ProviderAdapterSessionStoppedError({+ driver: CLAUDE_PROVIDER,+ });+ }+ if (!claudeSupportsMcpApps(liveQuery.capabilities)) {+ return yield* new ProviderAdapter.ProviderAdapterProtocolError({+ driver: CLAUDE_PROVIDER,+ detail: "This Claude process does not support MCP Apps.",+ });+ }+ return liveQuery;+ });++ // Servers can connect after capture, and a forged app reference can name a colliding server.+ const mcpAppServerStatuses = Effect.fn("ClaudeAdapterV2.mcpAppServerStatuses")(function* (+ providerThread: OrchestrationV2ProviderThread,+ server: string,+ ) {+ const liveQuery = yield* mcpAppQuery(providerThread);+ const statuses = yield* liveQuery.query.mcpServerStatus.pipe(+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterProtocolError({+ driver: CLAUDE_PROVIDER,+ detail: "Failed to list Claude MCP tools.",+ cause,+ }),+ ),+ );+ if (claudeMcpServerPrefixOverlaps(statuses, server)) {+ return yield* new ProviderAdapter.ProviderAdapterProtocolError({+ driver: CLAUDE_PROVIDER,+ detail: "Another MCP server's tool names overlap this app's server.",+ });+ }+ return { liveQuery, statuses };+ });++ /** Reads an app tool's `ui://` document into an attachment; a plain tool row is the fallback. */+ const captureClaudeMcpApp = Effect.fn("ClaudeAdapterV2.captureMcpApp")(+ function* (input: {+ readonly liveQuery: ClaudeLiveQueryContext;+ readonly toolCall: ActiveClaudeToolCall;+ readonly output: ClaudeNativeToolOutput;+ }) {+ const { liveQuery, toolCall } = input;+ if (+ !toolCall.toolName.startsWith("mcp__") ||+ toolCall.toolName.startsWith("mcp__t3-code__") ||+ !claudeSupportsMcpApps(liveQuery.capabilities)+ ) {+ return undefined;+ }+ const match = findClaudeMcpTool(+ yield* liveQuery.query.mcpServerStatus,+ toolCall.toolName,+ );+ const resourceUri = mcpAppToolResourceUri(match?.tool._meta);+ if (match === undefined || resourceUri === undefined) return undefined;+ const { contents } = yield* liveQuery.query.readMcpResource({+ server: match.server,+ uri: resourceUri,+ });+ const reference = yield* snapshotMcpApp({+ attachmentsDir,+ threadId: toolCall.threadId,+ server: match.server,+ tool: match.tool.name,+ resourceUri,+ contents,+ }).pipe(Effect.provideService(FileSystem.FileSystem, fileSystem));+ if (reference === undefined) return undefined;+ return {+ type: "structured_tool_use_result",+ value: {+ [MCP_APP_OUTPUT_KEY]: reference,+ result: claudeMcpCallToolResult(claudeNativeToolOutputValue(input.output)),+ },+ } satisfies ClaudeNativeToolOutput;+ },+ Effect.timeout(CLAUDE_MCP_APP_CAPTURE_TIMEOUT),+ Effect.catchCauseIf(+ (cause) => !Cause.hasInterruptsOnly(cause),+ (cause) =>+ Effect.logWarning("Failed to capture an MCP app; showing a plain tool row.", {+ cause,+ }).pipe(Effect.as(undefined)),+ ),+ Effect.orDie,+ );+const settleToolCall = Effect.fnUntraced(function* (input: {readonly context: ActiveClaudeTurnContext | null;readonly toolCall: ActiveClaudeToolCall;@@ -9385,13 +9714,21 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (toolInput: EMPTY_CLAUDE_NATIVE_TOOL_INPUT,parentToolUseId,}));+ const appOutput =+ parentToolUseId === null &&+ toolCall.runId !== null &&+ !isClaudeToolResultError(toolResult)+ ? yield* captureClaudeMcpApp({ liveQuery, toolCall, output })+ : undefined;yield* settleToolCall({context,toolCall,registry: toolCallsFor(context, toolCall),message,toolResult,- output,+ output:+ appOutput ??+ (toolCall.toolName.startsWith("mcp__") ? withoutForgedMcpApp(output) : output),completedAt: yield* DateTime.now,});// Subagents write to the session's shared task store, so their@@ -10590,6 +10927,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (promptEchoMode: "unknown",openedPermissionMode: queryOptions.permissionMode,receivedInit: false,+ capabilities: new Set(),permissionMode: queryOptions.permissionMode,stopping: false,handedOffSubagents: new Set(),@@ -10629,6 +10967,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (context.openedPermissionMode =message.permissionMode ?? context.openedPermissionMode;context.receivedInit = true;+ context.capabilities = new Set(message.capabilities ?? []);}if (message.type === "system" &&@@ -11488,6 +11827,85 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (message: { ...turnInput.message, text: "/compact" },}),steerTurn,+ mcpApps: {+ listTools: Effect.fn("ClaudeAdapterV2.listMcpTools")(function* ({+ providerThread,+ server,+ }) {+ const { liveQuery, statuses } = yield* mcpAppServerStatuses(providerThread, server);+ const status = statuses.find((candidate) => candidate.name === server);+ const rules = yield* liveQuery.query.listPermissionRules.pipe(+ Effect.orElseSucceed(() => null),+ );+ return (status?.tools ?? []).map((tool) => claudeMcpToolForApps(tool, rules));+ }),+ callTool: Effect.fn("ClaudeAdapterV2.callMcpTool")(function* (call) {+ const { liveQuery, statuses } = yield* mcpAppServerStatuses(+ call.providerThread,+ call.server,+ );+ const tool = claudeMcpToolName(call.server, call.tool);+ const sameName = (+ statuses.find((status) => status.name === call.server)?.tools ?? []+ ).filter((candidate) => claudeMcpToolName(call.server, candidate.name) === tool);+ // `refresh.weather` and `refresh_weather` reach Claude as one name, so the checked tool may not be the one run.+ if (sameName.length > 1) {+ return yield* new ProviderAdapter.ProviderAdapterProtocolError({+ driver: CLAUDE_PROVIDER,+ detail: "Another tool on this MCP server has the same Claude tool name.",+ });+ }+ // mcp_call skips Claude's permission check, so its deny rules are applied here.+ const rules = yield* liveQuery.query.listPermissionRules.pipe(+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterProtocolError({+ driver: CLAUDE_PROVIDER,+ detail: `Claude's permission rules could not be read, so ${tool} was not called.`,+ cause,+ }),+ ),+ );+ if (claudeRulesMayCoverMcpTools(rules, ["deny"])) {+ return yield* new ProviderAdapter.ProviderAdapterProtocolError({+ driver: CLAUDE_PROVIDER,+ detail: `A Claude deny rule may cover ${tool}, so it was not called.`,+ });+ }+ return claudeMcpCallToolResult(+ yield* liveQuery.query+ .callMcpTool({+ tool,+ arguments: call.arguments,+ })+ .pipe(+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterProtocolError({+ driver: CLAUDE_PROVIDER,+ detail: "Claude MCP tool call failed.",+ cause,+ }),+ ),+ ),+ );+ }),+ readResource: Effect.fn("ClaudeAdapterV2.readMcpResource")(function* (read) {+ const { liveQuery } = yield* mcpAppServerStatuses(read.providerThread, read.server);+ return yield* liveQuery.query+ .readMcpResource({ server: read.server, uri: read.uri })+ .pipe(+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterProtocolError({+ driver: CLAUDE_PROVIDER,+ detail: "Claude MCP resource read failed.",+ cause,+ }),+ ),+ );+ }),+ },stopTask: Effect.fn("ClaudeAdapterV2.stopTask")(function* ({ providerThread, taskId }) {const liveQuery = yield* Ref.get(queryContext);const task = (yield* Ref.get(sessionSubagentsByTaskId)).get(taskId);diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.tsindex 5898996e486..0c36d4a5869 100644--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts@@ -297,6 +297,38 @@ it.effect("reopens a stalled MCP registration before delivering the resumed prom),);+it.effect.each([+ { case: "a readable rule list", errors: undefined, readable: true },+ { case: "a settings file Claude skipped", errors: [{ file: "settings.json" }], readable: false },+ { case: "a reply without a rule list", response: {}, readable: false },+])("reads Claude's permission rules only when no settings file was skipped: $case", (testCase) =>+ Effect.scoped(+ Effect.gen(function* () {+ const rules = [{ behavior: "deny" as const, rule: "mcp__probe__redeploy" }];+ const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(+ () =>+ ({+ close: vi.fn(),+ request: async () => ({+ response:+ "response" in testCase+ ? testCase.response+ : { state: { rules, errors: testCase.errors } },+ }),+ }) as unknown as ClaudeSdk.Query,+ );+ yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));+ const runner = yield* ClaudeAgentSdkQueryRunner;+ const { mcpServers: _mcpServers, ...options } = resumedMcpQueryInput.options;+ const session = yield* runner.open({ ...resumedMcpQueryInput, options });+ yield* Effect.addFinalizer(() => session.close.pipe(Effect.orDie));+ const exit = yield* Effect.exit(session.listPermissionRules);+ if (testCase.readable) assert.deepEqual(exit, Exit.succeed(rules));+ else assert.isTrue(Exit.isFailure(exit));+ }).pipe(Effect.provide(realQueryRunner)),+ ),+);+it.effect.each([true, false])("only retries after confirmed process exit: %s", (exits) =>Effect.scoped(Effect.gen(function* () {diff --git a/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts b/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.tsindex e28bb374651..46994a891f7 100644--- a/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts+++ b/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts@@ -169,6 +169,10 @@ it.effect.each(deliveries)(applyFlagSettings: () => Effect.void,setPermissionMode: () => Effect.void,backgroundTasks: () => Effect.succeed(false),+ mcpServerStatus: Effect.succeed([]),+ readMcpResource: () => Effect.die("unexpected MCP resource read"),+ callMcpTool: () => Effect.die("unexpected MCP tool call"),+ listPermissionRules: Effect.die("unexpected permission rules read"),stopTask: () => Effect.void,interrupt: Effect.die("automatic delivery must never interrupt"),close: Effect.void,diff --git a/apps/server/src/provider/model-manifest.json b/apps/server/src/provider/model-manifest.jsonindex 56398dcc9e7..8c9969a1d0a 100644--- a/apps/server/src/provider/model-manifest.json+++ b/apps/server/src/provider/model-manifest.json@@ -1,6 +1,6 @@{"version": 1,- "updatedAt": "2026-11-02T21:16:47Z",+ "updatedAt": "2026-11-02T23:47:11Z","compatibility": [{"driver": "codex",@@ -25,7 +25,7 @@{"driver": "claudeAgent","t3CodeRange": ">=0.0.42",- "recommendedRange": ">=2.1.280",+ "recommendedRange": ">=2.1.301","ranges": [{ "range": ">=2.1.280", "status": "supported" },{ "range": ">=2.1.111 <2.1.280", "status": "graceful" },diff --git a/docs/user/html-renders.md b/docs/user/html-renders.mdindex ac1ca0ef048..ee0b1111a65 100644--- a/docs/user/html-renders.md+++ b/docs/user/html-renders.md@@ -10,7 +10,7 @@ Before publishing, agents check their work with screenshots from a small headles## MCP apps-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.+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.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.diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.tsindex f9f55ec1311..9ea7597e6d0 100644--- a/packages/provider-core/src/server/ProviderAdapter.ts+++ b/packages/provider-core/src/server/ProviderAdapter.ts@@ -424,6 +424,15 @@ export class ProviderAdapterProtocolError extends Schema.TaggedError<ProviderAda}}+export class ProviderAdapterSessionStoppedError extends Schema.TaggedError<ProviderAdapterSessionStoppedError>()(+ "ProviderAdapterSessionStoppedError",+ { driver: ProviderDriverKind },+) {+ override get message(): string {+ return `No running ${this.driver} session owns this thread.`;+ }+}+export const ProviderAdapterV2Error = Schema.Union([ProviderAdapterCapabilitiesError,ProviderAdapterOpenSessionError,@@ -442,6 +451,7 @@ export const ProviderAdapterV2Error = Schema.Union([ProviderAdapterRuntimeRequestResponseError,ProviderAdapterEventStreamError,ProviderAdapterProtocolError,+ ProviderAdapterSessionStoppedError,]);export type ProviderAdapterV2Error = typeof ProviderAdapterV2Error.Type;@@ -557,6 +567,8 @@ export interface ProviderAdapterV2HistoricalContext {export interface ProviderAdapterV2McpTool {readonly name: string;+ // Apps reject a `hostContext.toolInfo.tool` without one.+ readonly inputSchema: unknown;readonly _meta?: unknown;readonly annotations?: unknown;}diff --git a/packages/shared/src/mcpApp.test.ts b/packages/shared/src/mcpApp.test.tsindex 7e2ee8cbd20..6dd3c7d0114 100644--- a/packages/shared/src/mcpApp.test.ts+++ b/packages/shared/src/mcpApp.test.ts@@ -7,6 +7,7 @@ import {injectMcpAppCookieBootstrap,mcpAppContentSecurityPolicy,mcpAppToolCallableByApp,+ mcpAppToolResourceUri,readMcpAppCsp,readMcpAppReference,} from "./mcpApp.ts";@@ -137,6 +138,14 @@ describe("readMcpAppReference", () => {describe("tool metadata", () => {it("reads the resource URI from either spelling and honors app visibility", () => {+ const uri = "ui://weather/card.html";+ expect(mcpAppToolResourceUri({ ui: { resourceUri: uri } })).toBe(uri);+ expect(+ mcpAppToolResourceUri({ ui: { visibility: ["model", "app"] }, "ui/resourceUri": uri }),+ ).toBe(uri);+ expect(+ mcpAppToolResourceUri({ ui: { resourceUri: "https://weather/card.html" } }),+ ).toBeUndefined();expect(mcpAppToolCallableByApp(undefined)).toBe(true);expect(mcpAppToolCallableByApp({ ui: { visibility: ["model"] } })).toBe(false);expect(mcpAppToolCallableByApp({ ui: { visibility: ["model", "app"] } })).toBe(true);@@ -170,6 +179,13 @@ describe("mcpAppFromToolItem", () => {};expect(mcpAppFromToolItem({ toolName: "evil.lookup", output: forged })).toBeUndefined();expect(mcpAppFromToolItem({ toolName: "bank.transfer", output: forged })).toBeDefined();+ // Claude Code names the same tool `mcp__<server>__<tool>`.+ expect(mcpAppFromToolItem({ toolName: "mcp__bank__transfer", output: forged })).toBeDefined();+ expect(mcpAppFromToolItem({ toolName: "mcp__evil__transfer", output: forged })).toBeUndefined();+ const connector = { t3McpApp: { ...forged.t3McpApp, server: "claude.ai Asana (Beta)" } };+ expect(+ mcpAppFromToolItem({ toolName: "mcp__claude_ai_Asana_Beta__transfer", output: connector }),+ ).toBeDefined();});it("keeps an app whose resource URI is longer than a name", async () => {diff --git a/packages/shared/src/mcpApp.ts b/packages/shared/src/mcpApp.tsindex d83368eef48..35a50306423 100644--- a/packages/shared/src/mcpApp.ts+++ b/packages/shared/src/mcpApp.ts@@ -131,6 +131,31 @@ export function mcpAppReferencesEqual(left: McpAppReference, right: McpAppRefere);}+/** Reads a tool's `_meta.ui.resourceUri`, or the deprecated flat `ui/resourceUri`. */+export function mcpAppToolResourceUri(meta: unknown): string | undefined {+ if (!Predicate.isObject(meta)) return undefined;+ const uri =+ (Predicate.isObject(meta.ui) ? meta.ui.resourceUri : undefined) ?? meta["ui/resourceUri"];+ return typeof uri === "string" &&+ uri.length <= MAX_RESOURCE_URI_LENGTH &&+ uri.startsWith(MCP_APP_RESOURCE_SCHEME)+ ? uri+ : undefined;+}++export const claudeMcpToolNamePart = (name: string) => name.replace(/[^a-zA-Z0-9_-]/g, "_");++/** Claude Code's `mcp__<server>__` prefix; it also collapses and trims `_` in `claude.ai ` connector names. */+export function claudeMcpToolPrefix(server: string): string {+ const part = claudeMcpToolNamePart(server);+ return `mcp__${server.startsWith("claude.ai ") ? part.replace(/_+/g, "_").replace(/^_|_$/g, "") : part}__`;+}++/** Claude Code names MCP tools `mcp__<server>__<tool>`, replacing characters outside `[a-zA-Z0-9_-]`. */+export function claudeMcpToolName(server: string, tool: string): string {+ return `${claudeMcpToolPrefix(server)}${claudeMcpToolNamePart(tool)}`;+}+export function mcpAppToolCallableByApp(meta: unknown): boolean {const visibility =Predicate.isObject(meta) && Predicate.isObject(meta.ui) ? meta.ui.visibility : undefined;diff --git a/packages/shared/src/toolOutput.ts b/packages/shared/src/toolOutput.tsindex 4c1ea03344c..6287c673ef6 100644--- a/packages/shared/src/toolOutput.ts+++ b/packages/shared/src/toolOutput.ts@@ -9,7 +9,12 @@ import {readHtmlRenderReference,type HtmlRenderReference,} from "./htmlRender.ts";-import { MCP_APP_OUTPUT_KEY, readMcpAppReference, type McpAppReference } from "./mcpApp.ts";+import {+ claudeMcpToolName,+ MCP_APP_OUTPUT_KEY,+ readMcpAppReference,+ type McpAppReference,+} from "./mcpApp.ts";import { resolveT3McpToolId } from "./t3McpToolPresentation.ts";const MAX_PARSED_BYTES = 16_384;@@ -212,7 +217,11 @@ export function mcpAppFromToolItem(item: {readonly output?: unknown;}): McpAppReference | undefined {const app = compactDynamicToolOutput(item.output)?.[MCP_APP_OUTPUT_KEY];- return app !== undefined && item.toolName === `${app.server}.${app.tool}` ? app : undefined;+ return app !== undefined &&+ (item.toolName === `${app.server}.${app.tool}` ||+ item.toolName === claudeMcpToolName(app.server, app.tool))+ ? app+ : undefined;}/** Some providers report completion even when command output describes a failure. */diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 4f5985a40bc..97a49014763 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -823,8 +823,8 @@ importers:apps/server:dependencies:'@anthropic-ai/claude-agent-sdk':- specifier: ^0.3.284- version: 0.3.284(@anthropic-ai/[email protected]([email protected]))(@modelcontextprotocol/[email protected]([email protected])([email protected]))([email protected])+ specifier: ^0.3.316+ version: 0.3.316(@anthropic-ai/[email protected]([email protected]))(@modelcontextprotocol/[email protected]([email protected])([email protected]))([email protected])'@cursor/sdk':specifier: 1.2.0version: 1.2.0([email protected])@@ -2652,9 +2652,9 @@ packages:vitest:optional: true- '@anthropic-ai/[email protected]':- resolution: {integrity: sha512-NSoJwEq6nFSf8dtaacYx37QdGgqApI3eHFUlxclMLYi8irb6ZJwEaUnPnLUCyAyg9W/tMkgZC0GXWLRCc01I0w==}- engines: {node: '>=18.0.0'}+ '@anthropic-ai/[email protected]':+ resolution: {integrity: sha512-mCMr0que5kIy80JslJub6WFDB2+GYRGWNeVgSZaBpkBwXrr4wnRMnnGHitkA2BEJ5QP5xWyc6YH/6do/edxCWg==}+ engines: {node: '>=18.14.0'}peerDependencies:'@anthropic-ai/sdk': '>=0.93.0''@modelcontextprotocol/sdk': ^1.29.0@@ -12457,7 +12457,7 @@ snapshots:- bufferutil- utf-8-validate- '@anthropic-ai/[email protected](@anthropic-ai/[email protected]([email protected]))(@modelcontextprotocol/[email protected]([email protected])([email protected]))([email protected])':+ '@anthropic-ai/[email protected](@anthropic-ai/[email protected]([email protected]))(@modelcontextprotocol/[email protected]([email protected])([email protected]))([email protected])':dependencies:'@anthropic-ai/sdk': 0.93.0([email protected])'@modelcontextprotocol/sdk': 1.29.0([email protected])([email protected])