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

mcpBridge.testkit.ts

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