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

mcpExtensionSource.test.ts

551 lines21.3 KB

1// @effect-diagnostics nodeBuiltinImport:off -- Pi extensions run outside Effect; these tests exercise their native filesystem boundary.
2import * as NodeFSP from "node:fs/promises";
3import * as NodePath from "node:path";
4import * as NodeOS from "node:os";
5import * as NodeModule from "node:module";
6import * as NodeVM from "node:vm";
7import { assert, describe, it } from "@effect/vitest";
8​
9import { PI_T3_MCP_EXTENSION_SOURCE } from "./mcpExtensionSource.ts";
10import { loadMcpBridge } from "./mcpBridge.testkit.ts";
11​
12type RequestHook = (
13 event: { payload: unknown },
14 ctx: { model: { provider: string } },
15) => Record<string, unknown> | undefined;
16​
17interface SkillCommand {
18 readonly name: string;
19 readonly source: string;
20 readonly sourceInfo: { readonly path: string };
22​
23type InputHook = (
24 event: { text: string; images?: ReadonlyArray<unknown> },
25 ctx: { ui: { notify: (message: string, level: string) => void } },
26) => Promise<{ action: string; text: string; images?: ReadonlyArray<unknown> } | undefined>;
27​
28async function loadHooks(
29 commands: ReadonlyArray<SkillCommand> = [],
30 argv: ReadonlyArray<string> = [],
31) {
32 const handlers = new Map<string, unknown>();
33 const source = NodeModule.stripTypeScriptTypes(
34 PI_T3_MCP_EXTENSION_SOURCE.replace(/^import .*;$/gm, "").replace(
35 "export default async function",
36 "async function",
37 ),
38 );
39 await NodeVM.runInNewContext(`${source}\nt3McpExtension(pi)`, {
40 process: { env: {}, argv },
41 NodeFSP,
42 NodePath,
43 stripFrontmatter: (content: string) => content,
44 pi: {
45 on: (name: string, handler: unknown) => handlers.set(name, handler),
46 getCommands: () => commands,
47 },
48 });
49 return handlers;
51​
52describe("Pi orchestration prompt section", () => {
53 it.each([
54 {
55 name: "on Pi builds without prompt sections",
56 events: [
57 { systemPrompt: "base" },
58 { systemPrompt: "base", systemPromptOptions: {} },
59 { systemPrompt: "base", systemPromptOptions: { sections: null } },
60 ],
61 },
62 {
63 name: "when an earlier extension forces the system prompt",
64 events: [
65 {
66 systemPrompt: "forced",
67 systemPromptOptions: { sections: {}, forceSystemPrompt: "forced" },
68 },
69 ],
70 },
71 ])("appends guidance $name", async ({ events }) => {
72 const bridge = await loadMcpBridge();
73 const hook = bridge.handlers.get("before_agent_start")!;
74 for (const event of events) {
75 const result = await hook(event, { ui: { notify: assert.fail } });
76 assert.isDefined(result);
77 assert.isTrue(result!.systemPrompt.startsWith(`${event.systemPrompt}\n\n`));
78 assert.include(result!.systemPrompt, "orchestrator_capabilities");
79 }
80 });
81});
82​
83describe("Pi project trust", () => {
84 it.each([
85 { name: "a trusted folder", trusted: true, argv: [], notices: 0 },
86 { name: "an untrusted folder", trusted: false, argv: [], notices: 1 },
87 { name: "--no-approve", trusted: false, argv: ["--approve", "-na"], notices: 0 },
88 ])("sends $notices trust notice per session for $name", async ({ trusted, argv, notices }) => {
89 const sent: string[] = [];
90 const ctx = {
91 cwd: "/repo",
92 isProjectTrusted: () => trusted,
93 ui: { notify: (message: string) => sent.push(message) },
94 };
95 // Pi reruns extension factories on session replacement without asking about trust again.
96 for (const _session of [1, 2]) {
97 const handlers = (await loadHooks([], ["node", "pi", ...argv])) as Map<
98 string,
99 (event: unknown, ctx: unknown) => unknown
100 >;
101 for (const _turn of [1, 2]) await handlers.get("before_agent_start")!({}, ctx);
102 }
103 assert.equal(sent.length, notices * 2);
104 for (const message of sent)
105 assert.include(message, "for /repo because the folder is not trusted");
106 });
107});
108​
109describe("Pi MCP tool results", () => {
110 it("returns mixed screenshot blocks and typed script output without repeating structured text", async () => {
111 const content = [
112 { type: "text", text: "Browser screenshot" },
113 { type: "image", data: "AAAA", mimeType: "image/png", _meta: { private: true } },
114 { type: "text", text: "Screenshot captured" },
115 ] as const;
116 const result = { content, structuredContent: { count: 2 }, _meta: { private: true } };
117 const bridge = await loadMcpBridge({ modern: true, result });
118 const tool = bridge.tools.find((tool) => tool.name === "mcp__t3-code__preview_snapshot")!;
119 const output = await tool.execute("snapshot", {});
120 assert.deepEqual(output.content, [
121 content[0],
122 { type: "image", data: "AAAA", mimeType: "image/png" },
123 content[2],
124 ]);
125 assert.deepEqual(output.structuredContent, { content, structuredContent: { count: 2 } });
126 assert.deepEqual(tool.outputSchema, {
127 type: "object",
128 properties: {
129 content: { type: "array", items: { type: "object" } },
130 structuredContent: { type: "object", properties: { count: { type: "number" } } },
131 isError: { type: "boolean" },
132 _meta: { type: "object" },
133 },
134 required: ["content"],
135 });
136 });
137​
138 it.each([false, true])(
139 "preserves image-only results and error status, isError=%s",
140 async (isError) => {
141 const image = { type: "image", data: "AAAA", mimeType: "image/png" };
142 const result = { content: [image], isError };
143 const bridge = await loadMcpBridge({ result });
144 const output = await bridge.tools[0]!.execute("image", {});
145 assert.deepEqual(output.content[0], image);
146 assert.equal(output.content.length, isError ? 2 : 1);
147 if (isError) assert.include(output.content[1]?.text ?? "", "returned an error");
148 assert.equal(output.isError, isError ? true : undefined);
149 assert.deepEqual(output.structuredContent, result);
150 },
151 );
152​
153 it("uses structured output as model text when content is empty", async () => {
154 const result = { content: [], structuredContent: { count: 2 } };
155 const bridge = await loadMcpBridge({ result });
156 const output = await bridge.tools[0]!.execute("structured", {});
157 assert.deepEqual(output.content, [{ type: "text", text: '{"count":2}' }]);
158 assert.deepEqual(output.structuredContent, result);
159 });
160});
161​
162describe("Pi MCP tool exposure", () => {
163 const discoveryContext = {
164 model: { api: "anthropic-messages" },
165 ui: { notify: () => undefined },
166 };
167​
168 it("keeps orchestration direct and optional bridge tools discoverable on modern Pi", async () => {
169 const bridge = await loadMcpBridge({ modern: true, toolSearchAvailable: true });
170 await bridge.handlers.get("session_start")!({ systemPrompt: "" }, discoveryContext);
171 const start = bridge.handlers.get("before_agent_start");
172 assert.isDefined(start);
173 const prompt = await start!({ systemPrompt: "Pi system prompt" }, discoveryContext);
174 assert.include(prompt?.systemPrompt ?? "", "orchestrator_capabilities");
175 assert.equal(bridge.servers.length, 0);
176 assert.equal(bridge.tools.length, 8);
177 assert.deepEqual(bridge.getActiveTools(), ["read", "tool_search"]);
178 assert.deepEqual(
179 bridge.tools
180 .filter((tool) => tool.exposure !== "hidden")
181 .map((tool) => [tool.name, tool.exposure]),
182 [
183 ["mcp__t3-code__orchestrator_capabilities", "direct"],
184 ["mcp__t3-code__delegate_task", "direct"],
185 ["mcp__t3-code__task_status", "direct"],
186 ["mcp__t3-code__preview_snapshot", "deferred"],
187 ],
188 );
189 assert.deepEqual(
190 bridge.tools.filter((tool) => tool.exposure === "hidden").map((tool) => tool.name),
191 [
192 "mcp__t3_code__orchestrator_capabilities",
193 "mcp__t3_code__delegate_task",
194 "mcp__t3_code__task_status",
195 "mcp__t3_code__preview_snapshot",
196 ],
197 );
198 const result = await bridge.tools
199 .find((tool) => tool.name === "mcp__t3-code__preview_snapshot")!
200 .execute("call-1", { depth: 2 });
201 assert.equal(result.content[0]?.text, "browser snapshot");
202 assert.equal(bridge.requests.at(-1)?.method, "tools/call");
203 });
204​
205 it("restores gateway declarations after model switches and older tree loadouts without excluded tools", async () => {
206 const bridge = await loadMcpBridge({
207 modern: true,
208 toolSearchAvailable: true,
209 allowsTool: (name) => name !== "mcp__t3-code__delegate_task",
210 });
211 const event = { systemPrompt: "" };
212 await bridge.handlers.get("session_start")!(event, discoveryContext);
213 const gatewayContext = { model: { api: "openai-completions" }, ui: { notify: assert.fail } };
214 await bridge.handlers.get("model_select")!(event, gatewayContext);
215 bridge.restoreActiveTools(["read", "mcp__t3-code__task_status"]);
216 await bridge.handlers.get("session_tree")!(event, gatewayContext);
217 assert.deepEqual(bridge.getActiveTools(), [
218 "read",
219 "mcp__t3-code__task_status",
220 "tool_search",
221 "mcp__t3-code__orchestrator_capabilities",
222 "mcp__t3-code__preview_snapshot",
223 ]);
224 await bridge.handlers.get("model_select")!(event, discoveryContext);
225 assert.equal(
226 bridge.tools.find((tool) => tool.name === "mcp__t3-code__preview_snapshot")?.exposure,
227 "deferred",
228 );
229 assert.include(bridge.getActiveTools(), "mcp__t3-code__preview_snapshot");
230 });
231​
232 it.each(["legacy Pi", "disabled tool search"])(
233 "keeps tool execution available with %s",
234 async (mode) => {
235 const bridge = await loadMcpBridge({
236 modern: mode !== "legacy Pi",
237 toolSearchAvailable: mode === "disabled tool search",
238 toolSearchDisabled: mode === "disabled tool search",
239 });
240 if (mode !== "legacy Pi") {
241 const start = bridge.handlers.get("session_start");
242 await start!({ systemPrompt: "Pi system prompt" }, discoveryContext);
243 }
244 assert.equal(bridge.tools.filter((tool) => tool.exposure !== "hidden").length, 4);
245 assert.isTrue(
246 bridge.tools
247 .filter((tool) => tool.exposure !== "hidden")
248 .every((tool) => tool.exposure === undefined || tool.exposure === "direct"),
249 );
250 const tool = bridge.tools.find((tool) => tool.name === "mcp__t3-code__preview_snapshot");
251 assert.isDefined(tool);
252 const controller = new AbortController();
253 const result = await tool!.execute("call-1", { depth: 2 }, controller.signal);
254 assert.equal(result.content[0]?.text, "browser snapshot");
255 assert.strictEqual(bridge.transports.at(-1)?.signal, controller.signal);
256 assert.equal(bridge.transports.at(-1)?.url, "http://fixture.invalid/mcp");
257 assert.equal(bridge.transports.at(-1)?.authorization, "Bearer fixture-token");
258 assert.deepEqual(JSON.parse(JSON.stringify(bridge.requests.at(-1))), {
259 jsonrpc: "2.0",
260 id: 3,
261 method: "tools/call",
262 params: { name: "preview_snapshot", arguments: { depth: 2 } },
263 });
264 assert.isUndefined(tool?.promptSnippet);
265 assert.isUndefined(tool?.promptGuidelines);
266 },
267 );
268});
269​
270describe("Pi MCP tool schemas", () => {
271 it.each([{ type: "object" }, {}])(
272 "declares empty properties on object schemas that omit them: %j",
273 async (inputSchema) => {
274 const bridge = await loadMcpBridge({ inputSchema });
275 assert.isAbove(bridge.tools.length, 0);
276 for (const tool of bridge.tools) {
277 assert.deepEqual(tool.parameters, { type: "object", properties: {} });
278 }
279 },
280 );
281​
282 it("keeps declared properties and other schema keywords", async () => {
283 const inputSchema = {
284 type: "object",
285 properties: { depth: { type: "number" } },
286 required: ["depth"],
287 additionalProperties: false,
288 };
289 const bridge = await loadMcpBridge({ inputSchema });
290 for (const tool of bridge.tools) {
291 assert.deepEqual(tool.parameters, inputSchema);
292 }
293 });
294});
295​
296describe("Pi tool discovery permissions", () => {
297 it.each(["approval-required", "auto-accept-edits", "auto"])(
298 "allows annotated T3 reads in %s while gating mutations and replacements",
299 async (runtimeMode) => {
300 const bridge = await loadMcpBridge({ modern: true, runtimeMode });
301 const hook = bridge.handlers.get("tool_call") as unknown as (
302 event: { toolName: string; input: unknown },
303 ctx: { ui: { confirm: (title: string) => Promise<boolean> } },
304 ) => Promise<{ block: true; reason: string } | undefined>;
305 const confirmations: string[] = [];
306 const ctx = {
307 ui: {
308 confirm: async (title: string) => {
309 confirmations.push(title);
310 return false;
311 },
312 },
313 };
314 for (const prefix of ["mcp__t3-code__", "mcp__t3_code__"]) {
315 assert.isUndefined(
316 await hook({ toolName: prefix + "orchestrator_capabilities", input: {} }, ctx),
317 );
318 assert.equal(
319 (await hook({ toolName: prefix + "delegate_task", input: {} }, ctx))?.block,
320 true,
321 );
322 assert.equal(
323 (await hook({ toolName: prefix + "task_status", input: {} }, ctx))?.block,
324 true,
325 );
326 }
327 assert.equal(confirmations.length, 4);
328 bridge.setBridgeSourcePath("/user/extensions/replacement.ts");
329 assert.equal(
330 (await hook({ toolName: "mcp__t3-code__orchestrator_capabilities", input: {} }, ctx))
331 ?.block,
332 true,
333 );
334 assert.equal(
335 (await hook({ toolName: "mcp__other__orchestrator_capabilities", input: {} }, ctx))?.block,
336 true,
337 );
338 assert.equal(confirmations.length, 6);
339 },
340 );
341​
342 it("allows discovery without confirmation and still gates the discovered tool", async () => {
343 type ToolCallHook = (
344 event: { toolName: string; input: unknown },
345 ctx: {
346 signal: AbortSignal;
347 ui: {
348 confirm: (
349 title: string,
350 detail: string,
351 options: { signal: AbortSignal },
352 ) => Promise<boolean>;
353 };
354 },
355 ) => Promise<{ block: true; reason: string } | undefined>;
356 let toolCall: ToolCallHook | undefined;
357 let searchPath = "builtin:tool-search";
358 const source = NodeModule.stripTypeScriptTypes(
359 PI_T3_MCP_EXTENSION_SOURCE.replace(/^import .*;$/gm, "").replace(
360 "export default async function",
361 "async function",
362 ),
363 );
364 await NodeVM.runInNewContext(`${source}\nt3McpExtension(pi)`, {
365 process: { env: { T3_PI_RUNTIME_MODE: "approval-required" } },
366 pi: {
367 on: (name: string, handler: ToolCallHook) => {
368 if (name === "tool_call") toolCall = handler;
369 },
370 getAllTools: () => [{ name: "tool_search", sourceInfo: { path: searchPath } }],
371 },
372 });
373 assert.isDefined(toolCall);
374 const confirmations: string[] = [];
375 const controller = new AbortController();
376 const ctx = {
377 signal: controller.signal,
378 ui: {
379 confirm: async (title: string, _detail: string, options: { signal: AbortSignal }) => {
380 assert.strictEqual(options.signal, controller.signal);
381 confirmations.push(title);
382 return false;
383 },
384 },
385 };
386 assert.isUndefined(
387 await toolCall!({ toolName: "tool_search", input: { query: "preview_snapshot" } }, ctx),
388 );
389 assert.equal(confirmations.length, 0);
390 const result = await toolCall!({ toolName: "mcp__t3-code__preview_snapshot", input: {} }, ctx);
391 assert.equal(result?.block, true);
392 assert.deepEqual(confirmations, ["Allow mcp__t3-code__preview_snapshot?"]);
393​
394 searchPath = "/extensions/custom-search.ts";
395 const replaced = await toolCall!({ toolName: "tool_search", input: {} }, ctx);
396 assert.equal(replaced?.block, true);
397 assert.equal(confirmations.at(-1), "Allow tool_search?");
398 });
399});
400​
401async function loadRequestHook(): Promise<RequestHook> {
402 const handlers = new Map<string, RequestHook>();
403 const source = NodeModule.stripTypeScriptTypes(
404 PI_T3_MCP_EXTENSION_SOURCE.replace(/^import .*;$/gm, "").replace(
405 "export default async function",
406 "async function",
407 ),
408 );
409 await NodeVM.runInNewContext(`${source}\nt3McpExtension(pi)`, {
410 process: { env: {} },
411 pi: { on: (name: string, handler: RequestHook) => handlers.set(name, handler) },
412 });
413 const hook = handlers.get("before_provider_request");
414 assert.isDefined(hook);
415 return hook!;
417​
418describe("Pi upstream output-budget workaround", () => {
419 it.each(["max_tokens", "max_completion_tokens"])(
420 "caps %s without changing the conversation or tools",
421 async (key) => {
422 const hook = await loadRequestHook();
423 const payload = {
424 model: "moonshotai/kimi-k2.6",
425 messages: [{ role: "user", content: "hello" }],
426 tools: [{ type: "function", function: { name: "read" } }],
427 [key]: 231_969,
428 };
429 const result = hook({ payload }, { model: { provider: "openrouter" } });
430 assert.equal(result?.[key], 32_768);
431 assert.strictEqual(result?.messages, payload.messages);
432 assert.strictEqual(result?.tools, payload.tools);
433 assert.equal(result?.model, payload.model);
434 assert.equal(payload[key], 231_969);
435 },
436 );
437​
438 it("preserves smaller budgets and other providers' payloads", async () => {
439 const hook = await loadRequestHook();
440 for (const payload of [{ max_tokens: 8192 }, { max_completion_tokens: 32_768 }, {}, null]) {
441 assert.isUndefined(hook({ payload }, { model: { provider: "openrouter" } }));
442 }
443 assert.isUndefined(
444 hook({ payload: { max_tokens: 231_969 } }, { model: { provider: "anthropic" } }),
445 );
446 });
447});
448​
449async function loadInputHook(commands: ReadonlyArray<SkillCommand>) {
450 const handlers = await loadHooks(commands);
451 const hook = handlers.get("input");
452 assert.isDefined(hook);
453 return hook as InputHook;
455​
456describe("Pi skill references", () => {
457 it("loads every selected skill once while preserving inline prose, whitespace, and images", async () => {
458 const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "pi-skill-mentions-"));
459 try {
460 const alpha = NodePath.join(directory, "alpha.md");
461 const beta = NodePath.join(directory, "beta.md");
462 await NodeFSP.writeFile(alpha, "ALPHA_INSTRUCTIONS");
463 await NodeFSP.writeFile(beta, "BETA_INSTRUCTIONS");
464 const hook = await loadInputHook([
465 { name: "skill:alpha", source: "skill", sourceInfo: { path: alpha } },
466 { name: "skill:beta", source: "skill", sourceInfo: { path: beta } },
467 ]);
468 const text =
469 "Please use the $alpha philosophy, then $beta and $alpha\n```ts\n const x = 1;\n```";
470 const images = [{ type: "image", data: "fixture" }];
471 const result = await hook({ text, images }, { ui: { notify: assert.fail } });
472 assert.equal(result?.action, "transform");
473 assert.isTrue(result?.text.startsWith(text + "\n\n"));
474 assert.equal(result?.text.split("ALPHA_INSTRUCTIONS").length, 2);
475 assert.equal(result?.text.split("BETA_INSTRUCTIONS").length, 2);
476 assert.include(result?.text ?? "", `References are relative to ${directory}.`);
477 assert.strictEqual(result?.images, images);
478 } finally {
479 await NodeFSP.rm(directory, { recursive: true });
480 }
481 });
482​
483 it("leaves unknown references and native skill commands for Pi", async () => {
484 const hook = await loadInputHook([
485 { name: "skill:alpha", source: "skill", sourceInfo: { path: "/unused" } },
486 ]);
487 for (const text of [
488 "Explain $HOME",
489 "/skill:alpha use $alpha",
490 "Hello",
491 "$missing",
492 "Use $alpha, then continue",
493 "Use ($alpha)",
494 ]) {
495 assert.isUndefined(await hook({ text }, { ui: { notify: assert.fail } }));
496 }
497 });
498​
499 it("loads additional chips without duplicating a leading native skill", async () => {
500 const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "pi-skill-mentions-"));
501 try {
502 const path = NodePath.join(directory, "beta.md");
503 await NodeFSP.writeFile(path, "BETA_INSTRUCTIONS");
504 const hook = await loadInputHook([
505 { name: "skill:alpha", source: "skill", sourceInfo: { path: "/unused" } },
506 { name: "skill:beta", source: "skill", sourceInfo: { path } },
507 ]);
508 const text = "/skill:alpha use $alpha and $beta";
509 const result = await hook({ text }, { ui: { notify: assert.fail } });
510 assert.isTrue(result?.text.startsWith(text + "\n\n"));
511 assert.notInclude(result?.text ?? "", '<skill name="alpha"');
512 assert.include(result?.text ?? "", "BETA_INSTRUCTIONS");
513 } finally {
514 await NodeFSP.rm(directory, { recursive: true });
515 }
516 });
517​
518 it("reports an unreadable skill without deleting its reference or other selected instructions", async () => {
519 const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "pi-skill-mentions-"));
520 try {
521 const path = NodePath.join(directory, "readable.md");
522 await NodeFSP.writeFile(path, "READABLE_INSTRUCTIONS");
523 const hook = await loadInputHook([
524 {
525 name: "skill:missing",
526 source: "skill",
527 sourceInfo: { path: NodePath.join(directory, "missing.md") },
528 },
529 { name: "skill:readable", source: "skill", sourceInfo: { path } },
530 ]);
531 const notices: string[] = [];
532 const text = "Use $missing and $readable";
533 const result = await hook(
534 { text },
535 {
536 ui: {
537 notify: (message) => {
538 notices.push(message);
539 },
540 },
541 },
542 );
543 assert.isTrue(result?.text.startsWith(text + "\n\n"));
544 assert.include(result?.text ?? "", "READABLE_INSTRUCTIONS");
545 assert.equal(notices.length, 1);
546 assert.include(notices[0] ?? "", "Could not load skill missing");
547 } finally {
548 await NodeFSP.rm(directory, { recursive: true });
549 }
550 });
551});