Swarms 框架 MCP 集成完全指南:Agent 无缝调用外部工具、直连 MCPManager 与 MCPDeployer 部署实战
【免费下载链接】swarmsThe Enterprise-Grade Multi-Agent Orchestration Framework. Website: https://swarms.ai项目地址: https://gitcode.com/GitHub_Trending/swar/swarms
本篇技术指南以examples/mcp/目录为核心,系统讲解 swarms 框架的 Model Context Protocol(MCP)集成能力:如何让 Agent 通过一个 URL 自动发现并调用外部 MCP 服务器上的工具、如何用MCPManager绕过 Agent 直接与 MCP 服务器交互、如何把 Agent 或整个 swarm 用MCPDeployer反向暴露为带鉴权的 MCP 服务器,以及如何用FastMCP自建服务器。读完你可以在几分钟内把 DeepWiki、Microsoft Learn、Exa、Firecrawl 等真实公共 MCP 服务器接入自己的 Agent,也能把一个本地 Agent 发布成可供其他进程或机器调用的 MCP 服务。
MCP 是什么:为什么需要它
Model Context Protocol(MCP)是让 Agent 从外部服务器"拉取"工具的标准协议。核心思想非常直接:给 Agent 一个 URL,它就能自动发现服务器上提供了哪些工具、了解每个工具的参数 schema,并在需要时直接调用——完全不需要手工把工具函数接线到 Agent 里。
在 swarms 中,examples/mcp/README.md的一句话概括了它的价值:agent 通过指向一个 URL 来从外部服务器获取工具,工具发现与调用都由框架自动完成。这样带来的实际收益是:
- 工具与 Agent 解耦:新增能力只需启动一个新 MCP 服务器,或在 URL 列表里加一行,无需改动 Agent 代码;
- 标准化:任何遵循 MCP 协议的服务器(官方 MCP SDK、
FastMCP构建的服务)都能被同一个Agent消费; - 跨进程/跨机器组合:一个 Agent 可以把自己的能力暴露成 MCP 工具,供另一个 Agent 远程调用。
examples/mcp/目录下的示例按照使用目标分为四个子目录,对应 MCP 集成的四类场景:
| 目录 | 适用场景 | 推荐起点 |
|---|---|---|
| agents/ | 给 Agent 提供来自 MCP 服务器的工具 | 01_deepwiki_repo_qa.py |
| servers/ | 构建一个供 Agent 连接的 MCP 服务器 | crypto_price_server.py |
| client/ | 不经过 Agent,用MCPManager直接调用 MCP | 01_list_tools.py |
| mcp_deployer/ | 把 Agent 或 swarm 作为 MCP 服务器对外提供,并带鉴权 | single_agent_api_key.py |
30 秒上手:最小 MCP 集成
examples/mcp/README.md给出的最小编成示例只有几行代码——这就是完整集成的全部:
from swarms import Agent agent = Agent( agent_name="DeepWiki-Agent", model_name="gpt-4o-mini", mcp_url="https://mcp.deepwiki.com/mcp", # free, no API key max_loops=1, ) agent.run("What is the swarms framework? Use the deepwiki tools on kyegomez/swarms.")设置mcp_url之后,Agent 内部会完成以下工作(对应 swarms/tools/mcp_manager.py 中MCPManager的实现流程):
- 配置归一化:把传入的 URL 字符串归一化为一个
MCPConnection对象; - 传输选择:从 URL 自动推断传输方式——
https://URL 走 streamable HTTP;以/sse结尾的 URL 走 SSE;没有 scheme 或配置了command的走 stdio(见源码中的_resolve_transport); - 工具发现:启动会话后调用
session.list_tools(),把服务器暴露的 MCP 工具转换为 OpenAI function-calling schema(见_mcp_tool_to_openai); - 模型决策与执行:LLM 根据工具 schema 决定调用哪些工具,
execute_tool_calls把每个调用路由到声明该工具的服务器并执行。
注意mcp_url参数支持一次传一个 URL;如果要挂多个服务器,用mcp_urls传入列表(见下文)。examples/mcp/agents/下所有示例本质上都是这段代码的变体——多服务器、鉴权、MCP 工具与本地工具混用。
环境准备
pip install swarms export OPENAI_API_KEY="sk-..." # or any LiteLLM-supported provider几点说明:
- 框架底层通过 LiteLLM 调用模型,因此
OPENAI_API_KEY可以换成任意 LiteLLM 支持的提供方(Anthropic、Gemini、本地 vLLM 等)。示例中的model_name都是普通 LiteLLM 字符串,替换成你有密钥的任意模型即可; - 免密钥服务器优先:
examples/mcp/agents/中前四个示例(DeepWiki、GitMCP、Microsoft Learn、双服务器组合)完全不需要 MCP 侧 API key,只需一个 LLM key 即可运行; - 指向
http://localhost:8000/mcp的示例需要先启动本地服务器——先在另一个终端运行 servers/ 下的某个服务器脚本。
Agent 侧配置模式:从单服务器到多服务器与本地工具混用
examples/mcp/agents/README.md将配置模式归纳为几种典型形态,对应的示例文件都经过真实公共服务器验证。
模式一:裸 URL——最小配置
deepwiki_minimal.py演示最小的mcp_urlAgent;01_deepwiki_repo_qa.py则是完整版,指向 DeepWiki 的公共服务器(https://mcp.deepwiki.com/mcp,无需鉴权),暴露read_wiki_structure、read_wiki_contents、ask_question三个工具,用于对任意公共 GitHub 仓库做 Q&A:
agent = Agent( agent_name="DeepWiki-Agent", agent_description="Answers questions about GitHub repos via DeepWiki MCP.", system_prompt=DEEPWIKY_SYSTEM_PROMPT, model_name=MODEL, mcp_url="https://mcp.deepwiki.com/mcp", max_loops=1, reasoning_effort=None, )模式二:MCPConnection 对象——定制头、鉴权与超时
当裸 URL 不够用时,用MCPConnection对象替代字符串,可以精细控制连接行为,见mcp_connection_object.py:
from swarms.schemas.mcp_schemas import MCPConnection mcp_config = MCPConnection( url="http://localhost:8000/mcp", # headers={"Authorization": "Bearer 1234567890"}, timeout=5, )MCPConnection的完整字段(源码位于 swarms/schemas/mcp_schemas.py):
| 字段 | 默认值 | 说明 |
|---|---|---|
url | http://localhost:8000/mcp | MCP 服务器地址 |
name | None | 服务器可读名称,用于日志与工具路由 |
api_key/authorization_token | None | API key(按api_key_header/api_key_prefix发送)或 Bearer token |
api_key_header | Authorization | 发送 API key 用的请求头,可改成X-API-Key等 |
api_key_prefix | Bearer | key 前缀;裸 key 可设为"" |
auth_type | None | 显式指定鉴权方式,缺省时从其他字段推断 |
oauth | None | OAuth 2.1 配置(见下文) |
transport | streamable_http | streamable_http/sse/stdio/auto |
headers | None | 附加请求头 |
timeout | 30 | HTTP 请求超时(秒) |
sse_read_timeout | 300 | SSE 流式事件等待上限(秒) |
tool_timeout | 120 | 单次工具调用超时,与timeout相互独立 |
command/args/env | None | stdio 传输下要启动的可执行文件、参数与环境变量 |
模式三:mcp_urls——多服务器一次接入
传一个列表给mcp_urls,Agent 会从每台服务器加载工具,模型在单次运行中能看到所有工具集的并集并自行决策调用哪个。见multi_mcp_urls.py与04_multi_server_agent.py:
agent = Agent( agent_name="Multi-MCP-Agent", model_name="gpt-4o-mini", mcp_urls=[ "https://mcp.deepwiki.com/mcp", # GitHub repo Q&A "https://learn.microsoft.com/api/mcp", # Microsoft docs ], max_loops=2, # 给模型留出调用两个服务器工具的空间 )multi_mcp_walkthrough.py是带注释的更完整多服务器演练。从源码看,多服务器时MCPManager会维护一张_tool_routes路由表,把每个工具名映射到其归属服务器;执行时按服务器分组,用asyncio.gather并发调用各组的会话(见 mcp_manager.py)。若不同服务器暴露了同名工具,会保留先注册者的定义并打印告警。
模式四:MCP 工具 + 本地工具混用
mcp_with_local_tools.py演示在同一个 Agent 上同时挂 MCP 工具和自定义函数工具——把本地工具 schema 放进tools_list_dictionary,同时设置mcp_url:
tools = [ { "type": "function", "function": { "name": "add_numbers", "description": "Add two numbers together and return the result.", "parameters": { "type": "object", "properties": { "name": {"type": "string", "description": "The name of the operation to perform."}, "a": {"type": "integer", "description": "The first number to add."}, "b": {"type": "integer", "description": "The second number to add."}, }, "required": ["name", "a", "b"], }, }, } ] agent = Agent( agent_name="Financial-Analysis-Agent", max_loops=2, tools_list_dictionary=tools, output_type="final", mcp_url="http://localhost:8000/mcp", )tools_list_dictionary.py单独展示了 MCP 工具被转换成的原始tools_list_dictionaryschema 形态——这正是 MCP 工具与本地工具能共存的原因:它们最终以同一种 OpenAI function-calling schema 交给 LLM。_mcp_tool_to_openai的实现确认了这一点:MCP 工具定义被转换为{"type": "function", "function": {"name": ..., "description": ..., "parameters": ..., "strict": False}}。
真实场景示例
finance_agent_mcp.py是一个由 MCP 服务器支撑的金融 Agent 完整示例;13_mcp_sequential_workflow.py则展示了多 Agent 场景:把 MCP 工具接入SequentialWorkflow,让流水线中的每个 Agent 都能使用这些工具。
公共 MCP 服务器:点哪个?
examples/mcp/agents/FREE_MCP_SERVERS.md整理了可直接使用的真实公共 MCP 服务器目录。其中多个完全不需要 API key,因此agents/下前四个示例只需要 LLM key 就能跑通。
按序号排列的示例覆盖了服务器接收密钥的所有常见方式:
| 示例 | 服务器 | 功能 | 鉴权 |
|---|---|---|---|
| 01 | DeepWiki | 任意公共 GitHub 仓库的 Q&A | 无 |
| 02 | GitMCP | 单仓库的文档/代码搜索 | 无 |
| 03 | Microsoft Learn | 官方 Azure/.NET 文档 | 无 |
| 04 | 双服务器组合 | 一个 Agent 挂两台服务器 | 无 |
| 05 | Exa | Web 搜索 | 免费 API key(查询参数) |
| 07 | Hugging Face | 检索模型与数据集 | 无(可选 token) |
| 10 | Firecrawl | 网页抓取转 Markdown | API key(URL 路径段) |
| 12 | Semgrep | 静态分析安全扫描 | 免费 token(Bearer) |
| 13 | SequentialWorkflow | 多 Agent 流水线中使用 MCP 工具 | 无 |
这些示例共同演示了三种密钥传递方式——查询参数(05)、Bearer token(12)、URL 路径段(10)——以及可选鉴权场景(07):缺 key 时降级为匿名访问而非直接报错。
不经过 Agent:用 MCPManager 直接调用 MCP
client/目录演示的是框架内部的另一层能力:MCPManager是 Agent 内部使用的同一个类,也可以单独拿来直接和 MCP 服务器对话。它负责传输选择、鉴权、工具发现、缓存,以及把每次调用路由到拥有该工具的服务器(swarms/tools/mcp_manager.py 模块 docstring 对其职责有完整描述)。
适合的使用场景:检视一台服务器暴露了什么工具、单独测试某个工具、或在 Agent 之外构建自己的 MCP 上层封装。
from swarms.tools.mcp_manager import MCPManager manager = MCPManager(mcp_url="http://localhost:8000/mcp") manager.list_tool_names() # 服务器上有什么 manager.get_tools() # 给 LLM 用的 OpenAI schema manager.call_tool("get_crypto_price", {"coin_id": "btc"}) # 直接调用一个工具 manager.execute_tool_calls(llm_response) # 执行模型请求的工具调用核心方法
| 方法 | 作用 |
|---|---|
list_tool_names() | 列出所有已配置服务器暴露的工具名 |
get_tools(format="openai"|"mcp", force_refresh=False) | 获取工具 schema。默认返回 OpenAI function-calling 格式,结果带缓存;force_refresh=True强制重新拉取(见01_list_tools.py) |
call_tool(name, arguments)/acall_tool(...) | 按名称调用单个工具,自动路由到所属服务器 |
execute_tool_calls(response, output_type="dict"|"json"|"str") | 执行 LLM 响应中包含的工具调用,按调用顺序返回结果(见03_execute_llm_tool_calls.py) |
add_server(server) | 运行中追加一台服务器并失效工具缓存(见04_multi_server.py) |
_normalize_tool_calls的实现让execute_tool_calls能兼容各种输入形态:JSON 字符串、单个工具调用、工具调用列表、完整 chat-completion message、dict 或 pydantic/OpenAI 对象都能被统一规整为[{"name": ..., "arguments": ...}]。
同步与异步
每个操作都有同步/异步两种形式:get_tools/aget_tools、call_tool/acall_tool、execute_tool_calls/aexecute_tool_calls。同步版本可以放心在普通代码里调用,包括在已运行的事件循环内部——run_async助手检测到正在运行的 loop 时,会把协程放到独立 worker 线程的专属事件循环中执行,规避asyncio.run() cannot be called from a running event loop的经典错误(mcp_manager.py)。
运行方式
大多数 client 示例期望本地服务器运行在http://localhost:8000/mcp:
python examples/mcp/servers/crypto_price_server.py # 终端 1 python examples/mcp/client/01_list_tools.py # 终端 2依赖关系:04_multi_server.py还需要okx_crypto_server.py(端口 8001);06_remote_agents.py需要agent_as_tool_server.py;05_auth_and_config.py不发起任何连接,只打印每种配置如何被解释。
MCP 鉴权:API key、Bearer、OAuth 2.1 与机密间接引用
API key 与 Bearer token
在MCPConnection上设置api_key或authorization_token即可。MCPManager._build_headers会组装请求头:API key 按api_key_header+api_key_prefix组合(默认变成Authorization: Bearer <key>),authorization_token则固定发送为Authorization: Bearer <token>。
OAuth 2.1 支持
MCPOAuthConfig(swarms/schemas/mcp_schemas.py)支持三种形态:
- 授权码流程(默认):
grant_type="authorization_code"。PKCE 与 RFC 7591 动态客户端注册由 MCP SDK 处理,client_id可选。通过回环 HTTP 服务器(_OAuthCallbackServer)捕获?code=...&state=...重定向,token 缓存到磁盘(默认~/.swarms/mcp_auth/<server>.json,权限 0600),交互式授权只弹一次浏览器; - 客户端凭证流程:
grant_type="client_credentials",无头机器对机器调用,需要client_id/client_secret。token 端点从服务器/.well-known/oauth-authorization-server元数据自动发现,或用token_url显式指定(_discover_token_endpoint); - 预签发 token:直接给
access_token,不再运行任何流程,仅作为 Bearer 凭证发送。
MCPOAuthConfig常用字段:client_id、client_secret、scopes(如['mcp:tools', 'offline_access'])、redirect_uri(默认http://127.0.0.1:8765/callback)、open_browser(无头环境设为False,URL 改为打印到日志)、callback_timeout(默认 300 秒)、token_storage_path、use_token_cache。
机密间接引用
任何字符串型敏感字段都可以写"env:MY_VAR"或"${MY_VAR}",_resolve_secret会在运行时从环境变量读取,避免把密钥硬编码进代码(mcp_manager.py)。05_auth_and_config.py对每种配置如何被解析做了详细展示。
自建 MCP 服务器:FastMCP 三分钟起步
servers/下的服务器用FastMCP构建,跑起来后把 Agent 指向其 URL 即可使用:
| 服务器 | 暴露的工具 | 端口 |
|---|---|---|
| crypto_price_server.py | get_crypto_price——实时币价 | 8000 |
| okx_crypto_server.py | get_okx_crypto_price——OKX 币价 | 8001 |
| agent_as_tool_server.py | create_agent——把整个 swarms Agent 包装成一个 MCP 工具 | 8000 |
| streamable_http_server.py | 有状态 vs 无状态 streamable HTTP 传输配置 | 8000 |
运行方式与接入:
python examples/mcp/servers/crypto_price_server.pyfrom swarms import Agent agent = Agent( agent_name="Crypto-Agent", model_name="gpt-4o-mini", mcp_url="http://localhost:8000/mcp", max_loops=1, ) agent.run("What is the current price of Bitcoin?")agent_as_tool_server.py是最有意思的一个:它把一个 swarmsAgent变成 MCP 工具,于是另一个 Agent 或任意 MCP 客户端都可以远程拉起并运行它——这就是跨进程、跨机器组合 swarm 的方式。agents/和client/下使用http://localhost:8000/mcp的示例大多期望crypto_price_server.py在运行。
把 Agent 发布成 MCP 服务器:MCPDeployer 与鉴权层
mcp_deployer/是完整闭环的最后一块:消费 MCP 之外,还能生产 MCP。MCPDeployer(swarms/structs/mcp_deployer.py)把一个Agent、任何带run()方法的 swarm、或普通 callable 包装成带鉴权层的 MCP 服务器。每个目标成为一个以其名字命名的工具,接收task参数和可选的img。传列表或{工具名: 目标}字典可以在一台服务器上同时服务多个 Agent 和 swarm;add_tool()可在启动前继续注册。
from swarms import Agent, MCPDeployer agent = Agent(agent_name="Researcher", model_name="gpt-5.4", max_loops=1) MCPDeployer(agent, api_keys=["sk-local-dev"], port=8000).run()另一个 Agent 这样连接:
from swarms.schemas.mcp_schemas import MCPConnection # Agent(mcp_url=MCPConnection(url="http://127.0.0.1:8000/mcp", api_key="sk-local-dev"))示例总览
| 示例 | 目标 | 鉴权 | 传输 | 独立运行 |
|---|---|---|---|---|
| single_agent_api_key.py | 单个 Agent | 静态api_keys | streamable HTTP | 持续服务 |
| sequential_workflow_as_tool.py | SequentialWorkflow | 静态api_keys | streamable HTTP | 持续服务 |
| multiple_agents_one_server.py | 两个 Agent + 一个SequentialWorkflow+ 两个函数,各为独立工具 | 静态api_keys | streamable HTTP | 持续服务 |
| custom_auth_per_tenant.py | 单个 Agent | 异步auth可调用对象(读取x-tenant) | streamable HTTP | 持续服务 |
| owner_key_or_tenant_auth.py | 单个 Agent | 同步auth:环境中的 owner key,或白名单x-tenant | streamable HTTP | 持续服务 |
| token_verifier_with_scopes.py | 单个 Agent | TokenVerifier+required_scopes | streamable HTTP | 持续服务 |
| env_keys_and_extra_tools.py | 一个 Agent + 两个普通函数 | api_key_env | streamable HTTP | 持续服务 |
| background_server_and_client_agent.py | 单个 Agent | 静态api_keys | streamable HTTP | 是:服务、调用、停止 |
| plain_function_json_response.py | 普通函数(无 LLM) | 静态api_keys | streamable HTTP、JSON 响应 | 是,无需 LLM key |
| sse_transport.py | 单个 Agent | 静态api_keys | SSE | 持续服务 |
| stdio_transport.py | 单个 Agent | 无(宿主机即边界) | stdio | 由 MCP 宿主启动 |
鉴权优先级
MCPDeployer的鉴权层按以下优先级生效(源码注释与此一致,见 mcp_deployer.py 与 mcp_deployer/README.md):
auth=callable(credential, headers):自定义校验,支持同步或异步。返回真值放行;返回 dict 则保留为该请求的 claims;返回假值或抛异常则拒绝;token_verifier=:使用mcp包的TokenVerifier协议,强制校验required_scopes与过期时间;api_keys=[...]与api_key_env="VAR":静态密钥,常数时间比较;allow_anonymous=True:显式开启匿名;未配置任何鉴权时构造函数直接拒绝构建。
客户端可以用x-api-key头传密钥(用api_key_header改名),也可以发Authorization: Bearer——MCPManager默认就是这么发送的。被拒绝的请求返回 401 并带WWW-Authenticate: Bearer头;/health端点始终公开。
生命周期
run()阻塞运行;start()/stop(),或with MCPDeployer(...) as d:,让服务器跑在后台线程——这正是background_server_and_client_agent和plain_function_json_response的做法;timeout限定单次工具调用的时长;extra_tools在主工具之外再暴露更多普通函数。
常见问题与排查要点
- 连接失败时报错为空字符串:MCP SDK 的 anyio 会把传输失败包装成
ExceptionGroup,其str()为空。MCPManager的_describe_exception会扁平化分组并始终附带异常类型,让 401 等错误以可操作的形式呈现(mcp_manager.py)。如果你在较老版本中遇到"空错误信息",升级到包含该处理的版本即可; - 网络抖动导致工具发现失败:
MCPManager默认retry_attempts=3,每次失败按 2 的指数退避重试(2**attempt秒);可用retry_attempts调整; - 本地服务器没启动:指向
localhost:8000的示例报连接错误时,先确认crypto_price_server.py是否在另一终端运行; - 密钥别硬编码:优先使用
"env:VAR"或"${VAR}"形式从环境变量读取; - 模型与工具不匹配:多服务器场景记得给足
max_loops,让模型有空间在不同服务器之间往返调用工具(如04_multi_server_agent.py使用max_loops=2)。
总结
examples/mcp/覆盖了 MCP 集成的完整拼图:消费端(Agent(mcp_url=...)一行接入外部工具)、客户端层(MCPManager直连、检视与调用)、服务端(FastMCP自建服务器)和部署端(MCPDeployer把 Agent/swarm 发布为带鉴权的 MCP 服务)。所有能力共享同一套MCPConnection配置模型与MCPManager底层实现,因此从单 URL 到多服务器、从 API key 到 OAuth 2.1、从 HTTP 到 SSE/stdio,配置方式保持统一。顺着agents/的编号示例逐个跑通,即可在真实公共服务器上体验完整的工具发现—模型决策—执行闭环。
【免费下载链接】swarmsThe Enterprise-Grade Multi-Agent Orchestration Framework. Website: https://swarms.ai项目地址: https://gitcode.com/GitHub_Trending/swar/swarms
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考