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