Charge for server usage via the consume()
method, and best practices to handle idempotency and successful/failed calls.
AgentPayClient
and are able to extract the User API Key from incoming requests, you can charge for the usage of your MCP Server’s features using the consume()
method.
This is the core mechanism for monetizing your tools with AgentPay.
consume()
Methodagentpay_client.consume()
method is called each time you want to record a billable event for a user.
api_key
(str): Required. The User API Key provided by the client user in their request. This key identifies the user to be charged.amount_cents
(int): Required. The cost of the operation in cents. For example, to charge $0.10, you would pass 10
. Pass 0
for free operations you want to track.usage_event_id
(str): Required. A unique identifier (e.g., a UUID) for this specific consumption event. This is crucial for idempotency. If you make the same consume()
call with the same usage_event_id
multiple times (e.g., due to a retry), AgentPay will only process and charge for the event once.consume()
method returns a ConsumptionResult
object with the following attributes:
success
(bool): True
if the consumption was successful and the charge was applied. False
otherwise.error_message
(str | None): If success
is False
, this provides a human-readable message describing the error (e.g., “Insufficient funds,” “Invalid API Key”).error_code
(str | None): If success
is False
, this provides a short error code (e.g., INSUFFICIENT_FUNDS
, INVALID_API_KEY
) that can be used for programmatic error handling.consume()
method gives you flexibility in how you price your tools:
consume()
method first validates the API Key, then attempts to charge the user. This means it can fail for two types of reasons:
"invalid_key"
: The key is not recognized or has been revoked/deactivated."outstanding_payment"
: The key is associated with an account that has an unpaid consumption attempt. This happens when a previous consume()
call failed due to insufficient funds."insufficient_balance"
: The key is valid but the associated account has no remaining balance (including free credits)."outstanding_payment"
validate_api_key()
), you’ll naturally catch invalid keys (including those with outstanding payments) early.consume()
fails, inform the user they need to add funds to their AgentPay account. The system will automatically handle reactivating their key once they’ve paid their outstanding balance.consume()
with amount_cents=0
to track usage patterns.usage_event_id
is vital. If a network error occurs after you’ve called consume()
but before you receive a response, or if your server process restarts unexpectedly, you might retry the operation. By sending the same usage_event_id
, you ensure the user is not charged multiple times for the same logical operation.
usage_event_id
for each distinct user request or billable action.consume()
call for that specific action.