1. Protocol Overview & Economic Thesis

Legacy Web2 payment networks (Stripe, Visa, MasterCard) are architected around human consumer checkouts. They impose a fixed $0.30 base fee + 2.9% on every transaction. For AI agents invoking micro-tools ($0.001 – $0.01), this fixed fee makes micro-billing 150x more expensive than the underlying compute.

Furthermore, autonomous AI agents cannot fill in credit card expiry dates, solve Cloudflare Turnstile challenges, or navigate browser OAuth redirects.

Subcent402 establishes an open machine-to-machine financial standard by coupling the HTTP 402 / MCP -32042 status code with stateless cryptographic Macaroons and Base USDC / Lightning settlement.

2. Challenge-Response Handshake Specification

Subcent402 executes an autonomous, programmatic 2-step challenge-response handshake without requiring static API keys or human intervention:

Step 1: The Payment Required Challenge

When an agent invokes a paid MCP tool or REST endpoint without valid authorization, the server immediately halts execution and returns a cryptographic challenge:

// MCP JSON-RPC 2.0 Error Response (Code: -32042)
{
  "jsonrpc": "2.0",
  "id": "req_8a2f91c",
  "error": {
    "code": -32042,
    "message": "Payment Required: Tool 'tokenmarkdown_extract' costs $0.001 USD.",
    "data": {
      "protocol": "L402",
      "price_usd": 0.001,
      "macaroon": "eyJ2ZXJzaW9uIjoiMS4wIiwiaWRlbnRpZmllciI6IjIzODg...fQ==",
      "payment_hash": "238885d39b546d206926f2716537c4988a240b52b78f77b9d68cb2f0273b3595",
      "accepted_rails": ["BASE_USDC", "LIGHTNING_BTC", "VIRTUAL_VAULT"],
      "expires_at": 1787866577150,
      "recipient": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e",
      "tool_name": "tokenmarkdown_extract"
    }
  }
}

Step 2: Auto-Settlement & Preimage Proof

The agent's client wallet verifies the price against local BudgetGuard limits, settles the payment in <80ms, obtains the 32-byte secret preimage, and re-submits the tool invocation with proof attached:

// Re-Invoking MCP Tool with _auth_l402 proof:
invoke_tool("tokenmarkdown_extract", {
  "url": "https://linear.app",
  "_auth_l402": "<macaroon_base64>:<32_byte_preimage_hex>"
})

// Or in standard REST API HTTP Headers:
Authorization: L402 <macaroon_base64>:<32_byte_preimage_hex>

3. Macaroon HMAC Cryptographic Verification & Zero-Knowledge Isolation

Unlike JSON Web Tokens (JWTs) which require heavy asymmetric RSA/ECDSA signature verification or database lookups, Subcent402 uses chained symmetric HMAC-SHA256 Macaroons.

🔒 Zero-Knowledge Key Isolation Guarantee: Your tool server's SUBCENT402_ROOT_SECRET never leaves your own local environment. It is never transmitted across the network, never logged, and never stored in any external database. The verification math below is standard open cryptographic verification that allows your server to validate payments offline in 0.18ms without trusting any third party.

Mathematical Verification Chain

// 1. Initial Key Derivation (Stateless & Local to Your Server):
K_0 = HMAC-SHA256(YourServerRootSecret, PaymentHash)

// 2. Chained Contextual Caveats (Tool Scope, Expiration, Nonce):
K_1 = HMAC-SHA256(K_0, "tool=tokenmarkdown_extract&expires_at=1787866577150")

// 3. Preimage Proof Verification:
Assert SHA-256(Preimage) == PaymentHash

// 4. Offline Constant-Time Signature Comparison:
Assert ConstantTimeEqual(Macaroon.Signature, Hex(K_1)) == True

Because verification relies exclusively on symmetric HMAC math, your tool server validates requests in <0.2ms with zero network roundtrips or database dependencies.

4. MCP & HTTP Error Codes

Subcent402 standardizes error handling across both Model Context Protocol (MCP) and REST environments:

  • MCP -32042: Payment Required challenge containing Macaroon and payment hash.
  • HTTP 402 Payment Required: Returned with WWW-Authenticate: L402 ... header.
  • MCP -32043: Invalid Preimage proof or HMAC signature mismatch.
  • MCP -32044: Macaroon token has expired or caveat constraint violated.

5. TypeScript MCP Server Paywall (`@subcent402/sdk`)

Monetize any TypeScript MCP tool in 3 lines of code:

import { withSubcent402 } from "@subcent402/sdk";

export const extractTool = withSubcent402({
  priceUsd: 0.001,
  toolName: "tokenmarkdown_extract",
  recipientWallet: "0xYourBaseUsdcAddressOrLightning",
  rootSecret: process.env.SUBCENT402_ROOT_SECRET!
}, async (params) => {
  return await extractCleanMarkdown(params.url);
});

6. Native Python Server Decorator (`subcent402`)

Monetize Python functions, FastAPI routes, and CrewAI tools with standard decorators:

from subcent402 import with_subcent402

@with_subcent402(
    price_usd=0.004,
    tool_name="sec_edgar_extractor",
    recipient_wallet="0xYourWalletAddress",
    root_secret="your_local_secret_key"
)
async def extract_filing(ticker: str, **kwargs):
    return {"ticker": ticker, "status": "extracted"}

7. Standard HTTP 402 REST Middleware

Protect standard HTTP REST APIs and webhooks across Hono, Express, or Cloudflare Workers:

import { Hono } from "hono";
import { handleHttp402Paywall } from "@subcent402/sdk";

const app = new Hono();

app.post("/v1/api", async (c) => {
  const check = handleHttp402Paywall(c.req.raw, {
    priceUsd: 0.003,
    toolName: "api",
    rootSecret: process.env.SUBCENT402_ROOT_SECRET!
  });
  
  if (!check.isAuthorized) {
    c.header("WWW-Authenticate", check.wwwAuthenticateHeader);
    return c.json(check.challenge, 402);
  }
  
  return c.json({ status: "executed" });
});

8. Enterprise Guardrails: BudgetGuard & Slack HITL

Prevent runaway LLM loops from draining corporate balances with strict local spending policies:

import { wrapMcpClient } from "@subcent402/client";
import { createSlackHitlApprover } from "@subcent402/client/budget/hitl-webhook";

const agent = wrapMcpClient(rawClient, {
  budget: {
    maxDailySpendUsd: 5.00,  // Hard daily limit
    maxPerCallUsd: 0.05,     // Hard per-call ceiling
    hitlThresholdUsd: 0.50,  // Escalates to Slack if call > $0.50
    hitlCallback: createSlackHitlApprover({
      webhookUrl: process.env.SLACK_APPROVAL_WEBHOOK!
    })
  }
});

9. Claude Desktop & Cursor Integration

Drop Subcent402 MCP servers directly into your claude_desktop_config.json:

{
  "mcpServers": {
    "tokenmarkdown_extract": {
      "command": "npx",
      "args": ["-y", "@subcent402/tokenmarkdown-mcp"],
      "env": {
        "SUBCENT402_MAX_DAILY_SPEND": "5.00",
        "SUBCENT402_AUTO_SETTLE": "true"
      }
    }
  }
}

10. Multi-Rail Settlement (Base USDC & Lightning)

Subcent402 supports non-custodial multi-rail settlement across:

  • Base USDC (L2): Instant smart contract settlement using EIP-712 gasless permits and sub-cent on-chain gas.
  • Bitcoin Lightning Network: Zero-latency streaming micropayments via BOLT11 invoices and LNURL.
  • Virtual Credit Vaults: Local pre-funded credit balances for developers operating in zero-crypto environments.