Mcp

mcp

Package mcp provides MCP (Model Context Protocol) transport integration for the x402 payment protocol.

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.

Source: mcp/constants.go:6

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.

Source: mcp/types.go:11

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

Source: mcp/utils.go:93

AttachPaymentResponseToMeta attaches settlement response to result

func AttachPaymentToMeta(params map[string]interface{}, payload types.PaymentPayload) map[string]interface{}

Source: mcp/utils.go:44

AttachPaymentToMeta attaches payment payload to request params

func BoolPtr(b bool) *bool

Source: mcp/types.go:74

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)

Source: mcp/client.go:433

CallPaidTool makes an MCP tool call with automatic x402 payment handling.

Flow:

  1. Calls the tool without payment
  2. If the server returns a payment required error, creates a payment
  3. Retries with payment attached in _meta
  4. 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

Source: mcp/utils.go:199

CreatePaymentRequiredError creates a PaymentRequiredError with the given message and payment required data.

Example:

err := mcp.CreatePaymentRequiredError("Payment required", &paymentRequired)
return nil, err

func CreateToolResourceUrl(toolName string, customUrl string) string

Source: mcp/utils.go:162

CreateToolResourceUrl creates a resource URL for an MCP tool

func ExtractPaymentFromMeta(params map[string]interface{}) (*types.PaymentPayload, error)

Source: mcp/utils.go:13

ExtractPaymentFromMeta extracts payment payload from MCP request _meta field

func ExtractPaymentRequiredFromError(err interface{}) (*types.PaymentRequired, error)

Source: mcp/utils.go:236

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)

Source: mcp/utils.go:103

ExtractPaymentRequiredFromResult extracts PaymentRequired from tool result (dual format)

func ExtractPaymentResponseFromMeta(result MCPToolResult) (*x402.SettleResponse, error)

Source: mcp/utils.go:64

ExtractPaymentResponseFromMeta extracts settlement response from MCP result _meta

func IsObject(value interface{}) bool

Source: mcp/utils.go:181

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

Source: mcp/utils.go:217

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

Source: mcp/server.go:43

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

Source: mcp/client.go:31

NewX402MCPClient creates an x402-aware MCP client.

func NewX402MCPClientFromConfig(caller MCPCaller, schemes []SchemeRegistration, options Options) *X402MCPClient

Source: mcp/client.go:40

NewX402MCPClientFromConfig creates an x402-aware MCP client from scheme registrations.

Types

type AfterExecutionContext

Source: mcp/types.go:130

AfterExecutionContext extends ServerHookContext with result

type AfterExecutionContext struct {
	ServerHookContext
	Result MCPToolResult
}
Fields
  • ServerHookContext
  • Result MCPToolResult

type AfterExecutionHook

Source: mcp/types.go:136

AfterExecutionHook is called after tool execution

type AfterExecutionHook func(context AfterExecutionContext) error

type AfterPaymentContext

Source: mcp/types.go:50

AfterPaymentContext is provided to after payment hooks

type AfterPaymentContext struct {
	ToolName       string
	PaymentPayload types.PaymentPayload
	Result         MCPToolResult
	SettleResponse *x402.SettleResponse
}
Fields
  • ToolName string
  • PaymentPayload types.PaymentPayload
  • Result MCPToolResult
  • SettleResponse *x402.SettleResponse

type AfterPaymentHook

Source: mcp/types.go:47

AfterPaymentHook is called after payment is submitted

type AfterPaymentHook func(context AfterPaymentContext) error

type AfterSettlementHook

Source: mcp/types.go:145

AfterSettlementHook is called after successful settlement

type AfterSettlementHook func(context SettlementContext) error

type BeforeExecutionHook

Source: mcp/types.go:127

BeforeExecutionHook is called before tool execution (can abort)

type BeforeExecutionHook func(context ServerHookContext) (bool, error)

type BeforePaymentHook

Source: mcp/types.go:44

BeforePaymentHook is called before payment is created

type BeforePaymentHook func(context PaymentRequiredContext) error

type DynamicPayTo

Source: mcp/types.go:160

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

Source: mcp/types.go:164

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

Source: mcp/client.go:15

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

Source: mcp/types.go:87

MCPContentItem represents an MCP content item

type MCPContentItem struct {
	Type string
	Text string
}
Fields
  • Type string
  • Text string

type MCPToolCallResult

Source: mcp/types.go:93

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 []MCPContentItem
  • IsError bool
  • PaymentResponse *x402.SettleResponse
  • PaymentMade bool

type MCPToolContext

Source: mcp/types.go:21

MCPToolContext provides context during tool execution

type MCPToolContext struct {
	ToolName  string
	Arguments map[string]interface{}
	Meta      map[string]interface{}
}
Fields
  • ToolName string
  • Arguments map[string]interface{}
  • Meta map[string]interface{}

type MCPToolResult

Source: mcp/types.go:79

MCPToolResult represents an MCP tool call result

type MCPToolResult struct {
	Content           []MCPContentItem
	IsError           bool
	Meta              map[string]interface{}
	StructuredContent map[string]interface{}
}
Fields
  • Content []MCPContentItem
  • IsError bool
  • Meta map[string]interface{}
  • StructuredContent map[string]interface{}

type Options

Source: mcp/types.go:58

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 *bool

    AutoPayment 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

Source: mcp/types.go:28

PaymentRequiredContext is provided to onPaymentRequired hooks

type PaymentRequiredContext struct {
	ToolName        string
	Arguments       map[string]interface{}
	PaymentRequired types.PaymentRequired
}
Fields
  • ToolName string
  • Arguments map[string]interface{}
  • PaymentRequired types.PaymentRequired

type PaymentRequiredError

Source: mcp/types.go:148

PaymentRequiredError represents a payment required error

type PaymentRequiredError struct {
	Code            int
	Message         string
	PaymentRequired *types.PaymentRequired
}
Fields
  • Code int
  • Message string
  • PaymentRequired *types.PaymentRequired

func Error) Error() string

Source: mcp/types.go:154

type PaymentRequiredHook

Source: mcp/types.go:41

PaymentRequiredHook is called when a 402 response is received

type PaymentRequiredHook func(context PaymentRequiredContext) (*PaymentRequiredHookResult, error)

type PaymentRequiredHookResult

Source: mcp/types.go:35

PaymentRequiredHookResult is returned from payment required hooks

type PaymentRequiredHookResult struct {
	Payment *types.PaymentPayload
	Abort   bool
}
Fields
  • Payment *types.PaymentPayload
  • Abort bool

type PaymentWrapper

Source: mcp/server.go:25

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

Source: mcp/server.go:63

Wrap wraps a tool handler with x402 payment verification and settlement. The returned handler can be used directly with mcpServer.AddTool().

Flow:

  1. Extracts x402/payment from request _meta
  2. If no payment, returns 402 payment required error
  3. Verifies payment via facilitator
  4. OnBeforeExecution hook (if configured)
  5. Executes the original handler
  6. OnAfterExecution hook (if configured)
  7. Settles payment via facilitator
  8. OnAfterSettlement hook (if configured)
  9. Returns result with settlement info in _meta

type PaymentWrapperConfig

Source: mcp/types.go:101

PaymentWrapperConfig configures payment wrapper behavior

type PaymentWrapperConfig struct {
	Accepts    []types.PaymentRequirements
	Resource   *ResourceInfo
	Hooks      *PaymentWrapperHooks
	Extensions map[string]interface{}
}
Fields
  • Accepts []types.PaymentRequirements
  • Resource *ResourceInfo
  • Hooks *PaymentWrapperHooks
  • Extensions map[string]interface{}

type PaymentWrapperHooks

Source: mcp/types.go:112

PaymentWrapperHooks provides server-side hooks

type PaymentWrapperHooks struct {
	OnBeforeExecution *BeforeExecutionHook
	OnAfterExecution  *AfterExecutionHook
	OnAfterSettlement *AfterSettlementHook
}
Fields
  • OnBeforeExecution *BeforeExecutionHook
  • OnAfterExecution *AfterExecutionHook
  • OnAfterSettlement *AfterSettlementHook

type ResourceInfo

Source: mcp/types.go:109

ResourceInfo provides resource metadata. Alias for types.ResourceInfo for compatibility.

type ResourceInfo = types.ResourceInfo

type SchemeRegistration

Source: mcp/types.go:167

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.Network
  • Client x402.SchemeNetworkClient
  • ClientV1 x402.SchemeNetworkClientV1
  • X402Version int

    1 or 2 (defaults to 2)

type ServerHookContext

Source: mcp/types.go:119

ServerHookContext is provided to server-side hooks

type ServerHookContext struct {
	ToolName            string
	Arguments           map[string]interface{}
	PaymentRequirements types.PaymentRequirements
	PaymentPayload      types.PaymentPayload
}
Fields
  • ToolName string
  • Arguments map[string]interface{}
  • PaymentRequirements types.PaymentRequirements
  • PaymentPayload types.PaymentPayload

type SettlementContext

Source: mcp/types.go:139

SettlementContext extends ServerHookContext with settlement

type SettlementContext struct {
	ServerHookContext
	Settlement x402.SettleResponse
}
Fields
  • ServerHookContext
  • Settlement x402.SettleResponse

type ToolCallResult

Source: mcp/client.go:401

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.Content

    Content is the list of content items from the tool response.

  • IsError bool

    IsError indicates whether the tool returned an error.

  • PaymentResponse *x402.SettleResponse

    PaymentResponse is the settlement response if payment was made.

  • PaymentMade bool

    PaymentMade indicates whether a payment was made during this call.

  • RawResult *mcp.CallToolResult

    RawResult is the original MCP CallToolResult.

type ToolHandler

Source: mcp/server.go:22

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.ToolHandler

type X402MCPClient

Source: mcp/client.go:21

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)

Source: mcp/client.go:82

CallTool calls a tool with automatic payment handling.

func CallToolWithPayment(ctx context.Context, name string, args map[string]interface{}, payload types.PaymentPayload) (*MCPToolCallResult, error)

Source: mcp/client.go:188

CallToolWithPayment calls a tool with a pre-created payment payload.

func Client) Client() MCPCaller

Source: mcp/client.go:54

Client returns the underlying MCP caller (e.g. *mcp.ClientSession).

func GetToolPaymentRequirements(ctx context.Context, name string, args map[string]interface{}) (*types.PaymentRequired, error)

Source: mcp/client.go:319

GetToolPaymentRequirements fetches payment requirements for a tool without paying.

func OnAfterPayment(hook AfterPaymentHook) *X402MCPClient

Source: mcp/client.go:76

OnAfterPayment registers a hook called after payment is submitted.

func OnBeforePayment(hook BeforePaymentHook) *X402MCPClient

Source: mcp/client.go:70

OnBeforePayment registers a hook called before creating payment.

func OnPaymentRequired(hook PaymentRequiredHook) *X402MCPClient

Source: mcp/client.go:64

OnPaymentRequired registers a hook called when payment is required.

func PaymentClient() *x402.X402Client

Source: mcp/client.go:59

PaymentClient returns the underlying x402 payment client.