mcp
import "github.com/x402-foundation/x402/go/v2/mcp"
Package mcp provides MCP (Model Context Protocol) transport integration for the x402 payment protocol.
This package enables paid tool calls in MCP servers and automatic payment handling in MCP clients.
Client Usage
Wrap an MCP session with payment handling:
import (
"context"
"github.com/x402-foundation/x402/go/v2/mcp"
mcpsdk "github.com/modelcontextprotocol/go-sdk/mcp"
)
// Connect to MCP server using the official SDK
mcpClient := mcpsdk.NewClient(&mcpsdk.Implementation{Name: "my-agent", Version: "1.0.0"}, nil)
session, _ := mcpClient.Connect(ctx, transport, nil)
// Wrap session with x402 (AutoPayment defaults to true)
x402Mcp := mcp.NewX402MCPClientFromConfig(session, []mcp.SchemeRegistration{
{Network: "eip155:84532", Client: evmClientScheme},
}, mcp.Options{})
// Call tools - payment handled automatically
result, err := x402Mcp.CallTool(ctx, "get_weather", map[string]interface{}{"city": "NYC"})Server Usage
Wrap tool handlers with payment:
import (
"context"
x402 "github.com/x402-foundation/x402/go/v2"
"github.com/x402-foundation/x402/go/v2/mcp"
)
// Create resource server
resourceServer := x402.Newx402ResourceServer(facilitatorClient)
resourceServer.Register("eip155:84532", evmServerScheme)
// Build payment requirements
accepts, _ := resourceServer.BuildPaymentRequirements(ctx, config)
// Create payment wrapper
wrapper := mcp.NewPaymentWrapper(resourceServer, mcp.PaymentWrapperConfig{
Accepts: accepts,
})
// Register paid tool
mcpServer.AddTool(tool, wrapper.Wrap(func(ctx context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: "result"}}}, nil
}))Factory Functions
NewX402MCPClientFromConfig creates a client with scheme registrations:
x402Mcp := mcp.NewX402MCPClientFromConfig(session, []mcp.SchemeRegistration{
{Network: "eip155:84532", Client: evmClientScheme},
}, mcp.Options{})Convenience Re-exports
This package re-exports commonly used types from the x402 core package for convenience:
import "github.com/x402-foundation/x402/go/v2/mcp"
// Re-exported types available:
// - x402.X402Client (via x402 package)
// - x402.X402ResourceServer (via x402 package)
// - types.PaymentPayload, types.PaymentRequired, types.PaymentRequirements (via types package)Package mcp provides MCP (Model Context Protocol) integration for x402.
Server-side: Use NewPaymentWrapper to wrap MCP tool handlers with automatic x402 payment verification and settlement.
Client-side: Use CallPaidTool to make MCP tool calls with automatic x402 payment handling.
Constants
MCP meta key constants for x402 payment protocol.
const (
// PaymentMetaKey is the _meta key for sending payment payloads (client -> server).
PaymentMetaKey = "x402/payment"
// PaymentResponseMetaKey is the _meta key for settlement responses (server -> client).
PaymentResponseMetaKey = "x402/payment-response"
)Protocol constants for MCP x402 payment integration.
const (
// MCP_PAYMENT_REQUIRED_CODE is the JSON-RPC error code for payment required (x402)
MCP_PAYMENT_REQUIRED_CODE = 402
// MCP_PAYMENT_META_KEY is the MCP _meta key for payment payload (client → server)
MCP_PAYMENT_META_KEY = "x402/payment"
// MCP_PAYMENT_RESPONSE_META_KEY is the MCP _meta key for payment response (server → client)
MCP_PAYMENT_RESPONSE_META_KEY = "x402/payment-response"
)Functions
func AttachPaymentResponseToMeta(result MCPToolResult, response x402.SettleResponse) MCPToolResult
AttachPaymentResponseToMeta attaches settlement response to result
func AttachPaymentToMeta(params map[string]interface{}, payload types.PaymentPayload) map[string]interface{}
AttachPaymentToMeta attaches payment payload to request params
func BoolPtr(b bool) *bool
BoolPtr returns a pointer to the given bool value. This is a convenience helper for setting Options.AutoPayment.
Example:
options := mcp.Options{AutoPayment: mcp.BoolPtr(false)}func CallPaidTool( ctx context.Context, mcpClient MCPCaller, x402Client *x402.X402Client, name string, args map[string]any, ) (*ToolCallResult, error)
CallPaidTool makes an MCP tool call with automatic x402 payment handling.
Flow:
- Calls the tool without payment
- If the server returns a payment required error, creates a payment
- Retries with payment attached in _meta
- Returns the result with payment response extracted
Example:
result, err := mcp402.CallPaidTool(ctx, session, x402Client, "get_weather", map[string]any{"city": "SF"})
if err != nil {
log.Fatal(err)
}
fmt.Println(result.PaymentResponse.Transaction)func CreatePaymentRequiredError(message string, paymentRequired *types.PaymentRequired) *PaymentRequiredError
CreatePaymentRequiredError creates a PaymentRequiredError with the given message and payment required data.
Example:
err := mcp.CreatePaymentRequiredError("Payment required", &paymentRequired)
return nil, errfunc CreateToolResourceUrl(toolName string, customUrl string) string
CreateToolResourceUrl creates a resource URL for an MCP tool
func ExtractPaymentFromMeta(params map[string]interface{}) (*types.PaymentPayload, error)
ExtractPaymentFromMeta extracts payment payload from MCP request _meta field
func ExtractPaymentRequiredFromError(err interface{}) (*types.PaymentRequired, error)
ExtractPaymentRequiredFromError extracts PaymentRequired from an MCP JSON-RPC error.
This function checks if the error is a 402 payment required error and extracts the PaymentRequired data from the error's data field.
Example:
err := client.CallTool(ctx, "tool", args)
if pr := mcp.ExtractPaymentRequiredFromError(err); pr != nil {
// Handle payment required
}func ExtractPaymentRequiredFromResult(result MCPToolResult) (*types.PaymentRequired, error)
ExtractPaymentRequiredFromResult extracts PaymentRequired from tool result (dual format)
func ExtractPaymentResponseFromMeta(result MCPToolResult) (*x402.SettleResponse, error)
ExtractPaymentResponseFromMeta extracts settlement response from MCP result _meta
func IsObject(value interface{}) bool
IsObject checks if a value is a non-null object (map[string]interface{}).
Example:
if mcp.IsObject(value) {
obj := value.(map[string]interface{})
// Use obj
}func IsPaymentRequiredError(err error) bool
IsPaymentRequiredError checks if an error is a PaymentRequiredError.
Example:
err := client.CallTool(ctx, "tool", args)
if mcp.IsPaymentRequiredError(err) {
var paymentErr *mcp.PaymentRequiredError
errors.As(err, &paymentErr)
// Handle payment required
}func NewPaymentWrapper(server *x402.X402ResourceServer, config PaymentWrapperConfig) *PaymentWrapper
NewPaymentWrapper creates a new payment wrapper for MCP tool handlers.
Example:
wrapper := mcp402.NewPaymentWrapper(resourceServer, mcp402.PaymentWrapperConfig{
Accepts: weatherAccepts,
Resource: &types.ResourceInfo{URL: "mcp://tool/get_weather", Description: "Get weather"},
})
wrappedHandler := wrapper.Wrap(func(ctx context.Context, request *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
// extract args from request.Params.Arguments
return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: "result"}}}, nil
})func NewX402MCPClient(caller MCPCaller, paymentClient *x402.X402Client, options Options) *X402MCPClient
NewX402MCPClient creates an x402-aware MCP client.
func NewX402MCPClientFromConfig(caller MCPCaller, schemes []SchemeRegistration, options Options) *X402MCPClient
NewX402MCPClientFromConfig creates an x402-aware MCP client from scheme registrations.
Types
type AfterExecutionContext
AfterExecutionContext extends ServerHookContext with result
type AfterExecutionContext struct {
ServerHookContext
Result MCPToolResult
}Fields
ServerHookContextResult MCPToolResult
type AfterExecutionHook
AfterExecutionHook is called after tool execution
type AfterExecutionHook func(context AfterExecutionContext) errortype AfterPaymentContext
AfterPaymentContext is provided to after payment hooks
type AfterPaymentContext struct {
ToolName string
PaymentPayload types.PaymentPayload
Result MCPToolResult
SettleResponse *x402.SettleResponse
}Fields
ToolName stringPaymentPayload types.PaymentPayloadResult MCPToolResultSettleResponse *x402.SettleResponse
type AfterPaymentHook
AfterPaymentHook is called after payment is submitted
type AfterPaymentHook func(context AfterPaymentContext) errortype AfterSettlementHook
AfterSettlementHook is called after successful settlement
type AfterSettlementHook func(context SettlementContext) errortype BeforeExecutionHook
BeforeExecutionHook is called before tool execution (can abort)
type BeforeExecutionHook func(context ServerHookContext) (bool, error)type BeforePaymentHook
BeforePaymentHook is called before payment is created
type BeforePaymentHook func(context PaymentRequiredContext) errortype DynamicPayTo
DynamicPayTo resolves a payTo address dynamically based on tool call context. Use this type for custom server implementations that need per-request recipient resolution.
type DynamicPayTo func(context MCPToolContext) (string, error)type DynamicPrice
DynamicPrice resolves a price dynamically based on tool call context. Use this type for custom server implementations that need per-request pricing.
type DynamicPrice func(context MCPToolContext) (x402.Price, error)type MCPCaller
MCPCaller is the interface for making MCP tool calls. This is satisfied by the official MCP SDK's *mcp.ClientSession.
type MCPCaller interface {
CallTool(ctx context.Context, params *mcp.CallToolParams) (*mcp.CallToolResult, error)
}Methods
CallTool func(ctx context.Context, params *mcp.CallToolParams) (*mcp.CallToolResult, error)
type MCPContentItem
MCPContentItem represents an MCP content item
type MCPContentItem struct {
Type string
Text string
}Fields
Type stringText string
type MCPToolCallResult
MCPToolCallResult represents the result of a tool call with payment metadata
type MCPToolCallResult struct {
Content []MCPContentItem
IsError bool
PaymentResponse *x402.SettleResponse
PaymentMade bool
}Fields
Content []MCPContentItemIsError boolPaymentResponse *x402.SettleResponsePaymentMade bool
type MCPToolContext
MCPToolContext provides context during tool execution
type MCPToolContext struct {
ToolName string
Arguments map[string]interface{}
Meta map[string]interface{}
}Fields
ToolName stringArguments map[string]interface{}Meta map[string]interface{}
type MCPToolResult
MCPToolResult represents an MCP tool call result
type MCPToolResult struct {
Content []MCPContentItem
IsError bool
Meta map[string]interface{}
StructuredContent map[string]interface{}
}Fields
Content []MCPContentItemIsError boolMeta map[string]interface{}StructuredContent map[string]interface{}
type Options
Options configures x402MCPClient behavior
type Options struct {
// AutoPayment enables automatic payment handling when a tool requires payment.
// Defaults to true. When nil, defaults to true. Set to BoolPtr(false) to disable.
AutoPayment *bool
// OnPaymentRequested is called before creating a payment, allowing the caller
// to approve or deny. Return (true, nil) to approve, (false, nil) to deny.
OnPaymentRequested func(context PaymentRequiredContext) (bool, error)
}Fields
AutoPayment *boolAutoPayment enables automatic payment handling when a tool requires payment. Defaults to true. When nil, defaults to true. Set to BoolPtr(false) to disable.
OnPaymentRequested func(context PaymentRequiredContext) (bool, error)OnPaymentRequested is called before creating a payment, allowing the caller to approve or deny. Return (true, nil) to approve, (false, nil) to deny.
type PaymentRequiredContext
PaymentRequiredContext is provided to onPaymentRequired hooks
type PaymentRequiredContext struct {
ToolName string
Arguments map[string]interface{}
PaymentRequired types.PaymentRequired
}Fields
ToolName stringArguments map[string]interface{}PaymentRequired types.PaymentRequired
type PaymentRequiredError
PaymentRequiredError represents a payment required error
type PaymentRequiredError struct {
Code int
Message string
PaymentRequired *types.PaymentRequired
}Fields
Code intMessage stringPaymentRequired *types.PaymentRequired
func Error) Error() string
type PaymentRequiredHook
PaymentRequiredHook is called when a 402 response is received
type PaymentRequiredHook func(context PaymentRequiredContext) (*PaymentRequiredHookResult, error)type PaymentRequiredHookResult
PaymentRequiredHookResult is returned from payment required hooks
type PaymentRequiredHookResult struct {
Payment *types.PaymentPayload
Abort bool
}Fields
Payment *types.PaymentPayloadAbort bool
type PaymentWrapper
PaymentWrapper wraps MCP tool handlers with x402 payment verification and settlement.
type PaymentWrapper struct {
// contains filtered or unexported fields
}func Wrapper) Wrap(handler ToolHandler) ToolHandler
Wrap wraps a tool handler with x402 payment verification and settlement. The returned handler can be used directly with mcpServer.AddTool().
Flow:
- Extracts x402/payment from request _meta
- If no payment, returns 402 payment required error
- Verifies payment via facilitator
- OnBeforeExecution hook (if configured)
- Executes the original handler
- OnAfterExecution hook (if configured)
- Settles payment via facilitator
- OnAfterSettlement hook (if configured)
- Returns result with settlement info in _meta
type PaymentWrapperConfig
PaymentWrapperConfig configures payment wrapper behavior
type PaymentWrapperConfig struct {
Accepts []types.PaymentRequirements
Resource *ResourceInfo
Hooks *PaymentWrapperHooks
Extensions map[string]interface{}
}Fields
Accepts []types.PaymentRequirementsResource *ResourceInfoHooks *PaymentWrapperHooksExtensions map[string]interface{}
type PaymentWrapperHooks
PaymentWrapperHooks provides server-side hooks
type PaymentWrapperHooks struct {
OnBeforeExecution *BeforeExecutionHook
OnAfterExecution *AfterExecutionHook
OnAfterSettlement *AfterSettlementHook
}Fields
OnBeforeExecution *BeforeExecutionHookOnAfterExecution *AfterExecutionHookOnAfterSettlement *AfterSettlementHook
type ResourceInfo
ResourceInfo provides resource metadata. Alias for types.ResourceInfo for compatibility.
type ResourceInfo = types.ResourceInfotype SchemeRegistration
SchemeRegistration represents a payment scheme registration
type SchemeRegistration struct {
Network x402.Network
Client x402.SchemeNetworkClient
ClientV1 x402.SchemeNetworkClientV1
X402Version int // 1 or 2 (defaults to 2)
}Fields
Network x402.NetworkClient x402.SchemeNetworkClientClientV1 x402.SchemeNetworkClientV1X402Version int1 or 2 (defaults to 2)
type ServerHookContext
ServerHookContext is provided to server-side hooks
type ServerHookContext struct {
ToolName string
Arguments map[string]interface{}
PaymentRequirements types.PaymentRequirements
PaymentPayload types.PaymentPayload
}Fields
ToolName stringArguments map[string]interface{}PaymentRequirements types.PaymentRequirementsPaymentPayload types.PaymentPayload
type SettlementContext
SettlementContext extends ServerHookContext with settlement
type SettlementContext struct {
ServerHookContext
Settlement x402.SettleResponse
}Fields
ServerHookContextSettlement x402.SettleResponse
type ToolCallResult
ToolCallResult is the result of a paid MCP tool call.
type ToolCallResult struct {
// Content is the list of content items from the tool response.
Content []mcp.Content
// IsError indicates whether the tool returned an error.
IsError bool
// PaymentResponse is the settlement response if payment was made.
PaymentResponse *x402.SettleResponse
// PaymentMade indicates whether a payment was made during this call.
PaymentMade bool
// RawResult is the original MCP CallToolResult.
RawResult *mcp.CallToolResult
}Fields
Content []mcp.ContentContent is the list of content items from the tool response.
IsError boolIsError indicates whether the tool returned an error.
PaymentResponse *x402.SettleResponsePaymentResponse is the settlement response if payment was made.
PaymentMade boolPaymentMade indicates whether a payment was made during this call.
RawResult *mcp.CallToolResultRawResult is the original MCP CallToolResult.
type ToolHandler
ToolHandler is the function signature for MCP tool handlers. This is an alias for the official MCP SDK's mcp.ToolHandler type.
type ToolHandler = mcp.ToolHandlertype X402MCPClient
X402MCPClient wraps an MCP session (MCPCaller) with automatic x402 payment handling. Use NewX402MCPClient or NewX402MCPClientFromConfig with *mcp.ClientSession.
type X402MCPClient struct {
// contains filtered or unexported fields
}func CallTool(ctx context.Context, name string, args map[string]interface{}) (*MCPToolCallResult, error)
CallTool calls a tool with automatic payment handling.
func CallToolWithPayment(ctx context.Context, name string, args map[string]interface{}, payload types.PaymentPayload) (*MCPToolCallResult, error)
CallToolWithPayment calls a tool with a pre-created payment payload.
func Client) Client() MCPCaller
Client returns the underlying MCP caller (e.g. *mcp.ClientSession).
func GetToolPaymentRequirements(ctx context.Context, name string, args map[string]interface{}) (*types.PaymentRequired, error)
GetToolPaymentRequirements fetches payment requirements for a tool without paying.
func OnAfterPayment(hook AfterPaymentHook) *X402MCPClient
OnAfterPayment registers a hook called after payment is submitted.
func OnBeforePayment(hook BeforePaymentHook) *X402MCPClient
OnBeforePayment registers a hook called before creating payment.
func OnPaymentRequired(hook PaymentRequiredHook) *X402MCPClient
OnPaymentRequired registers a hook called when payment is required.
func PaymentClient() *x402.X402Client
PaymentClient returns the underlying x402 payment client.
