// PEP-212: «code mode» for the MCP servers. Instead of dozens of tool descriptions the client gets // two tools: `search_api` (finds methods of the `peppa` object and returns short TypeScript // signatures) and `execute` (runs a short JS script against that object in a sandbox). // // One source of truth: the tools are still defined once with `define(name, description, schema, // readOnly, run)`. The same definitions become the direct MCP tools (mode `tools`/`both`) and the // methods of `peppa` (mode `code`/`both`); signatures are generated from the zod schemas. A method // is the tool's own `run`, closed over the caller (`projectForUser`, superadmin check, `lockProject`), // so the rights are exactly those of the tool. // // Sandbox: QuickJS compiled to wasm (see openspec/changes/pep-212-mcp-code-mode/design.md). The // script sees the language and `peppa` — no process, require, fs, fetch, timers, imports. import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { getQuickJS, newQuickJSWASMModule, type QuickJSContext, type QuickJSDeferredPromise, type QuickJSWASMModule } from "quickjs-emscripten"; import { getProject, logEvent, PeppaError, platformProjectKey } from "@peppa/core"; import type { Db } from "@peppa/db"; import { z } from "zod"; export type McpMode = "code" | "tools" | "both"; /** `PEPPA_MCP_MODE=code|tools|both` (default `both`: old tool names keep working during the transition). */ export function mcpMode(env: Record = process.env): McpMode { const v = (env.PEPPA_MCP_MODE ?? "").trim().toLowerCase(); return v === "code" || v === "tools" || v === "both" ? v : "both"; } export const LIMITS = { timeoutMs: 10_000, memoryBytes: 32 * 1024 * 1024, stackBytes: 512 * 1024, outputChars: 64 * 1024, maxCalls: 50, logChars: 8 * 1024 }; export interface ToolDef { name: string; description: string; shape: z.ZodRawShape; readOnly: boolean; run: (args: never) => Promise; } export type Define = (name: string, description: string, schema: S, readOnly: boolean, run: (a: z.infer>) => Promise) => void; // ---------- the API generated from the definitions ---------- const KEEP_NAME = new Set(["usage", "inbox", "memory", "rules", "started", "progress", "incident_policy", "project_settings", "deploy"]); const NS_OVERRIDE: Record = { ask_pm: "pm.ask", deploy: "releases.deploy", platform_status: "platform.status", create_error_task: "errors.createTask" }; /** `list_tasks` → `tasks.list`, `get_task` → `tasks.get`, `ask_pm` → `pm.ask`, `get_usage` → `usage.get`. */ export function apiPath(name: string): { ns: string; method: string } { const o = NS_OVERRIDE[name]; if (o) { const [ns, method] = o.split("."); return { ns: ns!, method: method! }; } const i = name.indexOf("_"); if (i < 0) return { ns: name, method: "run" }; const verb = name.slice(0, i); const noun = name.slice(i + 1); return { ns: KEEP_NAME.has(noun) || noun.endsWith("s") ? noun : `${noun}s`, method: verb }; } /** Aliases of other tools (list_goals …) are not API methods — they would only add noise. */ const isAlias = (d: ToolDef) => /^Alias of /i.test(d.description); type JsonSchema = { type?: string | string[]; enum?: unknown[]; const?: unknown; anyOf?: JsonSchema[]; oneOf?: JsonSchema[]; items?: JsonSchema; properties?: Record; required?: string[]; description?: string }; function tsType(s: JsonSchema | boolean | undefined): string { if (!s || s === true) return "any"; if (s.enum) return s.enum.map((v) => JSON.stringify(v)).join(" | "); if (s.const !== undefined) return JSON.stringify(s.const); const alt = s.anyOf ?? s.oneOf; if (alt) return alt.map(tsType).join(" | "); const t = Array.isArray(s.type) ? s.type : [s.type]; return t .map((x) => { if (x === "string") return "string"; if (x === "number" || x === "integer") return "number"; if (x === "boolean") return "boolean"; if (x === "null") return "null"; if (x === "array") { const inner = tsType(s.items); return /[|{]/.test(inner) ? `(${inner})[]` : `${inner}[]`; } if (x === "object") return objectType(s); return "any"; }) .join(" | "); } function objectType(s: JsonSchema, withDocs = false): string { const props = Object.entries(s.properties ?? {}); if (!props.length) return "{}"; const required = new Set(s.required ?? []); const doc = (d?: string) => (withDocs && d ? ` /* ${d.replace(/\*\//g, "").replace(/\s+/g, " ").slice(0, 110)} */` : ""); return `{ ${props.map(([k, v]) => `${k}${required.has(k) ? "" : "?"}: ${tsType(v)}${doc(v.description)}`).join("; ")} }`; } /** A short TypeScript signature of one API method, generated from the tool's zod schema. */ export function signature(d: ToolDef): string { const { ns, method } = apiPath(d.name); const json = z.toJSONSchema(z.object(d.shape), { io: "input", unrepresentable: "any" }) as JsonSchema; const has = Object.keys(json.properties ?? {}).length > 0; const allOptional = !(json.required ?? []).length; const args = has ? `args${allOptional ? "?" : ""}: ${objectType(json, true)}` : ""; return `peppa.${ns}.${method}(${args}): Promise`; } const firstSentence = (s: string) => (s.split(/(?<=[.!?])\s/)[0] ?? s).slice(0, 220); /** `search_api`: the methods that match the query, with signatures — never the whole API at once. */ export function searchApi(defs: ToolDef[], query: string, limit = 8): string { const api = defs.filter((d) => !isAlias(d)); const q = query.trim().toLowerCase(); if (!q || q === "*" || q === "all") { const byNs = new Map(); for (const d of api) { const { ns, method } = apiPath(d.name); byNs.set(ns, [...(byNs.get(ns) ?? []), method]); } return `All methods (search again with words for signatures):\n${[...byNs].map(([ns, ms]) => `- peppa.${ns}: ${ms.join(", ")}`).join("\n")}\nAny tool can also be called as peppa.call("", args).`; } const words = q.split(/[^\p{L}\p{N}_.]+/u).filter(Boolean); const scored = api .map((d) => { const { ns, method } = apiPath(d.name); const path = `${ns}.${method} ${d.name}`.toLowerCase(); const text = d.description.toLowerCase(); let score = 0; for (const w of words) score += (path.includes(w) ? 3 : 0) + (text.includes(w) ? 1 : 0); return { d, score }; }) .filter((x) => x.score > 0) .sort((a, b) => b.score - a.score) .slice(0, limit); if (!scored.length) return `No methods match «${query}». Try other words, or search "*" to list every namespace.`; return scored.map(({ d }) => `${signature(d)}\n // ${firstSentence(d.description)}`).join("\n\n"); } // ---------- sandbox ---------- let quick: Promise | null = null; const module_ = () => (quick ??= getQuickJS()); export interface SandboxResult { ok: boolean; /** The returned value (strings as is, else JSON) with console output, or the error text. */ text: string; calls: string[]; ms: number; } const errorText = (v: unknown): string => { if (v && typeof v === "object") { const o = v as { name?: unknown; message?: unknown }; if (typeof o.message === "string") return o.name && o.name !== "Error" ? `${String(o.name)}: ${o.message}` : o.message; } return typeof v === "string" ? v : JSON.stringify(v); }; /** * Runs `code` (the body of an async function; `return` the result) with `peppa` bound to `call`. * `spec` is `{ns: {method: toolName}}`; `call(tool, args)` runs the tool as the caller. */ export async function runSandbox(code: string, spec: Record>, call: (tool: string, args: unknown) => Promise, limits: Partial = {}): Promise { const lim = { ...LIMITS, ...limits }; const started = Date.now(); const calls: string[] = []; const logs: string[] = []; let logChars = 0; const fail = (text: string): SandboxResult => ({ ok: false, text, calls, ms: Date.now() - started }); const QJS = await module_(); const rt = QJS.newRuntime(); rt.setMemoryLimit(lim.memoryBytes); rt.setMaxStackSize(lim.stackBytes); const deadline = started + lim.timeoutMs; rt.setInterruptHandler(() => Date.now() > deadline); const ctx: QuickJSContext = rt.newContext(); const pending = new Set(); let alive = true; let timer: ReturnType | undefined; let aborted = false; const pump = () => { if (!alive) return; const r = rt.executePendingJobs(); if (r.error) r.error.dispose(); }; try { const hostCall = ctx.newFunction("__call", (toolH, argsH) => { const tool = ctx.getString(toolH); const argsJson = ctx.getString(argsH); const p = ctx.newPromise(); pending.add(p); p.settled.then(() => { pending.delete(p); if (alive) { p.dispose(); pump(); } }); if (calls.length >= lim.maxCalls) { const e = ctx.newError(`Too many API calls in one script (max ${lim.maxCalls})`); p.reject(e); e.dispose(); return p.handle; } calls.push(tool); void (async () => { let text = ""; let err: string | null = null; try { text = await call(tool, JSON.parse(argsJson)); } catch (e) { err = e instanceof z.ZodError ? `Invalid arguments: ${e.issues.map((i) => `${i.path.join(".") || "(args)"}: ${i.message}`).join("; ")}` : e instanceof PeppaError ? e.message : `Internal error: ${(e as Error).message}`; } if (!alive) return; const h = err === null ? ctx.newString(text) : ctx.newError(err); if (err === null) p.resolve(h); else p.reject(h); h.dispose(); })(); return p.handle; }); ctx.setProp(ctx.global, "__call", hostCall); hostCall.dispose(); const hostLog = ctx.newFunction("__log", (h) => { const s = ctx.getString(h); if (logChars < lim.logChars) { logs.push(s.slice(0, lim.logChars - logChars)); logChars += s.length; } }); ctx.setProp(ctx.global, "__log", hostLog); hostLog.dispose(); const src = `(() => { const __c = __call, __l = __log; delete globalThis.__call; delete globalThis.__log; const __spec = ${JSON.stringify(spec)}; const peppa = { call: (name, args) => __c(String(name), JSON.stringify(args ?? {})) }; for (const ns of Object.keys(__spec)) { peppa[ns] = {}; for (const m of Object.keys(__spec[ns])) peppa[ns][m] = (args) => __c(__spec[ns][m], JSON.stringify(args ?? {})); } const __fmt = (v) => typeof v === "string" ? v : (() => { try { return JSON.stringify(v) } catch { return String(v) } })(); const console = { log: (...a) => __l(a.map(__fmt).join(" ")), error: (...a) => __l(a.map(__fmt).join(" ")), warn: (...a) => __l(a.map(__fmt).join(" ")) }; return (async () => { ${code} })().then((v) => v === undefined ? "" : typeof v === "string" ? v : JSON.stringify(v, null, 1)); })()`; const evaled = ctx.evalCode(src, "execute.js"); if (evaled.error) { const e = ctx.dump(evaled.error); evaled.error.dispose(); return fail(`Script error: ${errorText(e)}`); } const settled = ctx.resolvePromise(evaled.value); evaled.value.dispose(); pump(); const timeout = new Promise((_, rej) => { timer = setTimeout(() => rej(new Error("time")), Math.max(1, deadline - Date.now())); }); const res = await Promise.race([settled, timeout]); if (res.error) { const e = ctx.dump(res.error); res.error.dispose(); const msg = errorText(e); return fail(/interrupted/i.test(msg) ? `Time limit exceeded (${lim.timeoutMs / 1000} s)` : /out of memory/i.test(msg) ? "Memory limit exceeded" : `Script error: ${msg}`); } let text = ctx.getString(res.value); res.value.dispose(); if (text.length > lim.outputChars) text = `${text.slice(0, lim.outputChars)}\n…[truncated, ${text.length - lim.outputChars} more characters — return less]`; const out = logs.length ? `${text}${text ? "\n\n" : ""}console:\n${logs.join("\n")}` : text; return { ok: true, text: out, calls, ms: Date.now() - started }; } catch (e) { aborted = true; return fail((e as Error).message === "time" ? `Time limit exceeded (${lim.timeoutMs / 1000} s)` : `Script error: ${(e as Error).message}`); } finally { if (timer) clearTimeout(timer); alive = false; try { for (const p of pending) p.dispose(); ctx.dispose(); rt.dispose(); } catch { // A runtime that could not be disposed cleanly may have poisoned the shared wasm module: start a fresh one. quick = newQuickJSWASMModule(); } void aborted; } } // ---------- wiring into an MCP server ---------- export interface ExecuteReport { ok: boolean; calls: string[]; ms: number; chars: number; error?: string; } export interface CodeModeOptions { mode?: McpMode; /** Tools that stay direct MCP tools in every mode (get_started; the agent's update_task …). */ direct: string[]; /** The tool's options for the SDK (readOnly annotation) are filled from `define`. */ /** Called after every `execute` — writes the journal event as the same actor. */ journal?: (r: ExecuteReport) => Promise | void; } type Result = { content: Array<{ type: "text"; text: string }>; isError?: boolean }; export const SEARCH_API_DESCRIPTION = "Find methods of the Peppa API (the `peppa` object used by `execute`). Returns short TypeScript signatures of the best matches; search \"*\" to list every namespace."; export const EXECUTE_DESCRIPTION = "Run a short JavaScript script (body of an async function — use `return`) that calls the Peppa API through the `peppa` object, e.g. `const t = await peppa.tasks.list({project:\"PEP\", status:\"review\"}); return t;`. Find methods with search_api first. Methods return text; errors throw. No files, network or process; 10 s, 64 KB. Returns the returned value (strings as is, others as JSON) plus console.log lines."; export function createCodeMode(server: McpServer, opts: CodeModeOptions) { const mode = opts.mode ?? mcpMode(); const defs: ToolDef[] = []; const define: Define = (name, description, schema, readOnly, run) => { defs.push({ name, description, shape: schema, readOnly, run: run as ToolDef["run"] }); if (mode === "code" && !opts.direct.includes(name)) return; server.registerTool(name, { description, inputSchema: schema, annotations: { readOnlyHint: readOnly, openWorldHint: false } }, (async (a: z.infer>): Promise => { try { return { content: [{ type: "text", text: await run(a) }] }; } catch (e) { return { content: [{ type: "text", text: e instanceof PeppaError ? e.message : `Internal error: ${(e as Error).message}` }], isError: true }; } }) as never); }; /** The `{ns: {method: tool}}` map and the lookup the sandbox calls through. */ const api = () => { const list = defs.filter((d) => !isAlias(d)); const spec: Record> = {}; for (const d of list) { const { ns, method } = apiPath(d.name); spec[ns] ??= {}; spec[ns]![method] ??= d.name; } return { spec, byName: new Map(defs.map((d) => [d.name, d])) }; }; /** Registers `search_api` and `execute` (unless the mode is `tools`). Call after every `define`. */ function finish() { if (mode === "tools") return; server.registerTool("search_api", { description: SEARCH_API_DESCRIPTION, inputSchema: { query: z.string().describe("Words about what you need, e.g. «tasks move» or «monitors»; \"*\" lists everything") }, annotations: { readOnlyHint: true, openWorldHint: false } }, (async ({ query }: { query: string }): Promise => ({ content: [{ type: "text", text: searchApi(defs, query) }] })) as never); server.registerTool("execute", { description: EXECUTE_DESCRIPTION, inputSchema: { code: z.string().min(1).max(20_000).describe("Async function body; `return` the result") }, annotations: { readOnlyHint: false, openWorldHint: false } }, (async ({ code }: { code: string }): Promise => { const r = await execute(code); return { content: [{ type: "text", text: r.text }], isError: !r.ok }; }) as never); } async function execute(code: string): Promise { const { spec, byName } = api(); const r = await runSandbox(code, spec, async (tool, args) => { const d = byName.get(tool); if (!d) throw new PeppaError(`Unknown method ${tool}. Use search_api.`); return d.run(z.object(d.shape).parse(args ?? {}) as never); }); try { await opts.journal?.({ ok: r.ok, calls: r.calls, ms: r.ms, chars: r.text.length, error: r.ok ? undefined : r.text.slice(0, 300) }); } catch { // The journal must never break the script's answer. } return r; } return { define, finish, execute, defs: () => defs, mode }; } /** The journal event of one script (`mcp_execute`), written in the platform project as the current actor. */ export function executeJournal(db: Db, sessionId?: number | null): (r: ExecuteReport) => Promise { return async (r) => { const p = await getProject(db, platformProjectKey()).catch(() => null); if (p) await logEvent(db, { projectId: p.id, sessionId: sessionId ?? null, type: "mcp_execute", payload: r }); }; }