一文带大家了解关于MCP 的完整 Hello World 示例

一文带大家了解关于MCP 的完整 Hello World 示例_第1张图片

本文默认读者已经了解了MCP概念,不了解MCP概念的同学可以参考文章:

一文读懂大模型中的MCP协议到底是啥东东-CSDN博客

以下是一个基于 Model Context Protocol (MCP) 的完整 Hello World 示例,包含服务端和客户端代码,展示最基本的工具注册与调用流程:

一、MCP服务端(Server)

# mcp_server.py
from jsonrpcserver import method, Success, Result, serve

# 注册一个最简单的MCP工具:返回"Hello World"
@method
def hello_world(context: dict) -> Result:
    """MCP工具:返回Hello World"""
    # 实际业务逻辑(此处仅返回字符串)
    return Success({"message": "Hello, MCP World!"})

if __name__ == "__main__":
    # 启动MCP服务端(端口5000)
    print("MCP服务端已启动,监听端口 5000...")
    serve(port=5000, methods=[hello_world])

二、MCP客户端(Client)

# mcp_client.py
import requests

def call_mcp_hello():
    # 构建符合JSON-RPC 2.0标准的请求体
    payload = {
        "jsonrpc": "2.0",
        "method": "hello_world",  # 调用注册的工具名
        "params": {
            "context": {"user": "demo"}  # 安全上下文(示例)
        },
        "id": 1
    }

    # 发送请求到MCP服务端
    response = requests.post(
        "http://localhost:5000",
        json=payload,
        headers={"Content-Type": "application/json"}
    ).json()

    # 解析响应
    if "result" in response:
        return response["result"]["message"]
    else:
        return f"错误: {response['error']['message']}"

if __name__ == "__main__":
    result = call_mcp_hello()
    print("MCP服务端响应:", result)

三、运行流程

  1. 安装依赖(需Python 3.7+):

    pip install jsonrpcserver requests
  2. 启动服务端

    python mcp_server.py
    # 输出:MCP服务端已启动,监听端口 5000...
  3. 运行客户端

    python mcp_client.py
    # 输出:MCP服务端响应: Hello, MCP World!

四、关键代码解析

  1. 服务端核心逻辑

    • 使用 @method 装饰器注册工具方法 hello_world

    • 返回结构必须符合MCP标准:Success({"key": value})

    • 自动处理协议层细节(序列化/反序列化)

  2. 客户端核心逻辑

    • 请求体严格遵循JSON-RPC 2.0格式:

      {
        "jsonrpc": "2.0",
        "method": "方法名",
        "params": {"context": {}, ...},
        "id": 请求ID
      }
    • 响应体自动解析:

      {
        "jsonrpc": "2.0",
        "result": {"message": "Hello, MCP World!"},
        "id": 1
      }
  3. 协议扩展性

    • 新增工具只需在服务端添加新的 @method 方法

    • 客户端调用时只需修改 method 名称和参数

五、高级特性扩展

若需实现 动态工具发现,可添加以下代码:

# 在服务端添加工具元数据
@method
def list_tools() -> Result:
    return Success({
        "tools": [{
            "name": "hello_world",
            "description": "返回欢迎信息",
            "params": {}  # 无输入参数
        }]
    })

# 客户端查询可用工具
def discover_tools():
    response = requests.post(
        "http://localhost:5000",
        json={"jsonrpc": "2.0", "method": "list_tools", "id": 2}
    ).json()
    print("可用工具:", response["result"]["tools"])

运行后输出:

可用工具: [{'name': 'hello_world', 'description': '返回欢迎信息', 'params': {}}]

六、协议交互流程

sequenceDiagram
    participant Client as MCP客户端
    participant Server as MCP服务端

    Client->>Server: JSON-RPC请求
    Note over Server: 解析请求
执行hello_world方法 Server->>Client: JSON-RPC响应

七、示例场景:通过MCP实现AI模型调用数据库查询工具

# ---------- MCP 服务端 (Server) ----------
from jsonrpcserver import method, serve
import sqlite3

# 注册MCP工具:SQLite数据库查询
@method
def query_database(context: dict, sql: str) -> dict:
    """MCP协议标准工具接口:输入SQL语句,返回查询结果"""
    try:
        # 权限验证(示例)
        if not context.get("auth_token") == "SECRET_123":
            return {"error": "Permission denied"}
        
        # 连接数据库并执行查询
        conn = sqlite3.connect('demo.db')
        cursor = conn.cursor()
        cursor.execute(sql)
        results = cursor.fetchall()
        conn.close()
        
        # 返回MCP标准格式
        return {
            "status": "success",
            "data": results
        }
    except Exception as e:
        return {"status": "error", "message": str(e)}

if __name__ == "__main__":
    # 启动MCP服务端(端口5000)
    serve(port=5000, methods=[query_database])

# ---------- MCP 客户端 (Client) ----------
import requests

def mcp_client_call(sql_query: str) -> str:
    """通过MCP协议调用数据库工具"""
    # 构建JSON-RPC 2.0请求
    payload = {
        "jsonrpc": "2.0",
        "method": "query_database",
        "params": {
            "context": {"auth_token": "SECRET_123"},  # 安全上下文
            "sql": sql_query
        },
        "id": 1
    }
    
    # 发送请求到MCP服务端
    response = requests.post(
        "http://localhost:5000",
        json=payload,
        headers={"Content-Type": "application/json"}
    ).json()
    
    # 处理响应
    if "error" in response:
        return f"Error: {response['error']}"
    else:
        return response["result"]

# ---------- AI模型调用示例 ----------
# 用户提问:"显示最近3个月的订单数据"
# AI模型生成SQL并通过MCP调用工具
sql = "SELECT * FROM orders WHERE order_date >= DATE('now','-3 month')"
result = mcp_client_call(sql)
print("MCP查询结果:", result)

关键代码解析

  1. 服务端工具注册

    • 使用@method装饰器定义query_database方法,符合MCP的Tools规范

    • 内置权限验证(auth_token),体现MCP的安全控制

    • 返回结构遵循{status: "success"/"error", data: [...]}标准格式

  2. 客户端协议调用

    • 请求格式严格遵循JSON-RPC 2.0标准,包含methodparams字段

    • context参数传递安全凭证,支持细粒度权限管理

    • 通过HTTP协议与MCP服务端通信,支持跨网络调用

  3. AI模型集成

    • 模型只需生成标准化SQL语句,无需关心具体数据库连接细节

    • 通过MCP实现自然语言→工具调用→结构化数据的完整链路

以上,通过此示例,开发者可以快速理解MCP协议的核心交互模式,后续只需替换工具逻辑即可扩展复杂功能(如数据库操作、API调用等)。

你可能感兴趣的:(AI相关,ai,AI编程,自然语言处理)