Skip to main content
Glama
presidio-v

presidio-hardened-x402-mcp

by presidio-v

presidio-hardened-x402-mcp

PyPI version Python GitHub release License: MIT CI OpenSSF Scorecard OpenSSF Best Practices

Pre-payment safety gate for x402 — agents call screen_payment_metadata(...), check_payment_policy(...), and check_payment_replay(...) before signing, catching PII, budget overruns, and duplicate payments before metadata or money leaves the agent host.

Part of the presidio-hardened-* toolkit family. Thin MCP (Model Context Protocol) adapter over the presidio-hardened-x402 library, pinned for parent 0.11.x compatibility (presidio-hardened-x402>=0.11.1,<0.12.0). The >=0.11.1 floor is a security floor, not a preference — it is the release that closed the percent-encoded PII redaction bypass.

Why this exists

x402 agentic payments routinely carry user-supplied free text — descriptions, memos, query-string parameters — straight through to merchants and facilitators. When an LLM agent generates that text, it can include PII the user never intended to share. Once the merchant logs it, retention is their decision, not yours.

This MCP server gives agents a small default-deny gate before payment leaves the agent host. Three tools expose the parent library's stable pre-payment controls: PII redaction, spending policy, and replay detection. They are designed to compose with payment-execution and endpoint-safety MCP servers (x402station, Coinbase x402, Sardis, ...), while newer parent-library surfaces — evidence-ref@1 verification, the v0.9.1 SLO broker, the v0.10.0 settlement-ref@1 treasury binding, and the v0.11.0 CapabilityEnforcer — stay in the Python library unless an MCP tool explicitly wraps them later.

Related MCP server: x402 Endpoint Trust

Install & configure

Requires Python ≥ 3.10. Distributed on PyPI; recommended invocation via uvx (no global install).

Claude Desktop / Claude Code

Add to ~/Library/Application Support/Claude/claude_desktop_config.json (macOS) or the equivalent on your platform:

{
  "mcpServers": {
    "presidio-x402": {
      "command": "uvx",
      "args": ["presidio-hardened-x402-mcp"]
    }
  }
}

Cursor / Windsurf / Continue

Same shape — every MCP host accepts command / args / env. See your editor's MCP-server docs for the config-file path.

Environment variables

All optional. Defaults give a zero-config in-process mode with no quota, no network, and no PII storage.

Variable

Purpose

Default

PRESIDIO_X402_MCP_MODE

regex (zero-setup) or nlp (needs [nlp] extra + a spaCy model)

regex

PRESIDIO_X402_MCP_MAX_PER_CALL_USD

Max USD per single payment (policy gate)

unset → no limit

PRESIDIO_X402_MCP_DAILY_LIMIT_USD

Max USD per rolling window (policy gate)

unset → no limit

PRESIDIO_X402_MCP_PER_ENDPOINT_JSON

Per-endpoint cap, e.g. '{"api.foo.com": 5.00}'

unset

PRESIDIO_X402_MCP_WINDOW_SECONDS

Rolling window for the daily limit

86400

PRESIDIO_X402_MCP_AGENT_ID

Label written into audit records

unset

PRESIDIO_X402_MCP_REPLAY_TTL

Fingerprint cache TTL (seconds)

300

PRESIDIO_X402_MCP_REDIS_URL

Use Redis for replay state instead of in-memory

unset

PRESIDIO_X402_MCP_AUDIT_PATH

Append-only JSON-L audit log path; omit to disable

unset

PRESIDIO_X402_MCP_LOG_LEVEL

DEBUG / INFO / WARNING / ERROR

INFO

PRESIDIO_X402_MCP_REMOTE_BASE_URL

Enable HTTP-proxy mode for tool 1 — see Modes. Must be https://; plain http:// is accepted only for loopback and otherwise refuses to start

unset

PRESIDIO_X402_MCP_REMOTE_API_KEY

API key for the remote screening service

unset

PRESIDIO_X402_FINGERPRINT_KEY

32-byte hex key for cross-process replay detection

unset (per-process)

PRESIDIO_X402_CHAIN_KEY

32-byte hex key for cross-process audit-chain HMAC

unset (per-process)

PRESIDIO_X402_REQUIRE_FINGERPRINT_KEY

Fail startup if replay key is absent or invalid

unset

PRESIDIO_X402_REQUIRE_CHAIN_KEY

Fail startup if audit-chain key is absent or invalid

unset

Generate cross-process keys with openssl rand -hex 32.

Tools

screen_payment_metadata(resource_url, description, reason, entities?)

Detects and redacts PII in payment metadata. No side effects — safe to call repeatedly.

// Input
{
  "resource_url": "https://api.foo.com/u/jane@example.com",
  "description": "monthly fee for jane@example.com",
  "reason": ""
}

// Output
{
  "redacted_resource_url": "https://api.foo.com/u/<EMAIL_ADDRESS>",
  "redacted_description": "monthly fee for <EMAIL_ADDRESS>",
  "redacted_reason": "",
  "entities_found": [
    { "entity_type": "EMAIL_ADDRESS", "field": "resource_url", "count": 1 },
    { "entity_type": "EMAIL_ADDRESS", "field": "description", "count": 1 }
  ],
  "mode": "in_process"
}

entities (optional list of Presidio entity types) narrows detection to a whitelist. Field-length caps mirror the screening-api wire contract that remains stable through parent 0.7.x: resource_url ≤ 2048, description ≤ 4096, reason ≤ 4096 characters. Oversized inputs raise ValueError.

check_payment_policy(resource_url, amount_usd)

Spending-policy gate. Records the spend on success — call exactly once, immediately before payment. Skipping the actual payment after a successful check inflates the daily-limit ledger until the window rolls over.

// Input
{ "resource_url": "https://api.foo.com/x", "amount_usd": 1.50 }

// Output (allowed)
{ "allowed": true }

// Output (denied — over per-call limit of $5.00)
{ "allowed": false, "reason": "...", "limit_usd": 5.00, "amount_usd": 6.00 }

check_payment_replay(resource_url, pay_to, amount, currency, deadline_seconds)

Duplicate-payment gate via HMAC-SHA256 fingerprint of the canonical fields. Records the fingerprint on success — call exactly once, immediately before payment.

amount is a string to preserve precision. Cross-process detection requires PRESIDIO_X402_FINGERPRINT_KEY (and optionally PRESIDIO_X402_MCP_REDIS_URL); otherwise each MCP server process keeps its own in-memory store.

// Input
{
  "resource_url": "https://api.foo.com/x",
  "pay_to": "0xabc...",
  "amount": "1.50",
  "currency": "USDC",
  "deadline_seconds": 1700000000
}

// Output (first seen)
{ "is_replay": false, "fingerprint": "29aaf60f..." }

// Output (duplicate within TTL)
{ "is_replay": true, "fingerprint": "29aaf60f..." }

Modes

In-process (default). Wraps the local presidio-hardened-x402 library in the same process as the MCP server. No network, no API key, no quota. PII never leaves the agent host. Use this unless you have a specific reason not to.

HTTP-proxy. When both PRESIDIO_X402_MCP_REMOTE_BASE_URL and PRESIDIO_X402_MCP_REMOTE_API_KEY are set, screen_payment_metadata calls /v1/screen on the configured host (e.g. https://screen.presidio-group.eu) for centralized audit. On auth / quota / network failure, returns a structured { "error": "auth_error" | "rate_limit" | "unavailable", "detail": ..., "mode": "remote" } — never silently falls back to in-process. Tools 2 and 3 always stay in-process.

Composability

Designed to slot into agent flows alongside payment-execution and endpoint-safety MCP servers:

agent intent: pay https://api.foo.com/x with 1.50 USDC
    │
    ├─ x402station    preflight(url)            ← is the ENDPOINT safe? (decoys, dead, traps)
    │
    ├─ presidio-x402  screen_payment_metadata   ← is the PAYLOAD safe? (PII)
    ├─ presidio-x402  check_payment_policy      ← within budget?
    ├─ presidio-x402  check_payment_replay      ← not a duplicate?
    │
    └─ pay()

screen_payment_metadata is read-only and safe to interleave anywhere. The policy and replay gates record state on call — sequence them immediately before payment.

Combined snippet: preflight → screen → pay

Endpoint-safety and payload-safety are independent signals — calling both is what you actually want before signing. Configure the two MCP servers side-by-side:

{
  "mcpServers": {
    "x402station":   { "command": "npx", "args": ["-y", "x402station-mcp"],
                       "env": { "AGENT_PRIVATE_KEY": "0x…" } },
    "presidio-x402": { "command": "uvx", "args": ["presidio-hardened-x402-mcp"] }
  }
}

Agent flow before signing a payment (pseudocode — each step is one MCP tool call):

# 1. endpoint safety: is the URL trustworthy? (x402station-mcp)
pf = preflight(url)
if not pf["ok"]:
    abort(reason=pf["warnings"])  # decoy / zombie / dead / price-trap

# 2. payload safety: redact PII before it leaves the host (presidio-x402)
s = screen_payment_metadata(resource_url=url, description=description, reason="")
url, description = s["redacted_resource_url"], s["redacted_description"]

# 3. spend gates: record-on-success, call exactly once each (presidio-x402)
if not check_payment_policy(url, amount_usd)["allowed"]:
    abort(reason="policy")
if check_payment_replay(url, pay_to, amount, currency, deadline_seconds)["is_replay"]:
    abort(reason="replay")

# 4. sign + pay
pay(url, amount, description=description)

The two servers are developed independently, on purpose — keeping the signals uncorrelated is the point. See x402station-mcp for the preflight tool's full output schema and warning catalog.

Notes for developers

  • Logs go to stderr (MCP clients capture stderr). stdout is reserved for JSON-RPC frames.

  • The package is a thin adapter. All security logic lives in presidio-hardened-x402 — read its docs for the entity-type catalog, policy semantics, evidence-ref verification, SLO broker, and audit-chain details.

  • This MCP release intentionally exposes the same three tools as 0.1.1; the compatibility update is dependency and metadata alignment with parent 0.7.x, not a promotion of the full parent SLO/evidence surface into MCP.

  • When testing via mcp-inspector --cli, bare numeric --tool-arg amount=1.50 is auto-coerced to a float and rejected by the schema. Real MCP clients send proper JSON types; the tool's amount argument is a string to preserve precision.

  • Local dev: uv venv && uv pip install -e ".[dev]" && pytest tests/.

License

MIT. See LICENSE.


SDLC

This repository is developed under the Presidio hardened-family SDLC: https://github.com/presidio-v/presidio-hardened-docs/blob/main/sdlc/sdlc-report.md.

Roadmap (next 12 months)

  • Now / in flight — OpenSSF Best Practices silver and a Scorecard above 7: governance docs, a real CodeQL job alongside Bandit, least-privilege workflow tokens, and Atheris fuzzing of the configuration validators. Closing the remaining findings in SECURITY-AUDIT.md.

  • Next — a release carrying the raised parent floor, so the published package no longer resolves a parent with the percent-encoding redaction bypass. Hash-pinned CI dependencies, ideally as a family-wide change rather than in this repo alone.

  • Later (under evaluation) — signed releases with build provenance; tracking the MCP specification as it stabilises; exposing the parent library's capability-grant@1 enforcement as a fourth tool, if agent demand justifies the added surface.

Governance, Architecture, Security

  • Governance — roles, decision process, and how to become a maintainer.

  • Architecture — components, trust boundaries, and the core processing path.

  • Assurance case — the security claims and the evidence backing each one.

  • Security policy — supported versions and how to report a vulnerability.

  • Contributing — review bar, test policy, and verification commands.

  • Stability guarantees — what counts as the public API and what may not change.

Available Tools

3 tools
check_payment_policyA

Check whether a payment is allowed by the configured spending policy.

WARNING: this records the spend against rolling time-window ledgers. Call exactly once, immediately before submitting the payment. If you call this and then do not pay, the spend window will be inflated until it rolls over.

Configure limits at server startup via PRESIDIO_X402_MCP_* env vars.

Args: resource_url: x402 resource URL being paid (used for per-endpoint limits). amount_usd: Payment amount in USD-equivalent.

Returns: {"allowed": true} on success, or {"allowed": false, "reason": str, "limit_usd": float, "amount_usd": float}.

ParametersJSON Schema
NameRequiredDescriptionDefault
amount_usdYes
resource_urlYes

Output Schema

ParametersJSON Schema
NameRequiredDescription

No output parameters

TDQS

A4.6/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description fully discloses critical behavioral details: it records spend against rolling time-window ledgers and warns that calling without paying inflates the spend window. It also mentions configuration via env vars, leaving no ambiguity about side effects.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured with a clear purpose, a prominent warning, configuration notes, and a parameter/return section. It is efficient but slightly verbose; every sentence adds value. Could be trimmed, but quality is high.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's simplicity (two scalar params, no nested objects) and the presence of an output schema (return format described), the description covers purpose, side effects, usage, parameters, and returns comprehensively. No critical information is missing.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, but the description adds meaning: resource_url is 'x402 resource URL being paid (used for per-endpoint limits)' and amount_usd is 'Payment amount in USD-equivalent.' This clarifies usage beyond the parameter names, though format constraints or examples are missing.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Check whether a payment is allowed by the configured spending policy.' It uses a specific verb ('check') and resource ('payment policy'), and distinguishes from siblings (screen_payment_metadata, check_payment_replay) by its focus on spending limits and side effects.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides explicit when-to-use guidance: 'Call exactly once, immediately before submitting the payment.' It warns against calling without paying to avoid inflating the spend window. No explicit when-not-to-use or comparison to siblings, but the guidance is clear and actionable.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

check_payment_replayA

Check whether this exact payment has been seen recently (replay protection).

WARNING: this records the fingerprint. Call exactly once, immediately before submitting the payment.

Cross-process detection requires PRESIDIO_X402_FINGERPRINT_KEY (and optionally PRESIDIO_X402_MCP_REDIS_URL); otherwise each MCP server process has its own ephemeral in-memory store.

Args: resource_url: x402 resource URL. pay_to: Recipient address. amount: Amount as string (preserves precision). currency: Currency symbol (e.g. "USDC"). deadline_seconds: Payment deadline as epoch seconds.

Returns: {"is_replay": false, "fingerprint": ""} on first seen, or {"is_replay": true, "fingerprint": ""} on duplicate.

ParametersJSON Schema
NameRequiredDescriptionDefault
amountYes
pay_toYes
currencyYes
resource_urlYes
deadline_secondsYes

Output Schema

ParametersJSON Schema
NameRequiredDescription

No output parameters

TDQS

A4.8/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Discloses that it records a fingerprint (side effect), requires environment variables for cross-process operation, and describes the return format. No annotations are present, but the description fully covers safety and behavioral traits.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Concise, well-structured with a title statement, warning, and list of args and returns. Every sentence adds value with no redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Covers side effects, prerequisites (env vars), usage order, and return values. For a tool with 5 required params and no annotations, the description is fully complete.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 0% schema description coverage, the description provides brief but meaningful explanations for all 5 parameters (e.g., 'Amount as string (preserves precision)'), adding clarity beyond the schema's bare names and types.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool checks for replay of a payment using a fingerprint. The verb 'check' and resource 'payment replay' are specific. However, it does not explicitly differentiate from siblings like screen_payment_metadata or check_payment_policy, though the distinct behavior is implied.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Provides explicit guidance: 'Call exactly once, immediately before submitting the payment.' Also explains cross-process detection dependencies, helping the agent understand when and how to use the tool.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

screen_payment_metadataA

Screen x402 payment metadata for PII before signing the payment.

Call BEFORE sending the payment request. Detects emails, phone numbers, SSNs, names, and other PII in the resource URL, description, and reason fields and returns redacted strings plus per-field entity counts.

No side effects.

Runs in one of two modes:

  • in_process (default): wraps the local presidio_x402 PIIFilter.

  • remote: when both PRESIDIO_X402_MCP_REMOTE_BASE_URL and ..._REMOTE_API_KEY are set, POSTs to /v1/screen on that host for centralized audit. On remote failure, returns a structured error dict instead of silently falling back — the caller must decide whether to retry, accept reduced screening, or abort.

Args: resource_url: x402 resource URL the agent is about to pay (max 2048 chars). description: Human-readable description (max 4096 chars). reason: Reason / memo string (max 4096 chars). entities: Optional whitelist of Presidio entity types to detect. If None, all configured entities are scanned.

Returns: On success: dict with keys redacted_resource_url, redacted_description, redacted_reason, entities_found (list of {entity_type, field, count}), and mode (one of "in_process", "remote"). On remote failure: dict with keys error (one of "auth_error", "rate_limit", "unavailable"), detail, optional retry_after (for rate_limit), and mode ("remote").

ParametersJSON Schema
NameRequiredDescriptionDefault
reasonNo
entitiesNo
descriptionNo
resource_urlYes

Output Schema

ParametersJSON Schema
NameRequiredDescription

No output parameters

TDQS

A4.6/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description fully discloses no side effects, modes, error handling, and return schemas for both success and remote failure. Very thorough and transparent.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Well-structured with sections for purpose, usage, modes, args, and returns. Each sentence adds value, no fluff.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Covers all aspects: inputs (4 params), outputs (success and error), behavioral modes, and error handling. Complete given complexity and presence of output schema.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 0%, but the description provides detailed parameter info: constraints (max lengths), optional entities whitelist, and default values. Fully compensates for missing schema descriptions.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

Clearly states the tool screens x402 payment metadata for PII before signing. The verb 'screen' and resource are specific, but no explicit contrast with sibling tools check_payment_policy and check_payment_replay.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Explicitly says 'Call BEFORE sending the payment request.' Describes two modes and how to handle remote failure, providing clear context for use. No alternatives mentioned, but usage is well-defined.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 3 tool updatesv0.1.2
    • First observedcheck_payment_policy
    • First observedcheck_payment_replay
    • First observedscreen_payment_metadata

TDQS

A4.8/5.0

Scored across 3 tools

Disambiguation5/5

Each tool serves a completely distinct purpose: PII screening, spending policy enforcement, and replay protection. The descriptions clearly delineate their roles, leaving no ambiguity about which tool to use for each pre-payment check.

Naming Consistency5/5

All three tools follow a consistent verb_noun pattern in snake_case (screen_payment_metadata, check_payment_policy, check_payment_replay). The verbs 'screen' and 'check' accurately differentiate the actions, and the nouns clearly indicate the target aspect of payment processing.

Tool Count5/5

Three tools cover the essential pre-payment validation steps (privacy, policy, replay) without unnecessary overlap or bloat. This is a well-scoped set that fully serves the server's stated purpose.

Completeness5/5

The tool surface provides a complete set of checks needed before submitting an x402 payment: PII redaction, spending limit verification, and replay detection. There are no obvious gaps for the declared pre-payment domain.

Maintenance

ActivityActive
ResponsivenessUnresponsive

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Related MCP Servers