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

mcpExtensionSource.ts

439 lines16.4 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 JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };
42​
43type JsonRpcResponse = {
44 readonly id?: number | string;
45 readonly result?: JsonValue;
46 readonly error?: { readonly message?: string };
47};
48​
49type McpTool = {
50 readonly name: string;
51 readonly description?: string;
52 readonly inputSchema?: Record<string, unknown>;
53 readonly outputSchema?: Record<string, unknown>;
54};
55​
56function env(name: string): string | undefined {
57 const value = process.env[name];
58 return value && value.length > 0 ? value : undefined;
60​
61function runtimeMode(): RuntimeMode {
62 const value = env(RUNTIME_MODE_ENV);
63 return value === "approval-required" ||
64 value === "auto-accept-edits" ||
65 value === "auto" ||
66 value === "full-access"
67 ? value
68 : "full-access";
70​
71function toolInputSummary(input: unknown): string {
72 try {
73 return JSON.stringify(input, null, 2).slice(0, 4_000);
74 } catch {
75 return String(input).slice(0, 4_000);
76 }
78​
79function parseSseOrJson(body: string, contentType: string): JsonRpcResponse {
80 if (contentType.includes("text/event-stream")) {
81 for (const line of body.split("\\n")) {
82 const trimmed = line.startsWith("data:") ? line.slice(5).trim() : "";
83 if (trimmed.length === 0) continue;
84 const parsed = JSON.parse(trimmed) as JsonRpcResponse;
85 if (parsed.id !== undefined || parsed.result !== undefined || parsed.error !== undefined) {
86 return parsed;
87 }
88 }
89 throw new Error("MCP SSE response had no JSON-RPC payload.");
90 }
91 return JSON.parse(body) as JsonRpcResponse;
93​
94function jsonSchemaToTypebox(schema: Record<string, unknown> | undefined) {
95 const unsafe = (Type as { Unsafe?: (value: unknown) => unknown }).Unsafe;
96 if (typeof unsafe === "function" && schema !== undefined) {
97 return unsafe(schema);
98 }
99 return Type.Object({}, { additionalProperties: true });
101​
102type ModelContent =
103 | { type: "text"; text: string }
104 | { type: "image"; data: string; mimeType: string };
105​
106function mcpModelContent(result: unknown): ModelContent[] {
107 if (result === null || result === undefined) return [];
108 if (typeof result !== "object") return [{ type: "text", text: String(result) }];
109 const record = result as {
110 readonly content?: ReadonlyArray<{
111 readonly type?: string;
112 readonly text?: string;
113 readonly data?: string;
114 readonly mimeType?: string;
115 }>;
116 readonly structuredContent?: unknown;
117 };
118 const content: ModelContent[] = [];
119 if (Array.isArray(record.content)) {
120 for (const part of record.content) {
121 if (part?.type === "text" && typeof part.text === "string") {
122 content.push({ type: "text", text: part.text });
123 } else if (part?.type === "image" && typeof part.data === "string" && typeof part.mimeType === "string") {
124 content.push({ type: "image", data: part.data, mimeType: part.mimeType });
125 }
126 }
127 }
128 // Structured output belongs to scripts. Only use it as model text when
129 // the server supplied no model-facing blocks, matching Pi's native MCP tools.
130 if (content.length === 0) {
131 content.push({ type: "text", text: JSON.stringify(record.structuredContent ?? result) });
132 }
133 return content;
135​
136function mcpScriptResult(result: JsonValue | undefined) {
137 if (typeof result !== "object" || result === null || Array.isArray(result)) return result;
138 const { _meta: _ignored, ...scriptResult } = result;
139 return scriptResult;
141​
142function mcpOutputSchema(tool: McpTool) {
143 return jsonSchemaToTypebox({
144 type: "object",
145 properties: {
146 content: { type: "array", items: { type: "object" } },
147 ...(tool.outputSchema === undefined ? {} : { structuredContent: tool.outputSchema }),
148 isError: { type: "boolean" },
149 _meta: { type: "object" },
150 },
151 required: ["content"],
152 });
154​
155function isMcpToolError(result: unknown): boolean {
156 return (
157 typeof result === "object" &&
158 result !== null &&
159 "isError" in result &&
160 result.isError === true
161 );
163​
164function createMcpClient(endpoint: string, token: string) {
165 let nextId = 1;
166 let sessionId: string | undefined;
167​
168 const headers = (): Record<string, string> => {
169 const next: Record<string, string> = {
170 accept: "application/json, text/event-stream",
171 authorization: token.startsWith("Bearer ") ? token : \`Bearer \${token}\`,
172 "content-type": "application/json",
173 // Effect's HTTP MCP rejects post-initialize requests without this
174 // (400). The worktree client in McpHttpServer tests sends the same
175 // header; initialize itself does not require it.
176 "mcp-protocol-version": PROTOCOL,
177 };
178 if (sessionId !== undefined) next["mcp-session-id"] = sessionId;
179 return next;
180 };
181​
182 const request = async (method: string, params?: unknown, signal?: AbortSignal) => {
183 const id = nextId++;
184 const response = await fetch(endpoint, {
185 method: "POST",
186 headers: headers(),
187 body: JSON.stringify({ jsonrpc: "2.0", id, method, params }),
188 signal,
189 });
190 const nextSession = response.headers.get("mcp-session-id");
191 if (nextSession) sessionId = nextSession;
192 const body = await response.text();
193 if (!response.ok) {
194 throw new Error(\`MCP \${method} failed (\${response.status}): \${body.slice(0, 400)}\`);
195 }
196 if (body.length === 0) return undefined;
197 const parsed = parseSseOrJson(body, response.headers.get("content-type") ?? "");
198 if (parsed.error) {
199 throw new Error(parsed.error.message ?? \`MCP \${method} returned an error\`);
200 }
201 return parsed.result;
202 };
203​
204 const notify = async (method: string, params?: unknown, signal?: AbortSignal) => {
205 await fetch(endpoint, {
206 method: "POST",
207 headers: headers(),
208 body: JSON.stringify({ jsonrpc: "2.0", method, params }),
209 signal,
210 });
211 };
212​
213 return {
214 async connect(signal?: AbortSignal) {
215 await request(
216 "initialize",
217 {
218 protocolVersion: PROTOCOL,
219 capabilities: {},
220 clientInfo: { name: "t3-pi-mcp", version: "1.0.0" },
221 },
222 signal,
223 );
224 await notify("notifications/initialized", {}, signal).catch(() => undefined);
225 },
226 async listTools(signal?: AbortSignal) {
227 const tools: McpTool[] = [];
228 let cursor: string | undefined;
229 do {
230 const result = (await request(
231 "tools/list",
232 cursor === undefined ? {} : { cursor },
233 signal,
234 )) as { tools?: McpTool[]; nextCursor?: string } | undefined;
235 tools.push(...(result?.tools ?? []));
236 cursor = result?.nextCursor;
237 } while (cursor);
238 return tools;
239 },
240 async callTool(name: string, args: Record<string, unknown>, signal?: AbortSignal) {
241 return request("tools/call", { name, arguments: args }, signal);
242 },
243 };
245​
246export default async function t3McpExtension(pi: ExtensionAPI) {
247 // Keep skill chips in the request. Pi expands only one leading /skill:
248 // command, so use its own frontmatter loader for every selected chip here.
249 pi.on("input", async (event, ctx) => {
250 if (!event.text.includes("$")) return;
251 const commands = pi.getCommands().filter((command) => command.source === "skill");
252 const nativeSkill = /^\\/skill:([^ ]+)(?: |$)/.exec(event.text)?.[1];
253 const seen = new Set<string>(nativeSkill === undefined ? [] : [nativeSkill]);
254 const blocks: string[] = [];
255 for (const match of event.text.matchAll(/(^|\\s)\\$([^\\s]+)(?=\\s|$)/g)) {
256 const name = match[2];
257 if (name === undefined || seen.has(name)) continue;
258 const command = commands.find((candidate) => candidate.name === "skill:" + name);
259 if (command === undefined) continue;
260 seen.add(name);
261 const path = command.sourceInfo.path;
262 try {
263 const body = stripFrontmatter(await NodeFSP.readFile(path, "utf8")).trim();
264 blocks.push(
265 \`<skill name="\${name}" location="\${path}">\\nReferences are relative to \${NodePath.dirname(path)}.\\n\\n\${body}\\n</skill>\`,
266 );
267 } catch {
268 ctx.ui.notify(\`Could not load skill \${name} from \${path}.\`, "error");
269 }
270 }
271 if (blocks.length === 0) return;
272 return {
273 action: "transform",
274 text: event.text + "\\n\\n" + blocks.join("\\n\\n"),
275 images: event.images,
276 };
277 });
278​
279 // Workaround for an upstream Pi context-budgeting bug: pi-ai reuses the
280 // previous response's usage even when a fork's instructions/tools differ,
281 // then reserves almost all remaining context for output. OpenRouter can
282 // reject even a short conversation. Remove this cap when Pi accounts for
283 // the current request prefix reliably (api/simple-options + utils/estimate).
284 pi.on("before_provider_request", (event, ctx) => {
285 if (ctx.model?.provider !== "openrouter") return;
286 const payload = event.payload;
287 if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return;
288 const replacement = { ...payload } as Record<string, unknown>;
289 let changed = false;
290 for (const key of ["max_tokens", "max_completion_tokens"]) {
291 const limit = replacement[key];
292 if (typeof limit === "number" && Number.isFinite(limit) && limit > 32_768) {
293 replacement[key] = 32_768;
294 changed = true;
295 }
296 }
297 if (changed) return replacement;
298 });
299​
300 // Pi deliberately leaves permission policy to extensions. T3's injected
301 // bridge uses Pi's public blocking tool hook so the shared runtime modes
302 // keep their normal meaning without replacing or shadowing Pi's runtime.
303 // Only Pi's own search is known to be read-only. An extension that replaces
304 // it keeps the name, and cannot discover deferred tools either.
305 const hasBuiltinToolSearch = () =>
306 typeof pi.getAllTools === "function" &&
307 pi.getAllTools().some((tool) => tool.name === "tool_search" && tool.sourceInfo?.path === "builtin:tool-search");
308​
309 pi.on("tool_call", async (event, ctx) => {
310 const mode = runtimeMode();
311 if (mode === "full-access") return;
312 if (event.toolName === "tool_search" ? hasBuiltinToolSearch() : READ_ONLY_TOOLS.has(event.toolName)) {
313 return;
314 }
315 if (mode === "auto-accept-edits" && FILE_CHANGE_TOOLS.has(event.toolName)) {
316 return;
317 }
318 const approved = await ctx.ui.confirm(
319 \`Allow \${event.toolName}?\`,
320 toolInputSummary(event.input),
321 );
322 if (!approved) {
323 return { block: true, reason: \`\${event.toolName} was declined in T3 Code.\` };
324 }
325 });
326​
327 const endpoint = env(URL_ENV);
328 const token = env(TOKEN_ENV);
329 if (endpoint === undefined || token === undefined) {
330 pi.on("session_start", async (_event, ctx) => {
331 ctx.ui.notify(
332 "t3-code MCP unavailable: T3_MCP_URL or T3_MCP_BEARER_TOKEN is missing.",
333 "warning",
334 );
335 });
336 return;
337 }
338​
339 // Tool exposure arrived with registerMcpServer in Pi 0.99. Keep the HTTP
340 // bridge as the credential owner: mcp.json overrides native registrations.
341 const supportsExposure = "registerMcpServer" in pi && typeof pi.registerMcpServer === "function";
342 const directTools = new Set(["orchestrator_capabilities", "delegate_task", "task_status"]);
343 let deferOptionalTools = supportsExposure;
344 let catalog: ReadonlyArray<McpTool> = [];
345​
346 const client = createMcpClient(endpoint, token);
347 let started: Promise<void> | undefined;
348​
349 const registerTools = () => {
350 // Preserve public names for saved loadouts and tool selectors. Hidden
351 // canonical names reserve ownership against Pi's configured MCP servers.
352 const prefixes = supportsExposure ? ["mcp__t3-code__", "mcp__t3_code__"] : ["mcp__t3-code__"];
353 for (const tool of catalog) {
354 const name = tool.name;
355 for (const prefix of prefixes) {
356 const exposure = prefix === "mcp__t3_code__" ? "hidden" :
357 deferOptionalTools && !directTools.has(name) ? "deferred" : "direct";
358 pi.registerTool({
359 name: \`\${prefix}\${name}\`,
360 label: name,
361 description: tool.description ?? name,
362 parameters: jsonSchemaToTypebox(tool.inputSchema),
363 ...(supportsExposure ? { outputSchema: mcpOutputSchema(tool) } : {}),
364 ...(supportsExposure ? { exposure } : {}),
365 async execute(_toolCallId, params, signal) {
366 const result = await client.callTool(
367 name,
368 (params ?? {}) as Record<string, unknown>,
369 signal,
370 );
371 const content = mcpModelContent(result);
372 if (isMcpToolError(result) && !content.some((part) => part.type === "text" && part.text.length > 0)) {
373 content.push({ type: "text", text: "MCP tool t3-code/" + name + " returned an error" });
374 }
375 return {
376 content,
377 structuredContent: mcpScriptResult(result),
378 details: { server: "t3-code", tool: name },
379 ...(isMcpToolError(result) ? { isError: true } : {}),
380 };
381 },
382 });
383 }
384 }
385 };
386​
387 const ensureStarted = () => {
388 if (started !== undefined) return started;
389 const attempt = (async () => {
390 const signal = AbortSignal.timeout(10_000);
391 await client.connect(signal);
392 catalog = await client.listTools(signal);
393 registerTools();
394 })();
395 started = attempt;
396 void attempt.catch(() => {
397 if (started === attempt) started = undefined;
398 });
399 return attempt;
400 };
401​
402 // CLI extensions load before builtins, and Pi keeps the first registration
403 // of a tool name. Register now so the bridge owns the T3 namespace even when
404 // mcp.json configures it; retry a failed connection at session_start.
405 await ensureStarted().catch(() => undefined);
406​
407 const reconcileDiscovery = () => {
408 if (!supportsExposure) return;
409 // A disabled or replaced search builtin cannot discover deferred tools.
410 const hasToolSearch = hasBuiltinToolSearch();
411 const exposureChanged = deferOptionalTools !== hasToolSearch;
412 deferOptionalTools = hasToolSearch;
413 if (exposureChanged) registerTools();
414 if (hasToolSearch) {
415 const active = pi.getActiveTools();
416 if (!active.includes("tool_search")) pi.setActiveTools([...active, "tool_search"]);
417 }
418 };
419​
420 // Tree navigation restores its saved loadout after session_start.
421 pi.on("session_tree", reconcileDiscovery);
422 pi.on("session_start", async (_event, ctx) => {
423 reconcileDiscovery();
424 try {
425 await ensureStarted();
426 } catch (error) {
427 const message = error instanceof Error ? error.message : String(error);
428 ctx.ui.notify(\`t3-code MCP unavailable: \${message}\`, "warning");
429 }
430 });
431​
432 // Deliver orchestration guidance through pi's real system-prompt channel.
433 // Wrapping the first user message instead would stop it from starting
434 // with "/" and silently break slash-command expansion.
435 pi.on("before_agent_start", (event) => ({
436 systemPrompt: event.systemPrompt + "\\n\\n" + ORCHESTRATION_INSTRUCTIONS,
437 }));
439`;