|
| 1 | +/** |
| 2 | + * A reference MCP server that honours StateGuard idempotency keys, built on the |
| 3 | + * TypeScript MCP SDK (1.32.1, `McpServer`) with this adapter. It mirrors the |
| 4 | + * Python reference (examples/mcp/keyed_reference_server.py). |
| 5 | + * |
| 6 | + * node examples/keyed_reference_server.ts --db orders.db --ledger ledger.txt \ |
| 7 | + * [--payments http://127.0.0.1:PORT] [--outbox outbox.txt] |
| 8 | + * |
| 9 | + * Tools: |
| 10 | + * create_order(item, qty) mutating, transactional: the order row and its key's record commit |
| 11 | + * in one SQLite transaction (the store's database). |
| 12 | + * append_ledger(entry) mutating, two-phase, with recovery: appends `entry<TAB>key` in one |
| 13 | + * fsync'd write; a torn last line is cut at startup (exclusive store); |
| 14 | + * the recovery check looks for this key's own line. |
| 15 | + * charge(account, amount) mutating, two-phase; the downstream payment service (--payments) |
| 16 | + * dedupes by the key the call sends (native idempotency), and the |
| 17 | + * recovery check asks it, by key, what it recorded. |
| 18 | + * send_notice(to) mutating, two-phase, an external effect with NO key and NO check: |
| 19 | + * appends to --outbox. A crash after the append leaves it in doubt. |
| 20 | + * read_ledger() read-only. |
| 21 | + * |
| 22 | + * Every call without a key is an ordinary MCP tool call. |
| 23 | + * |
| 24 | + * TEST-ONLY faults (--fault POINT --fault-file F): SIGKILL once per F at POINT |
| 25 | + * on the first keyed call of a mutating tool that reaches it (in-handler points |
| 26 | + * also fire for unkeyed calls): before_begin, after_begin, mid_effect (ledger: |
| 27 | + * half a line), after_effect, after_record, hang_after_record (never answers). |
| 28 | + * --no-advertise keys nothing; --no-recover keeps abandoned keys in doubt. |
| 29 | + */ |
| 30 | + |
| 31 | +import { closeSync, existsSync, fsyncSync, openSync, readFileSync, truncateSync, writeSync, writeFileSync } from "node:fs"; |
| 32 | +import type { DatabaseSync } from "node:sqlite"; |
| 33 | +import { parseArgs } from "node:util"; |
| 34 | + |
| 35 | +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; |
| 36 | +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; |
| 37 | +import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; |
| 38 | +import { z } from "zod"; |
| 39 | + |
| 40 | +import { IdempotencyStore, KeyedTools, NotExecuted, Recovery, currentKey } from "../src/index.ts"; |
| 41 | +import type { KeyedPoint } from "../src/index.ts"; |
| 42 | + |
| 43 | +const { values: args } = parseArgs({ |
| 44 | + options: { |
| 45 | + db: { type: "string" }, |
| 46 | + ledger: { type: "string" }, |
| 47 | + payments: { type: "string" }, |
| 48 | + outbox: { type: "string" }, |
| 49 | + scope: { type: "string", default: "keyed-reference" }, |
| 50 | + "no-advertise": { type: "boolean", default: false }, |
| 51 | + "no-recover": { type: "boolean", default: false }, |
| 52 | + fault: { type: "string" }, |
| 53 | + "fault-file": { type: "string" }, |
| 54 | + "effect-delay": { type: "string", default: "0" }, |
| 55 | + }, |
| 56 | +}); |
| 57 | +if (args.db === undefined || args.ledger === undefined) throw new Error("--db and --ledger are required"); |
| 58 | +const ledger = args.ledger; |
| 59 | +const outbox = args.outbox; |
| 60 | +const effectDelay = Number(args["effect-delay"]) * 1000; |
| 61 | +const MUTATING = new Set(["create_order", "append_ledger", "charge", "send_notice"]); |
| 62 | + |
| 63 | +function hits(point: string): boolean { |
| 64 | + const flag = args["fault-file"]; |
| 65 | + if (args.fault !== point || flag === undefined || existsSync(flag)) return false; |
| 66 | + writeFileSync(flag, point); |
| 67 | + return true; |
| 68 | +} |
| 69 | + |
| 70 | +async function crash(point: string): Promise<void> { |
| 71 | + if (!hits(point)) return; |
| 72 | + if (point === "hang_after_record") await new Promise<never>(() => {}); |
| 73 | + process.kill(process.pid, "SIGKILL"); |
| 74 | +} |
| 75 | + |
| 76 | +const sleep = (ms: number) => new Promise((done) => setTimeout(done, ms)); |
| 77 | +const text = (payload: unknown): CallToolResult => ({ content: [{ type: "text", text: JSON.stringify(payload) }] }); |
| 78 | + |
| 79 | +const recovering = !args["no-recover"]; |
| 80 | +const store = new IdempotencyStore(args.db, { scope: args.scope, exclusive: recovering }); |
| 81 | +if (recovering && existsSync(ledger)) { |
| 82 | + // Holding the lock: no other process is appending. A torn last line was never an entry. |
| 83 | + const data = readFileSync(ledger); |
| 84 | + const keep = data.lastIndexOf(0x0a) + 1; |
| 85 | + if (keep !== data.length) { |
| 86 | + truncateSync(ledger, keep); |
| 87 | + process.stderr.write(`keyed-reference: cut a torn ledger line (${data.length - keep} bytes)\n`); |
| 88 | + } |
| 89 | +} |
| 90 | +{ |
| 91 | + const db = store.connect(); |
| 92 | + db.exec("CREATE TABLE IF NOT EXISTS orders (id INTEGER PRIMARY KEY, item TEXT, qty INT)"); |
| 93 | + db.close(); |
| 94 | +} |
| 95 | + |
| 96 | +function insertOrder(db: DatabaseSync, input: Record<string, unknown>): CallToolResult { |
| 97 | + if (hits("after_begin")) process.kill(process.pid, "SIGKILL"); |
| 98 | + const qty = input["qty"]; |
| 99 | + if (typeof qty !== "number" || !Number.isInteger(qty) || qty <= 0) throw new Error("qty must be a positive integer"); |
| 100 | + const run = db.prepare("INSERT INTO orders (item, qty) VALUES (?, ?)").run(String(input["item"]), qty); |
| 101 | + if (hits("mid_effect") || hits("after_effect")) process.kill(process.pid, "SIGKILL"); |
| 102 | + return text({ order_id: Number(run.lastInsertRowid), item: input["item"] }); |
| 103 | +} |
| 104 | + |
| 105 | +function appendLine(path: string, line: string, tornAt?: number): void { |
| 106 | + const fd = openSync(path, "a"); |
| 107 | + try { |
| 108 | + const bytes = Buffer.from(line, "utf8"); |
| 109 | + writeSync(fd, tornAt === undefined ? bytes : bytes.subarray(0, tornAt)); |
| 110 | + fsyncSync(fd); |
| 111 | + } finally { |
| 112 | + closeSync(fd); |
| 113 | + } |
| 114 | +} |
| 115 | + |
| 116 | +function ledgerHasKey(key: string, input: Record<string, unknown>): Recovery { |
| 117 | + // Exact: this key's own line. A crash's torn line was cut at startup; one now means |
| 118 | + // an append in this process failed part-way, and an append can't be ruled out. |
| 119 | + const lines = (existsSync(ledger) ? readFileSync(ledger, "utf8") : "").split("\n"); |
| 120 | + if (lines.at(-1)) return Recovery.unknown("the ledger ends in a torn line"); |
| 121 | + if (lines.slice(0, -1).includes(`${String(input["entry"])}\t${key}`)) { |
| 122 | + return Recovery.found(text({ appended: input["entry"] })); |
| 123 | + } |
| 124 | + return Recovery.absent(); |
| 125 | +} |
| 126 | + |
| 127 | +async function payments(path: string, init?: RequestInit): Promise<Response> { |
| 128 | + if (args.payments === undefined) throw new Error("--payments is not configured"); |
| 129 | + return fetch(`${args.payments}${path}`, init); |
| 130 | +} |
| 131 | + |
| 132 | +async function chargeHasKey(key: string): Promise<Recovery> { |
| 133 | + // The downstream honours the key itself: ask it what it recorded for this key. |
| 134 | + const response = await payments(`/payments/${encodeURIComponent(key)}`); |
| 135 | + if (response.status === 404) return Recovery.absent(); |
| 136 | + if (!response.ok) return Recovery.unknown(`payment service answered ${response.status}`); |
| 137 | + const { receipt } = (await response.json()) as { receipt: string }; |
| 138 | + return Recovery.found(text({ receipt })); |
| 139 | +} |
| 140 | + |
| 141 | +const keyed = new KeyedTools(store, { |
| 142 | + onPoint: async (point: KeyedPoint, tool: string) => { |
| 143 | + if (!MUTATING.has(tool)) return; |
| 144 | + if (point === "before_begin" || point === "after_record") await crash(point); |
| 145 | + if (point === "after_record") await crash("hang_after_record"); |
| 146 | + }, |
| 147 | +}); |
| 148 | +if (!args["no-advertise"]) { |
| 149 | + keyed.transactional("create_order", insertOrder); |
| 150 | + keyed.twoPhase("append_ledger", recovering ? { recover: ledgerHasKey } : {}); |
| 151 | + keyed.twoPhase("charge", recovering ? { recover: (key) => chargeHasKey(key) } : {}); |
| 152 | + keyed.twoPhase("send_notice"); // no key on the effect, no check: in doubt after a crash |
| 153 | +} |
| 154 | + |
| 155 | +const mcp = new McpServer({ name: "keyed-reference-ts", version: "0.1.0" }); |
| 156 | +keyed.install(mcp.server); |
| 157 | + |
| 158 | +mcp.registerTool( |
| 159 | + "create_order", |
| 160 | + { description: "Create an order.", inputSchema: { item: z.string(), qty: z.number() } }, |
| 161 | + async (input) => { |
| 162 | + const db = store.connect(); // reached without a key: an ordinary call |
| 163 | + try { |
| 164 | + return insertOrder(db, input); |
| 165 | + } finally { |
| 166 | + db.close(); |
| 167 | + } |
| 168 | + }, |
| 169 | +); |
| 170 | + |
| 171 | +mcp.registerTool( |
| 172 | + "append_ledger", |
| 173 | + { description: "Append an entry to the ledger.", inputSchema: { entry: z.string() } }, |
| 174 | + async ({ entry }) => { |
| 175 | + if (!entry || entry.includes("\n") || entry.includes("\t")) throw new NotExecuted("entry must be one line without tabs"); |
| 176 | + await crash("after_begin"); |
| 177 | + const key = currentKey(); |
| 178 | + const line = `${key ? `${entry}\t${key}` : entry}\n`; |
| 179 | + if (effectDelay) await sleep(effectDelay); |
| 180 | + if (hits("mid_effect")) { |
| 181 | + appendLine(ledger, line, Math.floor(Buffer.byteLength(line) / 2)); |
| 182 | + process.kill(process.pid, "SIGKILL"); |
| 183 | + } |
| 184 | + appendLine(ledger, line); |
| 185 | + await crash("after_effect"); |
| 186 | + return text({ appended: entry }); |
| 187 | + }, |
| 188 | +); |
| 189 | + |
| 190 | +mcp.registerTool( |
| 191 | + "charge", |
| 192 | + { description: "Charge an account (downstream payment service).", inputSchema: { account: z.string(), amount: z.number() } }, |
| 193 | + async ({ account, amount }) => { |
| 194 | + await crash("after_begin"); |
| 195 | + const key = currentKey() ?? `unkeyed-${crypto.randomUUID()}`; |
| 196 | + const response = await payments("/payments", { |
| 197 | + method: "POST", |
| 198 | + headers: { "content-type": "application/json", "idempotency-key": key }, |
| 199 | + body: JSON.stringify({ account, amount }), |
| 200 | + }); |
| 201 | + const { receipt } = (await response.json()) as { receipt: string }; |
| 202 | + await crash("after_effect"); |
| 203 | + return text({ receipt }); |
| 204 | + }, |
| 205 | +); |
| 206 | + |
| 207 | +mcp.registerTool( |
| 208 | + "send_notice", |
| 209 | + { description: "Send a notice (an external effect with no idempotency).", inputSchema: { to: z.string() } }, |
| 210 | + async ({ to }) => { |
| 211 | + if (outbox === undefined) throw new Error("--outbox is not configured"); |
| 212 | + await crash("after_begin"); |
| 213 | + appendLine(outbox, `${to}\n`); |
| 214 | + await crash("after_effect"); |
| 215 | + return text({ sent: to }); |
| 216 | + }, |
| 217 | +); |
| 218 | + |
| 219 | +mcp.registerTool( |
| 220 | + "read_ledger", |
| 221 | + { description: "Read the ledger.", inputSchema: {}, annotations: { readOnlyHint: true } }, |
| 222 | + async () => { |
| 223 | + const lines = (existsSync(ledger) ? readFileSync(ledger, "utf8") : "").split("\n").filter(Boolean); |
| 224 | + return text({ lines: lines.map((line) => line.split("\t")[0]) }); |
| 225 | + }, |
| 226 | +); |
| 227 | + |
| 228 | +await mcp.connect(new StdioServerTransport()); |
0 commit comments