Open History to see the last commit
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";
18
19/**
20 * Pi tools whose confirmations the bridge raises as file-change approvals.
21 * Auto-accept edits skips them; the adapter keys the approval kind off them.
22 */
23export const PI_FILE_CHANGE_TOOLS = ["edit", "write"] as const;
24
25export const PI_T3_MCP_EXTENSION_SOURCE = `\
26import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
27import { Type } from "typebox";
28
29const URL_ENV = ${JSON.stringify(T3_MCP_URL_ENV)};
30const TOKEN_ENV = ${JSON.stringify(T3_MCP_BEARER_ENV)};
31const RUNTIME_MODE_ENV = ${JSON.stringify(T3_PI_RUNTIME_MODE_ENV)};
32const ORCHESTRATION_INSTRUCTIONS = ${JSON.stringify(T3_CODE_ORCHESTRATION_INSTRUCTIONS.trim())};
33const PROTOCOL = "2025-06-18";
34const READ_ONLY_TOOLS = new Set(["read", "grep", "find", "ls"]);
35const FILE_CHANGE_TOOLS = new Set(${JSON.stringify(PI_FILE_CHANGE_TOOLS)});
36
37type RuntimeMode = "approval-required" | "auto-accept-edits" | "auto" | "full-access";
38
39type JsonRpcResponse = {
40 readonly id?: number | string;
41 readonly result?: unknown;
42 readonly error?: { readonly message?: string };
43};
44
45type McpTool = {
46 readonly name: string;
47 readonly description?: string;
48 readonly inputSchema?: Record<string, unknown>;
49};
50
51function env(name: string): string | undefined {
52 const value = process.env[name];
53 return value && value.length > 0 ? value : undefined;
54}
55
56function runtimeMode(): RuntimeMode {
57 const value = env(RUNTIME_MODE_ENV);
58 return value === "approval-required" ||
59 value === "auto-accept-edits" ||
60 value === "auto" ||
61 value === "full-access"
62 ? value
63 : "full-access";
64}
65
66function toolInputSummary(input: unknown): string {
67 try {
68 return JSON.stringify(input, null, 2).slice(0, 4_000);
69 } catch {
70 return String(input).slice(0, 4_000);
71 }
72}
73
74function parseSseOrJson(body: string, contentType: string): JsonRpcResponse {
75 if (contentType.includes("text/event-stream")) {
76 for (const line of body.split("\\n")) {
77 const trimmed = line.startsWith("data:") ? line.slice(5).trim() : "";
78 if (trimmed.length === 0) continue;
79 const parsed = JSON.parse(trimmed) as JsonRpcResponse;
80 if (parsed.id !== undefined || parsed.result !== undefined || parsed.error !== undefined) {
81 return parsed;
82 }
83 }
84 throw new Error("MCP SSE response had no JSON-RPC payload.");
85 }
86 return JSON.parse(body) as JsonRpcResponse;
87}
88
89function jsonSchemaToTypebox(schema: Record<string, unknown> | undefined) {
90 const unsafe = (Type as { Unsafe?: (value: unknown) => unknown }).Unsafe;
91 if (typeof unsafe === "function" && schema !== undefined) {
92 return unsafe(schema);
93 }
94 return Type.Object({}, { additionalProperties: true });
95}
96
97function formatMcpContent(result: unknown): string {
98 if (result === null || result === undefined) return "";
99 if (typeof result !== "object") return String(result);
100 const record = result as {
101 readonly content?: ReadonlyArray<{ readonly type?: string; readonly text?: string }>;
102 readonly structuredContent?: unknown;
103 readonly isError?: boolean;
104 };
105 const texts: string[] = [];
106 if (Array.isArray(record.content)) {
107 for (const part of record.content) {
108 if (part?.type === "text" && typeof part.text === "string") texts.push(part.text);
109 }
110 }
111 // Most T3 tools mirror structuredContent in a text block. Repeating it would
112 // leave T3's own output parsing two JSON documents instead of one.
113 if (record.structuredContent !== undefined) {
114 const structured = JSON.stringify(record.structuredContent);
115 if (!texts.includes(structured)) texts.push(structured);
116 }
117 if (texts.length > 0) return texts.join("\\n");
118 return JSON.stringify(result);
119}
120
121function isMcpToolError(result: unknown): boolean {
122 return (
123 typeof result === "object" &&
124 result !== null &&
125 "isError" in result &&
126 result.isError === true
127 );
128}
129
130function createMcpClient(endpoint: string, token: string) {
131 let nextId = 1;
132 let sessionId: string | undefined;
133
134 const headers = (): Record<string, string> => {
135 const next: Record<string, string> = {
136 accept: "application/json, text/event-stream",
137 authorization: token.startsWith("Bearer ") ? token : \`Bearer \${token}\`,
138 "content-type": "application/json",
139 // Effect's HTTP MCP rejects post-initialize requests without this
140 // (400). The worktree client in McpHttpServer tests sends the same
141 // header; initialize itself does not require it.
142 "mcp-protocol-version": PROTOCOL,
143 };
144 if (sessionId !== undefined) next["mcp-session-id"] = sessionId;
145 return next;
146 };
147
148 const request = async (method: string, params?: unknown, signal?: AbortSignal) => {
149 const id = nextId++;
150 const response = await fetch(endpoint, {
151 method: "POST",
152 headers: headers(),
153 body: JSON.stringify({ jsonrpc: "2.0", id, method, params }),
154 signal,
155 });
156 const nextSession = response.headers.get("mcp-session-id");
157 if (nextSession) sessionId = nextSession;
158 const body = await response.text();
159 if (!response.ok) {
160 throw new Error(\`MCP \${method} failed (\${response.status}): \${body.slice(0, 400)}\`);
161 }
162 if (body.length === 0) return undefined;
163 const parsed = parseSseOrJson(body, response.headers.get("content-type") ?? "");
164 if (parsed.error) {
165 throw new Error(parsed.error.message ?? \`MCP \${method} returned an error\`);
166 }
167 return parsed.result;
168 };
169
170 const notify = async (method: string, params?: unknown, signal?: AbortSignal) => {
171 await fetch(endpoint, {
172 method: "POST",
173 headers: headers(),
174 body: JSON.stringify({ jsonrpc: "2.0", method, params }),
175 signal,
176 });
177 };
178
179 return {
180 async connect(signal?: AbortSignal) {
181 await request(
182 "initialize",
183 {
184 protocolVersion: PROTOCOL,
185 capabilities: {},
186 clientInfo: { name: "t3-pi-mcp", version: "1.0.0" },
187 },
188 signal,
189 );
190 await notify("notifications/initialized", {}, signal).catch(() => undefined);
191 },
192 async listTools(signal?: AbortSignal) {
193 const tools: McpTool[] = [];
194 let cursor: string | undefined;
195 do {
196 const result = (await request(
197 "tools/list",
198 cursor === undefined ? {} : { cursor },
199 signal,
200 )) as { tools?: McpTool[]; nextCursor?: string } | undefined;
201 tools.push(...(result?.tools ?? []));
202 cursor = result?.nextCursor;
203 } while (cursor);
204 return tools;
205 },
206 async callTool(name: string, args: Record<string, unknown>, signal?: AbortSignal) {
207 return request("tools/call", { name, arguments: args }, signal);
208 },
209 };
210}
211
212export default async function t3McpExtension(pi: ExtensionAPI) {
213 // Workaround for an upstream Pi context-budgeting bug: pi-ai reuses the
214 // previous response's usage even when a fork's instructions/tools differ,
215 // then reserves almost all remaining context for output. OpenRouter can
216 // reject even a short conversation. Remove this cap when Pi accounts for
217 // the current request prefix reliably (api/simple-options + utils/estimate).
218 pi.on("before_provider_request", (event, ctx) => {
219 if (ctx.model?.provider !== "openrouter") return;
220 const payload = event.payload;
221 if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return;
222 const replacement = { ...payload } as Record<string, unknown>;
223 let changed = false;
224 for (const key of ["max_tokens", "max_completion_tokens"]) {
225 const limit = replacement[key];
226 if (typeof limit === "number" && Number.isFinite(limit) && limit > 32_768) {
227 replacement[key] = 32_768;
228 changed = true;
229 }
230 }
231 if (changed) return replacement;
232 });
233
234 // Pi deliberately leaves permission policy to extensions. T3's injected
235 // bridge uses Pi's public blocking tool hook so the shared runtime modes
236 // keep their normal meaning without replacing or shadowing Pi's runtime.
237 // Only Pi's own search is known to be read-only. An extension that replaces
238 // it keeps the name, and cannot discover deferred tools either.
239 const hasBuiltinToolSearch = () =>
240 typeof pi.getAllTools === "function" &&
241 pi.getAllTools().some((tool) => tool.name === "tool_search" && tool.sourceInfo?.path === "builtin:tool-search");
242
243 pi.on("tool_call", async (event, ctx) => {
244 const mode = runtimeMode();
245 if (mode === "full-access") return;
246 if (event.toolName === "tool_search" ? hasBuiltinToolSearch() : READ_ONLY_TOOLS.has(event.toolName)) {
247 return;
248 }
249 if (mode === "auto-accept-edits" && FILE_CHANGE_TOOLS.has(event.toolName)) {
250 return;
251 }
252 const approved = await ctx.ui.confirm(
253 \`Allow \${event.toolName}?\`,
254 toolInputSummary(event.input),
255 );
256 if (!approved) {
257 return { block: true, reason: \`\${event.toolName} was declined in T3 Code.\` };
258 }
259 });
260
261 const endpoint = env(URL_ENV);
262 const token = env(TOKEN_ENV);
263 if (endpoint === undefined || token === undefined) {
264 pi.on("session_start", async (_event, ctx) => {
265 ctx.ui.notify(
266 "t3-code MCP unavailable: T3_MCP_URL or T3_MCP_BEARER_TOKEN is missing.",
267 "warning",
268 );
269 });
270 return;
271 }
272
273 // Tool exposure arrived with registerMcpServer in Pi 0.99. Keep the HTTP
274 // bridge as the credential owner: mcp.json overrides native registrations.
275 const supportsExposure = "registerMcpServer" in pi && typeof pi.registerMcpServer === "function";
276 const directTools = new Set(["orchestrator_capabilities", "delegate_task", "task_status"]);
277 let deferOptionalTools = supportsExposure;
278 let catalog: ReadonlyArray<McpTool> = [];
279
280 const client = createMcpClient(endpoint, token);
281 let started: Promise<void> | undefined;
282
283 const registerTools = () => {
284 // Preserve public names for saved loadouts and tool selectors. Hidden
285 // canonical names reserve ownership against Pi's configured MCP servers.
286 const prefixes = supportsExposure ? ["mcp__t3-code__", "mcp__t3_code__"] : ["mcp__t3-code__"];
287 for (const tool of catalog) {
288 const name = tool.name;
289 for (const prefix of prefixes) {
290 const exposure = prefix === "mcp__t3_code__" ? "hidden" :
291 deferOptionalTools && !directTools.has(name) ? "deferred" : "direct";
292 pi.registerTool({
293 name: \`\${prefix}\${name}\`,
294 label: name,
295 description: tool.description ?? name,
296 parameters: jsonSchemaToTypebox(tool.inputSchema),
297 ...(supportsExposure ? { exposure } : {}),
298 async execute(_toolCallId, params, signal) {
299 const result = await client.callTool(
300 name,
301 (params ?? {}) as Record<string, unknown>,
302 signal,
303 );
304 const text = formatMcpContent(result);
305 return {
306 content: [{ type: "text", text }],
307 details: { server: "t3-code", tool: name },
308 ...(isMcpToolError(result) ? { isError: true } : {}),
309 };
310 },
311 });
312 }
313 }
314 };
315
316 const ensureStarted = () => {
317 if (started !== undefined) return started;
318 const attempt = (async () => {
319 const signal = AbortSignal.timeout(10_000);
320 await client.connect(signal);
321 catalog = await client.listTools(signal);
322 registerTools();
323 })();
324 started = attempt;
325 void attempt.catch(() => {
326 if (started === attempt) started = undefined;
327 });
328 return attempt;
329 };
330
331 // CLI extensions load before builtins, and Pi keeps the first registration
332 // of a tool name. Register now so the bridge owns the T3 namespace even when
333 // mcp.json configures it; retry a failed connection at session_start.
334 await ensureStarted().catch(() => undefined);
335
336 const reconcileDiscovery = () => {
337 if (!supportsExposure) return;
338 // A disabled or replaced search builtin cannot discover deferred tools.
339 const hasToolSearch = hasBuiltinToolSearch();
340 const exposureChanged = deferOptionalTools !== hasToolSearch;
341 deferOptionalTools = hasToolSearch;
342 if (exposureChanged) registerTools();
343 if (hasToolSearch) {
344 const active = pi.getActiveTools();
345 if (!active.includes("tool_search")) pi.setActiveTools([...active, "tool_search"]);
346 }
347 };
348
349 // Tree navigation restores its saved loadout after session_start.
350 pi.on("session_tree", reconcileDiscovery);
351 pi.on("session_start", async (_event, ctx) => {
352 reconcileDiscovery();
353 try {
354 await ensureStarted();
355 } catch (error) {
356 const message = error instanceof Error ? error.message : String(error);
357 ctx.ui.notify(\`t3-code MCP unavailable: \${message}\`, "warning");
358 }
359 });
360
361 // Deliver orchestration guidance through pi's real system-prompt channel.
362 // Wrapping the first user message instead would stop it from starting
363 // with "/" and silently break slash-command expansion.
364 pi.on("before_agent_start", (event) => ({
365 systemPrompt: event.systemPrompt + "\\n\\n" + ORCHESTRATION_INSTRUCTIONS,
366 }));
367}
368`;