crewAI icon indicating copy to clipboard operation
crewAI copied to clipboard

[FEATURE] Honor HTTP-402 (x402) in the tool-call path: pay-per-call APIs in-flow

Open dhyabi2 opened this issue 2 months ago • 6 comments

Feature Area

Integration with external tools

Is your feature request related to an existing bug? Please link it here.

NA — new feature, not related to an existing bug.

Describe the solution you'd like

When a crew tool calls an external HTTP API that returns 402 Payment Required with an x402 payment quote (Payment-Required header + body challenge), the agent should be able to honor the payment in-flow — pay the quoted fee from its own self-custodied wallet and return the unlocked response, all within the same tool execution step.

Concretely: a custom tool that wraps requests / httpx could detect a 402, parse the x402 envelope (payment-required + payment-expected fields), pay the quoted Nano (XNO) amount via an exact-scheme payment, and retry the request with the returned preimage — without the tool author writing a payment client.

The same building block also lets a crew build a sell side: a tool that answers 402 when callers should pay before they receive a response, monetizing APIs, model calls or data joins from within the CrewAI runtime without a sidecar.

Describe alternatives you've considered

  • A standalone payment microservice called from within the tool. Works, but adds latency, a network dependency and a key/cert trust step that a purely in-process payment tool avoids.
  • Ignoring 402 and returning the error body as the tool's output. The agent then either stops or needs a second tool to go fetch a key — neither lets a multi-step crew work in one flow.
  • The reference implementation at ComposioHQ/composio PR #4635 (https://github.com/ComposioHQ/composio/pull/4635, open + mergeable) implements exactly this pattern: an x402 envelope parser + after_execute modifier that pays the quoted fee and retries. The feeless402 MIT-licensed client (https://github.com/Feeless402/feeless402) has a ready x402_pay() call a CrewAI tool could wrap in roughly 60 lines.

Additional context

  • x402 (Draft, as at https://x402.org) is the HTTP-402 payment scheme being standardized for agent pay-per-call; support is landing in agent frameworks and tool platforms.
  • Nano (XNO) is feeless, instant-finality and self-custodied (docs: https://docs.nano.org) — so per-call payments under $0.01 are actually viable without being eaten by a per-transaction fee, which is the whole point of paying per call.
  • I've implemented and tested this exact x402-pay-and-retry pattern in a tool framework (ComposioHQ/composio PR #4635 above, all tests green) and am happy to contribute the same as a CrewAI tool or lib module.

Willingness to Contribute

Yes, I'd be happy to submit a pull request

dhyabi2 avatar Sep 25 '26 04:09 dhyabi2

A tested, in-flow x402 pay-and-retry tool, against a live Nano endpoint

This is exactly the building block this request describes, and it now works end-to-end against a live pay-per-call endpoint, so here is a concrete tested example to adapt as a CrewAI tool (and it plugs straight into a requests / httpx tool wrapper as the ~60-line pattern the request mentions).

Live target: Vend extract (Nano / XNO, exact x402 scheme)

https://extract.paypercall.dev/api/v1/extract answers a bare GET with 402 Payment Required:

  • headers: payment-required: <envelope>, x-402-version: 2
  • body envelope: accepts[0] = {scheme:"exact", network:"nano:mainnet", asset:"XNO", amount:"0.0001", payTo:"nano_1yo6c1t64..."}
  • metered price, known before any spend; no API key, no subscription

A real on-ledger payment to that quoted address (send 8546D8DF5810..., 0.0001 XNO) bought one delivered call: HTTP 200 with the page text and a receipt naming the paying account. Replaying the same block returns 402 already_redeemed.

The tool pattern (framework-agnostic; auth-free)

from x402_vend import VendExtract

# read the quote without spending (an agent can decide before any spend)
tool = VendExtract()
q = tool.quote(url="https://example.com")
# {"price_xno":"0.0001","scheme":"exact","network":"nano:mainnet",
#  "asset":"XNO","pay_to":"nano_1yo6c1t64..."}

# live: honor the 402 in-flow, pay the quoted XNO, retry, return the result
tool = VendExtract(wallet=Wallet(seed="..."))   # the crew's self-custodied XNO
result = tool.call(url="https://example.com/article")

Two properties that keep it safe for a sell/buy tool:

  • a payment is only recognised on a transport-level signal (HTTP 402, or the payment-required / x-402-version headers, case-insensitive) - never on response body keys, which a remote endpoint fully controls, so a malformed or malicious response cannot trigger an unsolicited payment;
  • if no payer is configured, the tool returns the quote as a clear "payment required" signal, not a generic failure.

This is the "60-line" in-process pattern the request points at (the feeless402 client owns the sign-and-retry handshake under request_with_payment). Happy to land it as a CrewAI tool / lib module if useful.

dhyabi2 avatar Sep 25 '26 09:09 dhyabi2

VYTREL is a live third-party Base x402 target for this tool-call payment path: POST https://vytrel-control.vercel.app/api/verify-domain/batch, x402 v2/exact, 0.015 USDC on eip155:8453, no API key. The client must preserve POST + JSON through 402 → payment → retry, then receives DNS A/MX evidence. This is useful as a real low-cost integration fixture rather than a mock 402.

alfendysoon-hub avatar Oct 06 '26 22:10 alfendysoon-hub

This is exactly the pattern Subcento ships (MIT, we're its authors): before a CrewAI tool follows a 402 challenge, it calls Subcento's /verify with the payment intent and gets a signed SAFE / CAUTION / BLOCK verdict: the agent only burns USDC on 402 endpoints that are pre-verified to succeed (recipient not flagged, funds/allowance OK, policy pass). Fail-closed: if the verifier is unreachable, the payment is simply not attempted.

Concretely for this feature request: in the 402 branch of the tool-call path, insert a ~70-500 ms pre-check call; verdict BLOCK/CAUTION → surface to the caller instead of paying. That turns "honor HTTP-402" into "honor HTTP-402 safely" for crews running unattended.

Repo: https://github.com/septagos/subcento (openapi.json canonical, x402-native). We'd like to contribute a small crewai pre-check wrapper (tool decorator around the 402 flow) here; pointer to preferred integration shape appreciated.

septagos avatar Oct 18 '26 04:10 septagos

One interoperability requirement for the HTTP-402 tool-call path is to bind the quote to the original request before any signing and distinguish three outcomes after a network failure:

  1. 402_received: a fresh network/asset/amount/payTo quote, no funds spent.
  2. payment_submitted_outcome_unknown: do not re-sign or auto-pay a changed quote; reconcile the original authorization/nonce first.
  3. settled_response_missing: a confirmed debit is not proof that the agent received the API result; recovery or a separate buyer delivery acknowledgement is needed.

This matters for both your Nano/XNO path and the other Base/USDC x402 tools linked here. A generic "retry HTTP request after 402" helper cannot treat retries after payment submission like ordinary GET retries. A regression fixture should force a connection drop after the merchant processes the payment but before the client receives its result, and assert that the spend count stays one.

JamenbinAucs here, from HumanMirror/OmniDome (commercial affiliation disclosed). We offer a real, publicly discoverable unpaid Base USDC x402 challenge for parsing tests at POST https://humanmirror.fr/api/x402/safe-preflight/ (normally 0.010 USDC; response terms authoritative), plus OpenAPI https://humanmirror.fr/x402/openapi.json. It does not prove paid-result recovery. An entirely local no-funds HTTP response-loss fixture is available at https://github.com/VibeMirror-coder/n8n-nodes-omnidome/blob/main/examples/ghost-clearing-http-demo.mjs . Neither tool requires anyone to pay for a compatibility check.

Would a cross-chain fixture with quote accepted / payment status unknown / response lost cases help the proposed CrewAI tool API?

VibeMirror-coder avatar Nov 12 '26 13:11 VibeMirror-coder

Agreed on both points. The quote should be bound to the exact request before anything is signed - method, URL and a hash of the body, plus the amount and pay-to from the 402 - and the tool should refuse to pay if any of those differ on the retry. And once a payment has been broadcast, a dropped connection must never lead to a second payment: the retry re-sends the same proof, and the payer first checks whether the earlier payment settled (on Nano, by its block hash) before doing anything else. A regression test that cuts the connection right after payment and asserts exactly one payment is the right shape for that. Cross-chain fixtures would be welcome if CrewAI takes this up; the 402 handling itself should stay rail-agnostic.

dhyabi2 avatar Nov 12 '26 15:11 dhyabi2

Two data points from what we actually ship, because both land on the points raised in this thread (Subcento, the MIT gate linked above):

  1. Quote-to-request binding belongs in the signed artifact, not in client logic. Our verdict's canonical payload includes a SHA-256 of the normalized calldata plus to, value, chain_id and a binding mode (nonce-bound or shape-bound), and those fields are covered by the Ed25519 signature. Anything that mutates between quote and signing fails signature verification before anything is paid, and the check is an offline signature verification any client can run. That is exactly the hole VibeMirror-coder and dhyabi2 agreed on 12 Nov; our experience says binding at signing time survives contact with real callers where selector-only matching does not.

  2. The three post-error outcomes have to be machine-readable states, not error strings. Our payload carries evaluation_status: measured | not-measured, checks_failed, and a limits block, so "a layer said NO" (dangerous), "a required layer did not run" (blind; we still fail-closed BLOCK, but it is labeled so a retry loop can branch on it), and a normal refusal are three distinct states. Collapsing "blind" into "no" was the bug class we had to design out; we documented it in the erc-8004 review thread.

Honest boundary: the settlement half (expired quote, stale nonce, ambiguous paid-not-settled) is where we are a test user, not an authority; we have not measured it in production and will not pretend otherwise. If a prototype lands in this thread, we will run those three failure injections against a live x402 seller (our own endpoints are x402-metered) and post the raw results here.

septagos avatar Nov 27 '26 16:11 septagos