Tag Archives: x402

Monetization Gateway beta: charge AI agents for consumption with HTTP 402

Post Syndicated from Rohin Lohe original https://blog.cloudflare.com/monetization-gateway-beta/

Today, we’re making the Cloudflare Monetization Gateway available as part of a closed beta, and showcasing four customer use cases that are in production today. Since we announced the plan three months ago, we have been working closely with our customers to make the Gateway fast, flexible, and easy to use.

With just a few clicks, the Monetization Gateway allows domain owners to charge agents for access to their website, APIs, MCP tools, or datasets. Request access today in the Cloudflare Dashboard.

Proliferation of agents and machine payments

Today, most software businesses sell their products through subscriptions or prepaid credits. These business models require buyers to make a considerable upfront economic investment, so buyers limit themselves to a few subscriptions that fit into their budget. But this business model doesn’t align itself with how the predominant source of traffic on the Internet — agents — operates.

Agents seek outcomes, whether that’s sourced from a direct question or an implicit elicitation. To achieve an outcome, an agent may visit new sites, call MCP tools, or ingest data feeds. Businesses everywhere want to be in the critical path to help agents get better results. This helps them meet new users where they are, get paid for their inputs to those agents' answers, and take a leading position in headless agentic commerce.

Companies need to align their business models with the consumption patterns of agents to capture this opportunity. Payments must match an agent's consumption unit: per request, per search query, per token. The popular payment rails of today are unable to support this. These payment rails assume that the buyer will accept high latency, will only transact in large dollar values, and that they are a well-known, or identifiable, entity to the seller. Agents desire the opposite: cheap, fast, and reliable payment rails that can safely scale with minimal human intervention.

Sellers and buyers will be incentivized to align their business models with consumption, and they’ll use the payment network that helps them achieve that. Today, stablecoin transactions, and their underlying blockchain networks, are able to support these requirements. Over time, we may see existing networks introduce solutions or new payment networks come online. The Monetization Gateway exists to help ensure that sellers can focus on their product, and buyers can receive a predictable buying experience.

Building with the Monetization Gateway

The Monetization Gateway lets sellers charge agents for any resource behind Cloudflare’s network, priced per use. It's built for resources where every request is the use, like APIs, tools, and data. High-value content is different: a page might be crawled once and used a thousand times. For that, Pay Per Use offers a trusted network of verified buyers who report each use and pay for it.

The gateway uses the HTTP 402 Payment Required status code so buyers can offer payment for a resource over HTTP, inline with the request for the resource itself. This is an important distinction because there is no redirect to a checkout page and no separate payment API to call.

Sellers define which requests require payment, the cost, and where the payment should be sent. Buyers receive the payment instructions, sign an authorization, and receive the resource after the payment has been settled.

In its simplest form, this can be thought of as a ‘paywall for agents’. Sellers can go live in seconds with a few clicks, identify the audience they want to charge, and ensure that buyers are unable to access the resources until the buyer has paid.

Beyond its ease of implementation, we provide sellers a set of pricing and monetization capabilities out of the box. You write pricing rules that match any part of a request, such as the URL, headers, or query parameters, and choose from several pricing schemes. We handle the rest: payment verification and settlement through Coinbase's x402 Facilitator, failures and retries, analytics, and keeping up with changes to the x402 protocol. Payments settle on the Base blockchain using USDC, a stablecoin pegged to the U.S. dollar. Over time, we plan to help sellers make their services discoverable to agents, expose logs for all transactions, support additional payment rails, and incorporate identity primitives.

Let’s look at how our customers are using it in production today.

Cloudflare AI Gateway: pay for inference

Cloudflare’s AI Gateway is a control plane and model marketplace that allows developers to access hundreds of AI models with a single API key. Our goal is to operate the richest model catalog in the ecosystem and get it in the hands of as many customers as possible. AI Gateway allows customers to purchase credits that can be used toward all AI Gateway consumption. But as more agents carry wallets, maintaining a credit balance as the only usage mechanism adds unnecessary friction.

Starting today, U.S.-based Cloudflare customers can pay for inference at request time to a select set of models by adding the header PAYMENT-METHOD: x402. Detailed instructions are in our AI Gateway Developer Docs. Over time, you can expect to see the HTTP 402 status code embedded natively through more of Cloudflare’s infrastructure products.

AI Gateway has a complex pricing engine powering how each token gets billed. We’ve co-designed Monetization Gateway to meet the requirements of origin-controlled pricing. When this configuration is enabled, the Monetization Gateway requests pricing information directly from the seller (AI Gateway). For AI Gateway, this means being able to rely on its existing pricing module without having to maintain a rules catalog in the Monetization Gateway.

Need to set prices from your origin? Email us and we'll help you get started.

Ceramic.ai: pay for web search

"The web was built for a human buyer, someone who signs up and enters a card. Agents need to act on their own behalf, and payments are how they do it. Search is one of the first things every agent needs, so it should be one of the first things an agent can buy." — Dr. Anna Patterson, Founder, Ceramic.ai

If inference is the reasoning, search is the reality check. Ceramic.ai provides a web search API built for agents. Ceramic.ai maintains a proprietary index of more than 40 billion pages and has optimized every layer of its stack for machine callers, returning search results in as little as 50 milliseconds. At that speed, an agent can search repeatedly throughout a task.

That makes search a natural fit for agent-native payments. Search is one of the most elastic things an agent buys. A simple question might take one query, while a complex research task might take hundreds. When an agent can pay for search itself, it no longer has to ration queries against a budget someone set in advance. It can decide how hard to look based on the task, spending more when the stakes call for more evidence.

Ceramic.ai uses the Monetization Gateway’s fixed pricing monetization scheme to allow agents to pay to execute a search without an API key. Use the demo and Ceramic.ai docs to learn more.

Stocktwits: pay for stock signals

“Agents change the way data gets consumed. Instead of a customer signing up for a subscription or negotiating an enterprise license, an agent can ask for exactly what it needs, when it needs it. The ability to charge for that individual request opens up a completely new way for Stocktwits to make its data available.” – Howard Lindzon, Founder and CEO, Stocktwits

When a stock starts moving, one of the first questions traders ask is: what is everyone else saying?

For 18 years, that conversation has been happening on Stocktwits. Launched in 2008, Stocktwits pioneered cashtags (like $NET) to organize market conversations around individual stocks. Today, more than 10 million people use Stocktwits to follow markets, share ideas, and see what other investors are talking about.

Because Stocktwits is built specifically for investors, it provides a real-time view into what retail investors are watching and discussing. Stocktwits turns that activity into signals including:

  • Sentiment: whether recent posts about a ticker are predominantly bullish or bearish
  • Message volume: how much conversation a ticker is generating relative to its typical activity
  • Followers: how many Stocktwits users follow a ticker, providing a measure of sustained retail interest
  • Trending: which tickers are gaining attention fastest

These signals have long been available through Stocktwits' existing data products. The Monetization Gateway creates an additional distribution channel for a new type of customer: AI agents that need market context on demand. For example, an agent monitoring a portfolio or researching an investment might check whether conversation around $NET is taking off, whether sentiment is skewing bullish or bearish, or how many investors follow the ticker. Instead of requiring a traditional data license, a developer can pay for the individual requests their agent actually makes.

To start, Stocktwits built a separate, agent-facing path for these requests, with Cloudflare's Monetization Gateway sitting in front of it. Its existing API and enterprise data products remain unchanged. Each request is priced individually, giving Stocktwits a way to make its market signals accessible to AI agents while preserving its existing data products and licensing models. Get started with their docs today.

API2PDF: pay for API access

API2PDF is a REST API that helps developers generate PDFs from HTML and Office documents. Since launching in 2018, API2PDF has seen a growing number of AI agents directing developers to its service and now treats them as a first-class customer.

API2PDF’s consumption-based pricing model charges customers for the bandwidth and compute required to fulfill each request. Previously, customers needed to create an account and obtain an API key before using the service. After the first month, they needed to supply a credit card, which resulted in a >50% drop off in conversion. API2PDF now uses the Monetization Gateway to return an HTTP 402 response when a user or agent makes a request without an API key. Because each request depends on variable compute and bandwidth costs, API2PDF uses variable pricing to inform agents of the maximum price a single request could cost. Once the client completes the payment, API2PDF fulfills the request and settles only the actual consumption.

Agents face the same build-versus-buy decision developers do. An agent that needs a PDF could burn tokens to generate one itself, or it could pay a specialized API like API2PDF a fraction of a cent to do it properly.

Get started today

The Monetization Gateway is available in closed beta to eligible U.S.-based sellers and buyers, with support for new geographies on the way. If you are interested in making your product agent-native, we want to hear from you. Fill out the onboarding application in the Cloudflare Dashboard, check out our Developer Docs, and we’ll get back to you shortly. If you have questions, ideas, or want to help us scale agentic payments, please send us an email.

We’d like to thank our partners for their contributions and feedback. Without them, this launch wouldn’t be possible. This includes Vail Gold and Jeff Rafter from Cloudflare AI Gateway; Dr. Anna Patterson, Sean Costello, Sadé Ried, and Autumn Yuan from Ceramic.ai; Leo Gorkin, Ethan Berk, and Santiago Sanchez from Stocktwits; and Zack Schwartz from API2PDF.

Announcing Cloudflare Wallets: the programmable wallet for the agentic Internet

Post Syndicated from Will Papper original https://blog.cloudflare.com/wallets/

Today, it is difficult for AI agents to try out new APIs. They often have to navigate through a login page designed for humans and not agents, contact a human to add a payment method, generate an API key, and then figure out how to call the API.

This flow is very difficult for agents for two reasons: Agents do not have a stable identifier to sign up for an API, and they do not have a native way to pay for APIs. Because they lack these things, they often struggle to onboard onto software, which limits the growth of agentic commerce. AI agents often give up on these tasks entirely, kicking registration, payment methods, and API key generation back to humans. This makes it very difficult for agents to try out and compare many APIs.

To solve this, we’ve created Cloudflare Wallets. Starting today, you can claim a Cloudflare Wallet handle for your account, which will provide a unique username to help you better connect with merchants. Soon, you will be able to set up and use your Cloudflare Wallet to pay for APIs and content.

Earlier this month, we announced the Monetization Gateway to help Cloudflare customers get paid for their websites and applications. Monetization Gateway will support micropayments using the x402 protocol, which allows for payments to be attached to HTTP requests. These micropayments will be able to pay for uses ranging from AI inference to data to content. If you want to pay or get paid for services behind Monetization Gateway and other x402-compatible endpoints, you’ll need a wallet. 

Cloudflare Wallets will allow you to store stablecoins, purchase services, and receive funds across the web. Each account with a wallet will also be able to create Virtual Wallets for its agents to enable them to buy APIs, MCP Tools, content, and more. You will be able to define guardrails for your Virtual Wallets (such as an allowance, an allow list, and a maximum transaction size) to help your agent spend money safely from your account. This will allow your agent to try out many APIs with low friction and managed risk. Wallet users will have the option to share their Cloudflare Wallet handles, which will give them a stable identity when interacting with merchants.

Building the two-sided agentic market

Cloudflare’s Monetization Gateway will allow eligible Cloudflare customers to sell their resources (such as content or APIs) headlessly to agentic buyers. But for that market to truly develop, agents need more tools to buy from merchants in a machine-native way. Wallets will add another tool to Cloudflare’s Agents SDK, enabling AI agents to easily purchase necessary APIs and content using micropayments.

There will be two types of Cloudflare Wallets: Account Wallets and Virtual Wallets.

Account Wallets are designed for humans who are owners and users of Cloudflare accounts. They will be able to add funds, delegate spend to virtual wallets managed by agents, and remove funds as needed. 

Virtual Wallets, by contrast, are designed for agents and operate via API keys. Within a Virtual Wallet, an agent will be able to spend funds according to its permissions. Its maximum spend will be capped by the limit set by the owner of the Account Wallet. This framework gives agents freedom to act on behalf of users without constant manual approval while limiting an agent’s ability to overspend.

The freedom to explore

Virtual Wallets are exciting because they will allow agents to do what they’re best at: explore dozens or hundreds of services and find the best one for a particular use case. Stablecoin micropayments via x402 will make it simple to try an API without an account, allowing agents to test new options with little friction. The spending caps on Virtual Wallets are designed so that humans can let agents explore autonomously within safe spending limits. These limits may seem like constraints, but counterintuitively they give agents more freedom. If an agent is responsible for $10, you can worry less about its spending than if it is responsible for $1,000. If an API only costs a few cents to try, then $10 is more than sufficient to pursue and evaluate many options.

Once you or your agent has picked an API to use, policies set by you in your Account Wallet will act as cost controls for Virtual Wallets. Want to give every employee a $100 per week budget for AI inference? Simply provision an Account Wallet with the right balance and create Virtual Wallets for each employee with that rule. Anyone who exceeds the limits on their Virtual Wallet will be able to request a manual override from a human who is authorized to make changes to the Account Wallet.

We want to make it easy for Account Wallets to set flexible yet firm spending policies that do not require daily, active monitoring. When something anomalous happens, such as unexpectedly fast spending, a human will be able to review and confirm whether everything is operating as intended. If the spend was intentional, then the administrator of the Account Wallet will be able to raise the limit or approve a one-time injection of funds. If the spend was unintentional, then the spending policies for adding funds to virtual wallets did their job by imposing caps.

We are working to make it as easy as possible to fund and use these wallets. We will start with simple ways to onramp and offramp funds within supported geographies, with self-funding via stablecoins available as an alternative for eligible users. The Internet will not shift completely overnight, but with a majority of traffic on the web now being driven by bots, we are excited to give agents and merchants first-class tools for agentic commerce.

Beyond payments alone

Allowing humans to delegate authority to agents to easily buy and sell services is a helpful starting point. But this delegation is not always obvious to the merchants as they interact with agents. Today, if an agent comes to your website, you may know little about them as a user, despite the fact that the agent is acting on behalf of an individual or an organization. This lack of attribution challenges many traditional web business models. It’s easy to give a one-week free trial or sign-up credits to a human or an organization. It’s hard to give these same perks to an agent that lacks a stable identity and when one human can spin up dozens of agents under their control.

We solve this problem by linking wallets to a Cloudflare account via cloudflare.pay. cloudflare.pay will allow agents to optionally identify themselves, since their identity is a delegate of the account. A research agent could live at research.example.cloudflare.pay, allowing merchants to know that it is an agent from a particular organization. This approach will permit agents to maintain consistent and persistent identities, making the experience better for all parties. It will be completely optional for agents to choose to declare their identity or not, and it will be up to businesses to decide whether they want to prioritize transacting with known agents.

Agent identifiers should be human-readable

We believe that the approach to dealing with agents will look like the approach to dealing with VPNs: If someone is unidentified, they are not inherently untrustworthy, but they need to prove themselves more. This is why we have Turnstile and other initiatives to detect bots within Bot Management. Our identity primitive will build on top of this prior work. For example, Web Bot Auth already allows agents to register their identity via a keypair. IDs attached to Cloudflare Wallets allow this keypair to become human-readable.

We know that agentic identity standards are changing quickly, which is why we wanted to keep our approach simple. We are proposing a human-readable identifier for a not-very-readable keypair, similar to the URL and IP-address pairings used in DNS. We are not trying to define a particular schema or other verification system. We only want to make identity simple to remember and easy to declare. As schemas to enrich agentic identity develop through the x402 Foundation’s initiatives, we will seek to adopt them and intend to encourage others to do the same.

The future of agentic commerce

At Cloudflare, we want to offer all the building blocks for agentic commerce to succeed. Monetization Gateway will offer a way for sellers to get paid without setting up traditional payment infrastructure. Wallets will offer a way for buyers to pay headlessly via agents. Identity will allow merchants to communicate with buyers who identify themselves or enforce identification requirements.

All of these building blocks will create a headless marketplace for the Internet. If you are excited about this and want to participate, you can claim your handle now. We’re excited to see what you build and monetize.

Announcing the Monetization Gateway: charge for any resource behind Cloudflare via x402

Post Syndicated from Rohin Lohe original https://blog.cloudflare.com/monetization-gateway/

Today, we are announcing the Cloudflare Monetization Gateway, an engine that will give Cloudflare customers the ability to charge for any asset protected by Cloudflare: web pages, datasets, APIs, or MCP tools. 

It will provide a single control plane to manage payment policies and access controls across your applications, while also protecting your origin from high payment volumes by handling payment verification and enforcement at the edge. At launch, payments will settle in stablecoins over x402, the open protocol we are building with a coalition of more than 25 industry leaders via the x402 Foundation. 

The evolving business model of the web

For 30 years, the web has run on a simple economic bargain: trading content for human attention. That attention has been monetized through advertising, subscriptions, and e-commerce. This bargain funded the Internet as we know it. 

But as agents become the dominant Internet users, the model is breaking. An agent does not look at ads or need to maintain a monthly subscription to all the tools it wants to access. It reads a page or consumes a data feed once, takes what it needs, and moves on. Across the web, AI crawlers already request content anywhere from a hundred to tens of thousands of times for every visitor they send back. 

This reality demands a new model: usage-based pricing for everything. If attention and e-commerce are moving from websites to AI harnesses and AI-written software, then agents should pay for the inputs they need — training data, inference content, developer tooling, and API usage. The natural unit of payment for software is the request, the token, or the outcome, not the seat or the month. A few examples of what that could look like:

  • A few cents per web search, billed per call

  • \$0.001 base fee plus a \$0.01 per MB charge for an upload endpoint

  • \$0.99 per resolved support escalation, paid only when the work succeeds

This is the same shift behind paying creators when an answer engine uses their content — a fair exchange of value whenever content or a resource is used, priced on neutral rails built for the purpose. People often envision an agent buying high-priced assets like web domains, but most of what an agent pays for sits upstream of any checkout, and is priced far lower.

Some of the Internet already works this way. Cloud and APIs have been sold by the call and by the hour for years, but only to a known buyer: a user signs up, they are issued an API key, and they incur usage-based metered billing. Content mostly skipped payment and ran on advertising instead. These business models have never been able to serve unverified buyers for sub-cent transactions because the payment rails cost too much and took too long to settle. Below a certain price, collecting the payment cost more than the payment was worth.

Historically, usage-based billing was difficult to implement. Businesses needed to effectively become payments companies, running their own accounting to track internal usage in a robust and auditable way. Tracking this usage required significant overhauls of backend systems. Many instead chose per-seat pricing because it is simpler and frequently more profitable. 

Agents flip this dynamic. A single agent can do the work of an entire team around the clock, making a flat one-time fee disconnected from actual consumption. At the same time, an agent can make thousands of micropayments without friction, while asking a person to approve each payment would be impossibly burdensome. Usage-based price points are where agents live and where stablecoin-based micropayments shine. That’s because stablecoins (such as Open USD and USDC) allow buyers to transfer tiny sums across the Internet, incurring negligible fees and settling in less than a second. This is not feasible with other payment rails today.

Here’s where we can help. Cloudflare has spent years building usage-based accounting for our own billing systems and for our customers’ analytics. We can dramatically simplify the implementation of usage-based billing for web-based assets thanks to our position as a proxy layer between buyers and sellers. As shown below, with Cloudflare supporting usage-based billing, the evidence of payment can move into the request itself, and the payment validation and the request paths merge.


And here’s the benefit to you: the metering, the payment exchange, and the settlement move off your origin. What stays with you is what matters — your rules, your prices, and your revenue. You will not need to onboard the buyer or stand up a billing system. You will write a rule and agentic buyers will pay for what they use.

A refresher on x402

Last year on Content Independence Day, we gave site owners one-click control over which AI crawlers could reach their content, and with Pay Per Crawl we let them charge crawlers for it. The Monetization Gateway is the next step: instead of only charging crawlers for content, you will be able to charge any caller for any resource, from an API to data to an MCP tool call, and you will not have to build the payment machinery yourself.

x402 is an open protocol that makes it possible to pay over HTTP, named for the 402 status code it finally puts to use. The x402 exchange is simple: a client requests a payment-gated resource. Instead of serving it, the server responds with 402 Payment Required and a small payload that states the price, the accepted asset, and where to pay. The client pays and repeats the request with proof of payment attached. A facilitator verifies, and the server returns the resource. It all happens inside ordinary HTTP requests and responses, with no redirect to a checkout page and no separate payment API to call. Settlement happens peer-to-peer, so any funds that a buyer sends to a seller are directly deposited to the seller’s wallet. We are designing the Monetization Gateway to keep payment overhead low and are aiming for sub-second payment settlement.


x402 Payment Flow: AI Agent ↔ APIServer ↔ Blockchain, Source: x402 Readme on GitHub

Two properties make x402 a good fit for machine payments. The payment amounts can be small, down to fractions of a cent, because the protocol adds almost no overhead. And the buyer needs no account with the seller, because the payment itself is the credential. x402 is rail agnostic, but it is a natural fit for stablecoins, which can settle in under a second for a fraction of a cent with zero chargebacks.

What the Monetization Gateway does

The Monetization Gateway will provide a flexible payment rules API that will allow you to express exactly when you want a caller to pay to access your digital resources.


Here’s how it will work. Tokens, APIs, MCP tool calls, and data already flow through that path. You will decide, as precisely as you want, which of that traffic has to pay. And you will be able to enforce your decisions by writing expressions, similar to expressions that you already write for other Cloudflare rules, in a simple, dedicated product API. The Monetization Gateway will scale with Cloudflare’s global network across 330+ cities, which means that the x402 handshake will occur in close proximity to your buyer. This will reduce request latency and protect your origin. 

A few examples of planned capabilities:

  • Charge for specific REST verbs: Require payment on calls to a specific route, for example $0.01 for every GET or POST request to /api/premium/*.

  • Variable pricing: Charge variable amounts for tasks of varying complexity, for example, image generation might charge any amount up to $2, depending on the compute used.

  • Charge only unauthenticated callers: Intercept HTTP 401 “Unauthorized” responses from your origin and return 402 “Payment Required” instead with pricing and payment instructions.

When a request matches, the Monetization Gateway will verify payment before letting it through. You will be able to set these rules in the dashboard, or manage them as code through the Cloudflare API and Terraform, so a paid endpoint is just another part of your infrastructure config.

The Monetization Gateway will initially allow users to require buyers to pay for services and resources in stablecoins. Sellers will be able to use the stablecoins they accumulate for their own transactions or redeem the stablecoins for equivalent fiat currency in their bank account. Using the Monetization Gateway offers a way to increase the addressable market for your products. With the Gateway, agents can request your resource, be told the price, pay, and get the response. No signup, no API key, no prior relationship required. You will decide how much you need to know about that buyer, and you will have the flexibility to require agents to authenticate with Web Bot Auth and apply usage-based pricing against accounts they already hold.

Where we see this going

The Monetization Gateway will turn the request into a payment and give Cloudflare customers new revenue opportunities, but where this goes is far bigger.

An agent is software that acts autonomously on a user’s behalf, and agents are starting to act on their own. Soon they will carry wallets and buy what they need without a person in the loop: a dataset, an API call, a tool, a block of compute. Some of those resources will be free, and some will require proof of who the agent is and who it acts for, through verified agent identity. Many will require both an identity and a payment, and Cloudflare is one of the few places that will be able to settle all of it inside a single request, by verifying the agent, applying the rule, and checking the payment before the origin ever sees the call. The agent becomes the primary buyer on the Internet, and the request becomes the transaction.

There is an enormous amount of value moving across the Internet today that goes unmonetized or undermonetized, not because no one would pay for it, but because the tools to charge for it have never existed. Every useful API call, every answer, every tool invocation an agent makes has value, and almost none of it is paid for today. That is the opportunity in front of us, and it is what the Monetization Gateway will unlock.

This is what we are building toward: an agent-first Internet with Internet-scale settlement built in. Where the people who make something worth paying for get paid by the software that uses it, automatically. And where the smallest new API can reach the same buyers, on the same terms, as the largest company on the web, and the independent creator is paid by the large language models that use their work. That is the next business model of the Internet, and we are building to power it.

Sign up for our waitlist

The Monetization Gateway waitlist is open now for Cloudflare customers. If you’re interested in monetizing your web page, dataset, API, or MCP tool with usage-based pricing, please join our early access list.


Launching the x402 Foundation with Coinbase, and support for x402 transactions

Post Syndicated from Will Allen original https://blog.cloudflare.com/x402/

Cloudflare is partnering with Coinbase to create the x402 Foundation. This foundation’s mission will be to encourage the adoption of the x402 protocol, an updated framework that allows clients and services to exchange value on the web using a common language. In addition to today’s partnership, we are shipping a set of features to allow developers to use x402 in the Agents SDK and our MCP integrations, as well as proposing a new deferred payment scheme.

Payments in the age of agents

Payments on the web have historically been designed for humans. We browse a merchant’s website, show intent by adding items to a cart, and confirm our intent to purchase by inputting our credit card information and clicking “Pay.” But what if you want to enable direct transactions between digital services? We need protocols to allow machine-to-machine transactions. 

Every day, sites on Cloudflare send out over a billion HTTP 402 response codes to bots and crawlers trying to access their content and e-commerce stores. This response code comes with a simple message: “Payment Required.”

Yet these 402 responses too often go unheard. One reason is a lack of standardization. Without a specification for how to format and respond to those response codes, content creators, publishers, and website operators lack adequate tools to convey their payment requests. x402 can give developers a clear, open protocol for websites and automated agents to negotiate payments across the globe. 

A Primer on x402

Coinbase authored the x402 transaction flow, outlined below, to help machines pay directly for resources over HTTP:

  1. A client attempts to access a resource gated by x402. 

  2. The server responds with the status code 402 Payment Required. The response body contains payment instructions including the payment amount and recipient.

  3. The client requests the x402-gated resource with the payment authorization header.

  4. The payment facilitator verifies the client’s payment payload and settles the transaction.

  5. The server responds with the requested resource in the response, along with the payment response header that confirms the payment outcome. 

This flow creates programmatic access to resources across the Internet. Clients and servers capable of interpreting the x402 protocol are able to transact without the need for accounts, subscriptions, or API keys.

x402 can be used to monetize traditional use cases, but also enables monetization of a new class of use cases. For example:

  • An assistant that is able to purchase accessories for your Halloween costume from multiple merchants.

  • An AI agent that pays per browser rendering session, instead of committing to a monthly subscription fee.

  • An autonomous stock trader that makes micropayments for a high quality real-time data feed to drive decisions.

Future versions of x402 could be agnostic of the payment rails, accommodating credit cards and bank accounts in addition to stablecoins. 

Cloudflare’s pay per crawl: proposing the x402 deferred payment scheme 

Agents and crawlers often require two important functions that already exist in much of today’s financial infrastructure: delayed settlement to account for disputes; and a single, aggregated payment to make their accounting simpler. For example, crawlers participating in our private beta of pay per crawl are able to crawl a vast number of pages easily, generate audit logs, and then be charged a single fee via a connected credit card or bank account at the end of each day. 

To account for these types of payment scenarios, we’re proposing a new deferred payment scheme for the x402 protocol. This new scheme is specifically designed for agentic payments that don’t need immediate settlement and can be handled either through traditional payment methods or stablecoins. By proposing this addition, we’re helping to ensure that any compliant server can optionally decouple the cryptographic handshake from the payment settlement itself, giving agents and servers the ability to use pre-negotiated licensing agreements, batch settlements, or subscriptions.

We will be bringing this new deferred payment scheme to pay per crawl as we expand and evolve the private beta. 

The Handshake Explained

Here’s our initial proposal for the handshake that could be released in the next major version of x402:

1. The Server’s Offer

Today, an unauthenticated or unauthorized client attempts to access a resource and receives a 402 Payment Required response. The server provides a payment commitment payload that the client can use to construct a re-request. This response is a machine-readable offer, and our proposal includes a new scheme of deferred.

HTTP/1.1 402 Payment Required
Content-Type: application/json

{
  "accepts": [
    {
      "scheme": "deferred",
      "network": "example-network-provider",
      "resource": "https://example.com/page",
      "...": "...",
      "extras": {
        "id": "abc123",
        "termsUrl": "https://example.com/terms"
      },
    }
  ]
}
2. The Client’s Signed Commitment

Next, the client re-sends the request with a signed payload containing their payment commitment. The deferred scheme uses HTTP Message Signatures where a JWK-formatted public key is available in a hosted directory. The Signature-Input header clearly explains which parts of the request are included in the Signature to serve as cryptographic proof of the client’s intent, verifiable by the service provider without an on-chain transaction. 

GET /path/to/resource HTTP/1.1
Host: www.example.com
User-Agent: Mozilla/5.0 Chrome/113.0.0 MyBotCrawler/1.1
Payment:
    scheme="deferred",
    network="example-network-provider",
    id="abc123"
Signature-Agent: signer.example.com
Signature-Input:
    sig=("payment" "signature-agent");
    created=1700000000;
    expires=1700011111;
    keyid="ba3e64==";
    tag="web-bot-auth"
Signature: sig=abc==
3. Successful Response

The resource server validates the signature and returns the content with a confirmation header. The server is responsible for attributing the payment to the account associated with the HTTP message signature, verifying the client’s identity and then delivering the content. In this scenario, there is no blockchain associated with the payments. 

HTTP/1.1 200 OK
Content-Type: text/html
Payment-Response:
    scheme="deferred",
    network="example-network-provider",
    id="abc123",
    timestamp=1730872968
4. Payment Settlement

The server can now handle the settlement flexibly. The validated id from the handshake acts as a reference for the transaction. This approach enables a flexible use model without per-request overhead, allowing the server to roll up payments on a subscription, daily, or even batch basis. This creates a flexible framework where the cryptographic trust is established immediately, while the financial settlement can use traditional payment rails or stablecoins. 

Cloudflare’s MCP servers, Agents SDK, and x402 payments

Running code is what moves an open convention from the theoretical to truly useful, and eventually to a recognized standard. Agents built using Cloudflare’s Agent SDK can now pay for resources with x402, and MCP servers can expose tools to be paid for via x402. To show how this works, we created the x402 playground, a live demo employing x402. The x402 playground is powered by the Agents SDK and has access to tools from MCP servers deployed on Cloudflare.


When you open the x402 playground, a new wallet is created and funded with Testnet USDC on a Base blockchain testnet. The agent, built with Agents SDK, has access to an MCP server with both free and paid tools.

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { McpAgent } from "agents/mcp";
import { withX402 } from "agents/x402";

export class PayMCP extends McpAgent {
  server = withX402(
    new McpServer({ name: "PayMCP", version: "1.0.0" }),
    X402_CONFIG
  );

  async init() {
    // Paid tool
    this.server.paidTool(
      "square",
      "Squares a number",
      0.01, // Tool price
      {
        a: z.number()
      },
      {},
      async ({ number }) => {
        return { content: [{ type: "text", text: String(a ** 2) }] };
      }
    );

    // Free tool
    this.server.tool(
      "add-two-numbers",
      "Adds two numbers",
      {
        a: z.number(),
        b: z.number(),
      },
      async ({ a, b }) => {
        return { content: [{ type: 'text', text: String(a + b) }] };
      }
    );
  }
}

When the agent attempts to use a paid tool, the MCP server responds with a 402 Payment Required. The agent is able to interpret the payment instructions and prompt the human whether they want to proceed with the transaction. Building an x402-compatible client requires a basic wrapper on the tool call:

import { Agent } from "agents";
import { withX402Client } from "agents/x402";

export class MyAgent extends Agent {
  // Your Agent definitions...

  async onToolCall() {

    // Build the x402 client
    const x402Client = withX402Client(
      myMcpClient,
      { network: "base-sepolia", account: this.account }
    );

    // The first parameter becomes the confirmation callback.
    // We can set it to `null` if we want the agent to pay automatically.
    const res = await x402Client.callTool(
      this.onPaymentRequired,
      {
        name: toolName,
        arguments: toolArgs
    });
  }
}

This test agent draws down the funds from the wallet and sends the payment payload to the MCP server, which settles the transaction. The transactions can be specified to execute with or without human confirmation, allowing you to design the interface best suited for your application.

What’s next? 

You can get started today by using the Agents SDK or by deploying your own MCP server.

We’ll continue to work closely with Coinbase to establish the x402 Foundation. Stay tuned for more announcements on the specifics of the structure very soon.

We believe in the value of open and interoperable protocols – which is why we are encouraging everyone to contribute to the x402 protocol directly. To get in touch with the team at Cloudflare working on x402, email us at [email protected].