agents 0.18.0 → 0.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -19
- package/dist/{agent-tool-types-BNUGGBzQ.d.ts → agent-tool-types-Btk9ETS-.d.ts} +997 -356
- package/dist/agent-tool-types.d.ts +1 -1
- package/dist/{agent-tools-BFbzVLFc.d.ts → agent-tools-UuScsJg3.d.ts} +2 -2
- package/dist/agent-tools.d.ts +1 -1
- package/dist/browser/ai.js +1 -1
- package/dist/browser/index.js +1 -1
- package/dist/browser/tanstack-ai.js +3 -2
- package/dist/browser/tanstack-ai.js.map +1 -1
- package/dist/chat/index.d.ts +2 -2
- package/dist/chat/index.js +1 -1
- package/dist/chat/index.js.map +1 -1
- package/dist/chat-sdk/index.d.ts +1 -1
- package/dist/client-invoker-BNSZxAkv.d.ts +20 -0
- package/dist/client-invoker-VNZ7X0nn.js +57 -0
- package/dist/client-invoker-VNZ7X0nn.js.map +1 -0
- package/dist/{client-CcjiFpTf.js → client-zqKcsyFa.js} +434 -168
- package/dist/client-zqKcsyFa.js.map +1 -0
- package/dist/client.d.ts +1 -1
- package/dist/{connector-CdldGF3h.js → connector-KEJnl6e5.js} +2 -2
- package/dist/connector-KEJnl6e5.js.map +1 -0
- package/dist/{do-oauth-client-provider-D4ZwyBDu.d.ts → do-oauth-client-provider-VTZj2VtM.d.ts} +23 -11
- package/dist/experimental/webmcp.js +1 -1
- package/dist/handler-stateless-8hQN_kC3.js +367 -0
- package/dist/handler-stateless-8hQN_kC3.js.map +1 -0
- package/dist/handler-stateless-C_bo-Ytq.d.ts +107 -0
- package/dist/index.d.ts +12 -12
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/mcp/client.d.ts +22 -18
- package/dist/mcp/client.js +1 -1
- package/dist/mcp/do-oauth-client-provider.d.ts +1 -1
- package/dist/mcp/do-oauth-client-provider.js +25 -12
- package/dist/mcp/do-oauth-client-provider.js.map +1 -1
- package/dist/mcp/index.d.ts +48 -34
- package/dist/mcp/index.js +84 -79
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/server.d.ts +17 -0
- package/dist/mcp/server.js +2 -0
- package/dist/mcp/x402.d.ts +21 -9
- package/dist/mcp/x402.js +8 -7
- package/dist/mcp/x402.js.map +1 -1
- package/dist/observability/ai/index.js +5 -2
- package/dist/observability/ai/index.js.map +1 -1
- package/dist/react.d.ts +1 -1
- package/dist/serializable.d.ts +1 -1
- package/dist/sub-routing.d.ts +6 -6
- package/dist/workflows.d.ts +1 -1
- package/docs/human-in-the-loop.md +63 -82
- package/docs/mcp-client.md +31 -7
- package/docs/mcp-servers.md +125 -88
- package/docs/securing-mcp-servers.md +9 -6
- package/package.json +32 -11
- package/dist/client-CcjiFpTf.js.map +0 -1
- package/dist/connector-CdldGF3h.js.map +0 -1
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import {
|
|
2
|
+
a as McpAuthContext,
|
|
3
|
+
i as createStatelessMcpHandler,
|
|
4
|
+
n as StatelessMcpHandler,
|
|
5
|
+
o as getMcpAuthContext,
|
|
6
|
+
r as StatelessMcpServerInput,
|
|
7
|
+
t as CreateStatelessMcpHandlerOptions
|
|
8
|
+
} from "../handler-stateless-C_bo-Ytq.js";
|
|
9
|
+
export {
|
|
10
|
+
type CreateStatelessMcpHandlerOptions as CreateMcpHandlerOptions,
|
|
11
|
+
type CreateStatelessMcpHandlerOptions,
|
|
12
|
+
type McpAuthContext,
|
|
13
|
+
type StatelessMcpHandler,
|
|
14
|
+
type StatelessMcpServerInput,
|
|
15
|
+
createStatelessMcpHandler as createMcpHandler,
|
|
16
|
+
getMcpAuthContext
|
|
17
|
+
};
|
package/dist/mcp/x402.d.ts
CHANGED
|
@@ -1,10 +1,14 @@
|
|
|
1
|
+
import {
|
|
2
|
+
n as LegacyCallToolResultSchema,
|
|
3
|
+
t as CompatibleMcpClient
|
|
4
|
+
} from "../client-invoker-BNSZxAkv.js";
|
|
1
5
|
import { ZodRawShape } from "zod";
|
|
2
|
-
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
3
6
|
import {
|
|
4
7
|
CallToolRequest,
|
|
8
|
+
CallToolRequestOptions
|
|
9
|
+
} from "@modelcontextprotocol/client";
|
|
10
|
+
import {
|
|
5
11
|
CallToolResult,
|
|
6
|
-
CallToolResultSchema,
|
|
7
|
-
CompatibilityCallToolResultSchema,
|
|
8
12
|
ToolAnnotations
|
|
9
13
|
} from "@modelcontextprotocol/sdk/types.js";
|
|
10
14
|
import {
|
|
@@ -16,7 +20,6 @@ import {
|
|
|
16
20
|
FacilitatorConfig,
|
|
17
21
|
FacilitatorConfig as FacilitatorConfig$1
|
|
18
22
|
} from "@x402/core/server";
|
|
19
|
-
import { RequestOptions } from "@modelcontextprotocol/sdk/shared/protocol.js";
|
|
20
23
|
import {
|
|
21
24
|
Network,
|
|
22
25
|
Network as Network$1,
|
|
@@ -65,10 +68,19 @@ interface X402AugmentedClient {
|
|
|
65
68
|
| ((payment: PaymentRequirements$1[]) => Promise<boolean>)
|
|
66
69
|
| null,
|
|
67
70
|
params: CallToolRequest["params"],
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
71
|
+
options?: CallToolRequestOptions
|
|
72
|
+
): Promise<CallToolResult>;
|
|
73
|
+
/**
|
|
74
|
+
* @deprecated Prefer the request-options overload. Explicit legacy result
|
|
75
|
+
* schemas remain honored through the SDK v2 request funnel.
|
|
76
|
+
*/
|
|
77
|
+
callTool(
|
|
78
|
+
x402ConfirmationCallback:
|
|
79
|
+
| ((payment: PaymentRequirements$1[]) => Promise<boolean>)
|
|
80
|
+
| null,
|
|
81
|
+
params: CallToolRequest["params"],
|
|
82
|
+
resultSchema: LegacyCallToolResultSchema,
|
|
83
|
+
options?: CallToolRequestOptions
|
|
72
84
|
): Promise<CallToolResult>;
|
|
73
85
|
}
|
|
74
86
|
type X402ClientConfig = {
|
|
@@ -88,7 +100,7 @@ type X402ClientConfig = {
|
|
|
88
100
|
version?: number /** Confirmation callback for payment approval */;
|
|
89
101
|
confirmationCallback?: (payment: PaymentRequirements$1[]) => Promise<boolean>;
|
|
90
102
|
};
|
|
91
|
-
declare function withX402Client<T extends
|
|
103
|
+
declare function withX402Client<T extends CompatibleMcpClient>(
|
|
92
104
|
client: T,
|
|
93
105
|
x402Config: X402ClientConfig
|
|
94
106
|
): X402AugmentedClient & T;
|
package/dist/mcp/x402.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { t as bindMcpClient } from "../client-invoker-VNZ7X0nn.js";
|
|
1
2
|
import { HTTPFacilitatorClient, x402ResourceServer } from "@x402/core/server";
|
|
2
3
|
import { x402Client } from "@x402/core/client";
|
|
3
4
|
import { registerExactEvmScheme } from "@x402/evm/exact/server";
|
|
@@ -147,6 +148,7 @@ function withX402(server, cfg) {
|
|
|
147
148
|
return server;
|
|
148
149
|
}
|
|
149
150
|
function withX402Client(client, x402Config) {
|
|
151
|
+
const invoker = bindMcpClient(client);
|
|
150
152
|
const { account } = x402Config;
|
|
151
153
|
const maxPaymentValue = x402Config.maxPaymentValue ?? BigInt(1e5);
|
|
152
154
|
const paymentClient = new x402Client();
|
|
@@ -158,9 +160,8 @@ function withX402Client(client, x402Config) {
|
|
|
158
160
|
return matching.length > 0 ? matching : reqs;
|
|
159
161
|
});
|
|
160
162
|
}
|
|
161
|
-
const _listTools = client.listTools.bind(client);
|
|
162
163
|
const listTools = async (params, options) => {
|
|
163
|
-
const toolsRes = await
|
|
164
|
+
const toolsRes = await invoker.listTools(params, options);
|
|
164
165
|
return {
|
|
165
166
|
...toolsRes,
|
|
166
167
|
tools: toolsRes.tools.map((tool) => {
|
|
@@ -176,9 +177,9 @@ function withX402Client(client, x402Config) {
|
|
|
176
177
|
})
|
|
177
178
|
};
|
|
178
179
|
};
|
|
179
|
-
const
|
|
180
|
-
|
|
181
|
-
const res = await
|
|
180
|
+
const callToolWithPayment = async (x402ConfirmationCallback, params, schemaOrOptions, options) => {
|
|
181
|
+
const invoke = (callParams) => invoker.callTool(callParams, schemaOrOptions, options);
|
|
182
|
+
const res = await invoke(params);
|
|
182
183
|
const maybeX402Error = res._meta?.["x402/error"];
|
|
183
184
|
if (res.isError && maybeX402Error && maybeX402Error.accepts && Array.isArray(maybeX402Error.accepts) && maybeX402Error.accepts.length > 0) {
|
|
184
185
|
const accepts = maybeX402Error.accepts;
|
|
@@ -228,13 +229,13 @@ function withX402Client(client, x402Config) {
|
|
|
228
229
|
};
|
|
229
230
|
}
|
|
230
231
|
const token = btoa(JSON.stringify(paymentPayload));
|
|
231
|
-
return
|
|
232
|
+
return invoke({
|
|
232
233
|
...params,
|
|
233
234
|
_meta: {
|
|
234
235
|
...params._meta,
|
|
235
236
|
"x402/payment": token
|
|
236
237
|
}
|
|
237
|
-
}
|
|
238
|
+
});
|
|
238
239
|
}
|
|
239
240
|
return res;
|
|
240
241
|
};
|
package/dist/mcp/x402.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"x402.js","names":[],"sources":["../../src/mcp/x402.ts"],"sourcesContent":["/**\n * X402 MCP Integration (v2)\n *\n * Based on:\n * - Coinbase's x402 (Apache 2.0): https://github.com/coinbase/x402\n * - @ethanniser and his work at https://github.com/ethanniser/x402-mcp\n */\n\nimport type {\n McpServer,\n RegisteredTool,\n ToolCallback\n} from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { Client as MCPClient } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type {\n CallToolResultSchema,\n CompatibilityCallToolResultSchema,\n CallToolRequest,\n CallToolResult,\n ToolAnnotations\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { ZodRawShape } from \"zod\";\nimport type { RequestOptions } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\n\n// v2 imports from @x402/core\nimport { x402ResourceServer, HTTPFacilitatorClient } from \"@x402/core/server\";\nimport type { FacilitatorConfig, ResourceConfig } from \"@x402/core/server\";\nimport { x402Client } from \"@x402/core/client\";\nimport type {\n PaymentPayload,\n PaymentRequirements,\n PaymentRequired,\n Network\n} from \"@x402/core/types\";\n\n// v2 imports from @x402/evm\nimport { registerExactEvmScheme as registerServerEvmScheme } from \"@x402/evm/exact/server\";\nimport { registerExactEvmScheme as registerClientEvmScheme } from \"@x402/evm/exact/client\";\nimport type { ClientEvmSigner } from \"@x402/evm\";\n\n// Re-export commonly used types for consumer convenience\nexport type {\n PaymentRequirements,\n PaymentRequired,\n Network\n} from \"@x402/core/types\";\nexport type { FacilitatorConfig } from \"@x402/core/server\";\nexport type { ClientEvmSigner } from \"@x402/evm\";\n\n/**\n * Map of legacy v1 network names to CAIP-2 identifiers.\n * Allows backward compatibility with v1 config.\n */\nconst LEGACY_NETWORK_MAP: Record<string, string> = {\n \"base-sepolia\": \"eip155:84532\",\n base: \"eip155:8453\",\n ethereum: \"eip155:1\",\n sepolia: \"eip155:11155111\"\n};\n\n/**\n * Normalize a network identifier to CAIP-2 format.\n * Accepts both legacy v1 names (\"base-sepolia\") and CAIP-2 (\"eip155:84532\").\n */\nexport function normalizeNetwork(network: string): Network {\n return (LEGACY_NETWORK_MAP[network] ?? network) as Network;\n}\n\n/*\n ======= SERVER SIDE =======\n*/\n\nexport type X402Config = {\n /**\n * Network identifier.\n * Accepts both legacy names (\"base-sepolia\") and CAIP-2 format (\"eip155:84532\").\n */\n network: string;\n /** Payment recipient address */\n recipient: `0x${string}`;\n /** Facilitator configuration. Defaults to https://x402.org/facilitator */\n facilitator?: FacilitatorConfig;\n /** @deprecated No longer used in v2. The protocol version is determined automatically. */\n version?: number;\n};\n\nexport interface X402AugmentedServer {\n paidTool<Args extends ZodRawShape>(\n name: string,\n description: string,\n priceUSD: number,\n paramsSchema: Args,\n annotations: ToolAnnotations,\n cb: ToolCallback<Args>\n ): RegisteredTool;\n}\n\nexport function withX402<T extends McpServer>(\n server: T,\n cfg: X402Config\n): T & X402AugmentedServer {\n const network = normalizeNetwork(cfg.network);\n const facilitatorConfig: FacilitatorConfig = cfg.facilitator ?? {\n url: \"https://x402.org/facilitator\"\n };\n\n // Create v2 resource server with facilitator client\n const facilitatorClient = new HTTPFacilitatorClient(facilitatorConfig);\n const resourceServer = new x402ResourceServer(facilitatorClient);\n registerServerEvmScheme(resourceServer);\n\n // Lazy initialization: fetch supported kinds from facilitator on first use\n let initPromise: Promise<void> | null = null;\n function ensureInitialized(): Promise<void> {\n if (!initPromise) {\n initPromise = resourceServer.initialize().catch((err) => {\n initPromise = null; // allow retry on failure\n throw err;\n });\n }\n return initPromise;\n }\n\n function paidTool<Args extends ZodRawShape>(\n name: string,\n description: string,\n priceUSD: number,\n paramsSchema: Args,\n annotations: ToolAnnotations,\n cb: ToolCallback<Args>\n ): RegisteredTool {\n return server.registerTool(\n name,\n {\n description,\n inputSchema: paramsSchema,\n annotations,\n _meta: {\n \"agents-x402/paymentRequired\": true,\n \"agents-x402/priceUSD\": priceUSD\n }\n },\n (async (args, extra) => {\n await ensureInitialized();\n\n // Build v2 payment requirements for this tool call\n const resourceConfig: ResourceConfig = {\n scheme: \"exact\",\n payTo: cfg.recipient,\n price: priceUSD,\n network,\n maxTimeoutSeconds: 300\n };\n\n let requirements: PaymentRequirements[];\n try {\n requirements =\n await resourceServer.buildPaymentRequirements(resourceConfig);\n } catch {\n const payload = { x402Version: 2, error: \"PRICE_COMPUTE_FAILED\" };\n return {\n isError: true,\n _meta: { \"x402/error\": payload },\n content: [{ type: \"text\", text: JSON.stringify(payload) }]\n } as const;\n }\n\n const resourceInfo = {\n url: `x402://${name}`,\n description,\n mimeType: \"application/json\"\n };\n\n // Get payment token from MCP _meta or HTTP headers\n // Support both v2 (PAYMENT-SIGNATURE) and v1 (X-PAYMENT) header names\n const headers = extra?.requestInfo?.headers ?? {};\n const token =\n (extra?._meta?.[\"x402/payment\"] as string | undefined) ??\n headers[\"PAYMENT-SIGNATURE\"] ??\n headers[\"X-PAYMENT\"];\n\n const paymentRequired = (\n reason = \"PAYMENT_REQUIRED\",\n extraFields: Record<string, unknown> = {}\n ) => {\n const payload = {\n x402Version: 2,\n error: reason,\n resource: resourceInfo,\n accepts: requirements,\n ...extraFields\n };\n return {\n isError: true,\n _meta: { \"x402/error\": payload },\n content: [{ type: \"text\", text: JSON.stringify(payload) }]\n } as const;\n };\n\n if (!token || typeof token !== \"string\") return paymentRequired();\n\n // Decode the payment payload (base64-encoded JSON)\n let paymentPayload: PaymentPayload;\n try {\n paymentPayload = JSON.parse(atob(token));\n } catch {\n return paymentRequired(\"INVALID_PAYMENT\");\n }\n\n // Find matching requirements for this payment\n const matchingReq = resourceServer.findMatchingRequirements(\n requirements,\n paymentPayload\n );\n if (!matchingReq) {\n return paymentRequired(\"INVALID_PAYMENT\");\n }\n\n // Verify payment with facilitator\n try {\n const vr = await resourceServer.verifyPayment(\n paymentPayload,\n matchingReq\n );\n if (!vr.isValid) {\n return paymentRequired(vr.invalidReason ?? \"INVALID_PAYMENT\", {\n payer: vr.payer\n });\n }\n } catch {\n return paymentRequired(\"INVALID_PAYMENT\");\n }\n\n // Execute the tool callback\n let result: CallToolResult;\n let failed = false;\n try {\n result = await cb(args, extra);\n if (\n result &&\n typeof result === \"object\" &&\n \"isError\" in result &&\n result.isError\n ) {\n failed = true;\n }\n } catch (e) {\n failed = true;\n result = {\n isError: true,\n content: [\n { type: \"text\", text: `Tool execution failed: ${String(e)}` }\n ]\n };\n }\n\n // Settle payment only on success\n if (!failed) {\n try {\n const s = await resourceServer.settlePayment(\n paymentPayload,\n matchingReq\n );\n if (s.success) {\n result._meta ??= {};\n result._meta[\"x402/payment-response\"] = {\n success: true,\n transaction: s.transaction,\n network: s.network,\n payer: s.payer\n };\n } else {\n return paymentRequired(s.errorReason ?? \"SETTLEMENT_FAILED\");\n }\n } catch {\n return paymentRequired(\"SETTLEMENT_FAILED\");\n }\n }\n\n return result;\n }) as ToolCallback<Args>\n );\n }\n\n Object.defineProperty(server, \"paidTool\", {\n value: paidTool,\n writable: false,\n enumerable: false,\n configurable: true\n });\n\n // Tell TS the object now also has the paidTool method\n return server as T & X402AugmentedServer;\n}\n\n/*\n ======= CLIENT SIDE =======\n*/\n\nexport interface X402AugmentedClient {\n callTool(\n x402ConfirmationCallback:\n | ((payment: PaymentRequirements[]) => Promise<boolean>)\n | null,\n params: CallToolRequest[\"params\"],\n resultSchema?:\n | typeof CallToolResultSchema\n | typeof CompatibilityCallToolResultSchema,\n options?: RequestOptions\n ): Promise<CallToolResult>;\n}\n\nexport type X402ClientConfig = {\n /**\n * EVM account/signer for signing payment authorizations.\n * Use `privateKeyToAccount()` from viem/accounts to create one.\n */\n account: ClientEvmSigner;\n /**\n * Preferred network identifier (optional).\n * Accepts both legacy names (\"base-sepolia\") and CAIP-2 format (\"eip155:84532\").\n * When set, the client prefers payment requirements matching this network.\n * If omitted, the client automatically selects from available requirements.\n */\n network?: string;\n /** Maximum payment value in atomic units (default: 0.10 USDC = 100000) */\n maxPaymentValue?: bigint;\n /** @deprecated No longer used in v2. The protocol version is determined automatically. */\n version?: number;\n /** Confirmation callback for payment approval */\n confirmationCallback?: (payment: PaymentRequirements[]) => Promise<boolean>;\n};\n\nexport function withX402Client<T extends MCPClient>(\n client: T,\n x402Config: X402ClientConfig\n): X402AugmentedClient & T {\n const { account } = x402Config;\n\n const maxPaymentValue = x402Config.maxPaymentValue ?? BigInt(100_000); // 0.10 USDC\n\n // Create v2 x402 payment client with EVM scheme support\n const paymentClient = new x402Client();\n registerClientEvmScheme(paymentClient, { signer: account });\n\n // If a preferred network is specified, register a policy to prefer it\n if (x402Config.network) {\n const preferredNetwork = normalizeNetwork(x402Config.network);\n paymentClient.registerPolicy((_version, reqs) => {\n const matching = reqs.filter((r) => r.network === preferredNetwork);\n return matching.length > 0 ? matching : reqs;\n });\n }\n\n const _listTools = client.listTools.bind(client);\n\n // Wrap the original method to include payment information in the description\n const listTools: typeof _listTools = async (params, options) => {\n const toolsRes = await _listTools(params, options);\n return {\n ...toolsRes,\n tools: toolsRes.tools.map((tool) => {\n let description = tool.description;\n // Check _meta for payment information (agents-x402/ is our extension for pre-advertising prices)\n if (tool._meta?.[\"agents-x402/paymentRequired\"]) {\n const cost = tool._meta?.[\"agents-x402/priceUSD\"]\n ? `$${tool._meta?.[\"agents-x402/priceUSD\"]}`\n : \"an unknown amount\";\n description += ` (This is a paid tool, you will be charged ${cost} for its execution)`;\n }\n return {\n ...tool,\n description\n };\n })\n };\n };\n\n const _callTool = client.callTool.bind(client);\n\n const callToolWithPayment = async (\n x402ConfirmationCallback:\n | ((payment: PaymentRequirements[]) => Promise<boolean>)\n | null,\n params: CallToolRequest[\"params\"],\n resultSchema?:\n | typeof CallToolResultSchema\n | typeof CompatibilityCallToolResultSchema,\n options?: RequestOptions\n ): ReturnType<typeof client.callTool> => {\n // Call the tool\n const res = await _callTool(params, resultSchema, options);\n\n // Check for x402 payment required error in response metadata\n const maybeX402Error = res._meta?.[\"x402/error\"] as\n | (PaymentRequired & Record<string, unknown>)\n | undefined;\n\n if (\n res.isError &&\n maybeX402Error &&\n maybeX402Error.accepts &&\n Array.isArray(maybeX402Error.accepts) &&\n maybeX402Error.accepts.length > 0\n ) {\n const accepts = maybeX402Error.accepts;\n const confirmationCallback =\n x402ConfirmationCallback ?? x402Config.confirmationCallback;\n\n // Use the confirmation callback if provided\n if (confirmationCallback && !(await confirmationCallback(accepts))) {\n return {\n isError: true,\n content: [{ type: \"text\", text: \"User declined payment\" }]\n };\n }\n\n // Check max payment value against the first requirement's amount\n const selectedReq = accepts[0];\n if (!selectedReq || selectedReq.scheme !== \"exact\") return res;\n\n let amount: bigint;\n try {\n amount = BigInt(selectedReq.amount);\n } catch {\n return res; // malformed amount — return original error\n }\n if (amount > maxPaymentValue) {\n return {\n isError: true,\n content: [\n {\n type: \"text\",\n text: `Payment exceeds client cap: ${amount} > ${maxPaymentValue}`\n }\n ]\n };\n }\n\n // Reconstruct the PaymentRequired response for the v2 x402 client\n const paymentRequiredResponse: PaymentRequired = {\n x402Version: (maybeX402Error.x402Version as number) ?? 2,\n resource: (maybeX402Error.resource as PaymentRequired[\"resource\"]) ?? {\n url: \"\",\n description: \"\",\n mimeType: \"application/json\"\n },\n accepts,\n extensions: maybeX402Error.extensions as\n | Record<string, unknown>\n | undefined\n };\n\n // Create the payment payload using the v2 x402 client\n let paymentPayload: PaymentPayload;\n try {\n paymentPayload = await paymentClient.createPaymentPayload(\n paymentRequiredResponse\n );\n } catch {\n return {\n isError: true,\n content: [{ type: \"text\", text: \"Failed to create payment payload\" }]\n };\n }\n\n // Encode the payment payload as a base64 JSON token for MCP transport\n const token = btoa(JSON.stringify(paymentPayload));\n\n // Retry the tool call with the payment token\n return _callTool(\n {\n ...params,\n _meta: {\n ...params._meta,\n \"x402/payment\": token\n }\n },\n resultSchema,\n options\n );\n }\n\n return res;\n };\n\n const _client = client as X402AugmentedClient & T;\n Object.defineProperty(_client, \"listTools\", {\n value: listTools,\n writable: false,\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(_client, \"callTool\", {\n value: callToolWithPayment,\n writable: false,\n enumerable: false,\n configurable: true\n });\n\n return _client;\n}\n"],"mappings":";;;;;;;;;AAqDA,MAAM,qBAA6C;CACjD,gBAAgB;CAChB,MAAM;CACN,UAAU;CACV,SAAS;AACX;;;;;AAMA,SAAgB,iBAAiB,SAA0B;CACzD,OAAQ,mBAAmB,YAAY;AACzC;AA+BA,SAAgB,SACd,QACA,KACyB;CACzB,MAAM,UAAU,iBAAiB,IAAI,OAAO;CAO5C,MAAM,iBAAiB,IAAI,mBAAmB,IADhB,sBALe,IAAI,eAAe,EAC9D,KAAK,+BACP,CAI8D,CAAC;CAC/D,uBAAwB,cAAc;CAGtC,IAAI,cAAoC;CACxC,SAAS,oBAAmC;EAC1C,IAAI,CAAC,aACH,cAAc,eAAe,WAAW,CAAC,CAAC,OAAO,QAAQ;GACvD,cAAc;GACd,MAAM;EACR,CAAC;EAEH,OAAO;CACT;CAEA,SAAS,SACP,MACA,aACA,UACA,cACA,aACA,IACgB;EAChB,OAAO,OAAO,a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a;KACb,UAAU;IACZ;IACA;IACA,YAAY,eAAe;GAG7B;GAGA,IAAI;GACJ,IAAI;IACF,iBAAiB,MAAM,cAAc,qBACnC,uBACF;GACF,QAAQ;IACN,OAAO;KACL,SAAS;KACT,SAAS,CAAC;MAAE,MAAM;MAAQ,MAAM;KAAmC,CAAC;IACtE;GACF;GAGA,MAAM,QAAQ,KAAK,KAAK,UAAU,cAAc,CAAC;GAGjD,OAAO,UACL;IACE,GAAG;IACH,OAAO;KACL,GAAG,OAAO;KACV,gBAAgB;IAClB;GACF,GACA,cACA,OACF;EACF;EAEA,OAAO;CACT;CAEA,MAAM,UAAU;CAChB,OAAO,eAAe,SAAS,aAAa;EAC1C,OAAO;EACP,UAAU;EACV,YAAY;EACZ,cAAc;CAChB,CAAC;CACD,OAAO,eAAe,SAAS,YAAY;EACzC,OAAO;EACP,UAAU;EACV,YAAY;EACZ,cAAc;CAChB,CAAC;CAED,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"x402.js","names":[],"sources":["../../src/mcp/x402.ts"],"sourcesContent":["/**\n * X402 MCP Integration (v2)\n *\n * Based on:\n * - Coinbase's x402 (Apache 2.0): https://github.com/coinbase/x402\n * - @ethanniser and his work at https://github.com/ethanniser/x402-mcp\n */\n\nimport type {\n McpServer,\n RegisteredTool,\n ToolCallback\n} from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type {\n CallToolRequest,\n CallToolRequestOptions,\n Client as MCPClient\n} from \"@modelcontextprotocol/client\";\nimport type {\n CallToolResult,\n ToolAnnotations\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport {\n bindMcpClient,\n type CallToolSchemaOrOptions,\n type CompatibleMcpClient,\n type LegacyCallToolResultSchema\n} from \"./client-invoker\";\nimport type { ZodRawShape } from \"zod\";\n\n// v2 imports from @x402/core\nimport { x402ResourceServer, HTTPFacilitatorClient } from \"@x402/core/server\";\nimport type { FacilitatorConfig, ResourceConfig } from \"@x402/core/server\";\nimport { x402Client } from \"@x402/core/client\";\nimport type {\n PaymentPayload,\n PaymentRequirements,\n PaymentRequired,\n Network\n} from \"@x402/core/types\";\n\n// v2 imports from @x402/evm\nimport { registerExactEvmScheme as registerServerEvmScheme } from \"@x402/evm/exact/server\";\nimport { registerExactEvmScheme as registerClientEvmScheme } from \"@x402/evm/exact/client\";\nimport type { ClientEvmSigner } from \"@x402/evm\";\n\n// Re-export commonly used types for consumer convenience\nexport type {\n PaymentRequirements,\n PaymentRequired,\n Network\n} from \"@x402/core/types\";\nexport type { FacilitatorConfig } from \"@x402/core/server\";\nexport type { ClientEvmSigner } from \"@x402/evm\";\n\n/**\n * Map of legacy v1 network names to CAIP-2 identifiers.\n * Allows backward compatibility with v1 config.\n */\nconst LEGACY_NETWORK_MAP: Record<string, string> = {\n \"base-sepolia\": \"eip155:84532\",\n base: \"eip155:8453\",\n ethereum: \"eip155:1\",\n sepolia: \"eip155:11155111\"\n};\n\n/**\n * Normalize a network identifier to CAIP-2 format.\n * Accepts both legacy v1 names (\"base-sepolia\") and CAIP-2 (\"eip155:84532\").\n */\nexport function normalizeNetwork(network: string): Network {\n return (LEGACY_NETWORK_MAP[network] ?? network) as Network;\n}\n\n/*\n ======= SERVER SIDE =======\n*/\n\nexport type X402Config = {\n /**\n * Network identifier.\n * Accepts both legacy names (\"base-sepolia\") and CAIP-2 format (\"eip155:84532\").\n */\n network: string;\n /** Payment recipient address */\n recipient: `0x${string}`;\n /** Facilitator configuration. Defaults to https://x402.org/facilitator */\n facilitator?: FacilitatorConfig;\n /** @deprecated No longer used in v2. The protocol version is determined automatically. */\n version?: number;\n};\n\nexport interface X402AugmentedServer {\n paidTool<Args extends ZodRawShape>(\n name: string,\n description: string,\n priceUSD: number,\n paramsSchema: Args,\n annotations: ToolAnnotations,\n cb: ToolCallback<Args>\n ): RegisteredTool;\n}\n\nexport function withX402<T extends McpServer>(\n server: T,\n cfg: X402Config\n): T & X402AugmentedServer {\n const network = normalizeNetwork(cfg.network);\n const facilitatorConfig: FacilitatorConfig = cfg.facilitator ?? {\n url: \"https://x402.org/facilitator\"\n };\n\n // Create v2 resource server with facilitator client\n const facilitatorClient = new HTTPFacilitatorClient(facilitatorConfig);\n const resourceServer = new x402ResourceServer(facilitatorClient);\n registerServerEvmScheme(resourceServer);\n\n // Lazy initialization: fetch supported kinds from facilitator on first use\n let initPromise: Promise<void> | null = null;\n function ensureInitialized(): Promise<void> {\n if (!initPromise) {\n initPromise = resourceServer.initialize().catch((err) => {\n initPromise = null; // allow retry on failure\n throw err;\n });\n }\n return initPromise;\n }\n\n function paidTool<Args extends ZodRawShape>(\n name: string,\n description: string,\n priceUSD: number,\n paramsSchema: Args,\n annotations: ToolAnnotations,\n cb: ToolCallback<Args>\n ): RegisteredTool {\n return server.registerTool(\n name,\n {\n description,\n inputSchema: paramsSchema,\n annotations,\n _meta: {\n \"agents-x402/paymentRequired\": true,\n \"agents-x402/priceUSD\": priceUSD\n }\n },\n (async (args, extra) => {\n await ensureInitialized();\n\n // Build v2 payment requirements for this tool call\n const resourceConfig: ResourceConfig = {\n scheme: \"exact\",\n payTo: cfg.recipient,\n price: priceUSD,\n network,\n maxTimeoutSeconds: 300\n };\n\n let requirements: PaymentRequirements[];\n try {\n requirements =\n await resourceServer.buildPaymentRequirements(resourceConfig);\n } catch {\n const payload = { x402Version: 2, error: \"PRICE_COMPUTE_FAILED\" };\n return {\n isError: true,\n _meta: { \"x402/error\": payload },\n content: [{ type: \"text\", text: JSON.stringify(payload) }]\n } as const;\n }\n\n const resourceInfo = {\n url: `x402://${name}`,\n description,\n mimeType: \"application/json\"\n };\n\n // Get payment token from MCP _meta or HTTP headers\n // Support both v2 (PAYMENT-SIGNATURE) and v1 (X-PAYMENT) header names\n const headers = extra?.requestInfo?.headers ?? {};\n const token =\n (extra?._meta?.[\"x402/payment\"] as string | undefined) ??\n headers[\"PAYMENT-SIGNATURE\"] ??\n headers[\"X-PAYMENT\"];\n\n const paymentRequired = (\n reason = \"PAYMENT_REQUIRED\",\n extraFields: Record<string, unknown> = {}\n ) => {\n const payload = {\n x402Version: 2,\n error: reason,\n resource: resourceInfo,\n accepts: requirements,\n ...extraFields\n };\n return {\n isError: true,\n _meta: { \"x402/error\": payload },\n content: [{ type: \"text\", text: JSON.stringify(payload) }]\n } as const;\n };\n\n if (!token || typeof token !== \"string\") return paymentRequired();\n\n // Decode the payment payload (base64-encoded JSON)\n let paymentPayload: PaymentPayload;\n try {\n paymentPayload = JSON.parse(atob(token));\n } catch {\n return paymentRequired(\"INVALID_PAYMENT\");\n }\n\n // Find matching requirements for this payment\n const matchingReq = resourceServer.findMatchingRequirements(\n requirements,\n paymentPayload\n );\n if (!matchingReq) {\n return paymentRequired(\"INVALID_PAYMENT\");\n }\n\n // Verify payment with facilitator\n try {\n const vr = await resourceServer.verifyPayment(\n paymentPayload,\n matchingReq\n );\n if (!vr.isValid) {\n return paymentRequired(vr.invalidReason ?? \"INVALID_PAYMENT\", {\n payer: vr.payer\n });\n }\n } catch {\n return paymentRequired(\"INVALID_PAYMENT\");\n }\n\n // Execute the tool callback\n let result: CallToolResult;\n let failed = false;\n try {\n result = await cb(args, extra);\n if (\n result &&\n typeof result === \"object\" &&\n \"isError\" in result &&\n result.isError\n ) {\n failed = true;\n }\n } catch (e) {\n failed = true;\n result = {\n isError: true,\n content: [\n { type: \"text\", text: `Tool execution failed: ${String(e)}` }\n ]\n };\n }\n\n // Settle payment only on success\n if (!failed) {\n try {\n const s = await resourceServer.settlePayment(\n paymentPayload,\n matchingReq\n );\n if (s.success) {\n result._meta ??= {};\n result._meta[\"x402/payment-response\"] = {\n success: true,\n transaction: s.transaction,\n network: s.network,\n payer: s.payer\n };\n } else {\n return paymentRequired(s.errorReason ?? \"SETTLEMENT_FAILED\");\n }\n } catch {\n return paymentRequired(\"SETTLEMENT_FAILED\");\n }\n }\n\n return result;\n }) as ToolCallback<Args>\n );\n }\n\n Object.defineProperty(server, \"paidTool\", {\n value: paidTool,\n writable: false,\n enumerable: false,\n configurable: true\n });\n\n // Tell TS the object now also has the paidTool method\n return server as T & X402AugmentedServer;\n}\n\n/*\n ======= CLIENT SIDE =======\n*/\n\nexport interface X402AugmentedClient {\n callTool(\n x402ConfirmationCallback:\n | ((payment: PaymentRequirements[]) => Promise<boolean>)\n | null,\n params: CallToolRequest[\"params\"],\n options?: CallToolRequestOptions\n ): Promise<CallToolResult>;\n /**\n * @deprecated Prefer the request-options overload. Explicit legacy result\n * schemas remain honored through the SDK v2 request funnel.\n */\n callTool(\n x402ConfirmationCallback:\n | ((payment: PaymentRequirements[]) => Promise<boolean>)\n | null,\n params: CallToolRequest[\"params\"],\n resultSchema: LegacyCallToolResultSchema,\n options?: CallToolRequestOptions\n ): Promise<CallToolResult>;\n}\n\nexport type X402ClientConfig = {\n /**\n * EVM account/signer for signing payment authorizations.\n * Use `privateKeyToAccount()` from viem/accounts to create one.\n */\n account: ClientEvmSigner;\n /**\n * Preferred network identifier (optional).\n * Accepts both legacy names (\"base-sepolia\") and CAIP-2 format (\"eip155:84532\").\n * When set, the client prefers payment requirements matching this network.\n * If omitted, the client automatically selects from available requirements.\n */\n network?: string;\n /** Maximum payment value in atomic units (default: 0.10 USDC = 100000) */\n maxPaymentValue?: bigint;\n /** @deprecated No longer used in v2. The protocol version is determined automatically. */\n version?: number;\n /** Confirmation callback for payment approval */\n confirmationCallback?: (payment: PaymentRequirements[]) => Promise<boolean>;\n};\n\nexport function withX402Client<T extends CompatibleMcpClient>(\n client: T,\n x402Config: X402ClientConfig\n): X402AugmentedClient & T {\n const invoker = bindMcpClient(client);\n const { account } = x402Config;\n\n const maxPaymentValue = x402Config.maxPaymentValue ?? BigInt(100_000); // 0.10 USDC\n\n // Create v2 x402 payment client with EVM scheme support\n const paymentClient = new x402Client();\n registerClientEvmScheme(paymentClient, { signer: account });\n\n // If a preferred network is specified, register a policy to prefer it\n if (x402Config.network) {\n const preferredNetwork = normalizeNetwork(x402Config.network);\n paymentClient.registerPolicy((_version, reqs) => {\n const matching = reqs.filter((r) => r.network === preferredNetwork);\n return matching.length > 0 ? matching : reqs;\n });\n }\n\n const listTools = async (\n params?: Parameters<MCPClient[\"listTools\"]>[0],\n options?: Parameters<MCPClient[\"listTools\"]>[1]\n ) => {\n const toolsRes = await invoker.listTools(params, options);\n return {\n ...toolsRes,\n tools: toolsRes.tools.map((tool) => {\n let description = tool.description;\n // Check _meta for payment information (agents-x402/ is our extension for pre-advertising prices)\n if (tool._meta?.[\"agents-x402/paymentRequired\"]) {\n const cost = tool._meta?.[\"agents-x402/priceUSD\"]\n ? `$${tool._meta?.[\"agents-x402/priceUSD\"]}`\n : \"an unknown amount\";\n description += ` (This is a paid tool, you will be charged ${cost} for its execution)`;\n }\n return {\n ...tool,\n description\n };\n })\n };\n };\n\n const callToolWithPayment = async (\n x402ConfirmationCallback:\n | ((payment: PaymentRequirements[]) => Promise<boolean>)\n | null,\n params: CallToolRequest[\"params\"],\n schemaOrOptions?: CallToolSchemaOrOptions,\n options?: CallToolRequestOptions\n ): ReturnType<MCPClient[\"callTool\"]> => {\n const invoke = (callParams: CallToolRequest[\"params\"]) =>\n invoker.callTool(callParams, schemaOrOptions, options);\n const res = await invoke(params);\n\n // Check for x402 payment required error in response metadata\n const maybeX402Error = res._meta?.[\"x402/error\"] as\n | (PaymentRequired & Record<string, unknown>)\n | undefined;\n\n if (\n res.isError &&\n maybeX402Error &&\n maybeX402Error.accepts &&\n Array.isArray(maybeX402Error.accepts) &&\n maybeX402Error.accepts.length > 0\n ) {\n const accepts = maybeX402Error.accepts;\n const confirmationCallback =\n x402ConfirmationCallback ?? x402Config.confirmationCallback;\n\n // Use the confirmation callback if provided\n if (confirmationCallback && !(await confirmationCallback(accepts))) {\n return {\n isError: true,\n content: [{ type: \"text\", text: \"User declined payment\" }]\n };\n }\n\n // Check max payment value against the first requirement's amount\n const selectedReq = accepts[0];\n if (!selectedReq || selectedReq.scheme !== \"exact\") return res;\n\n let amount: bigint;\n try {\n amount = BigInt(selectedReq.amount);\n } catch {\n return res; // malformed amount — return original error\n }\n if (amount > maxPaymentValue) {\n return {\n isError: true,\n content: [\n {\n type: \"text\",\n text: `Payment exceeds client cap: ${amount} > ${maxPaymentValue}`\n }\n ]\n };\n }\n\n // Reconstruct the PaymentRequired response for the v2 x402 client\n const paymentRequiredResponse: PaymentRequired = {\n x402Version: (maybeX402Error.x402Version as number) ?? 2,\n resource: (maybeX402Error.resource as PaymentRequired[\"resource\"]) ?? {\n url: \"\",\n description: \"\",\n mimeType: \"application/json\"\n },\n accepts,\n extensions: maybeX402Error.extensions as\n | Record<string, unknown>\n | undefined\n };\n\n // Create the payment payload using the v2 x402 client\n let paymentPayload: PaymentPayload;\n try {\n paymentPayload = await paymentClient.createPaymentPayload(\n paymentRequiredResponse\n );\n } catch {\n return {\n isError: true,\n content: [{ type: \"text\", text: \"Failed to create payment payload\" }]\n };\n }\n\n // Encode the payment payload as a base64 JSON token for MCP transport\n const token = btoa(JSON.stringify(paymentPayload));\n\n // Retry the tool call with the payment token\n return invoke({\n ...params,\n _meta: {\n ...params._meta,\n \"x402/payment\": token\n }\n });\n }\n\n return res;\n };\n\n const _client = client as X402AugmentedClient & T;\n Object.defineProperty(_client, \"listTools\", {\n value: listTools,\n writable: false,\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(_client, \"callTool\", {\n value: callToolWithPayment,\n writable: false,\n enumerable: false,\n configurable: true\n });\n\n return _client;\n}\n"],"mappings":";;;;;;;;;;AA2DA,MAAM,qBAA6C;CACjD,gBAAgB;CAChB,MAAM;CACN,UAAU;CACV,SAAS;AACX;;;;;AAMA,SAAgB,iBAAiB,SAA0B;CACzD,OAAQ,mBAAmB,YAAY;AACzC;AA+BA,SAAgB,SACd,QACA,KACyB;CACzB,MAAM,UAAU,iBAAiB,IAAI,OAAO;CAO5C,MAAM,iBAAiB,IAAI,mBAAmB,IADhB,sBALe,IAAI,eAAe,EAC9D,KAAK,+BACP,CAI8D,CAAC;CAC/D,uBAAwB,cAAc;CAGtC,IAAI,cAAoC;CACxC,SAAS,oBAAmC;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AS;IACT,SAAS,CACP;KACE,MAAM;KACN,MAAM,+BAA+B,OAAO,KAAK;IACnD,CACF;GACF;GAIF,MAAM,0BAA2C;IAC/C,aAAc,eAAe,eAA0B;IACvD,UAAW,eAAe,YAA4C;KACpE,KAAK;KACL,aAAa;KACb,UAAU;IACZ;IACA;IACA,YAAY,eAAe;GAG7B;GAGA,IAAI;GACJ,IAAI;IACF,iBAAiB,MAAM,cAAc,qBACnC,uBACF;GACF,QAAQ;IACN,OAAO;KACL,SAAS;KACT,SAAS,CAAC;MAAE,MAAM;MAAQ,MAAM;KAAmC,CAAC;IACtE;GACF;GAGA,MAAM,QAAQ,KAAK,KAAK,UAAU,cAAc,CAAC;GAGjD,OAAO,OAAO;IACZ,GAAG;IACH,OAAO;KACL,GAAG,OAAO;KACV,gBAAgB;IAClB;GACF,CAAC;EACH;EAEA,OAAO;CACT;CAEA,MAAM,UAAU;CAChB,OAAO,eAAe,SAAS,aAAa;EAC1C,OAAO;EACP,UAAU;EACV,YAAY;EACZ,cAAc;CAChB,CAAC;CACD,OAAO,eAAe,SAAS,YAAY;EACzC,OAAO;EACP,UAAU;EACV,YAAY;EACZ,cAAc;CAChB,CAAC;CAED,OAAO;AACT"}
|
|
@@ -1803,7 +1803,7 @@ const SEMANTIC_CONTEXT_KEYS = /* @__PURE__ */ new Set([
|
|
|
1803
1803
|
function runtimeContextAttributes(runtimeContextValue) {
|
|
1804
1804
|
const attributes = {};
|
|
1805
1805
|
const runtimeContext = recordValue(runtimeContextValue);
|
|
1806
|
-
for (const [key, value] of Object.entries(runtimeContext ?? {})) if (!SEMANTIC_CONTEXT_KEYS.has(key) && isScalarAttributeValue(value)) attributes[`cloudflare.agents.runtime_context.${key}`] = value;
|
|
1806
|
+
for (const [key, value] of Object.entries(runtimeContext ?? {})) if (!SEMANTIC_CONTEXT_KEYS.has(key) && isScalarAttributeValue(value)) attributes[key.startsWith("cloudflare.agents.") ? key : `cloudflare.agents.runtime_context.${key}`] = value;
|
|
1807
1807
|
return attributes;
|
|
1808
1808
|
}
|
|
1809
1809
|
function toolContextAttributes(toolName, toolContextValue) {
|
|
@@ -1820,6 +1820,7 @@ function isScalarAttributeValue(value) {
|
|
|
1820
1820
|
}
|
|
1821
1821
|
//#endregion
|
|
1822
1822
|
//#region src/observability/ai/index.ts
|
|
1823
|
+
const agentsAISDKTelemetryBrand = Symbol.for("cloudflare.agents.ai-sdk-telemetry");
|
|
1823
1824
|
/**
|
|
1824
1825
|
* Wraps an AI SDK namespace with tracing.
|
|
1825
1826
|
*/
|
|
@@ -1834,10 +1835,12 @@ function wrapAISDK(ai, options = {}) {
|
|
|
1834
1835
|
* per-call telemetry configuration.
|
|
1835
1836
|
*/
|
|
1836
1837
|
function createAISDKTelemetry(options = {}) {
|
|
1837
|
-
|
|
1838
|
+
const telemetry = createAISDKV7Telemetry({
|
|
1838
1839
|
options,
|
|
1839
1840
|
tracer
|
|
1840
1841
|
});
|
|
1842
|
+
Object.defineProperty(telemetry, agentsAISDKTelemetryBrand, { value: true });
|
|
1843
|
+
return telemetry;
|
|
1841
1844
|
}
|
|
1842
1845
|
//#endregion
|
|
1843
1846
|
export { createAISDKTelemetry, wrapAISDK };
|