Loomal

Integrating x402 with LangChain agents tools that pay for themselves.

Give a LangChain agent a funded wallet and an x402-aware HTTP client, and every priced endpoint on the internet becomes a tool it can call mid-run — no API keys to provision.

A LangChain agent is only as capable as its tool belt, and the best tools increasingly cost money per call: premium search, structured extraction, enrichment lookups. The traditional answer — sign up for each provider, store an API key, wire it into the tool — doesn't scale past a handful of services and breaks entirely when the agent discovers a tool at runtime.

x402 replaces that with payment in the request cycle. The agent's HTTP client receives a 402 challenge, signs a USDC authorization from its own wallet, retries, and gets the response. From LangChain's perspective nothing special happened: a tool was called and returned a result. The payment is the wrapper's problem.

Step 1: Give the agent a wallet

The agent needs an EVM account funded with USDC on Base. Generate a keypair, fund it with a small budget — even $5 covers hundreds of calls at typical per-call prices, which start at $0.01 on Loomal — and load the private key from an environment variable or secret manager, never from code.

One detail that surprises people: the wallet needs USDC but no ETH. In the x402 exact scheme the agent signs an authorization and the facilitator submits the on-chain transaction, so the payer never spends gas. Funding is one stablecoin transfer and you're done.

Step 2: Wrap a paying client as a tool

The x402 Python SDK ships an httpx client that handles the 402 handshake transparently. Wrap it in a function, decorate it as a LangChain tool, and put the price in the docstring — the model reads tool descriptions when deciding what to call, and knowing the cost lets it economize.

paid_tool.py
import os
from eth_account import Account
from x402.clients.httpx import x402HttpxClient
from langchain_core.tools import tool
from langgraph.prebuilt import create_react_agent

wallet = Account.from_key(os.environ["AGENT_WALLET_KEY"])

@tool
async def paid_extract(url: str) -> str:
    """Extract structured data from a web page.
    Paid tool: costs $0.01 in USDC per call."""
    async with x402HttpxClient(
        account=wallet, base_url="https://api.example.com"
    ) as client:
        resp = await client.get(f"/extract?url={url}")
        return (await resp.aread()).decode()

agent = create_react_agent(model, tools=[paid_extract])

Step 3: Put guardrails on spend

An agent in a reasoning loop will happily retry a tool twenty times, and with paid tools each retry is real money. Two guards cover most failure modes: a per-call price ceiling in the x402 client (refuse any 402 quoting more than you expect), and a per-run budget counter in the tool wrapper that raises once cumulative spend crosses a limit.

Log every payment alongside the tool call. x402 settlements come with receipts and a transaction hash, so reconciling 'what did this run cost' is a query, not an investigation — but only if you record which run made which call.

Finding tools worth paying for

The wrapper pattern works against any x402 endpoint, which raises the practical question of where to find them. The Loomal Index is built for exactly this: a machine-queryable catalog where every listing carries a price and a payable endpoint, so you — or eventually the agent itself — can discover a capability, read its cost, and call it in one motion.

Start with one paid tool that plugs a real gap in your agent's abilities, watch the per-run cost for a week, then expand. Pay-per-call means experimenting with a premium tool costs cents, not a monthly commitment.

FAQ

Does the LangChain agent know it's paying?

Only as much as you tell it. The x402 handshake happens inside the HTTP client, invisibly to the model. Putting the price in the tool's docstring is good practice — the model factors cost into tool choice, calling cheap tools first and paid ones when they're worth it.

Do I need ETH for gas in the agent's wallet?

No. The agent signs a USDC payment authorization and the facilitator submits the transaction on Base, paying gas itself. The wallet only needs USDC.

How do I stop a runaway loop from draining the wallet?

Three layers: keep the wallet balance small (it's the hard cap), set a maximum acceptable per-call price in the client, and track cumulative spend per run in your tool wrapper, raising an error past a budget. Wallet funding is the backstop the agent can't code around.

Can I use this from LangChain.js instead of Python?

Yes — the same pattern applies with the x402 fetch wrapper in JavaScript: wrap a paying fetch in a tool function and hand it to your agent. The protocol flow, wallet requirements, and guardrails are identical.

Selling to LangChain agents?

Price your endpoint with x402 and let agents pay per call.

Open the Loomal console