Menu

Explorer & Settings

Tempo Explorer Submit Project
Back to all projects

agentic-payment-mcp

by diegosilva-05 · Updated 4 months ago

MCP server for agentic payment validation — KYA identity verification, deterministic fraud scoring, and capture pre-flight for agentic commerce platforms

In the AI payments ecosystem

agentic-payment-mcp is an early-stage Python project in the AI payments / x402 ecosystem, focused on agentic-ai, agentic-commerce, fintech, mcp. It currently has 0 GitHub stars and 0 forks, and sits alongside related tools like mcp-dev-latam, sardis, agentpay, awesome-agentic-commerce, tdm-integration-kit, TDM-Agent-Integration-Kit.

README.md View on GitHub →

Agentic Payment Validation — MCP Server

Prototype — Python 3.11 · MCP SDK · Pydantic v2 · pytest-asyncio

Problem Statement

As payments evolve from transactional services into intelligent agentic experiences, agentic commerce platforms face a structural gap: shopping agents (LLMs orchestrating purchase flows) need to initiate payment operations, but acquiring infrastructure was designed for human-driven, session-authenticated requests, not autonomous AI clients with delegated authority. This MCP server implements the validation layer that bridges that gap — enforcing Know-Your-Agent (KYA) identity binding, deterministic fraud signal scoring, and capture pre-flight governance before any payment request reaches the SEP (Single Entry Point). It ensures that AI-initiated payment operations satisfy the same identity, risk, and regulatory requirements as human-initiated ones, without adding a dependency on LLM inference to the authorization critical path.


Architecture

┌─────────────────────────────────────────────────────────────────────────────┐
│                            AGENTIC COMMERCE FLOW                            │
│                                                                             │
│   ┌────────────────┐     MCP Protocol     ┌─────────────────────────────┐   │
│   │ Shopping Agent │ ◄──────────────────► │   MCP Server                │   │
│   │  (LLM client)  │   stdio / HTTP+SSE   │   (this project)            │   │
│   └────────────────┘                      │                             │   │
│          │                                │  1. validate_agent          │   │
│          │  Orchestrate tool calls        │     KYA gate (15 ms)        │   │
│          │  Select next step based        │                             │   │
│          │  on tool output                │  2. check_fraud_signals     │   │
│          │                                │     Risk scoring (25 ms)    │   │
│          │                                │                             │   │
│          │                                │  3. capture_transaction     │   │
│          │                                │     Pre-flight (10 ms)      │   │
│          │                                └────────────┬────────────────┘   │
│          │                                             │                    │
│          │                                             │ SEP-formatted      │
│          │                                             │ capture payload    │
│          │                                             │ (delegated)        │
│          │                                             ▼                    │
│          │                                ┌─────────────────────────────┐   │
│          │                                │  Acquirer SEP Layer         │   │
│          │                                │  (Acquiring Infrastructure) │   │
│          │                                │  · Verifiable Intent proof  │   │
│          │                                │  · Card network routing     │   │
│          └────────────────────────────────│  · Settlement execution     │   │
│                                           └─────────────────────────────┘   │
│                                                                             │
│  ▸ The LLM orchestrates tool selection. No LLM is invoked inside tools.     │
│  ▸ Tools are deterministic, auditable, and latency-bounded.                 │
│  ▸ Session state is server-side. The client cannot skip validation steps.   │
└─────────────────────────────────────────────────────────────────────────────┘

Tool sequence and latency budget

Step Tool Budget Gate
1 validate_agent_identity 15 ms Platform allow-list · token format · agent-merchant registry · scope intersection
2 check_fraud_signals 25 ms Requires step 1. Amount thresholds · cross-border · device · velocity · recurring discount
3 capture_transaction 10 ms Requires steps 1 + 2. KYA status · fraud clearance · amount consistency · idempotency
Total SLA 50 ms Hard constraint — no LLM inference in path

Design Decisions

1. No LLM in the authorization critical path. Tool implementations are rule-based and execute in microseconds. The <50 ms SLA is incompatible with LLM inference (typically 200–2000 ms), and compliance audit trails require decisions that are reproducible and attributable — not probabilistic. The LLM operates as the orchestrator above the MCP layer, not inside it.

2. KYA enforcement is server-side, not client-trust. The SessionRegistry tracks validation state per session_id on the server. check_fraud_signals and capture_transaction both gate on a recorded KYA pass — a client cannot fabricate a valid session by skipping validate_agent_identity. In production this registry is Redis-backed and shared across server instances.

3. The capture tool is read-only by design — this is the architecture, not a TODO. This server is the validation pre-flight layer. It constructs a SEP-formatted payload with requires_verifiable_intent: true, but never POSTs to acquiring infrastructure. Write execution is delegated to the SEP, which validates cryptographic proof of consumer intent (Mastercard Agent Pay / Visa Intelligent Commerce) before card network routing. Keeping the boundary explicit prevents accidental write-path expansion.

4. Input hashing for PII compliance. Audit records store the SHA-256 digest of the canonicalized input dict, never raw field values. This preserves correlation capability (same logical input always produces the same hash) without exposing customer PII in the audit trail — a requirement for both PCI-DSS and GDPR compliance in cross-border payment flows.

5. Deterministic, rule-based fraud scoring. Five rules with explicit score contributions and factor decomposition. The MCP tool contract (FraudSignalResult with risk_factors, risk_score, risk_level, recommended_action) is independent of the backing scorer. In production the rule engine is replaced by a pre-trained ML model served from a dedicated inference endpoint — the contract does not change.

6. Pydantic v2 schemas as the tool contract. AgentValidationRequest, FraudSignalRequest, and CaptureRequest serve dual purpose: runtime input validation and JSON Schema generation for list_tools(). Every field description is written for LLM consumption — the schema instructs the agent what to send without requiring separate documentation.

7. MCP-layer idempotency. LLM agents retry tool calls under uncertainty. An in-process _seen_idempotency_keys set (production: Redis SET NX) deduplicates capture requests before they reach the SEP. This prevents a double-capture on network ambiguity — a failure mode specific to agentic flows that human-driven payment UIs do not produce.


Critical Constraints

Constraint Value
Total authorization latency SLA < 50 ms
KYA budget 15 ms
Fraud scoring budget 25 ms
Capture pre-flight budget 10 ms
Maximum transaction amount 50 000.00 (settlement currency)
Supported currencies USD, EUR, MXN, BRL, GBP
Supported agent platforms openai, anthropic, google, cohere
Risk score range 0 (safe) → 100 (certain fraud)
Write access on capture tool Disabled — by design
Audit record PII SHA-256 hash only, never raw input

Local Setup

# Install (Python 3.11+ required)
git clone https://github.com/YOUR_USERNAME/agentic-payment-mcp.git
cd agentic-payment-mcp
pip install -e ".[dev]"

# Run the test suite
pytest -v

# Start the MCP server (stdio transport)
python -m src.server

The server speaks MCP over stdio and is compatible with any MCP client (Claude Desktop, custom agent runtimes, mcp CLI).


Project Structure

src/
├── server.py               # MCP server — tool registration, SessionRegistry, call_tool router
├── config.py               # Centralized constants (SLA budgets, risk thresholds, allow-lists)
├── tools/
│   ├── validate_agent.py   # KYA tool — platform check, token format, registry lookup, scopes
│   ├── check_fraud.py      # Fraud tool — 5-rule scoring engine, band mapping, session gate
│   └── capture_transaction.py  # Capture tool — 4-precondition check, SEP payload construction
├── schemas/
│   ├── agent.py            # AgentValidationRequest / AgentValidationResult
│   ├── fraud.py            # FraudSignalRequest / FraudSignalResult / RiskFactor
│   └── transaction.py      # CaptureRequest / CapturePreflightResult
└── audit/
    └── logger.py           # AuditLogger — SHA-256 input hashing, structured JSON emission

tests/
├── conftest.py             # Fixtures: fresh SessionRegistry, AuditLogger, idempotency cleanup
├── test_validate_agent.py  # 6 tests — happy path, platform/token/status failures, scope hard-fail
├── test_check_fraud.py     # 5 tests — approve path, KYA gate, cross-border, recurring, latency
└── test_capture_transaction.py  # 6 tests — full flow, KYA/fraud gates, amount mismatch, idempotency

What This Does Not Do (and Why)

Does not process real payments. This is the validation pre-flight layer. Real payment execution requires acquirer SEP integration, card network certification (Mastercard, Visa), and PCI DSS Level 1 compliance infrastructure.

Does not implement cryptographic Verifiable Intent. Token validation and the requires_verifiable_intent flag are structurally present but mocked. Production requires integration with Mastercard Agent Pay and Visa Intelligent Commerce SDKs for consumer intent proof chains.

Does not use ML for fraud scoring. The rule engine is a structurally accurate stand-in. The FraudSignalResult contract is identical to what a production ML scorer would return — the backing implementation is replaceable without changing the MCP interface.

Does not persist state across restarts. SessionRegistry is in-memory; audit logs are emitted to the logging subsystem only. Production requires Redis-backed session state and immutable audit log stores (AWS QLDB, Azure Immutable Blob Storage).

Does not implement multi-tenant isolation. Single-server prototype. Production requires tenant-scoped session namespacing, per-merchant rate limiting, and isolated audit log streams.


Stack

Component Choice Rationale
Runtime Python 3.11+ `str
MCP layer mcp SDK (official) Handles protocol framing, tool registration, stdio/SSE transport
Schemas Pydantic v2 model_json_schema() for LLM-facing JSON Schema; strict validation
Async anyio / asyncio MCP SDK requires async; all tool handlers are async def
Testing pytest + pytest-asyncio asyncio_mode = "auto" — no @pytest.mark.asyncio boilerplate

License

MIT

All Python libraries →