Skip to content

[FEATURE] AgentCore Payments Integration for Strands SDK #1802

@rajuans

Description

@rajuans

Problem Statement

AI agents increasingly need to access paid services through pay-per-use models, especially for:

Premium API endpoints requiring x402 cryptocurrency payments

  • MCP servers with paid tools (e.g., Coinbase Bazaar)
  • Content providers using payment-gated access
  • Microtransactions (often <$1 or fractions of a cent) where traditional payment methods are cost-prohibitive
  • Currently, Strands developers must manually implement:

HTTP 402 detection and payment requirement extraction (v1 body-based, v2 header-based)

  • Integration with AgentCore Payments ProcessPayment API
  • Payment proof generation and retry logic with correct headers
  • Payment session and instrument ID management
  • Budget enforcement guardrails

This adds weeks of development effort and creates inconsistent implementations across agent projects.

Proposed Solution

  1. Built-in Payment Tools
  • http_request (enhanced): Detects HTTP 402 responses, extracts x402 payment requirements (v1 and v2), returns x402_payload to agent
  • process_payment: Calls AgentCore ProcessPayment API with SigV4 auth; takes x402_payload as-is; returns signed payment proof
  • http_request_with_payment_header: Retries request with payment proof; handles v1 (X-PAYMENT) and v2 (PAYMENT-SIGNATURE) headers
  1. Payment Session Context
@strand
def my_payment_agent(
    payment_session_id: str,
    payment_instrument_id: str,
    payment_manager_arn: str,
):
    # Auto-injected into tool context
    # Agent cannot modify or create new sessions
  1. Interceptor Pattern (Alternative)
# Automatic payment handling without LLM involvement
@payment_interceptor(session_id, instrument_id)
def fetch_with_auto_payment(url):
    # Handles 402 → ProcessPayment → retry transparently
  1. Optional MCP Bazaar Integration
  • connect_to_bazaar()
  • discover_bazaar_tools(network_filter)
  • call_bazaar_tool(tool_name) — handles full 402 → pay → retry flow
  1. Payment Session & Budget Configuration
    Session-level budget enforcement is set by the application backend (ManagementRole), not by the agent:
session = create_payment_session(
    payment_manager_arn=mananger_arn,
    user_id="user-123",
    expiry_duration=300,  # seconds
    limits={
        "maxSpendAmount": {
            "value": "1.0",      # $1.00 USD limit
            "currency": "USD"    # Converted from stablecoin
        }
    }
)
# Agent receives session_id and can ONLY spend within this limit
# Agent CANNOT create new sessions or override limits
  1. Role-Based Access Control:
  • ProcessPaymentRole: Agent can ONLY call ProcessPayment
  • ManagementRole: Backend creates instruments/sessions
  • ControlPlaneRole: Developer setup (PaymentManager, PaymentConnector)
  • ResourceRetrievalRole: Service runtime role

Use Case

@strand
def research_agent(query: str, payment_session_id: str, payment_instrument_id: str):
    """Agent that pays for premium research APIs"""

    # 1. Agent tries to call paid endpoint
    result = http_request("https://premium-api.example/research")

    # 2. Detects 402, extracts x402_payload
    if result.status_code == 402:
        payment_req = result.x402_payload

        # 3. Process payment within session budget
        proof = process_payment(
            payment_session_id=payment_session_id,
            payment_instrument_id=payment_instrument_id,
            x402_payload=payment_req  # Passed as-is
        )

        # 4. Retry with proof
        result = http_request_with_payment_header(
            url="https://premium-api.example/research",
            proof=proof,
            payment_requirements=payment_req
        )

    return result.content

Alternatives Solutions

No response

Additional Context

Security Considerations

  • LLM Isolation: Payment tools should be called from deterministic code paths (interceptors/hooks), not directly by the LLM, to prevent prompt injection attacks
  • Budget Enforcement: Agent receives session ID but cannot create sessions or modify limits
  • Credential Security: AgentCore Identity securely stores wallet credentials; agent never sees raw credentials
  • Audit Trail: All transactions logged via AgentCore Observability
  • Failure Handling: Errors propagate to the caller for retry — no internal retry logic

Implementation Checklist

  • Add payment module to Strands SDK with 3 core tools
  • Implement x402 v1 and v2 protocol support
  • Add SigV4 signing for AgentCore Payments API calls
  • Support ProcessPaymentRole IAM authentication
  • Add payment session context to agent runtime
  • Support Ethereum and Solana stablecoin networks (USDC/USDT)
  • Implement MCP Bazaar integration tools (optional)
  • Add payment interceptor decorator pattern
  • Create example agent in samples/payment_agent/
  • Document IAM role setup (4 roles: ControlPlane, Management, ProcessPayment, ResourceRetrieval)

Testing Requirements

  • Unit tests for x402 payload extraction (v1 and v2)
  • Integration tests with Ethereum and Solana testnets
  • Budget enforcement tests (session limit exceeded)
  • IAM role permission boundary tests

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions