@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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/client/x402MCPClient.ts","../../src/utils/encoding.ts","../../src/types/mcp.ts","../../src/server/paymentWrapper.ts","../../src/index.ts"],"sourcesContent":["import type {\n PaymentPayload,\n PaymentRequired,\n SettleResponse,\n Network,\n SchemeNetworkClient,\n} from \"@x402/core/types\";\nimport { isPaymentRequired } from \"@x402/core/schemas\";\nimport { x402Client } from \"@x402/core/client\";\nimport type { x402ClientConfig } from \"@x402/core/client\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\n\nimport type {\n MCPResultWithMeta,\n PaymentRequestedContext,\n x402MCPClientOptions,\n PaymentRequiredHook,\n PaymentRequiredContext,\n} from \"../types\";\nimport { MCP_PAYMENT_REQUIRED_CODE, MCP_PAYMENT_META_KEY } from \"../types\";\nimport { extractPaymentResponseFromMeta } from \"../utils\";\n\n// ============================================================================\n// MCP SDK Result Types\n// ============================================================================\n\n/**\n * MCP content item - using a flexible type that matches the MCP SDK's content format.\n * The MCP SDK returns content items with a `type` discriminator and type-specific fields.\n * We use this type to preserve the original response structure from the SDK.\n */\nexport type MCPContentItem = {\n [key: string]: unknown;\n type: string;\n};\n\n/**\n * Result returned by MCP SDK callTool method.\n * This mirrors the SDK's CallToolResult type to ensure compatibility.\n */\ninterface MCPCallToolResult {\n content: MCPContentItem[];\n isError?: boolean;\n _meta?: Record<string, unknown>;\n structuredContent?: Record<string, unknown>;\n}\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\n/**\n * Type guard for MCP text content\n *\n * @param content - The content item to check\n * @returns True if the content is a text content item with a string text field\n */\nfunction isMCPTextContent(content: MCPContentItem): content is MCPContentItem & { text: string } {\n return content.type === \"text\" && typeof content.text === \"string\";\n}\n\n/**\n * Type guard for MCPCallToolResult\n *\n * @param result - The result to check\n * @returns True if the result is a valid MCP call tool result\n */\nfunction isMCPCallToolResult(result: unknown): result is MCPCallToolResult {\n if (typeof result !== \"object\" || result === null) {\n return false;\n }\n\n const obj = result as Record<string, unknown>;\n return Array.isArray(obj.content);\n}\n\n// ============================================================================\n// Hook Types\n// ============================================================================\n\n/**\n * Hook called before payment is created\n */\nexport type BeforePaymentHook = (context: PaymentRequestedContext) => Promise<void> | void;\n\n/**\n * Hook called after payment is submitted\n */\nexport type AfterPaymentHook = (context: {\n toolName: string;\n paymentPayload: PaymentPayload;\n result: MCPResultWithMeta;\n settleResponse: SettleResponse | null;\n}) => Promise<void> | void;\n\n// ============================================================================\n// Public Types\n// ============================================================================\n\n/**\n * Result of a tool call with payment metadata.\n * Content is forwarded directly from the MCP SDK to preserve the original response structure.\n */\nexport interface x402MCPToolCallResult {\n /** The tool result content, forwarded directly from MCP SDK */\n content: MCPContentItem[];\n /** Whether the tool returned an error */\n isError?: boolean;\n /** Payment settlement response if payment was made */\n paymentResponse?: SettleResponse;\n /** Whether payment was required and submitted */\n paymentMade: boolean;\n}\n\n/**\n * x402-enabled MCP client that handles payment for tool calls.\n *\n * Wraps an MCP client to automatically detect 402 (payment required) errors\n * from tool calls, create payment payloads, and retry with payment attached.\n *\n * PROTOCOL COMPLIANCE:\n * This wrapper is a COMPLETE, TRANSPARENT passthrough exposing all 19 public methods\n * from the MCP SDK Client class. It's suitable for any MCP use case including:\n * - Chatbots and conversational agents\n * - IDE integrations (like Cursor, VSCode)\n * - Autonomous agents\n * - Custom MCP applications\n *\n * Only callTool() is enhanced with payment handling. All other methods are direct\n * passthroughs ensuring full MCP protocol compatibility.\n *\n * STABILITY:\n * Depends on formal MCP specification (JSON-RPC 2.0 based) with semantic versioning.\n * Proven stable across SDK versions: 1.9.0 → 1.12.1 → 1.15.1\n *\n * @example\n * ```typescript\n * import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\n * import { x402MCPClient } from \"@x402/mcp\";\n * import { x402Client } from \"@x402/core/client\";\n * import { ExactEvmScheme } from \"@x402/evm/exact/client\";\n *\n * const paymentClient = new x402Client()\n * .register(\"eip155:84532\", new ExactEvmScheme(account));\n *\n * const mcpClient = new Client({ name: \"my-agent\", version: \"1.0.0\" }, {...});\n * const x402Mcp = new x402MCPClient(mcpClient, paymentClient, {\n * autoPayment: true,\n * onPaymentRequested: async ({ paymentRequired }) => {\n * return confirm(`Pay ${paymentRequired.accepts[0].amount}?`);\n * },\n * });\n *\n * await x402Mcp.connect(transport);\n *\n * // Full MCP protocol access - all 19 methods available\n * const tools = await x402Mcp.listTools();\n * const resource = await x402Mcp.readResource({ uri: \"file://...\" });\n * const prompt = await x402Mcp.getPrompt({ name: \"code-review\" });\n * const result = await x402Mcp.callTool(\"financial_analysis\", { ticker: \"AAPL\" });\n * ```\n */\nexport class x402MCPClient {\n private readonly mcpClient: Client;\n private readonly _paymentClient: x402Client;\n private readonly options: Required<x402MCPClientOptions>;\n private readonly paymentRequiredHooks: PaymentRequiredHook[] = [];\n private readonly beforePaymentHooks: BeforePaymentHook[] = [];\n private readonly afterPaymentHooks: AfterPaymentHook[] = [];\n\n /**\n * Creates a new x402MCPClient instance.\n *\n * @param mcpClient - The underlying MCP client instance\n * @param paymentClient - The x402 client for creating payment payloads\n * @param options - Configuration options\n */\n constructor(\n mcpClient: Client,\n paymentClient: x402Client,\n options: x402MCPClientOptions = {},\n ) {\n this.mcpClient = mcpClient;\n this._paymentClient = paymentClient;\n this.options = {\n autoPayment: options.autoPayment ?? true,\n onPaymentRequested: options.onPaymentRequested ?? (() => true),\n };\n }\n\n /**\n * Get the underlying MCP client instance.\n *\n * @returns The MCP client instance\n */\n get client(): Client {\n return this.mcpClient;\n }\n\n /**\n * Get the underlying x402 payment client instance.\n *\n * @returns The x402 client instance\n */\n get paymentClient(): x402Client {\n return this._paymentClient;\n }\n\n /**\n * Connect to an MCP server transport.\n * Passthrough to the underlying MCP client.\n *\n * @param transport - The transport to connect to\n * @returns Promise that resolves when connected\n */\n async connect(transport: Parameters<Client[\"connect\"]>[0]): Promise<void> {\n await this.mcpClient.connect(transport);\n }\n\n /**\n * Close the MCP connection.\n * Passthrough to the underlying MCP client.\n *\n * @returns Promise that resolves when closed\n */\n async close(): Promise<void> {\n await this.mcpClient.close();\n }\n\n /**\n * List available tools from the server.\n * Passthrough to the underlying MCP client.\n *\n * @returns Promise resolving to the list of tools\n */\n async listTools(): ReturnType<Client[\"listTools\"]> {\n return this.mcpClient.listTools();\n }\n\n /**\n * List available resources from the server.\n * Passthrough to the underlying MCP client.\n *\n * @returns Promise resolving to the list of resources\n */\n async listResources(): ReturnType<Client[\"listResources\"]> {\n return this.mcpClient.listResources();\n }\n\n /**\n * List available prompts from the server.\n * Passthrough to the underlying MCP client.\n *\n * @returns Promise resolving to the list of prompts\n */\n async listPrompts(): ReturnType<Client[\"listPrompts\"]> {\n return this.mcpClient.listPrompts();\n }\n\n /**\n * Get a specific prompt from the server.\n * Passthrough to the underlying MCP client.\n *\n * @param args - Arguments for getPrompt method\n * @returns Promise resolving to the prompt\n */\n async getPrompt(...args: Parameters<Client[\"getPrompt\"]>): ReturnType<Client[\"getPrompt\"]> {\n return this.mcpClient.getPrompt(...args);\n }\n\n /**\n * Read a resource from the server.\n * Passthrough to the underlying MCP client.\n *\n * @param args - Arguments for readResource method\n * @returns Promise resolving to the resource content\n */\n async readResource(...args: Parameters<Client[\"readResource\"]>): ReturnType<Client[\"readResource\"]> {\n return this.mcpClient.readResource(...args);\n }\n\n /**\n * List resource templates from the server.\n * Passthrough to the underlying MCP client.\n *\n * @param args - Arguments for listResourceTemplates method\n * @returns Promise resolving to the list of resource templates\n */\n async listResourceTemplates(...args: Parameters<Client[\"listResourceTemplates\"]>): ReturnType<Client[\"listResourceTemplates\"]> {\n return this.mcpClient.listResourceTemplates(...args);\n }\n\n /**\n * Subscribe to resource updates.\n * Passthrough to the underlying MCP client.\n *\n * @param args - Arguments for subscribeResource method\n * @returns Promise resolving when subscribed\n */\n async subscribeResource(...args: Parameters<Client[\"subscribeResource\"]>): ReturnType<Client[\"subscribeResource\"]> {\n return this.mcpClient.subscribeResource(...args);\n }\n\n /**\n * Unsubscribe from resource updates.\n * Passthrough to the underlying MCP client.\n *\n * @param args - Arguments for unsubscribeResource method\n * @returns Promise resolving when unsubscribed\n */\n async unsubscribeResource(...args: Parameters<Client[\"unsubscribeResource\"]>): ReturnType<Client[\"unsubscribeResource\"]> {\n return this.mcpClient.unsubscribeResource(...args);\n }\n\n /**\n * Ping the server.\n * Passthrough to the underlying MCP client.\n *\n * @param args - Arguments for ping method\n * @returns Promise resolving to ping response\n */\n async ping(...args: Parameters<Client[\"ping\"]>): ReturnType<Client[\"ping\"]> {\n return this.mcpClient.ping(...args);\n }\n\n /**\n * Request completion suggestions.\n * Passthrough to the underlying MCP client.\n *\n * @param args - Arguments for complete method\n * @returns Promise resolving to completion suggestions\n */\n async complete(...args: Parameters<Client[\"complete\"]>): ReturnType<Client[\"complete\"]> {\n return this.mcpClient.complete(...args);\n }\n\n /**\n * Set the logging level on the server.\n * Passthrough to the underlying MCP client.\n *\n * @param args - Arguments for setLoggingLevel method\n * @returns Promise resolving when level is set\n */\n async setLoggingLevel(...args: Parameters<Client[\"setLoggingLevel\"]>): ReturnType<Client[\"setLoggingLevel\"]> {\n return this.mcpClient.setLoggingLevel(...args);\n }\n\n /**\n * Get server capabilities after initialization.\n * Passthrough to the underlying MCP client.\n *\n * @returns Server capabilities or undefined if not initialized\n */\n getServerCapabilities(): ReturnType<Client[\"getServerCapabilities\"]> {\n return this.mcpClient.getServerCapabilities();\n }\n\n /**\n * Get server version information after initialization.\n * Passthrough to the underlying MCP client.\n *\n * @returns Server version info or undefined if not initialized\n */\n getServerVersion(): ReturnType<Client[\"getServerVersion\"]> {\n return this.mcpClient.getServerVersion();\n }\n\n /**\n * Get server instructions after initialization.\n * Passthrough to the underlying MCP client.\n *\n * @returns Server instructions or undefined if not initialized\n */\n getInstructions(): ReturnType<Client[\"getInstructions\"]> {\n return this.mcpClient.getInstructions();\n }\n\n /**\n * Send notification that roots list has changed.\n * Passthrough to the underlying MCP client.\n *\n * @returns Promise resolving when notification is sent\n */\n async sendRootsListChanged(): ReturnType<Client[\"sendRootsListChanged\"]> {\n return this.mcpClient.sendRootsListChanged();\n }\n\n /**\n * Register a hook to run when a 402 payment required is received.\n * Hooks run in order; first to return a result wins.\n *\n * This can be used to:\n * - Provide pre-existing payment payloads (implementation-specific, not part of x402 spec)\n * - Abort the payment flow for certain tools\n * - Log or track payment required events\n *\n * Note: Payment caching is an implementation pattern and not defined in the x402 MCP\n * transport specification. Implementations that cache payments should ensure cached\n * payloads are still valid (not expired, correct nonce, etc.).\n *\n * @param hook - Hook function\n * @returns This instance for chaining\n *\n * @example\n * ```typescript\n * // Example: Custom payment handling (implementation-specific)\n * client.onPaymentRequired(async ({ toolName, paymentRequired }) => {\n * // Custom logic to provide a payment or abort\n * if (shouldAbort(toolName)) {\n * return { abort: true };\n * }\n * // Return undefined to proceed with normal payment flow\n * });\n * ```\n */\n onPaymentRequired(hook: PaymentRequiredHook): this {\n this.paymentRequiredHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to run before payment is created.\n *\n * @param hook - Hook function\n * @returns This instance for chaining\n */\n onBeforePayment(hook: BeforePaymentHook): this {\n this.beforePaymentHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to run after payment is submitted.\n *\n * @param hook - Hook function\n * @returns This instance for chaining\n */\n onAfterPayment(hook: AfterPaymentHook): this {\n this.afterPaymentHooks.push(hook);\n return this;\n }\n\n /**\n * Calls a tool, automatically handling 402 payment required errors.\n *\n * If the tool returns a 402 error and autoPayment is enabled, this method\n * will automatically create a payment payload and retry the tool call.\n *\n * @param name - The name of the tool to call\n * @param args - Arguments to pass to the tool\n * @param options - Optional MCP request options (timeout, signal, etc.)\n * @param options.timeout - Request timeout in milliseconds (default: 60000)\n * @param options.signal - AbortSignal for cancellation\n * @param options.resetTimeoutOnProgress - If true, progress notifications reset the timeout\n * @returns The tool result with payment metadata\n * @throws Error if payment is required but autoPayment is disabled and no payment provided\n * @throws Error if payment approval is denied\n * @throws Error if payment creation fails\n */\n async callTool(\n name: string,\n args: Record<string, unknown> = {},\n options?: { timeout?: number; signal?: AbortSignal; resetTimeoutOnProgress?: boolean },\n ): Promise<x402MCPToolCallResult> {\n // First attempt without payment\n const result = await this.mcpClient.callTool({ name, arguments: args }, undefined, options);\n\n // Validate result structure\n if (!isMCPCallToolResult(result)) {\n throw new Error(\"Invalid MCP tool result: missing content array\");\n }\n\n // Check if this is a payment required response (isError with payment_required in content)\n const paymentRequired = this.extractPaymentRequiredFromResult(result);\n\n if (!paymentRequired) {\n // Not a payment required response, forward original MCP response as-is\n return {\n content: result.content,\n isError: result.isError,\n paymentMade: false,\n };\n }\n\n // Payment required - run onPaymentRequired hooks first\n const paymentRequiredContext: PaymentRequiredContext = {\n toolName: name,\n arguments: args,\n paymentRequired,\n };\n\n // Run payment required hooks - first to return a result wins\n for (const hook of this.paymentRequiredHooks) {\n const hookResult = await hook(paymentRequiredContext);\n if (hookResult) {\n if (hookResult.abort) {\n throw new Error(\"Payment aborted by hook\");\n }\n if (hookResult.payment) {\n // Use the hook-provided payment\n return this.callToolWithPayment(name, args, hookResult.payment, options);\n }\n }\n }\n\n // No hook handled it, proceed with normal flow\n if (!this.options.autoPayment) {\n // Auto-payment disabled, throw with payment info\n const err = new Error(\"Payment required\") as Error & {\n code: number;\n paymentRequired: PaymentRequired;\n };\n err.code = MCP_PAYMENT_REQUIRED_CODE;\n err.paymentRequired = paymentRequired;\n throw err;\n }\n\n // Create payment requested context\n const paymentRequestedContext: PaymentRequestedContext = {\n toolName: name,\n arguments: args,\n paymentRequired,\n };\n\n // Check if payment is approved via onPaymentRequested hook\n const approved = await this.options.onPaymentRequested(paymentRequestedContext);\n if (!approved) {\n throw new Error(\"Payment request denied\");\n }\n\n // Run before payment hooks\n for (const hook of this.beforePaymentHooks) {\n await hook(paymentRequestedContext);\n }\n\n // Create payment payload\n const paymentPayload = await this._paymentClient.createPaymentPayload(paymentRequired);\n\n // Retry with payment\n return this.callToolWithPayment(name, args, paymentPayload, options);\n }\n\n /**\n * Calls a tool with an explicit payment payload.\n *\n * Use this method when you want to provide payment upfront or when\n * implementing custom payment handling.\n *\n * @param name - The name of the tool to call\n * @param args - Arguments to pass to the tool\n * @param paymentPayload - The payment payload to include\n * @param options - Optional MCP request options (timeout, signal, etc.)\n * @param options.timeout - Request timeout in milliseconds (default: 60000)\n * @param options.signal - AbortSignal for cancellation\n * @param options.resetTimeoutOnProgress - If true, progress notifications reset the timeout\n * @returns The tool result with payment metadata\n */\n async callToolWithPayment(\n name: string,\n args: Record<string, unknown>,\n paymentPayload: PaymentPayload,\n options?: { timeout?: number; signal?: AbortSignal; resetTimeoutOnProgress?: boolean },\n ): Promise<x402MCPToolCallResult> {\n // Build the call parameters with payment metadata\n // Note: The MCP SDK's callTool accepts _meta but the types don't always expose it\n const callParams = {\n name,\n arguments: args,\n _meta: {\n [MCP_PAYMENT_META_KEY]: paymentPayload,\n },\n };\n\n // Call with payment in _meta\n const result = await this.mcpClient.callTool(callParams, undefined, options);\n\n // Validate result structure\n if (!isMCPCallToolResult(result)) {\n throw new Error(\"Invalid MCP tool result: missing content array\");\n }\n\n // Build result with meta for extraction (preserve _meta if present)\n const resultWithMeta: MCPResultWithMeta = {\n content: result.content,\n isError: result.isError,\n _meta: result._meta,\n };\n\n // Extract payment response from _meta\n const paymentResponse = extractPaymentResponseFromMeta(resultWithMeta);\n\n // Run after payment hooks\n for (const hook of this.afterPaymentHooks) {\n await hook({\n toolName: name,\n paymentPayload,\n result: resultWithMeta,\n settleResponse: paymentResponse,\n });\n }\n\n // Forward original MCP response content as-is\n return {\n content: result.content,\n isError: result.isError,\n paymentResponse: paymentResponse ?? undefined,\n paymentMade: true,\n };\n }\n\n /**\n * Probes a tool to discover its payment requirements.\n *\n * **WARNING: Side Effects** - This method actually calls the tool to trigger a 402 response.\n * If the tool is free (no payment required), it will execute and return null.\n * Use with caution on tools that have side effects or are expensive to run.\n *\n * Useful for displaying pricing information to users before calling paid tools.\n *\n * @param name - The name of the tool to probe\n * @param args - Arguments that may affect pricing (for dynamic pricing scenarios)\n * @returns The payment requirements if the tool requires payment, null if the tool is free\n *\n * @example\n * ```typescript\n * // Check if a tool requires payment before calling\n * const requirements = await client.getToolPaymentRequirements(\"expensive_analysis\");\n *\n * if (requirements) {\n * const price = requirements.accepts[0];\n * console.log(`This tool costs ${price.amount} on ${price.network}`);\n * // Optionally show user and get confirmation before calling\n * } else {\n * console.log(\"This tool is free\");\n * // Note: the tool has already executed!\n * }\n * ```\n */\n async getToolPaymentRequirements(\n name: string,\n args: Record<string, unknown> = {},\n ): Promise<PaymentRequired | null> {\n // Note: This actually calls the tool to trigger 402 if paid.\n // If the tool is free, it will execute as a side effect.\n const result = await this.mcpClient.callTool({ name, arguments: args });\n\n // Validate result structure\n if (!isMCPCallToolResult(result)) {\n return null;\n }\n\n // Check if this is a payment required response\n return this.extractPaymentRequiredFromResult(result);\n }\n\n // ============================================================================\n // Private Methods\n // ============================================================================\n\n /**\n * Extracts PaymentRequired from a tool result (structured 402 response).\n *\n * Per MCP transport spec, supports:\n * 1. structuredContent with direct PaymentRequired object (optional, preferred)\n * 2. content[0].text with JSON-encoded PaymentRequired object (required)\n *\n * @param result - The tool call result\n * @returns PaymentRequired if this is a 402 response, null otherwise\n */\n private extractPaymentRequiredFromResult(result: MCPCallToolResult): PaymentRequired | null {\n // Only check if isError is true\n if (!result.isError) {\n return null;\n }\n\n if (result.structuredContent) {\n const extracted = this.extractPaymentRequiredFromObject(result.structuredContent);\n if (extracted) {\n return extracted;\n }\n }\n\n const content = result.content;\n if (content.length === 0) {\n return null;\n }\n\n const firstItem = content[0];\n if (!isMCPTextContent(firstItem)) {\n return null;\n }\n\n try {\n const parsed: unknown = JSON.parse(firstItem.text);\n if (typeof parsed === \"object\" && parsed !== null) {\n const extracted = this.extractPaymentRequiredFromObject(\n parsed as Record<string, unknown>,\n );\n if (extracted) {\n return extracted;\n }\n }\n } catch {\n // Not JSON, not our structured response\n }\n\n return null;\n }\n\n /**\n * Extracts PaymentRequired from an object.\n * Expects direct PaymentRequired format (per MCP transport spec).\n *\n * @param obj - The object to extract from\n * @returns PaymentRequired if found, null otherwise\n */\n private extractPaymentRequiredFromObject(obj: Record<string, unknown>): PaymentRequired | null {\n if (isPaymentRequired(obj)) {\n return obj as PaymentRequired;\n }\n\n return null;\n }\n\n}\n\n/**\n * Configuration for createx402MCPClient factory\n */\nexport interface x402MCPClientConfig {\n /** MCP client name */\n name: string;\n\n /** MCP client version */\n version: string;\n\n /**\n * Payment scheme registrations.\n * Each registration maps a network to its scheme client implementation.\n */\n schemes: Array<{\n network: Network;\n client: SchemeNetworkClient;\n x402Version?: number;\n }>;\n\n /**\n * Whether to automatically retry tool calls with payment on 402 errors.\n *\n * @default true\n */\n autoPayment?: boolean;\n\n /**\n * Hook called when a payment is requested.\n * Return true to proceed with payment, false to abort.\n */\n onPaymentRequested?: (context: PaymentRequestedContext) => Promise<boolean> | boolean;\n\n /**\n * Additional MCP client options\n */\n mcpClientOptions?: Record<string, unknown>;\n}\n\n/**\n * Wraps an existing MCP client with x402 payment handling.\n *\n * Use this when you already have an MCP client instance and want to add\n * payment capabilities. For a simpler setup, use createx402MCPClient instead.\n *\n * @param mcpClient - The MCP client to wrap\n * @param paymentClient - The x402 client for payment handling\n * @param options - Configuration options\n * @returns An x402MCPClient instance\n *\n * @example\n * ```typescript\n * import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\n * import { wrapMCPClientWithPayment } from \"@x402/mcp\";\n * import { x402Client } from \"@x402/core/client\";\n * import { ExactEvmScheme } from \"@x402/evm/exact/client\";\n *\n * const mcpClient = new Client({ name: \"my-agent\", version: \"1.0.0\" });\n * const paymentClient = new x402Client()\n * .register(\"eip155:84532\", new ExactEvmScheme(account));\n *\n * const x402Mcp = wrapMCPClientWithPayment(mcpClient, paymentClient, {\n * autoPayment: true,\n * });\n *\n * await x402Mcp.connect(transport);\n * const result = await x402Mcp.callTool(\"paid_tool\", { arg: \"value\" });\n * ```\n */\nexport function wrapMCPClientWithPayment(\n mcpClient: Client,\n paymentClient: x402Client,\n options?: x402MCPClientOptions,\n): x402MCPClient {\n return new x402MCPClient(mcpClient, paymentClient, options);\n}\n\n/**\n * Wraps an existing MCP client with x402 payment handling using a config object.\n *\n * Similar to wrapMCPClientWithPayment but uses a configuration object for\n * setting up the payment client, similar to the axios pattern.\n *\n * @param mcpClient - The MCP client to wrap\n * @param config - Payment client configuration\n * @param options - x402 MCP client options\n * @returns An x402MCPClient instance\n *\n * @example\n * ```typescript\n * import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\n * import { wrapMCPClientWithPaymentFromConfig } from \"@x402/mcp\";\n * import { ExactEvmScheme } from \"@x402/evm/exact/client\";\n *\n * const mcpClient = new Client({ name: \"my-agent\", version: \"1.0.0\" });\n *\n * const x402Mcp = wrapMCPClientWithPaymentFromConfig(mcpClient, {\n * schemes: [\n * { network: \"eip155:84532\", client: new ExactEvmScheme(account) },\n * ],\n * });\n *\n * await x402Mcp.connect(transport);\n * ```\n */\nexport function wrapMCPClientWithPaymentFromConfig(\n mcpClient: Client,\n config: x402ClientConfig,\n options?: x402MCPClientOptions,\n): x402MCPClient {\n const paymentClient = x402Client.fromConfig(config);\n return new x402MCPClient(mcpClient, paymentClient, options);\n}\n\n/**\n * Creates a fully configured x402 MCP client with sensible defaults.\n *\n * This factory function provides the simplest way to create an x402-enabled MCP client.\n * It handles creation of both the underlying MCP Client and x402Client, making it\n * easy to get started with paid tool calls.\n *\n * @param config - Client configuration options\n * @returns A configured x402MCPClient instance\n *\n * @example\n * ```typescript\n * import { createx402MCPClient } from \"@x402/mcp\";\n * import { ExactEvmScheme } from \"@x402/evm/exact/client\";\n * import { SSEClientTransport } from \"@modelcontextprotocol/sdk/client/sse.js\";\n *\n * const client = createx402MCPClient({\n * name: \"my-agent\",\n * version: \"1.0.0\",\n * schemes: [\n * { network: \"eip155:84532\", client: new ExactEvmScheme(account) },\n * ],\n * autoPayment: true,\n * onPaymentRequested: async ({ paymentRequired }) => {\n * console.log(`Payment required: ${paymentRequired.accepts[0].amount}`);\n * return true; // Auto-approve\n * },\n * });\n *\n * // Connect to server\n * const transport = new SSEClientTransport(new URL(\"http://localhost:4022/sse\"));\n * await client.connect(transport);\n *\n * // List available tools\n * const { tools } = await client.listTools();\n *\n * // Call a paid tool (payment handled automatically)\n * const result = await client.callTool(\"get_weather\", { city: \"NYC\" });\n * ```\n */\nexport function createx402MCPClient(config: x402MCPClientConfig): x402MCPClient {\n // Create MCP client\n const mcpClient = new Client(\n {\n name: config.name,\n version: config.version,\n },\n config.mcpClientOptions,\n );\n\n // Create x402 payment client\n const paymentClient = new x402Client();\n\n // Register schemes\n for (const scheme of config.schemes) {\n if (scheme.x402Version === 1) {\n paymentClient.registerV1(scheme.network, scheme.client);\n } else {\n paymentClient.register(scheme.network, scheme.client);\n }\n }\n\n // Create x402MCPClient with options\n return new x402MCPClient(mcpClient, paymentClient, {\n autoPayment: config.autoPayment,\n onPaymentRequested: config.onPaymentRequested,\n });\n}\n","import type { PaymentPayload, PaymentRequired, SettleResponse } from \"@x402/core/types\";\nimport {\n MCP_PAYMENT_META_KEY,\n MCP_PAYMENT_REQUIRED_CODE,\n MCP_PAYMENT_RESPONSE_META_KEY,\n type MCPPaymentRequiredError,\n type MCPRequestParamsWithMeta,\n type MCPResultWithMeta,\n} from \"../types\";\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\n/**\n * Type guard for checking if a value is a non-null object.\n * Exported for use in other modules.\n *\n * @param value - The value to check\n * @returns True if value is a non-null object\n */\nexport function isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\n/**\n * Type guard for PaymentPayload structure.\n * Only performs minimal structural validation - full validation happens in verifyPayment.\n *\n * @param value - The value to check\n * @returns True if value is a PaymentPayload structure\n */\nfunction isPaymentPayloadStructure(value: unknown): value is PaymentPayload {\n if (!isObject(value)) {\n return false;\n }\n // PaymentPayload must have x402Version and payload fields\n return \"x402Version\" in value && \"payload\" in value;\n}\n\n/**\n * Type guard for SettleResponse structure.\n *\n * @param value - The value to check\n * @returns True if value is a SettleResponse structure\n */\nfunction isSettleResponseStructure(value: unknown): value is SettleResponse {\n if (!isObject(value)) {\n return false;\n }\n return \"success\" in value;\n}\n\n/**\n * Type guard for PaymentRequired structure.\n *\n * @param value - The value to check\n * @returns True if value is a PaymentRequired structure\n */\nfunction isPaymentRequiredStructure(value: unknown): value is PaymentRequired {\n if (!isObject(value)) {\n return false;\n }\n return (\n \"x402Version\" in value &&\n \"accepts\" in value &&\n Array.isArray((value as { accepts: unknown }).accepts)\n );\n}\n\n// ============================================================================\n// Extraction Functions\n// ============================================================================\n\n/**\n * Extracts payment payload from MCP request _meta field.\n * Matches HTTP transport's simple validation approach.\n *\n * @param params - MCP request parameters that may contain _meta\n * @returns The payment payload if present and valid, null otherwise\n */\nexport function extractPaymentFromMeta(\n params: MCPRequestParamsWithMeta | undefined,\n): PaymentPayload | null {\n if (!params?._meta) {\n return null;\n }\n\n const payment = params._meta[MCP_PAYMENT_META_KEY];\n\n // Simple validation - just check it has expected structure\n // Full validation happens in verifyPayment\n if (!isPaymentPayloadStructure(payment)) {\n return null;\n }\n\n return payment;\n}\n\n/**\n * Attaches payment payload to MCP request params _meta field\n *\n * @param params - Original request params containing name and optional arguments\n * @param params.name - The tool name\n * @param params.arguments - Optional tool arguments\n * @param paymentPayload - Payment payload to attach\n * @returns New params object with payment in _meta\n */\nexport function attachPaymentToMeta(\n params: { name: string; arguments?: Record<string, unknown> },\n paymentPayload: PaymentPayload,\n): MCPRequestParamsWithMeta {\n return {\n ...params,\n _meta: {\n [MCP_PAYMENT_META_KEY]: paymentPayload,\n },\n };\n}\n\n/**\n * Extracts payment response from MCP result _meta field\n *\n * @param result - MCP result that may contain _meta\n * @returns The settlement response if present, null otherwise\n */\nexport function extractPaymentResponseFromMeta(\n result: MCPResultWithMeta | undefined,\n): SettleResponse | null {\n if (!result?._meta) {\n return null;\n }\n\n const response = result._meta[MCP_PAYMENT_RESPONSE_META_KEY];\n\n // Validate it has the required structure\n if (!isSettleResponseStructure(response)) {\n return null;\n }\n\n return response;\n}\n\n/**\n * Result content item for MCP responses\n */\ninterface ResultContentItem {\n [key: string]: unknown;\n type: string;\n}\n\n/**\n * Attaches settlement response to MCP result _meta field\n *\n * @param result - Original result object containing content and optional isError flag\n * @param result.content - The tool result content array\n * @param result.isError - Optional flag indicating if the result is an error\n * @param settleResponse - Settlement response to attach\n * @returns New result object with payment response in _meta\n */\nexport function attachPaymentResponseToMeta(\n result: { content: ResultContentItem[]; isError?: boolean },\n settleResponse: SettleResponse,\n): MCPResultWithMeta {\n return {\n ...result,\n _meta: {\n [MCP_PAYMENT_RESPONSE_META_KEY]: settleResponse,\n },\n };\n}\n\n/**\n * Creates an MCP JSON-RPC error for payment required (402)\n *\n * @param paymentRequired - The payment requirements\n * @param message - Optional custom error message\n * @returns JSON-RPC error object\n */\nexport function createPaymentRequiredError(\n paymentRequired: PaymentRequired,\n message?: string,\n): MCPPaymentRequiredError {\n return {\n code: MCP_PAYMENT_REQUIRED_CODE,\n message: message || \"Payment required\",\n data: paymentRequired,\n };\n}\n\n/**\n * Extracts PaymentRequired from an MCP JSON-RPC error\n *\n * @param error - The error object from a JSON-RPC response\n * @returns The PaymentRequired if this is a 402 error, null otherwise\n */\nexport function extractPaymentRequiredFromError(error: unknown): PaymentRequired | null {\n if (!isObject(error)) {\n return null;\n }\n\n // Check if this is a 402 payment required error\n if (error.code !== MCP_PAYMENT_REQUIRED_CODE) {\n return null;\n }\n\n // Extract and validate the data field\n const data = error.data;\n if (!isPaymentRequiredStructure(data)) {\n return null;\n }\n\n return data;\n}\n\n/**\n * Creates a resource URL for an MCP tool\n *\n * @param toolName - The name of the tool\n * @param customUrl - Optional custom URL override\n * @returns The resource URL\n */\nexport function createToolResourceUrl(toolName: string, customUrl?: string): string {\n if (customUrl) {\n return customUrl;\n }\n return `mcp://tool/${toolName}`;\n}\n","import type {\n Network,\n PaymentPayload,\n PaymentRequired,\n PaymentRequirements,\n Price,\n SettleResponse,\n} from \"@x402/core/types\";\nimport { isObject } from \"../utils/encoding\";\n\n/**\n * MCP JSON-RPC error code for payment required (x402)\n */\nexport const MCP_PAYMENT_REQUIRED_CODE = 402;\n\n/**\n * MCP _meta key for payment payload (client → server)\n */\nexport const MCP_PAYMENT_META_KEY = \"x402/payment\";\n\n/**\n * MCP _meta key for payment response (server → client)\n */\nexport const MCP_PAYMENT_RESPONSE_META_KEY = \"x402/payment-response\";\n\n/**\n * Dynamic function to resolve payTo address based on tool call context\n */\nexport type DynamicPayTo = (context: MCPToolContext) => string | Promise<string>;\n\n/**\n * Dynamic function to resolve price based on tool call context\n */\nexport type DynamicPrice = (context: MCPToolContext) => Price | Promise<Price>;\n\n/**\n * Context provided to dynamic functions and hooks during tool execution\n */\nexport interface MCPToolContext {\n /** The name of the tool being called */\n toolName: string;\n /** The arguments passed to the tool */\n arguments: Record<string, unknown>;\n /** Optional metadata from the request */\n meta?: Record<string, unknown>;\n}\n\n/**\n * Payment configuration for a paid MCP tool\n */\nexport interface MCPToolPaymentConfig {\n /** Payment scheme identifier (e.g., \"exact\") */\n scheme: string;\n\n /** Blockchain network identifier in CAIP-2 format (e.g., \"eip155:84532\") */\n network: Network;\n\n /** Price for the tool call (e.g., \"$0.10\", \"1000000\") */\n price: Price | DynamicPrice;\n\n /** Recipient wallet address or dynamic resolver */\n payTo: string | DynamicPayTo;\n\n /** Maximum time allowed for payment completion in seconds */\n maxTimeoutSeconds?: number;\n\n /** Scheme-specific additional information */\n extra?: Record<string, unknown>;\n\n /** Resource metadata for the tool */\n resource?: {\n /** Custom URL for the resource (defaults to mcp://tool/{toolName}) */\n url?: string;\n /** Human-readable description of the tool */\n description?: string;\n /** MIME type of the tool response */\n mimeType?: string;\n };\n}\n\n/**\n * Result of processing an MCP tool request for payment\n */\nexport type MCPPaymentProcessResult =\n | { type: \"no-payment-required\" }\n | {\n type: \"payment-verified\";\n paymentPayload: PaymentPayload;\n paymentRequirements: PaymentRequirements;\n }\n | {\n type: \"payment-error\";\n error: MCPPaymentError;\n };\n\n/**\n * MCP payment error structure for JSON-RPC error responses\n */\nexport interface MCPPaymentError {\n /** JSON-RPC error code (402 for payment required) */\n code: number;\n /** Human-readable error message */\n message: string;\n /** PaymentRequired data for 402 errors */\n data?: PaymentRequired;\n}\n\n/**\n * Context provided to onPaymentRequired hooks\n */\nexport interface PaymentRequiredContext {\n /** The tool name that returned 402 */\n toolName: string;\n /** The arguments that were passed to the tool */\n arguments: Record<string, unknown>;\n /** The payment requirements from the server */\n paymentRequired: PaymentRequired;\n}\n\n/**\n * Result from onPaymentRequired hook\n */\nexport interface PaymentRequiredHookResult {\n /** Custom payment payload to use instead of auto-generated */\n payment?: PaymentPayload;\n /** Skip payment and abort the call */\n abort?: boolean;\n}\n\n/**\n * Hook called when a 402 response is received, before payment processing.\n * Return payment to use that instead of auto-generating, abort: true to stop.\n * Return void/undefined to proceed with normal payment flow.\n */\nexport type PaymentRequiredHook = (\n context: PaymentRequiredContext,\n) => Promise<PaymentRequiredHookResult | void> | PaymentRequiredHookResult | void;\n\n/**\n * Options for x402MCPClient\n */\nexport interface x402MCPClientOptions {\n /**\n * Whether to automatically retry tool calls with payment on 402 errors.\n * When true (default), the client will automatically create and submit\n * payment when a 402 error is received.\n * When false, the client will throw the 402 error for manual handling.\n *\n * @default true\n */\n autoPayment?: boolean;\n\n /**\n * Hook called when a payment is requested by the server (402 response).\n * Return true to proceed with payment, false to abort.\n * Only called when autoPayment is true.\n *\n * This can be used to implement human-in-the-loop approval.\n */\n onPaymentRequested?: (context: PaymentRequestedContext) => Promise<boolean> | boolean;\n}\n\n/**\n * Context provided to payment requested hook\n */\nexport interface PaymentRequestedContext {\n /** The tool being called */\n toolName: string;\n /** The arguments passed to the tool */\n arguments: Record<string, unknown>;\n /** The payment requirements from the server */\n paymentRequired: PaymentRequired;\n}\n\n// ============================================================================\n// Server Hooks\n// ============================================================================\n\n/**\n * Context provided to server-side hooks during tool execution\n */\nexport interface ServerHookContext {\n /** The name of the tool being called */\n toolName: string;\n /** The arguments passed to the tool */\n arguments: Record<string, unknown>;\n /** The resolved payment requirements */\n paymentRequirements: PaymentRequirements;\n /** The payment payload from the client */\n paymentPayload: PaymentPayload;\n}\n\n/**\n * Hook called before tool execution (after payment verification)\n * Return false to abort execution and return a 402 error\n */\nexport type BeforeExecutionHook = (\n context: ServerHookContext,\n) => Promise<boolean | void> | boolean | void;\n\n/**\n * Context for after execution hook including the result\n */\nexport interface AfterExecutionContext extends ServerHookContext {\n /** The tool execution result */\n result: {\n content: Array<{ type: \"text\"; text: string }>;\n isError?: boolean;\n };\n}\n\n/**\n * Hook called after tool execution (before settlement)\n */\nexport type AfterExecutionHook = (context: AfterExecutionContext) => Promise<void> | void;\n\n/**\n * Context for settlement hooks\n */\nexport interface SettlementContext extends ServerHookContext {\n /** The settlement result */\n settlement: SettleResponse;\n}\n\n/**\n * Hook called after successful settlement\n */\nexport type AfterSettlementHook = (context: SettlementContext) => Promise<void> | void;\n\n/**\n * Tool content item type\n */\nexport interface ToolContentItem {\n [key: string]: unknown;\n type: string;\n text?: string;\n}\n\n/**\n * Result of a tool call that includes payment response metadata\n */\nexport interface MCPToolResultWithPayment {\n /** Standard MCP tool result content */\n content: ToolContentItem[];\n /** Whether the tool execution resulted in an error */\n isError?: boolean;\n /** Payment response metadata (settlement info) */\n paymentResponse?: SettleResponse;\n}\n\n/**\n * MCP metadata with payment\n */\nexport interface MCPMetaWithPayment {\n [key: string]: unknown;\n [MCP_PAYMENT_META_KEY]?: PaymentPayload;\n}\n\n/**\n * MCP request params with optional _meta field for payment\n */\nexport interface MCPRequestParamsWithMeta {\n /** Tool name */\n name: string;\n /** Tool arguments */\n arguments?: Record<string, unknown>;\n /** Metadata including potential payment payload */\n _meta?: MCPMetaWithPayment;\n}\n\n/**\n * MCP metadata with payment response\n */\nexport interface MCPMetaWithPaymentResponse {\n [key: string]: unknown;\n [MCP_PAYMENT_RESPONSE_META_KEY]?: SettleResponse;\n}\n\n/**\n * MCP result with optional _meta field for payment response\n */\nexport interface MCPResultWithMeta {\n /** Tool result content */\n content?: ToolContentItem[];\n /** Whether the result is an error */\n isError?: boolean;\n /** Metadata including potential payment response */\n _meta?: MCPMetaWithPaymentResponse;\n}\n\n/**\n * MCP JSON-RPC error with payment required data\n */\nexport interface MCPPaymentRequiredError {\n /** JSON-RPC error code (402) */\n code: typeof MCP_PAYMENT_REQUIRED_CODE;\n /** Error message */\n message: string;\n /** PaymentRequired data */\n data: PaymentRequired;\n}\n\n/**\n * Type guard to check if an error is a payment required error\n *\n * @param error - The error to check\n * @returns True if the error is a payment required error\n */\nexport function isPaymentRequiredError(error: unknown): error is MCPPaymentRequiredError {\n if (!isObject(error)) {\n return false;\n }\n\n if (error.code !== MCP_PAYMENT_REQUIRED_CODE || typeof error.message !== \"string\") {\n return false;\n }\n\n if (!isObject(error.data)) {\n return false;\n }\n\n return \"x402Version\" in error.data && \"accepts\" in error.data;\n}\n","/**\n * Payment wrapper for MCP tool handlers\n *\n * This module provides a functional API for adding x402 payment to MCP tool handlers.\n * Use createPaymentWrapper to wrap tool handlers with payment verification and settlement.\n */\n\nimport type { PaymentRequirements } from \"@x402/core/types\";\nimport { x402ResourceServer } from \"@x402/core/server\";\n\nimport type {\n MCPToolContext,\n BeforeExecutionHook,\n AfterExecutionHook,\n AfterSettlementHook,\n ServerHookContext,\n AfterExecutionContext,\n SettlementContext,\n} from \"../types\";\nimport { MCP_PAYMENT_RESPONSE_META_KEY } from \"../types\";\nimport { createToolResourceUrl, extractPaymentFromMeta } from \"../utils\";\n\n/**\n * Configuration for payment wrapper.\n */\nexport interface PaymentWrapperConfig {\n /**\n * Payment requirements that must be satisfied to call the tool.\n * Typically a single entry, but can support multiple payment options.\n *\n * Each requirement specifies:\n * - scheme: Payment scheme identifier (e.g., \"exact\")\n * - network: Blockchain network in CAIP-2 format (e.g., \"eip155:84532\")\n * - amount: Payment amount in token's smallest unit\n * - asset: Token contract address\n * - payTo: Recipient wallet address\n * - maxTimeoutSeconds: Payment timeout (optional)\n * - extra: Scheme-specific data (optional)\n */\n accepts: PaymentRequirements[];\n\n /** Resource metadata for the tool */\n resource?: {\n /** Custom URL for the resource (defaults to mcp://tool/{toolName}) */\n url?: string;\n /** Human-readable description of the tool */\n description?: string;\n /** MIME type of the tool response */\n mimeType?: string;\n };\n\n /** Hooks for payment lifecycle events */\n hooks?: {\n /** Called after payment verification, before tool execution. Return false to abort. */\n onBeforeExecution?: BeforeExecutionHook;\n /** Called after tool execution, before settlement */\n onAfterExecution?: AfterExecutionHook;\n /** Called after successful settlement */\n onAfterSettlement?: AfterSettlementHook;\n };\n}\n\n/**\n * Result type for wrapped tool handlers.\n * Matches the MCP SDK's expected tool result format with optional _meta.\n */\nexport interface WrappedToolResult {\n [key: string]: unknown;\n content: Array<{ type: \"text\"; text: string }>;\n isError?: boolean;\n _meta?: Record<string, unknown>;\n structuredContent?: Record<string, unknown>;\n}\n\n/**\n * Tool result type without payment metadata\n */\nexport interface ToolResult {\n [key: string]: unknown;\n content: Array<{ type: \"text\"; text: string }>;\n isError?: boolean;\n}\n\n/**\n * Handler function type for tools to be wrapped with payment.\n */\nexport type PaymentWrappedHandler<TArgs = Record<string, unknown>> = (\n args: TArgs,\n context: MCPToolContext,\n) => Promise<ToolResult> | ToolResult;\n\n/**\n * MCP SDK compatible tool callback type.\n * This type matches the signature expected by McpServer.tool() for tools with arguments.\n * The extra parameter contains _meta and other request context from the MCP SDK.\n */\nexport type MCPToolCallback<TArgs = Record<string, unknown>> = (\n args: TArgs,\n extra: unknown,\n) => WrappedToolResult | Promise<WrappedToolResult>;\n\n/**\n * Creates a reusable payment wrapper for adding x402 payment to MCP tool handlers.\n *\n * This is the primary API for integrating x402 payments with MCP servers.\n * Use this when you have an existing McpServer and want to add payment to specific tools.\n *\n * @param resourceServer - The x402 resource server for payment verification/settlement\n * @param config - Payment configuration with accepts array\n * @returns A function that wraps tool handlers with payment logic\n *\n * @example\n * ```typescript\n * // Build payment requirements using resource server\n * const accepts = await resourceServer.buildPaymentRequirements({\n * scheme: \"exact\",\n * network: \"eip155:84532\",\n * payTo: \"0xRecipient\",\n * price: \"$0.10\",\n * });\n *\n * // Create wrapper with payment requirements\n * const paid = createPaymentWrapper(resourceServer, {\n * accepts,\n * hooks: {\n * onBeforeExecution: async ({ paymentPayload }) => {\n * if (await isRateLimited(paymentPayload.payer)) return false;\n * },\n * onAfterSettlement: async ({ settlement }) => {\n * await sendReceipt(settlement.transaction);\n * },\n * },\n * });\n *\n * // Use with McpServer.tool()\n * mcpServer.tool(\"search\", \"Premium search ($0.10)\", { query: z.string() },\n * paid(async (args) => ({\n * content: [{ type: \"text\", text: \"Search results...\" }]\n * }))\n * );\n * ```\n */\nexport function createPaymentWrapper(\n resourceServer: x402ResourceServer,\n config: PaymentWrapperConfig,\n): <TArgs extends Record<string, unknown>>(\n handler: PaymentWrappedHandler<TArgs>,\n) => MCPToolCallback<TArgs> {\n // Validate accepts array\n if (!config.accepts || config.accepts.length === 0) {\n throw new Error(\"PaymentWrapperConfig.accepts must have at least one payment requirement\");\n }\n\n // Return wrapper function that takes only the handler\n return <TArgs extends Record<string, unknown>>(\n handler: PaymentWrappedHandler<TArgs>,\n ): MCPToolCallback<TArgs> => {\n return async (args: TArgs, extra: unknown): Promise<WrappedToolResult> => {\n // Extract _meta from extra if it's an object\n const _meta = (extra as { _meta?: Record<string, unknown> })?._meta;\n // Derive toolName from resource URL if available, otherwise use placeholder\n const toolName = config.resource?.url?.replace(\"mcp://tool/\", \"\") || \"paid_tool\";\n\n const context: MCPToolContext = {\n toolName,\n arguments: args,\n meta: _meta,\n };\n\n // Extract payment from _meta if present\n const paymentPayload = extractPaymentFromMeta({\n name: toolName,\n arguments: args,\n _meta,\n });\n\n // Use first payment requirement (typically only one)\n const paymentRequirements = config.accepts[0];\n\n // If no payment provided, return 402 error\n if (!paymentPayload) {\n return createPaymentRequiredResult(\n resourceServer,\n toolName,\n config,\n \"Payment required to access this tool\",\n );\n }\n\n // Verify payment\n const verifyResult = await resourceServer.verifyPayment(paymentPayload, paymentRequirements);\n\n if (!verifyResult.isValid) {\n return createPaymentRequiredResult(\n resourceServer,\n toolName,\n config,\n verifyResult.invalidReason || \"Payment verification failed\",\n );\n }\n\n // Build hook context\n const hookContext: ServerHookContext = {\n toolName,\n arguments: args,\n paymentRequirements,\n paymentPayload,\n };\n\n // Run onBeforeExecution hook if present\n if (config.hooks?.onBeforeExecution) {\n const hookResult = await config.hooks.onBeforeExecution(hookContext);\n if (hookResult === false) {\n return createPaymentRequiredResult(\n resourceServer,\n toolName,\n config,\n \"Execution blocked by hook\",\n );\n }\n }\n\n // Execute the tool handler\n const result = await handler(args, context);\n\n // Build after execution context\n const afterExecContext: AfterExecutionContext = {\n ...hookContext,\n result,\n };\n\n // Run onAfterExecution hook if present\n if (config.hooks?.onAfterExecution) {\n await config.hooks.onAfterExecution(afterExecContext);\n }\n\n // If the tool handler returned an error, don't proceed to settlement\n if (result.isError) {\n return result;\n }\n\n // Settle the payment\n try {\n const settleResult = await resourceServer.settlePayment(\n paymentPayload,\n paymentRequirements,\n );\n\n // Run onAfterSettlement hook if present\n if (config.hooks?.onAfterSettlement) {\n const settlementContext: SettlementContext = {\n ...hookContext,\n settlement: settleResult,\n };\n await config.hooks.onAfterSettlement(settlementContext);\n }\n\n // Return result with payment response in _meta\n return {\n content: result.content,\n isError: result.isError,\n _meta: {\n [MCP_PAYMENT_RESPONSE_META_KEY]: settleResult,\n },\n };\n } catch (settleError) {\n // Settlement failed after execution - return 402 error\n return createSettlementFailedResult(\n resourceServer,\n toolName,\n config,\n settleError instanceof Error ? settleError.message : \"Settlement failed\",\n );\n }\n };\n };\n}\n\n/**\n * Helper to create 402 payment required result from wrapper config.\n *\n * @param resourceServer - The x402 resource server for creating payment required response\n * @param toolName - Name of the tool for resource URL\n * @param config - Payment wrapper configuration\n * @param errorMessage - Error message describing why payment is required\n * @returns Promise resolving to structured 402 error result with payment requirements\n */\nasync function createPaymentRequiredResult(\n resourceServer: x402ResourceServer,\n toolName: string,\n config: PaymentWrapperConfig,\n errorMessage: string,\n): Promise<WrappedToolResult> {\n const resourceInfo = {\n url: createToolResourceUrl(toolName, config.resource?.url),\n description: config.resource?.description || `Tool: ${toolName}`,\n mimeType: config.resource?.mimeType || \"application/json\",\n };\n\n const paymentRequired = await resourceServer.createPaymentRequiredResponse(\n config.accepts,\n resourceInfo,\n errorMessage,\n );\n\n return {\n structuredContent: paymentRequired as unknown as Record<string, unknown>,\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(paymentRequired),\n },\n ],\n isError: true,\n };\n}\n\n/**\n * Helper to create 402 settlement failed result from wrapper config.\n *\n * @param resourceServer - The x402 resource server for creating error response\n * @param toolName - Name of the tool for resource URL\n * @param config - Payment wrapper configuration\n * @param errorMessage - Error message describing the settlement failure\n * @returns Promise resolving to structured 402 error result with settlement failure info\n */\nasync function createSettlementFailedResult(\n resourceServer: x402ResourceServer,\n toolName: string,\n config: PaymentWrapperConfig,\n errorMessage: string,\n): Promise<WrappedToolResult> {\n const resourceInfo = {\n url: createToolResourceUrl(toolName, config.resource?.url),\n description: config.resource?.description || `Tool: ${toolName}`,\n mimeType: config.resource?.mimeType || \"application/json\",\n };\n\n const paymentRequired = await resourceServer.createPaymentRequiredResponse(\n config.accepts,\n resourceInfo,\n `Payment settlement failed: ${errorMessage}`,\n );\n\n const settlementFailure = {\n success: false,\n errorReason: errorMessage,\n transaction: \"\",\n network: config.accepts[0].network,\n };\n\n const errorData = {\n ...paymentRequired,\n [MCP_PAYMENT_RESPONSE_META_KEY]: settlementFailure,\n };\n\n return {\n structuredContent: errorData as unknown as Record<string, unknown>,\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(errorData),\n },\n ],\n isError: true,\n };\n}\n","// @x402/mcp - MCP (Model Context Protocol) integration for x402 payment protocol\n//\n// This package provides MCP-native payment handling for AI agents and MCP servers.\n// It enables paid tool calls following the x402 protocol over MCP transport.\n\n// Client exports\nexport {\n x402MCPClient,\n createx402MCPClient,\n wrapMCPClientWithPayment,\n wrapMCPClientWithPaymentFromConfig,\n} from \"./client\";\nexport type {\n BeforePaymentHook,\n AfterPaymentHook,\n x402MCPToolCallResult,\n x402MCPClientConfig,\n MCPContentItem,\n} from \"./client\";\n\n// Server exports\nexport { createPaymentWrapper } from \"./server\";\nexport type {\n PaymentWrapperConfig,\n PaymentWrappedHandler,\n WrappedToolResult,\n ToolResult,\n MCPToolCallback,\n} from \"./server\";\n\n// Type exports\nexport {\n MCP_PAYMENT_REQUIRED_CODE,\n MCP_PAYMENT_META_KEY,\n MCP_PAYMENT_RESPONSE_META_KEY,\n isPaymentRequiredError,\n} from \"./types\";\nexport type {\n // Core MCP types\n MCPToolContext,\n MCPToolPaymentConfig,\n MCPPaymentProcessResult,\n MCPPaymentError,\n x402MCPClientOptions,\n PaymentRequestedContext,\n MCPToolResultWithPayment,\n MCPRequestParamsWithMeta,\n MCPResultWithMeta,\n MCPPaymentRequiredError,\n DynamicPayTo,\n DynamicPrice,\n ToolContentItem,\n // Server hook types\n ServerHookContext,\n BeforeExecutionHook,\n AfterExecutionContext,\n AfterExecutionHook,\n SettlementContext,\n AfterSettlementHook,\n // Client hook types\n PaymentRequiredContext,\n PaymentRequiredHookResult,\n PaymentRequiredHook,\n} from \"./types\";\n\n// Utility exports\nexport {\n extractPaymentFromMeta,\n attachPaymentToMeta,\n extractPaymentResponseFromMeta,\n attachPaymentResponseToMeta,\n createPaymentRequiredError,\n extractPaymentRequiredFromError,\n createToolResourceUrl,\n} from \"./utils\";\n\n// ============================================================================\n// Convenience Re-exports from @x402/core\n// ============================================================================\n// These re-exports provide common types and classes that MCP users frequently need,\n// reducing the number of separate package imports required.\n\nexport { x402Client } from \"@x402/core/client\";\nexport type { x402ClientConfig, SelectPaymentRequirements, PaymentPolicy } from \"@x402/core/client\";\n\nexport { x402ResourceServer } from \"@x402/core/server\";\n\nexport type {\n PaymentPayload,\n PaymentRequired,\n PaymentRequirements,\n SettleResponse,\n Network,\n SchemeNetworkClient,\n SchemeNetworkServer,\n} from \"@x402/core/types\";\n"],"mappings":";AAOA,SAAS,yBAAyB;AAClC,SAAS,kBAAkB;AAE3B,SAAS,cAAc;;;ACWhB,SAAS,SAAS,OAAkD;AACzE,SAAO,OAAO,UAAU,YAAY,UAAU;AAChD;AASA,SAAS,0BAA0B,OAAyC;AAC1E,MAAI,CAAC,SAAS,KAAK,GAAG;AACpB,WAAO;AAAA,EACT;AAEA,SAAO,iBAAiB,SAAS,aAAa;AAChD;AAQA,SAAS,0BAA0B,OAAyC;AAC1E,MAAI,CAAC,SAAS,KAAK,GAAG;AACpB,WAAO;AAAA,EACT;AACA,SAAO,aAAa;AACtB;AAQA,SAAS,2BAA2B,OAA0C;AAC5E,MAAI,CAAC,SAAS,KAAK,GAAG;AACpB,WAAO;AAAA,EACT;AACA,SACE,iBAAiB,SACjB,aAAa,SACb,MAAM,QAAS,MAA+B,OAAO;AAEzD;AAaO,SAAS,uBACd,QACuB;AACvB,MAAI,EAAC,iCAAQ,QAAO;AAClB,WAAO;AAAA,EACT;AAEA,QAAM,UAAU,OAAO,MAAM,oBAAoB;AAIjD,MAAI,CAAC,0BAA0B,OAAO,GAAG;AACvC,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAWO,SAAS,oBACd,QACA,gBAC0B;AAC1B,SAAO;AAAA,IACL,GAAG;AAAA,IACH,OAAO;AAAA,MACL,CAAC,oBAAoB,GAAG;AAAA,IAC1B;AAAA,EACF;AACF;AAQO,SAAS,+BACd,QACuB;AACvB,MAAI,EAAC,iCAAQ,QAAO;AAClB,WAAO;AAAA,EACT;AAEA,QAAM,WAAW,OAAO,MAAM,6BAA6B;AAG3D,MAAI,CAAC,0BAA0B,QAAQ,GAAG;AACxC,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAmBO,SAAS,4BACd,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,aAAa;AAAA,IACb,SAAS,OAAO,QAAQ,CAAC,EAAE;AAAA,EAC7B;AAEA,QAAM,YAAY;AAAA,IAChB,GAAG;AAAA,IACH,CAAC,6BAA6B,GAAG;AAAA,EACnC;AAEA,SAAO;AAAA,IACL,mBAAmB;AAAA,IACnB,SAAS;AAAA,MACP;AAAA,QACE,MAAM;AAAA,QACN,MAAM,KAAK,UAAU,SAAS;AAAA,MAChC;AAAA,IACF;AAAA,IACA,SAAS;AAAA,EACX;AACF;;;AC5RA,SAAS,cAAAA,mBAAkB;AAG3B,SAAS,0BAA0B;","names":["x402Client"]}
package/package.json ADDED
@@ -0,0 +1,64 @@
1
+ {
2
+ "name": "@x402/mcp",
3
+ "version": "2.3.0-alpha",
4
+ "main": "./dist/cjs/index.js",
5
+ "module": "./dist/esm/index.js",
6
+ "types": "./dist/cjs/index.d.ts",
7
+ "keywords": [],
8
+ "license": "Apache-2.0",
9
+ "author": "Coinbase Inc.",
10
+ "repository": "https://github.com/coinbase/x402",
11
+ "description": "x402 Payment Protocol",
12
+ "devDependencies": {
13
+ "@eslint/js": "^9.24.0",
14
+ "@types/node": "^22.13.4",
15
+ "@typescript-eslint/eslint-plugin": "^8.29.1",
16
+ "@typescript-eslint/parser": "^8.29.1",
17
+ "eslint": "^9.24.0",
18
+ "eslint-plugin-import": "^2.31.0",
19
+ "eslint-plugin-jsdoc": "^50.6.9",
20
+ "eslint-plugin-prettier": "^5.2.6",
21
+ "express": "^4.21.2",
22
+ "prettier": "3.5.2",
23
+ "tsup": "^8.4.0",
24
+ "tsx": "^4.19.2",
25
+ "typescript": "^5.7.3",
26
+ "viem": "^2.27.2",
27
+ "vite-tsconfig-paths": "^5.1.4",
28
+ "vitest": "^3.0.5",
29
+ "vite": "^6.2.6",
30
+ "@x402/evm": "~2.3.0"
31
+ },
32
+ "dependencies": {
33
+ "@modelcontextprotocol/sdk": "^1.12.1",
34
+ "zod": "^3.24.2",
35
+ "@x402/core": "~2.3.0"
36
+ },
37
+ "exports": {
38
+ ".": {
39
+ "import": {
40
+ "types": "./dist/esm/index.d.mts",
41
+ "default": "./dist/esm/index.mjs"
42
+ },
43
+ "require": {
44
+ "types": "./dist/cjs/index.d.ts",
45
+ "default": "./dist/cjs/index.js"
46
+ }
47
+ }
48
+ },
49
+ "files": [
50
+ "dist"
51
+ ],
52
+ "scripts": {
53
+ "start": "tsx --env-file=.env index.ts",
54
+ "test": "vitest run",
55
+ "test:integration": "vitest run --dir test/integration",
56
+ "test:watch": "vitest",
57
+ "build": "tsup",
58
+ "watch": "tsc --watch",
59
+ "format": "prettier -c .prettierrc --write \"**/*.{ts,js,cjs,json,md}\"",
60
+ "format:check": "prettier -c .prettierrc --check \"**/*.{ts,js,cjs,json,md}\"",
61
+ "lint": "eslint . --ext .ts --fix",
62
+ "lint:check": "eslint . --ext .ts"
63
+ }
64
+ }