Skip to main content

MCP Integration

The Model Context Protocol (MCP) integration provides a complete payment-protected MCP server with OAuth 2.1 support and automatic credit management. This is the simplest way to run a payment-protected AI agent.

Overview of MCP Integration

The MCP integration automatically handles:
  • OAuth 2.1 Discovery: Auto-configured .well-known endpoints
  • Paywall Protection: Automatic token verification and credit burning
  • Streaming Support: SSE (Server-Sent Events) for streaming responses
  • Credit Management: Fixed or dynamic credit costs per tool/resource/prompt
  • Client Registration: Dynamic client registration for OAuth flows

OAuth 2.1 Discovery

When you start an MCP server, the library automatically exposes OAuth 2.1 discovery endpoints required by the X402 spec: These endpoints are generated automatically—no manual configuration required.

Configure MCP

Initialize the MCP integration with your plan details:
planId is required; agentId is optional. The x402 facilitator is plan-centric — verify/settle resolve everything from the plan and the subscriber’s token. agentId is informational only (it also populates the OAuth client_id when present). A per-tool planId option overrides the server-level plan.

Register Tools with Credits

Register MCP tools and specify their credit cost:

Dynamic Credit Calculation

For variable costs based on input/output:

Register Resources

Register MCP resources with payment protection:

Register Prompts

Register MCP prompts with credit costs:

Start Managed Server

Start a complete MCP server with all endpoints configured:
🔐 Bind to localhost in development. The MCP server holds an OAuth issuer and accepts paid requests — exposing it directly on 0.0.0.0 is rarely what you want. Bind to 127.0.0.1 and front it with a reverse proxy (Caddy, nginx, Traefik) terminating TLS for any public traffic.

MCP Logical URIs

When registering your agent at nevermined.app, use MCP logical URIs instead of HTTP URLs:

URI Format

Examples

Wildcard Registration

Use wildcards to register all tools/resources/prompts at once:

Auto-Configured Endpoints

The start() method automatically creates these endpoints:

Complete Example: Weather Agent

Handler Options

In-band x402 signaling (_meta)

The MCP transport follows the x402 v2 MCP transport spec: payments are signaled in band through the MCP tool-call machinery, not via HTTP status codes or headers.

Request — payment payload

The client sends the x402 PaymentPayload in the request params _meta["x402/payment"] (plain JSON). Note this is the payment channel — separate from session auth: the MCP session is an OAuth-protected resource, so the client must also send an Authorization: Bearer <accessToken> header on the transport to establish the session (initialize returns 401 without it). For backwards compatibility the server also reads the payment from that header alone (no _meta) as a deprecated fallback for one release.

Response — settlement receipt

On a successful paid call, the SDK injects the settlement receipt under _meta["x402/payment-response"] (the spec key), and Nevermined-specific observability under a namespaced _meta["nevermined/credits"] key:
Free / no-credit calls omit the x402/payment-response key (no settlement occurred); nevermined/credits is still attached with creditsRedeemed: '0'.

Payment required

When payment is required (missing/invalid token, or no subscription), the tool returns an error tool result carrying the x402 PaymentRequired object — there is no HTTP 402 on /mcp:
Both structuredContent (the object) and content[0].text (its JSON string) are populated, per spec. This applies to tools only — resources and prompts raise a JSON-RPC error instead (they have no tool-result error channel).

Error Handling

Payment-required is signaled in band as an error tool result (see above) — there is no HTTP 402 on /mcp. OAuth and payment-required live at different layers and never collide: OAuth rejects at the HTTP layer (401), while payment-required is an MCP tool-call result. The in-band shape inherently disambiguates the two. onRedeemError controls only the error type surfaced when settlement fails after the tool executed — it no longer controls whether content is returned. Per the spec, a paid result is never delivered without settlement landing, so the executed tool’s content is always suppressed on settlement failure. 'ignore' (default) surfaces the in-band payment error; 'propagate' throws a JSON-RPC misconfiguration error.

Advanced: Custom Express App

For existing Express applications, use createRouter:

Best Practices

  1. Descriptive Names: Use clear tool/resource/prompt names
  2. Schema Validation: Always define proper input schemas with Zod
  3. Credit Pricing: Set appropriate credits based on resource cost
  4. Error Messages: Provide clear error messages in responses
  5. Graceful Shutdown: Always implement SIGINT handlers
  6. Wildcard URIs: Use wildcards for simpler agent registration
  7. Version Control: Include version in server configuration

Source References:
  • RUN.md (MCP Server section, lines 16-86)
  • src/mcp/index.ts (MCP integration API)
  • tests/integration/mcp-integration.test.ts (integration examples)