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-knownendpoints - 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:| Endpoint | Description |
|---|---|
/.well-known/oauth-protected-resource | Protected resource metadata |
/.well-known/oauth-authorization-server | Authorization server metadata |
/.well-known/openid-configuration | OpenID Connect discovery |
POST /register | Dynamic client registration |
Configure MCP
Initialize the MCP integration with your agent details:planIdis required;agentIdis optional. The x402 facilitator is plan-centric — verify/settle resolve everything from the plan and the subscriber’s token.agentIdis informational only (it also populates the OAuthclient_idwhen present). A per-toolplanIdoption 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 on0.0.0.0is rarely what you want. Bind to127.0.0.1and 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
| Type | URI | Description |
|---|---|---|
| Tool | mcp://weather-server/tools/get_weather | Single tool |
| Tool Wildcard | mcp://weather-server/tools/* | All tools |
| Resource | mcp://weather-server/resources/weather://current | Single resource |
| Resource Wildcard | mcp://weather-server/resources/* | All resources |
| Prompt | mcp://weather-server/prompts/weather-query | Single prompt |
Wildcard Registration
Use wildcards to register all tools/resources/prompts at once:Auto-Configured Endpoints
Thestart() method automatically creates these endpoints:
Complete Example: Weather Agent
Handler Options
| Option | Type | Description |
|---|---|---|
credits | bigint or function | Credits to consume per call |
planId | string | Optional override for the plan ID (otherwise inferred from token) |
maxAmount | bigint | Max credits to verify during authentication (default: 1n) |
onRedeemError | string | On post-execution settlement failure: 'ignore' (default) returns the in-band payment error; 'propagate' throws a JSON-RPC error. Tool content is always suppressed either way (paid content is never delivered without settlement). |
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 x402PaymentPayload in the request params _meta["x402/payment"] (plain JSON). For backwards compatibility an Authorization: Bearer <token> header is still accepted as a deprecated fallback when _meta["x402/payment"] is absent.
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:
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 x402PaymentRequired object — there is no HTTP 402 on /mcp:
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 HTTP402 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, usecreateRouter:
Best Practices
- Descriptive Names: Use clear tool/resource/prompt names
- Schema Validation: Always define proper input schemas with Zod
- Credit Pricing: Set appropriate credits based on resource cost
- Error Messages: Provide clear error messages in responses
- Graceful Shutdown: Always implement
SIGINThandlers - Wildcard URIs: Use wildcards for simpler agent registration
- Version Control: Include version in server configuration
Related Documentation
- Agents - Register your MCP agent in Nevermined
- Payment Plans - Configure pricing for your agent
- Validation of Requests - Understanding the validation flow
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)