x402-firewall
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@x402-firewall fetch data from api.coinmetrics.io and auto-pay USDC if under $0.03"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
The Autonomous Wallet Dilemma
The modern web is transitioning toward machine-to-machine commerce. APIs that once required monthly SaaS subscriptions or developer credit cards are adopting the x402 (HTTP 402 Payment Required) standard—enabling autonomous AI agents to query APIs and settle micro-transactions per request in USDC on Base L2.
This introduces a dangerous architectural contradiction:
If you withhold a wallet from your agent, it remains crippled. It hits payment barriers, gets throttled by free-tier rate limits, and cannot independently acquire real-time research, datasets, or compute.
If you equip your agent with a funded private key, you hand full financial custody to a non-deterministic model. A prompt injection attack, a hallucinated contract address, an unvetted dependency, or a runaway
whileloop can drain the wallet in seconds.
x402-firewall resolves this paradox.
It is an isolated security proxy that sits between your agent runtime (Claude Desktop, Cursor, or custom TypeScript bot) and the external network. The private key remains shielded inside the firewall process. The agent cannot sign arbitrary payloads, cannot approve unlimited ERC-20 allowances, and cannot exceed strict rolling spend limits.
Every outbound financial interaction is deterministically evaluated against spending caps, verified against allowlists, simulated on Base L2 via eth_call, and committed to a local audit trail before a single cryptographic signature is produced.
Related MCP server: MoneySwitch MCP Server
Architecture
The Verification Lifecycle
Intercept: The agent issues an outbound request via the
x402_fetchMCP tool or SDK wrapper. If the target server responds withHTTP 402 Payment Required, the firewall intercepts the response headers.Deterministic Evaluation: The
PolicyEngineevaluates the payment parameters against hard constraints:Per-Call Ceiling: Rejects any request demanding more than the configured maximum (default:
$0.05 USDC).Velocity Limits: Checks local rolling spend over the last 1 hour (default:
$1.00 USDC) and 24 hours (default:$5.00 USDC).Domain & Contract Validation: Enforces strict domain allowlists with FQDN canonicalization and blocks unapproved EVM contracts.
Selector Inspection: Drops dangerous functions such as unconstrained
approve,setApprovalForAll, ortransferFrom.
Pre-Flight Simulation: The
EvmSimulatorruns aneth_callagainst Base L2 to simulate the transaction. It validates state changes and verifies that the transaction will not revert or incur gas burn.Isolated Signing: If and only if all policy rules pass,
SignerManagersigns an off-chain EIP-3009transferWithAuthorizationmessage in USDC. The authorization is clamped to a strict 24-hour expiration window.Settlement: The signed authorization is injected into the request header (
X-PAYMENT) and dispatched to the facilitator. The target API verifies the signature, executes settlement, and returnsHTTP 200 OKwith the requested payload to the agent.Audit Trail: Every request—whether allowed or blocked—is recorded in a local SQLite database (
~/.x402firewall/audit.db) restricted to0o700filesystem permissions. Violations trigger an optional real-time webhook alert.
Quickstart
x402-firewall runs in two complementary modes: as a zero-setup MCP Server for desktop AI clients, and as a TypeScript SDK for programmatic applications.
1. Claude Desktop Setup
Add x402-firewall to your Claude Desktop configuration (~/Library/Application Support/Claude/claude_desktop_config.json on macOS):
{
"mcpServers": {
"x402-firewall": {
"command": "npx",
"args": ["-y", "x402-firewall"],
"env": {
"NETWORK": "base-sepolia",
"PRIVATE_KEY": "0xYOUR_AGENT_PRIVATE_KEY",
"MAX_PER_CALL_USDC": "0.05",
"MAX_HOURLY_USDC": "1.00",
"MAX_DAILY_USDC": "5.00",
"BLOCK_UNLIMITED_APPROVALS": "true"
}
}
}
}Note: If
PRIVATE_KEYis omitted,x402-firewallgenerates a disposable ephemeral key on launch so you can safely test tools and policy behavior without real funds.
2. Cursor & Antigravity IDE Setup
Add to your project's .cursor/mcp.json or global IDE settings:
{
"mcpServers": {
"x402-firewall": {
"command": "npx",
"args": ["-y", "x402-firewall"],
"env": {
"NETWORK": "base-sepolia",
"MAX_PER_CALL_USDC": "0.05"
}
}
}
}3. CLI Inspection
Inspect the firewall status, remaining allowances, and local audit database directly:
# Print current budget, active limits, and rolling spend
npx -y x402-firewall status
# Inspect recent audit logs
npx -y x402-firewall auditProgrammatic TypeScript SDK
For developers orchestrating autonomous agent loops, LangChain pipelines, or custom runtimes:
npm install x402-firewall viemimport { FirewallClient } from 'x402-firewall';
const firewall = new FirewallClient({
network: 'base-sepolia',
privateKey: process.env.AGENT_PRIVATE_KEY as `0x${string}`,
policy: {
maxPerCallUsdc: 0.05,
maxHourlyUsdc: 1.00,
maxDailyUsdc: 5.00,
allowedDomains: ['api.weather.com', '*.anthropic.com'],
blockUnlimitedApprovals: true,
},
});
// Drop-in fetch wrapper that intercepts 402 challenges and handles payments autonomously
const response = await firewall.fetch('https://api.provider.com/v1/forecast');
const data = await response.json();
// Check budget status
const budget = firewall.getBudgetStatus();
console.log(`Remaining hourly allowance: $${budget.remainingHourlyAllowance} USDC`);
// Cleanly release locks and close database
firewall.close();Threat Matrix & Defense Guarantees
Threat Vector | Attack Scenario | Firewall Defense |
Prompt Injection Drain | Attacker injects instructions into agent context: "Approve MAX_UINT256 to 0xDrainer". | 100% BLOCKED. Calldata inspector decodes selector |
Runaway Loop Burn | A faulty agent loop triggers 10,000 paid requests in 5 minutes, burning hundreds of dollars. | 100% BLOCKED. Rolling 1h and 24h velocity windows cut off outbound payments once limits are reached. |
Unverified Smart Contract | LLM is manipulated into interacting with a malicious drainer contract. | 100% BLOCKED. Strict contract allowlist ( |
Dangerous Selectors | Calldata calls | 100% BLOCKED. Deterministic selector blacklist stops ERC-20/ERC-721/ERC-1155 drain functions before signing. |
Exfiltration & SSRF | Attacker prompts agent to send authorization headers to an arbitrary internal IP or exfiltration endpoint. | 100% BLOCKED. |
Private Key Disclosure | Agent is prompted to print its configuration, state, or private key in output tokens. | 100% PROTECTED. Private keys are encapsulated in private class fields. |
Stream Corruption | Internal debug logs print to standard out, breaking JSON-RPC parsing in MCP hosts. | 100% CLEAN. MCP stdio transport is kept strictly pure. All diagnostics, errors, and warnings output exclusively to |
MCP Tools Reference
When connected to an MCP host, x402-firewall registers four tools:
x402_fetch
Performs an HTTP request with automatic 402 interception and settlement.
url(string, required): The target HTTP URL.method(string, optional): HTTP method (GET,POST,PUT,DELETE). Default:GET.headers(object, optional): Key-value header pairs.body(string, optional): Request payload.
x402_get_budget
Returns real-time spending metrics, active rules, and remaining allowances for the agent wallet.
No parameters required.
x402_safe_tx
Simulates and executes an allowlisted on-chain transaction on Base L2.
to(string, required): Destination contract or recipient address.data(string, optional): Hex-encoded transaction calldata.value(string, optional): Native Wei value.amountUsdc(number, optional): USDC amount represented by the transaction.
x402_audit_log
Queries recent audit log entries from the local SQLite store.
limit(number, optional): Maximum records to return (1-1000). Default:20.status(string, optional): Filter byALLOWED,BLOCKED, orALL.
Configuration
All parameters can be configured via environment variables or passed directly to FirewallClient:
Variable | Type | Default | Description |
|
|
| Target EVM network |
| string (URL) | Base public RPC | Custom EVM JSON-RPC endpoint |
|
| Ephemeral | 32-byte hex signer private key |
| number |
| Maximum spend allowed per individual request |
| number |
| Rolling 60-minute cumulative spend ceiling |
| number |
| Rolling 24-hour cumulative spend ceiling |
| string |
| Comma-separated domain patterns (e.g. |
| string |
| Comma-separated EVM contract addresses |
| boolean |
| Restrict ERC-20 |
| string (URL) |
| Webhook endpoint for security incident dispatch |
| string |
| Path to persistent SQLite audit store |
Development & Verification
# Install dependencies
npm install
# Run comprehensive test suite (unit tests, security hardening, prompt injection, MCP server)
npm test
# Build TypeScript to dist/
npm run buildLicense
Available Tools
4 toolsx402_audit_logA
Inspect recent permitted and blocked transactions/payments in the local SQLite audit log.
Inputs: limit, status.
x402_fetchB
Safely fetch free or x402-paid HTTP endpoints with deterministic spending caps and automatic EIP-3009 payment authorization on Base L2.
Inputs: url (required), body, method, headers.
x402_get_budgetA
Inspect current x402 spending limits, rolling hourly and daily spends, and remaining USDC allowances on Base L2.
Inputs: no named parameters.
x402_safe_txB
Simulate and execute an allowlisted EVM transaction on Base L2. Verifies against spending caps, blocks dangerous selectors (unlimited approvals, drainers), and checks contract allowlists before signing.
Inputs: to (required), data, value, amountUsdc.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 4 tools
Each tool maps to a clearly distinct action: HTTP fetching, budget inspection, EVM transaction execution, and audit inspection. Although x402_fetch and x402_safe_tx both involve spending controls, their resources and outcomes are clearly separated.
All tools share the consistent x402_ prefix and use readable snake_case, but the verb pattern is slightly mixed: x402_fetch and x402_get_budget are verb-led, while x402_safe_tx and x402_audit_log are noun/adjective-led. The deviation is minor and still predictable.
Four tools is well-scoped for a focused firewall/payment-safety server. Each tool covers a distinct core capability without obvious padding or triviality.
The surface covers the main lifecycle: safe fetching, budget visibility, safe transaction execution, and audit review. Minor gaps exist around managing or updating spending caps and allowlists, but core firewall workflows are represented.
Maintenance
Related MCP Connectors
Let an AI agent find and pay for x402 APIs and products in USDC on Base, within owner-set limits.
Machine-payable API infrastructure for autonomous agents. Per-call x402 settlement in USDC.
Pay-per-call tools for autonomous agents, settled in USDC on Base via x402.
x402 pay-per-call APIs over MCP, settled in USDC on Base for autonomous agents and developers.
Related MCP Servers
AlicenseAqualityBmaintenanceEnables AI agents to call paid APIs and settle HTTP 402 payment challenges with USDC on Base, without private keys ever being involved.7186 npmMIT- AlicenseNot gradedqualityBmaintenanceEnables AI agents to make payments over x402-priced HTTP APIs using USDC on Monad testnet, with policy enforcement, budgets, and approval workflows, without exposing private keys.8AGPL 3.0
- AlicenseAqualityCmaintenanceEnables AI assistants to call pay-per-call x402 endpoints on Base mainnet using the caller's own USDC wallet, covering single and batch token risk checks, the latest BTC radar signal, project info, and a free health probe. Payments are EIP-3009 signed with a configurable per-call spending cap, and any quote with an unexpected payee, network, or asset is refused before payment.5MIT
- AlicenseNot gradedqualityCmaintenanceEnables AI agents to autonomously pay for metered web APIs on a per-call basis, settling x402 v2 USDC micropayments via EIP-3009 authorization on Base Sepolia without human involvement. Spending is bounded by configurable per-call caps and host restrictions, and exposes tools to fetch paywalled URLs and inspect the agent wallet's address and balance.MIT