mcp-server-and-client-simple-demo

xdstone1on163/mcp-server-and-client-simple-demo

3.2

If you are the rightful owner of mcp-server-and-client-simple-demo and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to henry@mcphub.com.

This project provides example implementations of a Model Context Protocol (MCP) server and client.

Tools
2
Resources
0
Prompts
0

MCP 服务器和客户端示例

这个项目包含了 Model Context Protocol (MCP) 服务器和客户端的示例实现。

文件说明

  • server.py: MCP 服务器实现,可以以 stdio 或 HTTP 流式传输模式运行
  • client.py: 使用 stdio 连接到服务器的客户端
  • http_client.py: 使用 HTTP 连接到服务器的客户端

运行服务器

以 stdio 模式运行

修改 server.py 文件,取消注释 stdio 模式的行,注释 HTTP 模式的行:

mcp.run()             # stdio
# mcp.run(transport="streamable-http", host="0.0.0.0", port=8000)  # HTTP 可流式传输

然后运行服务器:

python server.py

以 HTTP 流式传输模式运行

修改 server.py 文件,注释 stdio 模式的行,取消注释 HTTP 模式的行:

# mcp.run()             # stdio
mcp.run(transport="streamable-http")  # HTTP 可流式传输

然后运行服务器:

python server.py

运行客户端

使用 stdio 客户端

如果服务器以 stdio 模式运行,使用 client.py

python client.py

使用 HTTP 客户端

如果服务器以 HTTP 流式传输模式运行,使用 http_client.py

python http_client.py

服务器功能

服务器提供以下功能:

  1. 工具 (Tools):

    • add: 简单的加法函数
    • long_task: 异步任务示例
  2. 资源 (Resources):

    • config://settings: 返回 JSON 配置
    • greeting://{name}: 动态问候资源
  3. 提示模板 (Prompts):

    • welcome_prompt: 可参数化的欢迎提示

HTTP 客户端与 stdio 客户端的区别

当服务器以 HTTP 流式传输模式运行时,客户端需要使用 HTTP 客户端连接到服务器。主要区别在于:

  1. 导入不同的客户端模块:

    • stdio: from mcp.client.stdio import stdio_client
    • HTTP: from mcp.client.streamable_http import streamablehttp_client
  2. 连接方式不同:

    • stdio: 启动服务器进程并通过标准输入/输出连接
    params = StdioServerParameters(command="python", args=["server.py"])
    async with stdio_client(params) as (read_stream, write_stream):
    
    • HTTP: 连接到 HTTP 服务器
    server_url = "http://localhost:8000/mcp/"
    async with streamablehttp_client(server_url) as (read_stream, write_stream, get_session_id):
    
  3. 参数不同:

    • stdio: 需要指定命令和参数
    • HTTP: 需要指定服务器 URL

其他部分(初始化、列出工具/资源/提示、调用工具、读取资源)的代码是相同的,因为 MCP 协议是传输方式无关的。