Open History to see the last commit
1import {
2 ProviderSessionId,
3 ProviderThreadId,
4 ThreadId,
5 TurnItemId,
6 type McpAppRequestError,
7 type OrchestrationV2ProviderThread,
8 type OrchestrationV2TurnItem,
9} from "@t3tools/contracts";
10import { assert, describe, it } from "@effect/vitest";
11import * as DateTime from "effect/DateTime";
12import * as Effect from "effect/Effect";
13import * as Layer from "effect/Layer";
14import * as Option from "effect/Option";
15
16import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
17import type {
18 ProviderAdapterV2McpApps,
19 ProviderAdapterV2SessionRuntime,
20} from "@t3tools/provider-core/server/ProviderAdapter";
21import * as ProviderSessionManager from "../orchestration-v2/ProviderSessionManager.ts";
22import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
23import * as McpAppModelContext from "./McpAppModelContext.ts";
24import * as McpAppRequests from "./McpAppRequests.ts";
25
26const threadId = ThreadId.make("thread-app");
27const itemId = TurnItemId.make("item-app");
28const providerThreadId = ProviderThreadId.make("provider-thread-app");
29const providerSessionId = ProviderSessionId.make("provider-session-app");
30const forkId = ThreadId.make("thread-fork");
31const unrelatedId = ThreadId.make("thread-unrelated");
32// A chain of forks deeper than any fixed walk limit: deep-70 → … → deep-1 → app.
33const deepForkId = (depth: number) => ThreadId.make(`thread-deep-${depth}`);
34const deepParent = (id: ThreadId): ThreadId | null => {
35 const match = /^thread-deep-(\d+)$/.exec(id);
36 if (match === null) return null;
37 const depth = Number(match[1]);
38 return depth === 1 ? threadId : deepForkId(depth - 1);
39};
40
41const appItem = (output: unknown): OrchestrationV2TurnItem => ({
42 id: itemId,
43 threadId,
44 runId: null,
45 nodeId: null,
46 providerThreadId,
47 providerTurnId: null,
48 nativeItemRef: null,
49 parentItemId: null,
50 ordinal: 0,
51 status: "completed",
52 title: null,
53 startedAt: null,
54 completedAt: null,
55 updatedAt: DateTime.makeUnsafe(0),
56 type: "dynamic_tool",
57 toolName: "weather.get_weather",
58 input: {},
59 output,
60});
61
62const app = {
63 attachmentId: "thread-app-00000000-0000-0000-0000-000000000000-html",
64 server: "weather",
65 tool: "get_weather",
66 resourceUri: "ui://weather/dashboard",
67};
68
69/** Each app's stored context, keyed by item, as the real store keeps it. */
70const storedContext = new Map<string, string>();
71
72function makeLayer(input: {
73 readonly item: OrchestrationV2TurnItem | null;
74 readonly mcpApps?: ProviderAdapterV2McpApps;
75 readonly live?: boolean;
76}) {
77 return McpAppRequests.layer.pipe(
78 Layer.provide(
79 Layer.mergeAll(
80 Layer.mock(McpAppModelContext.McpAppModelContext)({
81 set: (entry) =>
82 Effect.sync(() => {
83 const key = `${entry.threadId}/${entry.itemId}`;
84 if (entry.text.trim() === "") storedContext.delete(key);
85 else storedContext.set(key, entry.text);
86 }),
87 }),
88 Layer.mock(Orchestrator.OrchestratorV2)({
89 getTurnItem: () => Effect.succeed(input.item),
90 }),
91 Layer.mock(ThreadManagementService.ThreadManagementService)({
92 getThreadRecords: (id: ThreadId) =>
93 Effect.succeed({
94 // A fork of the app's thread, and an unrelated thread.
95 thread: {
96 lineage:
97 deepParent(id) !== null
98 ? {
99 parentThreadId: deepParent(id),
100 relationshipToParent: "fork",
101 rootThreadId: threadId,
102 }
103 : id === forkId
104 ? {
105 parentThreadId: threadId,
106 relationshipToParent: "fork",
107 rootThreadId: threadId,
108 }
109 : { parentThreadId: null, relationshipToParent: null, rootThreadId: id },
110 },
111 providerThreads: [
112 { id: providerThreadId, providerSessionId } as OrchestrationV2ProviderThread,
113 ],
114 } as never),
115 }),
116 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({
117 get: () =>
118 Effect.succeed(
119 input.live === false
120 ? Option.none()
121 : Option.some(
122 (input.mcpApps === undefined
123 ? {}
124 : { mcpApps: input.mcpApps }) as ProviderAdapterV2SessionRuntime,
125 ),
126 ),
127 }),
128 ),
129 ),
130 );
131}
132
133const reason = <A, R>(effect: Effect.Effect<A, McpAppRequestError, R>) =>
134 effect.pipe(
135 Effect.flip,
136 Effect.map((error) => error.reason),
137 );
138
139describe("McpAppRequests", () => {
140 const calls: Array<{ server: string; tool: string }> = [];
141 const mcpApps: ProviderAdapterV2McpApps = {
142 listTools: () =>
143 Effect.succeed([
144 { name: "refresh", annotations: { readOnlyHint: true } },
145 { name: "model_only", _meta: { ui: { visibility: ["model"] } } },
146 ]),
147 callTool: (input) =>
148 Effect.sync(() => {
149 calls.push({ server: input.server, tool: input.tool });
150 return { content: [{ type: "text", text: "ok" }] };
151 }),
152 readResource: () => Effect.succeed({ contents: [] }),
153 };
154
155 it.effect("calls tools on the app's own server and reports their read-only hint", () =>
156 Effect.gen(function* () {
157 const requests = yield* McpAppRequests.McpAppRequests;
158 const result = yield* requests.callTool({
159 threadId,
160 itemId,
161 name: "refresh",
162 arguments: {},
163 });
164 assert.deepEqual(result, { content: [{ type: "text", text: "ok" }] });
165 assert.deepEqual(calls.at(-1), { server: "weather", tool: "refresh" });
166 assert.deepEqual(yield* requests.toolInfo({ threadId, itemId, name: "refresh" }), {
167 callable: true,
168 readOnly: true,
169 tool: { name: "refresh", annotations: { readOnlyHint: true } },
170 });
171 }).pipe(Effect.provide(makeLayer({ item: appItem({ t3McpApp: app }), mcpApps }))),
172 );
173
174 it.effect("refuses tools hidden from apps or missing from the server", () =>
175 Effect.gen(function* () {
176 const requests = yield* McpAppRequests.McpAppRequests;
177 const before = calls.length;
178 for (const name of ["model_only", "unknown"]) {
179 assert.equal(
180 yield* reason(requests.callTool({ threadId, itemId, name, arguments: {} })),
181 "tool-not-callable",
182 );
183 }
184 assert.equal(calls.length, before);
185 }).pipe(Effect.provide(makeLayer({ item: appItem({ t3McpApp: app }), mcpApps }))),
186 );
187
188 it.effect("keeps each app's latest model context, without a live session", () =>
189 Effect.gen(function* () {
190 const requests = yield* McpAppRequests.McpAppRequests;
191 const own = { threadId, itemId, conversationThreadId: threadId };
192 // The app's text is stored as sent, whitespace included.
193 yield* requests.updateModelContext({
194 ...own,
195 content: [{ type: "text", text: " indented value " }],
196 });
197 assert.equal(storedContext.get(`${threadId}/${itemId}`), " indented value ");
198 // An update replaces the app's context rather than adding to it.
199 yield* requests.updateModelContext({
200 ...own,
201 content: [{ type: "text", text: "Filtered to overdue" }],
202 structuredContent: { filter: "overdue" },
203 });
204 assert.equal(
205 storedContext.get(`${threadId}/${itemId}`),
206 'Filtered to overdue\n{"filter":"overdue"}',
207 );
208 assert.equal(
209 yield* reason(
210 requests.updateModelContext({ ...own, content: [{ type: "image", data: "x" }] }),
211 ),
212 "unsupported-content",
213 );
214 // The cap is in UTF-8 bytes: 6,000 three-byte characters exceed 16 KiB.
215 assert.equal(
216 yield* reason(
217 requests.updateModelContext({
218 ...own,
219 content: [{ type: "text", text: "表".repeat(6000) }],
220 }),
221 ),
222 "request-failed",
223 );
224 yield* requests.updateModelContext(own);
225 assert.isFalse(storedContext.has(`${threadId}/${itemId}`));
226 }).pipe(Effect.provide(makeLayer({ item: appItem({ t3McpApp: app }), live: false }))),
227 );
228
229 it.effect("stores a fork's model context under the fork, and refuses unrelated threads", () =>
230 Effect.gen(function* () {
231 const requests = yield* McpAppRequests.McpAppRequests;
232 const content = [{ type: "text", text: "Seen from the fork" }];
233 yield* requests.updateModelContext({
234 threadId,
235 itemId,
236 conversationThreadId: forkId,
237 content,
238 });
239 assert.equal(storedContext.get(`${forkId}/${itemId}`), "Seen from the fork");
240 assert.isFalse(storedContext.has(`${threadId}/${itemId}`));
241 assert.equal(
242 yield* reason(
243 requests.updateModelContext({
244 threadId,
245 itemId,
246 conversationThreadId: unrelatedId,
247 content,
248 }),
249 ),
250 "not-an-app",
251 );
252 // However many forks deep, a descendant still counts.
253 yield* requests.updateModelContext({
254 threadId,
255 itemId,
256 conversationThreadId: deepForkId(70),
257 content,
258 });
259 assert.isTrue(storedContext.has(`${deepForkId(70)}/${itemId}`));
260 }).pipe(Effect.provide(makeLayer({ item: appItem({ t3McpApp: app }), live: false }))),
261 );
262
263 it.effect("reports why a request cannot run", () =>
264 Effect.gen(function* () {
265 const run = (layer: ReturnType<typeof makeLayer>) =>
266 Effect.gen(function* () {
267 const requests = yield* McpAppRequests.McpAppRequests;
268 return yield* reason(requests.readResource({ threadId, itemId, uri: "ui://weather/x" }));
269 }).pipe(Effect.provide(layer));
270 assert.equal(
271 yield* run(makeLayer({ item: appItem({ result: "plain" }), mcpApps })),
272 "not-an-app",
273 );
274 assert.equal(
275 yield* run(makeLayer({ item: appItem({ t3McpApp: app }), mcpApps, live: false })),
276 "session-stopped",
277 );
278 assert.equal(
279 yield* run(makeLayer({ item: appItem({ t3McpApp: app }) })),
280 "provider-unsupported",
281 );
282 }),
283 );
284});