{
  "markdown": "# MnemoPay\n\n[![npm version](https://img.shields.io/npm/v/@mnemopay/sdk.svg)](https://www.npmjs.com/package/@mnemopay/sdk) [![PyPI version](https://img.shields.io/pypi/v/mnemopay.svg)](https://pypi.org/project/mnemopay/) [![smithery badge](https://smithery.ai/badge/@mnemopay/sdk)](https://smithery.ai/server/@mnemopay/sdk) [![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](./LICENSE)\n\n**The governance layer for AI agents that handle money.** Charter-driven mission scope, FiscalGate budget enforcement, EU AI Act Article 12 audit bundles, Agent Reputation Scoring (300-850), and a tamper-evident MerkleAudit chain — across every payment rail an agent will ever touch.\n\nMnemoPay sits **above** the rail (Stripe, Paystack, Lightning, Stripe MPP, x402, Google AP2) and **below** the agent runtime (LangChain, CrewAI, Claude Agent SDK, your own loop). The rail moves money. The runtime decides. MnemoPay declares the rules, enforces the budget, and produces the evidence.\n\n```bash\nnpm install @mnemopay/sdk\n```\n\n> **New here?** Start at [`docs/QUICKSTART.md`](./docs/QUICKSTART.md) — 60 seconds, three steps, working code.\n>\n> **Docs:** [Quickstart](./docs/QUICKSTART.md) · [Architecture](./docs/architecture.md) · [Permissions](./docs/permissions.md) · [Action ledger](./docs/action-ledger.md) · [Integrations (OpenAI/Anthropic/Gemini/Cohere/Mistral/LangGraph)](./docs/INTEGRATIONS.md) · [Recall](./docs/RECALL.md) · [FiscalGate](./docs/FISCALGATE.md) · [Audit bundles (EU AI Act Art. 12)](./docs/AUDIT-BUNDLES.md) · [Subpath import rule](./docs/SUBPATH-IMPORT-RULE.md) · [Claude Agent SDK guide](./docs/agent-sdk-guide.md) · [Bundlers: Vite](./docs/INTEGRATION-VITE.md) · [Webpack](./docs/INTEGRATION-WEBPACK.md) · [Bun](./docs/INTEGRATION-BUN.md)\n>\n> **Community:** [LICENSE (Apache 2.0)](./LICENSE) · [CHANGELOG](./CHANGELOG.md) · [CONTRIBUTING](./CONTRIBUTING.md) · [CODE_OF_CONDUCT](./CODE_OF_CONDUCT.md) · [SECURITY](./SECURITY.md) · [Discussions](https://github.com/mnemopay/mnemopay-sdk/discussions) · [Good first issues](https://github.com/mnemopay/mnemopay-sdk/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22)\n>\n> **Receipts:** [Trust hub](https://mnemopay.com/trust) (entity, KYB, Apple Team ID, Article 12 audit chain — verify in <5 min) · [Benchmarks](./BENCHMARKS.md) (1M ops, 100% adversarial detection, $0 ledger drift) · [Python SDK on PyPI](https://pypi.org/project/mnemopay/) (full TS-rail parity since 1.1.0)\n\n```ts\nimport MnemoPay, {\n  Charter, FiscalGate, MerkleAudit,        // governance primitives\n  AgentReputationScoring, BehavioralEngine, // trust + reputation\n  StripeRail, X402Rail, GoogleAP2Rail,      // rails\n} from \"@mnemopay/sdk\";\n\nconst agent = MnemoPay.quick(\"my-agent\");\n\nawait agent.remember(\"User prefers monthly billing\");\nconst tx = await agent.charge(25, \"Monthly API access\");   // FiscalGate hold\nawait agent.settle(tx.id);                                  // FiscalGate capture\n\n// Agent Reputation Score — portable, 300-850 range. NOT FICO-brand, NOT a consumer\n// credit report, NOT governed by FCRA. Scores agents (software), not humans.\nconst scorer = new AgentReputationScoring();\nconst result = scorer.compute({ transactions: [tx], createdAt: new Date(), /* ... */ });\n// → { score: 672, rating: \"good\", feeRate: 0.015, trustLevel: \"standard\" }\n```\n\n14 modules. Hash-chained ledger. Charter / FiscalGate / Article 12 audit bundles. 6 payment rails. 200K-operation stress tested. Apache 2.0.\n\n> **What MnemoPay is NOT:** not a bank, not a money transmitter, not a Stripe replacement, not an agent framework, not a compliance platform. It's the rules-and-evidence layer between the rail and the runtime.\n\n---\n\n## Governance latency (sub-second invariant)\n\n\"Sub-second governance\" is a tested invariant, not marketing. The bench in `tests/bench/governance-latency.bench.ts` measures each governance hot path with `vitest bench` and emits a grep-able `[gov-bench]` summary line per scenario. Numbers below are steady-state percentiles from `npm run bench:governance` (run on the dev machine — your hardware will differ; the relative ordering is what matters).\n\n| Hot path                                                      |  p50    |  p95    |  p99    | machine                                              |\n|---------------------------------------------------------------|--------:|--------:|--------:|------------------------------------------------------|\n| `policy.evaluateAction` (EU AI Act, single tool_call)         |  2.1 µs |  2.8 µs |  5.0 µs | Intel i5-1035G1 @ 1.0 GHz · Node 25.9 · Windows 11   |\n| `MerkleAudit.record` (append + chain hash)                    | 20 µs   | 45 µs   | 150 µs  | Intel i5-1035G1 @ 1.0 GHz · Node 25.9 · Windows 11   |\n| `MnemoPayLite.remember()` end-to-end with auto-anchor (Ed25519)| 1.0 ms  | 1.7 ms  | 2.5 ms  | Intel i5-1035G1 @ 1.0 GHz · Node 25.9 · Windows 11   |\n\nBoth per-event hot paths (`evaluateAction`, `MerkleAudit.record`) clear an entire EU AI Act policy gate and audit-chain write **two orders of magnitude inside one millisecond**. The end-to-end `remember()` path — including Ed25519 sign + sequence + chain emit — still sits comfortably inside the \"sub-second governance\" envelope with three decimal-orders of headroom.\n\nA CI-enforced guard spec in `tests/governance/latency-invariant.test.ts` runs a degraded-mode sample on every `npm test` and fails if p95 for `policy.evaluateAction` regresses past 1 ms, or `MerkleAudit.record` past 5 ms. Bounds are sized to catch a ~10x regression, not flap on jitter.\n\n**How to reproduce:** `npm run bench:governance` (full vitest.bench harness) or `npm test -- latency-invariant` (CI-bound check).\n\n---\n\n## Native rails\n\nEvery rail ships with the same `PaymentRail` interface as `StripeRail` / `PaystackRail` / `LightningRail`:\n\n| Rail | What it is |\n|---|---|\n| **`StripeMPPRail`** | Stripe Machine Payments Protocol — agent payments routed as crypto deposits on the Tempo network via Stripe-pinned API `2026-03-04.preview` |\n| **`X402Rail`** | Coinbase x402 (HTTP 402 revival) — USDC on Base L2 via EIP-3009 `transferWithAuthorization`. Pluggable signer (bring-your-own viem/ethers/noble). Zero crypto deps in the SDK. |\n| **`GoogleAP2Rail`** | Google Agent Payment Protocol (FIDO Alliance, AP2 v0.2). Mandate VC + Intent VC + HTTP settlement. Pre-flight policy enforcement (caps, expiry, currency, recipients) before any signature is produced. |\n\nPlus the **Spatial governance fold** — `attachSpatialEvidence()` co-signs the MerkleAudit chain with GridStamp proof-of-presence for embodied agents (drones, robots). Loose-coupled — no `gridstamp` runtime dependency.\n\n### Subpath imports for smaller, safer consumers\n\nIf you only need one MnemoPay module, import that subpath instead of the package root. This keeps MCP servers and other stdio tools quiet, avoids pulling unused middleware into bundles, and makes the dependency boundary obvious.\n\n```ts\nimport { localEmbed, cosineSimilarity } from \"@mnemopay/sdk/recall\";\nimport { StripeRail, X402Rail } from \"@mnemopay/sdk/rails\";\nimport { SQLiteStorage } from \"@mnemopay/sdk/storage\";\nimport { CommerceEngine } from \"@mnemopay/sdk/commerce\";\n```\n\nUse the root import when you want the full SDK surface. Use `@mnemopay/sdk/mcp` only when you are intentionally mounting the MnemoPay MCP server.\n\n---\n\n## Swarm (stable — v1.11+)\n\n`@mnemopay/sdk/swarm` is the missing piece that browse.sh shipped as a public skill catalog. Ours adds the bit they don't: every agent in the swarm carries a DID, every action is FiscalGate-prechecked against per-agent + total caps, every TaskResult is appended to a shared Article-12 audit chain, and every skill invocation is billable through the same hash-chained ledger the rest of the SDK already uses.\n\n**CLI:** `npx @mnemopay/swarm list` · `npx @mnemopay/swarm demo` — see [mnemopay-swarm](https://github.com/mnemopay/mnemopay-swarm).\n\n```ts\nimport { Swarm } from \"@mnemopay/sdk/swarm\";\nimport { AuditChain } from \"@mnemopay/sdk/governance\";\nimport { open } from \"@mnemopay/browser\";   // any BrowserProvider works\n\nconst provider = await someProviderFactory();\nconst swarm = new Swarm({\n  size: 4,\n  provider,\n  did: \"did:mp:abc...\",\n  budget: { perAgent: 0.25, total: 1.00 },\n  audit: { chain: new AuditChain() },\n});\n\nconst run = await swarm.spawn([\n  { id: \"t1\", skillId: \"ramp.com/expense-create\",  prompt: \"submit $42 lunch\" },\n  { id: \"t2\", skillId: \"linear/issue-create\",      prompt: \"file UI bug\" },\n  { id: \"t3\", skillId: \"cloudflare/dns-record-set\", prompt: \"add CNAME\" },\n]);\n\nconst results = await swarm.gather(run);\nconst final   = await swarm.recombine(results, \"merge-json\");\n```\n\n**When to use it.** Any time you'd open N parallel browser sessions to attack a problem — multi-source research, cross-platform issue triage, A/B-style \"ask three agents, take the majority answer\" — but you want one audit bundle, one budget envelope, and one place where billing happens.\n\n**Three recombine strategies (plus your own).**\n- `first-success` — returns the output of the first `ok:true` task; perfect for race patterns where any answer is fine.\n- `majority-vote` — returns the most-common output across `ok:true` tasks; perfect for fact-extraction where consensus matters.\n- `merge-json` — deep-merges every `ok:true` object output with sorted keys (deterministic across runs).\n- `concat` — joins string outputs with `\\n` in spawn order.\n- Or pass any `(results) => unknown` callback.\n\n**Skill catalog.** Public listings live at [mcp.mnemopay.com/skills](https://mcp.mnemopay.com/skills). The catalog is intentionally small and honestly marked — verified-partner badges only show after a real partnership is signed. Everything else carries `verified: false, status: 'pending-partner'` so you know exactly what trust tier you're getting.\n\n### BrowserSwarm — native browser-session fan-out (stable since 1.11.0)\n\n`@mnemopay/sdk/swarm/browser` extends `Swarm` with a typed step sequence (`goto` / `act` / `extract` / `screenshot` / `wait`) per task and a lazy wire to `@mnemopay/browser` (optional peer dep — installing the SDK does NOT pull Playwright). Each task gets its own browser session, every step appends a `browser.step` event to the shared audit chain, and a thrown step kills only that one task — sibling sessions keep running.\n\n```ts\nimport { BrowserSwarm } from \"@mnemopay/sdk/swarm/browser\";\nconst swarm = new BrowserSwarm({\n  size: 3, provider: undefined as never,\n  budget: { perAgent: 0.25, total: 1.00 },\n  browser: { provider: \"stagehand\" },\n});\nconst run = await swarm.spawn([\n  { id: \"amzn\", prompt: \"amazon price\",  steps: [{type:\"goto\", url:\"https://amazon.com/dp/X\"},  {type:\"extract\", selector:\"#priceblock_ourprice\"}] },\n  { id: \"bby\",  prompt: \"best buy price\", steps: [{type:\"goto\", url:\"https://bestbuy.com/site/X\"},{type:\"extract\", selector:\".priceView-customer-price\"}] },\n  { id: \"tgt\",  prompt: \"target price\",   steps: [{type:\"goto\", url:\"https://target.com/p/X\"},   {type:\"extract\", selector:\"[data-test=product-price]\"}] },\n]);\nconst results = await swarm.gather(run);   // BrowserTaskResult[] with .screenshots + .extractedData\n```\n\nFile issues at [github.com/mnemopay/mnemopay-sdk](https://github.com/mnemopay/mnemopay-sdk).\n\n### Audit-only middleware — `.audit(client)` with streaming + on-disk chain (1.11.0-alpha.0)\n\nFor chat widgets and regulated pipelines where ANY prompt mutation is a violation but Article-12 telemetry is still required:\n\n```ts\nimport { AuditChain } from \"@mnemopay/sdk/governance/audit-chain\";\nimport { AnthropicMiddleware } from \"@mnemopay/sdk/middleware/anthropic-audit\";\n\nconst chain = new AuditChain({ path: \"./.audit-chain/llm.jsonl\" });  // file-backed since 1.11.0-alpha.0\nconst client = AnthropicMiddleware.audit(new Anthropic(), { chain });\n\n// .create AND .stream now both emit one `llm.call` event per call. Streams\n// that get cancelled mid-iteration emit `partial: true` with tokens-so-far.\nfor await (const chunk of client.messages.stream({ model, max_tokens, messages })) { /* ... */ }\n```\n\n`@mnemopay/sdk/middleware/openai-audit` exposes the equivalent shape for OpenAI — `chat.completions.create({ stream: true })` is intercepted automatically (pass `stream_options: { include_usage: true }` to capture the final usage block).\n\n---\n\n## Building an MCP server? Start here.\n\nIf you're shipping an MCP server and want to charge per-call — even sub-cent amounts — MnemoPay is built for you.\n\n- **Sub-cent payments** via Lightning rail (impossible on Stripe/Paystack due to fees)\n- **Per-tool metering** with `agent.charge(amount, toolName)` — two lines of code\n- **Agent Reputation Scoring** gates abusive callers automatically — 300-850 reputation score, free tier + paid tier\n- **Cryptographic receipts** every user can audit — no \"trust me bro\" billing\n- **Free indefinitely** for the first 10 MCP servers that adopt it, subject to 90 days' written notice of any future change ([email](mailto:omiagbogold@icloud.com) with your repo)\n\n```ts\nimport MnemoPay from \"@mnemopay/sdk\";\nconst agent = MnemoPay.quick(\"my-mcp-server\");\n\n// Inside your tool handler:\nconst tx = await agent.charge(0.002, \"embed_document\");  // 0.2¢\nif (tx.status === \"blocked\") return { error: \"Payment declined\" };\nawait agent.settle(tx.id);\n// ... run the tool\n```\n\nZero-config starter → production Lightning rail → Agent Reputation Scoring gating. Same API.\n\n---\n\n## What Makes MnemoPay Different\n\n$87M has been invested across 5 competitors. None have more than 3 of these 10 features:\n\n| Feature | MnemoPay | Mem0 ($24M) | Skyfire ($9.5M) | Kite ($33M) | Payman ($14M) |\n|---|:---:|:---:|:---:|:---:|:---:|\n| Persistent Memory | **Yes** | Yes | No | No | No |\n| Payment Rails (3) | **Yes** | No | USDC only | Stablecoin | Bank only |\n| Agent Identity (KYA) | **Yes** | No | Building | Passport | No |\n| **Agent Reputation Scoring (300-850)** | **Yes** | No | No | No | No |\n| **Behavioral Finance** | **Yes** | No | No | No | No |\n| **Memory Integrity (Merkle)** | **Yes** | No | No | No | No |\n| **EWMA Anomaly Detection** | **Yes** | No | No | No | No |\n| Double-Entry Ledger | **Yes** | No | No | No | No |\n| Autonomous Commerce | **Yes** | No | No | No | No |\n| Multi-Agent Network | **Yes** | No | Partial | Partial | No |\n| **Score** | **10/10** | 1/10 | 2/10 | 2/10 | 1/10 |\n\n---\n\n## Agent Reputation Scoring\n\nA novel cross-session reputation scoring system for AI agents. Five-component scoring on a 300-850 range (familiar to developers from consumer credit; MnemoPay is not affiliated with Fair Isaac Corporation or any consumer credit bureau):\n\n```ts\nimport { AgentReputationScoring } from \"@mnemopay/sdk\";\n\nconst scorer = new AgentReputationScoring();\nconst result = scorer.compute({\n  transactions: await agent.history(1000),\n  createdAt: agentCreationDate,\n  fraudFlags: 0,\n  disputeCount: 0,\n  disputesLost: 0,\n  warnings: 0,\n  budgetCap: 5000,\n  memoriesCount: agent.memories.size,\n});\n\nconsole.log(result.score);      // 742\nconsole.log(result.rating);     // \"very_good\"\nconsole.log(result.feeRate);    // 0.013 (1.3%)\nconsole.log(result.trustLevel); // \"high\"\nconsole.log(result.requiresHITL); // false\n```\n\n| Component | Weight | What It Measures |\n|---|---|---|\n| Payment History | 35% | Success rate, disputes, recency-weighted |\n| Credit Utilization | 20% | Spend vs budget cap, sweet spot 10-30% |\n| History Length | 15% | Account age, activity density |\n| Behavior Diversity | 15% | Counterparties, categories, amount range |\n| Fraud Record | 15% | Fraud flags, disputes lost, warnings |\n\n| Score Range | Rating | Trust Level | Fee Rate |\n|---|---|---|---|\n| 800-850 | Exceptional | Full trust | 1.0% |\n| 740-799 | Very Good | High trust | 1.3% |\n| 670-739 | Good | Standard | 1.5% |\n| 580-669 | Fair | Reduced | 1.9% |\n| 300-579 | Poor | Minimal + HITL | 2.5% |\n\n---\n\n## Behavioral Finance Engine\n\nPeer-reviewed behavioral economics from Nobel laureate Daniel Kahneman and collaborators. Every parameter cited to published research.\n\n```ts\nimport { BehavioralEngine } from \"@mnemopay/sdk\";\n\nconst behavioral = new BehavioralEngine();\n\n// Prospect Theory (Kahneman & Tversky, 1992)\n// Losses hurt 2.25x more than gains feel good\nbehavioral.prospectValue(100);   // { value: 57.5, domain: \"gain\" }\nbehavioral.prospectValue(-100);  // { value: -129.5, domain: \"loss\" }\n\n// Should the agent wait before buying?\nconst cooling = behavioral.coolingOff(2000, 5000); // amount, monthly income\n// → { recommended: true, hours: 3.2, riskLevel: \"high\", regretProbability: 0.65 }\n\n// Frame spending as goal delay (2.25x more effective than gain framing)\nconst frame = behavioral.lossFrame(200, {\n  name: \"Emergency Fund\", target: 10000, current: 3000, monthlySavings: 500\n});\n// → \"This $200 purchase delays your Emergency Fund goal by 12 days.\"\n\n// Save More Tomorrow (Thaler & Benartzi, 2004)\nconst smart = behavioral.commitmentDevice(0.035, 0.03, 4);\n// → { finalRate: 0.095, explanation: \"3.5% → 9.5% over 4 raise cycles\" }\n\n// Predict regret from purchase history\nbehavioral.recordRegret({ amount: 300, category: \"gadgets\", regretScore: 8, timestamp: \"...\" });\nconst prediction = behavioral.predictRegret(400, \"gadgets\");\n// → { probability: 0.72, triggerCoolingOff: true }\n```\n\n**Research sources:** Tversky & Kahneman 1992, Laibson 1997, Thaler & Benartzi 2004, Barber & Odean 2000, Nunes & Dreze 2006, Shiller 2000.\n\n---\n\n## Memory Integrity (Merkle Tree)\n\nTamper-evident memory. If anyone injects, modifies, or deletes an agent's memories, the Merkle root changes and you know.\n\n```ts\nimport { MerkleTree } from \"@mnemopay/sdk\";\n\nconst tree = new MerkleTree();\n\n// Every memory write adds a leaf\ntree.addLeaf(\"mem-1\", \"User prefers monthly billing\");\ntree.addLeaf(\"mem-2\", \"Last purchase was $25 API access\");\n\n// Take periodic snapshots\nconst snapshot = tree.snapshot();\n// → { rootHash: \"a3f2...\", leafCount: 2, snapshotHash: \"b7c1...\" }\n\n// Later: check if memories were tampered\nconst check = tree.detectTampering(snapshot);\n// → { tampered: false, summary: \"Integrity verified. 2 memories, root matches.\" }\n\n// Prove a specific memory exists without revealing others\nconst proof = tree.getProof(\"mem-1\");\nMerkleTree.verifyProof(proof); // true\n```\n\n**Defends against:** MemoryGraft injection, silent deletion, content tampering, replay attacks, reordering attacks.\n\n---\n\n## Anomaly Detection (EWMA + Behavioral Fingerprinting + Canaries)\n\nThree independent systems that catch compromised agents.\n\n```ts\nimport { EWMADetector, BehaviorMonitor, CanarySystem } from \"@mnemopay/sdk\";\n\n// 1. EWMA: real-time streaming anomaly detection\nconst detector = new EWMADetector(0.15, 2.5, 3.5, 10);\ndetector.update(100); // normal\ndetector.update(100); // normal\ndetector.update(9999); // → { anomaly: true, severity: \"critical\", zScore: 8.2 }\n\n// 2. Behavioral fingerprinting: detect hijacked agents\nconst monitor = new BehaviorMonitor({ warmupPeriod: 10 });\n// Build profile over time\nmonitor.observe(\"agent-1\", { amount: 100, hourOfDay: 14, chargesPerHour: 2 });\n// Sudden change = suspected hijack\nmonitor.observe(\"agent-1\", { amount: 9999, hourOfDay: 3, chargesPerHour: 50 });\n// → { suspected: true, severity: \"critical\", anomalousFeatures: 3 }\n\n// 3. Canary honeypots: plant traps for compromised agents\nconst canary = new CanarySystem();\nconst trap = canary.plant(\"transaction\");\ncanary.check(trap.id, \"rogue-agent\");\n// → { severity: \"critical\", message: \"CANARY TRIGGERED: Agent compromised\" }\n```\n\n**Math:** `mu_t = alpha * x_t + (1 - alpha) * mu_{t-1}`, alert when `|x_t - mu_t| > k * sigma_t` (Roberts 1959, Lucas & Saccucci 1990).\n\n---\n\n## Memory (Compounding Knowledge Base)\n\nNot a traditional RAG lookup. MnemoPay memories compound — every transaction strengthens associated context, weak memories decay, strong ones consolidate. The same pattern Karpathy describes as \"LLM Wiki\" but applied to payments and trust.\n\n- **Ebbinghaus forgetting curve** — memories decay naturally over time\n- **Hebbian reinforcement** — successful transactions strengthen associated memories\n- **RL feedback loop** — `rlFeedback(ids, reward)` applies EWMA importance updates after agent actions\n- **Consolidation** — auto-prunes weak memories, keeps what matters\n- **Semantic recall** — find memories by relevance, not just recency\n- **100KB per memory** — store rich context, not just strings\n\n```ts\n// After a recall + action, signal usefulness with rlFeedback\nconst memories = await agent.recall(\"user preferences\", 5);\n// ... agent acts on recalled memories ...\nawait agent.rlFeedback(memories.map(m => m.id), +1.0);   // +1 = useful, -1 = not useful\n```\n\n### Choosing a persistence adapter\n\nRecall is backed by a pluggable `PersistenceAdapter`. Pick by deployment shape:\n\n| Adapter | Infra | Best for | Import |\n|---|---|---|---|\n| `MemoryAdapter` (default) | none | dev, tests, ephemeral agents | built-in |\n| `SQLiteAdapter` | one file (`better-sqlite3`) | single-node, local-first, edge | `@mnemopay/sdk/storage` |\n| `PostgresAdapter` / `NeonAdapter` | Postgres + pgvector | hosted/multi-node prod (Neon, Supabase, RDS/Aurora, Cloud SQL) | `@mnemopay/sdk/recall/postgres` |\n\n`PostgresAdapter` and `NeonAdapter` are the same pgvector-backed implementation\n— \"Neon\" is just hosted Postgres; use whichever name fits your infra.\n\n```ts\nimport { MnemoPay } from \"@mnemopay/sdk\";\n\n// Via MnemoPay.create — { type: \"postgres\" } (alias of \"neon\")\nconst agent = await MnemoPay.create({\n  agentId: \"agent-1\",\n  persist: { type: \"postgres\", url: process.env.DATABASE_URL! },\n});\n\n// Or construct the adapter directly\nimport { PostgresAdapter, postgresMigrationSql } from \"@mnemopay/sdk/recall/postgres\";\nconst adapter = new PostgresAdapter({ url: process.env.DATABASE_URL! });\n```\n\nThe schema (a `vector(384)` column + HNSW cosine index) is auto-created on the\nfirst write. To manage it with your own migration tool instead, run the DDL\nfrom `postgresMigrationSql(table?, dimensions?)` and pass `skipBootstrap: true`.\nRequires the optional peer dep: `npm install pg`.\n\n## Reputation Streaks & Badges\n\nAgents earn trust over time. Consecutive successful settlements build streaks that unlock badges and reduce fees.\n\n```ts\nconst rep = await agent.reputation();\nconsole.log(rep.streak);\n// → { currentStreak: 47, bestStreak: 312, streakBonus: 0.094 }\n\nconsole.log(rep.badges);\n// → [\n//   { id: \"first_settlement\", name: \"First Settlement\", earnedAt: 1712700000000 },\n//   { id: \"streak_50\", name: \"Streak Master\", earnedAt: 1712900000000 },\n//   { id: \"volume_10k\", name: \"High Roller\", earnedAt: 1713100000000 },\n// ]\n```\n\n| Badge | Requirement |\n|---|---|\n| First Settlement | Complete 1 settlement |\n| Streak 10 | 10 consecutive settlements |\n| Streak 50 | 50 consecutive settlements |\n| Volume $1K | $1,000+ total settled |\n| Volume $10K | $10,000+ total settled |\n| Perfect Record | 100+ settlements, 0 disputes |\n\nStreaks reset on refunds or disputes. Streak bonuses compound reputation up to +10%.\n\n## Hash-Chained Ledger\n\nEvery ledger entry links to the previous via SHA-256 hash chain. If any entry is modified, the chain breaks and `verify()` catches it instantly.\n\n```ts\nconst summary = agent.ledger.verify();\nconsole.log(summary.chainValid);     // true\nconsole.log(summary.chainIntegrity); // 1.0 (100% of links verified)\n```\n\nCombined with Merkle integrity on memories and HMAC on transactions, MnemoPay gives you three independent tamper-detection systems.\n\n## Payments (cent-precise double-entry)\n\n- **Double-entry bookkeeping** — every debit has a credit, always balances to zero\n- **Escrow flow** — charge -> hold -> settle -> refund (same shape as Stripe/Square)\n- **Volume-tiered fees** — 1.9% / 1.5% / 1.0% based on cumulative volume\n- **3 payment rails** — Paystack (Africa), Stripe (global), Lightning (BTC)\n- **Cent-precise integer math** — stress-tested with 200,000 transactions across 50 concurrent agents, zero drift\n\n## Identity (KYA Compliance)\n\n- **Cryptographic identity** — HMAC-SHA256 keypairs, replay protection\n- **Capability tokens** — scoped permissions with spend limits\n- **Counterparty whitelists** — restrict who the agent can transact with\n- **Kill switch** — revoke all tokens instantly\n\n## Fraud Detection (ML-grade)\n\n- **Velocity checks** — per-minute/hour/day limits\n- **Isolation Forest** — unsupervised ML anomaly detection\n- **Geo-enhanced** — country tracking, rapid-hop detection, OFAC sanctions\n- **Adaptive engine** — asymmetric AIMD, anti-gaming, circuit breaker, PSI drift detection\n\n## Multi-Agent Commerce\n\n- **CommerceEngine** — autonomous shopping with mandates, escrow, approval callbacks\n- **MnemoPayNetwork** — register agents, execute deals, shared memory context\n- **Supply chains** — 10-step agent chains, 100-agent marketplaces, all tested\n\n---\n\n## Claude Agent SDK integration\n\nTwo primitives built specifically for the Claude Agent SDK pattern where an Opus orchestrator spawns Sonnet/Haiku subagents.\n\n### 1-hour prompt cache on recall results\n\nWhen you feed MnemoPay recall into a Claude system prompt, use `formatForClaudeCache()` to emit a content block with `cache_control: { type: \"ephemeral\", ttl: 3600 }`. The Anthropic API caches that prefix for up to 1 hour; cache reads are billed at roughly 10% of the normal input rate. With stable recall prefixes and a warm 1h cache, users have observed savings in the typical range of 85-92% on the recall portion of input tokens — your actual results depend on call frequency and memory set stability.\n\n```ts\nimport MnemoPay, { formatForClaudeCache } from \"@mnemopay/sdk\";\nimport Anthropic from \"@anthropic-ai/sdk\";\n\nconst agent = MnemoPay.quick(\"my-agent\");\nconst anthropic = new Anthropic();\n\n// Option A: recall() directly returns a cache block\nconst cacheBlock = await agent.recall(\"user preferences\", 10, {\n  formatForClaudeCache: true,\n});\n\n// Option B: convert an existing memory array (no extra recall call)\nconst memories = await agent.recall(\"user preferences\", 10);\nconst cacheBlock2 = MnemoPay.formatForClaudeCache(memories);\n// OR: formatForClaudeCache(memories) from the module directly\n\nconst response = await anthropic.messages.create({\n  model: \"claude-opus-4-7\",\n  max_tokens: 1024,\n  system: [\n    { type: \"text\", text: \"You are a helpful assistant.\", cache_control: { type: \"ephemeral\" } },\n    cacheBlock,  // ← MnemoPay recall cached for 1 hour\n  ],\n  messages: [{ role: \"user\", content: userMessage }],\n});\n```\n\nThe serialized text is sorted by memory id so identical memory sets produce byte-identical output — required for the cache prefix to hit on subsequent turns.\n\n### Per-subagent cost attribution\n\nTrack which subagent in a multi-agent pipeline spent how much — recorded as double-entry ledger pairs so it stays audit-clean.\n\n```ts\nimport MnemoPay, { SubagentCostTracker } from \"@mnemopay/sdk\";\n\nconst orchestrator = MnemoPay.quick(\"orchestrator\");\n\n// After each Claude API call, record the cost:\norchestrator.subagentCosts.attributeSubagentCost({\n  parentAgentId: \"orchestrator\",\n  subagentId: \"researcher-1\",\n  subagentRole: \"researcher\",\n  modelId: \"claude-sonnet-4-6\",\n  inputTokens: 5000,\n  outputTokens: 2000,\n  cacheReadTokens: 8500,   // tokens served from the 1h recall cache\n  cacheWriteTokens: 500,\n  cacheWriteTtl: \"1h\",\n});\n\n// At end of pipeline, get breakdown ordered by cost:\nconst breakdown = orchestrator.subagentCosts.subagentCostBreakdown(\"orchestrator\");\n// → [{ subagentId, subagentRole, modelId, totalCostUsd, cacheSavingsUsd, ... }]\n\nconst totalSaved = orchestrator.subagentCosts.totalCacheSavings(\"orchestrator\");\n```\n\nPricing table used: 2026 Anthropic list rates (Opus 4.7 $5/$25/M, Sonnet 4.6 $3/$15/M, Haiku 4.5 $1/$5/M; cache reads 0.1×, 1h writes 2×). Update `MODEL_PRICING` in `src/subagent-cost.ts` if rates change.\n\nSee `docs/agent-sdk-guide.md` for a full integration walkthrough.\n\n---\n\n## Payment Rails\n\nEvery rail implements the same `PaymentRail` interface — `createHold` / `capturePayment` / `reversePayment`. Swap rails without touching agent code.\n\n| Rail | Coverage |\n|---|---|\n| `StripeRail` | Cards (USD, EUR, GBP, +) |\n| `PaystackRail` | Africa (NGN, GHS, ZAR, KES) |\n| `LightningRail` | BTC sub-cent micropayments |\n| `StripeMPPRail` | Crypto deposits on Tempo via Stripe MPP |\n| `X402Rail` | USDC on Base via EIP-3009 transferWithAuthorization |\n| `GoogleAP2Rail` | AP2 v0.2 mandate-driven settlement (FIDO Alliance) |\n\n```ts\nimport {\n  PaystackRail, StripeRail, LightningRail,\n  StripeMPPRail, X402Rail, GoogleAP2Rail,\n} from \"@mnemopay/sdk\";\n\nconst paystack  = new PaystackRail(process.env.PAYSTACK_SECRET_KEY!);\nconst stripe    = new StripeRail(process.env.STRIPE_SECRET_KEY!);\nconst lightning = new LightningRail(LND_URL, MACAROON);\n\nconst mpp   = new StripeMPPRail(process.env.STRIPE_SECRET_KEY!);\nconst x402  = new X402Rail({ signer: yourEip3009Signer });   // bring-your-own crypto\nconst ap2   = new GoogleAP2Rail({ mandate, endpoint, signer });\n\nconst agent = MnemoPay.quick(\"my-agent\", { paymentRail: paystack });\n```\n\n### Stripe — real card charges with saved customers\n\nEnd-to-end flow for charging a user's saved card without a browser handoff:\n\n```ts\nimport MnemoPay, { StripeRail } from \"@mnemopay/sdk\";\n\nconst rail = new StripeRail(process.env.STRIPE_SECRET_KEY!);\nconst agent = MnemoPay.quick(\"agent-1\", { paymentRail: rail });\n\n// 1. Create a Stripe customer (one-time, persist cus_... to your DB)\nconst { customerId } = await rail.createCustomer(\"user@example.com\", \"Jerry O\");\n\n// 2. Collect a card via Stripe.js: create a SetupIntent, return client_secret\n//    to the browser, let Stripe Elements confirm it. You receive pm_... from\n//    the webhook or confirmation callback. Save it alongside the customer.\nconst { clientSecret } = await rail.createSetupIntent(customerId);\n// → hand clientSecret to frontend, get back paymentMethodId after confirm\n\n// 3. Charge the saved card later, off-session, no user interaction needed\nconst tx = await agent.charge(25, \"Monthly API access\", undefined, {\n  customerId,\n  paymentMethodId: \"pm_saved_from_step_2\",\n  offSession: true,\n});\n\n// 4. Settle (captures the hold) or refund (releases it)\nawait agent.settle(tx.id);\n```\n\nPaystack supports the same pattern via `authorizationCode`:\n\n```ts\nconst tx = await agent.charge(5000, \"NGN invoice\", undefined, {\n  email: \"customer@example.com\",\n  authorizationCode: \"AUTH_abc123\", // from an earlier Paystack transaction\n});\n```\n\n---\n\n## MCP Server\n\n```bash\nnpx @mnemopay/sdk init\n# or\nclaude mcp add mnemopay -s user -- npx -y @mnemopay/sdk\n```\n\n**Default tool group: `essentials` (14 tools, ~1K tokens).** One of the\nlightest MCP servers you can install — MnemoPay only loads memory + wallet +\ntx by default so it doesn't tax your agent's context budget.\n\n- `memory`: `remember`, `recall`, `forget`, `reinforce`, `consolidate`\n- `wallet`: `balance`, `profile`, `history`, `logs`\n- `tx`: `charge`, `settle`, `refund`, `dispute`, `receipt_get`\n\nNeed more? Opt in explicitly:\n\n```bash\nnpx @mnemopay/sdk --tools=all       # all 95 tools\nnpx @mnemopay/sdk --tools=agent     # essentials + commerce + hitl + payments + webhooks\nnpx @mnemopay/sdk --tools=reputation  # Agent Reputation Scoring only\n```\n\nGroups: `memory`, `wallet`, `tx`, `commerce`, `hitl`, `payments`, `webhooks`,\n`reputation`, `security`, `governance`, `identity`, `skills`, `spatial`,\n`agent_os`, `organization_admin`, `operator`. Aliases: `essentials` (default),\n`agent`, `all`. Also settable via `MNEMOPAY_TOOLS` env var.\n\n> **Breaking change in v1.3.0:** default was `all`, now `essentials`. If you\n> relied on commerce/hitl/webhooks/fico/security being available without a\n> flag, pass `--tools=all` or `--tools=agent`. See [CHANGELOG](./CHANGELOG.md).\n\n---\n\n## Middleware\n\nDrop-in proxies that make recall invisible: every chat call auto-injects the\ntop memories as system context and stores the exchange afterward. Same\n`Middleware.wrap(client, agent)` shape across every provider.\n\n```ts\n// OpenAI\nimport { mnemoPayMiddleware } from \"@mnemopay/sdk/middleware/openai\";\n\n// Anthropic\nimport { mnemoPayMiddleware } from \"@mnemopay/sdk/middleware/anthropic\";\n\n// Gemini\nimport { GeminiMiddleware } from \"@mnemopay/sdk/middleware/gemini\";\n\n// Cohere (v2 chat API)\nimport { CohereMiddleware } from \"@mnemopay/sdk/middleware/cohere\";\nconst cohere = CohereMiddleware.wrap(new CohereClientV2({ token }), agent);\n\n// Mistral\nimport { MistralMiddleware } from \"@mnemopay/sdk/middleware/mistral\";\nconst mistral = MistralMiddleware.wrap(new Mistral({ apiKey }), agent);\n\n// LangGraph\nimport { mnemoPayTools } from \"@mnemopay/sdk/langgraph\";\n```\n\n---\n\n## Architecture\n\nFull stack diagram and module map: [`docs/architecture.md`](./docs/architecture.md).\n\n```\n┌──────────────────────────────────────────────────────────────────┐\n│                       MnemoPay SDK                                │\n│              Governance · Memory · Payments · Identity            │\n├─────────────────────────────────────────────────────────────────┤\n│ GOVERNANCE  Charter · FiscalGate · Article 12 · MerkleAudit      │\n│             mission scope, budget enforcement, audit bundles     │\n├──────────┬──────────┬───────────┬─────────────────────────────────┤\n│  Memory  │ Payments │ Identity  │  Agent Reputation Scoring       │\n│          │          │           │  300-850, 5-component           │\n│ remember │ charge   │ KYA       ├─────────────────────────────────┤\n│ recall   │ settle   │ tokens    │  Behavioral Finance             │\n│ reinforce│ refund   │ perms     │  prospect theory, nudges        │\n│ forget   │ dispute  │ killswitch├─────────────────────────────────┤\n│          │          │           │  Anomaly Detection              │\n│          │          │           │  EWMA + fingerprinting          │\n├──────────┴──────────┴───────────┼─────────────────────────────────┤\n│     Double-Entry Ledger         │  Merkle Integrity               │\n│  debit + credit = always zero   │  tamper-evident memory          │\n├─────────────────────────────────┼─────────────────────────────────┤\n│     Fraud Guard (ML-grade)      │  Canary Honeypots               │\n│  velocity + geo + adaptive      │  compromise detection           │\n├─────────────────────────────────┴─────────────────────────────────┤\n│ SPATIAL    GridStamp adapter — proof-of-presence for embodied      │\n│            agents (drones, robots). Loose-coupled, fail-closed.    │\n├──────────────────────────────────────────────────────────────────┤\n│ RAILS  Stripe · Paystack · Lightning · StripeMPP · x402 · AP2    │\n│        same PaymentRail interface — drop-in swap, no agent diff   │\n└──────────────────────────────────────────────────────────────────┘\n```\n\n---\n\n## Module stability\n\nMnemoPay follows semver. Stability tiers tell you how much a module's public API may shift before 2.0 — see [VERSIONING.md](VERSIONING.md) for the full contract.\n\n| Module | Import | Stability | Notes |\n|---|---|---|---|\n| Memory / recall | `@mnemopay/sdk/recall` | **Stable** | remember · recall · reinforce · forget |\n| Payments | `@mnemopay/sdk` | **Stable** | charge · settle · refund · dispute, cent-precise |\n| Double-entry ledger | `@mnemopay/sdk` | **Stable** | debit+credit=0, hash-chained |\n| Identity (KYA) | `@mnemopay/sdk/identity` | **Stable** | Ed25519, capability tokens, killswitch |\n| Agent Reputation Scoring | `@mnemopay/sdk` | **Stable** | 5-component, 300–850 |\n| Fraud / anomaly | `@mnemopay/sdk` | **Stable** | velocity, geo, EWMA, canaries |\n| Payment rails (Stripe/Paystack/Lightning) | `@mnemopay/sdk/rails` | **Stable** | one `PaymentRail` interface |\n| Governance — policy | `@mnemopay/sdk/governance/policy` | **Stable** | sub-second `evaluateAction` |\n| Governance — audit chain | `@mnemopay/sdk/governance/audit-chain` | **Stable** | Merkle event stream, Article 12 export |\n| Governance — charter / Article 12 | `@mnemopay/sdk/governance` | **Stable** | mission scope + EU AI Act bundles |\n| Governance — approval routing | `@mnemopay/sdk/governance/approval` | **Beta** | HITL queue + `routeVerdict` |\n| Governance — risk taxonomy | `@mnemopay/sdk/governance/risk` | **Beta** | Low→Critical ladder + preset policy |\n| Governance — action ledger | `@mnemopay/sdk/governance/action-ledger` | **Beta** | typed \"what did the agent do\" record |\n| MnemoSkills (governed skills) | `@mnemopay/sdk/skills` | **Beta** | versioned, permissioned, billable capabilities — see [examples/08-invoice-collector.ts](./examples/08-invoice-collector.ts) |\n| Spatial / GridStamp | `@mnemopay/sdk/governance` | **Beta** | proof-of-presence, loose-coupled, fail-closed |\n| Rails — x402 / AP2 / StripeMPP | `@mnemopay/sdk/rails` | **Alpha** | emerging agent-payment standards |\n| Swarm | `@mnemopay/sdk/swarm` | **Stable** | `spawn` / `gather` / `recombine` / `stop`; 27 unit tests |\n| Swarm CLI | `@mnemopay/swarm` | **Stable** | catalog list/install/demo |\n| BrowserSwarm / voice | `@mnemopay/sdk/swarm/browser` | **Stable** | optional `@mnemopay/browser` peer |\n\n---\n\n## Testing\n\n```bash\nnpm test    # full test suite across 12 files\n```\n\n- `core.test.ts` — memory, payments, lifecycle, reputation scoring, behavioral, Merkle, EWMA, canaries, streaks, badges\n- `fraud.test.ts` — velocity, anomaly, fees, disputes, replay detection\n- `geo-fraud.test.ts` — geo signals, trust, sanctions\n- `identity.test.ts` — KYA, tokens, permissions\n- `production-100k.test.ts` — 100K operations, 10 concurrent agents, hash-chain verification, zero drift\n- `stress-200k.test.ts` — 200K real-world stress: 50 agents, burst traffic, race conditions, refund storms, memory leak detection\n- `ledger.test.ts` — double-entry, reconciliation\n- `network.test.ts` — multi-agent, deals, supply chains\n- `paystack.test.ts` — rail, webhooks, transfers\n- `stress.test.ts` — 1000-cycle precision, parallel ops\n- `recall.test.ts` — semantic search, decay, reinforcement\n\n---\n\n## License\n\nApache License 2.0 — see [LICENSE](LICENSE).\n\nCopyright 2026 J&B Enterprise LLC.\n\n---\n\n## Third-party attributions\n\nThe entity-observation write-path in `src/recall/observations.ts` (per-entity consolidated summaries, debounced regeneration, session-spanning rollups) is derived from [vectorize-io/hindsight](https://github.com/vectorize-io/hindsight) (MIT, Copyright (c) 2025 Vectorize AI, Inc.). The full upstream notice is preserved in [NOTICE](NOTICE) and in the header of the ported file.\n\n---\n\n## Trademark and regulatory notices\n\n**Agent Reputation Scoring** is a trustworthiness scoring system **for autonomous software agents**, not for consumer credit reporting. It does not produce a consumer report as defined by the Fair Credit Reporting Act (FCRA) and is not regulated under the FCRA. MnemoPay is not a consumer reporting agency.\n\nMnemoPay is not a bank, money transmitter, or insurer, and does not hold customer deposits. Payments are settled through third-party payment rails (Stripe, Paystack, Lightning Network) — MnemoPay is software that connects to those rails on behalf of developers, not a financial institution.\n\n\"FICO\" is a registered trademark of Fair Isaac Corporation. MnemoPay and its Agent Reputation Scoring module are not affiliated with, endorsed by, or derived from Fair Isaac Corporation. The `AgentCreditScore` and `AgentFICO` export names are deprecated aliases kept for backward compatibility with earlier beta releases and will be removed in a future major version.\n\n---\n\nBuilt by [Jeremiah Omiagbo](https://github.com/mnemopay)\n",
  "bytes": 39389,
  "sha": "27f65b69201134d4cec9052b276facb70a7137e8f809fc52704ca2e7729c2cb5",
  "repo_slug": "mnemopay/mnemopay-sdk",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_io_github_mnemopay_sdk_f966a095/readme"
}