Skip to main content
Glama
machine-utility-foundry

machine-utility-foundry

README.md
# Machine Utility Foundry (`foundry-x402`)

[![Machine Utility Foundry (x402 + ICP Trust & Safety Oracles) MCP on mcprush](https://mcprush.com/badge/machine-utility-foundry-x402-icp-trust-safety-mcp/score.svg)](https://mcprush.com/to/machine-utility-foundry-x402-icp-trust-safety-mcp?ref=badge)

**Safe Auto-Paying x402 Wallet & Counterparty Trust Oracle for Claude Desktop, Cursor, and Autonomous AI Agents (`Worker v1.2.3` / `foundry-x402@0.4.5`).**

Autonomous agents and desktop AI clients face three blockers when consuming **x402** paid APIs on Base Mainnet (`eip155:8453` USDC):
1. **Desktop MCP clients cannot sign EIP-3009 payments natively.**
2. **External x402 catalogs contain wash-traded bots, price bait-and-switch endpoints, and post-payment `402` honeypots.**
3. **Network drops or client crashes after signing can cause accidental double-payments on retries or fallback routes.**

`foundry-x402@0.4.5` solves all three: a local spend-capped Base USDC wallet bridge with pre-send `fsync` WAL & stale-RPC-resilient Base L2 auto-reconciliation + pre-settlement Ed25519 trust screening + automatic on-chain slashing backed by **Internet Computer (ICP)** and **Cloudflare Edge KV**.

---

## 1. Quick Start: Claude Desktop / Cursor / Windsurf (Zero-ETH Gasless Auto-Pay)

Generate an isolated Base Mainnet USDC micro-wallet in memory (never written to disk), fund it with `$1–$3` Base USDC (0 ETH gas required — EIP-3009 settlement is gas-sponsored), and paste the printed `mcpServers` JSON into your client config:

```bash
npx -y foundry-x402 new-wallet
```

Gives your AI assistant:
- **`safe_x402_request`** — Safely call & pay **any external `https://` x402 API** with pre-settlement honeypot screening, split-horizon bait-and-switch defense, per-call/session USD caps, automatic pre-send `fsync` WAL (`FOUNDRY_WAL_PATH`), and post-payment slashing.
- **`foundry_wallet_status`** — Live Base USDC balance, remaining session budget, unresolved WAL count, and optional `{ reconcile: true }` on-chain L2 reconciliation (`$0` free local check).
- **All Foundry Discovery & Failover Oracles** — Automatic `$0` zero-charge empty checks and seamless micro-USDC settlement when verified routes exist.

## 2. Quick Start: TypeScript / Node / Cloudflare Workers SDK (`v0.4.5`)

```bash
npm install foundry-x402
```

```ts
import {
  FileWriteAheadPaymentStore,
  X402OutcomeUnknownError,
  createBaseUsdcPaymentAdapter,
  createSafeX402Fetch,
  fetchWithSafeFailover,
  reconcileBaseUsdcAuthorization,
} from "foundry-x402";

const safeFetch = createSafeX402Fetch({
  paymentAdapter: createBaseUsdcPaymentAdapter(process.env.EVM_PRIVATE_KEY!),
  maxAcceptableUsd: 0.05,
  maxDynamicPriceMultiplierByEndpoint: { "api.example.com": 2 },
  attemptStore: new FileWriteAheadPaymentStore("./.foundry-x402/wal.jsonl"),
});

try {
  // 1-call parallel-quarantined failover across live-verified x402 providers:
  const { response, selectedUrl } = await fetchWithSafeFailover({
    safeFetch,
    need: "weather forecast",
    maxPriceUsd: 0.01,
  });
  console.log(selectedUrl, response.status);
} catch (err) {
  if (err instanceof X402OutcomeUnknownError) {
    const { authorizer, nonce, validBefore } = err.attempt;
    if (authorizer && nonce && validBefore) {
      // Gasless Base L2 block-pinned USDC.authorizationState check before any retry
      const recon = await reconcileBaseUsdcAuthorization({ authorizer, nonce, validBefore });
      console.log(recon.status, recon.safeToRetry);
    }
  }
  throw err;
}
```

### `v0.4.5` Crash-Safe & L2 Guarantees
- **`OUTCOME_UNKNOWN` Fail-Closed Failover & Automatic Dedup**: `fetchWithSafeFailover` throws `X402OutcomeUnknownError` and halts before calling fallback providers whenever a post-sign request drops or returns HTTP non-2xx (even if `PAYMENT-RESPONSE` is present). `createSafeX402Fetch` and `FoundryLocalMcpBridge` enable `InMemoryPaymentAttemptStore` by default and force `redirect: "manual"` on signed settlement requests.
- **Stale-RPC-Resilient Base L2 Block-Pinned Auto-Reconciliation**: `reconcileBaseUsdcAuthorization` pins `eth_getBlockByNumber("latest")` and `USDC.authorizationState` to the exact same hex block on the same RPC node, skips stale replicas (`maxBlockAgeSec`, default `120s`), caps future clock drift at `120s`, and fails over across `rpcUrls` before returning `CONFIRMED_NOT_SETTLED` (`safeToRetry: true`). Both `safeFetch` and `foundry-x402 mcp` automatically reconcile unresolved WAL entries on retry (with a `120s` cooldown guard when `RECONCILED_SETTLED`).
- **Pre-Send `fsync` WAL**: `FileWriteAheadPaymentStore` (enabled automatically in `npx -y foundry-x402 mcp` via `FOUNDRY_WAL_PATH` resolving `LOCALAPPDATA` / `XDG_STATE_HOME` / `~/.foundry-x402/wal.jsonl`; `'off'` or `'none'` disables) persists `SIGNED_IN_FLIGHT` across process crashes/restarts before outbound socket I/O.
- **Per-Endpoint Dynamic Price Tolerance**: `maxDynamicPriceMultiplierByEndpoint` overrides `maxDynamicPriceMultiplier` (default `5`) per exact normalized URL or lowercase hostname, always capped by `maxAcceptableUsd`.

See [`packages/x402-safe-fetch/README.md`](./packages/x402-safe-fetch/README.md) for `@x402/core` zero-extra-roundtrip adapter options and `InMemoryPaymentAttemptStore` usage.

---

## 3. For x402 API Providers: Copy-Paste Docs Snippets

Give Claude/Cursor users and autonomous TypeScript agents a spend-capped, honeypot-screened client for your x402 API (requires a funded Base Mainnet `eip155:8453` USDC micro-wallet; 0 ETH gas needed via EIP-3009):

**Claude Desktop / Cursor Wallet Setup (fund `$1–$3` Base USDC & paste printed JSON into MCP config):**
```bash
npx -y foundry-x402 new-wallet
```

**TypeScript / Node Safe Client:**
```ts
import {
  FileWriteAheadPaymentStore,
  createBaseUsdcPaymentAdapter,
  createSafeX402Fetch,
} from "foundry-x402";

const safeFetch = createSafeX402Fetch({
  paymentAdapter: createBaseUsdcPaymentAdapter(process.env.EVM_PRIVATE_KEY!),
  maxAcceptableUsd: 0.10, // Set >= your endpoint's max USD price (e.g. 1.00 for $1 endpoints)
  paidProbeThresholdUsd: 0.01, // Optional: skip the $0.005 Foundry Oracle fee on sub-cent ($0.001) micro-calls
  attemptStore: new FileWriteAheadPaymentStore("./.foundry-x402/wal.jsonl"), // Optional: persist duplicate-pay guard across restarts
});
```

---

## 4. Core x402 Trust & Routing Oracles (Primary Wedge)

All oracle verdicts include offline-verifiable **Ed25519 signatures** (`/.well-known/jwks.json`) and **IC Mainnet ledger proofs**:

- `POST /v1/x402/route-plan` (`$0.015` — **`$0.00` if 0 matches**) — Parallel-quarantined x402 failover planner: live-probes top wash-filtered candidates in parallel and returns signed `primary` + `fallback` execution tickets with locked `paymentTerms`.
- `GET|POST /v1/x402/recommend` (`$0.005` — **`$0.00` if 0 matches**) — Neutral (`ZERO_SELF_PREFERENCE`), wash-filtered x402 API recommender with organic 30-day payer counts.
- `POST /v1/oracle/x402-counterparty` (`$0.005`) — Live 402 header, official Base USDC asset, SSRF/DNS-rebinding-safe liveness, bait-and-switch, and historical reputation score (`0–100`).

### Free Public Discovery & On-Chain Slashing Endpoints (`$0.00`)
- `GET /v1/x402/recommend-preview?need={task}` — Free match count, masked host hint, and price range preview before paying.
- `GET /v1/oracle/reputation-stats` — Live 2-hour autonomous Bazaar crawl stats, wash-trade counts, & IC Mainnet anchor receipt.
- `POST /v1/oracle/delivery-feedback` — Free EIP-191 payer-signed & Base Mainnet `eth_getTransactionReceipt`-verified post-payment slashing endpoint.
- [`llms.txt`](./llms.txt) · `GET /llms.txt` — LLM-readable endpoint, SDK `v0.4.5`, and provider snippet index.
- `GET /v1/verify/:receiptId` · `GET /.well-known/jwks.json` · `GET /.well-known/x402` · `GET /.well-known/mcp.json` · `GET /openapi.json` · `POST /mcp`

### Secondary Deterministic Guardrails & Attestation Utilities
- `POST /v1/state/budget-guard` (`$0.005`) — Payer-isolated ICP shared multi-agent budget cap & atomic nonce replay guard.
- `POST /v1/guard/evm-preflight` (`$0.01`) — Fail-closed Base Mainnet `eth_call` simulator & unlimited approve / Permit2 / counterfeit USDC guard.
- `POST /v1/attest/artifact` (`$0.005`) & `POST /v1/attest/bundle` (`$0.015`) — Deterministic JSON Schema / Policy / BigInt Ledger audit anchored on IC Mainnet.
- `POST /v1/diff/breaking-openapi` (`$0.01`) — Deterministic `$ref` & `allOf` OpenAPI 3.x breaking-change auditor (up to 2 MB).

---

## 5. Operations & Verification

```powershell
npm.cmd run typecheck        # Sync Apify modules & typecheck Worker + SDK
npm.cmd test                 # Run full unit & Red-Team regression suite
npm.cmd run deploy           # Build SDK & deploy Cloudflare Worker + Cron + KV
npm.cmd run pulse            # Live OpenAPI, full 8-tool MCP, 402 & external Base USDC audit
npm.cmd run bazaar:bootstrap # $0.07 E2E settlement check across all 8 routes
npm.cmd run canary:run       # Execute isolated micro-USDC mystery-shopper sweep
```

TDQS

A3.5/5.0

Scored across 14 tools

Disambiguation3/5

The set splits into recognizable clusters (recommendation/preview/plan/oracle, attestation/verification, preflight guard, wallet/budget), but the boundaries within clusters blur: preview_x402_recommendation vs recommend_x402_api vs plan_safe_x402_failover_route vs oracle_x402_counterparty all answer 'is this endpoint good?', and attention must be paid to pick the free vs paid vs single-endpoint variant. Distinct tools like diff_breaking_openapi and foundry_wallet_status are unambiguous.

Naming Consistency3/5

Most names are snake_case verb-leading (get_, verify_, recommend_, plan_, attest_, diff_), but noun-first names like foundry_wallet_status, stateful_budget_guard_icp, and oracle_x402_counterparty break the pattern, and qualifier suffixes (_icp, _base, _onchain, _x402) are placed inconsistently. Still readable, just not predictable.

Tool Count4/5

14 tools sits at the upper end of the comfortable range for a single-purpose x402 trust/safety platform, and each maps to a distinct workflow step (wallet, gateway, discovery, probes, attestation, guarding, slashing). Arguably a couple of the recommendation tools could be consolidated.

Completeness4/5

Strong lifecycle coverage: budget checks, safe payment gateway, endpoint discovery/ranking, trust probing, failover planning, on-chain attestation and verification, preflight tx simulation, post-payment slashing reporting, and OpenAPI diffing. Gaps are minor — no way to list or manage one's own prior attestations/receipts beyond verify-by-ID, and no dispute/refund path.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues