@x402/mcp 2.3.0-alpha
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 +351 -0
- package/dist/cjs/index.d.ts +971 -0
- package/dist/cjs/index.js +826 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/esm/index.d.mts +971 -0
- package/dist/esm/index.mjs +782 -0
- package/dist/esm/index.mjs.map +1 -0
- package/package.json +64 -0
|
@@ -0,0 +1,971 @@
|
|
|
1
|
+
import { PaymentRequired, PaymentPayload, SettleResponse, PaymentRequirements, Network, Price, SchemeNetworkClient } from '@x402/core/types';
|
|
2
|
+
export { Network, PaymentPayload, PaymentRequired, PaymentRequirements, SchemeNetworkClient, SchemeNetworkServer, SettleResponse } from '@x402/core/types';
|
|
3
|
+
import { x402Client, x402ClientConfig } from '@x402/core/client';
|
|
4
|
+
export { PaymentPolicy, SelectPaymentRequirements, x402Client, x402ClientConfig } from '@x402/core/client';
|
|
5
|
+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
6
|
+
import { x402ResourceServer } from '@x402/core/server';
|
|
7
|
+
export { x402ResourceServer } from '@x402/core/server';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* MCP JSON-RPC error code for payment required (x402)
|
|
11
|
+
*/
|
|
12
|
+
declare const MCP_PAYMENT_REQUIRED_CODE = 402;
|
|
13
|
+
/**
|
|
14
|
+
* MCP _meta key for payment payload (client → server)
|
|
15
|
+
*/
|
|
16
|
+
declare const MCP_PAYMENT_META_KEY = "x402/payment";
|
|
17
|
+
/**
|
|
18
|
+
* MCP _meta key for payment response (server → client)
|
|
19
|
+
*/
|
|
20
|
+
declare const MCP_PAYMENT_RESPONSE_META_KEY = "x402/payment-response";
|
|
21
|
+
/**
|
|
22
|
+
* Dynamic function to resolve payTo address based on tool call context
|
|
23
|
+
*/
|
|
24
|
+
type DynamicPayTo = (context: MCPToolContext) => string | Promise<string>;
|
|
25
|
+
/**
|
|
26
|
+
* Dynamic function to resolve price based on tool call context
|
|
27
|
+
*/
|
|
28
|
+
type DynamicPrice = (context: MCPToolContext) => Price | Promise<Price>;
|
|
29
|
+
/**
|
|
30
|
+
* Context provided to dynamic functions and hooks during tool execution
|
|
31
|
+
*/
|
|
32
|
+
interface MCPToolContext {
|
|
33
|
+
/** The name of the tool being called */
|
|
34
|
+
toolName: string;
|
|
35
|
+
/** The arguments passed to the tool */
|
|
36
|
+
arguments: Record<string, unknown>;
|
|
37
|
+
/** Optional metadata from the request */
|
|
38
|
+
meta?: Record<string, unknown>;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Payment configuration for a paid MCP tool
|
|
42
|
+
*/
|
|
43
|
+
interface MCPToolPaymentConfig {
|
|
44
|
+
/** Payment scheme identifier (e.g., "exact") */
|
|
45
|
+
scheme: string;
|
|
46
|
+
/** Blockchain network identifier in CAIP-2 format (e.g., "eip155:84532") */
|
|
47
|
+
network: Network;
|
|
48
|
+
/** Price for the tool call (e.g., "$0.10", "1000000") */
|
|
49
|
+
price: Price | DynamicPrice;
|
|
50
|
+
/** Recipient wallet address or dynamic resolver */
|
|
51
|
+
payTo: string | DynamicPayTo;
|
|
52
|
+
/** Maximum time allowed for payment completion in seconds */
|
|
53
|
+
maxTimeoutSeconds?: number;
|
|
54
|
+
/** Scheme-specific additional information */
|
|
55
|
+
extra?: Record<string, unknown>;
|
|
56
|
+
/** Resource metadata for the tool */
|
|
57
|
+
resource?: {
|
|
58
|
+
/** Custom URL for the resource (defaults to mcp://tool/{toolName}) */
|
|
59
|
+
url?: string;
|
|
60
|
+
/** Human-readable description of the tool */
|
|
61
|
+
description?: string;
|
|
62
|
+
/** MIME type of the tool response */
|
|
63
|
+
mimeType?: string;
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Result of processing an MCP tool request for payment
|
|
68
|
+
*/
|
|
69
|
+
type MCPPaymentProcessResult = {
|
|
70
|
+
type: "no-payment-required";
|
|
71
|
+
} | {
|
|
72
|
+
type: "payment-verified";
|
|
73
|
+
paymentPayload: PaymentPayload;
|
|
74
|
+
paymentRequirements: PaymentRequirements;
|
|
75
|
+
} | {
|
|
76
|
+
type: "payment-error";
|
|
77
|
+
error: MCPPaymentError;
|
|
78
|
+
};
|
|
79
|
+
/**
|
|
80
|
+
* MCP payment error structure for JSON-RPC error responses
|
|
81
|
+
*/
|
|
82
|
+
interface MCPPaymentError {
|
|
83
|
+
/** JSON-RPC error code (402 for payment required) */
|
|
84
|
+
code: number;
|
|
85
|
+
/** Human-readable error message */
|
|
86
|
+
message: string;
|
|
87
|
+
/** PaymentRequired data for 402 errors */
|
|
88
|
+
data?: PaymentRequired;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Context provided to onPaymentRequired hooks
|
|
92
|
+
*/
|
|
93
|
+
interface PaymentRequiredContext {
|
|
94
|
+
/** The tool name that returned 402 */
|
|
95
|
+
toolName: string;
|
|
96
|
+
/** The arguments that were passed to the tool */
|
|
97
|
+
arguments: Record<string, unknown>;
|
|
98
|
+
/** The payment requirements from the server */
|
|
99
|
+
paymentRequired: PaymentRequired;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Result from onPaymentRequired hook
|
|
103
|
+
*/
|
|
104
|
+
interface PaymentRequiredHookResult {
|
|
105
|
+
/** Custom payment payload to use instead of auto-generated */
|
|
106
|
+
payment?: PaymentPayload;
|
|
107
|
+
/** Skip payment and abort the call */
|
|
108
|
+
abort?: boolean;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Hook called when a 402 response is received, before payment processing.
|
|
112
|
+
* Return payment to use that instead of auto-generating, abort: true to stop.
|
|
113
|
+
* Return void/undefined to proceed with normal payment flow.
|
|
114
|
+
*/
|
|
115
|
+
type PaymentRequiredHook = (context: PaymentRequiredContext) => Promise<PaymentRequiredHookResult | void> | PaymentRequiredHookResult | void;
|
|
116
|
+
/**
|
|
117
|
+
* Options for x402MCPClient
|
|
118
|
+
*/
|
|
119
|
+
interface x402MCPClientOptions {
|
|
120
|
+
/**
|
|
121
|
+
* Whether to automatically retry tool calls with payment on 402 errors.
|
|
122
|
+
* When true (default), the client will automatically create and submit
|
|
123
|
+
* payment when a 402 error is received.
|
|
124
|
+
* When false, the client will throw the 402 error for manual handling.
|
|
125
|
+
*
|
|
126
|
+
* @default true
|
|
127
|
+
*/
|
|
128
|
+
autoPayment?: boolean;
|
|
129
|
+
/**
|
|
130
|
+
* Hook called when a payment is requested by the server (402 response).
|
|
131
|
+
* Return true to proceed with payment, false to abort.
|
|
132
|
+
* Only called when autoPayment is true.
|
|
133
|
+
*
|
|
134
|
+
* This can be used to implement human-in-the-loop approval.
|
|
135
|
+
*/
|
|
136
|
+
onPaymentRequested?: (context: PaymentRequestedContext) => Promise<boolean> | boolean;
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Context provided to payment requested hook
|
|
140
|
+
*/
|
|
141
|
+
interface PaymentRequestedContext {
|
|
142
|
+
/** The tool being called */
|
|
143
|
+
toolName: string;
|
|
144
|
+
/** The arguments passed to the tool */
|
|
145
|
+
arguments: Record<string, unknown>;
|
|
146
|
+
/** The payment requirements from the server */
|
|
147
|
+
paymentRequired: PaymentRequired;
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Context provided to server-side hooks during tool execution
|
|
151
|
+
*/
|
|
152
|
+
interface ServerHookContext {
|
|
153
|
+
/** The name of the tool being called */
|
|
154
|
+
toolName: string;
|
|
155
|
+
/** The arguments passed to the tool */
|
|
156
|
+
arguments: Record<string, unknown>;
|
|
157
|
+
/** The resolved payment requirements */
|
|
158
|
+
paymentRequirements: PaymentRequirements;
|
|
159
|
+
/** The payment payload from the client */
|
|
160
|
+
paymentPayload: PaymentPayload;
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Hook called before tool execution (after payment verification)
|
|
164
|
+
* Return false to abort execution and return a 402 error
|
|
165
|
+
*/
|
|
166
|
+
type BeforeExecutionHook = (context: ServerHookContext) => Promise<boolean | void> | boolean | void;
|
|
167
|
+
/**
|
|
168
|
+
* Context for after execution hook including the result
|
|
169
|
+
*/
|
|
170
|
+
interface AfterExecutionContext extends ServerHookContext {
|
|
171
|
+
/** The tool execution result */
|
|
172
|
+
result: {
|
|
173
|
+
content: Array<{
|
|
174
|
+
type: "text";
|
|
175
|
+
text: string;
|
|
176
|
+
}>;
|
|
177
|
+
isError?: boolean;
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Hook called after tool execution (before settlement)
|
|
182
|
+
*/
|
|
183
|
+
type AfterExecutionHook = (context: AfterExecutionContext) => Promise<void> | void;
|
|
184
|
+
/**
|
|
185
|
+
* Context for settlement hooks
|
|
186
|
+
*/
|
|
187
|
+
interface SettlementContext extends ServerHookContext {
|
|
188
|
+
/** The settlement result */
|
|
189
|
+
settlement: SettleResponse;
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Hook called after successful settlement
|
|
193
|
+
*/
|
|
194
|
+
type AfterSettlementHook = (context: SettlementContext) => Promise<void> | void;
|
|
195
|
+
/**
|
|
196
|
+
* Tool content item type
|
|
197
|
+
*/
|
|
198
|
+
interface ToolContentItem {
|
|
199
|
+
[key: string]: unknown;
|
|
200
|
+
type: string;
|
|
201
|
+
text?: string;
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Result of a tool call that includes payment response metadata
|
|
205
|
+
*/
|
|
206
|
+
interface MCPToolResultWithPayment {
|
|
207
|
+
/** Standard MCP tool result content */
|
|
208
|
+
content: ToolContentItem[];
|
|
209
|
+
/** Whether the tool execution resulted in an error */
|
|
210
|
+
isError?: boolean;
|
|
211
|
+
/** Payment response metadata (settlement info) */
|
|
212
|
+
paymentResponse?: SettleResponse;
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* MCP metadata with payment
|
|
216
|
+
*/
|
|
217
|
+
interface MCPMetaWithPayment {
|
|
218
|
+
[key: string]: unknown;
|
|
219
|
+
[MCP_PAYMENT_META_KEY]?: PaymentPayload;
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* MCP request params with optional _meta field for payment
|
|
223
|
+
*/
|
|
224
|
+
interface MCPRequestParamsWithMeta {
|
|
225
|
+
/** Tool name */
|
|
226
|
+
name: string;
|
|
227
|
+
/** Tool arguments */
|
|
228
|
+
arguments?: Record<string, unknown>;
|
|
229
|
+
/** Metadata including potential payment payload */
|
|
230
|
+
_meta?: MCPMetaWithPayment;
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* MCP metadata with payment response
|
|
234
|
+
*/
|
|
235
|
+
interface MCPMetaWithPaymentResponse {
|
|
236
|
+
[key: string]: unknown;
|
|
237
|
+
[MCP_PAYMENT_RESPONSE_META_KEY]?: SettleResponse;
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* MCP result with optional _meta field for payment response
|
|
241
|
+
*/
|
|
242
|
+
interface MCPResultWithMeta {
|
|
243
|
+
/** Tool result content */
|
|
244
|
+
content?: ToolContentItem[];
|
|
245
|
+
/** Whether the result is an error */
|
|
246
|
+
isError?: boolean;
|
|
247
|
+
/** Metadata including potential payment response */
|
|
248
|
+
_meta?: MCPMetaWithPaymentResponse;
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* MCP JSON-RPC error with payment required data
|
|
252
|
+
*/
|
|
253
|
+
interface MCPPaymentRequiredError {
|
|
254
|
+
/** JSON-RPC error code (402) */
|
|
255
|
+
code: typeof MCP_PAYMENT_REQUIRED_CODE;
|
|
256
|
+
/** Error message */
|
|
257
|
+
message: string;
|
|
258
|
+
/** PaymentRequired data */
|
|
259
|
+
data: PaymentRequired;
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* Type guard to check if an error is a payment required error
|
|
263
|
+
*
|
|
264
|
+
* @param error - The error to check
|
|
265
|
+
* @returns True if the error is a payment required error
|
|
266
|
+
*/
|
|
267
|
+
declare function isPaymentRequiredError(error: unknown): error is MCPPaymentRequiredError;
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* MCP content item - using a flexible type that matches the MCP SDK's content format.
|
|
271
|
+
* The MCP SDK returns content items with a `type` discriminator and type-specific fields.
|
|
272
|
+
* We use this type to preserve the original response structure from the SDK.
|
|
273
|
+
*/
|
|
274
|
+
type MCPContentItem = {
|
|
275
|
+
[key: string]: unknown;
|
|
276
|
+
type: string;
|
|
277
|
+
};
|
|
278
|
+
/**
|
|
279
|
+
* Hook called before payment is created
|
|
280
|
+
*/
|
|
281
|
+
type BeforePaymentHook = (context: PaymentRequestedContext) => Promise<void> | void;
|
|
282
|
+
/**
|
|
283
|
+
* Hook called after payment is submitted
|
|
284
|
+
*/
|
|
285
|
+
type AfterPaymentHook = (context: {
|
|
286
|
+
toolName: string;
|
|
287
|
+
paymentPayload: PaymentPayload;
|
|
288
|
+
result: MCPResultWithMeta;
|
|
289
|
+
settleResponse: SettleResponse | null;
|
|
290
|
+
}) => Promise<void> | void;
|
|
291
|
+
/**
|
|
292
|
+
* Result of a tool call with payment metadata.
|
|
293
|
+
* Content is forwarded directly from the MCP SDK to preserve the original response structure.
|
|
294
|
+
*/
|
|
295
|
+
interface x402MCPToolCallResult {
|
|
296
|
+
/** The tool result content, forwarded directly from MCP SDK */
|
|
297
|
+
content: MCPContentItem[];
|
|
298
|
+
/** Whether the tool returned an error */
|
|
299
|
+
isError?: boolean;
|
|
300
|
+
/** Payment settlement response if payment was made */
|
|
301
|
+
paymentResponse?: SettleResponse;
|
|
302
|
+
/** Whether payment was required and submitted */
|
|
303
|
+
paymentMade: boolean;
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* x402-enabled MCP client that handles payment for tool calls.
|
|
307
|
+
*
|
|
308
|
+
* Wraps an MCP client to automatically detect 402 (payment required) errors
|
|
309
|
+
* from tool calls, create payment payloads, and retry with payment attached.
|
|
310
|
+
*
|
|
311
|
+
* PROTOCOL COMPLIANCE:
|
|
312
|
+
* This wrapper is a COMPLETE, TRANSPARENT passthrough exposing all 19 public methods
|
|
313
|
+
* from the MCP SDK Client class. It's suitable for any MCP use case including:
|
|
314
|
+
* - Chatbots and conversational agents
|
|
315
|
+
* - IDE integrations (like Cursor, VSCode)
|
|
316
|
+
* - Autonomous agents
|
|
317
|
+
* - Custom MCP applications
|
|
318
|
+
*
|
|
319
|
+
* Only callTool() is enhanced with payment handling. All other methods are direct
|
|
320
|
+
* passthroughs ensuring full MCP protocol compatibility.
|
|
321
|
+
*
|
|
322
|
+
* STABILITY:
|
|
323
|
+
* Depends on formal MCP specification (JSON-RPC 2.0 based) with semantic versioning.
|
|
324
|
+
* Proven stable across SDK versions: 1.9.0 → 1.12.1 → 1.15.1
|
|
325
|
+
*
|
|
326
|
+
* @example
|
|
327
|
+
* ```typescript
|
|
328
|
+
* import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
329
|
+
* import { x402MCPClient } from "@x402/mcp";
|
|
330
|
+
* import { x402Client } from "@x402/core/client";
|
|
331
|
+
* import { ExactEvmScheme } from "@x402/evm/exact/client";
|
|
332
|
+
*
|
|
333
|
+
* const paymentClient = new x402Client()
|
|
334
|
+
* .register("eip155:84532", new ExactEvmScheme(account));
|
|
335
|
+
*
|
|
336
|
+
* const mcpClient = new Client({ name: "my-agent", version: "1.0.0" }, {...});
|
|
337
|
+
* const x402Mcp = new x402MCPClient(mcpClient, paymentClient, {
|
|
338
|
+
* autoPayment: true,
|
|
339
|
+
* onPaymentRequested: async ({ paymentRequired }) => {
|
|
340
|
+
* return confirm(`Pay ${paymentRequired.accepts[0].amount}?`);
|
|
341
|
+
* },
|
|
342
|
+
* });
|
|
343
|
+
*
|
|
344
|
+
* await x402Mcp.connect(transport);
|
|
345
|
+
*
|
|
346
|
+
* // Full MCP protocol access - all 19 methods available
|
|
347
|
+
* const tools = await x402Mcp.listTools();
|
|
348
|
+
* const resource = await x402Mcp.readResource({ uri: "file://..." });
|
|
349
|
+
* const prompt = await x402Mcp.getPrompt({ name: "code-review" });
|
|
350
|
+
* const result = await x402Mcp.callTool("financial_analysis", { ticker: "AAPL" });
|
|
351
|
+
* ```
|
|
352
|
+
*/
|
|
353
|
+
declare class x402MCPClient {
|
|
354
|
+
private readonly mcpClient;
|
|
355
|
+
private readonly _paymentClient;
|
|
356
|
+
private readonly options;
|
|
357
|
+
private readonly paymentRequiredHooks;
|
|
358
|
+
private readonly beforePaymentHooks;
|
|
359
|
+
private readonly afterPaymentHooks;
|
|
360
|
+
/**
|
|
361
|
+
* Creates a new x402MCPClient instance.
|
|
362
|
+
*
|
|
363
|
+
* @param mcpClient - The underlying MCP client instance
|
|
364
|
+
* @param paymentClient - The x402 client for creating payment payloads
|
|
365
|
+
* @param options - Configuration options
|
|
366
|
+
*/
|
|
367
|
+
constructor(mcpClient: Client, paymentClient: x402Client, options?: x402MCPClientOptions);
|
|
368
|
+
/**
|
|
369
|
+
* Get the underlying MCP client instance.
|
|
370
|
+
*
|
|
371
|
+
* @returns The MCP client instance
|
|
372
|
+
*/
|
|
373
|
+
get client(): Client;
|
|
374
|
+
/**
|
|
375
|
+
* Get the underlying x402 payment client instance.
|
|
376
|
+
*
|
|
377
|
+
* @returns The x402 client instance
|
|
378
|
+
*/
|
|
379
|
+
get paymentClient(): x402Client;
|
|
380
|
+
/**
|
|
381
|
+
* Connect to an MCP server transport.
|
|
382
|
+
* Passthrough to the underlying MCP client.
|
|
383
|
+
*
|
|
384
|
+
* @param transport - The transport to connect to
|
|
385
|
+
* @returns Promise that resolves when connected
|
|
386
|
+
*/
|
|
387
|
+
connect(transport: Parameters<Client["connect"]>[0]): Promise<void>;
|
|
388
|
+
/**
|
|
389
|
+
* Close the MCP connection.
|
|
390
|
+
* Passthrough to the underlying MCP client.
|
|
391
|
+
*
|
|
392
|
+
* @returns Promise that resolves when closed
|
|
393
|
+
*/
|
|
394
|
+
close(): Promise<void>;
|
|
395
|
+
/**
|
|
396
|
+
* List available tools from the server.
|
|
397
|
+
* Passthrough to the underlying MCP client.
|
|
398
|
+
*
|
|
399
|
+
* @returns Promise resolving to the list of tools
|
|
400
|
+
*/
|
|
401
|
+
listTools(): ReturnType<Client["listTools"]>;
|
|
402
|
+
/**
|
|
403
|
+
* List available resources from the server.
|
|
404
|
+
* Passthrough to the underlying MCP client.
|
|
405
|
+
*
|
|
406
|
+
* @returns Promise resolving to the list of resources
|
|
407
|
+
*/
|
|
408
|
+
listResources(): ReturnType<Client["listResources"]>;
|
|
409
|
+
/**
|
|
410
|
+
* List available prompts from the server.
|
|
411
|
+
* Passthrough to the underlying MCP client.
|
|
412
|
+
*
|
|
413
|
+
* @returns Promise resolving to the list of prompts
|
|
414
|
+
*/
|
|
415
|
+
listPrompts(): ReturnType<Client["listPrompts"]>;
|
|
416
|
+
/**
|
|
417
|
+
* Get a specific prompt from the server.
|
|
418
|
+
* Passthrough to the underlying MCP client.
|
|
419
|
+
*
|
|
420
|
+
* @param args - Arguments for getPrompt method
|
|
421
|
+
* @returns Promise resolving to the prompt
|
|
422
|
+
*/
|
|
423
|
+
getPrompt(...args: Parameters<Client["getPrompt"]>): ReturnType<Client["getPrompt"]>;
|
|
424
|
+
/**
|
|
425
|
+
* Read a resource from the server.
|
|
426
|
+
* Passthrough to the underlying MCP client.
|
|
427
|
+
*
|
|
428
|
+
* @param args - Arguments for readResource method
|
|
429
|
+
* @returns Promise resolving to the resource content
|
|
430
|
+
*/
|
|
431
|
+
readResource(...args: Parameters<Client["readResource"]>): ReturnType<Client["readResource"]>;
|
|
432
|
+
/**
|
|
433
|
+
* List resource templates from the server.
|
|
434
|
+
* Passthrough to the underlying MCP client.
|
|
435
|
+
*
|
|
436
|
+
* @param args - Arguments for listResourceTemplates method
|
|
437
|
+
* @returns Promise resolving to the list of resource templates
|
|
438
|
+
*/
|
|
439
|
+
listResourceTemplates(...args: Parameters<Client["listResourceTemplates"]>): ReturnType<Client["listResourceTemplates"]>;
|
|
440
|
+
/**
|
|
441
|
+
* Subscribe to resource updates.
|
|
442
|
+
* Passthrough to the underlying MCP client.
|
|
443
|
+
*
|
|
444
|
+
* @param args - Arguments for subscribeResource method
|
|
445
|
+
* @returns Promise resolving when subscribed
|
|
446
|
+
*/
|
|
447
|
+
subscribeResource(...args: Parameters<Client["subscribeResource"]>): ReturnType<Client["subscribeResource"]>;
|
|
448
|
+
/**
|
|
449
|
+
* Unsubscribe from resource updates.
|
|
450
|
+
* Passthrough to the underlying MCP client.
|
|
451
|
+
*
|
|
452
|
+
* @param args - Arguments for unsubscribeResource method
|
|
453
|
+
* @returns Promise resolving when unsubscribed
|
|
454
|
+
*/
|
|
455
|
+
unsubscribeResource(...args: Parameters<Client["unsubscribeResource"]>): ReturnType<Client["unsubscribeResource"]>;
|
|
456
|
+
/**
|
|
457
|
+
* Ping the server.
|
|
458
|
+
* Passthrough to the underlying MCP client.
|
|
459
|
+
*
|
|
460
|
+
* @param args - Arguments for ping method
|
|
461
|
+
* @returns Promise resolving to ping response
|
|
462
|
+
*/
|
|
463
|
+
ping(...args: Parameters<Client["ping"]>): ReturnType<Client["ping"]>;
|
|
464
|
+
/**
|
|
465
|
+
* Request completion suggestions.
|
|
466
|
+
* Passthrough to the underlying MCP client.
|
|
467
|
+
*
|
|
468
|
+
* @param args - Arguments for complete method
|
|
469
|
+
* @returns Promise resolving to completion suggestions
|
|
470
|
+
*/
|
|
471
|
+
complete(...args: Parameters<Client["complete"]>): ReturnType<Client["complete"]>;
|
|
472
|
+
/**
|
|
473
|
+
* Set the logging level on the server.
|
|
474
|
+
* Passthrough to the underlying MCP client.
|
|
475
|
+
*
|
|
476
|
+
* @param args - Arguments for setLoggingLevel method
|
|
477
|
+
* @returns Promise resolving when level is set
|
|
478
|
+
*/
|
|
479
|
+
setLoggingLevel(...args: Parameters<Client["setLoggingLevel"]>): ReturnType<Client["setLoggingLevel"]>;
|
|
480
|
+
/**
|
|
481
|
+
* Get server capabilities after initialization.
|
|
482
|
+
* Passthrough to the underlying MCP client.
|
|
483
|
+
*
|
|
484
|
+
* @returns Server capabilities or undefined if not initialized
|
|
485
|
+
*/
|
|
486
|
+
getServerCapabilities(): ReturnType<Client["getServerCapabilities"]>;
|
|
487
|
+
/**
|
|
488
|
+
* Get server version information after initialization.
|
|
489
|
+
* Passthrough to the underlying MCP client.
|
|
490
|
+
*
|
|
491
|
+
* @returns Server version info or undefined if not initialized
|
|
492
|
+
*/
|
|
493
|
+
getServerVersion(): ReturnType<Client["getServerVersion"]>;
|
|
494
|
+
/**
|
|
495
|
+
* Get server instructions after initialization.
|
|
496
|
+
* Passthrough to the underlying MCP client.
|
|
497
|
+
*
|
|
498
|
+
* @returns Server instructions or undefined if not initialized
|
|
499
|
+
*/
|
|
500
|
+
getInstructions(): ReturnType<Client["getInstructions"]>;
|
|
501
|
+
/**
|
|
502
|
+
* Send notification that roots list has changed.
|
|
503
|
+
* Passthrough to the underlying MCP client.
|
|
504
|
+
*
|
|
505
|
+
* @returns Promise resolving when notification is sent
|
|
506
|
+
*/
|
|
507
|
+
sendRootsListChanged(): ReturnType<Client["sendRootsListChanged"]>;
|
|
508
|
+
/**
|
|
509
|
+
* Register a hook to run when a 402 payment required is received.
|
|
510
|
+
* Hooks run in order; first to return a result wins.
|
|
511
|
+
*
|
|
512
|
+
* This can be used to:
|
|
513
|
+
* - Provide pre-existing payment payloads (implementation-specific, not part of x402 spec)
|
|
514
|
+
* - Abort the payment flow for certain tools
|
|
515
|
+
* - Log or track payment required events
|
|
516
|
+
*
|
|
517
|
+
* Note: Payment caching is an implementation pattern and not defined in the x402 MCP
|
|
518
|
+
* transport specification. Implementations that cache payments should ensure cached
|
|
519
|
+
* payloads are still valid (not expired, correct nonce, etc.).
|
|
520
|
+
*
|
|
521
|
+
* @param hook - Hook function
|
|
522
|
+
* @returns This instance for chaining
|
|
523
|
+
*
|
|
524
|
+
* @example
|
|
525
|
+
* ```typescript
|
|
526
|
+
* // Example: Custom payment handling (implementation-specific)
|
|
527
|
+
* client.onPaymentRequired(async ({ toolName, paymentRequired }) => {
|
|
528
|
+
* // Custom logic to provide a payment or abort
|
|
529
|
+
* if (shouldAbort(toolName)) {
|
|
530
|
+
* return { abort: true };
|
|
531
|
+
* }
|
|
532
|
+
* // Return undefined to proceed with normal payment flow
|
|
533
|
+
* });
|
|
534
|
+
* ```
|
|
535
|
+
*/
|
|
536
|
+
onPaymentRequired(hook: PaymentRequiredHook): this;
|
|
537
|
+
/**
|
|
538
|
+
* Register a hook to run before payment is created.
|
|
539
|
+
*
|
|
540
|
+
* @param hook - Hook function
|
|
541
|
+
* @returns This instance for chaining
|
|
542
|
+
*/
|
|
543
|
+
onBeforePayment(hook: BeforePaymentHook): this;
|
|
544
|
+
/**
|
|
545
|
+
* Register a hook to run after payment is submitted.
|
|
546
|
+
*
|
|
547
|
+
* @param hook - Hook function
|
|
548
|
+
* @returns This instance for chaining
|
|
549
|
+
*/
|
|
550
|
+
onAfterPayment(hook: AfterPaymentHook): this;
|
|
551
|
+
/**
|
|
552
|
+
* Calls a tool, automatically handling 402 payment required errors.
|
|
553
|
+
*
|
|
554
|
+
* If the tool returns a 402 error and autoPayment is enabled, this method
|
|
555
|
+
* will automatically create a payment payload and retry the tool call.
|
|
556
|
+
*
|
|
557
|
+
* @param name - The name of the tool to call
|
|
558
|
+
* @param args - Arguments to pass to the tool
|
|
559
|
+
* @param options - Optional MCP request options (timeout, signal, etc.)
|
|
560
|
+
* @param options.timeout - Request timeout in milliseconds (default: 60000)
|
|
561
|
+
* @param options.signal - AbortSignal for cancellation
|
|
562
|
+
* @param options.resetTimeoutOnProgress - If true, progress notifications reset the timeout
|
|
563
|
+
* @returns The tool result with payment metadata
|
|
564
|
+
* @throws Error if payment is required but autoPayment is disabled and no payment provided
|
|
565
|
+
* @throws Error if payment approval is denied
|
|
566
|
+
* @throws Error if payment creation fails
|
|
567
|
+
*/
|
|
568
|
+
callTool(name: string, args?: Record<string, unknown>, options?: {
|
|
569
|
+
timeout?: number;
|
|
570
|
+
signal?: AbortSignal;
|
|
571
|
+
resetTimeoutOnProgress?: boolean;
|
|
572
|
+
}): Promise<x402MCPToolCallResult>;
|
|
573
|
+
/**
|
|
574
|
+
* Calls a tool with an explicit payment payload.
|
|
575
|
+
*
|
|
576
|
+
* Use this method when you want to provide payment upfront or when
|
|
577
|
+
* implementing custom payment handling.
|
|
578
|
+
*
|
|
579
|
+
* @param name - The name of the tool to call
|
|
580
|
+
* @param args - Arguments to pass to the tool
|
|
581
|
+
* @param paymentPayload - The payment payload to include
|
|
582
|
+
* @param options - Optional MCP request options (timeout, signal, etc.)
|
|
583
|
+
* @param options.timeout - Request timeout in milliseconds (default: 60000)
|
|
584
|
+
* @param options.signal - AbortSignal for cancellation
|
|
585
|
+
* @param options.resetTimeoutOnProgress - If true, progress notifications reset the timeout
|
|
586
|
+
* @returns The tool result with payment metadata
|
|
587
|
+
*/
|
|
588
|
+
callToolWithPayment(name: string, args: Record<string, unknown>, paymentPayload: PaymentPayload, options?: {
|
|
589
|
+
timeout?: number;
|
|
590
|
+
signal?: AbortSignal;
|
|
591
|
+
resetTimeoutOnProgress?: boolean;
|
|
592
|
+
}): Promise<x402MCPToolCallResult>;
|
|
593
|
+
/**
|
|
594
|
+
* Probes a tool to discover its payment requirements.
|
|
595
|
+
*
|
|
596
|
+
* **WARNING: Side Effects** - This method actually calls the tool to trigger a 402 response.
|
|
597
|
+
* If the tool is free (no payment required), it will execute and return null.
|
|
598
|
+
* Use with caution on tools that have side effects or are expensive to run.
|
|
599
|
+
*
|
|
600
|
+
* Useful for displaying pricing information to users before calling paid tools.
|
|
601
|
+
*
|
|
602
|
+
* @param name - The name of the tool to probe
|
|
603
|
+
* @param args - Arguments that may affect pricing (for dynamic pricing scenarios)
|
|
604
|
+
* @returns The payment requirements if the tool requires payment, null if the tool is free
|
|
605
|
+
*
|
|
606
|
+
* @example
|
|
607
|
+
* ```typescript
|
|
608
|
+
* // Check if a tool requires payment before calling
|
|
609
|
+
* const requirements = await client.getToolPaymentRequirements("expensive_analysis");
|
|
610
|
+
*
|
|
611
|
+
* if (requirements) {
|
|
612
|
+
* const price = requirements.accepts[0];
|
|
613
|
+
* console.log(`This tool costs ${price.amount} on ${price.network}`);
|
|
614
|
+
* // Optionally show user and get confirmation before calling
|
|
615
|
+
* } else {
|
|
616
|
+
* console.log("This tool is free");
|
|
617
|
+
* // Note: the tool has already executed!
|
|
618
|
+
* }
|
|
619
|
+
* ```
|
|
620
|
+
*/
|
|
621
|
+
getToolPaymentRequirements(name: string, args?: Record<string, unknown>): Promise<PaymentRequired | null>;
|
|
622
|
+
/**
|
|
623
|
+
* Extracts PaymentRequired from a tool result (structured 402 response).
|
|
624
|
+
*
|
|
625
|
+
* Per MCP transport spec, supports:
|
|
626
|
+
* 1. structuredContent with direct PaymentRequired object (optional, preferred)
|
|
627
|
+
* 2. content[0].text with JSON-encoded PaymentRequired object (required)
|
|
628
|
+
*
|
|
629
|
+
* @param result - The tool call result
|
|
630
|
+
* @returns PaymentRequired if this is a 402 response, null otherwise
|
|
631
|
+
*/
|
|
632
|
+
private extractPaymentRequiredFromResult;
|
|
633
|
+
/**
|
|
634
|
+
* Extracts PaymentRequired from an object.
|
|
635
|
+
* Expects direct PaymentRequired format (per MCP transport spec).
|
|
636
|
+
*
|
|
637
|
+
* @param obj - The object to extract from
|
|
638
|
+
* @returns PaymentRequired if found, null otherwise
|
|
639
|
+
*/
|
|
640
|
+
private extractPaymentRequiredFromObject;
|
|
641
|
+
}
|
|
642
|
+
/**
|
|
643
|
+
* Configuration for createx402MCPClient factory
|
|
644
|
+
*/
|
|
645
|
+
interface x402MCPClientConfig {
|
|
646
|
+
/** MCP client name */
|
|
647
|
+
name: string;
|
|
648
|
+
/** MCP client version */
|
|
649
|
+
version: string;
|
|
650
|
+
/**
|
|
651
|
+
* Payment scheme registrations.
|
|
652
|
+
* Each registration maps a network to its scheme client implementation.
|
|
653
|
+
*/
|
|
654
|
+
schemes: Array<{
|
|
655
|
+
network: Network;
|
|
656
|
+
client: SchemeNetworkClient;
|
|
657
|
+
x402Version?: number;
|
|
658
|
+
}>;
|
|
659
|
+
/**
|
|
660
|
+
* Whether to automatically retry tool calls with payment on 402 errors.
|
|
661
|
+
*
|
|
662
|
+
* @default true
|
|
663
|
+
*/
|
|
664
|
+
autoPayment?: boolean;
|
|
665
|
+
/**
|
|
666
|
+
* Hook called when a payment is requested.
|
|
667
|
+
* Return true to proceed with payment, false to abort.
|
|
668
|
+
*/
|
|
669
|
+
onPaymentRequested?: (context: PaymentRequestedContext) => Promise<boolean> | boolean;
|
|
670
|
+
/**
|
|
671
|
+
* Additional MCP client options
|
|
672
|
+
*/
|
|
673
|
+
mcpClientOptions?: Record<string, unknown>;
|
|
674
|
+
}
|
|
675
|
+
/**
|
|
676
|
+
* Wraps an existing MCP client with x402 payment handling.
|
|
677
|
+
*
|
|
678
|
+
* Use this when you already have an MCP client instance and want to add
|
|
679
|
+
* payment capabilities. For a simpler setup, use createx402MCPClient instead.
|
|
680
|
+
*
|
|
681
|
+
* @param mcpClient - The MCP client to wrap
|
|
682
|
+
* @param paymentClient - The x402 client for payment handling
|
|
683
|
+
* @param options - Configuration options
|
|
684
|
+
* @returns An x402MCPClient instance
|
|
685
|
+
*
|
|
686
|
+
* @example
|
|
687
|
+
* ```typescript
|
|
688
|
+
* import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
689
|
+
* import { wrapMCPClientWithPayment } from "@x402/mcp";
|
|
690
|
+
* import { x402Client } from "@x402/core/client";
|
|
691
|
+
* import { ExactEvmScheme } from "@x402/evm/exact/client";
|
|
692
|
+
*
|
|
693
|
+
* const mcpClient = new Client({ name: "my-agent", version: "1.0.0" });
|
|
694
|
+
* const paymentClient = new x402Client()
|
|
695
|
+
* .register("eip155:84532", new ExactEvmScheme(account));
|
|
696
|
+
*
|
|
697
|
+
* const x402Mcp = wrapMCPClientWithPayment(mcpClient, paymentClient, {
|
|
698
|
+
* autoPayment: true,
|
|
699
|
+
* });
|
|
700
|
+
*
|
|
701
|
+
* await x402Mcp.connect(transport);
|
|
702
|
+
* const result = await x402Mcp.callTool("paid_tool", { arg: "value" });
|
|
703
|
+
* ```
|
|
704
|
+
*/
|
|
705
|
+
declare function wrapMCPClientWithPayment(mcpClient: Client, paymentClient: x402Client, options?: x402MCPClientOptions): x402MCPClient;
|
|
706
|
+
/**
|
|
707
|
+
* Wraps an existing MCP client with x402 payment handling using a config object.
|
|
708
|
+
*
|
|
709
|
+
* Similar to wrapMCPClientWithPayment but uses a configuration object for
|
|
710
|
+
* setting up the payment client, similar to the axios pattern.
|
|
711
|
+
*
|
|
712
|
+
* @param mcpClient - The MCP client to wrap
|
|
713
|
+
* @param config - Payment client configuration
|
|
714
|
+
* @param options - x402 MCP client options
|
|
715
|
+
* @returns An x402MCPClient instance
|
|
716
|
+
*
|
|
717
|
+
* @example
|
|
718
|
+
* ```typescript
|
|
719
|
+
* import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
720
|
+
* import { wrapMCPClientWithPaymentFromConfig } from "@x402/mcp";
|
|
721
|
+
* import { ExactEvmScheme } from "@x402/evm/exact/client";
|
|
722
|
+
*
|
|
723
|
+
* const mcpClient = new Client({ name: "my-agent", version: "1.0.0" });
|
|
724
|
+
*
|
|
725
|
+
* const x402Mcp = wrapMCPClientWithPaymentFromConfig(mcpClient, {
|
|
726
|
+
* schemes: [
|
|
727
|
+
* { network: "eip155:84532", client: new ExactEvmScheme(account) },
|
|
728
|
+
* ],
|
|
729
|
+
* });
|
|
730
|
+
*
|
|
731
|
+
* await x402Mcp.connect(transport);
|
|
732
|
+
* ```
|
|
733
|
+
*/
|
|
734
|
+
declare function wrapMCPClientWithPaymentFromConfig(mcpClient: Client, config: x402ClientConfig, options?: x402MCPClientOptions): x402MCPClient;
|
|
735
|
+
/**
|
|
736
|
+
* Creates a fully configured x402 MCP client with sensible defaults.
|
|
737
|
+
*
|
|
738
|
+
* This factory function provides the simplest way to create an x402-enabled MCP client.
|
|
739
|
+
* It handles creation of both the underlying MCP Client and x402Client, making it
|
|
740
|
+
* easy to get started with paid tool calls.
|
|
741
|
+
*
|
|
742
|
+
* @param config - Client configuration options
|
|
743
|
+
* @returns A configured x402MCPClient instance
|
|
744
|
+
*
|
|
745
|
+
* @example
|
|
746
|
+
* ```typescript
|
|
747
|
+
* import { createx402MCPClient } from "@x402/mcp";
|
|
748
|
+
* import { ExactEvmScheme } from "@x402/evm/exact/client";
|
|
749
|
+
* import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
|
|
750
|
+
*
|
|
751
|
+
* const client = createx402MCPClient({
|
|
752
|
+
* name: "my-agent",
|
|
753
|
+
* version: "1.0.0",
|
|
754
|
+
* schemes: [
|
|
755
|
+
* { network: "eip155:84532", client: new ExactEvmScheme(account) },
|
|
756
|
+
* ],
|
|
757
|
+
* autoPayment: true,
|
|
758
|
+
* onPaymentRequested: async ({ paymentRequired }) => {
|
|
759
|
+
* console.log(`Payment required: ${paymentRequired.accepts[0].amount}`);
|
|
760
|
+
* return true; // Auto-approve
|
|
761
|
+
* },
|
|
762
|
+
* });
|
|
763
|
+
*
|
|
764
|
+
* // Connect to server
|
|
765
|
+
* const transport = new SSEClientTransport(new URL("http://localhost:4022/sse"));
|
|
766
|
+
* await client.connect(transport);
|
|
767
|
+
*
|
|
768
|
+
* // List available tools
|
|
769
|
+
* const { tools } = await client.listTools();
|
|
770
|
+
*
|
|
771
|
+
* // Call a paid tool (payment handled automatically)
|
|
772
|
+
* const result = await client.callTool("get_weather", { city: "NYC" });
|
|
773
|
+
* ```
|
|
774
|
+
*/
|
|
775
|
+
declare function createx402MCPClient(config: x402MCPClientConfig): x402MCPClient;
|
|
776
|
+
|
|
777
|
+
/**
|
|
778
|
+
* Payment wrapper for MCP tool handlers
|
|
779
|
+
*
|
|
780
|
+
* This module provides a functional API for adding x402 payment to MCP tool handlers.
|
|
781
|
+
* Use createPaymentWrapper to wrap tool handlers with payment verification and settlement.
|
|
782
|
+
*/
|
|
783
|
+
|
|
784
|
+
/**
|
|
785
|
+
* Configuration for payment wrapper.
|
|
786
|
+
*/
|
|
787
|
+
interface PaymentWrapperConfig {
|
|
788
|
+
/**
|
|
789
|
+
* Payment requirements that must be satisfied to call the tool.
|
|
790
|
+
* Typically a single entry, but can support multiple payment options.
|
|
791
|
+
*
|
|
792
|
+
* Each requirement specifies:
|
|
793
|
+
* - scheme: Payment scheme identifier (e.g., "exact")
|
|
794
|
+
* - network: Blockchain network in CAIP-2 format (e.g., "eip155:84532")
|
|
795
|
+
* - amount: Payment amount in token's smallest unit
|
|
796
|
+
* - asset: Token contract address
|
|
797
|
+
* - payTo: Recipient wallet address
|
|
798
|
+
* - maxTimeoutSeconds: Payment timeout (optional)
|
|
799
|
+
* - extra: Scheme-specific data (optional)
|
|
800
|
+
*/
|
|
801
|
+
accepts: PaymentRequirements[];
|
|
802
|
+
/** Resource metadata for the tool */
|
|
803
|
+
resource?: {
|
|
804
|
+
/** Custom URL for the resource (defaults to mcp://tool/{toolName}) */
|
|
805
|
+
url?: string;
|
|
806
|
+
/** Human-readable description of the tool */
|
|
807
|
+
description?: string;
|
|
808
|
+
/** MIME type of the tool response */
|
|
809
|
+
mimeType?: string;
|
|
810
|
+
};
|
|
811
|
+
/** Hooks for payment lifecycle events */
|
|
812
|
+
hooks?: {
|
|
813
|
+
/** Called after payment verification, before tool execution. Return false to abort. */
|
|
814
|
+
onBeforeExecution?: BeforeExecutionHook;
|
|
815
|
+
/** Called after tool execution, before settlement */
|
|
816
|
+
onAfterExecution?: AfterExecutionHook;
|
|
817
|
+
/** Called after successful settlement */
|
|
818
|
+
onAfterSettlement?: AfterSettlementHook;
|
|
819
|
+
};
|
|
820
|
+
}
|
|
821
|
+
/**
|
|
822
|
+
* Result type for wrapped tool handlers.
|
|
823
|
+
* Matches the MCP SDK's expected tool result format with optional _meta.
|
|
824
|
+
*/
|
|
825
|
+
interface WrappedToolResult {
|
|
826
|
+
[key: string]: unknown;
|
|
827
|
+
content: Array<{
|
|
828
|
+
type: "text";
|
|
829
|
+
text: string;
|
|
830
|
+
}>;
|
|
831
|
+
isError?: boolean;
|
|
832
|
+
_meta?: Record<string, unknown>;
|
|
833
|
+
structuredContent?: Record<string, unknown>;
|
|
834
|
+
}
|
|
835
|
+
/**
|
|
836
|
+
* Tool result type without payment metadata
|
|
837
|
+
*/
|
|
838
|
+
interface ToolResult {
|
|
839
|
+
[key: string]: unknown;
|
|
840
|
+
content: Array<{
|
|
841
|
+
type: "text";
|
|
842
|
+
text: string;
|
|
843
|
+
}>;
|
|
844
|
+
isError?: boolean;
|
|
845
|
+
}
|
|
846
|
+
/**
|
|
847
|
+
* Handler function type for tools to be wrapped with payment.
|
|
848
|
+
*/
|
|
849
|
+
type PaymentWrappedHandler<TArgs = Record<string, unknown>> = (args: TArgs, context: MCPToolContext) => Promise<ToolResult> | ToolResult;
|
|
850
|
+
/**
|
|
851
|
+
* MCP SDK compatible tool callback type.
|
|
852
|
+
* This type matches the signature expected by McpServer.tool() for tools with arguments.
|
|
853
|
+
* The extra parameter contains _meta and other request context from the MCP SDK.
|
|
854
|
+
*/
|
|
855
|
+
type MCPToolCallback<TArgs = Record<string, unknown>> = (args: TArgs, extra: unknown) => WrappedToolResult | Promise<WrappedToolResult>;
|
|
856
|
+
/**
|
|
857
|
+
* Creates a reusable payment wrapper for adding x402 payment to MCP tool handlers.
|
|
858
|
+
*
|
|
859
|
+
* This is the primary API for integrating x402 payments with MCP servers.
|
|
860
|
+
* Use this when you have an existing McpServer and want to add payment to specific tools.
|
|
861
|
+
*
|
|
862
|
+
* @param resourceServer - The x402 resource server for payment verification/settlement
|
|
863
|
+
* @param config - Payment configuration with accepts array
|
|
864
|
+
* @returns A function that wraps tool handlers with payment logic
|
|
865
|
+
*
|
|
866
|
+
* @example
|
|
867
|
+
* ```typescript
|
|
868
|
+
* // Build payment requirements using resource server
|
|
869
|
+
* const accepts = await resourceServer.buildPaymentRequirements({
|
|
870
|
+
* scheme: "exact",
|
|
871
|
+
* network: "eip155:84532",
|
|
872
|
+
* payTo: "0xRecipient",
|
|
873
|
+
* price: "$0.10",
|
|
874
|
+
* });
|
|
875
|
+
*
|
|
876
|
+
* // Create wrapper with payment requirements
|
|
877
|
+
* const paid = createPaymentWrapper(resourceServer, {
|
|
878
|
+
* accepts,
|
|
879
|
+
* hooks: {
|
|
880
|
+
* onBeforeExecution: async ({ paymentPayload }) => {
|
|
881
|
+
* if (await isRateLimited(paymentPayload.payer)) return false;
|
|
882
|
+
* },
|
|
883
|
+
* onAfterSettlement: async ({ settlement }) => {
|
|
884
|
+
* await sendReceipt(settlement.transaction);
|
|
885
|
+
* },
|
|
886
|
+
* },
|
|
887
|
+
* });
|
|
888
|
+
*
|
|
889
|
+
* // Use with McpServer.tool()
|
|
890
|
+
* mcpServer.tool("search", "Premium search ($0.10)", { query: z.string() },
|
|
891
|
+
* paid(async (args) => ({
|
|
892
|
+
* content: [{ type: "text", text: "Search results..." }]
|
|
893
|
+
* }))
|
|
894
|
+
* );
|
|
895
|
+
* ```
|
|
896
|
+
*/
|
|
897
|
+
declare function createPaymentWrapper(resourceServer: x402ResourceServer, config: PaymentWrapperConfig): <TArgs extends Record<string, unknown>>(handler: PaymentWrappedHandler<TArgs>) => MCPToolCallback<TArgs>;
|
|
898
|
+
|
|
899
|
+
/**
|
|
900
|
+
* Extracts payment payload from MCP request _meta field.
|
|
901
|
+
* Matches HTTP transport's simple validation approach.
|
|
902
|
+
*
|
|
903
|
+
* @param params - MCP request parameters that may contain _meta
|
|
904
|
+
* @returns The payment payload if present and valid, null otherwise
|
|
905
|
+
*/
|
|
906
|
+
declare function extractPaymentFromMeta(params: MCPRequestParamsWithMeta | undefined): PaymentPayload | null;
|
|
907
|
+
/**
|
|
908
|
+
* Attaches payment payload to MCP request params _meta field
|
|
909
|
+
*
|
|
910
|
+
* @param params - Original request params containing name and optional arguments
|
|
911
|
+
* @param params.name - The tool name
|
|
912
|
+
* @param params.arguments - Optional tool arguments
|
|
913
|
+
* @param paymentPayload - Payment payload to attach
|
|
914
|
+
* @returns New params object with payment in _meta
|
|
915
|
+
*/
|
|
916
|
+
declare function attachPaymentToMeta(params: {
|
|
917
|
+
name: string;
|
|
918
|
+
arguments?: Record<string, unknown>;
|
|
919
|
+
}, paymentPayload: PaymentPayload): MCPRequestParamsWithMeta;
|
|
920
|
+
/**
|
|
921
|
+
* Extracts payment response from MCP result _meta field
|
|
922
|
+
*
|
|
923
|
+
* @param result - MCP result that may contain _meta
|
|
924
|
+
* @returns The settlement response if present, null otherwise
|
|
925
|
+
*/
|
|
926
|
+
declare function extractPaymentResponseFromMeta(result: MCPResultWithMeta | undefined): SettleResponse | null;
|
|
927
|
+
/**
|
|
928
|
+
* Result content item for MCP responses
|
|
929
|
+
*/
|
|
930
|
+
interface ResultContentItem {
|
|
931
|
+
[key: string]: unknown;
|
|
932
|
+
type: string;
|
|
933
|
+
}
|
|
934
|
+
/**
|
|
935
|
+
* Attaches settlement response to MCP result _meta field
|
|
936
|
+
*
|
|
937
|
+
* @param result - Original result object containing content and optional isError flag
|
|
938
|
+
* @param result.content - The tool result content array
|
|
939
|
+
* @param result.isError - Optional flag indicating if the result is an error
|
|
940
|
+
* @param settleResponse - Settlement response to attach
|
|
941
|
+
* @returns New result object with payment response in _meta
|
|
942
|
+
*/
|
|
943
|
+
declare function attachPaymentResponseToMeta(result: {
|
|
944
|
+
content: ResultContentItem[];
|
|
945
|
+
isError?: boolean;
|
|
946
|
+
}, settleResponse: SettleResponse): MCPResultWithMeta;
|
|
947
|
+
/**
|
|
948
|
+
* Creates an MCP JSON-RPC error for payment required (402)
|
|
949
|
+
*
|
|
950
|
+
* @param paymentRequired - The payment requirements
|
|
951
|
+
* @param message - Optional custom error message
|
|
952
|
+
* @returns JSON-RPC error object
|
|
953
|
+
*/
|
|
954
|
+
declare function createPaymentRequiredError(paymentRequired: PaymentRequired, message?: string): MCPPaymentRequiredError;
|
|
955
|
+
/**
|
|
956
|
+
* Extracts PaymentRequired from an MCP JSON-RPC error
|
|
957
|
+
*
|
|
958
|
+
* @param error - The error object from a JSON-RPC response
|
|
959
|
+
* @returns The PaymentRequired if this is a 402 error, null otherwise
|
|
960
|
+
*/
|
|
961
|
+
declare function extractPaymentRequiredFromError(error: unknown): PaymentRequired | null;
|
|
962
|
+
/**
|
|
963
|
+
* Creates a resource URL for an MCP tool
|
|
964
|
+
*
|
|
965
|
+
* @param toolName - The name of the tool
|
|
966
|
+
* @param customUrl - Optional custom URL override
|
|
967
|
+
* @returns The resource URL
|
|
968
|
+
*/
|
|
969
|
+
declare function createToolResourceUrl(toolName: string, customUrl?: string): string;
|
|
970
|
+
|
|
971
|
+
export { type AfterExecutionContext, type AfterExecutionHook, type AfterPaymentHook, type AfterSettlementHook, type BeforeExecutionHook, type BeforePaymentHook, type DynamicPayTo, type DynamicPrice, type MCPContentItem, type MCPPaymentError, type MCPPaymentProcessResult, type MCPPaymentRequiredError, type MCPRequestParamsWithMeta, type MCPResultWithMeta, type MCPToolCallback, type MCPToolContext, type MCPToolPaymentConfig, type MCPToolResultWithPayment, MCP_PAYMENT_META_KEY, MCP_PAYMENT_REQUIRED_CODE, MCP_PAYMENT_RESPONSE_META_KEY, type PaymentRequestedContext, type PaymentRequiredContext, type PaymentRequiredHook, type PaymentRequiredHookResult, type PaymentWrappedHandler, type PaymentWrapperConfig, type ServerHookContext, type SettlementContext, type ToolContentItem, type ToolResult, type WrappedToolResult, attachPaymentResponseToMeta, attachPaymentToMeta, createPaymentRequiredError, createPaymentWrapper, createToolResourceUrl, createx402MCPClient, extractPaymentFromMeta, extractPaymentRequiredFromError, extractPaymentResponseFromMeta, isPaymentRequiredError, wrapMCPClientWithPayment, wrapMCPClientWithPaymentFromConfig, x402MCPClient, type x402MCPClientConfig, type x402MCPClientOptions, type x402MCPToolCallResult };
|