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

PeerMcpClient.test.ts

385 lines14.6 KB

1import { NodeHttpServer } from "@effect/platform-node";
2import { expect, it } from "@effect/vitest";
3import {
4 EnvironmentId,
5 OrchestrationV2LinkedSender,
6 OrchestratorMcpFailure,
7 ThreadId,
8} from "@t3tools/contracts";
9import * as Context from "effect/Context";
10import * as DateTime from "effect/DateTime";
11import * as Deferred from "effect/Deferred";
12import * as Duration from "effect/Duration";
13import * as Effect from "effect/Effect";
14import * as Fiber from "effect/Fiber";
15import * as Layer from "effect/Layer";
16import * as Queue from "effect/Queue";
17import * as Ref from "effect/Ref";
18import * as Schema from "effect/Schema";
19import { Tool, Toolkit } from "effect/ai";
20import * as TestClock from "effect/testing/TestClock";
21import { HttpClient, HttpClientResponse } from "effect/http";
22​
23import * as McpHttpServer from "../mcp/McpHttpServer.ts";
24import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
25import * as McpToolAccess from "../mcp/McpToolAccess.ts";
26import * as PeerLinks from "./PeerLinks.ts";
27import * as PeerMcpClient from "./PeerMcpClient.ts";
28import { descriptorOf, layerLinkingEnvironment, linkTo, servePeer } from "./PeerLinks.testkit.ts";
29​
30const Result = Schema.Struct({ modes: Schema.String });
31const toolkit = Toolkit.make(
32 Tool.make("probe", {
33 description: "Returns this request's mode limits.",
34 success: Result,
35 dependencies: [McpInvocationContext.McpInvocationContext],
36 }),
37 Tool.make("hold", {
38 description: "Holds a tool request open.",
39 success: Result,
40 dependencies: [McpInvocationContext.McpInvocationContext],
41 }),
42 Tool.make("refuse", {
43 description: "Refuses the call.",
44 success: Result,
45 failure: OrchestratorMcpFailure,
46 failureMode: "return",
47 }),
48);
49​
50/** One `probe` call to a linked peer at a remote address, answered by `http`. */
51const probeThrough = Effect.fn(function* (http: HttpClient.HttpClient) {
52 const box = descriptorOf("environment-box", "Box");
53 const context = yield* Layer.build(
54 PeerMcpClient.layer.pipe(
55 Layer.provide(
56 Layer.mergeAll(
57 Layer.succeed(HttpClient.HttpClient, http),
58 Layer.mock(PeerLinks.PeerLinks)({
59 resolve: () =>
60 Effect.succeed({
61 link: {
62 environmentId: box.environmentId,
63 label: box.label,
64 urls: ["https://peer.example"],
65 access: "auto",
66 linkedAt: DateTime.makeUnsafe(0),
67 expiresAt: DateTime.makeUnsafe(1),
68 lastReachedAt: null,
69 lastError: null,
70 },
71 url: "https://peer.example",
72 token: "fixture",
73 }),
74 recordOutcome: () => Effect.void,
75 }),
76 ),
77 ),
78 ),
79 );
80 return Context.get(context, PeerMcpClient.PeerMcpClient).call({
81 environmentId: box.environmentId,
82 tool: "probe",
83 arguments: {},
84 limits: { runtimeMode: "approval-required", interactionMode: "plan" },
85 success: Result,
86 });
87});
88​
89const probeResult = JSON.stringify({
90 result: { content: [{ type: "text", text: '{"modes":"approval-required/plan"}' }] },
91});
92​
93const refusal = new OrchestratorMcpFailure({
94 code: "thread_not_found",
95 message: "Thread thread-gone was not found.",
96});
97​
98const senderToolkit = Toolkit.make(
99 Tool.make("sender", {
100 description: "Returns the thread this request is made for.",
101 success: Schema.Struct({ senderThread: Schema.NullOr(OrchestrationV2LinkedSender) }),
102 dependencies: [McpInvocationContext.McpInvocationContext],
103 }),
104);
105​
106it.effect("tells the peer which thread a call is made for", () =>
107 Effect.scoped(
108 Effect.gen(function* () {
109 const handlers = McpToolAccess.toLayer(senderToolkit, {
110 sender: McpToolAccess.reads(() =>
111 McpInvocationContext.McpInvocationContext.pipe(
112 Effect.map((scope) => ({ senderThread: scope.client?.senderThread ?? null })),
113 ),
114 ),
115 });
116 const box = descriptorOf("environment-box", "Box");
117 const b = yield* servePeer(box, McpHttpServer.toolkitRegistration(senderToolkit, handlers));
118 const context = yield* Layer.build(
119 layerLinkingEnvironment(descriptorOf("environment-a", "A")),
120 );
121 const links = Context.get(context, PeerLinks.PeerLinks);
122 const client = Context.get(context, PeerMcpClient.PeerMcpClient);
123 yield* linkTo(links, b);
124 // A thread id may hold any character; it arrives as sent.
125 const sender = {
126 environmentId: EnvironmentId.make("environment-a"),
127 threadId: ThreadId.make("import:claude/orc lead"),
128 title: "orc lead / opus → fable",
129 };
130 const call = (input: { readonly sender?: typeof sender }) =>
131 client.call({
132 environmentId: box.environmentId,
133 tool: "sender",
134 arguments: {},
135 limits: { runtimeMode: "full-access", interactionMode: "default" },
136 ...input,
137 success: Schema.Struct({ senderThread: Schema.NullOr(OrchestrationV2LinkedSender) }),
138 });
139 expect(yield* call({ sender })).toEqual({ senderThread: sender });
140 expect(yield* call({})).toEqual({ senderThread: null });
141 // A long title is cut to whole characters rather than breaking the call.
142 const long = yield* call({ sender: { ...sender, title: "🧵".repeat(5000) } });
143 expect(long.senderThread?.title).toBe("🧵".repeat(200));
144 // A title holding an unpaired surrogate still lets the call through.
145 const broken = yield* call({ sender: { ...sender, title: "Review \ud800" } });
146 expect(broken.senderThread?.title).toBe("Review \ufffd");
147 }),
148 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
149);
150​
151it.effect.each([false, true])(
152 "reuses an initialized session before its first call finishes (cancelled: %s)",
153 (cancelFirst) =>
154 Effect.scoped(
155 Effect.gen(function* () {
156 const entered = yield* Deferred.make<void>();
157 const release = yield* Deferred.make<void>();
158 const modes = McpInvocationContext.McpInvocationContext.pipe(
159 Effect.map((scope) => {
160 const ceiling = McpInvocationContext.clientModeCeiling(scope.client);
161 return { modes: `${ceiling.runtimeMode}/${ceiling.interactionMode}` };
162 }),
163 );
164 const handlers = McpToolAccess.toLayer(toolkit, {
165 probe: McpToolAccess.reads(() => modes),
166 refuse: McpToolAccess.reads(() => Effect.fail(refusal)),
167 hold: McpToolAccess.reads(() =>
168 Deferred.succeed(entered, undefined).pipe(
169 Effect.andThen(Deferred.await(release)),
170 Effect.andThen(modes),
171 ),
172 ),
173 });
174 const box = descriptorOf("environment-box", "Box");
175 const b = yield* servePeer(box, McpHttpServer.toolkitRegistration(toolkit, handlers));
176 const context = yield* Layer.build(
177 layerLinkingEnvironment(descriptorOf("environment-a", "A")),
178 );
179 const links = Context.get(context, PeerLinks.PeerLinks);
180 const client = Context.get(context, PeerMcpClient.PeerMcpClient);
181 yield* linkTo(links, b);
182 const held = yield* client
183 .call({
184 environmentId: box.environmentId,
185 tool: "hold",
186 arguments: {},
187 limits: { runtimeMode: "full-access", interactionMode: "default" },
188 success: Result,
189 })
190 .pipe(Effect.forkScoped);
191 yield* Deferred.await(entered);
192 if (cancelFirst) yield* Fiber.interrupt(held);
193 const before = (yield* Ref.get(b.bearers)).length;
194 expect(
195 yield* client.call({
196 environmentId: box.environmentId,
197 tool: "probe",
198 arguments: {},
199 limits: { runtimeMode: "approval-required", interactionMode: "plan" },
200 success: Result,
201 }),
202 ).toEqual({ modes: "approval-required/plan" });
203 // One tool POST; no second initialize or initialized notification.
204 expect((yield* Ref.get(b.bearers)).length - before).toBe(1);
205 yield* Deferred.succeed(release, undefined);
206 if (!cancelFirst) expect(yield* Fiber.join(held)).toEqual({ modes: "auto/default" });
207 }),
208 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
209);
210​
211it.effect("keeps a link healthy when the peer refuses a call", () =>
212 Effect.scoped(
213 Effect.gen(function* () {
214 const handlers = McpToolAccess.toLayer(toolkit, {
215 probe: McpToolAccess.reads(() => Effect.succeed({ modes: "" })),
216 hold: McpToolAccess.reads(() => Effect.succeed({ modes: "" })),
217 refuse: McpToolAccess.reads(() => Effect.fail(refusal)),
218 });
219 const box = descriptorOf("environment-box", "Box");
220 const b = yield* servePeer(box, McpHttpServer.toolkitRegistration(toolkit, handlers));
221 const context = yield* Layer.build(
222 layerLinkingEnvironment(descriptorOf("environment-a", "A")),
223 );
224 const links = Context.get(context, PeerLinks.PeerLinks);
225 const client = Context.get(context, PeerMcpClient.PeerMcpClient);
226 yield* linkTo(links, b);
227 yield* links.recordOutcome(box.environmentId, { error: "earlier outage" });
228 const refused = yield* client
229 .call({
230 environmentId: box.environmentId,
231 tool: "refuse",
232 arguments: {},
233 limits: { runtimeMode: "full-access", interactionMode: "default" },
234 success: Result,
235 })
236 .pipe(Effect.flip);
237 // The agent hears the peer's own refusal; the link answered, so it is not failing.
238 expect(refused).toMatchObject({ code: refusal.code, message: refusal.message });
239 const link = yield* links.get(box.environmentId);
240 expect(link._tag === "Some" ? link.value.lastError : "missing").toBeNull();
241 }),
242 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
243);
244​
245it.effect("renews a missing peer session once and reuses its replacement", () =>
246 Effect.gen(function* () {
247 const sessionHeaders: Array<string | undefined> = [];
248 const statuses = [200, 202, 404, 200, 202, 200, 200, 200];
249 const outcomes: Array<string | null> = [];
250 const http = HttpClient.make((request) =>
251 Effect.sync(() => {
252 const index = sessionHeaders.length;
253 sessionHeaders.push(request.headers["mcp-session-id"]);
254 const status = statuses[index];
255 if (status === undefined) throw new Error("Unexpected retry");
256 return HttpClientResponse.fromWeb(
257 request,
258 new Response(
259 index === 7
260 ? "{}"
261 : index >= 5
262 ? JSON.stringify({
263 result: {
264 content: [{ type: "text", text: '{"modes":"approval-required/plan"}' }],
265 },
266 })
267 : "",
268 {
269 status,
270 headers:
271 index === 0
272 ? { "mcp-session-id": "old" }
273 : index === 3
274 ? { "mcp-session-id": "renewed" }
275 : {},
276 },
277 ),
278 );
279 }),
280 );
281 const box = descriptorOf("environment-box", "Box");
282 const context = yield* Layer.build(
283 PeerMcpClient.layer.pipe(
284 Layer.provide(
285 Layer.mergeAll(
286 Layer.succeed(HttpClient.HttpClient, http),
287 Layer.mock(PeerLinks.PeerLinks)({
288 resolve: () =>
289 Effect.succeed({
290 link: {
291 environmentId: box.environmentId,
292 label: box.label,
293 urls: ["https://peer.example"],
294 access: "auto",
295 linkedAt: DateTime.makeUnsafe(0),
296 expiresAt: DateTime.makeUnsafe(1),
297 lastReachedAt: null,
298 lastError: null,
299 },
300 url: "https://peer.example",
301 token: "fixture",
302 }),
303 recordOutcome: (_, outcome) => Effect.sync(() => outcomes.push(outcome.error)),
304 }),
305 ),
306 ),
307 ),
308 );
309 const client = Context.get(context, PeerMcpClient.PeerMcpClient);
310 for (let call = 0; call < 2; call++) {
311 expect(
312 yield* client.call({
313 environmentId: box.environmentId,
314 tool: "probe",
315 arguments: {},
316 limits: { runtimeMode: "approval-required", interactionMode: "plan" },
317 success: Result,
318 }),
319 ).toEqual({ modes: "approval-required/plan" });
320 }
321 // An answer with neither a result nor an error is the link's problem, not the call's.
322 const empty = yield* client
323 .call({
324 environmentId: box.environmentId,
325 tool: "probe",
326 arguments: {},
327 limits: { runtimeMode: "approval-required", interactionMode: "plan" },
328 success: Result,
329 })
330 .pipe(Effect.flip);
331 expect(outcomes).toEqual([null, null, empty.message]);
332 expect(sessionHeaders).toEqual([
333 undefined,
334 "old",
335 "old",
336 undefined,
337 "renewed",
338 "renewed",
339 "renewed",
340 "renewed",
341 ]);
342 }).pipe(Effect.scoped),
343);
344​
345it.effect("bounds the session handshake, not a tool call that waits longer", () =>
346 Effect.gen(function* () {
347 const arrived = yield* Queue.unbounded<number>();
348 const answer = yield* Deferred.make<void>();
349 let requests = 0;
350 const http = HttpClient.make((request) =>
351 Effect.gen(function* () {
352 const index = requests++;
353 yield* Queue.offer(arrived, index);
354 // The first initialize, then the next initialized notification, never answer;
355 // the third session's tool call answers late.
356 if (index === 0 || index === 2) return yield* Effect.never;
357 if (index === 5) yield* Deferred.await(answer);
358 return HttpClientResponse.fromWeb(
359 request,
360 new Response(index === 5 ? probeResult : "", {
361 status: index === 4 ? 202 : 200,
362 headers: { "mcp-session-id": "session" },
363 }),
364 );
365 }),
366 );
367 const probe = yield* probeThrough(http);
368​
369 for (const requestsBeforeStall of [1, 2]) {
370 const stalled = yield* probe.pipe(Effect.flip, Effect.forkScoped);
371 yield* Queue.takeN(arrived, requestsBeforeStall);
372 yield* TestClock.adjust(Duration.seconds(10));
373 expect(yield* Fiber.join(stalled)).toMatchObject({
374 code: "orchestration_error",
375 message: "The linked environment stopped answering.",
376 });
377 }
378​
379 const waiting = yield* Effect.forkScoped(probe);
380 yield* Queue.takeN(arrived, 3);
381 yield* TestClock.adjust(Duration.minutes(1));
382 yield* Deferred.succeed(answer, undefined);
383 expect(yield* Fiber.join(waiting)).toEqual({ modes: "approval-required/plan" });
384 }).pipe(Effect.scoped),
385);