Agent Prompt Guide — Teaching Agents to Pay for Things

Overview

This guide provides copy-paste system prompt additions that teach AI agents to handle x402 micropayments via Viatika. Choose the snippet that matches your integration method.


Option 1: MCP Server (Recommended)

If your agent has the Viatika MCP server configured, add this to the system prompt:

## x402 Payment Handling

You have access to Viatika payment tools via MCP:

- `pay_for_resource`: Make HTTP requests that may require payment. If the
  service returns 402 Payment Required, this tool automatically signs the
  payment through Viatika and retries. Use this for any URL that might
  require x402 micropayment.
  
  Parameters:
    - url (required): The URL to request
    - method (optional, default "GET"): HTTP method
    - headers (optional): Object of HTTP headers
    - body (optional): Request body string for POST/PUT

- `check_balance`: Check remaining credit balance. No parameters.
  Returns balance in credits and USD (1 credit = $0.001).

When to use pay_for_resource:
- User asks you to fetch/access a URL that might be paid
- You encounter a service that returns 402
- User explicitly asks to pay for a resource

When payment succeeds, tell the user:
- The result of the request
- That a payment was made and the amount (from amount_usdc field)

When payment is denied, tell the user:
- The denial reason (from the error field)
- Suggest checking budget/whitelist settings

Check balance proactively if the user asks about costs or budget.

Option 2: REST API (Direct Integration)

For agents that call Viatika's REST API directly (no MCP):

## x402 Payment Handling via Viatika REST API

When you make HTTP requests and receive a 402 Payment Required response,
handle it as follows:

1. Parse the response body as JSON. It should contain an x402 v2 payload:
   {
     "x402Version": 2,
     "accepts": [{"scheme": "exact", "network": "...", "amount": "...", "payTo": "...", ...}]
   }

2. Sign the payment by calling Viatika:
   POST {VIATIKA_API_URL}/v1/x402/sign-payment
   Authorization: Bearer {VIATIKA_API_TOKEN}
   Content-Type: application/json
   
   {
     "paymentRequired": <the full x402 payload from step 1>,
     "organizationId": "{VIATIKA_ORG_ID}",
     "entityId": "{VIATIKA_ENTITY_ID}",
     "entityType": "user",
     "providerId": "<domain of the service>"
   }

3. If approved (HTTP 200, approved: true):
   - Extract signature and authorization from response
   - Build X-Payment header (base64-encode the authorization JSON)
   - Build X-Payment-Signature header (concatenate r + s + v as hex, 0x-prefixed)
   - Retry the original request with these headers

4. If denied (HTTP 403, approved: false):
   - Report the denial reason to the user
   - Do NOT retry the payment

5. If pending approval (HTTP 202):
   - Tell the user the payment requires manual approval
   - Provide the approvalId for reference

Environment variables:
  VIATIKA_API_URL={api_url}
  VIATIKA_API_TOKEN={token}
  VIATIKA_ORG_ID={org_id}
  VIATIKA_ENTITY_ID={entity_id}

To check balance:
  GET {VIATIKA_API_URL}/v1/accounts/{VIATIKA_ORG_ID}
  Authorization: Bearer {VIATIKA_API_TOKEN}
  
  Response: {"balance": 8500, ...}  (1 credit = $0.001)

Option 3: Shell-Based Agents (Clawdbot, etc.)

For agents that execute shell commands:

## x402 Payment Handling

When you need to access a URL that may require x402 micropayment, use this flow:

Step 1: Try the request
  curl -s -w "\n%{http_code}" https://target-url.com/resource
  
Step 2: If status is 402, extract the x402 payload and sign it:
  PAYLOAD_402=$(curl -s https://target-url.com/resource)
  
  curl -X POST "${VIATIKA_API_URL}/v1/x402/sign-payment" \
    -H "Authorization: Bearer ${VIATIKA_API_TOKEN}" \
    -H "Content-Type: application/json" \
    -d '{
      "paymentRequired": '"${PAYLOAD_402}"',
      "organizationId": "'"${VIATIKA_ORG_ID}"'",
      "entityId": "'"${VIATIKA_ENTITY_ID}"'",
      "entityType": "user",
      "providerId": "target-url.com"
    }'

Step 3: If approved, retry with payment headers:
  curl https://target-url.com/resource \
    -H "X-Payment: <base64 payment>" \
    -H "X-Payment-Signature: <0x signature>"

Check balance:
  curl "${VIATIKA_API_URL}/v1/accounts/${VIATIKA_ORG_ID}" \
    -H "Authorization: Bearer ${VIATIKA_API_TOKEN}"

Key rules:
- 1 credit = $0.001 USD
- Never retry a denied payment (403)
- Report denial reasons to the user
- Report payment amounts when successful

Framework-Specific Examples

Claude (Anthropic)

Claude works best with the MCP server. The system prompt addition is minimal because tool descriptions are self-documenting:

You have Viatika x402 payment tools available. Use pay_for_resource
when accessing URLs that may require micropayment. Always report
payment amounts to the user. Check balance if asked about costs.

GPT (OpenAI) — Function Calling

Define these as OpenAI functions:

json
{
  "name": "pay_for_resource",
  "description": "Make an HTTP request. If 402 Payment Required, automatically sign payment via Viatika and retry.",
  "parameters": {
    "type": "object",
    "properties": {
      "url": {
        "type": "string",
        "description": "URL to request"
      },
      "method": {
        "type": "string",
        "description": "HTTP method",
        "default": "GET"
      },
      "headers": {
        "type": "object",
        "description": "HTTP headers"
      },
      "body": {
        "type": "string",
        "description": "Request body"
      }
    },
    "required": ["url"]
  }
}
json
{
  "name": "check_balance",
  "description": "Check Viatika credit balance. Returns credits and USD equivalent. 1 credit = $0.001.",
  "parameters": {
    "type": "object",
    "properties": {}
  }
}

System prompt addition:

When you receive a tool result from pay_for_resource:
- If payment_made is true, tell the user the cost (amount_usdc)
- If there's an error about denial, explain the reason and suggest
  checking budget/whitelist settings
- Never fabricate payment amounts or balances

Open-Source Agents (LangChain, AutoGPT, etc.)

For agents using tool/function frameworks, implement two tools that call the Viatika REST API. Here's the pseudocode:

python
import requests, json, base64, os

VIATIKA_URL = os.environ["VIATIKA_API_URL"]
VIATIKA_TOKEN = os.environ["VIATIKA_API_TOKEN"]
ORG_ID = os.environ["VIATIKA_ORG_ID"]
ENTITY_ID = os.environ["VIATIKA_ENTITY_ID"]

def pay_for_resource(url: str, method: str = "GET", headers: dict = None, body: str = None) -> dict:
    """Make HTTP request with automatic x402 payment handling."""
    # Step 1: Initial request
    resp = requests.request(method, url, headers=headers, data=body)
    
    if resp.status_code != 402:
        return {"success": resp.ok, "status_code": resp.status_code, "body": resp.text, "payment_made": False}
    
    # Step 2: Extract x402 payload
    x402_payload = resp.json()
    
    # Step 3: Sign payment
    sign_resp = requests.post(
        f"{VIATIKA_URL}/v1/x402/sign-payment",
        headers={
            "Authorization": f"Bearer {VIATIKA_TOKEN}",
            "Content-Type": "application/json"
        },
        json={
            "paymentRequired": x402_payload,
            "organizationId": ORG_ID,
            "entityId": ENTITY_ID,
            "entityType": "user",
            "providerId": url.split("/")[2]  # domain
        }
    )
    sign_data = sign_resp.json()
    
    if not sign_data.get("approved"):
        return {"success": False, "error": sign_data.get("message"), "payment_made": False}
    
    # Step 4: Retry with payment headers
    payment_headers = dict(headers or {})
    payment_headers["X-Payment"] = sign_data["payment"]       # base64 payload
    payment_headers["X-Payment-Signature"] = sign_data["signature"]  # 0x hex
    
    retry_resp = requests.request(method, url, headers=payment_headers, data=body)
    
    return {
        "success": retry_resp.ok,
        "status_code": retry_resp.status_code,
        "body": retry_resp.text,
        "payment_made": True,
        "amount_usdc": x402_payload["accepts"][0]["amount"]
    }

def check_balance() -> dict:
    """Check Viatika credit balance."""
    resp = requests.get(
        f"{VIATIKA_URL}/v1/accounts/{ORG_ID}",
        headers={"Authorization": f"Bearer {VIATIKA_TOKEN}"}
    )
    data = resp.json()
    credits = data["balance"]
    return {
        "balance_credits": credits,
        "balance_usd": f"${credits * 0.001:.2f}",
    }

Best Practices for Agent Prompts

DO

  • Report payment amounts: always tell the user when money was spent and how much
  • Check balance before expensive operations: if the user is about to make many paid requests
  • Explain denials clearly: policy denials have specific reasons — relay them
  • Use pay_for_resource for any URL that might be paid: the tool handles both paid and free URLs transparently

DON'T

  • Don't retry denied payments: if policy says no, it means no
  • Don't fabricate balances or amounts: always use the actual tool response
  • Don't expose internal details: users don't need to see signature hex, nonces, or wallet addresses
  • Don't assume all URLs need payment: many will return 200 directly without any 402

Transparency Template

When payment occurs, use this pattern:

✅ Got the data from [service]. This request cost $X.XX in x402 micropayments,
automatically handled by Viatika. Your remaining balance is approximately $Y.YY.

When payment is denied:

❌ Payment was denied: [reason]. Your current balance is [amount].
[If budget-exceeded]: Your daily budget has been reached. It will reset at midnight UTC.
[If not-whitelisted]: This service provider isn't on your approved list. Contact your admin to add it.