Model Context Protocol Tools¶
模型上下文协议工具¶
This guide walks you through two ways of integrating Model Context Protocol (MCP) with ADK.
本指南将介绍两种将模型上下文协议 (MCP) 与 ADK 集成的方法。
What is Model Context Protocol (MCP)?¶
什么是模型上下文协议 (MCP)?¶
The Model Context Protocol (MCP) is an open standard designed to standardize how Large Language Models (LLMs) like Gemini and Claude communicate with external applications, data sources, and tools. Think of it as a universal connection mechanism that simplifies how LLMs obtain context, execute actions, and interact with various systems.
模型上下文协议 (MCP) 是一个开放标准,旨在标准化大型语言模型 (LLM)(如 Gemini 和 Claude) 与外部应用程序、数据源和工具的通信方式。可以将其视为一个通用连接机制,简化了 LLM 获取上下文、执行操作以及与各种系统交互的方式。
MCP follows a client-server architecture, defining how data (resources), interactive templates (prompts), and actionable functions (tools) are exposed by an MCP server and consumed by an MCP client (which could be an LLM host application or an AI agent).
MCP 遵循客户端-服务器架构,定义了 数据 (资源)、交互模板 (提示词) 和 可操作函数 (工具) 如何由 MCP 服务器 公开并由 MCP 客户端 (可能是 LLM 主机应用程序或 AI 智能体) 使用。
This guide covers two primary integration patterns:
本指南涵盖两种主要的集成模式:
- Using Existing MCP Servers within ADK: An ADK agent acts as an MCP client, leveraging tools provided by external MCP servers.
- 在 ADK 中使用现有 MCP 服务器: ADK 智能体充当 MCP 客户端,利用外部 MCP 服务器提供的工具。
- Exposing ADK Tools via an MCP Server: Building an MCP server that wraps ADK tools, making them accessible to any MCP client.
- 通过 MCP 服务器公开 ADK 工具: 构建一个包装 ADK 工具的 MCP 服务器,使它们可供任何 MCP 客户端访问。
Prerequisites¶
先决条件¶
Before you begin, ensure you have the following set up:
在开始之前,请确保您已完成以下设置:
- Set up ADK: Follow the standard ADK setup instructions in the quickstart.
- 设置 ADK: 按照快速入门中的标准 ADK 设置说明 操作。
- Install/update Python/Java: MCP requires Python version of 3.9 or higher for Python or Java 17 or higher.
- 安装/更新 Python/Java: MCP 需要 Python 版本为 3.9 或更高版本,或 Java 17 或更高版本。
- Setup Node.js and npx: (Python only) Many community MCP servers are distributed as Node.js packages and run using
npx. Install Node.js (which includes npx) if you haven't already. For details, see https://nodejs.org/en. - 设置 Node.js 和 npx: (仅 Python) 许多社区 MCP 服务器作为 Node.js 包分发,并使用
npx运行。如果尚未安装,请安装 Node.js (包括 npx)。有关详细信息,请参阅 https://nodejs.org/en。 - Verify Installations: (Python only) Confirm
adkandnpxare in your PATH within the activated virtual environment: - 验证安装: (仅 Python) 确认
adk和npx在激活的虚拟环境中的 PATH 内:
1. Using MCP servers with ADK agents (ADK as an MCP client) in adk web¶
1. 在 adk web 中使用 MCP 服务器 (ADK 作为 MCP 客户端)¶
This section demonstrates how to integrate tools from external MCP (Model Context Protocol) servers into your ADK agents. This is the most common integration pattern when your ADK agent needs to use capabilities provided by an existing service that exposes an MCP interface. You will see how the McpToolset class can be directly added to your agent's tools list, enabling seamless connection to an MCP server, discovery of its tools, and making them available for your agent to use. These examples primarily focus on interactions within the adk web development environment.
本节演示如何将外部 MCP (模型上下文协议) 服务器的工具集成到您的 ADK 智能体中。这是当您的 ADK 智能体需要使用公开 MCP 接口的现有服务提供的功能时的 最常见 集成模式。您将看到 McpToolset 类如何直接添加到智能体的 tools 列表中,从而实现与 MCP 服务器的无缝连接、工具发现,并使它们可供智能体使用。这些示例主要关注 adk web 开发环境中的交互。
McpToolset class¶
McpToolset 类¶
The McpToolset class is ADK's primary mechanism for integrating tools from an MCP server. When you include an McpToolset instance in your agent's tools list, it automatically handles the interaction with the specified MCP server. Here's how it works:
McpToolset 类是 ADK 从 MCP 服务器集成工具的主要机制。当您在智能体的 tools 列表中包含 McpToolset 实例时,它会自动处理与指定 MCP 服务器的交互。其工作原理如下:
- Connection Management: On initialization,
McpToolsetestablishes and manages the connection to the MCP server. This can be a local server process (usingStdioConnectionParamsfor communication over standard input/output) or a remote server (usingSseConnectionParamsfor Server-Sent Events). The toolset also handles the graceful shutdown of this connection when the agent or application terminates.- 连接管理: 在初始化时,
McpToolset建立并管理与 MCP 服务器的连接。这可以是本地服务器进程 (使用StdioConnectionParams通过标准输入/输出进行通信) 或远程服务器 (使用SseConnectionParams进行服务器发送事件)。当智能体或应用程序终止时,工具集还会处理此连接的正常关闭。
- 连接管理: 在初始化时,
- Tool Discovery & Adaptation: Once connected,
McpToolsetqueries the MCP server for its available tools (via thelist_toolsMCP method). It then converts the schemas of these discovered MCP tools into ADK-compatibleBaseToolinstances.- 工具发现和适配: 连接后,
McpToolset查询 MCP 服务器以获取其可用工具 (通过list_toolsMCP 方法)。然后,它将这些发现的 MCP 工具的模式转换为 ADK 兼容的BaseTool实例。
- 工具发现和适配: 连接后,
- Exposure to Agent: These adapted tools are then made available to your
LlmAgentas if they were native ADK tools.- 向智能体公开: 这些适配的工具随后可供您的
LlmAgent使用,就像它们是原生 ADK 工具一样。
- 向智能体公开: 这些适配的工具随后可供您的
- Proxying Tool Calls: When your
LlmAgentdecides to use one of these tools,McpToolsettransparently proxies the call (using thecall_toolMCP method) to the MCP server, sends the necessary arguments, and returns the server's response back to the agent.- 代理工具调用: 当您的
LlmAgent决定使用这些工具之一时,McpToolset透明地将调用 (使用call_toolMCP 方法) 代理到 MCP 服务器,发送必要的参数,并将服务器的响应返回给智能体。
- 代理工具调用: 当您的
- Filtering (Optional): You can use the
tool_filterparameter when creating anMcpToolsetto select a specific subset of tools from the MCP server, rather than exposing all of them to your agent.- 筛选 (可选): 您可以在创建
McpToolset时使用tool_filter参数从 MCP 服务器中选择特定的工具子集,而不是将所有工具都公开给您的智能体。
- 筛选 (可选): 您可以在创建
The following examples demonstrate how to use McpToolset within the adk web development environment. For scenarios where you need more fine-grained control over the MCP connection lifecycle or are not using adk web, refer to the "Using MCP Tools in your own Agent out of adk web" section later in this page.
以下示例演示如何在 adk web 开发环境中使用 McpToolset。对于需要更精细控制 MCP 连接生命周期或不使用 adk web 的场景,请参阅本页面后面的 "在自己的智能体中使用 MCP 工具 (不在 adk web 中)" 部分。
Example 1: File System MCP Server¶
示例 1: 文件系统 MCP 服务器¶
This Python example demonstrates connecting to a local MCP server that provides file system operations.
此 Python 示例演示如何连接到提供文件系统操作的本地 MCP 服务器。
Step 1: Define your Agent with McpToolset¶
步骤 1: 使用 McpToolset 定义您的智能体¶
Create an agent.py file (e.g., in ./adk_agent_samples/mcp_agent/agent.py). The McpToolset is instantiated directly within the tools list of your LlmAgent.
创建一个 agent.py 文件 (例如,在 ./adk_agent_samples/mcp_agent/agent.py 中)。McpToolset 直接在 LlmAgent 的 tools 列表中实例化。
- Important: Replace
"/path/to/your/folder"in theargslist with the absolute path to an actual folder on your local system that the MCP server can access.- 重要: 将
args列表中的"/path/to/your/folder"替换为 MCP 服务器可以访问的本地系统上实际文件夹的 绝对路径。
- 重要: 将
- Important: Place the
.envfile in the parent directory of the./adk_agent_samplesdirectory.- 重要: 将
.env文件放在./adk_agent_samples目录的父目录中。
- 重要: 将
```python
./adk_agent_samples/mcp_agent/agent.py¶
import os # Required for path operations # 用于路径操作 from google.adk.agents import LlmAgent from google.adk.tools.mcp_tool import McpToolset from google.adk.tools.mcp_tool.mcp_session_manager import StdioConnectionParams from mcp import StdioServerParameters
It's good practice to define paths dynamically if possible,¶
如果可能,最好动态定义路径,¶
or ensure the user understands the need for an ABSOLUTE path.¶
或确保用户理解绝对路径的必要性。¶
For this example, we'll construct a path relative to this file,¶
对于此示例,我们将构建相对于此文件的路径,¶
assuming '/path/to/your/folder' is in the same directory as agent.py.¶
假设 '/path/to/your/folder' 与 agent.py 在同一目录中。¶
REPLACE THIS with an actual absolute path if needed for your setup.¶
如果您的设置需要,请将其替换为实际的绝对路径。¶
TARGET_FOLDER_PATH = os.path.join(os.path.dirname(os.path.abspath(file)), "/path/to/your/folder")
Ensure TARGET_FOLDER_PATH is an absolute path for the MCP server.¶
确保 TARGET_FOLDER_PATH 是 MCP 服务器的绝对路径。¶
If you created ./adk_agent_samples/mcp_agent/your_folder,¶
如果您创建了 ./adk_agent_samples/mcp_agent/your_folder,¶
root_agent = LlmAgent( model='gemini-2.0-flash', name='filesystem_assistant_agent', instruction='Help the user manage their files. You can list files, read files, etc.', tools=[ McpToolset( connection_params=StdioConnectionParams( server_params = StdioServerParameters( command='npx', args=[ "-y", # Argument for npx to auto-confirm install # npx 自动确认安装的参数 "@modelcontextprotocol/server-filesystem", # IMPORTANT: This MUST be an ABSOLUTE path to a folder the # 重要:这必须是 npx 进程可以访问的文件夹的绝对路径。 # npx process can access. # Replace with a valid absolute path on your system. # 替换为系统上有效的绝对路径。 # For example: "/Users/youruser/accessible_mcp_files" # 例如:"/Users/youruser/accessible_mcp_files" # or use a dynamically constructed absolute path: # 或使用动态构造的绝对路径: os.path.abspath(TARGET_FOLDER_PATH), ], ), ), # Optional: Filter which tools from the MCP server are exposed # 可选:筛选要公开的 MCP 服务器的哪些工具