How agent payments work
An agent connected to SolvaPay can pay for your tools and endpoints on its owner’s behalf. The owner sets a spend policy, a budget and a balance in SolvaPay. Your server never sees a card or a balance. Every paid call goes through two requests to SolvaPay:- Authorize, before the call runs. You send what the call may cost (the estimate). SolvaPay checks the owner’s spend policy, budget and balance, and holds the estimate. If the policy says the owner must approve, SolvaPay holds the request while the owner decides. The answer is allowed or refused.
- Complete, after the call ran. You send the status your upstream answered with and the cost it reported. SolvaPay settles the call at that cost. An error status charges nothing.
@solvapay/agents is a thin client for this. The spend policy, approvals, balance and settlement all run in SolvaPay. The package verifies who is calling, drives the two requests and turns a refusal into something the agent can read.
This page covers SolvaPay agents. To charge your own customers for MCP tools against a plan, see the MCP Server guide. The same package exists for Python and Go.
Install
@modelcontextprotocol/server (version 2) is an optional peer dependency. You need it only for the MCP route. The package has four entry points:
The package is ESM only. It imports
node:crypto, so on Cloudflare Workers turn on the nodejs_compat flag.
You need:
- Your secret key. Use a sandbox key (
sk_sandbox_…) while live agent payments aren’t open (see Sandbox and production). - Your provider reference (
prov_…). SolvaPay issues each agent token for one provider. - Agent payments turned on for your account (see the warning above).
Create a paid MCP server
createAgentMcpRoute returns a fetch-style route: (request: Request) => Promise<Response | null>. It answers requests on your MCP path that carry a SolvaPay agent token or agent key, and returns null for everything else so your own handler can answer.
server.ts
export default { fetch } shape runs on Cloudflare Workers, Bun and Deno. On Node, pass the route to any adapter that turns a Node request into a Request.
What each piece does:
createSolvaPayAgentClientcalls SolvaPay’s agent endpoints with your secret key. Each request times out after 10 seconds, plus the approval wait for authorize.createAgentTokenVerifierandcreateAgentKeyVerifierdecide who is calling. See How the agent is verified.createAgentCallsruns authorize and complete.maxWaitSecondsis how long a call may wait for the owner’s approval.logreceives one event per step (call.allowed,call.refused,call.completed,call.authorize_failedand others). There is no default logger.
Add agent payments to an existing server
Put the route in front of your current handler. Agents get the route, everyone else gets your server:mcpPath and its bearer token is an agent key (agk_…) or a JWT whose issuer is issuer. The issuer is read without verification at this point, only to route the request.
Paid and free tools
Thetools callback gets the MCP server, a paid function and the verified caller. Register paid tools with paid:
run returns:
If
run throws, the package treats the upstream as never reached. It releases the call, so nothing is charged, and the agent gets a tool error with unreachableMessage. The default says the service could not be reached and nothing was charged.
Free tools have two places:
freeTools(server)registers tools anyone may call, signed in or not.- Tools you register with
server.registerToolinsidetoolsare free too. Use this when a tool needs the caller: the third argument is the verified agent request, orundefinedbefore a host has signed in.
server.registerTool in @modelcontextprotocol/server version 2 takes a schema such as z.object({}). Paid tools take the raw shape.
How the agent is verified
An agent presents one of two credentials as its bearer token. Agent token. A short-lived JWT that SolvaPay’s agent issuer signs with ES256.createAgentTokenVerifier checks it locally against the issuer’s public keys (<issuer>/jwks.json). It accepts a token only when:
- The issuer is
issuerand the audience is yourproviderRef(or yourresource, see Sign-in for MCP hosts). - It has
sub,exp,iatandjti, with 30 seconds of clock tolerance. subis an agent reference (agt_…),principalis an account reference (ppl_…),scopeisusage, andenvissandboxorlive.
agk_. createAgentKeyVerifier asks SolvaPay whose it is and reuses each answer for 30 seconds, so a revoked key stops working within 30 seconds. Pass verifyAgentKey to the MCP route: without it, an agent key on the MCP path throws.
SolvaPay verifies the credential again on every authorize, so a token revoked after your check is still refused.
A verified agent (VerifiedAgent) has:
When a credential does not verify, the MCP route answers with a JSON-RPC error (code
-32001) and a WWW-Authenticate: Bearer error="invalid_token" header:
- 401 for an expired, forged or revoked credential, or one for another merchant.
- 403 for an agent from the other environment (
environment_mismatch).
Refusals and what the agent sees
When SolvaPay refuses a paid call,run never executes. The agent gets a tool error whose text is a sentence for its owner, and whose structuredContent.refusal.reason says which refusal it was, so the agent can act without parsing the text:
The HTTP status applies to the HTTP gate (
refusalStatus in @solvapay/agents/http). The MCP route always answers a refusal as a tool result.
unavailable also covers SolvaPay refusing your server rather than the agent, for example feature_not_enabled (agent payments are off for your account) or key_env_mismatch. The call.authorize_failed log event carries SolvaPay’s message, so check your logs when every call is unavailable.
Waiting for the owner’s approval
When the spend policy asks the owner, SolvaPay answers authorize with “waiting”.createAgentCalls keeps asking, holding each request for at most 55 seconds, until the owner answers or maxWaitSeconds runs out. Keep maxWaitSeconds below your MCP client’s tool-call timeout. The TypeScript MCP SDK’s default is 60 seconds. Set it to 0 to refuse with ask at once.
Complete a call at its cost
The MCP route completes each paid call for you with whatrun returned. In the HTTP gate you call allowed.finish yourself. Either way, SolvaPay settles the call by what you send:
cost.amount is a number in your currency. The package sends it as a decimal string with up to 8 places. SolvaPay counts credits in USD and refuses a currency it can’t price (currency_not_supported).
Each call completes once. A second finish or release throws. If SolvaPay can’t be told, finish returns null, the package logs call.complete_failed, and the reservation lapses at the estimate.
Paid endpoints in an HTTP API
createAgentHttpGate does the same for one HTTP request. It returns one of four results, and you write the response:
not_agent: the key isn’t an agent token or agent key. Your own auth decides.rejected: the credential didn’t verify.statusis 401, or 403 for the other environment.refused: SolvaPay refused the call.refusalResponseanswers with{ "error": { "type": "<reason>", "message": "…" } }and the status from the refusal table.allowed: forward the call, thenfinishit with the upstream’s status and cost, orreleaseit if the upstream was never reached.
requestId is your ID for the call. SolvaPay keys the call on it, so a retry with the same requestId continues the same call. allowed.callRef is SolvaPay’s reference for the call: tag your upstream usage with it if you send usage reports.
Prompt facts
SolvaPay uses facts about each call’s input to spot an agent stuck in a loop.promptFacts(text) returns a SHA-256 hash of the text, whether it carries a failed tool result, and its last 1,500 characters. The hash is always sent. The excerpt goes to SolvaPay only when the agent’s token says the owner allowed it (promptExcerpt).
Pick the text that repeats when the agent loops: a tool’s input, or the last user turn for a model proxy. On the MCP route, return it from the paid tool’s prompt. On the HTTP gate, pass promptFacts(text) as prompt, or null for none.
Sign-in for MCP hosts
Hosts such as Claude and ChatGPT can sign their user in with SolvaPay over OAuth and get an agent token for your server. SetprotectedResource on the route to turn this on, and pass the same URL as resource to the token verifier so it accepts tokens issued for it:
protectedResource set, the route:
- Serves the RFC 9728 metadata document at
/.well-known/oauth-protected-resource/mcpand/mcp/.well-known/oauth-protected-resource, namingissueras the authorization server. - Lets a host list every tool and run free tools before sign-in.
- Answers a paid tool call that has no agent token with a 401 challenge that sends the host to SolvaPay. A request with your own bearer token is still passed to your handler, unless it calls a paid tool.
- Answers an expired or rejected token with the same challenge, so the host signs in again.
lazyAuth: false to challenge every tool call without an agent token, free tools and your own bearer tokens included. initialize and tools/list still answer.
For an HTTP API, serve the metadata with protectedResourceHandler and pass the same resource to the gate. 401 results then carry the challenge headers:
Report usage
If your upstream keeps its own usage records, send them to SolvaPay to reconcile against what it settled. Report one customer and time window at a time, with each call’s cost by thecallRef SolvaPay returned:
reportIdis your ID for the report. Sending it again returns the first report’s results withduplicate: true.windowis[from, to)in ISO 8601.callsmust be complete for the window.untaggedlists usage you couldn’t match to acallRef, as{ at, cost }.- Costs are decimal strings with up to 8 places, all in
currency.
matched, adjusted, pending, already_reconciled or ignored (a callRef SolvaPay doesn’t know). An adjusted call has a reason (provisional, expired, no_debit or cost_differs) and the deltas SolvaPay booked. untagged.flagged is true when some untagged usage came after the owner’s spend policy.
Sandbox and production
Agents spend in one environment, and so does your secret key:- A sandbox key (
sk_sandbox_…) serves sandbox agents, which pay with test money. - A production key (
sk_live_…) will serve live agents. Live agent payments aren’t open yet, so SolvaPay refuses live agents, live cards and live top-ups withagent_live_disabledfor now.
secretKeyEnvironment(secretKey) reads the environment from the key’s prefix, or returns undefined when the prefix doesn’t say. Pass it as environment to both verifiers. An agent from the other environment is then refused with environment_mismatch (403) before your server calls SolvaPay. Without environment, SolvaPay refuses that agent at authorize as agent_not_accepted.
Build and test with a sandbox key and a sandbox agent. When live agent payments open, you switch to the production key. Your code doesn’t change.
Test without SolvaPay
@solvapay/agents/testing has stand-ins for SolvaPay’s side: agentKeys and signAgentToken make agent tokens signed with a local key, and FakeAgentApi answers authorize, complete, agent key verification and usage reports in memory.
route with Authorization: Bearer <token>, then check api.authorizes and api.completes. Set api.waitingAnswers to have authorize answer “waiting” that many times, or api.failAuthorize to a status to make it fail.
Related
- MCP Server guide: paid MCP tools for your own customers, against a plan.
- Agent payments in Python
- Agent payments in Go