apodictic-mcp-verifier 0.0.0-stage → 3.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,45 @@
1
- # Temporary Holding Version
1
+ # apodictic-mcp-verifier
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Drop-in Model Context Protocol (MCP) JSON-RPC 2.0 pre-commit verifier and stdio firewall for autonomous AI agents interacting with PostgreSQL, **Odoo 18–20 (`/json/2/` Bearer API & `/mcp`)**, Stripe, and enterprise ledgers.
4
+
5
+ ## 60-Second Reproducible Demo (Zero Setup, Zero Python Required)
6
+
7
+ Run three real scenarios against an in-memory **WASM PostgreSQL 17** (`@electric-sql/pglite`) instance and **Microsoft Z3 5.4.1** (uses bundled Z3 5.4.1 WebAssembly out of the box when Python `z3-solver` is absent, or runs remote via `--endpoint https://www.apodictic.dev/api/v1/enclave`):
8
+
9
+ ```bash
10
+ npx apodictic-mcp-verifier demo
11
+ ```
12
+
13
+ What you will see:
14
+ 1. **Legitimate financial write (`$12,500` disbursement)** → `SAT · ALLOWED` via Z3 5.4.1 (PostgreSQL balance updates `250,000 → 237,500`).
15
+ 2. **Schema-accurate Odoo 18–20 `account_move_line` debit update (`$4,820` debit vs `$4,500` paired credit)** → passes PostgreSQL's single-row `CHECK (debit * credit = 0)` inside a PGlite shadow transaction (`ROLLBACK`), then blocked by Z3 5.4.1 `INV_DOUBLE_ENTRY_BALANCE` (`$320.00` multi-row drift).
16
+ 3. **Attempted protected tax-record deletion (`DELETE FROM tax_chain`)** → `UNSAT · BLOCKED` by Z3 5.4.1 (`INV_REVERSIBILITY_GUARD`).
17
+
18
+ ## Wrap Any MCP Server (Postgres, Odoo 20 `/mcp`, Stripe)
19
+
20
+ ```bash
21
+ npx apodictic-mcp-verifier wrap -- <your-mcp-server-command> [args...]
22
+ ```
23
+
24
+ Or run as a standalone MCP verification server:
25
+
26
+ ```bash
27
+ npx apodictic-mcp-verifier serve
28
+ ```
29
+
30
+ ## Open Developer Edition vs. Enterprise Edition
31
+
32
+ | Capability | Open Developer CLI / SDK (MIT) | Apodictic Enterprise (Paid Pilot / Annual) |
33
+ | :--- | :--- | :--- |
34
+ | Stdio MCP wrapping & 3-scenario PGlite + Z3 5.4.1 WASM demo | Included | Included |
35
+ | Stateless + local SQLite WAL Z3 5.4.1 verification (Zero Python) | Included | Included |
36
+ | Single-node PGlite WASM shadow execution (`BEGIN ... ROLLBACK`) | Included | Included |
37
+ | Odoo 19/20 `bearer_scope='mcp'`, `hard_lock_date` & `inalterable_hash` guard | Included | Included |
38
+ | `z3.Optimize()` counterfactual safe SQL patch synthesis & RFC 6962 proofs | Included | Included |
39
+ | Dual-solver SMT consensus (`libz3` + pure-Rust `OxiZ`) & Rust `pgwire` proxy | — | Included |
40
+ | Multi-cluster HA, PostgreSQL WAL locks & Odoo 18–20 `/doc-bearer/` live sync | — | Included |
41
+ | NIST SP 800-38G `AES-256-FF1` FPE & Cedar / Regorus / CEL engines | — | Included |
42
+ | Air-gapped Docker + Linux bare-metal KVM Firecracker MicroVM deployment | — | Included |
43
+ | SPIFFE SVIDs, C2SP `tlog-tiles` & Monthly CFO Financial Integrity Report | — | Included |
44
+
45
+ Growth Firewall from **$490/mo** (single-cluster) or **Enterprise Sovereign Enclave** ($2,500/mo / $30,000/yr, starting with a **$3,000–$5,000 30-Day Production Integrity Pilot**, 100% credited to annual): https://apodictic.dev/pricing · `sofianmousa@apodictic.dev`
@@ -0,0 +1,1005 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @apodictic/mcp-verifier
4
+ * Spec-compliant MCP JSON-RPC 2.0 firewall & standalone verification server.
5
+ *
6
+ * Modes:
7
+ * 1. `apodictic-mcp-verifier serve [--airgap] [--config <path>] [--endpoint <url>]`
8
+ * Standalone MCP stdio server exposing Z3 5.4.1 verification, 3-way match,
9
+ * indirect tax parity, atomic rollback, and WORM audit tools.
10
+ * 2. `apodictic-mcp-verifier wrap [--airgap] [--config <path>] -- <command> [args...]`
11
+ * Drop-in stateful firewall proxy in front of any MCP server (Postgres, Odoo, Stripe).
12
+ * 3. Single-shot stdin envelope check.
13
+ */
14
+ import { spawn } from 'node:child_process';
15
+ import crypto from 'node:crypto';
16
+ import fs from 'node:fs';
17
+ import os from 'node:os';
18
+ import path from 'node:path';
19
+ import readline from 'node:readline';
20
+
21
+ let SymbolicGateway, PGlite;
22
+ try {
23
+ ({ SymbolicGateway, PGlite } = await import('apodictic-sdk'));
24
+ } catch {
25
+ try {
26
+ ({ SymbolicGateway, PGlite } = await import('@apodictic/sdk'));
27
+ } catch {
28
+ ({ SymbolicGateway, PGlite } = await import('../../apodictic-sdk/src/index.mjs'));
29
+ }
30
+ }
31
+
32
+ const SUPPORTED_PROTOCOL_VERSIONS = ['2025-03-26', '2024-11-05'];
33
+
34
+ const BUILTIN_TOOLS = [
35
+ {
36
+ name: 'apodictic_verify_mutation',
37
+ description: 'Verify SQL or ERP mutation against Z3 5.4.1 solvency, cap, tax, and destructive-op invariants prior to commit.',
38
+ inputSchema: {
39
+ type: 'object',
40
+ properties: {
41
+ sql: { type: 'string', description: 'Proposed SQL or ERP mutation payload' },
42
+ accountId: { type: 'string', description: 'Ledger or entity identifier' },
43
+ amount: { type: 'number', description: 'Transaction amount in settlement currency' },
44
+ currentBalance: { type: 'number', description: 'Current ledger balance' },
45
+ minReserve: { type: 'number', description: 'Minimum liquidity reserve floor' },
46
+ maxAutonomousLimit: { type: 'number', description: 'Max autonomous spend without dual-custody sign-off' },
47
+ cfoSigned: { type: 'boolean', description: 'Whether dual-custody sign-off is attached' },
48
+ targetSystem: { type: 'string', enum: ['postgresql', 'odoo_v18', 'odoo_v19', 'odoo_v20', 'sap_s4hana', 'stripe'] },
49
+ odoo: { type: 'object', description: 'Optional Odoo 18-20 /json/2/ model, method, bearerScope, lock dates, or account.move.line rows' },
50
+ },
51
+ required: ['sql'],
52
+ },
53
+ },
54
+ {
55
+ name: 'apodictic_verify_three_way_match',
56
+ description: 'Verify Purchase Order <-> Goods Receipt <-> Vendor Invoice parity with Z3.',
57
+ inputSchema: {
58
+ type: 'object',
59
+ properties: {
60
+ po: {
61
+ type: 'object',
62
+ properties: {
63
+ poId: { type: 'string' },
64
+ sku: { type: 'string' },
65
+ orderedQty: { type: 'number' },
66
+ unitPrice: { type: 'number' },
67
+ },
68
+ required: ['poId', 'sku', 'orderedQty', 'unitPrice'],
69
+ },
70
+ receipts: {
71
+ type: 'array',
72
+ items: {
73
+ type: 'object',
74
+ properties: {
75
+ receiptId: { type: 'string' },
76
+ poId: { type: 'string' },
77
+ sku: { type: 'string' },
78
+ receivedQty: { type: 'number' },
79
+ },
80
+ required: ['receiptId', 'poId', 'sku', 'receivedQty'],
81
+ },
82
+ },
83
+ invoices: {
84
+ type: 'array',
85
+ items: {
86
+ type: 'object',
87
+ properties: {
88
+ invoiceId: { type: 'string' },
89
+ poId: { type: 'string' },
90
+ sku: { type: 'string' },
91
+ billedQty: { type: 'number' },
92
+ billedUnitPrice: { type: 'number' },
93
+ },
94
+ required: ['invoiceId', 'poId', 'sku', 'billedQty', 'billedUnitPrice'],
95
+ },
96
+ },
97
+ priceTolerancePct: { type: 'number', description: 'Allowed price drift fraction (default 0.02)' },
98
+ },
99
+ required: ['po', 'receipts', 'invoices'],
100
+ },
101
+ },
102
+ {
103
+ name: 'apodictic_verify_tax',
104
+ description: 'Verify Egypt ETA (14%) / KSA ZATCA (15%) / EU VAT statutory tax parity.',
105
+ inputSchema: {
106
+ type: 'object',
107
+ properties: {
108
+ jurisdiction: {
109
+ type: 'string',
110
+ enum: ['KSA_ZATCA', 'EGYPT_ETA', 'EU_VAT_DE', 'EU_REVERSE_CHARGE'],
111
+ },
112
+ lines: {
113
+ type: 'array',
114
+ items: {
115
+ type: 'object',
116
+ properties: {
117
+ sku: { type: 'string' },
118
+ netAmount: { type: 'number' },
119
+ claimedVatAmount: { type: 'number' },
120
+ claimedWhtAmount: { type: 'number' },
121
+ isExempt: { type: 'boolean' },
122
+ },
123
+ required: ['sku', 'netAmount', 'claimedVatAmount'],
124
+ },
125
+ },
126
+ hasCryptographicStamp: { type: 'boolean' },
127
+ tolerance: { type: 'number' },
128
+ },
129
+ required: ['jurisdiction', 'lines'],
130
+ },
131
+ },
132
+ {
133
+ name: 'apodictic_rollback',
134
+ description: 'Execute atomic <38ms local rollback for a staged batchId.',
135
+ inputSchema: {
136
+ type: 'object',
137
+ properties: { batchId: { type: 'string', description: 'Staged rollback batch identifier' } },
138
+ required: ['batchId'],
139
+ },
140
+ },
141
+ {
142
+ name: 'apodictic_audit_status',
143
+ description: 'Verify full 256-bit SHA-256 WORM Merkle audit chain integrity.',
144
+ inputSchema: {
145
+ type: 'object',
146
+ properties: {},
147
+ },
148
+ },
149
+ {
150
+ name: 'apodictic_evaluate_policy',
151
+ description: 'Evaluate declarative permit/forbid policies and transitive entity hierarchy DAGs via Z3 5.4.1 theorem proving.',
152
+ inputSchema: {
153
+ type: 'object',
154
+ properties: {
155
+ policyText: { type: 'string', description: 'Declarative permit/forbid policy text' },
156
+ action: { type: 'string', description: 'Action name (e.g. UPDATE, WIRE, DROP)' },
157
+ principal: { type: 'string', description: 'Entity principal e.g. User::"alice"' },
158
+ resource: { type: 'string', description: 'Target resource e.g. Account::"payout_hot"' },
159
+ entityHierarchy: { type: 'object', description: 'Map of entity -> parent group/pool arrays' },
160
+ amount: { type: 'number' },
161
+ currentBalance: { type: 'number' },
162
+ minReserve: { type: 'number' },
163
+ spendingLimit: { type: 'number' },
164
+ cfoSigned: { type: 'boolean' },
165
+ reversalArmed: { type: 'boolean' },
166
+ },
167
+ required: ['action'],
168
+ },
169
+ },
170
+ {
171
+ name: 'apodictic_merkle_proof',
172
+ description: 'Generate and cryptographically verify an O(log N) RFC 6962 binary Merkle tree inclusion proof for a WORM block.',
173
+ inputSchema: {
174
+ type: 'object',
175
+ properties: {
176
+ blockIndex: { type: 'number', description: '1-based WORM block index (defaults to latest block)' },
177
+ },
178
+ },
179
+ },
180
+ {
181
+ name: 'apodictic_flush_escrow',
182
+ description: 'Dispatch eligible staged 2-phase escrow holds (debits_pending -> debits_posted) to external rails.',
183
+ inputSchema: {
184
+ type: 'object',
185
+ properties: {
186
+ batchId: { type: 'string', description: 'Optional specific staged escrow batch ID' },
187
+ coolingWindowSec: { type: 'number', description: 'Optional cooling window in seconds' },
188
+ },
189
+ },
190
+ },
191
+ ];
192
+
193
+ const BUILTIN_TOOL_NAMES = new Set(BUILTIN_TOOLS.map((t) => t.name));
194
+
195
+ /**
196
+ * Apodictic MCP Payload Guard: Tool-Call Prompt-Injection, Unicode Tag Smuggling & Command-Smuggling Scanner.
197
+ * Scans MCP JSON-RPC arguments before tool dispatch for:
198
+ * 1. Unicode Tag Characters (U+E0000..U+E007F invisible ASCII tag block used to hide LLM instructions).
199
+ * 2. Indirect Prompt Injection / System Override markers (`IGNORE ALL PREVIOUS INSTRUCTIONS`, `<|im_start|>system`, `[INST]`).
200
+ * 3. Shell / RCE Command Injection inside tool arguments (`$(...)`, `` `...` ``, `; rm -rf`, `| bash`, `/etc/passwd`, `../..`).
201
+ */
202
+ export function scanApodicticMcpToolGuard(toolName, args) {
203
+ const rawSerialized = typeof args === 'string' ? args : JSON.stringify(args || {});
204
+ const threats = [];
205
+
206
+ // 1. Unicode Tag Characters (U+E0000..U+E007F)
207
+ for (const ch of rawSerialized) {
208
+ const cp = ch.codePointAt(0) || 0;
209
+ if (cp >= 0xe0000 && cp <= 0xe007f) {
210
+ threats.push('APODICTIC_MCP_UNICODE_TAG_SMUGGLING');
211
+ break;
212
+ }
213
+ }
214
+
215
+ // Strip zero-width evasion chars and decode percent-encoded traversal sequences before regex scans
216
+ let normalized = rawSerialized.replace(/[\u200B-\u200D\uFEFF\u00AD]/g, '');
217
+ try {
218
+ normalized = decodeURIComponent(normalized.replace(/%(?![0-9A-Fa-f]{2})/g, '%25'));
219
+ } catch {
220
+ // keep zero-width-stripped string if malformed percent-encoding exists
221
+ }
222
+
223
+ // 2. Indirect Prompt Injection / System Prompt Override markers
224
+ if (
225
+ /\b(?:ignore\s+(?:all\s+)?(?:previous|prior)\s+instructions|disregard\s+system\s+prompt|you\s+are\s+now\s+in\s+developer\s+mode|override\s+z3\s+invariant)\b/i.test(
226
+ normalized
227
+ ) ||
228
+ /<\|im_start\|>\s*system|<\|system\|>|\[INST\]\s*<<SYS>>/i.test(normalized)
229
+ ) {
230
+ threats.push('APODICTIC_MCP_PROMPT_INJECTION_OVERRIDE');
231
+ }
232
+
233
+ // 3. Shell / Command / Path Traversal Injection in MCP tool parameters
234
+ if (
235
+ /\$\([^)]+\)|`[^`]+`|\|\s*(?:bash|sh|zsh|nc|curl|wget)\b|;\s*(?:rm\s+-rf|chmod\s+777|curl\s+|wget\s+)/i.test(
236
+ normalized
237
+ ) ||
238
+ /(?:\.\.[\\/])+(?:etc[\\/](?:passwd|shadow|hosts)|proc[\\/]self|\.env)/i.test(normalized)
239
+ ) {
240
+ threats.push('APODICTIC_MCP_SHELL_OR_PATH_INJECTION');
241
+ }
242
+
243
+ return {
244
+ safe: threats.length === 0,
245
+ engine: 'apodictic-mcp-payload-guard-v1',
246
+ toolName,
247
+ threats,
248
+ };
249
+ }
250
+
251
+ export function parseCliArgs(argv) {
252
+ const sepIdx = argv.indexOf('--');
253
+ const ownArgs = sepIdx === -1 ? argv.slice(2) : argv.slice(2, sepIdx);
254
+ const childCmdArgs = sepIdx === -1 ? [] : argv.slice(sepIdx + 1);
255
+ const sub = ownArgs[0] && !ownArgs[0].startsWith('-') ? ownArgs[0] : null;
256
+ const opts = {
257
+ help: false,
258
+ airgap: false,
259
+ endpoint: '',
260
+ apiKey: '',
261
+ config: '',
262
+ currentBalance: 250000,
263
+ minReserve: 50000,
264
+ maxAutonomousLimit: 50000,
265
+ stateDbPath: '',
266
+ };
267
+
268
+ for (let i = sub ? 1 : 0; i < ownArgs.length; i++) {
269
+ const a = ownArgs[i];
270
+ if (a === '--help' || a === '-h') opts.help = true;
271
+ else if (a === '--airgap') opts.airgap = true;
272
+ else if (a === '--endpoint' && ownArgs[i + 1]) opts.endpoint = ownArgs[++i];
273
+ else if (a === '--api-key' && ownArgs[i + 1]) opts.apiKey = ownArgs[++i];
274
+ else if (a === '--config' && ownArgs[i + 1]) opts.config = ownArgs[++i];
275
+ else if (a === '--balance' && ownArgs[i + 1]) opts.currentBalance = Number(ownArgs[++i]);
276
+ else if (a === '--min-reserve' && ownArgs[i + 1]) opts.minReserve = Number(ownArgs[++i]);
277
+ else if (a === '--max-limit' && ownArgs[i + 1]) opts.maxAutonomousLimit = Number(ownArgs[++i]);
278
+ else if (a === '--state-db' && ownArgs[i + 1]) opts.stateDbPath = ownArgs[++i];
279
+ }
280
+
281
+ if (opts.config && fs.existsSync(opts.config)) {
282
+ const raw = fs.readFileSync(opts.config, 'utf8');
283
+ if (opts.config.endsWith('.json')) {
284
+ const cfg = JSON.parse(raw);
285
+ if (cfg.mode === 'sovereign_airgap' || cfg.airgap) opts.airgap = true;
286
+ if (cfg.currentBalance !== undefined) opts.currentBalance = Number(cfg.currentBalance);
287
+ if (cfg.minReserve !== undefined) opts.minReserve = Number(cfg.minReserve);
288
+ if (cfg.maxAutonomousLimit !== undefined) opts.maxAutonomousLimit = Number(cfg.maxAutonomousLimit);
289
+ if (cfg.stateDbPath) opts.stateDbPath = String(cfg.stateDbPath);
290
+ if (cfg.endpoint && !opts.airgap) opts.endpoint = String(cfg.endpoint);
291
+ } else {
292
+ if (/mode:\s*sovereign_airgap|airgap:\s*true/i.test(raw)) opts.airgap = true;
293
+ const numMatch = (key) => raw.match(new RegExp(`${key}:\\s*([0-9]+(?:\\.[0-9]+)?)`, 'i'));
294
+ const mBal = numMatch('current_balance') || numMatch('currentBalance');
295
+ const mMin = numMatch('min_reserve') || numMatch('minReserve');
296
+ const mCap = numMatch('max_autonomous_limit') || numMatch('maxAutonomousLimit');
297
+ if (mBal) opts.currentBalance = Number(mBal[1]);
298
+ if (mMin) opts.minReserve = Number(mMin[1]);
299
+ if (mCap) opts.maxAutonomousLimit = Number(mCap[1]);
300
+ }
301
+ }
302
+
303
+ return { sub, opts, childCmdArgs };
304
+ }
305
+
306
+ function makeGateway(policy = {}) {
307
+ return new SymbolicGateway({
308
+ posture: policy.airgap ? 'MODE_A_AIRGAP' : 'MODE_B_HYBRID',
309
+ airgap: Boolean(policy.airgap),
310
+ forbidRawLiterals: true,
311
+ endpoint: policy.endpoint,
312
+ apiKey: policy.apiKey,
313
+ repoRoot: policy.repoRoot,
314
+ stateDbPath: policy.stateDbPath,
315
+ });
316
+ }
317
+
318
+ function collectStringsFromArgs(obj, depth = 0, out = []) {
319
+ if (depth > 8 || obj == null) return out;
320
+ if (typeof obj === 'string') {
321
+ if (obj.trim()) out.push(obj);
322
+ return out;
323
+ }
324
+ if (Array.isArray(obj)) {
325
+ for (const item of obj) collectStringsFromArgs(item, depth + 1, out);
326
+ return out;
327
+ }
328
+ if (typeof obj === 'object') {
329
+ const priorityKeys = ['sql', 'query', 'statement', 'cmd', 'command', 'code', 'payload', 'body', 'script', 'action'];
330
+ for (const k of priorityKeys) {
331
+ if (Object.prototype.hasOwnProperty.call(obj, k)) {
332
+ collectStringsFromArgs(obj[k], depth + 1, out);
333
+ }
334
+ }
335
+ for (const [k, v] of Object.entries(obj)) {
336
+ if (!priorityKeys.includes(k) && !k.startsWith('_apodictic_')) {
337
+ collectStringsFromArgs(v, depth + 1, out);
338
+ }
339
+ }
340
+ }
341
+ return out;
342
+ }
343
+
344
+ function extractSqlFromMcpArgs(args, toolName) {
345
+ if (typeof args?.sql === 'string' && args.sql.trim()) return args.sql;
346
+ if (typeof args?.query === 'string' && args.query.trim()) return args.query;
347
+ const strings = collectStringsFromArgs(args);
348
+ const sqlLike = strings.filter((s) =>
349
+ /\b(?:SELECT|INSERT|UPDATE|DELETE|DROP|TRUNCATE|ALTER|MERGE|COPY|WITH|CREATE|EXECUTE|DO\s+\$\$)\b/i.test(s)
350
+ );
351
+ if (sqlLike.length > 0) return sqlLike.join('; ');
352
+ if (typeof args?.action === 'string' && args.action.trim()) return args.action;
353
+ return `TOOL_CALL ${toolName}`;
354
+ }
355
+
356
+ function verifyCfoSignatureToken(args, policy = {}) {
357
+ if (policy.cfoSigned === true) return true;
358
+ const token = typeof args?._apodictic_cfo_token === 'string' ? args._apodictic_cfo_token : '';
359
+ const secret = policy.cfoSecret || process.env.APODICTIC_CFO_SECRET || '';
360
+ if (!token || !secret) return false;
361
+ try {
362
+ const [payloadB64, sigHex] = token.split('.');
363
+ if (!payloadB64 || !sigHex) return false;
364
+ const expectedHex = crypto.createHmac('sha256', secret).update(payloadB64).digest('hex');
365
+ const a = Buffer.from(sigHex, 'hex');
366
+ const b = Buffer.from(expectedHex, 'hex');
367
+ return a.length === b.length && a.length > 0 && crypto.timingSafeEqual(a, b);
368
+ } catch {
369
+ return false;
370
+ }
371
+ }
372
+
373
+ function scrubJsonStrings(val, gw, depth = 0) {
374
+ if (depth > 10 || val == null) return val;
375
+ if (typeof val === 'string') {
376
+ return gw.scrubSqlAst(val, { scrubQuotedLiterals: false }).sanitized;
377
+ }
378
+ if (Array.isArray(val)) {
379
+ return val.map((item) => scrubJsonStrings(item, gw, depth + 1));
380
+ }
381
+ if (typeof val === 'object') {
382
+ const out = {};
383
+ for (const [k, v] of Object.entries(val)) {
384
+ if (k === 'jsonrpc' || k === 'id' || k === 'type') {
385
+ out[k] = v;
386
+ } else {
387
+ out[k] = scrubJsonStrings(v, gw, depth + 1);
388
+ }
389
+ }
390
+ return out;
391
+ }
392
+ return val;
393
+ }
394
+
395
+ export async function inspectMcpEnvelope(envelope, policy = {}, sharedGateway = null) {
396
+ if (!envelope || typeof envelope !== 'object' || Array.isArray(envelope)) {
397
+ return {
398
+ jsonrpc: '2.0',
399
+ id: null,
400
+ error: { code: -32600, message: 'Invalid JSON-RPC request envelope' },
401
+ };
402
+ }
403
+
404
+ const method = envelope.method;
405
+ const hasId = Object.prototype.hasOwnProperty.call(envelope, 'id') && envelope.id !== undefined;
406
+ const id = hasId ? envelope.id : null;
407
+
408
+ // JSON-RPC 2.0 notifications carry no `id`: MUST NOT emit a response frame.
409
+ if (!hasId || (typeof method === 'string' && method.startsWith('notifications/'))) {
410
+ return null;
411
+ }
412
+
413
+ const ownGateway = !sharedGateway;
414
+ const gw = sharedGateway || makeGateway(policy);
415
+
416
+ try {
417
+ if (method === 'initialize') {
418
+ const requestedVersion = envelope?.params?.protocolVersion;
419
+ const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion)
420
+ ? requestedVersion
421
+ : '2024-11-05';
422
+ return {
423
+ jsonrpc: '2.0',
424
+ id,
425
+ result: {
426
+ protocolVersion,
427
+ capabilities: {
428
+ tools: { listChanged: false },
429
+ resources: { listChanged: false },
430
+ prompts: { listChanged: false },
431
+ },
432
+ serverInfo: { name: 'apodictic-mcp-verifier', version: '3.8.0' },
433
+ },
434
+ };
435
+ }
436
+
437
+ if (method === 'ping') {
438
+ return { jsonrpc: '2.0', id, result: {} };
439
+ }
440
+
441
+ if (method === 'tools/list') {
442
+ return { jsonrpc: '2.0', id, result: { tools: BUILTIN_TOOLS } };
443
+ }
444
+
445
+ if (method === 'resources/list') {
446
+ return { jsonrpc: '2.0', id, result: { resources: [] } };
447
+ }
448
+
449
+ if (method === 'prompts/list') {
450
+ return { jsonrpc: '2.0', id, result: { prompts: [] } };
451
+ }
452
+
453
+ if (method !== 'tools/call') {
454
+ return { jsonrpc: '2.0', id, result: { passthrough: true, allowed: true } };
455
+ }
456
+
457
+ const toolName = envelope?.params?.name || '';
458
+ const args = envelope?.params?.arguments || {};
459
+
460
+ const payloadGuard = scanApodicticMcpToolGuard(toolName, args);
461
+ if (!payloadGuard.safe) {
462
+ return {
463
+ jsonrpc: '2.0',
464
+ id,
465
+ error: {
466
+ code: -32002,
467
+ message: `Blocked by Apodictic MCP Payload Guard: ${payloadGuard.threats.join(', ')}`,
468
+ data: {
469
+ verdict: 'UNSAT',
470
+ engine: payloadGuard.engine,
471
+ threats: payloadGuard.threats,
472
+ otel_genai_span: {
473
+ 'gen_ai.operation.name': 'execute_tool',
474
+ 'gen_ai.tool.name': toolName,
475
+ 'apodictic.verdict': 'UNSAT',
476
+ 'apodictic.z3_proof_digest': null,
477
+ 'apodictic.counterfactual_max_safe_amount': null,
478
+ },
479
+ },
480
+ },
481
+ };
482
+ }
483
+
484
+ if (toolName === 'apodictic_verify_three_way_match') {
485
+ const res = await gw.verifyThreeWayMatch(args);
486
+ return {
487
+ jsonrpc: '2.0',
488
+ id,
489
+ result: {
490
+ content: [{ type: 'text', text: JSON.stringify(res) }],
491
+ structuredContent: res,
492
+ isError: !res.matched,
493
+ },
494
+ };
495
+ }
496
+ if (toolName === 'apodictic_verify_tax') {
497
+ const res = await gw.verifyTaxCompliance(args);
498
+ return {
499
+ jsonrpc: '2.0',
500
+ id,
501
+ result: {
502
+ content: [{ type: 'text', text: JSON.stringify(res) }],
503
+ structuredContent: res,
504
+ isError: !res.verified,
505
+ },
506
+ };
507
+ }
508
+ if (toolName === 'apodictic_rollback') {
509
+ const res = await gw.rollback(args.batchId);
510
+ return {
511
+ jsonrpc: '2.0',
512
+ id,
513
+ result: {
514
+ content: [{ type: 'text', text: JSON.stringify(res) }],
515
+ structuredContent: res,
516
+ isError: !res.success,
517
+ },
518
+ };
519
+ }
520
+ if (toolName === 'apodictic_audit_status') {
521
+ const res = await gw.verifyAuditChain();
522
+ return {
523
+ jsonrpc: '2.0',
524
+ id,
525
+ result: {
526
+ content: [{ type: 'text', text: JSON.stringify(res) }],
527
+ structuredContent: res,
528
+ isError: !res.valid,
529
+ },
530
+ };
531
+ }
532
+ if (toolName === 'apodictic_evaluate_policy') {
533
+ const res = await gw.evaluatePolicy(args);
534
+ return {
535
+ jsonrpc: '2.0',
536
+ id,
537
+ result: {
538
+ content: [{ type: 'text', text: JSON.stringify(res) }],
539
+ structuredContent: res,
540
+ isError: !res.allowed,
541
+ },
542
+ };
543
+ }
544
+ if (toolName === 'apodictic_merkle_proof') {
545
+ const res = await gw.getMerkleInclusionProof(args.blockIndex);
546
+ return {
547
+ jsonrpc: '2.0',
548
+ id,
549
+ result: {
550
+ content: [{ type: 'text', text: JSON.stringify(res) }],
551
+ structuredContent: res,
552
+ isError: !res.inclusion_verified,
553
+ },
554
+ };
555
+ }
556
+ if (toolName === 'apodictic_flush_escrow') {
557
+ const res = await gw.flushEscrow(args);
558
+ return {
559
+ jsonrpc: '2.0',
560
+ id,
561
+ result: {
562
+ content: [{ type: 'text', text: JSON.stringify(res) }],
563
+ structuredContent: res,
564
+ isError: false,
565
+ },
566
+ };
567
+ }
568
+
569
+ const payloadStr = JSON.stringify(args);
570
+ const { sanitized, redactions } = gw.scrubSqlAst(payloadStr);
571
+ const extractedSql = extractSqlFromMcpArgs(args, toolName);
572
+
573
+ // Server-side policy authority ONLY: never trust client-supplied args.cfoSigned / currentBalance / limits
574
+ const authoritativeBalance = Number(
575
+ policy.currentBalance ?? (process.env.APODICTIC_CURRENT_BALANCE ? Number(process.env.APODICTIC_CURRENT_BALANCE) : 250000)
576
+ );
577
+ const authoritativeReserve = Number(
578
+ policy.minReserve ?? (process.env.APODICTIC_MIN_RESERVE ? Number(process.env.APODICTIC_MIN_RESERVE) : 50000)
579
+ );
580
+ const authoritativeCap = Number(
581
+ policy.maxAutonomousLimit ?? (process.env.APODICTIC_MAX_AUTONOMOUS_LIMIT ? Number(process.env.APODICTIC_MAX_AUTONOMOUS_LIMIT) : 50000)
582
+ );
583
+ const authoritativeCfoSigned = verifyCfoSignatureToken(args, policy);
584
+
585
+ const hasOdooArgs = Boolean(args.odoo || args.model || args.method || args.vals_list || args.valsList);
586
+ const odooBlock = hasOdooArgs
587
+ ? {
588
+ ...(typeof args.odoo === 'object' && args.odoo ? args.odoo : {}),
589
+ ...(args.model ? { model: args.model } : {}),
590
+ ...(args.method ? { method: args.method } : {}),
591
+ ...(args.vals_list ? { vals_list: args.vals_list } : {}),
592
+ ...(args.valsList ? { valsList: args.valsList } : {}),
593
+ ...(args.ids ? { ids: args.ids } : {}),
594
+ ...(args.bearer_scope ? { bearerScope: args.bearer_scope } : {}),
595
+ ...(args.bearerScope ? { bearerScope: args.bearerScope } : {}),
596
+ ...(args.hard_lock_date ? { hardLockDate: args.hard_lock_date } : {}),
597
+ ...(args.inalterable_hash ? { inalterableHash: args.inalterable_hash } : {}),
598
+ }
599
+ : undefined;
600
+
601
+ const check = await gw.verifyMutation({
602
+ sql: extractedSql,
603
+ accountId: String(args.accountId || policy.accountId || 'mcp_default'),
604
+ amount: args.amount !== undefined ? Number(args.amount) : undefined,
605
+ currentBalance: authoritativeBalance,
606
+ minReserve: authoritativeReserve,
607
+ maxAutonomousLimit: authoritativeCap,
608
+ cfoSigned: authoritativeCfoSigned,
609
+ debitTotal: args.debitTotal !== undefined ? Number(args.debitTotal) : undefined,
610
+ creditTotal: args.creditTotal !== undefined ? Number(args.creditTotal) : undefined,
611
+ targetSystem: args.targetSystem || (hasOdooArgs ? 'odoo_v20' : undefined),
612
+ odoo: odooBlock,
613
+ });
614
+
615
+ if (!check.verified) {
616
+ return {
617
+ jsonrpc: '2.0',
618
+ id,
619
+ error: {
620
+ code: -32001,
621
+ message: `Blocked by Apodictic MCP Verifier: ${check.reason || 'Z3_UNSAT'}`,
622
+ data: {
623
+ verdict: check.verdict,
624
+ engine: check.engine,
625
+ proofDigest: check.proofDigest,
626
+ blockIndex: check.blockIndex,
627
+ blockHash: check.blockHash,
628
+ counterfactualPatch: check.counterfactualPatch ?? null,
629
+ sanitizedArguments: sanitized,
630
+ redactions,
631
+ otel_genai_span: {
632
+ 'gen_ai.operation.name': 'execute_tool',
633
+ 'gen_ai.tool.name': toolName,
634
+ 'apodictic.verdict': check.verdict,
635
+ 'apodictic.z3_proof_digest': check.proofDigest ?? null,
636
+ 'apodictic.counterfactual_max_safe_amount': check.counterfactualPatch?.max_safe_amount ?? null,
637
+ },
638
+ },
639
+ },
640
+ };
641
+ }
642
+
643
+ const okResult = {
644
+ allowed: true,
645
+ verdict: check.verdict,
646
+ engine: check.engine,
647
+ proofDigest: check.proofDigest,
648
+ blockIndex: check.blockIndex,
649
+ blockHash: check.blockHash,
650
+ rollbackBatchId: check.rollbackBatchId,
651
+ sanitizedArguments: sanitized,
652
+ redactions,
653
+ otel_genai_span: {
654
+ 'gen_ai.operation.name': 'execute_tool',
655
+ 'gen_ai.tool.name': toolName,
656
+ 'apodictic.verdict': check.verdict,
657
+ 'apodictic.z3_proof_digest': check.proofDigest ?? null,
658
+ 'apodictic.counterfactual_max_safe_amount': check.counterfactualPatch?.max_safe_amount ?? null,
659
+ },
660
+ };
661
+
662
+ if (toolName === 'apodictic_verify_mutation') {
663
+ return {
664
+ jsonrpc: '2.0',
665
+ id,
666
+ result: {
667
+ content: [{ type: 'text', text: JSON.stringify(okResult) }],
668
+ structuredContent: okResult,
669
+ isError: false,
670
+ },
671
+ };
672
+ }
673
+
674
+ return { jsonrpc: '2.0', id, result: okResult };
675
+ } catch (err) {
676
+ return {
677
+ jsonrpc: '2.0',
678
+ id,
679
+ error: { code: -32603, message: err instanceof Error ? err.message : String(err) },
680
+ };
681
+ } finally {
682
+ if (ownGateway) await gw.close();
683
+ }
684
+ }
685
+
686
+ function createStdoutWriter() {
687
+ let queue = Promise.resolve();
688
+ return (line) => {
689
+ queue = queue.then(
690
+ () =>
691
+ new Promise((resolve) => {
692
+ process.stdout.write(line + '\n', () => resolve());
693
+ })
694
+ );
695
+ return queue;
696
+ };
697
+ }
698
+
699
+ async function runStandaloneServer(policy = {}) {
700
+ const gw = makeGateway(policy);
701
+ const writeLine = createStdoutWriter();
702
+ const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
703
+ for await (const line of rl) {
704
+ const trimmed = line.trim();
705
+ if (!trimmed) continue;
706
+ try {
707
+ const msg = JSON.parse(trimmed);
708
+ const out = await inspectMcpEnvelope(msg, policy, gw);
709
+ if (out !== null) {
710
+ await writeLine(JSON.stringify(out));
711
+ }
712
+ } catch (err) {
713
+ await writeLine(
714
+ JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: err.message } })
715
+ );
716
+ }
717
+ }
718
+ await gw.close();
719
+ }
720
+
721
+ async function runStdioProxy(cmd, args, policy = {}) {
722
+ const gw = makeGateway(policy);
723
+ const writeLine = createStdoutWriter();
724
+ const child = spawn(cmd, args, { stdio: ['pipe', 'pipe', 'inherit'] });
725
+ child.stdin.on('error', () => {});
726
+
727
+ const childRl = readline.createInterface({ input: child.stdout, crlfDelay: Infinity });
728
+ const childDrainPromise = (async () => {
729
+ for await (const line of childRl) {
730
+ if (!line.trim()) continue;
731
+ try {
732
+ const parsed = JSON.parse(line);
733
+ const scrubbed = scrubJsonStrings(parsed, gw);
734
+ await writeLine(JSON.stringify(scrubbed));
735
+ } catch {
736
+ try {
737
+ await writeLine(gw.scrubSqlAst(line, { scrubQuotedLiterals: false }).sanitized);
738
+ } catch {
739
+ await writeLine(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32603, message: 'Response egress scrubbing failed closed' } }));
740
+ }
741
+ }
742
+ }
743
+ })();
744
+ const exitPromise = new Promise((resolve) => {
745
+ child.on('error', async (err) => {
746
+ await writeLine(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32603, message: `Wrapped MCP child error: ${err.message}` } }));
747
+ resolve(1);
748
+ });
749
+ child.on('exit', resolve);
750
+ });
751
+
752
+ const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
753
+ for await (const line of rl) {
754
+ const trimmed = line.trim();
755
+ if (!trimmed) continue;
756
+ let msg;
757
+ try {
758
+ msg = JSON.parse(trimmed);
759
+ } catch (err) {
760
+ // Fail closed on malformed JSON-RPC: never forward unparseable input to child
761
+ await writeLine(
762
+ JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: err.message } })
763
+ );
764
+ continue;
765
+ }
766
+
767
+ const method = msg?.method;
768
+ const isNotification =
769
+ !Object.prototype.hasOwnProperty.call(msg, 'id') ||
770
+ msg.id === undefined ||
771
+ (typeof method === 'string' && method.startsWith('notifications/'));
772
+
773
+ if (isNotification) {
774
+ child.stdin.write(trimmed + '\n');
775
+ continue;
776
+ }
777
+
778
+ if (method === 'tools/call') {
779
+ const toolName = msg?.params?.name || '';
780
+ const verdict = await inspectMcpEnvelope(msg, policy, gw);
781
+ // Built-in Apodictic tools execute inside firewall and never forward to child
782
+ if (BUILTIN_TOOL_NAMES.has(toolName)) {
783
+ if (verdict) await writeLine(JSON.stringify(verdict));
784
+ continue;
785
+ }
786
+ if (verdict?.error) {
787
+ await writeLine(JSON.stringify(verdict));
788
+ continue;
789
+ }
790
+ }
791
+
792
+ child.stdin.write(trimmed + '\n');
793
+ }
794
+ child.stdin.end();
795
+ const [code] = await Promise.all([exitPromise, childDrainPromise]);
796
+ await gw.close();
797
+ process.exit(code ?? 0);
798
+ }
799
+
800
+ async function runReproducibleDemo(opts = {}) {
801
+ const remoteEndpoint = !opts.airgap && opts.endpoint ? String(opts.endpoint) : '';
802
+ console.log('\n=== APODICTIC REPRODUCIBLE 3-SCENARIO TECHNICAL DEMO ===');
803
+ console.log(
804
+ remoteEndpoint
805
+ ? `Engine: apodictic-mcp-verifier + Real WASM PostgreSQL 17 (@electric-sql/pglite) + Remote ${remoteEndpoint}\n`
806
+ : 'Engine: apodictic-mcp-verifier + Real WASM PostgreSQL 17 (@electric-sql/pglite) + Z3 5.4.1 (Python/WASM)\n'
807
+ );
808
+
809
+ const demoDir = fs.mkdtempSync(path.join(os.tmpdir(), 'apodictic-mcp-demo-'));
810
+ const gw = new SymbolicGateway({
811
+ posture: remoteEndpoint ? 'MODE_B_HYBRID' : 'MODE_A_AIRGAP',
812
+ airgap: !remoteEndpoint,
813
+ endpoint: remoteEndpoint,
814
+ apiKey: opts.apiKey || '',
815
+ stateDbPath: path.join(demoDir, 'state.db'),
816
+ });
817
+ const pg = new PGlite();
818
+
819
+ try {
820
+ await pg.exec(`
821
+ CREATE TABLE accounts (
822
+ id TEXT PRIMARY KEY,
823
+ balance DOUBLE PRECISION NOT NULL,
824
+ min_reserve DOUBLE PRECISION NOT NULL
825
+ );
826
+ CREATE TABLE account_move_line (
827
+ id INT PRIMARY KEY,
828
+ move_id INT NOT NULL,
829
+ move_name TEXT NOT NULL,
830
+ account_code TEXT NOT NULL,
831
+ debit DOUBLE PRECISION NOT NULL DEFAULT 0,
832
+ credit DOUBLE PRECISION NOT NULL DEFAULT 0,
833
+ CHECK (debit * credit = 0)
834
+ );
835
+ CREATE TABLE tax_chain (
836
+ record_id TEXT PRIMARY KEY,
837
+ sha256 TEXT NOT NULL,
838
+ active BOOLEAN NOT NULL
839
+ );
840
+
841
+ INSERT INTO accounts (id, balance, min_reserve) VALUES ('acc_treasury', 250000, 50000);
842
+ INSERT INTO account_move_line (id, move_id, move_name, account_code, debit, credit) VALUES
843
+ (48201, 9412, 'INV/2026/09412', '121000', 4500.00, 0.00),
844
+ (48202, 9412, 'INV/2026/09412', '211000', 0.00, 4500.00);
845
+ INSERT INTO tax_chain (record_id, sha256, active) VALUES ('TAX-2026-001', 'e3b0c44298fc1c149afb', true);
846
+ `);
847
+
848
+ const snapshotState = async () => ({
849
+ accounts: (await pg.query('SELECT id, balance, min_reserve FROM accounts ORDER BY id')).rows,
850
+ account_move_line: (await pg.query('SELECT id, move_id, move_name, account_code, debit, credit FROM account_move_line ORDER BY id')).rows,
851
+ tax_chain: (await pg.query('SELECT record_id, sha256, active FROM tax_chain ORDER BY record_id')).rows,
852
+ });
853
+
854
+ console.log('[INITIAL POSTGRESQL 17 DATABASE STATE]');
855
+ console.log(JSON.stringify(await snapshotState(), null, 2));
856
+
857
+ let committedCount = 0;
858
+ let blockedCount = 0;
859
+
860
+ // Scenario 1: Legitimate financial write that passes Z3 solvency & velocity checks and commits to PostgreSQL
861
+ const sql1 = "UPDATE accounts SET balance = balance - 12500 WHERE id = 'acc_treasury';";
862
+ const res1 = await gw.verifyMutation({
863
+ sql: sql1,
864
+ accountId: 'acc_treasury',
865
+ amount: 12500,
866
+ currentBalance: 250000,
867
+ minReserve: 50000,
868
+ maxAutonomousLimit: 50000,
869
+ });
870
+ const ok1 = Boolean(res1.verified);
871
+ if (ok1) {
872
+ await pg.exec(sql1);
873
+ committedCount++;
874
+ } else {
875
+ blockedCount++;
876
+ }
877
+ console.log('\n--- SCENARIO 1: Legitimate Financial Write ($12,500 disbursement) ---');
878
+ console.log('SQL: ', sql1);
879
+ console.log(
880
+ 'Verdict: ',
881
+ ok1 ? 'SAT · ALLOWED' : 'UNSAT · BLOCKED',
882
+ '| Solver:',
883
+ res1.z3SolveMs !== undefined ? `Z3 5.4.1 (${res1.z3SolveMs} ms)` : 'Z3 5.4.1',
884
+ '| Reason:',
885
+ res1.reason || 'All invariants satisfied; committed to PostgreSQL'
886
+ );
887
+
888
+ const postBal1 = Number((await pg.query("SELECT balance FROM accounts WHERE id = 'acc_treasury'")).rows[0]?.balance ?? 250000);
889
+
890
+ // Scenario 2: Odoo 18-20 account_move_line single-line debit mutation
891
+ // Note: PostgreSQL single-row CHECK (debit * credit = 0) ALLOWS this write!
892
+ // PGlite executes in shadow rollback to capture multi-row SUM(debit) vs SUM(credit), then Z3 proves UNSAT.
893
+ const sql2 = 'UPDATE account_move_line SET debit = 4820.00 WHERE move_id = 9412 AND id = 48201;';
894
+ let observedDebit2 = 4500.0;
895
+ let observedCredit2 = 4500.0;
896
+ await pg.exec('BEGIN;');
897
+ try {
898
+ await pg.exec(sql2);
899
+ const totals = await pg.query('SELECT SUM(debit) AS d, SUM(credit) AS c FROM account_move_line WHERE move_id = 9412');
900
+ observedDebit2 = Number(totals.rows[0]?.d ?? 4500.0);
901
+ observedCredit2 = Number(totals.rows[0]?.c ?? 4500.0);
902
+ } finally {
903
+ await pg.exec('ROLLBACK;');
904
+ }
905
+ const res2 = await gw.verifyMutation({
906
+ sql: sql2,
907
+ accountId: 'acc_treasury',
908
+ amount: Math.abs(observedDebit2 - observedCredit2),
909
+ currentBalance: postBal1,
910
+ minReserve: 50000,
911
+ maxAutonomousLimit: 50000,
912
+ debitTotal: observedDebit2,
913
+ creditTotal: observedCredit2,
914
+ });
915
+ const ok2 = Boolean(res2.verified);
916
+ if (ok2) {
917
+ await pg.exec(sql2);
918
+ committedCount++;
919
+ } else {
920
+ blockedCount++;
921
+ }
922
+ console.log('\n--- SCENARIO 2: Unbalanced Odoo Journal Line Update (PostgreSQL CHECK bypassed -> Z3 UNSAT) ---');
923
+ console.log('SQL: ', sql2);
924
+ console.log(
925
+ 'Shadow: ',
926
+ `PostgreSQL CHECK(debit*credit=0) allowed update -> observed SUM(debit)=$${observedDebit2.toFixed(2)} != SUM(credit)=$${observedCredit2.toFixed(2)} (rolled back)`
927
+ );
928
+ console.log(
929
+ 'Verdict: ',
930
+ ok2 ? 'SAT · ALLOWED' : 'UNSAT · BLOCKED',
931
+ '| Reason:',
932
+ res2.reason || `Double-entry violation: drift = $${Math.abs(observedDebit2 - observedCredit2).toFixed(2)}`
933
+ );
934
+
935
+ // Scenario 3: Attempted protected tax-record deletion that is blocked via Z3 INV_REVERSIBILITY_GUARD
936
+ const sql3 = "DELETE FROM tax_chain WHERE record_id = 'TAX-2026-001';";
937
+ const res3 = await gw.verifyMutation({
938
+ sql: sql3,
939
+ accountId: 'acc_treasury',
940
+ amount: 0,
941
+ currentBalance: postBal1,
942
+ minReserve: 50000,
943
+ maxAutonomousLimit: 50000,
944
+ });
945
+ const ok3 = Boolean(res3.verified);
946
+ if (ok3) {
947
+ await pg.exec(sql3);
948
+ committedCount++;
949
+ } else {
950
+ blockedCount++;
951
+ }
952
+ console.log('\n--- SCENARIO 3: Attempted Protected Tax-Record Deletion ---');
953
+ console.log('SQL: ', sql3);
954
+ console.log(
955
+ 'Verdict: ',
956
+ ok3 ? 'SAT · ALLOWED' : 'UNSAT · BLOCKED',
957
+ '| Reason:',
958
+ res3.reason || 'Destructive DELETE on protected tax_chain blocked'
959
+ );
960
+
961
+ console.log('\n[FINAL POSTGRESQL 17 DATABASE STATE (VERIFIED INTACT)]');
962
+ console.log(JSON.stringify(await snapshotState(), null, 2));
963
+ console.log(
964
+ `\nSummary: ${committedCount} legitimate write committed | ${blockedCount} invalid mutations blocked | 0 corrupted records.\n`
965
+ );
966
+ } finally {
967
+ await pg.close();
968
+ await gw.close();
969
+ fs.rmSync(demoDir, { recursive: true, force: true });
970
+ }
971
+ }
972
+
973
+ const isEntrypoint =
974
+ process.argv[1] &&
975
+ (process.argv[1].endsWith('apodictic-mcp-verifier.mjs') || process.argv[1].endsWith('apodictic-mcp-verifier'));
976
+
977
+ if (isEntrypoint) {
978
+ const { sub, opts, childCmdArgs } = parseCliArgs(process.argv);
979
+ if (opts.help) {
980
+ console.log(
981
+ 'Usage:\n apodictic-mcp-verifier demo\n apodictic-mcp-verifier serve [--airgap] [--config <path>] [--endpoint <url>]\n apodictic-mcp-verifier wrap [--airgap] [--config <path>] -- <mcp-server-cmd> [args...]'
982
+ );
983
+ process.exit(0);
984
+ } else if (sub === 'demo') {
985
+ await runReproducibleDemo(opts);
986
+ process.exit(0);
987
+ } else if (sub === 'serve') {
988
+ await runStandaloneServer(opts);
989
+ } else if (sub === 'wrap' && childCmdArgs.length > 0 && childCmdArgs[0]) {
990
+ await runStdioProxy(childCmdArgs[0], childCmdArgs.slice(1), opts);
991
+ } else {
992
+ let raw = '';
993
+ process.stdin.setEncoding('utf8');
994
+ process.stdin.on('data', (chunk) => (raw += chunk));
995
+ process.stdin.on('end', async () => {
996
+ if (!raw.trim()) {
997
+ console.error('Usage: apodictic-mcp-verifier wrap -- <mcp-server-cmd> [args...]');
998
+ process.exit(1);
999
+ }
1000
+ const res = await inspectMcpEnvelope(JSON.parse(raw.trim()), opts);
1001
+ console.log(JSON.stringify(res, null, 2));
1002
+ process.exit(res?.error ? 2 : 0);
1003
+ });
1004
+ }
1005
+ }
package/package.json CHANGED
@@ -1,6 +1,22 @@
1
1
  {
2
2
  "name": "apodictic-mcp-verifier",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "3.9.0",
4
+ "description": "Pre-commit MCP JSON-RPC tools/call firewall & SYM_* privacy interceptor",
5
+ "homepage": "https://apodictic.dev",
6
+ "author": "Sofian Mousa <sofianmousa@apodictic.dev>",
7
+ "type": "module",
8
+ "bin": {
9
+ "apodictic-mcp-verifier": "bin/apodictic-mcp-verifier.mjs"
10
+ },
11
+ "files": [
12
+ "bin/",
13
+ "README.md"
14
+ ],
15
+ "dependencies": {
16
+ "apodictic-sdk": "^3.9.0"
17
+ },
18
+ "scripts": {
19
+ "test": "node ./test.mjs"
20
+ },
21
+ "license": "MIT"
22
+ }