Paid MCP Server Template

Paid MCP Server Template

A production-ready template for building monetized MCP servers that require per-call payments via the Mainlayer infrastructure. It provides a structured payment gate that ensures AI agents pay for tool usage before accessing server logic or data.

Category
访问服务器

README

paid-mcp-server

A production-ready MCP server template where each tool call requires payment via Mainlayer — payment infrastructure for AI agents.

Use this as the starting point for monetizing your MCP tools. Every tool call passes through a payment gate — if the caller hasn't paid, they receive clear instructions on how to do so.

High-virality template: Perfect for AI marketplaces, prompt shops, and tool marketplaces where every API call is monetized.


What this template does

AI agents use MCP servers to access tools. This template shows you how to monetize those tools using Mainlayer.

The flow:

  1. An agent calls a tool (e.g. search_web) and provides their payer_wallet.
  2. The server checks for a valid Mainlayer entitlement before running any logic.
  3. If not paid: agent receives a structured error with price and payment instructions.
  4. Agent pays via Mainlayer, then retries the same tool call.
  5. Tool executes and returns its result.

This template includes 6 tools (4 paid, 2 free):

Paid Tools

Tool Description Price
search_web Web search with structured results $0.01/call
analyze_code Analyze source code for issues $0.05/analysis
generate_image_prompt Generate optimized image generation prompts $0.02/call
summarize_url Summarize web content from URL $0.03/call

Free Tools (always available)

Tool Description
hello Greeting endpoint (free demo)
get_time Current server time (free demo)
echo Echo tool for testing

All demo tools use mocked data — replace implementations with real API calls for production.


Prerequisites


Setup

1. Clone and install

git clone https://github.com/your-org/paid-mcp-server
cd paid-mcp-server
npm install

2. Configure your API key

cp .env.example .env

Open .env and set your Mainlayer API key:

MAINLAYER_API_KEY=ml_your_api_key_here

Get your API key from the Mainlayer dashboard.

3. Register your tools on Mainlayer

This creates a "resource" for each tool — a paywall entry with a name and price.

npm run setup

The script will print resource IDs. Copy them into your .env:

RESOURCE_ID_WEATHER=res_xxxxxxxxxxxx
RESOURCE_ID_SEARCH=res_xxxxxxxxxxxx
RESOURCE_ID_SUMMARY=res_xxxxxxxxxxxx

4. Build and start the server

npm run build
npm start

The server runs over stdio, which is the standard MCP transport.


Connecting to Claude Desktop

This server works as an MCP server for Claude Desktop. Add it to your config:

macOS: ~/Library/Application Support/Claude/claude_desktop_config.json Windows: %APPDATA%\Claude\claude_desktop_config.json Linux: ~/.config/Claude/claude_desktop_config.json

{
  "mcpServers": {
    "paid-tools": {
      "command": "node",
      "args": ["/absolute/path/to/paid-mcp-server/dist/index.js"],
      "env": {
        "MAINLAYER_API_KEY": "ml_your_api_key_here",
        "RESOURCE_ID_SEARCH_WEB": "res_xxxxxxxxxxxx",
        "RESOURCE_ID_ANALYZE_CODE": "res_xxxxxxxxxxxx",
        "RESOURCE_ID_GENERATE_IMAGE_PROMPT": "res_xxxxxxxxxxxx",
        "RESOURCE_ID_SUMMARIZE_URL": "res_xxxxxxxxxxxx"
      }
    }
  }
}

After restarting Claude Desktop, the tools will appear in the tool list. Free tools are always available; paid tools return a 402 error with payment instructions if not authorized.

Example: Claude asks to search the web

Claude uses your payer wallet to call the tool:

Tool: search_web
Arguments: { "payer_wallet": "wallet_abc123", "query": "Claude AI" }

If not paid:

Error (402):
=== PAYMENT REQUIRED ===

Tool: Web Search
Price: 0.0100 USD per call
Resource ID: res_search_web

To pay, POST to: https://api.mainlayer.fr/payments
Authorization: Bearer <your_mainlayer_api_key>
Content-Type: application/json

{
  "resource_id": "res_search_web",
  "payer_wallet": "wallet_abc123"
}

After payment, retry your original tool call.
========================

Claude can handle this automatically or prompt you to pay.


How agents pay

When an agent calls a tool without a valid entitlement, they receive a structured error message:

=== PAYMENT REQUIRED ===

Tool: Current Weather
Price: 0.0010 USD per call
Resource ID: res_xxxxxxxxxxxx

To pay, POST to: https://api.mainlayer.fr/payments
Authorization: Bearer <your_mainlayer_api_key>
Content-Type: application/json

{
  "resource_id": "res_xxxxxxxxxxxx",
  "payer_wallet": "<your_wallet_address>"
}

After payment, retry your original tool call with the same arguments.
========================

The agent (or a human) makes the payment via Mainlayer, then retries the tool call. No changes needed on the server side — the entitlement check passes automatically.


Adding your own paid tool

Step 1 — Create the tool file

Create src/tools/my-tool.ts:

import type { ToolResult } from '../middleware.js';
import type { Entitlement } from '../mainlayer.js';

// Schema: what the tool does and what parameters it accepts
export const myToolSchema = {
  name: 'my_tool',
  description: 'What my tool does. Requires Mainlayer payment ($0.005/call).',
  inputSchema: {
    type: 'object' as const,
    properties: {
      // Every tool must include payer_wallet
      payer_wallet: {
        type: 'string',
        description: 'Your Mainlayer wallet address. Required for payment verification.',
      },
      my_input: {
        type: 'string',
        description: 'Input for my tool.',
      },
    },
    required: ['payer_wallet', 'my_input'],
  },
};

// Handler: runs only after payment is verified
export async function handleMyTool(
  args: Record<string, unknown>,
  _entitlement: Entitlement
): Promise<ToolResult> {
  const myInput = args.my_input as string;

  // Your tool logic here
  const result = `Processed: ${myInput}`;

  return {
    content: [{ type: 'text', text: result }],
  };
}

Step 2 — Register the resource in src/setup.ts

Add to the RESOURCES_TO_CREATE array:

{
  envKey: 'RESOURCE_ID_MY_TOOL',
  name: 'my_tool',
  displayName: 'My Tool',
  description: 'What my tool does.',
  price: 0.005,
  currency: 'USD',
},

Run setup again: npm run setup — copy the new resource ID into .env.

Step 3 — Register in src/index.ts

// Add import
import { myToolSchema, handleMyTool } from './tools/my-tool.js';

// Add to TOOL_RESOURCE_IDS
const TOOL_RESOURCE_IDS = {
  // ...existing
  my_tool: process.env.RESOURCE_ID_MY_TOOL ?? '',
};

// Add to TOOL_HANDLERS
const TOOL_HANDLERS = {
  // ...existing
  my_tool: handleMyTool,
};

// Add to ListTools response
return {
  tools: [...existing, myToolSchema],
};

Step 4 — Rebuild and restart

npm run build && npm start

That's it. Your new tool is live and paywalled.


Project structure

paid-mcp-server/
├── src/
│   ├── index.ts          # Server entry point + tool registration
│   ├── mainlayer.ts      # Mainlayer entitlement checking
│   ├── middleware.ts      # withPayment() — the payment gate
│   ├── setup.ts          # One-time resource registration script
│   └── tools/
│       ├── weather.ts    # Demo: weather tool ($0.001/call)
│       ├── research.ts   # Demo: web search tool ($0.005/call)
│       └── summary.ts    # Demo: AI summary tool ($0.01/call)
├── examples/
│   ├── custom-tool.ts    # Annotated guide to adding your own tool
│   └── setup.ts          # What setup does under the hood
├── .env.example          # Environment variable template
├── package.json
├── tsconfig.json
├── Dockerfile
└── docker-compose.yml

Deployment

Quick deployment to Railway

Deploy in 2 minutes without writing deployment config:

# 1. Install Railway CLI
npm install -g @railway/cli

# 2. Login
railway login

# 3. Create project
railway init

# 4. Set environment variables
railway variables set MAINLAYER_API_KEY=ml_your_key_here

# 5. Deploy
railway up

Visit your Railway project dashboard to see the deployed URL.

Quick deployment to Fly.io

# 1. Install and login
curl -L https://fly.io/install.sh | sh
flyctl auth login

# 2. Launch new app
flyctl launch --name my-paid-mcp-server

# 3. Set secrets
flyctl secrets set MAINLAYER_API_KEY=ml_your_key_here

# 4. Deploy
flyctl deploy

Your server will be live at https://my-paid-mcp-server.fly.dev.

Docker (local or self-hosted)

# 1. Copy and fill in your .env
cp .env.example .env

# 2. Build and run
docker-compose up --build

# 3. Server runs on http://localhost:3000

Manual VPS deployment

# On your VPS (Ubuntu/Debian):
sudo apt-get update && sudo apt-get install -y nodejs npm

# Clone repo and install
git clone https://github.com/your-org/paid-mcp-server.git
cd paid-mcp-server
npm install

# Set environment
export MAINLAYER_API_KEY=ml_your_key_here
npm run setup  # Register resources on Mainlayer

# Build and run (with PM2 for background process)
npm run build
npm install -g pm2
pm2 start dist/index.js --name "paid-mcp-server"
pm2 startup && pm2 save

# Server will automatically restart on reboot

Development

# Run in development mode (no build step)
npm run dev

# Type check
npm run typecheck

# Build
npm run build

Pricing guidelines

Price Suitable for
$0.001 Simple lookups (weather, exchange rates)
$0.005 Search queries, data enrichment
$0.01 AI inference, complex computations
$0.05+ Premium operations (image generation, video)

You can update prices at any time in the Mainlayer dashboard. Existing entitlements remain valid until they expire.


Key files to understand

  • src/mainlayer.ts — The requirePayment() function. Calls GET /entitlements/check and throws a structured McpError if payment is needed.
  • src/middleware.ts — The withPayment() wrapper. Extracts payer_wallet from args, looks up the resource ID, and calls requirePayment.
  • src/index.ts — Wires everything together. Add your tools here.

Support

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选