Add Nevermined x402 payments to your Strands AI agent tools
Start here: need to register a service and create a plan first? Follow the
5-minute setup.
Add payment protection to your Strands AI agent tools using the x402 protocol. The @requires_payment decorator handles verification and settlement automatically.
The @requires_payment decorator follows the x402 MCP transport spec — payment errors are returned as tool results with status: "error", not raised as exceptions. Each error includes:
A human-readable text block explaining the payment requirement
A structured JSON block containing the full PaymentRequired object
In Strands, tool errors flow through the LLM. The LLM sees the error and relays it to the user in natural language (e.g., “I need a payment token to use this tool”). The structured PaymentRequired data is preserved in agent.messages.Clients use extract_payment_required(agent.messages) to get the structured PaymentRequired dict from the conversation history. The PaymentRequired contains the accepts array with plan IDs, schemes, and networks needed to acquire an x402 access token.
The @requires_payment decorator wraps a Strands @tool function with x402 payment verification and settlement.
You must use @tool(context=True) instead of plain @tool. This tells Strands to inject tool_context into the function, which the decorator needs to access invocation_state for the payment token.
import osfrom dotenv import load_dotenvfrom strands import Agent, toolfrom payments_py import Payments, PaymentOptionsfrom payments_py.x402.strands import requires_paymentload_dotenv()# Initialize Paymentspayments = Payments.get_instance( PaymentOptions( nvm_api_key=os.environ["NVM_API_KEY"], environment=os.environ.get("NVM_ENVIRONMENT", "sandbox"), ))PLAN_ID = os.environ["NVM_PLAN_ID"]# Protect a tool with payment@tool(context=True)@requires_payment(payments=payments, plan_id=PLAN_ID, credits=1)def analyze_data(query: str, tool_context=None) -> dict: """Analyze data based on a query. Costs 1 credit per request. Args: query: The data analysis query to process. """ return { "status": "success", "content": [{"text": f"Analysis complete for: {query}"}], }# Create agent with payment-protected toolsagent = Agent(tools=[analyze_data])
That’s it! The decorator automatically:
Returns a PaymentRequired error when no token is provided
Verifies the x402 token via the Nevermined facilitator
Executes the tool function on successful verification
The decorator 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. You can explicitly override with
the scheme parameter.
# Nevermined (required)NVM_API_KEY=sandbox:your-api-keyNVM_ENVIRONMENT=sandboxNVM_PLAN_ID=your-plan-idNVM_AGENT_ID=your-agent-id # Optional# LLM ProviderOPENAI_API_KEY=sk-your-openai-key # Or configure your preferred model provider