Open History to see the last commit
1/**
2 * Do not import t3code modules from the string body. The Pi process resolves
3 * `@earendil-works/pi-coding-agent` and `typebox` from the user's pi install.
4 */
5import { T3_CODE_ORCHESTRATION_INSTRUCTIONS } from "@t3tools/provider-core/server/orchestrationInstructions";
6
7export const PI_T3_MCP_EXTENSION_FILENAME = "pi-t3-mcp-extension.ts";
8
9export const T3_MCP_URL_ENV = "T3_MCP_URL";
10export const T3_MCP_BEARER_ENV = "T3_MCP_BEARER_TOKEN";
11export const T3_PI_RUNTIME_MODE_ENV = "T3_PI_RUNTIME_MODE";
12export const T3_PI_MCP_EXTENSION_PATH_ENV = "T3_PI_MCP_EXTENSION_PATH";
13
14/**
15 * Pi tools whose confirmations the bridge raises as file-change approvals.
16 * Auto-accept edits skips them; the adapter keys the approval kind off them.
17 */
18export const PI_FILE_CHANGE_TOOLS = ["edit", "write"] as const;
19
20export const PI_T3_MCP_EXTENSION_SOURCE = `\
21import { stripFrontmatter, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
22import * as NodeFSP from "node:fs/promises";
23import * as NodePath from "node:path";
24import { Type } from "typebox";
25
26const URL_ENV = ${JSON.stringify(T3_MCP_URL_ENV)};
27const TOKEN_ENV = ${JSON.stringify(T3_MCP_BEARER_ENV)};
28const RUNTIME_MODE_ENV = ${JSON.stringify(T3_PI_RUNTIME_MODE_ENV)};
29const EXTENSION_PATH_ENV = ${JSON.stringify(T3_PI_MCP_EXTENSION_PATH_ENV)};
30const ORCHESTRATION_INSTRUCTIONS = ${JSON.stringify(T3_CODE_ORCHESTRATION_INSTRUCTIONS.trim())};
31const PROTOCOL = "2025-06-18";
32const READ_ONLY_TOOLS = new Set(["read", "grep", "find", "ls"]);
33const FILE_CHANGE_TOOLS = new Set(${JSON.stringify(PI_FILE_CHANGE_TOOLS)});
34
35type RuntimeMode = "approval-required" | "auto-accept-edits" | "auto" | "full-access";
36
37type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };
38
39type JsonRpcResponse = {
40 readonly id?: number | string;
41 readonly result?: JsonValue;
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 readonly annotations?: { readonly readOnlyHint?: boolean };
50 readonly outputSchema?: Record<string, unknown>;
51};
52
53function env(name: string): string | undefined {
54 const value = process.env[name];
55 return value && value.length > 0 ? value : undefined;
56}
57
58function runtimeMode(): RuntimeMode {
59 const value = env(RUNTIME_MODE_ENV);
60 return value === "approval-required" ||
61 value === "auto-accept-edits" ||
62 value === "auto" ||
63 value === "full-access"
64 ? value
65 : "full-access";
66}
67
68function toolInputSummary(input: unknown): string {
69 try {
70 return JSON.stringify(input, null, 2).slice(0, 4_000);
71 } catch {
72 return String(input).slice(0, 4_000);
73 }
74}
75
76function parseSseOrJson(body: string, contentType: string): JsonRpcResponse {
77 if (contentType.includes("text/event-stream")) {
78 for (const line of body.split("\\n")) {
79 const trimmed = line.startsWith("data:") ? line.slice(5).trim() : "";
80 if (trimmed.length === 0) continue;
81 const parsed = JSON.parse(trimmed) as JsonRpcResponse;
82 if (parsed.id !== undefined || parsed.result !== undefined || parsed.error !== undefined) {
83 return parsed;
84 }
85 }
86 throw new Error("MCP SSE response had no JSON-RPC payload.");
87 }
88 return JSON.parse(body) as JsonRpcResponse;
89}
90
91function jsonSchemaToTypebox(schema: Record<string, unknown> | undefined) {
92 const unsafe = (Type as { Unsafe?: (value: unknown) => unknown }).Unsafe;
93 if (typeof unsafe === "function" && schema !== undefined) {
94 // Zero-argument MCP tools may omit "properties", which some OpenAI-compatible
95 // servers reject. Declare it, as Pi does for its own MCP tools.
96 return unsafe({
97 ...schema,
98 type: schema.type ?? "object",
99 ...(schema.properties === undefined ? { properties: {} } : {}),
100 });
101 }
102 return Type.Object({}, { additionalProperties: true });
103}
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;
137}
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;
143}
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 });
156}
157
158function isMcpToolError(result: unknown): boolean {
159 return (
160 typeof result === "object" &&
161 result !== null &&
162 "isError" in result &&
163 result.isError === true
164 );
165}
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 };
247}
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 = (ctx: Pick<ExtensionContext, "model">) => {
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 const active = pi.getActiveTools();
432 // Completion gateways can silently drop calls to undeclared tools named
433 // in history or guidance. Eagerly load T3 schemas, including after tree
434 // restores, while retaining deferred exposure for Pi's allowlist rules.
435 // Pi still applies --tools/--exclude-tools to this active loadout.
436 const required = [
437 ...(hasToolSearch ? ["tool_search"] : []),
438 ...(ctx.model?.api === "openai-completions" ? catalog.map((tool) => "mcp__t3-code__" + tool.name) : []),
439 ];
440 const missing = required.filter((name) => !active.includes(name));
441 if (missing.length > 0) pi.setActiveTools([...active, ...missing]);
442 };
443
444 // Tree navigation restores its saved loadout after session_start.
445 pi.on("session_tree", (_event, ctx) => reconcileDiscovery(ctx));
446 pi.on("model_select", (_event, ctx) => reconcileDiscovery(ctx));
447 pi.on("session_start", async (_event, ctx) => {
448 reconcileDiscovery(ctx);
449 try {
450 await ensureStarted();
451 } catch (error) {
452 const message = error instanceof Error ? error.message : String(error);
453 ctx.ui.notify(\`t3-code MCP unavailable: \${message}\`, "warning");
454 }
455 });
456
457 // Keep guidance in the system prompt so leading slash commands still expand.
458 pi.on("before_agent_start", (event, ctx) => {
459 reconcileDiscovery(ctx);
460 const sections = event.systemPromptOptions?.sections;
461 if (sections && typeof sections === "object" && event.systemPromptOptions?.forceSystemPrompt === undefined) {
462 // A full prompt override bypasses Pi's later section rendering.
463 sections.t3_code_orchestration = ORCHESTRATION_INSTRUCTIONS;
464 return undefined;
465 }
466 return { systemPrompt: event.systemPrompt + "\\n\\n" + ORCHESTRATION_INSTRUCTIONS };
467 });
468}
469`;