Skip to main content

banner

Library for Activating AI Agent Payments Using the Nevermined Protocol

Python SDK to interact with the Nevermined Payments Protocol
nevermined.io

Motivation

The evolution of AI-native commerce is inevitable, but the infrastructure to support it is currently lacking. Today, AI agents require seamless, automated payment systems for individual transactions. As demand grows, these agents will scale into swarms, transacting and operating autonomously.

Existing solutions are designed for human use with physical money. This does not reflect the new reality, where AI Agents need to make and receive payments quickly and efficiently, without the limitations of traditional payment systems.

Nevermined provides a solution that seamlessly evolves from single-agent needs to complex AI economies, eliminating friction and supporting a fully autonomous, composable future for AI-driven commerce.

What is the Nevermined Payments Library?

The Nevermined Payments Library is a Python SDK that allows AI Builders and Subscribers to make AI Agents available for querying and use by other agents or humans. It is designed to be used alongside the Nevermined protocol, which provides a decentralized infrastructure for managing AI agents and their interactions.

The Payments Library enables:

  • Easy registration and discovery of AI agents and the payment plans required to access them. All agents registered in Nevermined expose their metadata in a generic way, making them searchable and discoverable for specific purposes.
  • Flexible definition of pricing options and how AI agents can be queried. This is achieved through payment plans (based on time or credits) and consumption costs (fixed per request or dynamic). All of this can be defined by the AI builder or agent during the registration process.
  • Subscribers (humans or other agents) to purchase credits that grant access to AI agent services. Payments can be made in crypto or fiat via Stripe integration. The protocol registers the payment and credits distribution settlement on-chain.
  • Agents or users with access credits to query other AI agents. Nevermined authorizes only users with sufficient balance and keeps track of their credit usage.

Initialize the payments library

from payments_py import Payments, PaymentOptions

payments = Payments.get_instance(
    PaymentOptions(nvm_api_key=nvm_api_key, environment="sandbox", app_id="your_app_id", version="1.0.0")
)

Optional integrations

The core SDK has no integration dependencies. Add one or more of the following extras when installing:

Extra Pulls in Purpose
fastapi fastapi, starlette payments_py.x402.fastapi.PaymentMiddleware for HTTP route-level payment gating
strands strands-agents Strands @requires_payment decorator
langchain langchain-core LangChain @requires_payment decorator + create_paid_react_agent
langsmith langsmith Auto-emit nvm:verify and nvm:settlement spans into LangSmith traces when LANGSMITH_TRACING=true
traceloop traceloop-sdk (+ OpenTelemetry) payments.observability.with_async_logger(...) — auto-instrument LLM calls and export tagged spans to Helicone
pip install "payments-py[langchain,langsmith]"

A2A Integration (Agents-to-Agents)

The Python SDK can both start an A2A server (FastAPI-based) and act as an A2A client.

What you need to expose an A2A agent with Nevermined

  • Publish an Agent Card at /.well-known/agent.json describing the agent.
  • Declare capabilities.streaming: true if you support message/stream and tasks/resubscribe.
  • Use HTTP auth via headers (e.g., Authorization: Bearer <token>), not inside JSON-RPC payloads.
  • Include a Nevermined payment extension in the Agent Card to enable authorization and credit burning per request.
  • Ensure the Agent Card url matches exactly the endpoint where your A2A server listens.

Nevermined payment extension in the Agent Card

Add the following structure to capabilities.extensions of your Agent Card:

{
  "capabilities": {
    "streaming": true,
    "pushNotifications": true,
    "extensions": [
      {
        "uri": "urn:nevermined:payment",
        "description": "Dynamic cost per request",
        "required": false,
        "params": {
          "paymentType": "dynamic",
          "credits": 1,
          "planId": "<planId>",
          "agentId": "<agentId>"
        }
      }
    ]
  },
  "url": "https://your-agent.example.com/a2a/"
}

Important:

  • The final streaming event of your agent should include metadata.creditsUsed to allow Nevermined to burn credits.
  • The exact URL (including basePath) must match the registration in Nevermined, otherwise validation will fail.

Build a payment-enabled Agent Card

from payments_py import Payments, PaymentOptions

payments_builder = Payments({
    "nvm_api_key": "<BUILDER_API_KEY>",
    "environment": "sandbox",
})

base_agent_card = {
    "name": "Py A2A Agent",
    "description": "A2A test agent",
    "capabilities": {
        "streaming": True,
        "pushNotifications": True,
        "stateTransitionHistory": True,
    },
    "defaultInputModes": ["text"],
    "defaultOutputModes": ["text"],
    "skills": [],
    "url": "https://your-agent.example.com/a2a/",
    "version": "1.0.0",
}

from payments_py.a2a.agent_card import build_payment_agent_card

agent_card = build_payment_agent_card(base_agent_card, {
    "paymentType": "dynamic",
    "credits": 1,
    "costDescription": "Dynamic cost per request",
    "planId": "<planId>",
    "agentId": "<agentId>",
})

Start an A2A server

from payments_py.a2a.server import PaymentsA2AServer

class DummyExecutor:
    async def execute(self, ctx, event_queue):
        event_queue.publish({
            "kind": "status-update",
            "taskId": ctx.taskId,
            "contextId": ctx.userMessage.get("contextId"),
            "status": {"state": "completed"},
            "metadata": {"creditsUsed": 1},
            "final": True,
        })
        event_queue.finished()

server = PaymentsA2AServer.start(
    agent_card=agent_card,
    executor=DummyExecutor(),
    payments_service=payments_builder,
    port=PORT,
    base_path="/a2a/",
)

Use the A2A client

payments_subscriber = Payments({
    "nvm_api_key": "<SUBSCRIBER_API_KEY>",
    "environment": "sandbox",
})

client = payments_subscriber.a2a.get_client(
    agent_base_url="https://your-agent.example.com/a2a/",
    agent_id="<agentId>",
    plan_id="<planId>",
)

# Send a simple request
result = await client.send_message({
    "message": {"kind": "message", "role": "user", "messageId": "123", "parts": [{"kind": "text", "text": "Hello"}]}
})

# Stream events
async for event in client.send_message_stream({
    "message": {"kind": "message", "role": "user", "messageId": "124", "parts": [{"kind": "text", "text": "Stream"}]}
}):
    if event.get("result", {}).get("final"):
        break

Plans helpers as static methods

You can build price and credits configurations through Payments.plans static helpers, mirroring payments_py/plans.py:

pc = payments_builder.plans.get_erc20_price_config(20, "0x...token...", payments_builder.account_address)
cc = payments_builder.plans.get_fixed_credits_config(100)

Typical API usage (Python)

from payments_py import Payments, PaymentOptions
from payments_py.common.types import PlanMetadata
from payments_py.x402 import (
    CreateDelegationPayload,
    DelegationConfig,
    X402TokenOptions,
)

payments = Payments.get_instance(
    PaymentOptions(nvm_api_key="<KEY>", environment="sandbox")
)

# Create a plan
plan_metadata = PlanMetadata(name="My Plan")
price = payments.plans.get_erc20_price_config(20, "0x...token...", payments.account_address)
credits = payments.plans.get_fixed_credits_config(100)
plan_res = payments.plans.register_credits_plan(plan_metadata, price, credits)
plan_id = plan_res["planId"]

# Register an agent
agent_res = payments.agents.register_agent(
    {"name": "My Agent"},
    {"endpoints": [{"POST": "https://your-agent.example.com/a2a/"}]},
    [plan_id],
)
agent_id = agent_res["agentId"]

# Order plan (optional - only needed for traditional credit-based access)
payments.plans.order_plan(plan_id)

# Get plan balance
balance = payments.plans.get_plan_balance(plan_id)

# Get x402 access token (for agent-to-agent authentication)
access = payments.x402.get_x402_access_token(plan_id, agent_id)
token = access["accessToken"]

# Or a single-use token bound to one seller endpoint (v3). Bind the SAME string
# the seller advertises in its 402 — here, the endpoint registered above.
delegation = payments.delegation.create_delegation(
    CreateDelegationPayload(
        provider="erc4337",
        spending_limit_cents=10000,
        duration_secs=604800,
        currency="usdc",
    )
)
access = payments.x402.get_x402_access_token(
    plan_id,
    agent_id,
    token_options=X402TokenOptions(
        delegation_config=DelegationConfig(delegation_id=delegation.delegation_id),
        resource="https://your-agent.example.com/a2a/",
        http_verb="POST",
        token_version=3,
    ),
)
if access.get("tokenVersion") == 3:
    ...  # consumed by its first settle — mint a fresh one per paid request

See Access Token Versions for the v2/v3 difference and the BCK.X402.0059 "already used" error.

Development

Setup

poetry install
poetry run pre-commit install

The second command wires a git hook (lives at .git/hooks/pre-commit) that runs black on staged Python files before every commit. CI enforces the same rules, so skipping the local hook just defers the failure to push time.

If you'd rather have pre-commit hooks wired automatically on every fresh clone of any repo, set up a global git template once on your machine:

pipx install pre-commit
git config --global init.templateDir ~/.git-template
pre-commit init-templatedir ~/.git-template

After that, git clone of any repo with a .pre-commit-config.yaml (this one, for instance) auto-installs its hooks — no per-repo pre-commit install step needed.

Running the formatter manually

poetry run black .              # format everything
poetry run black --check .      # CI-style check, no changes

Running tests

poetry install --extras "strands langchain"   # install all optional extras
poetry run pytest -m "not slow"               # full unit + integration suite
poetry run pytest tests/unit/x402/            # one directory

Custom CA bundle (self-signed-cert environments)

The SDK uses requests' default TLS verification against the system trust store. Public Nevermined backends (sandbox, live) serve real certs, so no configuration is needed.

If you're pointing the SDK at a dev environment that serves a self-signed certificate (e.g. a local Caddy with its own CA), export REQUESTS_CA_BUNDLE before running — requests reads it directly, no SDK change required:

export REQUESTS_CA_BUNDLE=/path/to/your-ca.pem
poetry run python your_script.py

Metadata

Release files for payments-py 1.19.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for payments-py 1.19.1
File Size Uploaded Provenance Actions
payments_py-1.19.1.tar.gz 280.6 kB Without provenance Details for payments_py-1.19.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for payments-py 1.19.1
File Interpreter ABI Platform Actions
payments_py-1.19.1-py3-none-any.whl Python 3 none any Details for payments_py-1.19.1-py3-none-any.whl

Total release size: 620.7 kB

Release files / payments_py-1.19.1.tar.gz

Download URL payments_py-1.19.1.tar.gz
Size 280.6 kB
Tags Source
SHA-256 checksum
How to use checksums
34ec3fd3ca80d9f3973e2c1a1a8060db499c3d916f812fd667b9789c3a383c6e
BLAKE2b-256 checksum
How to use checksums
d3cc7e553709c39d7b63e053b1e27682973c486a9b5a7dc586753e99fdb3db1e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.5.1 CPython/3.14.4 Linux/7.0.0-1019-azure

Release files / payments_py-1.19.1-py3-none-any.whl

Download URL payments_py-1.19.1-py3-none-any.whl
Size 340.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
2ad1ee9e3c10c3dbd4e342ade20e8a693c3187925a6d66a554c84fb7b455282b
BLAKE2b-256 checksum
How to use checksums
91fa1a1f1413f4db0b9009e9a6fcaf887a787b226c53163b3ba552804a92e6b3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.5.1 CPython/3.14.4 Linux/7.0.0-1019-azure

Security for payments-py 1.19.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.19.1 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page