Skip to content

mkmkkkkk/paysentry

Repository files navigation

PaySentry

Payment control plane for AI agents — spending limits, circuit breakers, and audit trails for x402, MCP, and autonomous agent payments.

npm npm License: MIT CI

Your agent just authorized $500 to an API endpoint. Was that intentional?


The Problem

AI agents are spending real money with zero governance:

  • x402 settlement failures drain wallets silently — facilitator takes payment, service returns 500 (coinbase/x402#1062)
  • No spending limits — one prompt injection = unlimited spend
  • No audit trail — "which agent spent $2,400 last Tuesday?"
  • Retry storms cause duplicate payments — failed settlements trigger retries with no dedup (coinbase/x402#808)
  • No circuit breakers — one flaky facilitator cascades into system-wide failures (coinbase/x402#803)

PaySentry is the missing layer between your agents and their wallets.


See it in action

PaySentry Demo — AI agent payments being allowed, blocked, and rate limited in real-time

Text version (if SVG doesn't render)
  PaySentry Demo — AI Agent Payment Controls
  ══════════════════════════════════════════════════

  Policy: Max $100/tx | Approval above $40 | Daily $500 | 5 tx/min
  Agent:  agent-research-01  |  Balance: $10000.00

  [1/5] $25.00  → api.openai.com      ✅ ALLOWED
  [2/5] $45.00  → anthropic.com       ⚠️ REQUIRES APPROVAL
  [3/5] $150.00 → sketchy-api.xyz     ❌ BLOCKED (above $100 limit)
  [4/5] $30.00  → api.openai.com      ✅ ALLOWED + 🔔 repeat recipient alert
  [5/5] 6 rapid payments              ❌ RATE LIMITED (5 tx/min)

  Summary:
    Allowed: 4  ($65.00)
    Pending: 1  ($45.00)
    Blocked: 2  ($150.00 + rate limit)
    Alerts:  4  (large tx, rate spike)

Try it yourself:

npx paysentry-demo

Quick Start

npm install @paysentry/core @paysentry/control @paysentry/observe

Add spending limits in 5 lines

import { PolicyEngine, blockAbove, requireApprovalAbove, allowAll } from '@paysentry/control';

const engine = new PolicyEngine();

engine.loadPolicy({
  id: 'production' as PolicyId,
  name: 'Production Controls',
  enabled: true,
  rules: [
    blockAbove(1000, 'USDC'),           // Hard block above $1000
    requireApprovalAbove(100, 'USDC'),  // Human approval above $100
    allowAll(),                         // Allow everything else
  ],
  budgets: [
    { window: 'daily', maxAmount: 500, currency: 'USDC' },
    { window: 'monthly', maxAmount: 5000, currency: 'USDC' },
  ],
});

const result = engine.evaluate(transaction);
// result.action: 'allow' | 'deny' | 'require_approval' | 'flag'

x402 adapter — 3 lines to protect your x402 server

npm install @paysentry/x402
import { PaySentryX402Adapter } from '@paysentry/x402';
import { PolicyEngine } from '@paysentry/control';
import { SpendTracker } from '@paysentry/observe';

const adapter = new PaySentryX402Adapter(
  { policyEngine: new PolicyEngine(), spendTracker: new SpendTracker() },
  { circuitBreaker: { failureThreshold: 5, recoveryTimeoutMs: 30_000 } },
);

// Registers all 6 lifecycle hooks: onBeforeVerify, onAfterVerify,
// onVerifyFailure, onBeforeSettle, onAfterSettle, onSettleFailure
adapter.withLifecycleHooks(yourX402Server);

What PaySentry Does

Problem Solution Package
Agents spend without limits Declarative spending policies, budget caps, approval chains @paysentry/control
No visibility into agent spend Real-time transaction tracking, analytics, anomaly detection @paysentry/observe
x402 settlement failures lose money Circuit breakers + retry classification per facilitator @paysentry/x402
No audit trail for compliance Immutable provenance chain: intent -> policy -> execution -> settlement @paysentry/protect
Can't test without real money Mock x402, ACP, and AP2 endpoints with pre-built failure scenarios @paysentry/sandbox

Packages

Package Version Description
@paysentry/core npm Core types, utilities, and shared infrastructure
@paysentry/observe npm Payment tracking, analytics, budget alerts, anomaly detection
@paysentry/control npm Policy engine — rules, budgets, approval chains, middleware
@paysentry/protect npm Dispute resolution — provenance, disputes, automated recovery
@paysentry/sandbox npm Mock payment environment — x402, ACP, AP2 with 9 test scenarios
@paysentry/x402 npm x402 protocol adapter — lifecycle hooks, circuit breakers
@paysentry/mcp 1.0.0 MCP server — 10 tools for AI agent payment control
@paysentry/a2a 1.0.0 Agent-to-agent payments — intents, mandates, escrow
@paysentry/dashboard 1.0.0 JSON API + SSE event stream for monitoring

Examples

Real-time spend tracking with alerts

import { SpendTracker, SpendAnalytics, SpendAlerts } from '@paysentry/observe';
import { createTransaction, type AgentId } from '@paysentry/core';

const tracker = new SpendTracker();
const analytics = new SpendAnalytics(tracker);
const alerts = new SpendAlerts(tracker);

// Alert when daily spend exceeds 80% of $500 budget
alerts.addRule({
  id: 'daily-budget',
  name: 'Daily USDC Budget',
  type: 'budget_threshold',
  severity: 'warning',
  enabled: true,
  config: {
    type: 'budget_threshold',
    threshold: 500,
    currency: 'USDC',
    windowMs: 86400000,
    alertAtPercent: 0.8,
  },
});

alerts.onAlert((alert) => {
  slack.send(`[${alert.severity}] ${alert.message}`);
});

// Record transactions as they happen
const tx = createTransaction({
  agentId: 'research-bot' as AgentId,
  recipient: 'https://api.openai.com/v1/chat',
  amount: 0.05,
  currency: 'USDC',
  purpose: 'GPT-4 market analysis',
  protocol: 'x402',
});
tx.status = 'completed';
tracker.record(tx);

const report = analytics.getAgentAnalytics('research-bot' as AgentId);
// report.spendByCurrency, report.topRecipients, report.anomalies

Express/Fastify middleware

import { createPolicyMiddleware } from '@paysentry/control';

app.use('/pay', createPolicyMiddleware({
  engine,
  approvalHandler: async (tx) => {
    return await slack.requestApproval(tx);
  },
}));

Payment sandbox for testing

import { MockX402, MockACP, ALL_SCENARIOS } from '@paysentry/sandbox';

const x402 = new MockX402({ latencyMs: 10, failureRate: 0.1 });
const result = await x402.processPayment(transaction);

// 9 pre-built scenarios: overspend, timeout, dispute, multi-protocol, etc.
console.log(ALL_SCENARIOS.map(s => s.name));

MCP server for AI agents

npm install @paysentry/mcp
import { createPaySentryMcpServer } from '@paysentry/mcp';

const { server } = createPaySentryMcpServer({
  agentId: 'my-agent',
  dailyBudget: 500,
  perTransactionLimit: 100,
});

// Agents get 10 tools: pay, check_balance, transaction_history,
// discover_capabilities, list_policies, create_policy, evaluate_payment,
// file_dispute, get_audit_trail, get_alerts

// Add to Claude Desktop config:
// { "mcpServers": { "paysentry": { "command": "npx", "args": ["paysentry-mcp"] } } }

Agent-to-agent payments

import { PaymentIntentManager, MandateManager, EscrowManager } from '@paysentry/a2a';
import { MemoryStorage } from '@paysentry/core';

const storage = new MemoryStorage();
const intents = new PaymentIntentManager(storage);
const mandates = new MandateManager(storage);
const escrow = new EscrowManager(storage);

// Agent A proposes payment to Agent B
const intent = intents.propose({
  fromAgent: 'agent-a' as AgentId,
  toAgent: 'agent-b' as AgentId,
  amount: 50,
  currency: 'USDC',
  purpose: 'data analysis',
});

// Agent B accepts
intents.accept(intent.id, 'agent-b' as AgentId);

// Standing mandates for recurring payments
const mandate = mandates.create({
  grantorAgent: 'agent-a' as AgentId,
  granteeAgent: 'agent-b' as AgentId,
  maxAmount: 100,
  currency: 'USDC',
  maxFrequency: 10,
  windowMs: 86400000, // daily
  expiresAt: new Date(Date.now() + 30 * 86400000).toISOString(),
});

See examples/ for complete runnable demos.

Run the E2E example

The full x402 payment flow with policy enforcement, circuit breaker, spend tracking, and alerts:

npm install && npm run build
npx tsx examples/05-x402-e2e.ts

Output shows allow/block/alert decisions for 5 scenarios:

  1. Small payment ($5) — allowed and settled
  2. Medium payment ($75) — blocked by approval policy
  3. Large payment ($1500) — blocked by budget
  4. Multiple payments — budget threshold alert at 80%
  5. Facilitator failures — circuit breaker opens

Architecture

              ┌──────────────────────────────────────────┐
              │            Your AI Agent                  │
              └──────────────────┬───────────────────────┘
                                 │
              ┌──────────────────v───────────────────────┐
              │          MCP Server (10 tools)            │
              │  pay · balance · history · discover       │
              │  policies · evaluate · disputes · alerts  │
              └──────────────────┬───────────────────────┘
                                 │
              ┌──────────────────v───────────────────────┐
              │       PaySentry Control Plane             │
              │                                          │
              │  OBSERVE    CONTROL    PROTECT    A2A     │
              │  tracking   policies   provenance intents │
              │  alerts     budgets    disputes   mandate │
              │  analytics  approval   recovery   escrow  │
              └────┬──────────┬──────────┬──────────┬────┘
                   │          │          │          │
              ┌────v───┐ ┌───v────┐ ┌───v────┐ ┌───v────┐
              │  x402  │ │  ACP   │ │  AP2   │ │Dashboard│
              │HTTP 402│ │Stripe/ │ │Agent-  │ │JSON API │
              │Protocol│ │Commrc  │ │to-Agent│ │SSE Feed │
              └────────┘ └────────┘ └────────┘ └────────┘

Roadmap

  • Core spending policies and budget enforcement
  • Real-time spend tracking and anomaly detection
  • Dispute resolution and automated recovery
  • Multi-protocol payment sandbox (x402, ACP, AP2)
  • x402 protocol adapter with circuit breakers
  • MCP payment server (10 tools: pay, balance, history, discover, policy CRUD, disputes, provenance, alerts)
  • Agent-to-agent payment primitives (intents, mandates, escrow, agent registry)
  • Dashboard API + SSE event stream for real-time monitoring
  • AP2 / Visa TAP protocol adapters

Development

npm install          # Install dependencies
npm run build        # Build all packages
npm run typecheck    # Type check
npm test             # Run tests
npm run lint         # Lint

Contributing

Contributions welcome. Open an issue first for major changes.

  1. Fork the repo
  2. Create a feature branch (git checkout -b feat/my-feature)
  3. Write tests for new functionality
  4. Ensure npm test and npm run typecheck pass
  5. Open a PR against main

License

MIT

About

The missing control plane for AI agent payments. Observe, control, protect, and test agent spending across x402, ACP, AP2, and Visa TAP.

Topics

Resources

License

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors