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