The consume() method is the core function in the AgentPay Python SDK for charging a user for their interaction with your MCP service.
The agentpay-sdk package currently on PyPI is a placeholder to reserve the name during Early Access. To get the actual SDK now, join the Waitlist.

Method Signature

consumption_result = agentpay_client.consume(
    api_key="USER_API_KEY_HERE",
    amount_cents=10,  # Example: 10 cents
    usage_event_id="UNIQUE_IDEMPOTENCY_KEY_HERE"
)

Parameters

  • api_key (str, required):
    • The User API Key provided by the client user making the request.
    • This key identifies the user whose balance will be debited.
  • amount_cents (int, required):
    • The cost of the specific tool usage or service interaction, specified in cents.
    • For example, to charge $0.50, you would pass 50.
    • You can determine this value dynamically in your server logic based on the complexity or resources used by the request.
    • Pass 0 to track usage without charging (e.g., for free operations).
    • If the user has free credits available, these will be consumed first.
  • usage_event_id (str, required):
    • A unique identifier (e.g., a UUID) that you generate for this specific consumption event.
    • Crucial for Idempotency: If the AgentPay SDK makes this consume() call multiple times with the same usage_event_id (e.g., due to network retries on your end), AgentPay will only process the charge once, preventing duplicate billing for the same underlying user action.
    • It is your responsibility to generate and manage these IDs. A common practice is to create a new UUID for each billable operation initiated by a user.

Return Object (ConsumptionResult)

The consume() method returns a ConsumptionResult object with the following attributes:
  • success (bool):
    • True if the consumption was successful and the user was charged.
    • False if the consumption failed (e.g., due to insufficient funds, invalid API key).
  • remaining_balance_cents (int | None):
    • If success is True, this attribute contains the user’s remaining balance in cents after the current charge has been deducted.
    • It might be None if success is False, or if balance information is not applicable to the type of failure.
  • error_message (str | None):
    • If success is False, this provides a human-readable message describing the reason for failure (e.g., “Insufficient funds.”, “API key is invalid or expired.”).
    • None if success is True.
  • error_code (str | None):
    • If success is False, this provides a short, machine-readable error code (e.g., INSUFFICIENT_FUNDS, INVALID_API_KEY, USAGE_EVENT_ID_CONFLICT).
    • This code can be used for programmatic error handling in your server logic.
    • None if success is True.

Example

import uuid

# Assume agentpay_client is an initialized AgentPayClient instance
cost_of_operation_cents = 25  # 25 cents for this example
idempotency_key = str(uuid.uuid4())

try:
    result = agentpay_client.consume(
        api_key="user_api_key_here",
        amount_cents=cost_of_operation_cents,
        usage_event_id=idempotency_key
    )

    if result.success:
        print(f"Successfully charged {cost_of_operation_cents} cents.")
        print(f"User's remaining balance: {result.remaining_balance_cents} cents.")
    else:
        print(f"Failed to charge user: {result.error_message} (Code: {result.error_code})")

except Exception as e:
    print(f"An unexpected SDK error occurred: {e}")

Error Handling

The method may raise the following exceptions:
  • AgentPayError: If there is an error communicating with the AgentPay service
  • ValueError: If any required parameter is empty or None

Error Codes

When success is False, the error_code field will contain one of the following values:
  • "INVALID_API_KEY": The provided API key is not recognized or has been revoked/deactivated
  • "OUTSTANDING_PAYMENT": The key is associated with an account that has an unpaid consumption attempt from a previous failed call
  • "INSUFFICIENT_FUNDS": The key is valid but the associated account has no remaining balance (including free credits)
  • "USAGE_EVENT_ID_CONFLICT": The same usage_event_id was used in a previous successful consumption call
When a consumption fails due to insufficient funds, AgentPay will automatically track the outstanding payment and process it when the user adds funds to their account. The API key will be reactivated once the payment is complete.

Performance Considerations

  • The method makes a synchronous HTTP request to the AgentPay service
  • Typical response time is < 100ms
  • We may release an asynchronous version in the future as needed