The best way to control Claude Code, Codex and more from any computer or phone

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