### Get Help for Nevermined CLI Commands Source: https://github.com/nevermined-io/docs/blob/main/docs/api-reference/cli/getting-started.md Provides examples of how to access help information for the Nevermined CLI at different levels: general help, topic-specific help, and command-specific help. ```bash # General help nvm --help # Topic help nvm plans --help # Command help nvm plans get-plan --help ``` -------------------------------- ### Run TypeScript Example with Dependencies Source: https://github.com/nevermined-io/docs/blob/main/docs/integrate/quickstart/typescript.mdx Instructions to install project dependencies and run the TypeScript example using `ts-node`. This allows for direct execution of TypeScript files without prior compilation. ```bash # Install dependencies npm install express @nevermined-io/payments # Run in development npx ts-node index.ts ``` -------------------------------- ### Install and Run Nevermined Docs Locally Source: https://github.com/nevermined-io/docs/blob/main/CLAUDE.md This snippet demonstrates how to set up and run the Nevermined documentation locally using Mintlify. It includes installing the Mintlify CLI, navigating to the docs directory, and starting the development server for hot-reloading. ```bash # 1. Install Mintlify CLI globally npm install -g mintlify # 2. Navigate to the docs directory cd /path/to/docs # 3. Start local dev server with hot reload mintlify dev # 4. Open browser to http://localhost:3000 ``` -------------------------------- ### Verify Nevermined CLI Setup Source: https://github.com/nevermined-io/docs/blob/main/docs/api-reference/cli/getting-started.md Tests the Nevermined CLI installation and configuration by attempting to list available payment plans. A successful execution indicates that the CLI is set up correctly. ```bash nvm plans get-plans ``` -------------------------------- ### Sequential Setup Steps with Tabs (MDX) Source: https://github.com/nevermined-io/docs/blob/main/CLAUDE.md Illustrates a multi-step setup process using Nevermined's Steps and Tabs components. Supports code examples in different languages within each step. ```mdx Instructions and context. ```typescript // code here ``` ```python # code here ``` More instructions. ``` -------------------------------- ### Initialize Nevermined CLI Configuration Source: https://github.com/nevermined-io/docs/blob/main/docs/api-reference/cli/getting-started.md Starts an interactive setup process to configure the Nevermined CLI. It prompts the user for their NVM API Key and the desired environment (sandbox or live). ```bash nvm config init ``` -------------------------------- ### Purchase Plan and Get Access Token (Python) Source: https://github.com/nevermined-io/docs/blob/main/docs/integrate/quickstart/5-minute-setup.mdx This Python code illustrates the process of ordering a plan, retrieving the plan balance, and generating an x402 access token using the Nevermined payments library. The obtained access token is used for subsequent API calls. ```python import os from payments_py import Payments, PaymentOptions payments = Payments.get_instance( PaymentOptions(nvm_api_key=os.environ['NVM_API_KEY'], environment='sandbox') ) # Order the plan order_result = payments.plans.order_plan(plan_id) # Get your balance about the plan you just ordered balance = payments.plans.get_plan_balance(plan_id) # Generate the x402 access token token_res = payments.x402.get_x402_access_token(plan_id, agent_id) access_token = token_res['accessToken'] ``` -------------------------------- ### Install Nevermined CLI Globally Source: https://github.com/nevermined-io/docs/blob/main/docs/api-reference/cli/getting-started.md Installs the Nevermined CLI globally using npm, allowing it to be used from any directory. This is the recommended installation method for general use. ```bash npm install -g @nevermined-io/cli ``` -------------------------------- ### Quick Start: Complete MCP Server Setup Source: https://github.com/nevermined-io/docs/blob/main/skills/nevermined-payments/references/mcp-paywall.md Demonstrates a complete setup of an MCP server with paywall protection. It initializes the Payments instance, registers a tool with a fixed credit cost, and starts the server. The server includes Express, OAuth 2.1 endpoints, MCP transport, session management, and graceful shutdown. ```typescript import { Payments } from "@nevermined-io/payments" import { z } from "zod" const payments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, environment: "sandbox" }) // Register tools with built-in paywall payments.mcp.registerTool( "weather.today", { title: "Today's Weather", description: "Get weather for a city", inputSchema: z.object({ city: z.string().min(2).max(80).describe("City name") }) }, async (args, extra, context) => { console.log(`Request ID: ${context?.authResult.requestId}`) console.log(`Credits charged: ${context?.credits}`) const weather = await fetchWeather(args.city) return { content: [{ type: "text", text: `Weather in ${args.city}: ${weather.description}, ${weather.temp}°C` }] } }, { credits: 5n } ) // Start everything (MCP Server + Express + OAuth) const { info, stop } = await payments.mcp.start({ port: 3000, agentId: process.env.NVM_AGENT_ID!, serverName: "my-weather-server", version: "1.0.0", description: "Weather MCP server with OAuth authentication" }) console.log(`Server running at ${info.baseUrl}/mcp`) process.on("SIGINT", async () => { await stop() process.exit(0) }) ``` -------------------------------- ### Nevermined CLI Installation and Configuration (Bash) Source: https://context7.com/nevermined-io/docs/llms.txt This section covers the installation and initial configuration of the Nevermined Command Line Interface (CLI). It includes global installation, verification, interactive setup, viewing configuration, using environment variables, and managing multiple configuration profiles. ```bash # Install globally npm install -g @nevermined-io/cli # Verify installation nvm --version # Interactive configuration nvm config init # ? Enter your NVM API Key: sandbox:eyJxxxxaaaabbbbbbbb # ? Select environment: sandbox # ✅ Configuration saved to ~/.config/nvm/config.json # View current configuration nvm config show # Use environment variables export NVM_API_KEY=sandbox:eyJxxxxaaaabbbbbbbb export NVM_ENVIRONMENT=sandbox # Create multiple profiles nvm config set profiles.production.nvmApiKey nvm-yyyyyyyy... nvm config set profiles.production.environment live nvm config set activeProfile production # Use specific profile for commands nvm --profile production plans list ``` -------------------------------- ### Starting Processing Requests (Python) Source: https://github.com/nevermined-io/docs/blob/main/docs/development-guide/observability.mdx Provides Python examples for starting a regular processing request and a batch processing request. Regular requests handle individual operations, while batch requests group multiple operations under one identifier for efficient credit redemption. ```python # Regular request - process one request at a time agent_request = payments.requests.start_processing_request( agent_id, auth_header, requested_url, http_verb ) # Batch request - process multiple requests together agent_request = payments.requests.start_processing_batch_request( agent_id, auth_header, requested_url, http_verb ); ``` -------------------------------- ### Purchase Plan and Get Access Token (TypeScript) Source: https://github.com/nevermined-io/docs/blob/main/docs/integrate/quickstart/5-minute-setup.mdx This TypeScript code demonstrates how a subscriber can order a plan, check their balance, and generate an x402 access token. The generated token is crucial for making authenticated requests to the Nevermined API. ```typescript import { Payments } from '@nevermined/payments' // As a subscriber const payments = Payments.getInstance({ nvmApiKey: subscriberKey, environment: 'sandbox' }) // Order the plan await payments.plans.orderPlan(PLAN_ID) // Get your balance about the plan you just ordered const balance = await payments.plans.getPlanBalance(PLAN_ID) // Generate the x402 access token const { accessToken } = await payments.x402.getX402AccessToken(PLAN_ID, AGENT_ID) // Use this token in the next request // HTTP header: 'payment-signature' // value: `${accessToken}` ``` -------------------------------- ### Set up Nevermined environment variables Source: https://github.com/nevermined-io/docs/blob/main/docs/api-reference/python/installation.mdx Example environment variables required for the Nevermined Payments Python SDK. This includes the mandatory API key and optional URLs for custom backend and proxy configurations. ```bash # Required NVM_API_KEY=sandbox:your-api-key-here # Optional (for custom environments) NVM_BACKEND_URL=https://api.sandbox.nevermined.app NVM_PROXY_URL=https://proxy.sandbox.nevermined.app ``` -------------------------------- ### Complete Purchase Flow Example (Bash) Source: https://github.com/nevermined-io/docs/blob/main/docs/api-reference/cli/purchases.md This script outlines a complete purchase workflow, including browsing plans, getting plan details, checking balance, purchasing a plan, verifying the purchase, and obtaining an access token. It utilizes various `nvm plans` commands and `nvm x402token`. ```bash #!/bin/bash # Complete purchase workflow # 1. Browse available plans echo "Available Plans:" nvm plans get-plans # 2. Get details about a specific plan PLAN_ID="123456789012345678" nvm plans get-plan $PLAN_ID # 3. Check current balance echo "Current balance:" nvm plans get-plan-balance $PLAN_ID # 4. Purchase the plan echo "Purchasing plan..." nvm plans order-plan $PLAN_ID # 5. Verify purchase echo "New balance:" nvm plans get-plan-balance $PLAN_ID # 6. Get access token for using the service echo "Getting access token..." nvm x402token get-x402-access-token $PLAN_ID ``` -------------------------------- ### POST /query (With Payment) Source: https://github.com/nevermined-io/docs/blob/main/docs/integrate/quickstart/5-minute-setup.mdx This endpoint allows querying the service after successfully obtaining an access token through the payment process. The token must be included in the `payment-signature` header. ```APIDOC ## POST /query (With Payment) ### Description Queries the service using a valid `payment-signature` obtained after purchasing a plan. This ensures authenticated and authorized access to the service. ### Method POST ### Endpoint /query ### Parameters #### Query Parameters None #### Request Body - **prompt** (string) - Required - The query prompt to send to the service. #### Headers - **payment-signature** (string) - Required - The x402 access token obtained after plan purchase. ### Request Example ```bash curl -X POST http://localhost:3000/query \ -H "Content-Type: application/json" \ -H "payment-signature: ${accessToken}" \ -d '{"prompt": "Hello"}' ``` ### Response #### Success Response (200 OK) - **result** (string) - The result of the query. - **creditsRemaining** (integer) - The number of credits remaining on the user's plan. #### Response Example ```json { "result": "Hello! How can I help you today?", "creditsRemaining": 99 } ``` ``` -------------------------------- ### Plan Purchase and Token Generation Source: https://github.com/nevermined-io/docs/blob/main/docs/integrate/quickstart/5-minute-setup.mdx This section details the process of ordering a plan, checking its balance, and generating an x402 access token required for authenticated requests. ```APIDOC ## Plan Purchase and Token Generation ### Description This process involves using the Nevermined SDK to order a service plan, verify the balance of that plan, and then generate an `x402` access token. This token is crucial for authenticating subsequent requests to the API. ### Method N/A (SDK Operations) ### Endpoint N/A (SDK Operations) ### Parameters (These are SDK parameters, not direct API parameters) #### TypeScript SDK - **subscriberKey** (string) - Your Nevermined API key. - **environment** (string) - The environment to connect to (e.g., 'sandbox'). - **PLAN_ID** (string) - The identifier of the plan to order. - **AGENT_ID** (string) - The identifier of the agent associated with the plan. #### Python SDK - **nvm_api_key** (string) - Your Nevermined API key. - **environment** (string) - The environment to connect to (e.g., 'sandbox'). - **plan_id** (string) - The identifier of the plan to order. - **agent_id** (string) - The identifier of the agent associated with the plan. ### Request Example (Code examples provided in TypeScript and Python) ### Response #### Success Response (Token Generation) - **accessToken** (string) - The generated x402 access token. #### Response Example (Conceptual) ```json { "accessToken": "your_generated_access_token" } ``` ``` -------------------------------- ### Install Nevermined Payments Library (TypeScript/JavaScript) Source: https://github.com/nevermined-io/docs/blob/main/docs/development-guide/getting-started.mdx Installs the Nevermined Payments library for TypeScript and JavaScript projects using npm or yarn. Ensure Node.js 16+ is installed. ```bash npm install @nevermined-io/payments # or yarn add @nevermined-io/payments ``` -------------------------------- ### Run Nevermined CLI with npx Source: https://github.com/nevermined-io/docs/blob/main/docs/api-reference/cli/getting-started.md Executes the Nevermined CLI without a global installation using npx. This is useful for one-off commands or testing the CLI before committing to an installation. ```bash npx @nevermined-io/cli --help ``` -------------------------------- ### Execute Server and API Calls Source: https://github.com/nevermined-io/docs/blob/main/docs/integrate/quickstart/python.mdx This section provides command-line instructions for running the server and testing API endpoints. It includes commands for starting the server directly with Uvicorn and using cURL to interact with the /setup and /query endpoints, demonstrating agent registration and basic query functionality. ```bash # Run the server python main.py # Or with uvicorn directly uvicorn main:app --reload --port 8000 ``` ```bash curl -X POST http://localhost:8000/setup ``` ```bash curl -X POST http://localhost:8000/query \ -H "Content-Type: application/json" \ -d '{"prompt": "Hello"}' ``` -------------------------------- ### Run Agent Registration Script Source: https://github.com/nevermined-io/docs/blob/main/docs/integrate/quickstart/5-minute-setup.mdx Instructions for running the agent registration scripts. This section provides the command-line commands for executing both the TypeScript and Python scripts. ```bash npx ts-node register-agent.ts ``` ```bash python register_agent.py ``` -------------------------------- ### Install Nevermined CLI from Source Source: https://github.com/nevermined-io/docs/blob/main/docs/api-reference/cli/getting-started.md Installs the Nevermined CLI from its source code repository. This method is intended for developers who wish to contribute to the project or need the latest development version. ```bash git clone https://github.com/nevermined-io/payments cd payments/cli yarn install yarn build:manifest ./bin/run.js --help ``` -------------------------------- ### Low-Level Server Example - Python/ASGI Source: https://github.com/nevermined-io/docs/blob/main/files/nevermined_mcp_for_llms.txt Demonstrates how to integrate `withPaywall` with a low-level ASGI server in Python. It shows the manual extraction of HTTP headers to build the `extra` context, which is crucial for passing authentication information to the protected handler. ```python from payments_py.mcp import build_extra_from_http_headers async def my_asgi_app(scope, receive, send): # ... headers = {k.decode(): v.decode() for k, v in scope.get("headers", [])} extra = build_extra_from_http_headers(headers) # CRITICAL: Pass `extra` as the second argument result = await protected_handler(arguments, extra) # ... ``` -------------------------------- ### Full Agent Setup Script Source: https://github.com/nevermined-io/docs/blob/main/docs/api-reference/cli/agents.md A bash script demonstrating the complete workflow for registering and configuring an AI agent. It covers creating a payment plan, registering the agent with that plan, updating agent metadata, and verifying agent accessibility. ```bash #!/bin/bash # Complete agent setup script # 1. Create a payment plan first PLAN_ID=$(nvm plans register-credits-plan \ --plan-metadata plan.json \ --price-config price.json \ --credits-config credits.json \ --format json | jq -r '.planId') echo "Created plan: $PLAN_ID" # 2. Register the agent with the plan AGENT_ID=$(nvm agents register-agent \ --agent-metadata agent.json \ --agent-api "https://api.example.com/agent" \ --payment-plans "$PLAN_ID" \ --format json | jq -r '.agentId') echo "Registered agent: $AGENT_ID" # 3. Update agent metadata if needed nvm agents update-agent-metadata $AGENT_ID \ --agent-metadata updated-agent.json # 4. Verify agent is accessible nvm agents get-agent $AGENT_ID echo "Agent setup complete!" ``` -------------------------------- ### Update Quickstart to Use Middleware Source: https://github.com/nevermined-io/docs/blob/main/evaluation/IMPROVEMENTS.md Revises Step 4 of the quickstart guide to replace an outdated proxy-based validation example with the modern x402 middleware approach using `paymentMiddleware` (Express) or `PaymentMiddleware` (FastAPI). This aligns the quickstart with current best practices. ```markdown Replace with `paymentMiddleware` (Express) or `PaymentMiddleware` (FastAPI) example. This is the recommended approach in the Skill and SDK docs. ``` -------------------------------- ### Nevermined CLI Configuration File Example Source: https://github.com/nevermined-io/docs/blob/main/docs/api-reference/cli/getting-started.md Illustrates the structure of the Nevermined CLI configuration file, typically located at `~/.config/nvm/config.json`. It shows how API keys and environments are stored for different profiles. ```json { "profiles": { "default": { "nvmApiKey": "live:eyJxxxxaaaabbbbbbbb", "environment": "live" } }, "activeProfile": "default" } ``` -------------------------------- ### Complete Nevermined Payments Python Example Source: https://github.com/nevermined-io/docs/blob/main/docs/integrate/quickstart/python.mdx A comprehensive FastAPI application demonstrating Nevermined payments. It includes models for requests and responses, a setup route for agent and plan registration, middleware for payment validation using X402 tokens, and protected API endpoints for querying the AI agent. This example uses USDC on Base Sepolia for payments. ```python import os from fastapi import FastAPI, Request, HTTPException, Depends from pydantic import BaseModel from payments_py import Payments, PaymentOptions from payments_py.plans import get_erc20_price_config, get_fixed_credits_config app = FastAPI(title="My AI Agent") # In this example we require a payment of 10 USDC for 100 requests # For that USDC payment we use USDC on Base Sepolia, so we need its contract address: USDC_ADDRESS = '0x036CbD53842c5426634e7929541eC2318f3dCF7e' # Initialize payments payments = Payments.get_instance( PaymentOptions( nvm_api_key=os.environ['NVM_API_KEY'], environment='sandbox' ) ) # Store IDs after registration agent_id = os.environ.get('AGENT_ID', '') plan_id = os.environ.get('PLAN_ID', '') # ============================================ # MODELS # ============================================ class QueryRequest(BaseModel): prompt: str class QueryResponse(BaseModel): result: str credits_remaining: int # ============================================ # SETUP: Run once to register your agent # ============================================ @app.post("/setup") async def register_agent(): global agent_id, plan_id result = payments.agents.register_agent_and_plan( agent_metadata={ 'name': 'My Python AI Agent', 'description': 'AI assistant built with Python', 'tags': ['ai', 'python'] }, agent_api={ 'endpoints': [{'POST': 'http://localhost:8000/query'}] }, plan_metadata={ 'name': 'Starter Plan', 'description': '100 queries' }, price_config=get_erc20_price_config( 10_000_000, # 10 USDC USDC_ADDRESS, os.environ['BUILDER_ADDRESS'] ), credits_config=get_fixed_credits_config(100, 1), access_limit='credits' ) agent_id = result['agentId'] plan_id = result['planId'] return { 'agent_id': agent_id, 'plan_id': plan_id, 'message': 'Add these to your .env file!' } # ============================================ # MIDDLEWARE: Validate payments # ============================================ async def validate_payment(request: Request) -> int: """Validate payment and return remaining credits.""" from payments_py.x402.helpers import build_payment_required x402_token = request.headers.get("payment-signature") if not x402_token: raise HTTPException(status_code=402, detail="Payment required") # Build payment requirements payment_required = build_payment_required( plan_id=plan_id, endpoint=str(request.url), agent_id=agent_id, http_verb=request.method ) # Verify permissions verification = payments.facilitator.verify_permissions( payment_required=payment_required, x402_access_token=x402_token, max_amount="1" ) if not verification.get("is_valid"): raise HTTPException(status_code=402, detail="Invalid payment") return verification.get("remaining_credits", 0) # ============================================ # ROUTES # ============================================ @app.get("/health") async def health(): """Health check (public).""" return { 'status': 'ok', 'agent_id': agent_id, 'plan_id': plan_id } @app.post("/query", response_model=QueryResponse) async def query( request: QueryRequest, credits: int = Depends(validate_payment) ): """Protected AI endpoint.""" # Your AI logic here result = f'You asked: "{request.prompt}". Here\'s my response...' return QueryResponse( result=result, credits_remaining=credits ) # ============================================ # MAIN ``` -------------------------------- ### Install Nevermined Payments Package Source: https://github.com/nevermined-io/docs/blob/main/docs/integrate/quickstart/typescript.mdx Installs the necessary Nevermined payments package using npm. This is the first step to integrating payment functionalities into your project. ```bash npm install @nevermined-io/payments ``` -------------------------------- ### Test API Query With Payment (Bash) Source: https://github.com/nevermined-io/docs/blob/main/docs/integrate/quickstart/5-minute-setup.mdx This snippet shows how to make a POST request to the /query endpoint after obtaining an access token. The 'payment-signature' header is included with the generated access token, allowing for successful query execution and returning results. ```bash curl -X POST http://localhost:3000/query \ -H "Content-Type: application/json" \ -H "payment-signature: ${accessToken}" \ -d '{"prompt": "Hello"}' ``` -------------------------------- ### Install and Run Mintlify CLI for Local Development Source: https://github.com/nevermined-io/docs/blob/main/README.md This snippet shows how to install the Mintlify CLI globally and then run the development server from the project root. This allows for local previewing and editing of documentation with hot reloading. ```bash npm install -g mintlify mintlify dev ``` -------------------------------- ### Install Nevermined Payments Python Packages Source: https://github.com/nevermined-io/docs/blob/main/docs/integrate/quickstart/python.mdx Installs the necessary Python packages for Nevermined payments, including `payments-py`, `fastapi`, and `uvicorn` for building the API. ```bash pip install payments-py fastapi uvicorn ``` -------------------------------- ### POST /query (Without Payment) Source: https://github.com/nevermined-io/docs/blob/main/docs/integrate/quickstart/5-minute-setup.mdx This endpoint allows querying the service. Without a valid payment signature, the request will fail, prompting the user to purchase a plan. ```APIDOC ## POST /query (Without Payment) ### Description Attempts to query the service without providing payment information. This request is expected to fail and return an error indicating that a plan needs to be purchased. ### Method POST ### Endpoint /query ### Parameters #### Query Parameters None #### Request Body - **prompt** (string) - Required - The query prompt to send to the service. ### Request Example ```json { "prompt": "Hello" } ``` ### Response #### Error Response (402 Payment Required) - **error** (string) - Indicates the type of error, e.g., "Payment Required". - **message** (string) - A human-readable message explaining the error. - **plans** (array) - A list of available plans that can be purchased. - **planId** (string) - The identifier for the plan. - **agentId** (string) - The identifier for the agent associated with the plan. #### Response Example ```json { "error": "Payment Required", "message": "Purchase a plan to access this API", "plans": [ { "planId": "did:nv:...", "agentId": "did:nv:..." } ] } ``` ``` -------------------------------- ### Install Nevermined Payments SDK (npm, pip) Source: https://github.com/nevermined-io/docs/blob/main/docs/integrate/quickstart/5-minute-setup.mdx Installs the Nevermined payments SDK for either TypeScript (npm) or Python (pip). These SDKs are essential for integrating payment functionalities into your applications. ```bash npm install @nevermined-io/payments ``` ```bash pip install payments-py ``` -------------------------------- ### Custom Low-Level Server (ASGI Python) Source: https://github.com/nevermined-io/docs/blob/main/docs/integrations/mcp.mdx Provides an example of setting up a custom MCP server using ASGI in Python. ```APIDOC ## Custom Low-Level Server (ASGI Python) ### Description This example shows how to build a custom ASGI application for an MCP server in Python, handling request parsing and routing. ### Method N/A (ASGI application) ### Endpoint N/A (ASGI application) ### Parameters N/A ### Request Example N/A ### Response N/A ### Python Code Example ```python # lowlevel_app.py from payments_py.mcp import build_extra_from_http_headers import json async def app(scope, receive, send): # Parse request headers = {k.decode(): v.decode() for k, v in scope.get("headers", [])} extra = build_extra_from_http_headers(headers) # Read body... body_bytes = b'' while True: message = await receive() body_bytes += message.get('body', b'') if message.get('type') == 'http.request' and not message.get('more_body'): break req = json.loads(body_bytes.decode()) # Route and call handler if req.get("method") == "tools/call": handler = get_tool_handler(req["params"]["name"]) result = await handler(req["params"]["arguments"], extra) response_body = json.dumps({"jsonrpc": "2.0", "id": req.get("id"), "result": result}).encode('utf-8') await send({ 'type': 'http.response.start', 'status': 200, 'headers': [ [b'content-type', b'application/json'], ], }) await send({ 'type': 'http.response.body', 'body': response_body, }) else: # Handle other methods or errors pass def get_tool_handler(name): # Placeholder for actual handler retrieval logic async def dummy_handler(args, extra): print(f"Called handler for {name} with args: {args} and extra: {extra}") return {"message": f"Handled {name}"} return dummy_handler ``` ``` -------------------------------- ### Register Agent and Payment Plan with Python Source: https://github.com/nevermined-io/docs/blob/main/docs/integrate/quickstart/5-minute-setup.mdx This Python code snippet shows how to register a service (agent) and its payment plan using the Nevermined Payments SDK. It requires environment variables for the API key and builder address, and configures a plan with USDC payment and fixed credits. ```python import os from payments_py import Payments, PaymentOptions from payments_py.plans import get_erc20_price_config, get_fixed_credits_config # In this example we require a payment of 10 USDC for 100 requests # For that USDC payment we use USDC on Base Sepolia, so we need its contract address: USDC_ADDRESS = '0x036CbD53842c5426634e7929541eC2318f3dCF7e' def main(): payments = Payments.get_instance( PaymentOptions( nvm_api_key=os.environ['NVM_API_KEY'], environment='sandbox' ) ) result = payments.agents.register_agent_and_plan( agent_metadata={ 'name': 'My AI Assistant', 'description': 'A paid service (agent API / MCP tool / protected resource)', 'tags': ['ai', 'payments'] }, agent_api={ 'endpoints': [{'POST': 'https://your-api.com/query'}] }, plan_metadata={ 'name': 'Starter Plan', 'description': '100 requests for $10' }, price_config=get_erc20_price_config( 10_000_000, # 10 USDC (6 decimals) USDC_ADDRESS, os.environ['BUILDER_ADDRESS'] ), credits_config=get_fixed_credits_config(100, 1), access_limit='credits' ) print('Registered!') print(f"Service (agent) ID: {result['agentId']}") print(f"Plan ID: {result['planId']}") print('\nSave these IDs for your integration.') if __name__ == '__main__': main() ``` -------------------------------- ### Complete Plan Creation and Subscription Example with Python SDK Source: https://github.com/nevermined-io/docs/blob/main/docs/api-reference/python/balance-module.mdx Demonstrates a full workflow: a plan owner registers a new credit plan (ERC20 based), a subscriber checks their initial balance, and then orders the plan. This example covers plan registration, balance checking, and plan ordering using two different SDK instances for builder and subscriber roles. ```python from payments_py import Payments, PaymentOptions from payments_py.common.types import PlanMetadata from payments_py.plans import get_erc20_price_config, get_fixed_credits_config # Initialize as builder (plan owner) payments_builder = Payments.get_instance( PaymentOptions(nvm_api_key="nvm:builder-key", environment="sandbox") ) # Initialize as subscriber payments_subscriber = Payments.get_instance( PaymentOptions(nvm_api_key="nvm:subscriber-key", environment="sandbox") ) ERC20_TOKEN = "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d" builder_address = payments_builder.account_address # 1. Builder creates a plan plan_result = payments_builder.plans.register_credits_plan( plan_metadata=PlanMetadata(name="Premium Plan"), price_config=get_erc20_price_config(20, ERC20_TOKEN, builder_address), credits_config=get_fixed_credits_config(100) ) plan_id = plan_result['planId'] print(f"Created plan: {plan_id}") # 2. Subscriber checks initial balance (should be 0 or not subscribed) initial_balance = payments_subscriber.plans.get_plan_balance(plan_id) print(f"Initial balance: {initial_balance.balance}") print(f"Is subscriber: {initial_balance.is_subscriber}") # 3. Subscriber orders the plan order_result = payments_subscriber.plans.order_plan(plan_id) print(f"Order success: {order_result['success']}") ``` -------------------------------- ### Multi-Tier Purchase Example (Bash) Source: https://github.com/nevermined-io/docs/blob/main/docs/api-reference/cli/purchases.md This script demonstrates purchasing different plan tiers based on usage needs, such as basic, pro, and custom enterprise plans. It shows how to order specific plan IDs and then check the balances for each purchased plan. ```bash #!/bin/bash # Purchase different tiers based on usage needs # Light user: Basic plan nvm plans order-plan "111111111111111111" # Power user: Pro plan nvm plans order-plan "222222222222222222" # Enterprise: Custom plan nvm plans order-plan "333333333333333333" # Check all balances echo "Current Balances:" nvm plans get-plan-balance "111111111111111111" nvm plans get-plan-balance "222222222222222222" nvm plans get-plan-balance "333333333333333333" ``` -------------------------------- ### Install Nevermined Rules for Amazon Q Developer Source: https://github.com/nevermined-io/docs/blob/main/docs/development-guide/build-using-nvm-skill.mdx Installs Nevermined rules for Amazon Q Developer by copying the rule file to your project's .amazonq/rules directory. This setup allows Amazon Q to recognize and utilize the Nevermined rules for relevant coding tasks. ```bash mkdir -p .amazonq/rules ``` -------------------------------- ### Install and Initialize Payments Library (Python) Source: https://github.com/nevermined-io/docs/blob/main/docs/getting-started/quickstart.mdx Install the payments-py library using pip and initialize the Payments client. This client facilitates interaction with Nevermined's payment services. The API key should be loaded from environment variables. ```bash pip install payments-py ``` ```python import os from payments_py import Payments, PaymentOptions payments = Payments.get_instance( PaymentOptions( nvm_api_key=os.environ.get('NVM_API_KEY'), environment='sandbox' # or 'live' ) ) ``` -------------------------------- ### Replace deprecated isValidRequest() in Quickstart and Patterns Source: https://github.com/nevermined-io/docs/blob/main/evaluation/IMPROVEMENTS.md Updates code examples in quickstart and various integration patterns to replace the deprecated `isValidRequest()` method with newer `paymentMiddleware`, `verifyPermissions`, or `settlePermissions` functions. Also addresses incorrect header usage. ```javascript import { paymentMiddleware } from '@nevermined-io/payments/express'; // ... Express app setup ... app.use(paymentMiddleware()); // ... rest of your Express app ``` ```javascript import { verifyPermissions, settlePermissions } from '@nevermined-io/payments'; // Assuming 'request' and 'response' are available const authorized = await verifyPermissions(request, response); if (authorized) { // Proceed with access } // For settling permissions after access await settlePermissions(request, response); ``` -------------------------------- ### Test API Query Without Payment (Bash) Source: https://github.com/nevermined-io/docs/blob/main/docs/integrate/quickstart/5-minute-setup.mdx This snippet demonstrates how to make a POST request to the /query endpoint without providing payment information. It is expected to fail with a 'Payment Required' error, indicating the need to purchase a plan. ```bash curl -X POST http://localhost:3000/query \ -H "Content-Type: application/json" \ -d '{"prompt": "Hello"}' ``` -------------------------------- ### Install and Initialize Payments SDK (Python) Source: https://github.com/nevermined-io/docs/blob/main/files/nevermined_mcp_for_llms.txt Installs the Nevermined Payments SDK using pip and initializes it with API keys and environment settings. Requires `payments-py` package and environment variables for API key and environment. ```bash pip install payments-py ``` ```python # payments_setup.py import os from payments_py.payments import Payments payments = Payments({ "nvm_api_key": os.environ["NVM_API_KEY"], "environment": os.environ.get("NVM_ENV", "sandbox"), # or "live" }) ``` -------------------------------- ### Complete TypeScript Example for Nevermined Payments Integration Source: https://github.com/nevermined-io/docs/blob/main/docs/integrate/quickstart/typescript.mdx A full-stack TypeScript example demonstrating the integration of Nevermined payments within an Express.js application. It covers agent and plan registration, payment validation middleware, and protected API routes. ```typescript import express from 'express' import { Payments, buildPaymentRequired } from '@nevermined-io/payments' const app = express() app.use(express.json()) // In this example we require a payment of 10 USDC for 100 requests // For that USDC payment we use USDC on Base Sepolia, so we need its contract address: const USDC_ADDRESS = '0x036CbD53842c5426634e7929541eC2318f3dCF7e' // Initialize payments const payments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, environment: 'sandbox' // or 'live' }) // Store IDs after registration let agentId: string let planId: string // ============================================ // SETUP: Run once to register your agent // ============================================ async function registerAgent() { const result = await payments.agents.registerAgentAndPlan( { name: 'My TypeScript AI Agent', description: 'AI assistant built with TypeScript', tags: ['ai', 'typescript'], dateCreated: new Date() }, { endpoints: [{ POST: `http://localhost:3000/query` }] }, { name: 'Starter Plan', description: '100 queries', dateCreated: new Date() }, payments.plans.getERC20PriceConfig(10_000_000n, USDC_ADDRESS, process.env.BUILDER_ADDRESS!), payments.plans.getFixedCreditsConfig(100n, 1n) ) agentId = result.agentId planId = result.planId console.log(`Agent ID: ${agentId}`) console.log(`Plan ID: ${planId}`) console.log('Add these to your .env file!') return result } // ============================================ // MIDDLEWARE: Validate payments // ============================================ async function validatePayment( req: express.Request, res: express.Response, next: express.NextFunction ) { // Get token from payment-signature header const x402Token = req.headers['payment-signature'] if (!x402Token) { // Return 402 with payment requirements return res.status(402).json({ error: 'Payment Required' }) } // Build payment required specification const paymentRequired = buildPaymentRequired(planId, { endpoint: req.url, agentId: agentId, httpVerb: req.method, }) // Verify permissions - facilitator extracts planId and subscriberAddress from token const verification = await payments.facilitator.verifyPermissions({ paymentRequired, x402AccessToken: x402Token, maxAmount: 1n, }) if (!verification.isValid) { return res.status(402).json({ error: 'Payment verification failed' }) } const balance = await payments.plans.getPlanBalance(planId) // Attach balance to request ;(req as any).credits = balance next() } // ============================================ // ROUTES // ============================================ // Health check (public) app.get('/health', (req, res) => { res.json({ status: 'ok', agentId, planId }) }) // Protected AI endpoint app.post('/query', validatePayment, async (req, res) => { const { prompt } = req.body // Your AI logic here const result = `You asked: "${prompt}". Here's my response...` res.json({ result, creditsRemaining: (req as any).credits }) }) // Setup endpoint (call once) app.post('/setup', async (req, res) => { try { const result = await registerAgent() res.json(result) } catch (error: any) { res.status(500).json({ error: error.message }) } }) // ============================================ // START SERVER // ============================================ const PORT = process.env.PORT || 3000 app.listen(PORT, () => { // Load IDs from environment if available agentId = process.env.AGENT_ID || '' planId = process.env.PLAN_ID || '' console.log(`Server running on http://localhost:${PORT}`) if (!agentId || !planId) { console.log('No agent registered yet. POST to /setup to register.') } else { console.log(`Agent: ${agentId}`) console.log(`Plan: ${planId}`) } }) ``` -------------------------------- ### Complete Weather Agent Example Source: https://github.com/nevermined-io/docs/blob/main/docs/api-reference/typescript/mcp-integration.md A comprehensive example demonstrating the creation of a weather agent. It registers multiple tools ('get_current_weather', 'get_forecast') and a resource ('weather-alerts'). The agent is configured with an agent ID and server name, and starts on port 5001 with graceful shutdown. ```typescript import { Payments, EnvironmentName } from '@nevermined-io/payments' import { z } from 'zod' const payments = Payments.getInstance({ nvmApiKey: process.env.NVM_API_KEY!, environment: 'sandbox' as EnvironmentName, }) // Configure MCP payments.mcp.configure({ agentId: process.env.NVM_AGENT_ID!, serverName: 'weather-agent', }) // Register multiple tools payments.mcp.registerTool( 'get_current_weather', { title: 'Get Current Weather', description: 'Get real-time weather for a location', inputSchema: z.object({ city: z.string(), country: z.string().optional(), }), }, async (args) => { const weather = await fetchWeather(args.city, args.country) return { content: [{ type: 'text', text: JSON.stringify(weather) }], } }, { credits: 1n } ) payments.mcp.registerTool( 'get_forecast', { title: 'Get Weather Forecast', description: 'Get 7-day weather forecast', inputSchema: z.object({ city: z.string(), days: z.number().min(1).max(7).default(3), }), }, async (args) => { const forecast = await fetchForecast(args.city, args.days) return { content: [{ type: 'text', text: JSON.stringify(forecast) }], } }, { credits: 2n } // Forecasts cost more ) // Register resource payments.mcp.registerResource( 'weather-alerts', 'weather://alerts', { title: 'Weather Alerts', description: 'Active weather alerts', }, async (uri) => { const alerts = await fetchAlerts() return { contents: [{ uri: 'weather://alerts', mimeType: 'application/json', text: JSON.stringify(alerts), }], } }, { credits: 1n } ) // Start server const { info, stop } = await payments.mcp.start({ port: 5001, agentId: process.env.NVM_AGENT_ID!, serverName: 'weather-agent', version: '1.0.0', }) console.log(`Weather MCP Agent running at ${info.baseUrl}`) console.log(`Register in Nevermined App with:`) console.log(` - mcp://weather-agent/tools/*`) console.log(` - mcp://weather-agent/resources/*`) // Graceful shutdown process.on('SIGINT', async () => { await stop() process.exit(0) }) // Mock functions async function fetchWeather(city: string, country?: string) { return { city, temp: 72, condition: 'sunny' } } async function fetchForecast(city: string, days: number) { return { city, days, forecast: [] } } async function fetchAlerts() { return { alerts: [] } } ``` -------------------------------- ### Add Complete .env Example to Skill Source: https://github.com/nevermined-io/docs/blob/main/evaluation/IMPROVEMENTS.md Suggests including a comprehensive `.env` file template in the Skill documentation. This example would cover required variables for various integrations, including API keys, environment settings, plan IDs, agent IDs, and builder addresses. ```bash # Required for all integrations NVM_API_KEY=nvm:your-api-key NVM_ENVIRONMENT=sandbox NVM_PLAN_ID=did:nv:your-plan-id # Required for MCP servers and multi-agent plans NVM_AGENT_ID=did:nv:your-agent-id # Required for plan registration BUILDER_ADDRESS=0xYourWalletAddress ``` -------------------------------- ### Get CLI Version Source: https://github.com/nevermined-io/docs/blob/main/docs/api-reference/cli/TESTING_NPM.md Displays the version information of the installed @nevermined-io/cli package. This command is useful for confirming the active version and ensuring compatibility. ```bash nvm --version @nevermined-io/cli/1.0.3-rc2 linux-x64 node-v24.10.0 ``` -------------------------------- ### Using `withPaywall` for Custom Servers Source: https://github.com/nevermined-io/docs/blob/main/docs/integrations/mcp.mdx Illustrates how to use the `withPaywall` function for granular control over custom MCP servers. ```APIDOC ## Using `withPaywall` for Custom Servers ### Description This method is for advanced use cases where you need fine-grained control over server-side logic, particularly for paywalled tools. ### Method N/A (SDK function usage) ### Endpoint N/A ### Parameters N/A ### Request Example ```typescript const protectedHandler = payments.mcp.withPaywall( myHandler, { kind: "tool", name: "my.tool", credits: 5n } ) ``` ### Response N/A ``` -------------------------------- ### View Current Nevermined CLI Configuration Source: https://github.com/nevermined-io/docs/blob/main/docs/api-reference/cli/getting-started.md Displays the currently active configuration settings for the Nevermined CLI, including the active profile, environment, and API key (truncated for security). ```bash nvm config show ``` -------------------------------- ### Complete Agent and Plan Management Example - Python Source: https://github.com/nevermined-io/docs/blob/main/docs/api-reference/python/agents-module.mdx Demonstrates a comprehensive workflow including initializing the SDK, creating payment plans, registering agents, registering agents and plans together, retrieving agent details, getting associated plans, and updating agent metadata. This example covers multiple functionalities within the payments SDK. ```python from payments_py import Payments, PaymentOptions from payments_py.common.types import AgentMetadata, AgentAPIAttributes, PlanMetadata from payments_py.plans import ( get_erc20_price_config, get_fixed_credits_config, get_free_price_config ) # Initialize payments = Payments.get_instance( PaymentOptions(nvm_api_key="nvm:your-key", environment="sandbox") ) ERC20_TOKEN = "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d" builder_address = payments.account_address # 1. Create a payment plan first plan_result = payments.plans.register_credits_plan( plan_metadata=PlanMetadata(name="AI Agent Plan"), price_config=get_erc20_price_config(20, ERC20_TOKEN, builder_address), credits_config=get_fixed_credits_config(100) ) plan_id = plan_result['planId'] # 2. Register an agent with the plan agent_result = payments.agents.register_agent( agent_metadata=AgentMetadata( name="My First AI Agent", description="A demo AI agent", tags=["demo", "ai"] ), agent_api=AgentAPIAttributes( endpoints=[{"POST": "https://api.example.com/agents/:agentId/tasks"}], agent_definition_url="https://api.example.com/openapi.json" ), payment_plans=[plan_id] ) agent_id = agent_result['agentId'] print(f"Created agent: {agent_id}") # 3. Or create both together combo_result = payments.agents.register_agent_and_plan( agent_metadata=AgentMetadata(name="Combo Agent"), agent_api=AgentAPIAttributes( endpoints=[{"POST": "https://api.example.com/combo"}], agent_definition_url="https://api.example.com/openapi.json" ), plan_metadata=PlanMetadata(name="Combo Plan"), price_config=get_free_price_config(), credits_config=get_fixed_credits_config(10) ) print(f"Combo Agent: {combo_result['agentId']}, Plan: {combo_result['planId']}") # 4. Retrieve agent details agent = payments.agents.get_agent(agent_id) print(f"Agent details: {agent}") # 5. Get associated plans plans = payments.agents.get_agent_plans(agent_id) print(f"Agent plans: {plans}") # 6. Update agent metadata payments.agents.update_agent_metadata( agent_id=agent_id, agent_metadata=AgentMetadata(name="Updated Agent Name"), agent_api=AgentAPIAttributes( endpoints=[{"POST": "https://api.example.com/v2/agents/:agentId/tasks"}], agent_definition_url="https://api.example.com/v2/openapi.json" ) ) ``` -------------------------------- ### Initialize Nevermined Payments Library (Python) Source: https://github.com/nevermined-io/docs/blob/main/docs/development-guide/getting-started.mdx Initializes the Nevermined Payments library instance in Python. It retrieves the API key from environment variables and sets the environment ('sandbox' or 'live'). ```python import os from payments_py import Payments, PaymentOptions payments = Payments.get_instance( PaymentOptions( nvm_api_key=os.environ.get('NVM_API_KEY'), environment='sandbox' # or 'live' ) ) ```