DeepMCPAgent:通用AI智能体框架,无需编程动态调用MCP工具,支持LangChain与LangGraph集成,轻松扩展多步骤复杂任务

一句话简介DeepMCPAgent 是一款通用 AI 智能体框架,通过 MCP 动态发现与调用外部工具,无需编程 即可规划与执行,支持 LangChain / LangGraph 无缝集成,默认回退 LangGraph-ReAct,安装 DeepAgents 即可启用高级多步骤/长链条任务模式,易扩展可插拔兼容主流 LLM

DeepMCPAgent 是一个通用 AI 智能体框架,通过 MCP 动态发现和调用外部工具,无需编程,支持 LangChain 和 LangGraph,提供两种智能体逻辑,易于扩展,允许随时增加或更新工具。

logo


不用写工具,MCP服务器里现抓现用的通用AI智能体框架:DeepMCPAgent
它通过 MCP 来动态发现和调用外部工具,然后规划、调用,无需编程。
与 LangChain 和 LangGraph 无缝集成,兼容主流 LLM。
它提供两种智能体逻辑,默认回退到 LangGraph-ReAct;额外安装 DeepAgents,即可启用高级模式,可处理多步骤、长链条的复杂任务。
好处是极易扩展,可以随时增加、删除或更新工具,完全不需要修改主程序。
fork 开源仓库 githubhttps://github.com/MaoTouHU/DeepMCPAgent


一、为什么选择 DeepMCPAgent(Why DeepMCPAgent?)

  • 🔌 无需手动接线工具 —— 通过 MCP 服务器(HTTP/SSE)动态发现工具并自动接入
  • 🌐 天然支持外部 API —— 可连接远程 MCP 服务器(支持自定义请求头/鉴权)
  • 🧠 模型无关(Model-agnostic) —— 可直接传入任意 LangChain 聊天模型实例(OpenAI、Anthropic、Ollama、Groq、本地模型等)
  • DeepAgents(可选) —— 安装后获得更强的深度代理循环;未安装则稳健回退至 LangGraph ReAct
  • 🛠️ 强类型工具参数 —— 以 JSON-Schema → Pydantic → LangChain BaseTool 构建,保障参数类型化与校验
  • 🧪 工程质量标准 —— 内置 mypy(严格模式)、ruff、pytest、GitHub Actions 与文档体系

MCP 优先。 智能体不应把工具“写死”在代码里,而应动态发现按需调用。DeepMCPAgent 正是连接这一能力的桥梁。


二、安装(Installation)

PyPI 安装:

pip install "deepmcpagent[deep]"

以上命令会安装带 DeepAgents 支持(推荐) 的 DeepMCPAgent,以获得更强的代理循环。
其他可选扩展(extras):

  • dev → 代码规范/类型检查/测试工具
  • docs → 文档站(MkDocs + Material + mkdocstrings)
  • examples → 示例所需的依赖
# 同时安装 deepagents 与开发工具链
pip install "deepmcpagent[deep,dev]"

⚠️ 如果你使用 zsh,请务必对 extras 参数加引号:

pip install "deepmcpagent[deep,dev]"

三、快速开始(Quickstart)

1)启动示例 MCP Server(HTTP)

python examples/servers/math_server.py

This serves an MCP endpoint at: http://127.0.0.1:8000/mcp

2)运行示例 Agent(带控制台富输出)

python examples/use_agent.py

你会看到:

在这里插入图片描述


四、自带模型 & 外挂模型(BYOM:Bring-Your-Own Model)

DeepMCPAgent 允许你传入 任意 LangChain Chat 模型实例(或使用 provider id 字符串给 init_chat_model):

import asyncio
from deepmcpagent import HTTPServerSpec, build_deep_agent

# choose your model:
# from langchain_openai import ChatOpenAI
# model = ChatOpenAI(model="gpt-4.1")

# from langchain_anthropic import ChatAnthropic
# model = ChatAnthropic(model="claude-3-5-sonnet-latest")

# from langchain_community.chat_models import ChatOllama
# model = ChatOllama(model="llama3.1")

async def main():
    servers = {
        "math": HTTPServerSpec(
            url="http://127.0.0.1:8000/mcp",
            transport="http",    # or "sse"
            # headers={"Authorization": "Bearer <token>"},
        ),
    }

    graph, _ = await build_deep_agent(
        servers=servers,
        model=model,
        instructions="Use MCP tools precisely."
    )

    out = await graph.ainvoke({"messages":[{"role":"user","content":"add 21 and 21 with tools"}]})
    print(out)

asyncio.run(main())

Tip: If you pass a string like "openai:gpt-4.1", we’ll call LangChain’s init_chat_model() for you (and it will read env vars like OPENAI_API_KEY). Passing a model instance gives you full control.


五、命令行(CLI:无需写 Python)

# list tools from one or more HTTP servers
deepmcpagent list-tools \
  --http name=math url=http://127.0.0.1:8000/mcp transport=http \
  --model-id "openai:gpt-4.1"

# interactive agent chat (HTTP/SSE servers only)
deepmcpagent run \
  --http name=math url=http://127.0.0.1:8000/mcp transport=http \
  --model-id "openai:gpt-4.1"

The CLI accepts repeated --http blocks; add header.X=Y pairs for auth:

--http name=ext url=https://api.example.com/mcp transport=http header.Authorization="Bearer TOKEN"

六、架构总览(Architecture at a glance)

┌────────────────┐        list_tools / call_tool        ┌─────────────────────────┐
│ LangChain/LLM  │  ──────────────────────────────────▶ │ FastMCP Client (HTTP/SSE)│
│  (your model)  │                                      └───────────┬──────────────┘
└──────┬─────────┘  tools (LC BaseTool)                               │
       │                                                              │
       ▼                                                              ▼
  LangGraph Agent                                    One or many MCP servers (remote APIs)
  (or DeepAgents)                                    e.g., math, github, search, ...
  • HTTPServerSpec(...)FastMCP client (single client, multiple servers)
  • Tool discovery → JSON-Schema → Pydantic → LangChain BaseTool
  • Agent loop → DeepAgents(若已安装)或 LangGraph ReAct(默认回退)

七、完整架构 & 运行流程(Mermaid 图示)

1)High-level Architecture(模块与数据流)

🌐 FastMCP Client
🧰 Tooling Layer (MCP)
🤖 Agent Runtime
👤 User / App
query
query
list_tools
messages
tool calls
call_tool
tool result
final answer
final answer
🛠 MCP Servers (HTTP/SSE)
Server A
(e.g., math)
Server B
(e.g., search)
Server C
(e.g., github)
servers_to_mcp_config()
(mcpServers dict)
FastMCPMulti
(fastmcp.Client)
MCPToolLoader
(JSON-Schema ➜ Pydantic ➜ BaseTool)
_FastMCPTool
(async _arun → client.call_tool)
build_deep_agent()
prompt.py
(DEFAULT_SYSTEM_PROMPT)
Agent Graph
DeepAgents loop
(if installed)
LangGraph ReAct
(fallback)
LangChain Model
(instance or init_chat_model(provider-id))
LangChain Tools
(BaseTool[])
Prompt / Task
CLI (Typer)
Python API

2)Runtime Sequence(端到端调用)

User CLI/Python build_deep_agent() MCPToolLoader Agent Graph (DeepAgents or ReAct) LangChain Model _FastMCPTool FastMCP Client MCP Server (HTTP/SSE) Enter prompt 1 build_deep_agent(servers, model, instructions?) 2 get_all_tools() 3 list_tools() 4 HTTP(S)/SSE list_tools 5 tools + JSON-Schema 6 tool specs 7 BaseTool[] 8 (Graph, Loader) 9 ainvoke({messages:[user prompt]}) 10 Reason over system + messages + tool descriptions 11 Tool call (e.g., add(a=3,b=5)) 12 _arun(a=3,b=5) 13 call_tool("add", {a:3,b:5}) 14 POST /mcp tools.call("add", {...}) 15 result { data: 8 } 16 result 17 ToolMessage(content=8) 18 Continue with observations 19 Final response "(3 + 5) * 7 = 56" 20 messages (incl. final LLM answer) 21 User CLI/Python build_deep_agent() MCPToolLoader Agent Graph (DeepAgents or ReAct) LangChain Model _FastMCPTool FastMCP Client MCP Server (HTTP/SSE)

3)Agent Control Loop(规划-行动-观测)

if tool needed
if direct answer sufficient
receive tool result
yes
no
Discover MCP tools via FastMCP
(JSON-Schema ➜ Pydantic ➜ BaseTool)
LLM plans next step
(uses system prompt + tool descriptions)
_FastMCPTool._arun
→ client.call_tool(name, args)
LLM crafts final message
Parse result payload (data/text/content)
More tools needed?

4)Code Structure(类型关系)

uses servers_to_mcp_config()
creates
discovery
tools for agent
StdioServerSpec
+command: str
+args: List[str]
+env: Dict[str,str]
+cwd: Optional[str]
+keep_alive: bool
HTTPServerSpec
+url: str
+transport: Literal["http","streamable-http","sse"]
+headers: Dict[str,str]
+auth: Optional[str]
FastMCPMulti
-_client: fastmcp.Client
+client()
MCPToolLoader
-_multi: FastMCPMulti
+get_all_tools()
+list_tool_info()
_FastMCPTool
+name: str
+description: str
+args_schema: Type[BaseModel]
-_tool_name: str
-_client: Any
+_arun(**kwargs) : async
ToolInfo
+server_guess: str
+name: str
+description: str
+input_schema: Dict[str,Any]
build_deep_agent
+servers: Mapping[str,ServerSpec]
+model: ModelLike
+instructions?: str
+returns:(graph, loader)
ServerSpec
BaseTool

5)部署与集成视图(边界与耦合)

MCP Servers
Network
LLM Provider(s)
Your App / Service
mcpServers
init_chat_model or model instance
Service A (HTTP)
/path: /mcp
Service B (SSE)
/path: /mcp
Service C (HTTP)
/path: /mcp
FastMCP Client
(HTTP/SSE)
OpenAI / Anthropic / Groq / Ollama...
CLI / API / Notebook
deepmcpagent (Python pkg)
- config.py
- clients.py
- tools.py
- agent.py
- prompt.py

6)错误处理与可观测性(重试与封装)

ok
raises
Tool Call
client.call_tool(name,args)
Extract data/text/content/result
Return ToolMessage to Agent
Tool/Transport Error
ToolMessage(status=error, content=trace)
Agent observes error
and may retry / alternate tool

八、实战建议与最佳实践(Best Practices)

  1. 统一模型与鉴权:使用 init_chat_model("openai:gpt-4.1") 这类 provider-id 时,让 CI/CD 通过环境变量注入 OPENAI_API_KEYANTHROPIC_API_KEY 等。
  2. 工具按需加载:用多个 MCP Server 时给出明确 name 标识与 headers,便于路由与审计。
  3. Schema 即契约:让服务端严格返回 JSON-Schema,客户端自动转 PydanticBaseTool,提升可维护性与类型安全。
  4. 深浅两套 Agent:开发期以 ReAct 兜底,生产期安装 DeepAgents 获得更强的多步骤规划与鲁棒性。
  5. 可观测性:开启 CLI 富输出与日志,关注 工具发现调用参数返回结构token usage
  6. 边界强隔离:工具为“黑盒能力”,保持解耦;升级工具无需改主程序,即插即用。

九、典型落地场景(Use Cases)

  • 企业内部自动化:知识检索(Search MCP)→ 工单系统(Ticket MCP)→ 通知(Slack/Email MCP)。
  • 研发辅助:Code MCP + Repo MCP + CI MCP,形成从生成代码提交/触发流水线的长链条。
  • 数据工作流:ETL MCP + DB MCP + 可视化 MCP,自动生成报表并投递。
  • 多模型策略:按任务切换 OpenAI/Anthropic/本地模型,成本与效果可平衡。

十、开发(Development)

# install dev tooling
pip install -e ".[dev]"

# lint & type-check
ruff check .
mypy

# run tests
pytest -q

十一、故障排查(Troubleshooting)

  • PEP 668: externally managed environment (macOS + Homebrew)
    使用虚拟环境:

    python3 -m venv .venv
    source .venv/bin/activate
    
  • 连接 404:确认服务端使用了路径(如 /mcp),客户端 URL 也包含该路径。

  • 工具调用失败 / 属性错误:升级到最新版本;PrivateAttr 用于保存客户端状态。

  • Token 偏高:工具型模型对提示较敏感,开发期可用更小模型压测。


十二、安全与隐私(Security & Privacy)

  • 你的 Key 你做主:框架不绑定供应商;可传任意 LangChain 模型。
  • HTTPServerSpec 中通过 HTTP headers 传递 Bearer/OAuth,以最小权限访问工具。

十三、对比速览(Summary Table)

维度 DeepMCPAgent LangChain 工具(手工接线) LangGraph ReAct(单用)
工具发现 ✅ MCP 动态发现 ❌ 需手工注册 ❌ 需手工注册
扩展成本 ✅ 即插即用 ❌ 需改主程序 ❌ 需改图谱
Agent 逻辑 ✅ DeepAgents(可选)/ ReAct 回退 取决于自实现 ✅ ReAct
类型安全 ✅ JSON-Schema→Pydantic 取决于自定义 取决于工具
生态兼容 ✅ LangChain / LangGraph
适配 LLM ✅ 主流皆可

注:表格为方法论维度的对比,实际以各项目具体实现为准。


十四、版权与开源使用说明

本项目采用 Apache-2.0 开源协议。用一句话概括:可商用、可修改、可再发布,但需保留版权与许可声明,且按“现状”提供不担保。

你可以:

  • ✅ 在个人或企业项目中免费商用
  • 修改/二次开发/再发布(含闭源集成场景);
  • ✅ 享有专利授权随代码一并授予(协议内已约定)。

你必须:

  • 📌 在分发/再发布时保留原始 LICENSE 与(如有)NOTICE
  • 📌 保留原始版权声明,若做了修改,请标注变更
  • ⚠️ 代码按“现状”提供,不附带任何明示或暗示的担保与责任承诺。

企业落地小贴士:

  • 建议以 Fork 方式接入,保留 LICENSE/NOTICE 文件;
  • 建立第三方依赖的许可证清单(license audit);
  • 对接远程 MCP 服务时,务必做好 鉴权与密钥管理(仅最小权限)。

十五、致谢与参考

感谢以下社区与项目为 DeepMCPAgent 的理念与实现提供了灵感与生态支撑:

  • MCP 社区:推动“模型上下文协议”的实践与标准化(Model Context Protocol)
  • LangChain / LangGraph:强大的智能体与图式编排框架
  • FastMCP:稳定的 MCP 客户端/服务端实现,支撑动态工具发现与调用
  • 以及所有贡献 Issue / PR 的开源伙伴们 🙌

参与贡献(Contributing):

  • 欢迎提交 Issue 讨论需求与 Bug,或通过 PR 直接改进;
  • 建议遵循仓库中的代码规范(lint/type/test)与提交说明;
  • 仓库地址(Fork/Star):https://github.com/MaoTouHU/DeepMCPAgent

结语

  • 如果你不想自己写工具,又希望直接“现抓现用” MCP 生态里的各类能力,DeepMCPAgent 能让接入过程从工程化变为配置化
  • 即插即用 / 动态发现 / 多模型兼容 / DeepAgents 高级循环 / ReAct 兜底,从简单查询到多步骤、长链条的复杂任务都能覆盖。
  • 现在就试试:
pip install "deepmcpagent[deep]"
python examples/servers/math_server.py
python examples/use_agent.py

⭐ 如果觉得有帮助,欢迎 Star & Forkhttps://github.com/MaoTouHU/DeepMCPAgent
有任何想法或问题,直接在仓库提 Issue,我会持续跟进与完善。

Logo

一起探索未来云端世界的核心,云原生技术专区带您领略创新、高效和可扩展的云计算解决方案,引领您在数字化时代的成功之路。

更多推荐