Skip to main content

MCP Integration

The Model Context Protocol (MCP) is an open standard that lets AI agents discover and invoke tools from external servers. ItPay implements MCP to give any MCP-compatible agent — Claude Desktop, Cursor, Cline, and others — the ability to discover paid AI services, initiate payments, scan QR codes, query invoices, and process refunds directly from natural language.

Learn more at modelcontextprotocol.io.


1. ItPay as MCP Server

ItPay exposes itself as a standard MCP server. Every paid AI service is modeled as an MCP tool:

MCP PhaseItPay MethodDescription
tools/listService DiscoveryReturns all available ServiceManifest entries as MCP tool definitions
tools/callPayment ExecutionInvokes the requested payment method against the selected manifest

Each ServiceManifest in the ItPay ecosystem maps to one or more MCP tools. The manifest's name, description, and pricing fields become the tool's identity, and each supported payment_methods flag translates into a dedicated tool that the agent can invoke.

Lifecycle Overview

The sequence diagram below shows the full lifecycle of an MCP interaction between the Agent (MCP Host) and the ItPay MCP Server — from tool discovery through payment execution and result delivery.

sequenceDiagram
participant Host as MCP Host<br/>(Agent / LLM)
participant Server as ItPay MCP Server
participant Gateway as ItPay Gateway<br/>(API Backend)

Note over Host,Server: Phase 1: Capability Discovery
Host->>Server: JSON-RPC: {"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}
Server->>Gateway: Query registered ServiceManifests
Gateway-->>Server: List of manifests with pricing + payment methods
Server-->>Host: JSON-RPC: {"jsonrpc":"2.0","id":1,"result":{"tools":[...]}}

Note over Host,Server: Phase 2: Tool Invocation (Payment)
Host->>Host: LLM selects best tool from returned definitions
Host->>Server: JSON-RPC: {"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"smart_summary__pay_one_time","arguments":{"manifest_id":"01J7X...","amount":99,"currency":"USD"}}}
Server->>Gateway: Create PaymentIntent in ItPay Gateway
Gateway-->>Server: PaymentIntent object + QR data
Server-->>Host: JSON-RPC: {"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"Payment initiated..."}]}}

Note over Host,Server: Phase 3: User completes payment via channel
Note over Host,Gateway: Payer scans QR → pays via Alipay/WeChat → channel settles
Gateway-->>Server: Webhook: payment.succeeded (async)
Server-->>Host: (Optional) Status update notification

How This Works in AI Applications When an AI agent connects to the ItPay MCP server, it first discovers what payment services are available. The LLM reads the tool descriptions and schemas to understand what each service costs and which payment methods it supports. Based on the user's natural language request, the agent selects the appropriate tool and initiates payment without manual intervention.


2. Protocol Messages

Every MCP interaction uses JSON-RPC 2.0 as the wire format. This section defines the exact framing for each message type.

2.1 tools/list Request

{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/list",
"params": {}
}

Understanding the tools/list Request

This message is the discovery handshake — it asks the MCP server "What can you do?" The server responds with every tool it exposes. In ItPay's case, that means every ServiceManifest × payment_method combination available in the ecosystem.

Field semantics:

  • jsonrpc — Protocol version. Must always be "2.0".
  • id — Request identifier. Used to correlate requests and responses. Clients may use any unique value (integer or string).
  • method — The MCP method. For discovery, this is always "tools/list".
  • params — Always an empty object {} for tools/list.
note

The tools/list method takes no parameters because it returns the complete set of available tools. There is no pagination or filtering — the server is expected to return everything it can do.

2.2 tools/list Response

The response returns an array of tool definitions. Each ServiceManifest in the ItPay ecosystem produces one tool per supported payment method:

{
"jsonrpc": "2.0",
"id": 1,
"result": {
"tools": [
{
"name": "smart_summary__pay_one_time",
"description": "Pay $0.99 per summary for Smart Summary — AI-powered document summarization by SummaryBot Inc.",
"inputSchema": {
"type": "object",
"properties": {
"manifest_id": {
"type": "string",
"description": "ServiceManifest UUIDv7"
},
"amount": {
"type": "number",
"description": "Payment amount in minor units (default: manifest price)"
},
"currency": {
"type": "string",
"description": "ISO 4217 currency code (default: manifest settlement_currency)"
},
"invoice_id": {
"type": "string",
"description": "Optional client invoice identifier"
}
},
"required": ["manifest_id"]
}
},
{
"name": "smart_summary__pay_subscription",
"description": "Subscribe to Smart Summary — monthly recurring payment for AI document summarization",
"inputSchema": {
"type": "object",
"properties": {
"manifest_id": {
"type": "string",
"description": "ServiceManifest UUIDv7"
},
"plan_id": {
"type": "string",
"enum": ["plan_starter", "plan_pro"],
"description": "Subscription plan: Starter ($9.99/mo, 50 requests) or Pro ($29.99/mo, 500 requests)"
}
},
"required": ["manifest_id", "plan_id"]
}
},
{
"name": "super_resolution__pay_one_time",
"description": "Pay $0.49 per image for Super Resolution — AI upscaling by PixelForge Ltd.",
"inputSchema": {
"type": "object",
"properties": {
"manifest_id": {
"type": "string",
"description": "ServiceManifest UUIDv7"
},
"amount": {
"type": "number",
"description": "Payment amount in minor units"
},
"currency": {
"type": "string",
"description": "ISO 4217 currency code"
}
},
"required": ["manifest_id"]
}
}
]
}
}

Understanding the tools/list Response

Each item in the tools array is a complete tool definition that an LLM can reason about:

  • name — The canonical identifier the host uses in subsequent tools/call requests. Follows the pattern {manifest_slug}__{payment_method}, using a double underscore separator.
  • description — A human-readable summary that the LLM uses to decide which tool fits the user's request. ItPay enriches this with pricing information and provider details.
  • inputSchema — A JSON Schema object that defines the expected parameters. The LLM uses this to construct valid arguments. Required fields are listed explicitly; optional fields have defaults or are truly optional.
tip

The LLM never sees the raw ServiceManifest — only these tool definitions. This means you control exactly what information the agent has access to, and you can shape its decision-making through careful description and inputSchema design.

2.3 tools/call Request

{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": {
"name": "smart_summary__pay_one_time",
"arguments": {
"manifest_id": "01J7XYKZ1A2B3C4D5E6F7G8H9I",
"amount": 99,
"currency": "USD",
"invoice_id": "inv_client_42"
}
}
}

Understanding the tools/call Request

This is the execution message — it tells the server to run a specific tool with specific arguments.

Field semantics:

  • method — Always "tools/call" for tool execution.
  • params.name — Must exactly match a tool name returned by tools/list. If it doesn't, the server returns error code -32000 (Tool not found).
  • params.arguments — Must conform to the tool's inputSchema. Required fields must be present; optional fields may be omitted. Type mismatches return error code -32602 (Invalid params).
note

The manifest_id field contains a UUIDv7 — a time-ordered UUID that encodes a timestamp. This enables efficient range queries on the ItPay Gateway for audit and reconciliation purposes. The invoice_id is an optional client-side identifier that can be any string the client chooses.

2.4 tools/call Response (Success)

{
"jsonrpc": "2.0",
"id": 2,
"result": {
"content": [
{
"type": "text",
"text": "✅ Payment initiated for **Smart Summary**\n\n- **Service:** Smart Summary by SummaryBot Inc.\n- **Amount:** $0.99\n- **Invoice:** `inv_01J7XYZ...`\n- **Payment Intent:** `pay_2xK3m9QrL8vN5pW1`\n- **QR Data:** `itpay://pay/pay_2xK3m9QrL8vN5pW1?channel=alipay&amount=0.99&currency=USD&sig=...`\n- **Status:** `pending`\n\nPlease scan the QR code with Alipay or WeChat to complete payment."
},
{
"type": "resource",
"resource": {
"uri": "itpay://qr/pay_2xK3m9QrL8vN5pW1",
"mimeType": "image/png",
"text": "<base64_encoded_qr_image>"
}
}
]
}
}

Understanding the tools/call Response

The response uses MCP's content array structure, which can contain multiple content items of different types:

  • type: "text" — A human-readable summary of the payment initiation. The LLM presents this to the user, including the QR data URL and payment status.
  • type: "resource" — An embedded resource containing the QR code as a base64-encoded PNG image. MCP-compatible hosts can render this directly in the UI.
note

The payment is initiated but not yet completed. The status is pending because the payment requires the user to scan the QR code with their payment app (Alipay, WeChat Pay, etc.). The ItPay Gateway receives an asynchronous webhook when the payment settles. The MCP host may optionally poll or receive a status update notification.

Edge cases:

  • If the QR image is too large for the MCP message, the server returns only the text content with the itpay:// URI.
  • If the payment intent was already created (e.g. from a previous call), the server returns the existing intent rather than creating a duplicate.

2.5 tools/call Response (Error)

{
"jsonrpc": "2.0",
"id": 2,
"error": {
"code": -32000,
"message": "Insufficient balance",
"data": {
"available": 50,
"required": 99,
"currency": "USD"
}
}
}

Understanding the Error Response

When a tool call fails, the server returns a JSON-RPC error object instead of a result. The error contains:

  • code — A numeric error code. ItPay uses codes in the -32000 to -32099 range (MCP reserved range) plus the standard -32602 for parameter validation.
  • message — A short, human-readable error name.
  • data — Structured error context that the LLM can use to take corrective action. For example, an Insufficient balance error includes the available balance so the agent can inform the user or choose a different service.

How This Works in AI Applications When an AI agent initiates a payment through MCP, it receives back structured, machine-readable results. The LLM can present the payment QR code inline, explain the next steps to the user, and handle errors gracefully — suggesting alternative payment methods or notifying the user of insufficient funds. This makes the payment experience feel like a natural part of the conversation rather than a separate transaction.


3. Discovery Flow

The discovery flow is the process by which an MCP host learns what payment services are available and how to invoke them.

ServiceManifest → Tool Mapping

The following table shows how ServiceManifest fields map to MCP tool properties:

ServiceManifest FieldMCP Tool FieldDescription
name ("Smart Summary")name prefix (smart_summary)Slugified manifest name becomes the tool name prefix
descriptiondescriptionCombined with payment method info for LLM context
pricing.fixed_priceinputSchema.properties.amount defaultDefault amount in minor units
pricing.currencyinputSchema.properties.currency defaultDefault currency code
payment_methods arrayGenerates N tools per manifestEach method (one_time, subscription, cumulative) produces a distinct tool
subscription_plans[]inputSchema.properties.plan_id.enumSubscription plan IDs populate the enum

Flow Steps

sequenceDiagram
participant Host as MCP Host<br/>(Agent / LLM)
participant Server as ItPay MCP Server

Note over Host,Server: Phase 1: Discovery
Host->>Server: tools/list
Server-->>Host: Tool definitions for all services

Note over Host,Server: Phase 2: Selection
Host->>Host: LLM evaluates descriptions & schemas

Note over Host,Server: Phase 3: Invocation
Host->>Server: tools/call {name, arguments}
Server-->>Host: Result (success or error)
  1. Discovery. The MCP host sends a tools/list request to the ItPay MCP server.
  2. Response. The server responds with a list of tool definitions — one per ServiceManifest × payment_method combination.
  3. Selection. The LLM chooses which tool to call based on its description and inputSchema.
  4. Invocation. The host invokes tools/call with the chosen tool name and appropriate arguments.
// tools/list response — abbreviated example
{
"tools": [
{
"name": "smart_summary__pay_one_time",
"description": "Pay $0.99 per summary for Smart Summary — AI-powered document summarization by SummaryBot Inc.",
"inputSchema": {
"type": "object",
"properties": {
"invoice_id": { "type": "string", "description": "Optional invoice ID for tracking" }
}
}
},
{
"name": "smart_summary__pay_subscription",
"description": "Subscribe to Smart Summary — monthly recurring payment for AI document summarization",
"inputSchema": {
"type": "object",
"properties": {
"plan_id": {
"type": "string",
"enum": ["plan_starter", "plan_pro"],
"description": "Subscription plan: Starter ($9.99/mo, 50 requests) or Pro ($29.99/mo, 500 requests)"
}
},
"required": ["plan_id"]
}
}
]
}

How This Works in AI Applications When a user asks "What AI services can I pay for?", the agent calls tools/list and presents the available services. The descriptions include pricing information, so the LLM can answer questions like "What's the cheapest summarization tool?" or "Is there a subscription for image upscaling?" without any additional prompting.


4. Tool Definitions

Each payment method in ItPay corresponds to a specific MCP tool pattern. The sections below define the canonical schema for each tool type.

4.1 pay_one_time

One-time per-call payment. The agent charges the user a fixed amount for a single service invocation.

ParameterTypeRequiredDescription
manifest_idstringyesUUIDv7 of the target ServiceManifest
amountnumbernoOverride amount in minor units (defaults to manifest price)
currencystringnoISO 4217 currency code (defaults to manifest settlement_currency)
invoice_idstringnoOptional client-side invoice identifier
metadataobjectnoArbitrary key-value pairs for tracking
{
"name": "<manifest_id>__pay_one_time",
"description": "Pay one-time for <manifest name> — <manifest description>",
"inputSchema": {
"type": "object",
"properties": {
"manifest_id": { "type": "string", "description": "ServiceManifest UUIDv7" },
"amount": { "type": "number", "description": "Payment amount in minor units" },
"currency": { "type": "string", "description": "ISO 4217 currency code" },
"invoice_id": { "type": "string", "description": "Optional client invoice ID" },
"metadata": { "type": "object", "description": "Arbitrary tracking metadata" }
},
"required": ["manifest_id"]
}
}

4.2 pay_cumulative

Post-paid billing. The agent authorizes a cumulative billing session where usage is tallied and billed at the end of the billing cycle.

ParameterTypeRequiredDescription
manifest_idstringyesUUIDv7 of the target ServiceManifest
session_idstringnoResume an existing cumulative session
max_spendnumbernoSpending cap in minor units for the session
{
"name": "<manifest_id>__pay_cumulative",
"description": "Start or resume cumulative billing for <manifest name> — billed at end of cycle",
"inputSchema": {
"type": "object",
"properties": {
"manifest_id": { "type": "string", "description": "ServiceManifest UUIDv7" },
"session_id": { "type": "string", "description": "Existing session ID to resume" },
"max_spend": { "type": "number", "description": "Spending cap in minor units" }
},
"required": ["manifest_id"]
}
}

4.3 pay_subscribe

Recurring subscription. The agent selects a plan from the manifest's subscription options and initiates recurring payments.

ParameterTypeRequiredDescription
manifest_idstringyesUUIDv7 of the target ServiceManifest
plan_idstringyesPlan identifier from the manifest's subscription plans
auto_renewbooleannoWhether the subscription auto-renews (default: true)
{
"name": "<manifest_id>__pay_subscribe",
"description": "Subscribe to <manifest name> — recurring payments for <manifest description>",
"inputSchema": {
"type": "object",
"properties": {
"manifest_id": { "type": "string", "description": "ServiceManifest UUIDv7" },
"plan_id": {
"type": "string",
"description": "Subscription plan ID from the manifest"
},
"auto_renew": {
"type": "boolean",
"description": "Auto-renew on expiry (default: true)"
}
},
"required": ["manifest_id", "plan_id"]
}
}

4.4 scan_qr

Scan a QR code to complete a payment. Used when the agent or user has a QR image (e.g. an Alipay or WeChat Pay QR code).

ParameterTypeRequiredDescription
qr_datastringyesQR code content string or base64-encoded image
channelstringnoPayment channel hint — "alipay", "wechat", "card"
{
"name": "scan_qr",
"description": "Scan a payment QR code — decode and process the embedded payment intent",
"inputSchema": {
"type": "object",
"properties": {
"qr_data": { "type": "string", "description": "QR code content string or base64 image data" },
"channel": {
"type": "string",
"enum": ["alipay", "wechat", "card"],
"description": "Payment channel hint"
}
},
"required": ["qr_data"]
}
}

4.5 query_invoice

Retrieve the status and details of an existing invoice.

ParameterTypeRequiredDescription
invoice_idstringyesInvoice UUID to query
expandstring[]noRelated objects to include ("payment_intent", "manifest")
{
"name": "query_invoice",
"description": "Query an ItPay invoice — status, amount, payment channel, and timestamps",
"inputSchema": {
"type": "object",
"properties": {
"invoice_id": { "type": "string", "description": "Invoice UUIDv7 to query" },
"expand": {
"type": "array",
"items": { "type": "string", "enum": ["payment_intent", "manifest"] },
"description": "Related objects to expand in the response"
}
},
"required": ["invoice_id"]
}
}

4.6 refund

Process a refund against a completed payment.

ParameterTypeRequiredDescription
invoice_idstringyesInvoice UUID to refund
amountnumbernoPartial refund amount in minor units (default: full refund)
reasonstringnoReason for the refund
{
"name": "refund",
"description": "Process a full or partial refund against a completed ItPay invoice",
"inputSchema": {
"type": "object",
"properties": {
"invoice_id": { "type": "string", "description": "Invoice UUIDv7 to refund" },
"amount": { "type": "number", "description": "Partial refund amount in minor units" },
"reason": { "type": "string", "description": "Refund reason" }
},
"required": ["invoice_id"]
}
}

How This Works in AI Applications Each tool type serves a distinct payment pattern that an AI agent can handle conversationally. For a one-time task like "summarize this document," the agent uses pay_one_time. For ongoing usage like "I need image upscaling all month," it uses pay_subscribe. The agent selects the appropriate tool based on the user's stated intent and the tool descriptions returned during discovery.


5. Error Handling

When an MCP tool call fails, the server returns a JSON-RPC error response with a structured error code and message.

Error CodeNameConditionExample data
-32602Invalid paramsRequired parameter missing or wrong type{"field":"manifest_id","reason":"required"}
-32000Tool not foundname does not match any registered tool{"available_tools":["smart_summary__pay_one_time","scan_qr"]}
-32001Insufficient balanceUser's ItPay wallet balance is too low{"available":50,"required":100,"currency":"USD"}
-32002Invalid manifestmanifest_id is not a valid ServiceManifest UUID{"manifest_id":"bad_uuid","reason":"not_found"}
-32003Payment failedUnderlying payment channel rejected the intent{"channel":"alipay","reason":"insufficient_funds"}
-32004Refund not allowedInvoice cannot be refunded (e.g. already refunded, KYC too low){"invoice_id":"inv_123","reason":"already_refunded"}

5.1 Tool Not Found

{
"jsonrpc": "2.0",
"id": 3,
"error": {
"code": -32000,
"message": "Tool not found",
"data": {
"requested_tool": "nonexistent_tool",
"available_tools": [
"smart_summary__pay_one_time",
"smart_summary__pay_subscription",
"super_resolution__pay_one_time",
"scan_qr",
"query_invoice",
"refund"
]
}
}
}

The data field includes the list of available_tools so the LLM can self-correct and retry with a valid tool name.

5.2 Insufficient Balance

{
"jsonrpc": "2.0",
"id": 4,
"error": {
"code": -32001,
"message": "Insufficient balance",
"data": {
"available": 50,
"required": 199,
"currency": "USD",
"manifest_id": "01J7XYKZ1A2B3C4D5E6F7G8H9I"
}
}
}

The data field includes the available balance and required amount, enabling the LLM to inform the user how much more is needed, or to suggest a cheaper alternative.

5.3 Invalid Parameters

{
"jsonrpc": "2.0",
"id": 5,
"error": {
"code": -32602,
"message": "Invalid params",
"data": {
"field": "plan_id",
"reason": "must be one of: plan_starter, plan_pro",
"received": "plan_enterprise"
}
}
}

This is a standard JSON-RPC error code (-32602) reused for parameter validation. The data field identifies the specific field, the validation rule, and the value that was rejected.

How This Works in AI Applications Error handling in MCP is designed for autonomous recovery. When an agent receives an error like Tool not found, it can inspect available_tools and retry with a valid name. For Insufficient balance, it can inform the user and suggest a lower-cost service. This self-healing pattern reduces the need for manual intervention and makes the payment flow feel robust.


6. Client Configuration

Any MCP host can connect to the ItPay server. Below are examples for common clients.

6.1 Claude Desktop

Add the ItPay MCP server to your claude_desktop_config.json:

{
"mcpServers": {
"itpay": {
"command": "npx",
"args": ["-y", "@itpay/mcp"],
"env": {
"ITPAY_API_KEY": "sk_itp...here"
}
}
}
}

6.2 Cursor

In Cursor, add the MCP server via Settings → Features → MCP Servers:

Name: ItPay
Type: command
Command: npx -y @itpay/mcp
Environment Variables:
ITPAY_API_KEY=sk_itp...here

6.3 Cline (VS Code Extension)

Add to your MCP configuration file:

{
"mcpServers": {
"itpay": {
"command": "npx",
"args": ["-y", "@itpay/mcp"],
"env": {
"ITPAY_API_KEY": "sk_itp...here"
}
}
}
}

Verifying the Connection

Once connected, ask your agent:

"What paid services are available through ItPay?"

The agent will call tools/list and display the available services. You can then ask it to initiate a payment for any listed service.


7. MCP + x402 Combined Flow

ItPay supports an advanced MCP + x402 combined flow where tool discovery and payment are coupled through the HTTP 402 protocol.

Combined Flow Swimlane

The sequence below shows the complete x402 dance — from the agent's initial service call, through the 402 response, to the MCP payment and final retry with proof.

sequenceDiagram
participant Agent as Agent (MCP Host)
participant Service as External Service API<br/>(e.g. SummaryBot)
participant MCP as ItPay MCP Server

Note over Agent,Service: Step 1: Agent calls external API
Agent->>Service: POST /summarize<br/>{"text":"Long document..."}
Service-->>Agent: 402 Payment Required
Service-->>Agent: X-ItPay-Manifest: manifest_01J7X...
Service-->>Agent: Body: {ServiceManifest with pricing}

Note over Agent,MCP: Step 2: Agent discovers payment options
Agent->>MCP: tools/list (cached or fresh)
MCP-->>Agent: Tool definitions for manifest

Note over Agent,MCP: Step 3: Agent initiates payment
Agent->>MCP: tools/call<br/>{"name":"smart_summary__pay_one_time","arguments":{"manifest_id":"01J7X...","amount":99}}
MCP-->>Agent: PaymentIntent created, QR data returned

Note over Agent,Service: Step 4: User scans QR, pays via channel
Note over Agent,Service: Payment settles, ItPay receives webhook

Note over Agent,Service: Step 5: Agent retries with proof
Agent->>Service: POST /summarize<br/>{"text":"Long document..."}<br/>X-Payment-Proof: inv_01J7Y...
Service-->>Agent: 200 OK<br/>{"summary":"...","invoice_id":"inv_01J7Y..."}

Understanding the Combined Flow

This flow couples the MCP payment protocol with the HTTP 402 (Payment Required) status code, creating a complete payment lifecycle:

  1. Agent runs a tool that costs money. The agent calls the tool provider's service (e.g. a summarization API).
  2. Service responds with 402 Payment Required and includes a ServiceManifest in the response body or X-ItPay-Manifest header.
  3. The agent discovers the manifest. The agent extracts the manifest and presents payment options to the user.
  4. Payment through MCP. The agent calls pay_one_time (or pay_subscribe, etc.) on the ItPay MCP server.
  5. Service releases the resource. Once the payment intent is confirmed, the agent retries the original request with the payment proof and receives the result.

Cash Register Pattern

The x402 flow works like a cash register: the first request triggers the "ring" (402), the agent pays at the register (MCP tool), and the receipt (payment proof) lets the agent claim the goods.

Example in Practice

curl -X POST https://api.summarybot.ai/summarize \
-H "Content-Type: application/json" \
-d '{"text": "Long document content..."}'

# Response: 402 Payment Required
# X-ItPay-Manifest: manifest_01J7XYKZ1A2B...

How This Works in AI Applications The combined flow creates a seamless experience where the agent autonomously handles the entire payment lifecycle. The user simply asks for a service (e.g. "Summarize this document"), the agent encounters the paywall, initiates payment through MCP, presents the QR code to the user for scanning, and then retries the request with the payment proof — all without requiring the user to manually enter payment details.

Benefits of the Combined Flow

  • Discoverability. The 402 response carries the ServiceManifest, so the agent knows exactly what it's paying for and how.
  • Autonomy. The agent handles the entire payment lifecycle without manual intervention.
  • Atomicity. The payment proof is bound to the original request, preventing replay or misattribution.
  • Composability. Any standard MCP host can participate without custom payment logic — the MCP server handles everything.

Next Steps