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

mcpExtensionSource.ts

456 lines17.4 KB

1/**
2 * Source for the T3-owned Pi extension that consumes T3's HTTP MCP server.
3 *
4 * Pi 0.99+ discovers optional HTTP bridge tools on demand. Older versions
5 * keep them directly available. Pi loads this TypeScript via `--extension`; the
6 * server writes it to a cache so packaged builds need no sibling .ts file.
7 *
8 * Do not import t3code modules from the string body. The Pi process resolves
9 * `@earendil-works/pi-coding-agent` and `typebox` from the user's pi install.
10 */
11import { T3_CODE_ORCHESTRATION_INSTRUCTIONS } from "@t3tools/provider-core/server/orchestrationInstructions";
12​
13export const PI_T3_MCP_EXTENSION_FILENAME = "pi-t3-mcp-extension.ts";
14​
15export const T3_MCP_URL_ENV = "T3_MCP_URL";
16export const T3_MCP_BEARER_ENV = "T3_MCP_BEARER_TOKEN";
17export const T3_PI_RUNTIME_MODE_ENV = "T3_PI_RUNTIME_MODE";
18export const T3_PI_MCP_EXTENSION_PATH_ENV = "T3_PI_MCP_EXTENSION_PATH";
19​
20/**
21 * Pi tools whose confirmations the bridge raises as file-change approvals.
22 * Auto-accept edits skips them; the adapter keys the approval kind off them.
23 */
24export const PI_FILE_CHANGE_TOOLS = ["edit", "write"] as const;
25​
26export const PI_T3_MCP_EXTENSION_SOURCE = `\
27import { stripFrontmatter, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
28import * as NodeFSP from "node:fs/promises";
29import * as NodePath from "node:path";
30import { Type } from "typebox";
31​
32const URL_ENV = ${JSON.stringify(T3_MCP_URL_ENV)};
33const TOKEN_ENV = ${JSON.stringify(T3_MCP_BEARER_ENV)};
34const RUNTIME_MODE_ENV = ${JSON.stringify(T3_PI_RUNTIME_MODE_ENV)};
35const EXTENSION_PATH_ENV = ${JSON.stringify(T3_PI_MCP_EXTENSION_PATH_ENV)};
36const ORCHESTRATION_INSTRUCTIONS = ${JSON.stringify(T3_CODE_ORCHESTRATION_INSTRUCTIONS.trim())};
37const PROTOCOL = "2025-06-18";
38const READ_ONLY_TOOLS = new Set(["read", "grep", "find", "ls"]);
39const FILE_CHANGE_TOOLS = new Set(${JSON.stringify(PI_FILE_CHANGE_TOOLS)});
40​
41type RuntimeMode = "approval-required" | "auto-accept-edits" | "auto" | "full-access";
42​
43type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };
44​
45type JsonRpcResponse = {
46 readonly id?: number | string;
47 readonly result?: JsonValue;
48 readonly error?: { readonly message?: string };
49};
50​
51type McpTool = {
52 readonly name: string;
53 readonly description?: string;
54 readonly inputSchema?: Record<string, unknown>;
55 readonly annotations?: { readonly readOnlyHint?: boolean };
56 readonly outputSchema?: Record<string, unknown>;
57};
58​
59function env(name: string): string | undefined {
60 const value = process.env[name];
61 return value && value.length > 0 ? value : undefined;
63​
64function runtimeMode(): RuntimeMode {
65 const value = env(RUNTIME_MODE_ENV);
66 return value === "approval-required" ||
67 value === "auto-accept-edits" ||
68 value === "auto" ||
69 value === "full-access"
70 ? value
71 : "full-access";
73​
74function toolInputSummary(input: unknown): string {
75 try {
76 return JSON.stringify(input, null, 2).slice(0, 4_000);
77 } catch {
78 return String(input).slice(0, 4_000);
79 }
81​
82function parseSseOrJson(body: string, contentType: string): JsonRpcResponse {
83 if (contentType.includes("text/event-stream")) {
84 for (const line of body.split("\\n")) {
85 const trimmed = line.startsWith("data:") ? line.slice(5).trim() : "";
86 if (trimmed.length === 0) continue;
87 const parsed = JSON.parse(trimmed) as JsonRpcResponse;
88 if (parsed.id !== undefined || parsed.result !== undefined || parsed.error !== undefined) {
89 return parsed;
90 }
91 }
92 throw new Error("MCP SSE response had no JSON-RPC payload.");
93 }
94 return JSON.parse(body) as JsonRpcResponse;
96​
97function jsonSchemaToTypebox(schema: Record<string, unknown> | undefined) {
98 const unsafe = (Type as { Unsafe?: (value: unknown) => unknown }).Unsafe;
99 if (typeof unsafe === "function" && schema !== undefined) {
100 return unsafe(schema);
101 }
102 return Type.Object({}, { additionalProperties: true });
104​
105type ModelContent =
106 | { type: "text"; text: string }
107 | { type: "image"; data: string; mimeType: string };
108​
109function mcpModelContent(result: unknown): ModelContent[] {
110 if (result === null || result === undefined) return [];
111 if (typeof result !== "object") return [{ type: "text", text: String(result) }];
112 const record = result as {
113 readonly content?: ReadonlyArray<{
114 readonly type?: string;
115 readonly text?: string;
116 readonly data?: string;
117 readonly mimeType?: string;
118 }>;
119 readonly structuredContent?: unknown;
120 };
121 const content: ModelContent[] = [];
122 if (Array.isArray(record.content)) {
123 for (const part of record.content) {
124 if (part?.type === "text" && typeof part.text === "string") {
125 content.push({ type: "text", text: part.text });
126 } else if (part?.type === "image" && typeof part.data === "string" && typeof part.mimeType === "string") {
127 content.push({ type: "image", data: part.data, mimeType: part.mimeType });
128 }
129 }
130 }
131 // Structured output belongs to scripts. Only use it as model text when
132 // the server supplied no model-facing blocks, matching Pi's native MCP tools.
133 if (content.length === 0) {
134 content.push({ type: "text", text: JSON.stringify(record.structuredContent ?? result) });
135 }
136 return content;
138​
139function mcpScriptResult(result: JsonValue | undefined) {
140 if (typeof result !== "object" || result === null || Array.isArray(result)) return result;
141 const { _meta: _ignored, ...scriptResult } = result;
142 return scriptResult;
144​
145function mcpOutputSchema(tool: McpTool) {
146 return jsonSchemaToTypebox({
147 type: "object",
148 properties: {
149 content: { type: "array", items: { type: "object" } },
150 ...(tool.outputSchema === undefined ? {} : { structuredContent: tool.outputSchema }),
151 isError: { type: "boolean" },
152 _meta: { type: "object" },
153 },
154 required: ["content"],
155 });
157​
158function isMcpToolError(result: unknown): boolean {
159 return (
160 typeof result === "object" &&
161 result !== null &&
162 "isError" in result &&
163 result.isError === true
164 );
166​
167function createMcpClient(endpoint: string, token: string) {
168 let nextId = 1;
169 let sessionId: string | undefined;
170​
171 const headers = (): Record<string, string> => {
172 const next: Record<string, string> = {
173 accept: "application/json, text/event-stream",
174 authorization: token.startsWith("Bearer ") ? token : \`Bearer \${token}\`,
175 "content-type": "application/json",
176 // Effect's HTTP MCP rejects post-initialize requests without this
177 // (400). The worktree client in McpHttpServer tests sends the same
178 // header; initialize itself does not require it.
179 "mcp-protocol-version": PROTOCOL,
180 };
181 if (sessionId !== undefined) next["mcp-session-id"] = sessionId;
182 return next;
183 };
184​
185 const request = async (method: string, params?: unknown, signal?: AbortSignal) => {
186 const id = nextId++;
187 const response = await fetch(endpoint, {
188 method: "POST",
189 headers: headers(),
190 body: JSON.stringify({ jsonrpc: "2.0", id, method, params }),
191 signal,
192 });
193 const nextSession = response.headers.get("mcp-session-id");
194 if (nextSession) sessionId = nextSession;
195 const body = await response.text();
196 if (!response.ok) {
197 throw new Error(\`MCP \${method} failed (\${response.status}): \${body.slice(0, 400)}\`);
198 }
199 if (body.length === 0) return undefined;
200 const parsed = parseSseOrJson(body, response.headers.get("content-type") ?? "");
201 if (parsed.error) {
202 throw new Error(parsed.error.message ?? \`MCP \${method} returned an error\`);
203 }
204 return parsed.result;
205 };
206​
207 const notify = async (method: string, params?: unknown, signal?: AbortSignal) => {
208 await fetch(endpoint, {
209 method: "POST",
210 headers: headers(),
211 body: JSON.stringify({ jsonrpc: "2.0", method, params }),
212 signal,
213 });
214 };
215​
216 return {
217 async connect(signal?: AbortSignal) {
218 await request(
219 "initialize",
220 {
221 protocolVersion: PROTOCOL,
222 capabilities: {},
223 clientInfo: { name: "t3-pi-mcp", version: "1.0.0" },
224 },
225 signal,
226 );
227 await notify("notifications/initialized", {}, signal).catch(() => undefined);
228 },
229 async listTools(signal?: AbortSignal) {
230 const tools: McpTool[] = [];
231 let cursor: string | undefined;
232 do {
233 const result = (await request(
234 "tools/list",
235 cursor === undefined ? {} : { cursor },
236 signal,
237 )) as { tools?: McpTool[]; nextCursor?: string } | undefined;
238 tools.push(...(result?.tools ?? []));
239 cursor = result?.nextCursor;
240 } while (cursor);
241 return tools;
242 },
243 async callTool(name: string, args: Record<string, unknown>, signal?: AbortSignal) {
244 return request("tools/call", { name, arguments: args }, signal);
245 },
246 };
248​
249export default async function t3McpExtension(pi: ExtensionAPI) {
250 // Keep skill chips in the request. Pi expands only one leading /skill:
251 // command, so use its own frontmatter loader for every selected chip here.
252 pi.on("input", async (event, ctx) => {
253 if (!event.text.includes("$")) return;
254 const commands = pi.getCommands().filter((command) => command.source === "skill");
255 const nativeSkill = /^\\/skill:([^ ]+)(?: |$)/.exec(event.text)?.[1];
256 const seen = new Set<string>(nativeSkill === undefined ? [] : [nativeSkill]);
257 const blocks: string[] = [];
258 for (const match of event.text.matchAll(/(^|\\s)\\$([^\\s]+)(?=\\s|$)/g)) {
259 const name = match[2];
260 if (name === undefined || seen.has(name)) continue;
261 const command = commands.find((candidate) => candidate.name === "skill:" + name);
262 if (command === undefined) continue;
263 seen.add(name);
264 const path = command.sourceInfo.path;
265 try {
266 const body = stripFrontmatter(await NodeFSP.readFile(path, "utf8")).trim();
267 blocks.push(
268 \`<skill name="\${name}" location="\${path}">\\nReferences are relative to \${NodePath.dirname(path)}.\\n\\n\${body}\\n</skill>\`,
269 );
270 } catch {
271 ctx.ui.notify(\`Could not load skill \${name} from \${path}.\`, "error");
272 }
273 }
274 if (blocks.length === 0) return;
275 return {
276 action: "transform",
277 text: event.text + "\\n\\n" + blocks.join("\\n\\n"),
278 images: event.images,
279 };
280 });
281​
282 // Workaround for an upstream Pi context-budgeting bug: pi-ai reuses the
283 // previous response's usage even when a fork's instructions/tools differ,
284 // then reserves almost all remaining context for output. OpenRouter can
285 // reject even a short conversation. Remove this cap when Pi accounts for
286 // the current request prefix reliably (api/simple-options + utils/estimate).
287 pi.on("before_provider_request", (event, ctx) => {
288 if (ctx.model?.provider !== "openrouter") return;
289 const payload = event.payload;
290 if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return;
291 const replacement = { ...payload } as Record<string, unknown>;
292 let changed = false;
293 for (const key of ["max_tokens", "max_completion_tokens"]) {
294 const limit = replacement[key];
295 if (typeof limit === "number" && Number.isFinite(limit) && limit > 32_768) {
296 replacement[key] = 32_768;
297 changed = true;
298 }
299 }
300 if (changed) return replacement;
301 });
302​
303 // Pi deliberately leaves permission policy to extensions. T3's injected
304 // bridge uses Pi's public blocking tool hook so the shared runtime modes
305 // keep their normal meaning without replacing or shadowing Pi's runtime.
306 // Only Pi's own search is known to be read-only. An extension that replaces
307 // it keeps the name, and cannot discover deferred tools either.
308 const hasBuiltinToolSearch = () =>
309 typeof pi.getAllTools === "function" &&
310 pi.getAllTools().some((tool) => tool.name === "tool_search" && tool.sourceInfo?.path === "builtin:tool-search");
311​
312 const readOnlyMcpTools = new Set<string>();
313 const isReadOnlyMcpTool = (name: string) => {
314 const extensionPath = env(EXTENSION_PATH_ENV);
315 if (extensionPath === undefined || !readOnlyMcpTools.has(name) || typeof pi.getAllTools !== "function") return false;
316 // A user extension may own the same name. Only our registered HTTP bridge
317 // may inherit the canonical T3 server's read-only annotation.
318 return pi.getAllTools().some((tool) => tool.name === name &&
319 typeof tool.sourceInfo?.path === "string" &&
320 NodePath.resolve(tool.sourceInfo.path) === NodePath.resolve(extensionPath));
321 };
322​
323 pi.on("tool_call", async (event, ctx) => {
324 const mode = runtimeMode();
325 if (mode === "full-access") return;
326 if ((event.toolName === "tool_search" ? hasBuiltinToolSearch() : READ_ONLY_TOOLS.has(event.toolName)) || isReadOnlyMcpTool(event.toolName)) {
327 return;
328 }
329 if (mode === "auto-accept-edits" && FILE_CHANGE_TOOLS.has(event.toolName)) {
330 return;
331 }
332 const approved = await ctx.ui.confirm(
333 \`Allow \${event.toolName}?\`,
334 toolInputSummary(event.input),
335 { signal: ctx.signal },
336 );
337 if (!approved) {
338 return { block: true, reason: \`\${event.toolName} was declined in T3 Code.\` };
339 }
340 });
341​
342 const endpoint = env(URL_ENV);
343 const token = env(TOKEN_ENV);
344 if (endpoint === undefined || token === undefined) {
345 pi.on("session_start", async (_event, ctx) => {
346 ctx.ui.notify(
347 "t3-code MCP unavailable: T3_MCP_URL or T3_MCP_BEARER_TOKEN is missing.",
348 "warning",
349 );
350 });
351 return;
352 }
353​
354 // Tool exposure arrived with registerMcpServer in Pi 0.99. Keep the HTTP
355 // bridge as the credential owner: mcp.json overrides native registrations.
356 const supportsExposure = "registerMcpServer" in pi && typeof pi.registerMcpServer === "function";
357 const directTools = new Set(["orchestrator_capabilities", "delegate_task", "task_status"]);
358 let deferOptionalTools = supportsExposure;
359 let catalog: ReadonlyArray<McpTool> = [];
360​
361 const client = createMcpClient(endpoint, token);
362 let started: Promise<void> | undefined;
363​
364 const registerTools = () => {
365 // Preserve public names for saved loadouts and tool selectors. Hidden
366 // canonical names reserve ownership against Pi's configured MCP servers.
367 const prefixes = supportsExposure ? ["mcp__t3-code__", "mcp__t3_code__"] : ["mcp__t3-code__"];
368 readOnlyMcpTools.clear();
369 for (const tool of catalog) {
370 const name = tool.name;
371 for (const prefix of prefixes) {
372 if (tool.annotations?.readOnlyHint === true) readOnlyMcpTools.add(\`\${prefix}\${name}\`);
373 const exposure = prefix === "mcp__t3_code__" ? "hidden" :
374 deferOptionalTools && !directTools.has(name) ? "deferred" : "direct";
375 pi.registerTool({
376 name: \`\${prefix}\${name}\`,
377 label: name,
378 description: tool.description ?? name,
379 parameters: jsonSchemaToTypebox(tool.inputSchema),
380 ...(supportsExposure ? { outputSchema: mcpOutputSchema(tool) } : {}),
381 ...(supportsExposure ? { exposure } : {}),
382 async execute(_toolCallId, params, signal) {
383 const result = await client.callTool(
384 name,
385 (params ?? {}) as Record<string, unknown>,
386 signal,
387 );
388 const content = mcpModelContent(result);
389 if (isMcpToolError(result) && !content.some((part) => part.type === "text" && part.text.length > 0)) {
390 content.push({ type: "text", text: "MCP tool t3-code/" + name + " returned an error" });
391 }
392 return {
393 content,
394 structuredContent: mcpScriptResult(result),
395 details: { server: "t3-code", tool: name },
396 ...(isMcpToolError(result) ? { isError: true } : {}),
397 };
398 },
399 });
400 }
401 }
402 };
403​
404 const ensureStarted = () => {
405 if (started !== undefined) return started;
406 const attempt = (async () => {
407 const signal = AbortSignal.timeout(10_000);
408 await client.connect(signal);
409 catalog = await client.listTools(signal);
410 registerTools();
411 })();
412 started = attempt;
413 void attempt.catch(() => {
414 if (started === attempt) started = undefined;
415 });
416 return attempt;
417 };
418​
419 // CLI extensions load before builtins, and Pi keeps the first registration
420 // of a tool name. Register now so the bridge owns the T3 namespace even when
421 // mcp.json configures it; retry a failed connection at session_start.
422 await ensureStarted().catch(() => undefined);
423​
424 const reconcileDiscovery = () => {
425 if (!supportsExposure) return;
426 // A disabled or replaced search builtin cannot discover deferred tools.
427 const hasToolSearch = hasBuiltinToolSearch();
428 const exposureChanged = deferOptionalTools !== hasToolSearch;
429 deferOptionalTools = hasToolSearch;
430 if (exposureChanged) registerTools();
431 if (hasToolSearch) {
432 const active = pi.getActiveTools();
433 if (!active.includes("tool_search")) pi.setActiveTools([...active, "tool_search"]);
434 }
435 };
436​
437 // Tree navigation restores its saved loadout after session_start.
438 pi.on("session_tree", reconcileDiscovery);
439 pi.on("session_start", async (_event, ctx) => {
440 reconcileDiscovery();
441 try {
442 await ensureStarted();
443 } catch (error) {
444 const message = error instanceof Error ? error.message : String(error);
445 ctx.ui.notify(\`t3-code MCP unavailable: \${message}\`, "warning");
446 }
447 });
448​
449 // Deliver orchestration guidance through pi's real system-prompt channel.
450 // Wrapping the first user message instead would stop it from starting
451 // with "/" and silently break slash-command expansion.
452 pi.on("before_agent_start", (event) => ({
453 systemPrompt: event.systemPrompt + "\\n\\n" + ORCHESTRATION_INSTRUCTIONS,
454 }));
456`;