Skip to main content
Start here: need to register a service and create a plan first? Follow the 5-minute setup.

Runnable tutorial

langchain-paid-agent-py — a deliberately minimal LangChain + LangGraph agent with a single tool gated by @requires_payment. Clone, fill in .env, run poetry run buyer to see the full discovery → token-acquisition → settlement flow in five numbered steps. The cleanest starting point if you’d rather read working code than docs.
Add payment protection to LangChain and LangChain.js tools using the x402 protocol. The library provides two complementary approaches: Both use the same Nevermined plan, credits, and settlement flow — choose whichever fits your deployment model.

Installation

The @nevermined-io/payments/langchain sub-path export provides the requiresPayment() wrapper. For the HTTP server approach, also install express.

Approach 1: Tool Decorator / Wrapper

x402 Payment Flow (decorator)

Quick Start

In LangChain.js, requiresPayment() is a higher-order function that wraps the tool implementation:
The payment token is read from config.configurable.payment_token. Pass it when invoking the tool or agent.

Invoking with payment

LLM-driven tool calling

LangGraph ReAct agent

The same payment-protected tools work with LangGraph’s create_react_agent. The simple case — buyer already holds a token — just threads it through configurable:

Discovery-first flow with createPaidReactAgent

If the buyer doesn’t know the plan id / scheme / provider up front, the x402 way is to invoke the agent without a token, let the protected tool raise PaymentRequiredError, and read the requirements off the exception. By default LangGraph’s ToolNode would catch that exception and stringify it into a ToolMessage for the LLM — losing the X402PaymentRequired payload. Both SDKs ship a paid-agent helper for exactly this — createPaidReactAgent (TypeScript) / create_paid_react_agent (Python) — that builds the underlying ToolNode with handleToolErrors: false / handle_tool_errors=False, so the exception propagates to agent.invoke()’s caller with the payload intact.
Create the delegation that backs the payment signature first (with createDelegation), then pass its delegationId in the token’s delegationConfig. This applies to both card-delegation and crypto (nvm:erc4337) plans. Passing creation fields inline instead of a delegationId is deprecated and emits a runtime warning — see the x402 Protocol module reference (TypeScript · Python) for the full token-options surface. This discovery flow covers Stripe and Braintree. For Visa-priced plans, createDelegation from the SDK is rejected (BCK.VISA.0014) — create the Visa delegation in the Nevermined app and reuse its delegationId here.
createPaidReactAgent is async in TypeScript — it awaits the lazy @langchain/langgraph import so the dependency stays optional. Install LangGraph yourself (pnpm add @langchain/langgraph) to use it.

Reading the settlement receipt

After a successful agent call, the buyer can read the settlement receipt — credits redeemed, remaining balance, transaction hash, network, payer — via lastSettlement() (TypeScript) / last_settlement() (Python). LangGraph copies configurable per node, so the in-place payment_settlement write is invisible to the outer scope; the accessor reads it from a module-level slot instead.
lastSettlement() / last_settlement() reads from a module-level slot. In multi-tenant processes (e.g. a server handling concurrent settlements), the value reflects whichever invocation settled most recently — there is no per-call isolation. For multi-tenant scenarios, surface settlement via a callback or observability layer instead.

Trace payments in LangSmith

Once payment protection is wired up, you can have every paid tool call surface as structured spans in LangSmith — no code changes required, just two env vars and an optional dependency. Both SDKs emit the identical nvm:verify / nvm:settlement span shape (the cross-SDK observability-spans-v1 contract), so a single trace can be correlated across a TypeScript buyer and a Python seller — e.g. filter on nvm.tx_hash. Install the optional dependency:
langsmith is an optional peer dependency — the requiresPayment wrapper emits the spans automatically when it is installed and tracing is enabled.
Enable tracing:
That’s it. Running the same agent invocation now produces a trace tree with two dedicated Nevermined child spans nested under the tool:
Each Nevermined span carries nvm.* metadata for audit + reconciliation: The same nvm.* metadata is also attached to the parent tool span so cmd-F searches in the LangSmith UI land on either level. Failed discovery probes are first-class too. When the buyer’s first agent.invoke() runs without a payment_token (the discovery-first flow), the nvm:verify span still opens, carries the static nvm.plan_ids / nvm.scheme / nvm.network, and is marked failed by the raised PaymentRequiredError. That gives you “which plan was the probe against?” filterability instead of an opaque LangChain crash.
The payment_token the buyer passes in configurable.payment_token would normally be captured into the parent tool span’s metadata by LangChain and inherited by every child span. The full token grants access to the protected tool until it expires. Both SDKs proactively strip it from the parent span’s metadata before opening any nvm:* child, so the full credential never reaches a Nevermined-emitted attribute. The abbreviated nvm.payment_token (first 16 chars + + last 4 chars) remains available for correlation.A too-short token (≤ 20 chars — almost always a misconfiguration, since real x402 access tokens are JWTs) is redacted, not exported: at most the first 4 chars are surfaced followed by a …(short) marker, and a token of 4 chars or fewer reveals nothing (just …(short)). A warning is logged, so a wrong value passed as the token never lands in a trace.Other channels (custom callbacks, an explicit metadata write that includes the token, tool signatures that contain the token) are not covered — strip them yourself or set export LANGSMITH_HIDE_INPUTS=true for blanket coverage.
If a span failure ever occurs during metadata building or attachment, observability is silently dropped — the payment flow itself is never interrupted. Settlement receipts persist (via lastSettlement() in TypeScript / last_settlement() in Python) regardless of whether the span emit succeeded. For the full module reference, see the Python LangChain module reference. The TypeScript helper surface (verifySpan, settlementSpan, abbreviateToken, addMetadata, redactMetadataKeys, activeRunTree, plus buildVerifyMetadata / buildSettleMetadata for manual use outside the requiresPayment decorator) is exported from @nevermined-io/payments/langsmith — JSDoc on each helper documents the contract until the next update-docs.yml sync mirrors a dedicated TS api-reference page.

Dynamic Credits

The credits argument is sent to the facilitator as max_amount. The amount actually redeemed depends on the plan’s server-side credit config: fixed plans (where plan.credits.minAmount == plan.credits.maxAmount) always burn plan.credits.maxAmount and ignore the supplied value (per nvm-monorepo#1568); range plans clamp the value into [minAmount, maxAmount]. If you want predictable per-call cost, configure the plan as fixed.
Three patterns for credit calculation:
The credits function receives { args, result } after tool execution.

Approach 2: HTTP Server with Payment Middleware

For serving the agent over HTTP, use payment middleware on your framework. Payment is handled at the HTTP layer — tools are plain functions with no decorators or payment config.

x402 Payment Flow (HTTP)

Server: LangChain

Server: LangGraph

Replace the tool-call loop with LangGraph’s create_react_agent:
The HTTP app, middleware, and route handlers are identical to the LangChain version above.

Client: Full x402 HTTP Flow

x402 HTTP Headers

The settlement receipt (payment-response) contains:

Decorator Configuration

With Agent ID

Multiple Plans (Python only)

Scheme and Network

The decorator/wrapper automatically detects the payment scheme from plan metadata. Plans with fiat pricing (isCrypto: false) use nvm:card-delegation (Stripe). No code changes are needed on the agent side.

Complete Examples

Working seller/buyer agents with LangGraph — includes both Python and TypeScript variants:
Each includes:
  • src/server.ts / src/agent.ts — LangGraph createReactAgent with payment-protected tools
  • src/demo.tsrequiresPayment wrapper demo (seller only)
  • src/client.ts — HTTP client with full x402 payment flow

Environment Variables

Next Steps

Express Middleware (TS)

Deep dive into paymentMiddleware for Express

FastAPI Middleware (Python)

Deep dive into PaymentMiddleware for FastAPI

x402 Protocol

Deep dive into x402 payment flows

Payment Models

Configure credits, subscriptions, and dynamic pricing