Open History to see the last commit
1import {
2 McpAppRequestError,
3 type McpAppCallToolInput,
4 type McpAppCallToolResult,
5 type McpAppReadResourceInput,
6 type McpAppReadResourceResult,
7 type McpAppToolInfo,
8 type McpAppToolInfoInput,
9 type McpAppUpdateModelContextInput,
10 type OrchestrationV2AppThread,
11 type ThreadId,
12 type TurnItemId,
13} from "@t3tools/contracts";
14import { mcpAppToolCallableByApp, type McpAppReference } from "@t3tools/shared/mcpApp";
15import { mcpAppFromToolItem } from "@t3tools/shared/toolOutput";
16import * as Context from "effect/Context";
17import * as Effect from "effect/Effect";
18import * as Layer from "effect/Layer";
19import * as Option from "effect/Option";
20import * as Predicate from "effect/Predicate";
21import * as Schema from "effect/Schema";
22
23import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
24import type {
25 ProviderAdapterV2McpApps,
26 ProviderAdapterV2McpTool,
27} from "../orchestration-v2/ProviderAdapter.ts";
28import * as ProviderSessionManager from "../orchestration-v2/ProviderSessionManager.ts";
29import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
30import * as McpAppModelContext from "./McpAppModelContext.ts";
31
32/**
33 * Requests an MCP App makes of its own MCP server. The app is resolved from the
34 * tool call that produced it, so it reaches only that server, and each request
35 * runs through the thread's live provider session, whose MCP client owns the
36 * connection and its credentials. A stopped session is reported, never
37 * started: an app view must not spend a provider turn.
38 */
39export class McpAppRequests extends Context.Service<
40 McpAppRequests,
41 {
42 readonly callTool: (
43 input: McpAppCallToolInput,
44 ) => Effect.Effect<McpAppCallToolResult, McpAppRequestError>;
45 readonly toolInfo: (
46 input: McpAppToolInfoInput,
47 ) => Effect.Effect<McpAppToolInfo, McpAppRequestError>;
48 readonly readResource: (
49 input: McpAppReadResourceInput,
50 ) => Effect.Effect<McpAppReadResourceResult, McpAppRequestError>;
51 readonly updateModelContext: (
52 input: McpAppUpdateModelContextInput,
53 ) => Effect.Effect<void, McpAppRequestError>;
54 }
55>()("t3/mcpApps/McpAppRequests") {}
56
57const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
58const utf8 = new TextEncoder();
59
60const readOnlyHint = (tool: ProviderAdapterV2McpTool) =>
61 Predicate.isObject(tool.annotations) && tool.annotations.readOnlyHint === true;
62
63const toolTitle = (tool: ProviderAdapterV2McpTool) =>
64 Predicate.isObject(tool.annotations) && typeof tool.annotations.title === "string"
65 ? tool.annotations.title
66 : undefined;
67
68const make = Effect.gen(function* () {
69 const orchestrator = yield* Orchestrator.OrchestratorV2;
70 const threadManagement = yield* ThreadManagementService.ThreadManagementService;
71 const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
72 const modelContext = yield* McpAppModelContext.McpAppModelContext;
73
74 const fail = (threadId: ThreadId, reason: McpAppRequestError["reason"], cause?: unknown) =>
75 new McpAppRequestError({ threadId, reason, ...(cause === undefined ? {} : { cause }) });
76
77 /** The app a tool call produced, read from the stored item. */
78 const resolveApp = Effect.fn("McpAppRequests.resolveApp")(function* (input: {
79 readonly threadId: ThreadId;
80 readonly itemId: TurnItemId;
81 }) {
82 // The stored item, not the wire projection, so the reference is intact.
83 const item = yield* orchestrator
84 .getTurnItem({ threadId: input.threadId, itemId: input.itemId })
85 .pipe(Effect.mapError((cause) => fail(input.threadId, "request-failed", cause)));
86 const app: McpAppReference | undefined =
87 item?.type === "dynamic_tool" ? mcpAppFromToolItem(item) : undefined;
88 if (item === null || app === undefined || item.providerThreadId === null) {
89 return yield* fail(input.threadId, "not-an-app");
90 }
91 return { app, providerThreadId: item.providerThreadId };
92 });
93
94 /** The app, its provider thread, and the live session's MCP Apps operations. */
95 const resolve = Effect.fn("McpAppRequests.resolve")(function* (input: {
96 readonly threadId: ThreadId;
97 readonly itemId: TurnItemId;
98 }) {
99 const { app, providerThreadId } = yield* resolveApp(input);
100 const projection = yield* threadManagement
101 .getThreadRecords(input.threadId, ["providerThreads"])
102 .pipe(Effect.mapError((cause) => fail(input.threadId, "request-failed", cause)));
103 const providerThread = projection.providerThreads.find(
104 (candidate) => candidate.id === providerThreadId,
105 );
106 if (providerThread?.providerSessionId == null) {
107 return yield* fail(input.threadId, "session-stopped");
108 }
109 const runtime = Option.getOrUndefined(
110 yield* providerSessions
111 .get(providerThread.providerSessionId)
112 .pipe(Effect.mapError((cause) => fail(input.threadId, "request-failed", cause))),
113 );
114 if (runtime === undefined) return yield* fail(input.threadId, "session-stopped");
115 const mcpApps: ProviderAdapterV2McpApps | undefined = runtime.mcpApps;
116 if (mcpApps === undefined) return yield* fail(input.threadId, "provider-unsupported");
117 return { app, providerThread, mcpApps };
118 });
119
120 const findTool = Effect.fn("McpAppRequests.findTool")(function* (
121 threadId: ThreadId,
122 resolved: Effect.Success<ReturnType<typeof resolve>>,
123 name: string,
124 ) {
125 const tools = yield* resolved.mcpApps
126 .listTools({ providerThread: resolved.providerThread, server: resolved.app.server })
127 .pipe(Effect.mapError((cause) => fail(threadId, "request-failed", cause)));
128 return tools.find((tool) => tool.name === name);
129 });
130
131 const toolInfo = Effect.fn("McpAppRequests.toolInfo")(function* (input: McpAppToolInfoInput) {
132 const resolved = yield* resolve(input);
133 const tool = yield* findTool(input.threadId, resolved, input.name);
134 const title = tool === undefined ? undefined : toolTitle(tool);
135 return {
136 callable: tool !== undefined && mcpAppToolCallableByApp(tool._meta),
137 readOnly: tool !== undefined && readOnlyHint(tool),
138 ...(title === undefined ? {} : { title }),
139 ...(tool === undefined ? {} : { tool }),
140 } satisfies McpAppToolInfo;
141 });
142
143 const callTool = Effect.fn("McpAppRequests.callTool")(function* (input: McpAppCallToolInput) {
144 const resolved = yield* resolve(input);
145 // The spec forbids apps calling tools hidden from them; checked here too,
146 // since a client's own check is only a courtesy to its user.
147 const tool = yield* findTool(input.threadId, resolved, input.name);
148 if (tool === undefined || !mcpAppToolCallableByApp(tool._meta)) {
149 return yield* fail(input.threadId, "tool-not-callable");
150 }
151 return yield* resolved.mcpApps
152 .callTool({
153 providerThread: resolved.providerThread,
154 server: resolved.app.server,
155 tool: input.name,
156 arguments: input.arguments,
157 })
158 .pipe(Effect.mapError((cause) => fail(input.threadId, "request-failed", cause)));
159 });
160
161 const readResource = Effect.fn("McpAppRequests.readResource")(function* (
162 input: McpAppReadResourceInput,
163 ) {
164 const resolved = yield* resolve(input);
165 return yield* resolved.mcpApps
166 .readResource({
167 providerThread: resolved.providerThread,
168 server: resolved.app.server,
169 uri: input.uri,
170 })
171 .pipe(Effect.mapError((cause) => fail(input.threadId, "request-failed", cause)));
172 });
173
174 // Context is state for the agent's next turn, so it needs the app but not a
175 // live session. Text blocks are kept as written and structured content as
176 // JSON; other content kinds are not declared by the host.
177 /** Whether `threadId` is `ancestorId` or forked from it, however many forks deep. */
178 const descendsFrom = Effect.fn("McpAppRequests.descendsFrom")(function* (
179 threadId: ThreadId,
180 ancestorId: ThreadId,
181 ) {
182 // Walks fork links until the chain ends; a thread seen twice means a
183 // corrupt cycle, which proves nothing.
184 const seen = new Set<ThreadId>();
185 let current: ThreadId | null = threadId;
186 while (current !== null && !seen.has(current)) {
187 if (current === ancestorId) return true;
188 seen.add(current);
189 const records: { readonly thread: OrchestrationV2AppThread } = yield* threadManagement
190 .getThreadRecords(current, [])
191 .pipe(Effect.mapError((cause) => fail(threadId, "request-failed", cause)));
192 const { lineage } = records.thread;
193 current = lineage.relationshipToParent === "fork" ? lineage.parentThreadId : null;
194 }
195 return false;
196 });
197
198 const updateModelContext = Effect.fn("McpAppRequests.updateModelContext")(function* (
199 input: McpAppUpdateModelContextInput,
200 ) {
201 const { app } = yield* resolveApp(input);
202 // Context belongs to the conversation on screen, which only shows this app
203 // when it is the app's own thread or one forked from it.
204 if (!(yield* descendsFrom(input.conversationThreadId, input.threadId))) {
205 return yield* fail(input.threadId, "not-an-app");
206 }
207 const texts: Array<string> = [];
208 for (const block of input.content ?? []) {
209 if (!Predicate.isObject(block) || block.type !== "text" || typeof block.text !== "string") {
210 return yield* fail(input.threadId, "unsupported-content");
211 }
212 texts.push(block.text);
213 }
214 if (input.structuredContent !== undefined) {
215 texts.push(encodeJson(input.structuredContent));
216 }
217 // Kept as sent; blank text clears the app's context in the store.
218 const text = texts.join("\n");
219 if (utf8.encode(text).byteLength > McpAppModelContext.MCP_APP_MODEL_CONTEXT_MAX_BYTES) {
220 return yield* fail(
221 input.threadId,
222 "request-failed",
223 new Error("Model context is too large."),
224 );
225 }
226 yield* modelContext
227 .set({
228 threadId: input.conversationThreadId,
229 itemId: input.itemId,
230 server: app.server,
231 tool: app.tool,
232 text,
233 })
234 .pipe(Effect.mapError((cause) => fail(input.threadId, "request-failed", cause)));
235 });
236
237 return McpAppRequests.of({ callTool, toolInfo, readResource, updateModelContext });
238});
239
240export const layer = Layer.effect(McpAppRequests, make);