/** * Cotton MCP on the personal object: JSON-RPC over POST at /mcp, answered the * way the Rust server answered at /v1/mcp (crates/cotton-server/src/mcp/server.rs) * so the hooks and scripts work unchanged except for URL and token: * * - POST only, always `application/json`, never SSE, whatever Accept says; GET * is a 405. No `initialize` and no session id are needed: the callers send a * bare `tools/call` with id 1. * - Batches answer arrays; a notification runs and answers nothing, and a * request of only notifications is a 202. * - A tool's answer travels as compact JSON text in `content[0].text`; a * refusal is the sentence itself with `isError: true`. * * The tools are data (catalogue.json, generated from the Rust by * `pnpm rules:catalogue`: crates/cotton-tools/src/mcp/object_catalogue.rs); * a handler answers each by name. Scopes are checked here, before * a handler reads a row: the token's words, a lane's one write, the owner's dev tools. */ import { devWorker } from "../env.ts"; import { outwardRefusal, outwardTool, toolOpen } from "../key_allow.ts"; import { readsMemory } from "../memory_lock.ts"; import { readsTables } from "../open_tables_lock.ts"; import { ACTS, actLines } from "../acts.ts"; import { isGoneAct } from "../retired.ts"; import catalogue from "./catalogue.json"; import { withOpenProjects } from "./tools/window.ts"; import { OUTSIDE_RULE } from "./outside.ts"; import { changeIds, Content, fail, ToolFailure, type ChangeTrail, type Data, type Handler, type McpCaller, type Sibling, type ToolContext } from "./context.ts"; export interface CatalogueTool { name: string; title: string; description: string; scope: string; inputSchema: Data; annotations: Data; } /** run_act lists and admits the acts the object's dispatch has (src/acts.ts), never a copy of them. */ function withActs(tool: CatalogueTool): CatalogueTool { if (tool.name !== "run_act") return tool; const schema = structuredClone(tool.inputSchema) as Data & { properties: Record }; // A retired app's act is never offered (TABLE DROP 1): a call to one still meets its refusal. schema.properties.act = { ...schema.properties.act, enum: Object.keys(ACTS).filter((act) => !isGoneAct(act)) }; const lines = actLines((act) => !isGoneAct(act)); return { ...tool, description: `${tool.description}\n${lines}`, inputSchema: schema }; } const TOOLS = (catalogue.tools as CatalogueTool[]).map(withActs); /** The one write a lane token may make: its session log (crates/cotton-tools/src/mcp/lane_scope.rs). */ const LANE_WRITE_DOORS = new Set(["log_session"]); const LIMIT_REFUSAL = "limit must be a number — this tool pages, and the page size is how many rows come back in one call."; type Rpc = { jsonrpc: "2.0"; id: string | number | null; result?: unknown; error?: { code: number; message: string } }; export function mcpJson(value: unknown, status = 200, headers: Record = {}): Response { return new Response(JSON.stringify(value), { status, headers: { "content-type": "application/json", "cache-control": "no-store", ...headers } }); } /** Whether this Worker serves the `dev_` tools at all: the dev Worker and the tests only. */ export function devToolsHere(env: { ENV_LABEL?: string }): boolean { return devWorker(env); } export function unauthorized(error: string): Response { return mcpJson({ error, code: "unauthorized" }, 401); } /** * Does this token's scope admit the tool? Owner holds everything but a `dev_` tool off dev; a lane reads and writes its * session log. A `dev_` tool (dev_reveal_secret opens any saved password with the server's vault key, under no window) * is refused to every token on a Worker that is not dev or test (ROUTES-AUDIT 4, 23 Nov 2026), the owner scope too, * which every assistant connected through OAuth holds. */ export function grants(caller: McpCaller, tool: CatalogueTool, devTools = false): boolean { if (tool.name.startsWith("dev_") && !devTools) return false; // ADMIN KEYS 2: a key that carries its list is shown and may call only what the list opens (src/key_allow.ts). if (!toolOpen(caller.allow ?? null, tool.name, tool.scope)) return false; if (caller.scopes.has("owner")) return true; if (tool.name.startsWith("dev_")) return false; if (caller.lane) return caller.scopes.has("read") && (tool.scope === "read" || LANE_WRITE_DOORS.has(tool.name)); const held = (word: string) => caller.scopes.has(word) || (caller.scopes.has("coordinator") && (word === "read" || word === "write" || word === "machines")); if (tool.scope === "machines") return held("machines") && held("write"); return held(tool.scope); } /** * `database` is the wrapper's argument, never a tool's: taken off before the * handler, it names this database (its id, its name, or "personal") or one of * the owner's other databases this endpoint reaches (a sibling, by id or * name), where the call then runs. Anything else is database_mismatch. */ function strip(ctx: ToolContext, args: Data): { args: Data; sibling: Sibling | null } { const out: Data = { ...args }; let sibling: Sibling | null = null; for (const key of ["database", "toDatabase", "fromDatabase", "todoDatabase"]) { if (!(key in out)) continue; const v = out[key]; delete out[key]; if (v === null || v === undefined) continue; if (typeof v !== "string") fail("database must be the id or name of a database, as a string"); const named = v.trim().toLowerCase(); if (named === ctx.database.id.toLowerCase() || named === ctx.database.name.toLowerCase() || named === "personal") continue; const other = ctx.siblings.find((s) => s.id.toLowerCase() === named || s.name.toLowerCase() === named); if (!other || key !== "database") fail("database_mismatch", { code: "database_mismatch" }); sibling = other; } return { args: out, sibling }; } /** The most JSON-RPC messages one batch may hold (AUDIT C 5); a client sends one at a time in practice. */ export const MAX_BATCH = 20; export class McpServer { private readonly handlers: Record; constructor(handlers: Record) { this.handlers = handlers; } async answer(request: Request, ctx: () => ToolContext): Promise { if (request.method !== "POST") return mcpJson({ error: "send JSON-RPC over POST; there is no SSE stream", code: "method_not_allowed" }, 405, { allow: "POST" }); let body: unknown; try { body = JSON.parse(await request.text()); } catch { return mcpJson({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "request body is not valid JSON" } }); } const context = ctx(); if (Array.isArray(body)) { if (!body.length) return mcpJson({ jsonrpc: "2.0", id: null, error: { code: -32600, message: "empty batch" } }); // AUDIT C 5: one request is never a flood (a thousand deletes then an empty_bin): a batch holds at most this many. if (body.length > MAX_BATCH) return mcpJson({ jsonrpc: "2.0", id: null, error: { code: -32600, message: `a batch holds at most ${MAX_BATCH} messages; this one has ${body.length}` } }); const answers: Rpc[] = []; for (const message of body) { const answer = await this.one(context, message); if (answer) answers.push(answer); } return answers.length ? mcpJson(answers) : new Response(null, { status: 202 }); } const answer = await this.one(context, body); return answer ? mcpJson(answer) : new Response(null, { status: 202 }); } private async one(ctx: ToolContext, message: unknown): Promise { if (message === null || typeof message !== "object" || Array.isArray(message)) return { jsonrpc: "2.0", id: null, error: { code: -32600, message: "request must be a JSON object" } }; const m = message as Data; const notification = !("id" in m); const id = m.id; if (m.jsonrpc !== "2.0") return { jsonrpc: "2.0", id: null, error: { code: -32600, message: 'jsonrpc must be "2.0"' } }; if (!notification && id !== null && typeof id !== "string" && typeof id !== "number") return { jsonrpc: "2.0", id: null, error: { code: -32600, message: "id must be a string, number or null" } }; if (m.params !== undefined && (m.params === null || typeof m.params !== "object" || Array.isArray(m.params))) return { jsonrpc: "2.0", id: null, error: { code: -32600, message: "params must be an object" } }; if (typeof m.method !== "string") return { jsonrpc: "2.0", id: null, error: { code: -32600, message: "method is required" } }; const params = (m.params as Data | undefined) ?? {}; const rid = (notification ? null : id) as string | number | null; let answer: Rpc; try { answer = { jsonrpc: "2.0", id: rid, result: await this.method(ctx, m.method, params) }; } catch (error) { if (error instanceof RpcError) answer = { jsonrpc: "2.0", id: rid, error: { code: error.code, message: error.message } }; else throw error; } return notification ? null : answer; } private async method(ctx: ToolContext, method: string, params: Data): Promise { switch (method) { case "initialize": return { protocolVersion: catalogue.protocolVersion, capabilities: { tools: { listChanged: false }, prompts: { listChanged: false } }, serverInfo: catalogue.serverInfo, // AUDIT C 4: the kernel, then what an "outside" mark means (src/mcp/outside.ts). instructions: `${JSON.stringify({ database: { id: ctx.database.id, name: ctx.database.name }, app: "Cotton" })}\n${ctx.caller.scopes.has("read") || ctx.caller.scopes.has("owner") || ctx.caller.scopes.has("coordinator") ? catalogue.kernel : catalogue.staticKernel}\n${OUTSIDE_RULE}`, }; case "ping": return {}; case "tools/list": return { tools: TOOLS.filter((t) => this.handlers[t.name] && grants(ctx.caller, t, devToolsHere(ctx.env))).map((t) => ({ name: t.name, title: t.title, description: t.description, inputSchema: t.inputSchema, annotations: t.annotations })) }; case "prompts/list": return { prompts: [] }; case "tools/call": { if (typeof params.name !== "string") throw new RpcError(-32602, "name is required"); const args = params.arguments && typeof params.arguments === "object" && !Array.isArray(params.arguments) ? (params.arguments as Data) : {}; return this.call(ctx, params.name, args); } default: throw new RpcError(-32601, `unsupported method ${JSON.stringify(method)}`); } } /** One tool call, admitted in the Rust order: known, scope, limit, then the handler. */ async call(ctx: ToolContext, name: string, raw: Data): Promise { try { const tool = TOOLS.find((t) => t.name === name); if (!tool) fail(`unknown tool ${JSON.stringify(name)}`); const { args, sibling } = strip(ctx, raw); // Another database's call runs whole in its own object — scope and handler — as this same caller. if (sibling) { if (ctx.caller.allow) fail("this key reads and writes this database alone: its list names none of the owner's other databases", { code: "key_allow" }); return await ctx.forward(sibling, name, args); } if (!grants(ctx.caller, tool, devToolsHere(ctx.env))) { if (!toolOpen(ctx.caller.allow ?? null, name, tool.scope)) fail(`\`${name}\` is not open to this key: the owner widens what it may do from the phone`, { code: "key_allow" }); if (name.startsWith("dev_") && !devToolsHere(ctx.env)) fail(`\`${name}\` is not served here: it is a development tool.`); if (ctx.caller.lane && tool.scope !== "read") fail(`this is lane ${ctx.caller.lane}'s token: it reads, and writes only its session log — \`${name}\` is not log_session`); if (name.startsWith("dev_")) fail(`\`${name}\` is an owner-scope tool: the owner's app may call it; an assistant may not.`); fail(`this token does not have "${tool.scope}" access. Ask the owner to reconnect with ${tool.scope} enabled.`); } // ADMIN KEYS 4: outward is decided in one place (key_allow outwardTool), by what this call does, before it runs. const away = outwardRefusal(ctx.caller.allow ?? null, outwardTool(name, args), `\`${name}\``); if (away) fail(away, { code: "key_allow" }); const handler = this.handlers[name]; if (!handler) fail(`${name} is not implemented on this server yet`); if (typeof args.limit === "string") fail(LIMIT_REFUSAL); ctx.trail.tool = name; ctx.trail.ids.length = 0; if (ctx.memoryRead && readsMemory(name, args)) ctx.memoryRead(); if (ctx.tablesRead && readsTables(name, args)) ctx.tablesRead(); // OPEN TABLES: a sealed project table reads opened for the tools that read it (tools/window.ts). const opened = await withOpenProjects(ctx, name); const answer = await handler(opened, args); // A call a window answered is written where the owner sees it: which tables, how many rows. if (ctx.window.handed.length) ctx.window.log(ctx.window.handed.splice(0), name, rowsAnswered(answer), /^(create|update)_/.test(name)); if (answer instanceof Content) return { content: answer.blocks, isError: false }; return { content: [{ type: "text", text: JSON.stringify(stamped(answer, ctx.trail)) }], isError: false }; } catch (error) { if (error instanceof ToolFailure) { const out: Data = { content: [{ type: "text", text: error.message }], isError: true }; if (error.structured) out.structuredContent = error.structured; return out; } if (error instanceof Error && "code" in error && "status" in error) { // An engine refusal (bad link, missing required column, a change written over since) reads as the tool's sentence, its code beside it. return { content: [{ type: "text", text: error.message }], isError: true, structuredContent: { code: error.code } }; } // A read that fails for any other reason (SQLite out of room or time on a big object) answers a plain refusal, // never a 500 (coordinator, 23 Nov 2026: storage_summary answered 500 twice on his 4.2 GB object). A write's // failure still rolls back and answers as it did. const scoped = TOOLS.find((t) => t.name === name); if (scoped?.scope === "read") { console.error(`cottondb: ${name} failed: ${error instanceof Error ? error.stack ?? error.message : String(error)}`); return { content: [{ type: "text", text: `${name} could not finish on this database just now. Ask again in a moment, or ask for less (one table, a shorter period, a smaller limit).` }], isError: true, structuredContent: { code: "read_failed" } }; } throw error; } } } /** A write's answer carries its change: `change_id` to undo it by, `undoable`; an answer that names its own is left as it is. */ function stamped(answer: unknown, trail: ChangeTrail): unknown { if (!trail.ids.length || answer === null || typeof answer !== "object" || Array.isArray(answer) || "change_id" in answer) return answer; return { ...(answer as Data), ...changeIds(trail) }; } class RpcError extends Error { readonly code: number; constructor(code: number, message: string) { super(message); this.code = code; } } /** How many rows an answer carries, for the window's log: its records, hits, changes or suggestions, else the one record. */ function rowsAnswered(answer: unknown): number { if (!answer || typeof answer !== "object" || answer instanceof Content) return 1; const a = answer as Data; for (const key of ["records", "hits", "changes", "suggestions", "rows"]) if (Array.isArray(a[key])) return (a[key] as unknown[]).length; return 1; }