模型上下文协议集成

Model Context Protocol (MCP) 是一个在Google ADK框架中使用的先进架构模式,用于将工具逻辑(服务器)与代理逻辑(客户端)解耦。

  • by Rex6961
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 Rex6961/MCPAgent

使用说明

# Model Context Protocol (MCP) Integration

This project demonstrates an advanced architectural pattern using the **Model Context Protocol (MCP)** within the Google ADK framework. Unlike standard Function Calling (where logic is embedded in the agent's code), this project decouples the **Tool Logic (Server)** from the **Agent Logic (Client)**.

## 🧠 Logic & Visualization

To understand MCP, we use the **"Universal USB Driver" Analogy**:

- **MCP Servers (The Flash Drives):** Standalone processes containing specific capabilities. We have two:
    1.  **Math Server:** Logic for calculations (`add_numbers`).
    2.  **Filesystem Server:** Logic for accessing local files (`list_files`).
- **MCP Client/Agent (The Computer):** Connects to the servers via standard ports (Stdio), "reads" the available tools, and dynamically adds them to its toolset.
- **Transport (The USB Cable):** The communication layer. In this project, we use standard input/output (`Stdio`) pipes to send JSON-RPC messages.

### Architecture Diagram

The Agent spawns multiple Servers as subprocesses and communicates via JSON-RPC protocol simultaneously.
sequenceDiagram
    participant Agent as ADK Agent (Client)
    participant Transport as Stdio Pipes
    participant Server1 as Math MCP Server
    participant Server2 as Filesystem MCP Server

    Note over Agent, Server2: Initialization Phase
    Agent->>Transport: Spawn Process 1 (simple_mcp.py)
    Agent->>Transport: Spawn Process 2 (filesystem_server.py)
    Server1-->>Agent: List Tools [add_numbers, get_time...]
    Server2-->>Agent: List Tools [list_files]

    Note over Agent, Server2: Execution Phase
    Agent->>Agent: LLM needs to calculate
    Agent->>Server1: JSON-RPC (add_numbers)
    Server1-->>Agent: Result (155)

    Agent->>Agent: LLM needs file list
    Agent->>Server2: JSON-RPC (list_files)
    Server2-->>Agent: Result (['file1.txt', 'src'...])

📂 项目结构

该项目遵循将服务器实现与代理消费者分离的模块化结构。

.
├── Makefile                        # Automation: install, lint, format, run
├── pyproject.toml                  # Dependencies (mcp, google-adk)
├── src
│   └── mcp_agent
│       ├── agent.py                # CLIENT: The ADK Agent that consumes tools
│       ├── config.py               # CONFIG: Pydantic settings
│       └── servers
│           ├── simple_mcp.py       # SERVER 1: Math & Time utilities
│           └── filesystem_server.py# SERVER 2: Filesystem operations
└── tests                           # Unit Tests

⚙️ 设置和安装

  1. 先决条件:Python 3.13+,安装了Poetry。
  2. 环境: 使用 Makefile 安装依赖项(包括 mcp SDK):
make install

  1. 配置: 创建 .env 根目录中的文件。此项目需要Google API密钥。
GOOGLE__API_KEY=your_actual_api_key
GOOGLE__GENAI_USE_VERTEXAI=false

🚀 用法

此命令启动Agent,Agent将在后台自动启动两个MCP服务器。

make run

预期输出

观察系统日志。您将看到代理连接、从多个来源发现工具并执行它们。

USER: Calculate 100 + 55 using the tools, and give the current time, and give files to the path '../', and then echo the result.
AGENT:
[SYSTEM: Calling MCP Tool 'add_numbers']
[SYSTEM: Calling MCP Tool 'get_current_time']
[SYSTEM: Calling MCP Tool 'list_files']
[SYSTEM: Calling MCP Tool 'get_echo']
Echo from MCP: 155, Time: 15/12/2025 10:00, Files: ['Makefile', 'pyproject.toml', 'src'...]
[SYSTEM: Closing MCP connection...]

💻 代码亮点

1.数学服务器(simple_mcp.py)

提供基本的计算逻辑。

@mcp.tool()
def add_numbers(a: int, b: int) -> int:
    return a + b

2.文件系统服务器(filesystem_server.py)

提供对操作系统层的访问。请注意,这是一个完全独立的文件/进程。

from mcp.server.fastmcp import FastMCP
import os

mcp = FastMCP("FileSystemServer")

@mcp.tool()
def list_files(directory: str) -> dict:
    """Echoes directories files."""
    return {"files": str(os.listdir(directory))}

3.代理客户(agent.py)

Agent通过定义多个连接参数连接到多个工具。

# 1. Define Servers
server_params_math = StdioServerParameters(command="python", args=[".../simple_mcp.py"])
server_params_fs = StdioServerParameters(command="python", args=[".../filesystem_server.py"])

# 2. Initialize Toolsets
math_toolset = McpToolset(connection_params=StdioConnectionParams(server_params_math))
fs_toolset = McpToolset(connection_params=StdioConnectionParams(server_params_fs))

# 3. Agent consumes both
agent = LlmAgent(
    name="McpConsumer",
    tools=[math_toolset, fs_toolset], # <--- Multi-source tools
    # ...
)

🏆 关键要点

  • 解耦: 您可以更改服务器代码(甚至用TypeScript重写),而无需更改代理的一行代码。
  • 安全: 代理人在自己的流程中运行;工具在另一个中运行。
  • 可扩展性: 我们演示了连接 多个MCP服务器 (数学+文件系统)无缝集成到单个代理。