Are you building with an LLM?If you are using an AI assistant for development, you can provide it with a comprehensive context file to streamline the integration process.Click here to view the raw context file. Simply copy its contents and paste them into your LLM’s input as a knowledge base.
- Paywall Protection: Wrap your handlers with
withPaywallto automatically verifyAuthorizationtokens and check for valid subscriptions. - Credit Burning: Automatically burn credits after a successful API call, with support for both fixed and dynamic costs.
- Declarative Registration: Use the
attachmethod to register and protect your tools in a single, clean step. - Framework Agnostic: Works with both high-level servers (like the official TypeScript SDK’s
McpServeror Python’sFastMCP) and custom low-level ASGI/Express routers.
What is MCP?
As Large Language Models (LLMs) and AI agents become more sophisticated, their greatest limitation is their isolation. By default, they lack access to real-time information, private data sources, or the ability to perform actions in the outside world. The Model Context Protocol (MCP) was designed to solve this problem by creating a standardized communication layer for AI. Think of MCP as a universal language that allows any AI agent to ask a server, “What can you do?” and “How can I use your capabilities?”. It turns a closed-off model into an agent that can interact with the world through a secure and discoverable interface. An MCP server essentially publishes a “menu” of its services, which can include:- Tools: These are concrete actions the agent can request, like sending an email, querying a database, or fetching a weather forecast. The agent provides specific arguments (e.g.,
city="Paris") and the server executes the action. - Resources: These are stable pointers to data, identified by a URI. While a tool call might give a human-readable summary, a resource link (
weather://today/Paris) provides the raw, structured data (like a JSON object) that an agent can parse and use for further tasks. - Prompts: These are pre-defined templates that help guide an agent’s behavior, ensuring it requests information in the correct format or follows a specific interaction pattern.
Why integrate MCP with Nevermined Payments Library?
While MCP provides a powerful standard for what an AI agent can do, it doesn’t specify who is allowed to do it or how those services are paid for. This is where Nevermined Payments Library comes in. By integrating Nevermined, you can transform your open MCP server into a secure, monetizable platform. The core idea is to place a “paywall” in front of your MCP handlers. This paywall acts as a gatekeeper, intercepting every incoming request to a tool, resource, or prompt. Before executing your logic, it checks the user’sAuthorization header to verify they have a valid subscription and sufficient credits through the Nevermined protocol. If they don’t, the request is blocked. If they do, the request proceeds, and after your handler successfully completes, the paywall automatically deducts the configured number of credits.
This integration allows you to build a sustainable business model around your AI services. You can offer different subscription tiers (plans), charge dynamically based on usage, and maintain a complete audit trail of every transaction, all without cluttering your core application logic with complex payment code.
OAuth 2.1 Support for Remote MCP Servers
Nevermined Payments Library implements complete OAuth 2.1 authentication for MCP servers, acting as both:- OAuth Authorization Server (RFC 8414)
- OAuth Protected Resource Server (RFC 8414)
- OpenID Connect Provider (OIDC Discovery 1.0)
/.well-known/oauth-authorization-server, /.well-known/oauth-protected-resource, /.well-known/openid-configuration) are automatically generated and configured. Your MCP server becomes instantly compatible with any OAuth-enabled MCP client (Claude Desktop, custom agents, etc.) without any manual OAuth setup.
Simplified API: Complete MCP Server in Minutes
The Nevermined Payments Library provides a high-level API that handles everything for you:- ✅ MCP Server creation
- ✅ Express.js setup with CORS
- ✅ OAuth 2.1 endpoints (auto-generated)
- ✅ HTTP transport (POST/GET/DELETE
/mcp) - ✅ Session management for streaming
- ✅ Paywall protection for all tools/resources/prompts
Quick Example
Here’s how to create a complete, production-ready MCP server with OAuth authentication:- TypeScript
- Python
- ✅ Running with OAuth 2.1 authentication
- ✅ Protected by Nevermined paywall
- ✅ Compatible with Claude Desktop and any MCP client
- ✅ Monetizable with automatic credit deduction
What payments.mcp.start() Does for You
This single function call handles:
- Express Server Setup: Creates and configures an Express.js application
- OAuth Endpoints: Auto-generates RFC-compliant discovery endpoints:
/.well-known/oauth-authorization-server/.well-known/oauth-protected-resource/.well-known/openid-configuration/register(Dynamic Client Registration - RFC 7591)
- MCP Transport: Sets up HTTP transport endpoints (POST/GET/DELETE
/mcp) - Session Management: Handles SSE streaming and session lifecycle
- CORS & Middleware: Configures CORS, JSON parsing, and HTTP logging
- Graceful Shutdown: Returns a
stop()function for clean server termination
Complete Working Example
See the full production-ready example with advanced features:- GitHub: weather-mcp/src/server/main.ts
- Dynamic credit calculation based on response size
- Resources with URI templates (
weather://today/{city}) - Prompts for LLM guidance
- OpenAI observability integration
Dynamic Credits
Instead of fixed credits, you can calculate them dynamically based on the handler’s result:- Fixed credits: Calculated BEFORE handler execution (available in
context.credits) - Dynamic credits: Calculated AFTER handler execution (based on
ctx.result)
Client Usage
Step 1: Get Access Token Users need to subscribe to your agent’s plan and obtain an access token:~/Library/Application Support/Claude/claude_desktop_config.json):
Advanced Usage: Low-Level APIs
The sections below show advanced, low-level APIs for users who need custom server implementations or fine-grained control.For most use cases, we recommend using the simplified API above with
payments.mcp.start().0) Requirements & Installation
- TypeScript
- Python
- Node.js >= 18
@nevermined-io/payments(includes everything needed)zodfor schema validation
1) Create a Minimal MCP Server
First, let’s create a basic MCP server without any paywall to ensure the core setup is working.- TypeScript
- Python
This server uses the official MCP SDK and exposes a single tool,
weather.today.2) Initialize Nevermined Payments
Initialize the Nevermined Payments SDK with your builder/agent owner API key and environment.- TypeScript
- Python
When using low-level APIs, you may need to call
payments.mcp.configure() to set defaults.
With the simplified API (payments.mcp.start()), configuration is handled automatically.3) Dynamic Credits (Optional)
Instead of charging fixed credits, you can calculate them dynamically based on input arguments or response content.Understanding CreditsContext
When using a function forcredits, it receives a CreditsContext object with:
ctx.args: The input arguments the user sent (e.g.,{ city: "London" })ctx.result: The complete response your handler returnedctx.request.toolName: The name of the tool being calledctx.request.logicalUrl: The full logical URL for observabilityctx.request.authHeader: The auth token (for advanced logging)
Examples
- Based on Response Size
- Based on Input Arguments
- Conditional Pricing
- Python
Charge credits proportional to the response length:
- ✅ Fixed credits (
credits: 5n): Calculated BEFORE handler execution, available incontext.credits - ✅ Dynamic credits (function): Calculated AFTER handler execution, based on
ctx.argsandctx.result - ✅ Return type: Must return
bigint(TypeScript) orint(Python) - ⚠️ Performance: Keep calculations lightweight to avoid delays
4) Connecting MCP Clients
Once your server is running withpayments.mcp.start(), connecting clients is straightforward. Nevermined handles OAuth authentication automatically - clients just need to know the server URL.
Claude Desktop
Add to your Claude Desktop config file:- macOS:
~/Library/Application Support/Claude/claude_desktop_config.json - Windows:
%APPDATA%\Claude\claude_desktop_config.json
Cursor IDE
Add to your Cursor MCP config file:- Location:
~/.cursor/mcp.json
Custom MCP Client (TypeScript/JavaScript)
How OAuth Works Behind the Scenes
When a client connects to your MCP server:- Discovery: Client reads
/.well-known/oauth-authorization-serverto find OAuth endpoints - Registration: Client registers itself via
/register(dynamic client registration) - Authorization: Client obtains access token via OAuth 2.1 flow
- Authenticated Requests: All subsequent MCP requests include the token automatically
payments.mcp.start() configures everything automatically!
For production servers, replace
http://localhost:3000 with your public domain (e.g., https://weather-mcp.yourdomain.com).Advanced Usage
The methods below are for advanced use cases requiring custom server setup. For most applications, use the simplified
payments.mcp.start() approach shown above.Using withPaywall for Custom Servers
If you’re building a custom MCP server and want granular control, use withPaywall:
Using attach for Declarative Registration
Custom Low-Level Server
For custom Express servers, you can usepayments.mcp.createApp():
- TypeScript
- Python
Error Handling
| Error Code | Description |
|---|---|
-32003 | Payment Required - No token / Invalid token / Insufficient credits |
-32002 | Misconfiguration - Server setup error |
-32603 | Internal Error - Handler execution failed |
Full Code Examples
Production-Ready Example
The Weather MCP Server is a complete, production-ready example that demonstrates all features:- Repository: tutorials/mcp-examples/weather-mcp
- Main Server: weather-mcp/src/server/main.ts
- ✅ Complete OAuth 2.1 authentication with
payments.mcp.start() - ✅ Tools with dynamic credit calculation based on response size
- ✅ Resources with URI templates (
weather://today/{city}) - ✅ Prompts for LLM guidance
- ✅ OpenAI integration with Nevermined observability
- ✅ Graceful shutdown handling
- ✅ Environment-based configuration
Additional Examples
Advanced and low-level API examples:- TypeScript (Low-level): nevermined-io/weather-mcp-demo - Examples using
withPaywallandattachfor custom servers - Python: nevermined-io/weather-mcp-demo-py - Python implementation with FastMCP