Skip to content

Commit a294db3

Browse files
add agents x402 docs (#25326)
* add x402 docs * Update src/content/docs/agents/x402.mdx Co-authored-by: Brendan Irvine-Broque <[email protected]> * Update src/content/docs/agents/x402.mdx Co-authored-by: Brendan Irvine-Broque <[email protected]> * amends --------- Co-authored-by: Brendan Irvine-Broque <[email protected]>
1 parent cd5ca5c commit a294db3

File tree

1 file changed

+174
-0
lines changed

1 file changed

+174
-0
lines changed

src/content/docs/agents/x402.mdx

Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
1+
---
2+
title: x402
3+
pcx_content_type: navigation
4+
sidebar:
5+
order: 5
6+
group:
7+
hideIndex: false
8+
---
9+
10+
## What is x402?
11+
12+
[x402](https://www.x402.org/) is an open payment standard that enables services to charge for access to their APIs and content directly over HTTP. It is built around the HTTP 402 Payment Required status code and allows clients to programmatically pay for resources without accounts, sessions, or credential management.
13+
14+
## x402 Workers and Agents
15+
16+
You can create paywalled endpoints in your Workers and query any x402 server from your agent by wrapping the `fetch` with x402 and your account.
17+
18+
```ts
19+
import { Hono } from "hono";
20+
import { Agent, getAgentByName } from "agents";
21+
import { wrapFetchWithPayment } from "x402-fetch";
22+
import { paymentMiddleware } from "x402-hono";
23+
24+
// This allows us to derive an account from just the private key
25+
import { privateKeyToAccount } from "viem/accounts";
26+
27+
// The code below creates an Agent that can fetch the protected route and automatically pay.
28+
// The agent's account must not be empty! You can get test credits
29+
// for base-sepolia here: https://faucet.circle.com/
30+
export class PayAgent extends Agent<Env> {
31+
fetchWithPay!: ReturnType<typeof wrapFetchWithPayment>;
32+
33+
onStart() {
34+
// We derive the account from which the agent will pay
35+
const privateKey = process.env.CLIENT_TEST_PK as `0x${string}`;
36+
const account = privateKeyToAccount(privateKey);
37+
console.log("Agent will pay from this address:", account.address);
38+
this.fetchWithPay = wrapFetchWithPayment(fetch, account);
39+
}
40+
41+
async onRequest(req: Request) {
42+
const url = new URL(req.url);
43+
console.log("Trying to fetch paid API");
44+
45+
// Use the x402 compatible fetch (fetchWithPay) to access the paid endpoint
46+
// Note: this could be any paid endpoint, on any server
47+
const paidUrl = new URL("/protected-route", url.origin).toString();
48+
return this.fetchWithPay(paidUrl, {});
49+
}
50+
}
51+
52+
const app = new Hono<{ Bindings: Env }>();
53+
54+
// Configure the middleware.
55+
// Only gate the `protected-route` endpoint, everything else we keep free.
56+
app.use(
57+
paymentMiddleware(
58+
process.env.SERVER_ADDRESS as `0x${string}`, // our server's public address
59+
{
60+
"/protected-route": {
61+
price: "$0.10",
62+
network: "base-sepolia",
63+
config: {
64+
description: "Access to premium content",
65+
},
66+
},
67+
},
68+
{ url: "https://x402.org/facilitator" }, // Payment facilitator URL
69+
// To learn more about facilitators https://x402.gitbook.io/x402/core-concepts/facilitator
70+
),
71+
);
72+
73+
// Our paid endpoint will return some premium content.
74+
app.get("/protected-route", (c) => {
75+
return c.json({
76+
message: "This content is behind a paywall. Thanks for paying!",
77+
});
78+
});
79+
80+
// The agent will fetch our own protected route and automatically pay.
81+
app.get("/agent", async (c) => {
82+
const agent = await getAgentByName(c.env.PAY_AGENT, "1234");
83+
return agent.fetch(c.req.raw);
84+
});
85+
86+
export default app;
87+
```
88+
89+
Check out the [complete example](https://github.com/cloudflare/agents/tree/main/examples/x402).
90+
91+
## MCP servers with paid tools
92+
93+
x402 supercharges your MCP servers so they can include paid tools.
94+
95+
```ts
96+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
97+
import { McpAgent } from "agents/mcp";
98+
import { withX402, type X402Config } from "agents/x402";
99+
100+
const X402_CONFIG: X402Config = {
101+
network: "base",
102+
recipient: env.MCP_ADDRESS,
103+
facilitator: { url: "https://x402.org/facilitator" }, // Payment facilitator URL
104+
// To learn more about facilitators https://x402.gitbook.io/x402/core-concepts/facilitator
105+
};
106+
107+
export class PaidMCP extends McpAgent<Env> {
108+
server = withX402(
109+
new McpServer({ name: "PaidMCP", version: "1.0.0" }),
110+
X402_CONFIG,
111+
); // That's it!
112+
113+
async init() {
114+
// Paid tool
115+
this.server.paidTool(
116+
"square",
117+
"Squares a number",
118+
0.01, // USD
119+
{ number: z.number() },
120+
{},
121+
async ({ number }) => {
122+
return { content: [{ type: "text", text: String(number ** 2) }] };
123+
},
124+
);
125+
126+
// Free tool
127+
this.server.tool(
128+
"echo",
129+
"Echo a message",
130+
{ message: z.string() },
131+
async ({ message }) => {
132+
return { content: [{ type: "text", text: message }] };
133+
},
134+
);
135+
}
136+
}
137+
```
138+
139+
We also include an MCP client that you can use from anywhere (not just your Agents!) to pay for these tools.
140+
141+
```ts
142+
import { Agent } from "agents";
143+
import { withX402Client } from "agents/x402";
144+
import { privateKeyToAccount } from "viem/accounts";
145+
146+
export class MyAgent extends Agent {
147+
// Your Agent definitions...
148+
149+
onStart() {
150+
const { id } = await this.mcp.connect(`${env.WORKER_URL}/mcp`);
151+
const account = privateKeyToAccount(this.env.MY_PRIVATE_KEY);
152+
153+
this.x402Client = withX402Client(this.mcp.mcpConnections[id].client, {
154+
network: "base-sepolia",
155+
account,
156+
});
157+
}
158+
159+
onPaymentRequired(paymentRequirements): Promise<boolean> {
160+
// Your human-in-the-loop confirmation flow...
161+
}
162+
163+
async onToolCall(toolName: string, toolArgs: unknown) {
164+
// The first parameter becomes the confirmation callback.
165+
// We can set it to `null` if we want the agent to pay automatically.
166+
return await this.x402Client.callTool(this.onPaymentRequired, {
167+
name: toolName,
168+
arguments: toolArgs,
169+
});
170+
}
171+
}
172+
```
173+
174+
Check out the [complete example](https://github.com/cloudflare/agents/tree/main/examples/x402-mcp).

0 commit comments

Comments
 (0)