LangChain接入Filesystem-MCP工具

发布时间:2026-03-18 21:00:25编辑:123阅读(8)

    LangChain接入Filesystem-MCP工具


    Filesystem MCP工具接入

    接下来借助创建好的MCP客户端,仅需填写MCP配置,即可非常便捷的接入更多MCP工具。这里以github上的Filesystem MCP工具为例进行演示。Filesystem服务器时一个最基础同时也是最常用的MCP服务器,同时也是官方推荐的服务器。

    服务器项目地址:https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem

    借助Filesystem,我们可以高效便捷操作本地文件夹。同时Filesystem也是一个js项目.

    源码托管在npm平台上:https://www.npmjs.com/package/@modelcontextprotocol/server-filesystem

    仅需要填写如下配置,即可使用Filesystem MCP:

    {
      "mcpServers": {
        "filesystem": {
          "command": "npx",
          "args": [
            "-y",
            "@modelcontextprotocol/server-filesystem",
            "/path/to/other/allowed/dir"
          ]
        }
      }
    }

    在servers_config.json中写入MCP工具配置:

    {
      "mcpServers": {
        "weather": {
          "command": "python",
          "args": ["weather_server.py"],
          "transport": "stdio"
        },
        "filesystem": {
          "command": "npx",
          "args": [
            "-y",
            "@modelcontextprotocol/server-filesystem",
            "D:\\mcp_demo"
          ], 
          "transport": "stdio"
        }
      }
    }


    client.py

    import asyncio
    import json
    from langchain_ollama import ChatOllama
    from typing import Any,Dict
    from langchain.agents import create_agent
    from langchain_mcp_adapters.client import MultiServerMCPClient
    from langgraph.checkpoint.memory import InMemorySaver
    
    # 设置记忆存储
    checkpointer = InMemorySaver()
    
    # 读取提示词
    with open("./agent_prompts.txt", mode='r', encoding='utf-8') as f:
        prompt = f.read()
    
    # 设置对话配置
    config = {
        "configurable":{
            "thread_id":"2"
        }
    }
    
    class Configuration:
        @staticmethod
        def load_servers(file_path: str = "servers_config.json") -> Dict[str, Any]:
            with open(file_path, mode='r', encoding='utf-8') as f:
                return json.load(f).get("mcpServers", {})
    
    async def run_chat_loop():
        """启动 MCP-Agent 聊天循环"""
        cfg = Configuration()
        servers_cfg = Configuration.load_servers()
        # 连接多台MCP服务器
        mcp_client = MultiServerMCPClient(servers_cfg)
        _tools = await mcp_client.get_tools()
        print(f"已加载{len(_tools)}个MCP工具:{[t.name for t in _tools]}")
    
        # 初始化大模型
        model = ChatOllama(
        model="qwen3:8b",
        temperature=0,
        top_p=0.95,
        )
    
        # 构造 LangGraph Agent
        agent = create_agent(
            model=model,
            tools=_tools,
            system_prompt=prompt,
            checkpointer=checkpointer
        )
        print("\n MCP Agent 已启动,输入'quit'退出")
        while True:
            user_input = input("\n你:").strip()
            if user_input.lower() == "quit":
                break
            try:
                result = await agent.ainvoke(
                    {"messages": [{"role":"user", "content":user_input}]},
                    config
                )
                print(f"\nAI:{result['messages'][-1].content}")
            except Exception as e:
                print(f"\n 错误:{e}")
    
    if __name__ == '__main__':
        asyncio.run(run_chat_loop())

    运行client.py执行结果如下:

    已加载15个MCP工具:['query_weather', 'read_file', 'read_text_file', 'read_media_file', 'read_multiple_files', 'write_file', 

    'edit_file', 'create_directory', 'list_directory', 'list_directory_with_sizes', 'directory_tree', 'move_file', 'search_files', 

    'get_file_info', 'list_allowed_directories']


     MCP Agent 已启动,输入'quit'退出

    你:目录下有几个文件

    AI:请提供具体的目录路径,以便我查询该目录下的文件数量。


    你:目录路径 D:\\mcp_demo

    AI:目录 D:\mcp_demo 下共有 6 个文件:

    1. agent_prompts.txt

    2. client.py

    3. servers_config.json

    4. weather_server.py

    5. write_server.py

    6. output (目录)

    需要查看具体文件内容或目录结构吗?


    你:创建一个名为demo.txt的文件,并把当前目录下的文件名以及文件大小都写入到demo.txt中

    AI:已成功创建 `D:\mcp_demo\demo.txt` 文件,内容如下:

    ```

    agent_prompts.txt 517

    client.py 1986

    output 0

    servers_config.json 215

    weather_server.py 4568

    write_server.py 3218

    ```

    > 说明:`output` 是目录,因此大小显示为 `0`。如果需要包含子文件夹内的文件列表,可以补充说明哦!


关键字