文件系统代理 - MCP 集成 本示例演示了如何使用 将 ADK 代理连接到 文件系统 MCP 服务器。该代理可通过模型上下文协议执行文件操作,例如读取、写入和列出文件。 本示例展示的内容 MCP 服务器连接:连接到 文件操作:读取、写入、列出文件和目录 标准输入输出通信:使用标准输入输出与本地 MCP 服务器进行通信 自动工具发现:让 ADK 发现并使用可用的文件系统工具 工作原理 MCP 服务器设置 代理连接到提供以下工具的文件系统 MCP 服务器: :列出文件和文件夹 :读取文件内容 :将内容写入文件 :创建新目录 连接流程 开始使用 先决条件 Node.
本示例演示了如何使用 MCPToolset 将 ADK 代理连接到 文件系统 MCP 服务器。该代理可通过模型上下文协议执行文件操作,例如读取、写入和列出文件。
@modelcontextprotocol/server-filesystem代理连接到提供以下工具的文件系统 MCP 服务器:
list_directory:列出文件和文件夹read_file:读取文件内容write_file:将内容写入文件create_directory:创建新目录MCPToolset( connection_params=StdioServerParameters( command='npx', args=['-y', '@modelcontextprotocol/server-filesystem', '/path/to/folder'] ) )
requirements.txt 安装导航到教程根目录:
cd ai_agent_framework_crash_course/google_adk_tutorials/
启动 ADK Web:
adk web
选择代理:从下拉菜单中选择 filesystem_mcp_agent
测试命令:
User: List files in the current directory Agent: I'll list the files in the current directory for you. [Uses list_directory tool] Found the following files: - sample.txt - hello.txt
User: Read the contents of sample.txt Agent: I'll read the contents of sample.txt for you. [Uses read_file tool] The file contains: This is a sample file for the MCP filesystem agent demonstration. You can read, write, and list files using MCP tools.
User: Create a new file called notes.txt with the content "Meeting notes for today" Agent: I'll create the file notes.txt with your specified content. [Uses write_file tool] Successfully created notes.txt with the content "Meeting notes for today".
root_agent = LlmAgent( model='gemini-3-flash-preview', name='filesystem_mcp_agent', instruction=""" You are a helpful filesystem assistant that can help users manage their files. You have access to filesystem tools through the Model Context Protocol (MCP). """, tools=[ MCPToolset( connection_params=StdioServerParameters( command='npx', args=['-y', '@modelcontextprotocol/server-filesystem', DEMO_FOLDER] ) ) ] )
代理使用代理文件的父目录进行演示:
sample.txt文件系统 MCP 服务器会自动提供以下工具:
| 工具 | 描述 | 参数 |
|---|---|---|
list_directory |
列出文件和文件夹 | path(可选) |
read_file |
读取文件内容 | path(必填) |
write_file |
将内容写入文件 | path, content |
create_directory |
创建新目录 | path |
MCPToolset( connection_params=StdioServerParameters( command='npx', args=['-y', '@modelcontextprotocol/server-filesystem', DEMO_FOLDER] ), tool_filter=['list_directory', 'read_file'] # Only expose specific tools )
npx 运行未找到 Node.js:
# Install Node.js # macOS: brew install node # Ubuntu: sudo apt install nodejs npm
权限错误:
MCP 服务器未启动:
# Test MCP server directly npx @modelcontextprotocol/server-filesystem /path/to/folder # Run with debug logging adk web --debug
在尝试本示例后:
DEMO_FOLDER 更改为您的首选位置免责声明:
本文档采用基于机器的 AI 翻译服务进行翻译。尽管我们力求准确,但请注意,自动翻译可能存在错误或不准确之处。应以原文语言版本的原始文档作为权威依据。如需获取关键信息,建议使用专业的人工翻译。对于因使用本翻译而产生的任何误解或误读,我们概不负责。