Skip to main content
Glama

MCP + LangChain 演示

一个面向初学者的项目,演示如何构建 MCP(模型上下文协议) 服务器,并使用 LangChain 和 LangGraph 将其连接到 LLM 代理。


什么是 MCP?

MCP(模型上下文协议) 是一种开放协议,允许你以标准化的方式向 LLM 暴露自定义工具(函数)。可以将其视为 AI 模型的通用插件系统。

关键概念:

术语

定义

MCP 服务器

通过传输层(stdio 或 HTTP)暴露工具(函数)的进程。LLM 可以调用这些工具。

MCP 客户端

连接到一个或多个 MCP 服务器、发现其工具并将其转发给 LLM 的进程。

工具

使用 @mcp.tool() 装饰的 Python 函数,LLM 可以调用它。

传输层

客户端和服务器之间的通信方式。stdio = 通过 stdin/stdout 在同一台机器上通信。streamable-http = 通过 HTTP 通信。

FastMCP

来自 mcp 库的高级 Python 类,可轻松创建 MCP 服务器。


Related MCP server: Model Context Protocol Multi-Agent Server

项目结构

MCPLEARNING/
├── mathserver.py      # MCP Server 1 - Math tools (stdio transport)
├── weather.py         # MCP Server 2 - Weather tool (HTTP transport)
├── client.py          # LangChain agent that connects to both servers
├── .env               # API keys (NOT pushed to GitHub)
├── .gitignore
├── requirements.txt
└── pyproject.toml

工作原理(逐步说明)

第 1 步:MCP 服务器 — mathserver.py

此文件创建一个名为 "Math" 的 MCP 服务器,暴露两个工具:

  • add(a, b) — 返回两个整数的和。

  • multiply(a, b) — 返回两个整数的乘积。

它运行在 stdio 传输层上,意味着客户端将其作为子进程启动,并通过 stdin/stdout 进行通信。无需端口。

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("Math")

@mcp.tool()
def add(a: int, b: int) -> int:
    """Addition of two numbers"""
    return a + b

@mcp.tool()
def multiply(a: int, b: int) -> int:
    """Multiplication of two numbers"""
    return a * b

if __name__ == "__main__":
    mcp.run(transport="stdio")

第 2 步:MCP 服务器 — weather.py

此文件创建一个名为 "Weather" 的 MCP 服务器,暴露一个工具:

  • get_weather(location) — 返回指定位置的天气信息。

它运行在 streamable-http 传输层上,意味着它在 http://127.0.0.1:8000/mcp 上启动一个 Web 服务器。客户端通过 HTTP 连接到它。

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("Weather")

@mcp.tool()
async def get_weather(location: str) -> str:
    """Get the weather"""
    return "It's always raining in California"

if __name__ == "__main__":
    mcp.run(transport="streamable-http")

第 3 步:客户端代理 — client.py

这是项目的大脑。它:

  1. 连接到两个 MCP 服务器,使用 MultiServerMCPClient。

  2. 发现两个服务器的所有工具(add、multiply、get_weather)。

  3. 创建一个 Groq LLM(托管的开源模型)并将工具绑定到它。

  4. 构建一个 LangGraph 代理 — 一个状态机,其中:

    • LLM 决定是调用工具还是直接响应。

    • 如果调用了工具,结果会反馈给 LLM 以给出最终答案。

  5. 测试两个查询:

    • "What is 3 + 5?" → 使用 add 工具。

    • "What is the weather in California?" → 使用 get_weather 工具。


先决条件

  • Python 3.13+

  • uv 包管理器(推荐)或 pip

  • Groq API 密钥 — 在 console.groq.com 免费获取


设置

1. 克隆仓库

git clone https://github.com/<YOUR_USERNAME>/MCPLEARNING.git
cd MCPLEARNING

2. 创建并激活虚拟环境

# Using uv (recommended)
uv venv
uv pip install -r requirements.txt

# Or using pip
python -m venv .venv
.venv\Scripts\activate        # Windows
source .venv/bin/activate     # Mac/Linux
pip install -r requirements.txt

3. 设置你的 API 密钥

在项目根目录创建一个 .env 文件:

GROQ_API_KEY=your_groq_api_key_here

重要: 切勿提交你的 .env 文件。它已通过 .gitignore 排除。


运行项目

你需要打开 两个终端:

终端 1 — 启动天气 MCP 服务器

python weather.py

你应该看到:

INFO: Uvicorn running on http://127.0.0.1:8000

注意: 只有 weather.py 需要手动启动。mathserver.py 由客户端自动生成(stdio 传输层)。

终端 2 — 运行客户端

python client.py

预期输出

Available MCP tools:
- add
- multiply
- get_weather

==============================
Testing Math MCP
==============================

Math Response: 3 + 5 = 8.

==============================
Testing Weather MCP
==============================

Weather Response: It's always raining in California.

如何创建你自己的 MCP 服务器

  1. 安装 MCP 库:

pip install mcp
  1. 创建一个新的 Python 文件(例如 myserver.py):

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("MyServer")

@mcp.tool()
def my_tool(param: str) -> str:
    """Description of what this tool does."""
    return f"Result: {param}"

if __name__ == "__main__":
    mcp.run(transport="stdio")        # For stdio transport
    # mcp.run(transport="streamable-http")  # For HTTP transport
  1. 在客户端中连接它,通过将其添加到 MultiServerMCPClient 配置:

client = MultiServerMCPClient({
    "myserver": {
        "command": "python",
        "args": ["myserver.py"],
        "transport": "stdio",
    },
})

传输层比较

传输层

工作原理

使用场景

stdio

客户端将服务器作为子进程启动。通过 stdin/stdout 通信。

本地工具,简单设置,无需网络。

streamable-http

服务器作为 Web 服务器运行。客户端通过 HTTP 连接。

远程工具,多个客户端,跨机器访问。


使用的关键库

库

用途

mcp

使用 FastMCP 构建 MCP 服务器。

langchain-mcp-adapters

在 MCP 服务器和 LangChain 工具之间建立桥梁。

langchain-groq

用于 Groq 托管 LLM 的 LangChain 集成。

langgraph

将代理工作流构建为图(代理 ↔ 工具循环)。

python-dotenv

从 .env 文件加载 API 密钥。


需要注意的重要事项

  1. 天气服务器必须在客户端之前运行 — 由于它使用 HTTP 传输层,服务器进程必须首先启动。数学服务器(stdio)由客户端自动生成。

  2. 需要 Groq API 密钥 — 没有它,LLM 调用将失败。在 console.groq.com 获取免费密钥。

  3. 切勿提交 .env — 在推送代码之前,始终将 .env 添加到 .gitignore。

  4. 端口冲突 — 天气服务器默认在端口 8000 上运行。如果另一个进程使用该端口,服务器将无法启动。

  5. Windows 编码问题 — 在 Windows 上,控制台可能不支持 LLM 返回的 UTF-8 字符。client.py 通过 sys.stdout.reconfigure(encoding="utf-8") 处理此问题。

  6. 模型可用性 — Groq 模型名称(openai/gpt-oss-120b)必须在 Groq 平台上有效且可用。查看 Groq 的模型列表 了解当前选项。

Related MCP Connectors

Related MCP Servers