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

mcpBridge.testkit.ts

140 lines4.8 KB

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