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 return unsafe(schema);
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 // Keep skill chips in the request. Pi expands only one leading /skill:
245 // command, so use its own frontmatter loader for every selected chip here.
246 pi.on("input", async (event, ctx) => {
247 if (!event.text.includes("$")) return;
248 const commands = pi.getCommands().filter((command) => command.source === "skill");
249 const nativeSkill = /^\\/skill:([^ ]+)(?: |$)/.exec(event.text)?.[1];
250 const seen = new Set<string>(nativeSkill === undefined ? [] : [nativeSkill]);
251 const blocks: string[] = [];
252 for (const match of event.text.matchAll(/(^|\\s)\\$([^\\s]+)(?=\\s|$)/g)) {
253 const name = match[2];
254 if (name === undefined || seen.has(name)) continue;
255 const command = commands.find((candidate) => candidate.name === "skill:" + name);
256 if (command === undefined) continue;
257 seen.add(name);
258 const path = command.sourceInfo.path;
259 try {
260 const body = stripFrontmatter(await NodeFSP.readFile(path, "utf8")).trim();
261 blocks.push(
262 \`<skill name="\${name}" location="\${path}">\\nReferences are relative to \${NodePath.dirname(path)}.\\n\\n\${body}\\n</skill>\`,
263 );
264 } catch {
265 ctx.ui.notify(\`Could not load skill \${name} from \${path}.\`, "error");
266 }
267 }
268 if (blocks.length === 0) return;
269 return {
270 action: "transform",
271 text: event.text + "\\n\\n" + blocks.join("\\n\\n"),
272 images: event.images,
273 };
274 });
275
276 // Workaround for an upstream Pi context-budgeting bug: pi-ai reuses the
277 // previous response's usage even when a fork's instructions/tools differ,
278 // then reserves almost all remaining context for output. OpenRouter can
279 // reject even a short conversation. Remove this cap when Pi accounts for
280 // the current request prefix reliably (api/simple-options + utils/estimate).
281 pi.on("before_provider_request", (event, ctx) => {
282 if (ctx.model?.provider !== "openrouter") return;
283 const payload = event.payload;
284 if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return;
285 const replacement = { ...payload } as Record<string, unknown>;
286 let changed = false;
287 for (const key of ["max_tokens", "max_completion_tokens"]) {
288 const limit = replacement[key];
289 if (typeof limit === "number" && Number.isFinite(limit) && limit > 32_768) {
290 replacement[key] = 32_768;
291 changed = true;
292 }
293 }
294 if (changed) return replacement;
295 });
296
297 // Pi deliberately leaves permission policy to extensions. T3's injected
298 // bridge uses Pi's public blocking tool hook so the shared runtime modes
299 // keep their normal meaning without replacing or shadowing Pi's runtime.
300 // Only Pi's own search is known to be read-only. An extension that replaces
301 // it keeps the name, and cannot discover deferred tools either.
302 const hasBuiltinToolSearch = () =>
303 typeof pi.getAllTools === "function" &&
304 pi.getAllTools().some((tool) => tool.name === "tool_search" && tool.sourceInfo?.path === "builtin:tool-search");
305
306 const readOnlyMcpTools = new Set<string>();
307 const isReadOnlyMcpTool = (name: string) => {
308 const extensionPath = env(EXTENSION_PATH_ENV);
309 if (extensionPath === undefined || !readOnlyMcpTools.has(name) || typeof pi.getAllTools !== "function") return false;
310 // A user extension may own the same name. Only our registered HTTP bridge
311 // may inherit the canonical T3 server's read-only annotation.
312 return pi.getAllTools().some((tool) => tool.name === name &&
313 typeof tool.sourceInfo?.path === "string" &&
314 NodePath.resolve(tool.sourceInfo.path) === NodePath.resolve(extensionPath));
315 };
316
317 pi.on("tool_call", async (event, ctx) => {
318 const mode = runtimeMode();
319 if (mode === "full-access") return;
320 if ((event.toolName === "tool_search" ? hasBuiltinToolSearch() : READ_ONLY_TOOLS.has(event.toolName)) || isReadOnlyMcpTool(event.toolName)) {
321 return;
322 }
323 if (mode === "auto-accept-edits" && FILE_CHANGE_TOOLS.has(event.toolName)) {
324 return;
325 }
326 const approved = await ctx.ui.confirm(
327 \`Allow \${event.toolName}?\`,
328 toolInputSummary(event.input),
329 { signal: ctx.signal },
330 );
331 if (!approved) {
332 return { block: true, reason: \`\${event.toolName} was declined in T3 Code.\` };
333 }
334 });
335
336 const endpoint = env(URL_ENV);
337 const token = env(TOKEN_ENV);
338 if (endpoint === undefined || token === undefined) {
339 pi.on("session_start", async (_event, ctx) => {
340 ctx.ui.notify(
341 "t3-code MCP unavailable: T3_MCP_URL or T3_MCP_BEARER_TOKEN is missing.",
342 "warning",
343 );
344 });
345 return;
346 }
347
348 // Tool exposure arrived with registerMcpServer in Pi 0.99. Keep the HTTP
349 // bridge as the credential owner: mcp.json overrides native registrations.
350 const supportsExposure = "registerMcpServer" in pi && typeof pi.registerMcpServer === "function";
351 const directTools = new Set(["orchestrator_capabilities", "delegate_task", "task_status"]);
352 let deferOptionalTools = supportsExposure;
353 let catalog: ReadonlyArray<McpTool> = [];
354
355 const client = createMcpClient(endpoint, token);
356 let started: Promise<void> | undefined;
357
358 const registerTools = () => {
359 // Preserve public names for saved loadouts and tool selectors. Hidden
360 // canonical names reserve ownership against Pi's configured MCP servers.
361 const prefixes = supportsExposure ? ["mcp__t3-code__", "mcp__t3_code__"] : ["mcp__t3-code__"];
362 readOnlyMcpTools.clear();
363 for (const tool of catalog) {
364 const name = tool.name;
365 for (const prefix of prefixes) {
366 if (tool.annotations?.readOnlyHint === true) readOnlyMcpTools.add(\`\${prefix}\${name}\`);
367 const exposure = prefix === "mcp__t3_code__" ? "hidden" :
368 deferOptionalTools && !directTools.has(name) ? "deferred" : "direct";
369 pi.registerTool({
370 name: \`\${prefix}\${name}\`,
371 label: name,
372 description: tool.description ?? name,
373 parameters: jsonSchemaToTypebox(tool.inputSchema),
374 ...(supportsExposure ? { outputSchema: mcpOutputSchema(tool) } : {}),
375 ...(supportsExposure ? { exposure } : {}),
376 async execute(_toolCallId, params, signal) {
377 const result = await client.callTool(
378 name,
379 (params ?? {}) as Record<string, unknown>,
380 signal,
381 );
382 const content = mcpModelContent(result);
383 if (isMcpToolError(result) && !content.some((part) => part.type === "text" && part.text.length > 0)) {
384 content.push({ type: "text", text: "MCP tool t3-code/" + name + " returned an error" });
385 }
386 return {
387 content,
388 structuredContent: mcpScriptResult(result),
389 details: { server: "t3-code", tool: name },
390 ...(isMcpToolError(result) ? { isError: true } : {}),
391 };
392 },
393 });
394 }
395 }
396 };
397
398 const ensureStarted = () => {
399 if (started !== undefined) return started;
400 const attempt = (async () => {
401 const signal = AbortSignal.timeout(10_000);
402 await client.connect(signal);
403 catalog = await client.listTools(signal);
404 registerTools();
405 })();
406 started = attempt;
407 void attempt.catch(() => {
408 if (started === attempt) started = undefined;
409 });
410 return attempt;
411 };
412
413 // CLI extensions load before builtins, and Pi keeps the first registration
414 // of a tool name. Register now so the bridge owns the T3 namespace even when
415 // mcp.json configures it; retry a failed connection at session_start.
416 await ensureStarted().catch(() => undefined);
417
418 const reconcileDiscovery = (ctx: Pick<ExtensionContext, "model">) => {
419 if (!supportsExposure) return;
420 // A disabled or replaced search builtin cannot discover deferred tools.
421 const hasToolSearch = hasBuiltinToolSearch();
422 const exposureChanged = deferOptionalTools !== hasToolSearch;
423 deferOptionalTools = hasToolSearch;
424 if (exposureChanged) registerTools();
425 const active = pi.getActiveTools();
426 // Completion gateways can silently drop calls to undeclared tools named
427 // in history or guidance. Eagerly load T3 schemas, including after tree
428 // restores, while retaining deferred exposure for Pi's allowlist rules.
429 // Pi still applies --tools/--exclude-tools to this active loadout.
430 const required = [
431 ...(hasToolSearch ? ["tool_search"] : []),
432 ...(ctx.model?.api === "openai-completions" ? catalog.map((tool) => "mcp__t3-code__" + tool.name) : []),
433 ];
434 const missing = required.filter((name) => !active.includes(name));
435 if (missing.length > 0) pi.setActiveTools([...active, ...missing]);
436 };
437
438 // Tree navigation restores its saved loadout after session_start.
439 pi.on("session_tree", (_event, ctx) => reconcileDiscovery(ctx));
440 pi.on("model_select", (_event, ctx) => reconcileDiscovery(ctx));
441 pi.on("session_start", async (_event, ctx) => {
442 reconcileDiscovery(ctx);
443 try {
444 await ensureStarted();
445 } catch (error) {
446 const message = error instanceof Error ? error.message : String(error);
447 ctx.ui.notify(\`t3-code MCP unavailable: \${message}\`, "warning");
448 }
449 });
450
451 // Deliver orchestration guidance through pi's real system-prompt channel.
452 // Wrapping the first user message instead would stop it from starting
453 // with "/" and silently break slash-command expansion.
454 pi.on("before_agent_start", (event, ctx) => {
455 reconcileDiscovery(ctx);
456 return { systemPrompt: event.systemPrompt + "\\n\\n" + ORCHESTRATION_INSTRUCTIONS };
457 });
458}
459`;