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

McpAppRequests.test.ts

254 lines8.8 KB

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