Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

McpAppRequests.ts

224 lines9.0 KB

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 * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
25import * as ProviderSessionManager from "../orchestration-v2/ProviderSessionManager.ts";
26import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
27import * as McpAppModelContext from "./McpAppModelContext.ts";
28​
29/**
30 * A stopped session is reported, never started: an app view must not spend a
31 * provider turn.
32 */
33export class McpAppRequests extends Context.Service<
34 McpAppRequests,
35 {
36 readonly callTool: (
37 input: McpAppCallToolInput,
38 ) => Effect.Effect<McpAppCallToolResult, McpAppRequestError>;
39 readonly toolInfo: (
40 input: McpAppToolInfoInput,
41 ) => Effect.Effect<McpAppToolInfo, McpAppRequestError>;
42 readonly readResource: (
43 input: McpAppReadResourceInput,
44 ) => Effect.Effect<McpAppReadResourceResult, McpAppRequestError>;
45 readonly updateModelContext: (
46 input: McpAppUpdateModelContextInput,
47 ) => Effect.Effect<void, McpAppRequestError>;
48 }
49>()("t3/mcpApps/McpAppRequests") {}
50​
51const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
52const utf8 = new TextEncoder();
53​
54const readOnlyHint = (tool: ProviderAdapter.ProviderAdapterV2McpTool) =>
55 Predicate.isObject(tool.annotations) && tool.annotations.readOnlyHint === true;
56​
57const toolTitle = (tool: ProviderAdapter.ProviderAdapterV2McpTool) =>
58 Predicate.isObject(tool.annotations) && typeof tool.annotations.title === "string"
59 ? tool.annotations.title
60 : undefined;
61​
62const make = Effect.gen(function* () {
63 const orchestrator = yield* Orchestrator.OrchestratorV2;
64 const threadManagement = yield* ThreadManagementService.ThreadManagementService;
65 const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
66 const modelContext = yield* McpAppModelContext.McpAppModelContext;
67​
68 const fail = (threadId: ThreadId, reason: McpAppRequestError["reason"], cause?: unknown) =>
69 new McpAppRequestError({ threadId, reason, ...(cause === undefined ? {} : { cause }) });
70​
71 const resolveApp = Effect.fn("McpAppRequests.resolveApp")(function* (input: {
72 readonly threadId: ThreadId;
73 readonly itemId: TurnItemId;
74 }) {
75 const item = yield* orchestrator
76 .getTurnItem({ threadId: input.threadId, itemId: input.itemId })
77 .pipe(Effect.mapError((cause) => fail(input.threadId, "request-failed", cause)));
78 const app: McpAppReference | undefined =
79 item?.type === "dynamic_tool" ? mcpAppFromToolItem(item) : undefined;
80 if (item === null || app === undefined || item.providerThreadId === null) {
81 return yield* fail(input.threadId, "not-an-app");
82 }
83 return { app, providerThreadId: item.providerThreadId };
84 });
85​
86 const resolve = Effect.fn("McpAppRequests.resolve")(function* (input: {
87 readonly threadId: ThreadId;
88 readonly itemId: TurnItemId;
89 }) {
90 const { app, providerThreadId } = yield* resolveApp(input);
91 const projection = yield* threadManagement
92 .getThreadRecords(input.threadId, ["providerThreads"])
93 .pipe(Effect.mapError((cause) => fail(input.threadId, "request-failed", cause)));
94 const providerThread = projection.providerThreads.find(
95 (candidate) => candidate.id === providerThreadId,
96 );
97 if (providerThread?.providerSessionId == null) {
98 return yield* fail(input.threadId, "session-stopped");
99 }
100 const runtime = Option.getOrUndefined(
101 yield* providerSessions
102 .get(providerThread.providerSessionId)
103 .pipe(Effect.mapError((cause) => fail(input.threadId, "request-failed", cause))),
104 );
105 if (runtime === undefined) return yield* fail(input.threadId, "session-stopped");
106 const mcpApps: ProviderAdapter.ProviderAdapterV2McpApps | undefined = runtime.mcpApps;
107 if (mcpApps === undefined) return yield* fail(input.threadId, "provider-unsupported");
108 return { app, providerThread, mcpApps };
109 });
110​
111 const findTool = Effect.fn("McpAppRequests.findTool")(function* (
112 threadId: ThreadId,
113 resolved: Effect.Success<ReturnType<typeof resolve>>,
114 name: string,
115 ) {
116 const tools = yield* resolved.mcpApps
117 .listTools({ providerThread: resolved.providerThread, server: resolved.app.server })
118 .pipe(Effect.mapError((cause) => fail(threadId, "request-failed", cause)));
119 return tools.find((tool) => tool.name === name);
120 });
121​
122 const toolInfo = Effect.fn("McpAppRequests.toolInfo")(function* (input: McpAppToolInfoInput) {
123 const resolved = yield* resolve(input);
124 const tool = yield* findTool(input.threadId, resolved, input.name);
125 const title = tool === undefined ? undefined : toolTitle(tool);
126 return {
127 callable: tool !== undefined && mcpAppToolCallableByApp(tool._meta),
128 readOnly: tool !== undefined && readOnlyHint(tool),
129 ...(title === undefined ? {} : { title }),
130 ...(tool === undefined ? {} : { tool }),
131 } satisfies McpAppToolInfo;
132 });
133​
134 const callTool = Effect.fn("McpAppRequests.callTool")(function* (input: McpAppCallToolInput) {
135 const resolved = yield* resolve(input);
136 // The spec forbids apps calling tools hidden from them; checked here too,
137 // since a client's own check is only a courtesy to its user.
138 const tool = yield* findTool(input.threadId, resolved, input.name);
139 if (tool === undefined || !mcpAppToolCallableByApp(tool._meta)) {
140 return yield* fail(input.threadId, "tool-not-callable");
141 }
142 return yield* resolved.mcpApps
143 .callTool({
144 providerThread: resolved.providerThread,
145 server: resolved.app.server,
146 tool: input.name,
147 arguments: input.arguments,
148 })
149 .pipe(Effect.mapError((cause) => fail(input.threadId, "request-failed", cause)));
150 });
151​
152 const readResource = Effect.fn("McpAppRequests.readResource")(function* (
153 input: McpAppReadResourceInput,
154 ) {
155 const resolved = yield* resolve(input);
156 return yield* resolved.mcpApps
157 .readResource({
158 providerThread: resolved.providerThread,
159 server: resolved.app.server,
160 uri: input.uri,
161 })
162 .pipe(Effect.mapError((cause) => fail(input.threadId, "request-failed", cause)));
163 });
164​
165 const descendsFrom = Effect.fn("McpAppRequests.descendsFrom")(function* (
166 threadId: ThreadId,
167 ancestorId: ThreadId,
168 ) {
169 const seen = new Set<ThreadId>();
170 let current: ThreadId | null = threadId;
171 while (current !== null && !seen.has(current)) {
172 if (current === ancestorId) return true;
173 seen.add(current);
174 const records: { readonly thread: OrchestrationV2AppThread } = yield* threadManagement
175 .getThreadRecords(current, [])
176 .pipe(Effect.mapError((cause) => fail(threadId, "request-failed", cause)));
177 const { lineage } = records.thread;
178 current = lineage.relationshipToParent === "fork" ? lineage.parentThreadId : null;
179 }
180 return false;
181 });
182​
183 const updateModelContext = Effect.fn("McpAppRequests.updateModelContext")(function* (
184 input: McpAppUpdateModelContextInput,
185 ) {
186 const { app } = yield* resolveApp(input);
187 // Context belongs to the conversation on screen, which only shows this app
188 // when it is the app's own thread or one forked from it.
189 if (!(yield* descendsFrom(input.conversationThreadId, input.threadId))) {
190 return yield* fail(input.threadId, "not-an-app");
191 }
192 const texts: Array<string> = [];
193 for (const block of input.content ?? []) {
194 if (!Predicate.isObject(block) || block.type !== "text" || typeof block.text !== "string") {
195 return yield* fail(input.threadId, "unsupported-content");
196 }
197 texts.push(block.text);
198 }
199 if (input.structuredContent !== undefined) {
200 texts.push(encodeJson(input.structuredContent));
201 }
202 const text = texts.join("\n");
203 if (utf8.encode(text).byteLength > McpAppModelContext.MCP_APP_MODEL_CONTEXT_MAX_BYTES) {
204 return yield* fail(
205 input.threadId,
206 "request-failed",
207 new Error("Model context is too large."),
208 );
209 }
210 yield* modelContext
211 .set({
212 threadId: input.conversationThreadId,
213 itemId: input.itemId,
214 server: app.server,
215 tool: app.tool,
216 text,
217 })
218 .pipe(Effect.mapError((cause) => fail(input.threadId, "request-failed", cause)));
219 });
220​
221 return McpAppRequests.of({ callTool, toolInfo, readResource, updateModelContext });
222});
223​
224export const layer = Layer.effect(McpAppRequests, make);