pi-mono/packages/coding-agent/test/suite/mcp-oauth-server.ts
Armin Ronacher 8562bcf66a feat(coding-agent): codemode and MCP
This adds codemode and MCP support to pi. Codemode (packages/codemode) runs
model-written JavaScript in a QuickJS wasm VM inside a worker. From there the
script calls pi's tools as async functions, uses a per-session store, and can
read the model catalog and run classifiers. The codemode tool in coding-agent
is compatible with Codex's exec tool, and codemode.mode works like Codex's
tool modes (on or only). Large results are written to a JSON temp file. MCP
(packages/mcp) is a standalone client for stdio and streamable HTTP servers,
with OAuth.

The core only gets general mechanisms; codemode, tool_search and MCP are
built-in extensions that use them. Other extensions can replace these
built-ins. Tools declare an exposure: direct, model-only, codemode, deferred
or hidden. prepareLoadout() lets an orchestrating tool change which tool
declarations the model sees. ctx.executeTool() runs nested calls through
validation and the tool_call/tool_result hooks. Those calls emit events with
parentToolCallId and are recorded as bounded nestedCalls on the parent
result, which compaction and HTML export use. Tools can also return
structuredContent with an outputSchema, and can report errors with isError
instead of throwing. MCP servers come from mcp.json (global, or per project
after the project is trusted) or from pi.registerMcpServer(). They are
managed with /mcp and pi mcp list|login|logout, and their runtimes load on
first use.

Closes #10040
2026-09-29 09:12:50 +02:00

143 lines
5.4 KiB
TypeScript

import { createHash } from "node:crypto";
import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
import { LATEST_PROTOCOL_VERSION } from "@earendil-works/pi-mcp";
async function readBody(request: IncomingMessage): Promise<string> {
const chunks: Buffer[] = [];
for await (const chunk of request) chunks.push(Buffer.from(chunk));
return Buffer.concat(chunks).toString("utf8");
}
function json(response: ServerResponse, status: number, body: unknown, headers: Record<string, string> = {}): void {
response.writeHead(status, { "content-type": "application/json", ...headers }).end(JSON.stringify(body));
}
/** MCP server protected by OAuth, with its own authorization server (discovery, DCR, PKCE, refresh). */
export async function startOAuthMcpServer() {
const log: string[] = [];
const validTokens = new Set<string>();
const refreshTokens = new Set<string>();
const challenges = new Map<string, string>();
let issued = 0;
let origin = "";
const issueTokens = () => {
issued++;
const tokens = { access_token: `access-${issued}`, refresh_token: `refresh-${issued}` };
validTokens.add(tokens.access_token);
refreshTokens.add(tokens.refresh_token);
return { ...tokens, token_type: "Bearer", expires_in: 3600 };
};
const handleMcp = async (request: IncomingMessage, response: ServerResponse) => {
if (request.method !== "POST") {
response.writeHead(request.method === "GET" ? 405 : 200).end();
return;
}
const token = request.headers.authorization?.replace(/^Bearer /, "");
if (!token || !validTokens.has(token)) {
log.push(`401 ${token ?? "none"}`);
response
.writeHead(401, {
"www-authenticate": `Bearer resource_metadata="${origin}/.well-known/oauth-protected-resource/mcp"`,
})
.end();
return;
}
const message = JSON.parse(await readBody(request)) as { id?: number; method: string; params?: unknown };
if (message.id === undefined) {
response.writeHead(202).end();
return;
}
let result: unknown;
if (message.method === "initialize") {
result = {
protocolVersion: LATEST_PROTOCOL_VERSION,
capabilities: { tools: {} },
serverInfo: { name: "issues", version: "1.0.0" },
};
} else if (message.method === "tools/list") {
result = { tools: [{ name: "whoami", inputSchema: { type: "object", properties: {} } }] };
} else if (message.method === "tools/call") {
log.push(`call ${token}`);
result = { content: [{ type: "text", text: `token ${token}` }] };
} else {
result = {};
}
json(response, 200, { jsonrpc: "2.0", id: message.id, result });
};
const handle = async (request: IncomingMessage, response: ServerResponse) => {
const url = new URL(request.url ?? "/", origin);
switch (url.pathname) {
case "/mcp":
return handleMcp(request, response);
case "/.well-known/oauth-protected-resource/mcp":
return json(response, 200, { resource: `${origin}/mcp`, authorization_servers: [origin] });
case "/.well-known/oauth-authorization-server":
return json(response, 200, {
issuer: origin,
authorization_endpoint: `${origin}/authorize`,
token_endpoint: `${origin}/token`,
registration_endpoint: `${origin}/register`,
response_types_supported: ["code"],
code_challenge_methods_supported: ["S256"],
token_endpoint_auth_methods_supported: ["none"],
});
case "/register": {
const metadata = JSON.parse(await readBody(request)) as Record<string, unknown>;
log.push("register");
return json(response, 201, { ...metadata, client_id: "client-1" });
}
case "/authorize": {
const code = `code-${challenges.size + 1}`;
challenges.set(code, url.searchParams.get("code_challenge") ?? "");
const redirect = new URL(url.searchParams.get("redirect_uri") ?? "");
redirect.searchParams.set("code", code);
redirect.searchParams.set("state", url.searchParams.get("state") ?? "");
response.writeHead(302, { location: redirect.href }).end();
return;
}
case "/token": {
const params = new URLSearchParams(await readBody(request));
if (params.get("grant_type") === "authorization_code") {
const challenge = challenges.get(params.get("code") ?? "");
const verifier = createHash("sha256")
.update(params.get("code_verifier") ?? "")
.digest("base64url");
if (!challenge || challenge !== verifier) return json(response, 400, { error: "invalid_grant" });
challenges.delete(params.get("code") ?? "");
log.push("token code");
return json(response, 200, issueTokens());
}
const refresh = params.get("refresh_token") ?? "";
if (!refreshTokens.delete(refresh)) return json(response, 400, { error: "invalid_grant" });
log.push("token refresh");
return json(response, 200, issueTokens());
}
default:
response.writeHead(404).end();
}
};
const server: Server = createServer((request, response) => {
void handle(request, response).catch((error) => {
response.writeHead(500).end(String(error));
});
});
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
if (!address || typeof address === "string") throw new Error("test server did not bind to TCP");
origin = `http://127.0.0.1:${address.port}`;
return {
url: `${origin}/mcp`,
log,
/** Simulates access token expiry. */
expireAccessTokens: () => validTokens.clear(),
close: () =>
new Promise<void>((resolve) => {
server.closeAllConnections();
server.close(() => resolve());
}),
};
}