Skip to main content
Glama
SyDd0
by SyDd0

自定义 MCP Server — 从零理解 MCP 协议

这是什么?

一个从头手写的 MCP (Model Context Protocol) 工具服务器,包含 6 个实用工具。

配合 LangChain Agent 客户端,完整演示了 MCP 协议的核心工作流

MCP Server (工具提供方)          LangChain Agent (工具消费方)
─────────────────────────        ───────────────────────────
定义工具 + 参数 Schema    ←→     自动发现工具 (tools/list)
等待工具调用              ←→     调用工具 (tools/call)
返回执行结果              ←→     LLM 推理 → 最终回答

Related MCP server: SampleMCP

项目结构

my-mcp-server/
├── mcp_server.py      # MCP Server: 6 个工具, 支持 HTTP/stdio 双模式
├── agent_client.py    # LangChain Agent: 自动发现并调用 MCP 工具
├── pyproject.toml     # 依赖清单
├── .env.example       # 环境变量模板
└── README.md          # 你正在看的文件

快速开始

1. 安装依赖

pip install fastmcp langchain langchain-openai langchain-mcp-adapters python-dotenv

2. 设置 API Key

cp .env.example .env
# 编辑 .env, 填入你的 OPENAI_API_KEY

3. 启动 MCP Server

# 终端 1: HTTP 模式 (推荐,方便调试)
python mcp_server.py --transport http --port 8000

4. 运行 Agent 客户端

# 终端 2: 交互模式
python agent_client.py

# 或者单次提问
python agent_client.py "帮我搜索当前目录下所有的 Python 文件"

包含的工具

工具名

功能

示例

search_files

按文件名模式搜索本地文件

"找所有 .py 文件"

read_text_file

读取文本文件内容

"读取 README.md"

calculate

安全的数学表达式求值

"计算 3+5*7"

json_formatter

JSON 格式化/美化

"格式化这段 JSON"

get_current_time

查询当前时间 (支持时区)

"现在几点了?"

system_info

查看系统信息

"我的系统是什么?"

MCP 协议核心概念

tools/list — 工具发现

Agent 启动时调用,服务器返回所有可用工具的清单。每个工具包含:

  • name: 工具名 (如 calculate)

  • description: 功能描述 (LLM 读这个来决定要不要用)

  • inputSchema: 参数定义 (JSON Schema 格式,描述每个参数的类型、是否必填)

tools/call — 工具调用

Agent 决定使用某个工具时调用,传入工具名和参数。服务器执行后返回结果。

为什么不用硬编码?

传统做法:

# 每加一个工具都要改 Agent 代码
tools = [calculator_tool, search_tool, ...]  # 硬编码

MCP 做法:

# Agent 启动时自动发现工具,不用改代码
mcp_client = MultiServerMCPClient({"server": {"url": "..."}})
tools = await mcp_client.get_tools()  # 自动发现!

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    C
    maintenance
    A general-purpose MCP server with utility tools including datetime information, safe math calculations, text statistics, JSON extraction, knowledge base search, and HTTP GET requests. It demonstrates server-side MCP implementation and can be connected to Claude Desktop or LangGraph agents.
    MIT
  • F
    license
    Not graded
    quality
    D
    maintenance
    An MCP server with six tools including web search, URL fetching, math calculation, and note management. Designed for a live-coding demo integrating FastMCP with LangGraph ReAct agents.
    8
    -
  • F
    license
    Not graded
    quality
    D
    maintenance
    A proof-of-concept MCP server that enables LLMs to read local text files and fetch real-time weather data through external tools.
    -