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

mcpBridge.testkit.ts

168 lines5.6 KB

1// @effect-diagnostics nodeBuiltinImport:off -- Executes the shipped Pi extension at its native JavaScript boundary.
2import * as NodeModule from "node:module";
3import * as NodePath from "node:path";
4import * as NodeVM from "node:vm";
5import { PI_T3_MCP_EXTENSION_SOURCE } from "./mcpExtensionSource.ts";
6​
7interface RegisteredTool {
8 readonly name: string;
9 readonly description: string;
10 readonly parameters: unknown;
11 readonly outputSchema?: unknown;
12 readonly exposure?: string;
13 readonly promptSnippet?: string;
14 readonly promptGuidelines?: ReadonlyArray<string>;
15 readonly execute: (
16 id: string,
17 args: Record<string, unknown>,
18 signal?: AbortSignal,
19 ) => Promise<{
20 readonly content: ReadonlyArray<{
21 readonly type: string;
22 readonly text?: string;
23 readonly data?: string;
24 readonly mimeType?: string;
25 }>;
26 readonly structuredContent?: unknown;
27 readonly isError?: boolean;
28 }>;
30​
31type AgentStartHook = (
32 event: {
33 systemPrompt: string;
34 systemPromptOptions?: { sections?: Record<string, string> | null; forceSystemPrompt?: string };
35 },
36 ctx: {
37 model?: { api: string };
38 ui: { notify: (message: string, severity: string) => void };
39 },
40) => Promise<{ systemPrompt: string } | undefined>;
41​
42export async function loadMcpBridge(
43 options: {
44 readonly modern?: boolean;
45 readonly result?: unknown;
46 readonly toolSearchAvailable?: boolean;
47 readonly toolSearchDisabled?: boolean;
48 readonly allowsTool?: (name: string) => boolean;
49 readonly runtimeMode?: string;
50 } = {},
51) {
52 const handlers = new Map<string, AgentStartHook>();
53 const tools: RegisteredTool[] = [];
54 const requests: Array<{ readonly method: string; readonly params?: unknown }> = [];
55 let activeTools = ["read"];
56 let bridgeSourcePath = "/fixture/pi-t3-extension.ts";
57 const transports: Array<{
58 readonly url: string;
59 readonly authorization: string;
60 readonly signal: AbortSignal | undefined;
61 }> = [];
62 const servers: Array<{ readonly name: string; readonly config: Record<string, unknown> }> = [];
63 const catalog = [
64 {
65 name: "orchestrator_capabilities",
66 description: "Discover available providers and models.",
67 annotations: { readOnlyHint: true },
68 },
69 { name: "delegate_task", description: "Delegate work to another agent." },
70 {
71 name: "task_status",
72 description: "Check delegated work.",
73 annotations: { readOnlyHint: false },
74 },
75 { name: "preview_snapshot", description: "Inspect the collaborative browser." },
76 ].map((tool) => ({
77 ...tool,
78 inputSchema: { type: "object", properties: {} },
79 outputSchema: { type: "object", properties: { count: { type: "number" } } },
80 }));
81 const source = NodeModule.stripTypeScriptTypes(
82 PI_T3_MCP_EXTENSION_SOURCE.replace(/^import .*;$/gm, "").replace(
83 "export default async function",
84 "async function",
85 ),
86 );
87 await NodeVM.runInNewContext(`${source}\nt3McpExtension(pi)`, {
88 process: {
89 env: {
90 T3_MCP_URL: "http://fixture.invalid/mcp",
91 T3_MCP_BEARER_TOKEN: "fixture-token",
92 T3_PI_MCP_EXTENSION_PATH: "/fixture/pi-t3-extension.ts",
93 T3_PI_RUNTIME_MODE: options.runtimeMode,
94 },
95 },
96 AbortSignal,
97 NodePath,
98 Type: { Unsafe: (schema: unknown) => schema },
99 fetch: async (
100 url: string,
101 transport: { body: string; headers: Record<string, string>; signal?: AbortSignal },
102 ) => {
103 transport.signal?.throwIfAborted();
104 transports.push({
105 url,
106 authorization: transport.headers.authorization!,
107 signal: transport.signal,
108 });
109 const request = JSON.parse(transport.body) as {
110 id: number;
111 method: string;
112 params?: unknown;
113 };
114 requests.push(request);
115 const result =
116 request.method === "tools/list"
117 ? { tools: catalog }
118 : request.method === "tools/call"
119 ? (options.result ?? { content: [{ type: "text", text: "browser snapshot" }] })
120 : {};
121 return new Response(JSON.stringify({ jsonrpc: "2.0", id: request.id, result }), {
122 headers: { "content-type": "application/json" },
123 });
124 },
125 pi: {
126 on: (name: string, handler: AgentStartHook) => handlers.set(name, handler),
127 registerTool: (tool: RegisteredTool) => {
128 if (options.allowsTool && !options.allowsTool(tool.name)) return;
129 const index = tools.findIndex((current) => current.name === tool.name);
130 if (index === -1) tools.push(tool);
131 else tools[index] = tool;
132 },
133 getActiveTools: () => activeTools,
134 setActiveTools: (names: string[]) => {
135 activeTools = names.filter((name) => options.allowsTool?.(name) ?? true);
136 },
137 getAllTools: () => [
138 ...tools.map((tool) => ({ name: tool.name, sourceInfo: { path: bridgeSourcePath } })),
139 ...(options.toolSearchAvailable &&
140 !options.toolSearchDisabled &&
141 (options.allowsTool?.("tool_search") ?? true)
142 ? [{ name: "tool_search", sourceInfo: { path: "builtin:tool-search" } }]
143 : []),
144 ],
145 ...(options.modern
146 ? {
147 registerMcpServer: (name: string, config: Record<string, unknown>) =>
148 servers.push({ name, config }),
149 unregisterMcpServer: () => servers.splice(0),
150 }
151 : {}),
152 },
153 });
154 return {
155 handlers,
156 tools,
157 setBridgeSourcePath: (path: string) => {
158 bridgeSourcePath = path;
159 },
160 requests,
161 servers,
162 transports,
163 getActiveTools: () => activeTools,
164 restoreActiveTools: (names: string[]) => {
165 activeTools = names;
166 },
167 };