如何将MCP服务器货币化
一个完整的示例,演示开发人员如何 将MCP(模型上下文协议)服务器货币化 使用PayLink,以及人工智能代理如何使用这些付费服务。
概述
该项目展示了以下内容之间的整合:
- MCP服务器 -AI模型可以使用的工具
- PayLink -实现货币化的支付层
- AI智能体 -付费使用工具的LangChain/LangGraph代理
建筑
上图展示了完整的支付流程:
- 代理 发起对货币化MCP工具的调用
- PayLink基础设施 验证付款:
- 检查代理钱包是否有足够的余额 - 将资金从代理钱包转移到MCP钱包
- 论成功:请求被转发到货币化MCP服务器,该服务器执行工具并返回结果
- 失败时 (信用额度不足):通知代理人请求用户资助
付款方式
- 代理 通过调用工具
PayLinkTools - PayLink 拦截请求并附加代理的钱包凭据
- MCP服务器 通过以下方式接收带有钱包上下文的请求
set_agent_wallet_from_scope() - @要求付款 装饰师检查是否需要付款并处理
- 付款从代理的钱包转移到服务器的钱包
- 工具执行 并返回结果
项目结构
how_to_monitize_mcp/
├── README.md # This file
├── example_mcp_server/ # The monetized MCP server
│ ├── main.py # Server implementation
│ ├── pyproject.toml # Dependencies
│ └── README.md
└── agent/ # The AI agent consumer
├── src/
│ └── graph.py # LangGraph agent definition
├── notebooks/
│ └── use_monitized_mcp.ipynb # Interactive example
├── langgraph.json # LangGraph configuration
├── pyproject.toml # Dependencies
└── README.md快速开始
先决条件
- Python 3.13+
- 紫外线 -快速Python包管理器
- OpenAI API密钥 -对于AI代理(设置为
OPENAI_API_KEY) - PayLink帐户 -用于钱包凭证
步骤1:启动货币化MCP服务器
# Navigate to the server directory
cd example_mcp_server
# Create and activate virtual environment
uv venv
source .venv/bin/activate
# Install dependencies
uv sync
# Run the server
uv run main.py服务器将在以下时间启动 http://0.0.0.0:5003/mcp
步骤2:运行AI代理
打开一个新终端:
# Navigate to the agent directory
cd agent
# Create and activate virtual environment
uv venv
source .venv/bin/activate
# Install dependencies
uv sync
# Run the LangGraph development server
langgraph dev代理人将在 http://127.0.0.1:2024 使用Studio UI。
详细实施
货币化MCP服务器(example_mcp_server/main.py)
MCP服务器公开了以下工具 要求付款 执行前:
1.定义工具
@app.list_tools()
async def list_tools() -> list[types.Tool]:
return [
types.Tool(
name="add",
description="Add two integers",
inputSchema={
"type": "object",
"properties": {
"a": {"type": "number"},
"b": {"type": "number"},
},
"required": ["a", "b"],
},
),
types.Tool(
name="subtract",
description="Subtract two integers",
inputSchema={...},
),
]2.添加付款要求 @require_payment
from paylink.mcp.monetize_mcp import require_payment
@app.call_tool()
@require_payment(
{
"add": 0.10, # $0.10 per call
"subtract": 0.20, # $0.20 per call
}
)
async def call_tool(tool_name: str, arguments: dict[str, Any]) -> list[TextContent]:
if tool_name == "add":
result = arguments["a"] + arguments["b"]
return [types.TextContent(type="text", text=str(result))]
# ... handle other tools3.从请求中提取钱包上下文
from paylink.mcp.wallet_context import set_agent_wallet_from_scope, reset_agent_wallet
async def handle_streamable_http(scope: Scope, receive: Receive, send: Send) -> None:
# Extract wallet info from request headers
token = set_agent_wallet_from_scope(scope)
try:
await session_manager.handle_request(scope, receive, send)
finally:
reset_agent_wallet(token)AI代理(agent/src/graph.py)
代理人使用 PayLinkTools 连接到货币化的MCP服务器:
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
from paylink.integrations.langchain_tools import PayLinkTools
# Initialize the LLM
llm = init_chat_model(model="gpt-4o-mini")
# Connect to the monetized MCP server
client = PayLinkTools(base_url="http://0.0.0.0:5003/mcp")
# Get available tools (includes payment metadata)
tools = client.list_tools()
# Create the agent with the tools
agent = create_agent(
model=llm,
tools=tools
)使用笔记本
交互式笔记本(agent/notebooks/use_monitized_mcp.ipynb)演示了直接使用工具:
from paylink.integrations.langchain_tools import PayLinkTools
# Connect to the monetized server
client = PayLinkTools(base_url="http://0.0.0.0:5003/mcp")
# List available tools
tools = client.list_tools()
print(tools)
# Call a paid tool (payment is automatic)
result = client.call_tool("add", {"a": 5, "b": 3})
print(result) # Output: 8钱包配置
代理和服务器都需要钱包配置。设置您的 .env 文件:
对于MCP服务器
# Server receives payments to this wallet
MCP_WALLET_CONNECTION_STRING = ""对于代理人
# Agent pays from this wallet
WALLET_CONNECTION_STRING=""
OPENAI_API_KEY=your-openai-key依赖项
MCP服务器
dependencies = [
"mcp[cli]>=1.21.0",
"click>=8.1",
"httpx>=0.27",
"paylink>=0.4.0",
]代理
dependencies = [
"langchain>=1.1.0",
"langchain-openai>=1.1.0",
"langgraph>=1.0.4",
"langgraph-cli[inmem]>=0.4.7",
"paylink>=0.4.0",
]关键概念
什么是MCP?
这 模型上下文协议(MCP) 是一个开放标准,使人工智能模型能够安全地连接到外部工具和数据源。它为LLM提供了一种标准化的方法来:
- 列出可用工具
- 调用带有参数的工具
- 接收结构化响应
什么是PayLink?
PayLink 是一个支付层,可以实现人工智能服务的货币化。它提供:
- 钱包管理 服务提供商和消费者
- 自动付款处理 通过装饰师
- 与流行框架集成 (LangChain、MCP等)
为什么要将MCP服务器货币化?
- 工具开发人员 可以从他们的创作中获得收入
- 公平补偿 用于计算资源和API调用
- 可持续生态系统 用于AI工具开发
- 按使用付费模式 可根据实际使用情况进行调整
示例流程
User: "What is 15 plus 27?"
1. Agent receives the query
2. LLM decides to use the "add" tool
3. PayLinkTools sends request to MCP server
- Includes wallet credentials in headers
4. MCP server's @require_payment checks:
- Tool "add" costs $0.10
- Agent wallet has sufficient balance
5. Payment is processed ($0.10 transferred)
6. Tool executes: 15 + 27 = 42
7. Result returned to agent
8. Agent responds: "15 plus 27 equals 42"定制
添加新的付费工具
- 在中添加工具定义
list_tools() - 添加定价
@require_payment装饰器 - 在中实现工具逻辑
call_tool()
@require_payment(
{
"add": 0.10,
"subtract": 0.20,
"multiply": 0.15, # New tool
"divide": 0.25, # New tool
}
)
async def call_tool(tool_name: str, arguments: dict[str, Any]) -> list[TextContent]:
# ... existing logic
elif tool_name == "multiply":
result = arguments["a"] * arguments["b"]
return [types.TextContent(type="text", text=str(result))]动态定价
您还可以根据以下因素实施动态定价:
- 输入复杂性
- 资源使用
- 一天中的时间
- 用户层
资源
许可证
此示例作为PayLink SDK的一部分提供用于教育目的。
