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

McpAppRequests.ts

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