Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

mcpExtensionSource.ts

402 lines15.0 KB

1/**
2 * Source for the T3-owned Pi extension that consumes T3's HTTP MCP server.
3 *
4 * Pi 0.99+ discovers optional HTTP bridge tools on demand. Older versions
5 * keep them directly available. Pi loads this TypeScript via `--extension`; the
6 * server writes it to a cache so packaged builds need no sibling .ts file.
7 *
8 * Do not import t3code modules from the string body. The Pi process resolves
9 * `@earendil-works/pi-coding-agent` and `typebox` from the user's pi install.
10 */
11import { T3_CODE_ORCHESTRATION_INSTRUCTIONS } from "@t3tools/provider-core/server/orchestrationInstructions";
12​
13export const PI_T3_MCP_EXTENSION_FILENAME = "pi-t3-mcp-extension.ts";
14​
15export const T3_MCP_URL_ENV = "T3_MCP_URL";
16export const T3_MCP_BEARER_ENV = "T3_MCP_BEARER_TOKEN";
17export const T3_PI_RUNTIME_MODE_ENV = "T3_PI_RUNTIME_MODE";
18​
19/**
20 * Pi tools whose confirmations the bridge raises as file-change approvals.
21 * Auto-accept edits skips them; the adapter keys the approval kind off them.
22 */
23export const PI_FILE_CHANGE_TOOLS = ["edit", "write"] as const;
24​
25export const PI_T3_MCP_EXTENSION_SOURCE = `\
26import { stripFrontmatter, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
27import * as NodeFSP from "node:fs/promises";
28import * as NodePath from "node:path";
29import { Type } from "typebox";
30​
31const URL_ENV = ${JSON.stringify(T3_MCP_URL_ENV)};
32const TOKEN_ENV = ${JSON.stringify(T3_MCP_BEARER_ENV)};
33const RUNTIME_MODE_ENV = ${JSON.stringify(T3_PI_RUNTIME_MODE_ENV)};
34const ORCHESTRATION_INSTRUCTIONS = ${JSON.stringify(T3_CODE_ORCHESTRATION_INSTRUCTIONS.trim())};
35const PROTOCOL = "2025-06-18";
36const READ_ONLY_TOOLS = new Set(["read", "grep", "find", "ls"]);
37const FILE_CHANGE_TOOLS = new Set(${JSON.stringify(PI_FILE_CHANGE_TOOLS)});
38​
39type RuntimeMode = "approval-required" | "auto-accept-edits" | "auto" | "full-access";
40​
41type JsonRpcResponse = {
42 readonly id?: number | string;
43 readonly result?: unknown;
44 readonly error?: { readonly message?: string };
45};
46​
47type McpTool = {
48 readonly name: string;
49 readonly description?: string;
50 readonly inputSchema?: 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;
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";
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 }
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;
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 });
98​
99function formatMcpContent(result: unknown): string {
100 if (result === null || result === undefined) return "";
101 if (typeof result !== "object") return String(result);
102 const record = result as {
103 readonly content?: ReadonlyArray<{ readonly type?: string; readonly text?: string }>;
104 readonly structuredContent?: unknown;
105 readonly isError?: boolean;
106 };
107 const texts: string[] = [];
108 if (Array.isArray(record.content)) {
109 for (const part of record.content) {
110 if (part?.type === "text" && typeof part.text === "string") texts.push(part.text);
111 }
112 }
113 // Most T3 tools mirror structuredContent in a text block. Repeating it would
114 // leave T3's own output parsing two JSON documents instead of one.
115 if (record.structuredContent !== undefined) {
116 const structured = JSON.stringify(record.structuredContent);
117 if (!texts.includes(structured)) texts.push(structured);
118 }
119 if (texts.length > 0) return texts.join("\\n");
120 return JSON.stringify(result);
122​
123function isMcpToolError(result: unknown): boolean {
124 return (
125 typeof result === "object" &&
126 result !== null &&
127 "isError" in result &&
128 result.isError === true
129 );
131​
132function createMcpClient(endpoint: string, token: string) {
133 let nextId = 1;
134 let sessionId: string | undefined;
135​
136 const headers = (): Record<string, string> => {
137 const next: Record<string, string> = {
138 accept: "application/json, text/event-stream",
139 authorization: token.startsWith("Bearer ") ? token : \`Bearer \${token}\`,
140 "content-type": "application/json",
141 // Effect's HTTP MCP rejects post-initialize requests without this
142 // (400). The worktree client in McpHttpServer tests sends the same
143 // header; initialize itself does not require it.
144 "mcp-protocol-version": PROTOCOL,
145 };
146 if (sessionId !== undefined) next["mcp-session-id"] = sessionId;
147 return next;
148 };
149​
150 const request = async (method: string, params?: unknown, signal?: AbortSignal) => {
151 const id = nextId++;
152 const response = await fetch(endpoint, {
153 method: "POST",
154 headers: headers(),
155 body: JSON.stringify({ jsonrpc: "2.0", id, method, params }),
156 signal,
157 });
158 const nextSession = response.headers.get("mcp-session-id");
159 if (nextSession) sessionId = nextSession;
160 const body = await response.text();
161 if (!response.ok) {
162 throw new Error(\`MCP \${method} failed (\${response.status}): \${body.slice(0, 400)}\`);
163 }
164 if (body.length === 0) return undefined;
165 const parsed = parseSseOrJson(body, response.headers.get("content-type") ?? "");
166 if (parsed.error) {
167 throw new Error(parsed.error.message ?? \`MCP \${method} returned an error\`);
168 }
169 return parsed.result;
170 };
171​
172 const notify = async (method: string, params?: unknown, signal?: AbortSignal) => {
173 await fetch(endpoint, {
174 method: "POST",
175 headers: headers(),
176 body: JSON.stringify({ jsonrpc: "2.0", method, params }),
177 signal,
178 });
179 };
180​
181 return {
182 async connect(signal?: AbortSignal) {
183 await request(
184 "initialize",
185 {
186 protocolVersion: PROTOCOL,
187 capabilities: {},
188 clientInfo: { name: "t3-pi-mcp", version: "1.0.0" },
189 },
190 signal,
191 );
192 await notify("notifications/initialized", {}, signal).catch(() => undefined);
193 },
194 async listTools(signal?: AbortSignal) {
195 const tools: McpTool[] = [];
196 let cursor: string | undefined;
197 do {
198 const result = (await request(
199 "tools/list",
200 cursor === undefined ? {} : { cursor },
201 signal,
202 )) as { tools?: McpTool[]; nextCursor?: string } | undefined;
203 tools.push(...(result?.tools ?? []));
204 cursor = result?.nextCursor;
205 } while (cursor);
206 return tools;
207 },
208 async callTool(name: string, args: Record<string, unknown>, signal?: AbortSignal) {
209 return request("tools/call", { name, arguments: args }, signal);
210 },
211 };
213​
214export default async function t3McpExtension(pi: ExtensionAPI) {
215 // Keep skill chips in the request. Pi expands only one leading /skill:
216 // command, so use its own frontmatter loader for every selected chip here.
217 pi.on("input", async (event, ctx) => {
218 if (!event.text.includes("$")) return;
219 const commands = pi.getCommands().filter((command) => command.source === "skill");
220 const nativeSkill = /^\\/skill:([^ ]+)(?: |$)/.exec(event.text)?.[1];
221 const seen = new Set<string>(nativeSkill === undefined ? [] : [nativeSkill]);
222 const blocks: string[] = [];
223 for (const match of event.text.matchAll(/(^|\\s)\\$([^\\s]+)(?=\\s|$)/g)) {
224 const name = match[2];
225 if (name === undefined || seen.has(name)) continue;
226 const command = commands.find((candidate) => candidate.name === "skill:" + name);
227 if (command === undefined) continue;
228 seen.add(name);
229 const path = command.sourceInfo.path;
230 try {
231 const body = stripFrontmatter(await NodeFSP.readFile(path, "utf8")).trim();
232 blocks.push(
233 \`<skill name="\${name}" location="\${path}">\\nReferences are relative to \${NodePath.dirname(path)}.\\n\\n\${body}\\n</skill>\`,
234 );
235 } catch {
236 ctx.ui.notify(\`Could not load skill \${name} from \${path}.\`, "error");
237 }
238 }
239 if (blocks.length === 0) return;
240 return {
241 action: "transform",
242 text: event.text + "\\n\\n" + blocks.join("\\n\\n"),
243 images: event.images,
244 };
245 });
246​
247 // Workaround for an upstream Pi context-budgeting bug: pi-ai reuses the
248 // previous response's usage even when a fork's instructions/tools differ,
249 // then reserves almost all remaining context for output. OpenRouter can
250 // reject even a short conversation. Remove this cap when Pi accounts for
251 // the current request prefix reliably (api/simple-options + utils/estimate).
252 pi.on("before_provider_request", (event, ctx) => {
253 if (ctx.model?.provider !== "openrouter") return;
254 const payload = event.payload;
255 if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return;
256 const replacement = { ...payload } as Record<string, unknown>;
257 let changed = false;
258 for (const key of ["max_tokens", "max_completion_tokens"]) {
259 const limit = replacement[key];
260 if (typeof limit === "number" && Number.isFinite(limit) && limit > 32_768) {
261 replacement[key] = 32_768;
262 changed = true;
263 }
264 }
265 if (changed) return replacement;
266 });
267​
268 // Pi deliberately leaves permission policy to extensions. T3's injected
269 // bridge uses Pi's public blocking tool hook so the shared runtime modes
270 // keep their normal meaning without replacing or shadowing Pi's runtime.
271 // Only Pi's own search is known to be read-only. An extension that replaces
272 // it keeps the name, and cannot discover deferred tools either.
273 const hasBuiltinToolSearch = () =>
274 typeof pi.getAllTools === "function" &&
275 pi.getAllTools().some((tool) => tool.name === "tool_search" && tool.sourceInfo?.path === "builtin:tool-search");
276​
277 pi.on("tool_call", async (event, ctx) => {
278 const mode = runtimeMode();
279 if (mode === "full-access") return;
280 if (event.toolName === "tool_search" ? hasBuiltinToolSearch() : READ_ONLY_TOOLS.has(event.toolName)) {
281 return;
282 }
283 if (mode === "auto-accept-edits" && FILE_CHANGE_TOOLS.has(event.toolName)) {
284 return;
285 }
286 const approved = await ctx.ui.confirm(
287 \`Allow \${event.toolName}?\`,
288 toolInputSummary(event.input),
289 );
290 if (!approved) {
291 return { block: true, reason: \`\${event.toolName} was declined in T3 Code.\` };
292 }
293 });
294​
295 const endpoint = env(URL_ENV);
296 const token = env(TOKEN_ENV);
297 if (endpoint === undefined || token === undefined) {
298 pi.on("session_start", async (_event, ctx) => {
299 ctx.ui.notify(
300 "t3-code MCP unavailable: T3_MCP_URL or T3_MCP_BEARER_TOKEN is missing.",
301 "warning",
302 );
303 });
304 return;
305 }
306​
307 // Tool exposure arrived with registerMcpServer in Pi 0.99. Keep the HTTP
308 // bridge as the credential owner: mcp.json overrides native registrations.
309 const supportsExposure = "registerMcpServer" in pi && typeof pi.registerMcpServer === "function";
310 const directTools = new Set(["orchestrator_capabilities", "delegate_task", "task_status"]);
311 let deferOptionalTools = supportsExposure;
312 let catalog: ReadonlyArray<McpTool> = [];
313​
314 const client = createMcpClient(endpoint, token);
315 let started: Promise<void> | undefined;
316​
317 const registerTools = () => {
318 // Preserve public names for saved loadouts and tool selectors. Hidden
319 // canonical names reserve ownership against Pi's configured MCP servers.
320 const prefixes = supportsExposure ? ["mcp__t3-code__", "mcp__t3_code__"] : ["mcp__t3-code__"];
321 for (const tool of catalog) {
322 const name = tool.name;
323 for (const prefix of prefixes) {
324 const exposure = prefix === "mcp__t3_code__" ? "hidden" :
325 deferOptionalTools && !directTools.has(name) ? "deferred" : "direct";
326 pi.registerTool({
327 name: \`\${prefix}\${name}\`,
328 label: name,
329 description: tool.description ?? name,
330 parameters: jsonSchemaToTypebox(tool.inputSchema),
331 ...(supportsExposure ? { exposure } : {}),
332 async execute(_toolCallId, params, signal) {
333 const result = await client.callTool(
334 name,
335 (params ?? {}) as Record<string, unknown>,
336 signal,
337 );
338 const text = formatMcpContent(result);
339 return {
340 content: [{ type: "text", text }],
341 details: { server: "t3-code", tool: name },
342 ...(isMcpToolError(result) ? { isError: true } : {}),
343 };
344 },
345 });
346 }
347 }
348 };
349​
350 const ensureStarted = () => {
351 if (started !== undefined) return started;
352 const attempt = (async () => {
353 const signal = AbortSignal.timeout(10_000);
354 await client.connect(signal);
355 catalog = await client.listTools(signal);
356 registerTools();
357 })();
358 started = attempt;
359 void attempt.catch(() => {
360 if (started === attempt) started = undefined;
361 });
362 return attempt;
363 };
364​
365 // CLI extensions load before builtins, and Pi keeps the first registration
366 // of a tool name. Register now so the bridge owns the T3 namespace even when
367 // mcp.json configures it; retry a failed connection at session_start.
368 await ensureStarted().catch(() => undefined);
369​
370 const reconcileDiscovery = () => {
371 if (!supportsExposure) return;
372 // A disabled or replaced search builtin cannot discover deferred tools.
373 const hasToolSearch = hasBuiltinToolSearch();
374 const exposureChanged = deferOptionalTools !== hasToolSearch;
375 deferOptionalTools = hasToolSearch;
376 if (exposureChanged) registerTools();
377 if (hasToolSearch) {
378 const active = pi.getActiveTools();
379 if (!active.includes("tool_search")) pi.setActiveTools([...active, "tool_search"]);
380 }
381 };
382​
383 // Tree navigation restores its saved loadout after session_start.
384 pi.on("session_tree", reconcileDiscovery);
385 pi.on("session_start", async (_event, ctx) => {
386 reconcileDiscovery();
387 try {
388 await ensureStarted();
389 } catch (error) {
390 const message = error instanceof Error ? error.message : String(error);
391 ctx.ui.notify(\`t3-code MCP unavailable: \${message}\`, "warning");
392 }
393 });
394​
395 // Deliver orchestration guidance through pi's real system-prompt channel.
396 // Wrapping the first user message instead would stop it from starting
397 // with "/" and silently break slash-command expansion.
398 pi.on("before_agent_start", (event) => ({
399 systemPrompt: event.systemPrompt + "\\n\\n" + ORCHESTRATION_INSTRUCTIONS,
400 }));
402`;