
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 ProtocolMCP集成能力如何让 Agent 通过一个 URL 自动发现并调用外部 MCP 服务器上的工具、如何用MCPManager绕过 Agent 直接与 MCP 服务器交互、如何把 Agent 或整个 swarm 用MCPDeployer反向暴露为带鉴权的 MCP 服务器以及如何用FastMCP自建服务器。读完你可以在几分钟内把 DeepWiki、Microsoft Learn、Exa、Firecrawl 等真实公共 MCP 服务器接入自己的 Agent也能把一个本地 Agent 发布成可供其他进程或机器调用的 MCP 服务。MCP 是什么为什么需要它Model Context ProtocolMCP是让 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.pyservers/构建一个供 Agent 连接的 MCP 服务器crypto_price_server.pyclient/不经过 Agent用MCPManager直接调用 MCP01_list_tools.pymcp_deployer/把 Agent 或 swarm 作为 MCP 服务器对外提供并带鉴权single_agent_api_key.py30 秒上手最小 MCP 集成examples/mcp/README.md给出的最小编成示例只有几行代码——这就是完整集成的全部from swarms import Agent agent Agent( agent_nameDeepWiki-Agent, model_namegpt-4o-mini, mcp_urlhttps://mcp.deepwiki.com/mcp, # free, no API key max_loops1, ) 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_KEYsk-... # 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_urlAgent01_deepwiki_repo_qa.py则是完整版指向 DeepWiki 的公共服务器https://mcp.deepwiki.com/mcp无需鉴权暴露read_wiki_structure、read_wiki_contents、ask_question三个工具用于对任意公共 GitHub 仓库做 QAagent Agent( agent_nameDeepWiki-Agent, agent_descriptionAnswers questions about GitHub repos via DeepWiki MCP., system_promptDEEPWIKY_SYSTEM_PROMPT, model_nameMODEL, mcp_urlhttps://mcp.deepwiki.com/mcp, max_loops1, reasoning_effortNone, )模式二MCPConnection 对象——定制头、鉴权与超时当裸 URL 不够用时用MCPConnection对象替代字符串可以精细控制连接行为见mcp_connection_object.pyfrom swarms.schemas.mcp_schemas import MCPConnection mcp_config MCPConnection( urlhttp://localhost:8000/mcp, # headers{Authorization: Bearer 1234567890}, timeout5, )MCPConnection的完整字段源码位于 swarms/schemas/mcp_schemas.py字段默认值说明urlhttp://localhost:8000/mcpMCP 服务器地址nameNone服务器可读名称用于日志与工具路由api_key/authorization_tokenNoneAPI key按api_key_header/api_key_prefix发送或 Bearer tokenapi_key_headerAuthorization发送 API key 用的请求头可改成X-API-Key等api_key_prefixBearerkey 前缀裸 key 可设为auth_typeNone显式指定鉴权方式缺省时从其他字段推断oauthNoneOAuth 2.1 配置见下文transportstreamable_httpstreamable_http/sse/stdio/autoheadersNone附加请求头timeout30HTTP 请求超时秒sse_read_timeout300SSE 流式事件等待上限秒tool_timeout120单次工具调用超时与timeout相互独立command/args/envNonestdio 传输下要启动的可执行文件、参数与环境变量模式三mcp_urls——多服务器一次接入传一个列表给mcp_urlsAgent 会从每台服务器加载工具模型在单次运行中能看到所有工具集的并集并自行决策调用哪个。见multi_mcp_urls.py与04_multi_server_agent.pyagent Agent( agent_nameMulti-MCP-Agent, model_namegpt-4o-mini, mcp_urls[ https://mcp.deepwiki.com/mcp, # GitHub repo QA https://learn.microsoft.com/api/mcp, # Microsoft docs ], max_loops2, # 给模型留出调用两个服务器工具的空间 )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_urltools [ { 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_nameFinancial-Analysis-Agent, max_loops2, tools_list_dictionarytools, output_typefinal, mcp_urlhttp://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 就能跑通。按序号排列的示例覆盖了服务器接收密钥的所有常见方式示例服务器功能鉴权01DeepWiki任意公共 GitHub 仓库的 QA无02GitMCP单仓库的文档/代码搜索无03Microsoft Learn官方 Azure/.NET 文档无04双服务器组合一个 Agent 挂两台服务器无05ExaWeb 搜索免费 API key查询参数07Hugging Face检索模型与数据集无可选 token10Firecrawl网页抓取转 MarkdownAPI keyURL 路径段12Semgrep静态分析安全扫描免费 tokenBearer13SequentialWorkflow多 Agent 流水线中使用 MCP 工具无这些示例共同演示了三种密钥传递方式——查询参数05、Bearer token12、URL 路径段10——以及可选鉴权场景07缺 key 时降级为匿名访问而非直接报错。不经过 Agent用 MCPManager 直接调用 MCPclient/目录演示的是框架内部的另一层能力MCPManager是 Agent 内部使用的同一个类也可以单独拿来直接和 MCP 服务器对话。它负责传输选择、鉴权、工具发现、缓存以及把每次调用路由到拥有该工具的服务器swarms/tools/mcp_manager.py 模块 docstring 对其职责有完整描述。适合的使用场景检视一台服务器暴露了什么工具、单独测试某个工具、或在 Agent 之外构建自己的 MCP 上层封装。from swarms.tools.mcp_manager import MCPManager manager MCPManager(mcp_urlhttp://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(formatopenai|mcp, force_refreshFalse)获取工具 schema。默认返回 OpenAI function-calling 格式结果带缓存force_refreshTrue强制重新拉取见01_list_tools.pycall_tool(name, arguments)/acall_tool(...)按名称调用单个工具自动路由到所属服务器execute_tool_calls(response, output_typedict|json|str)执行 LLM 响应中包含的工具调用按调用顺序返回结果见03_execute_llm_tool_calls.pyadd_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/mcppython 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端口 800106_remote_agents.py需要agent_as_tool_server.py05_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_headerapi_key_prefix组合默认变成Authorization: Bearer keyauthorization_token则固定发送为Authorization: Bearer token。OAuth 2.1 支持MCPOAuthConfigswarms/schemas/mcp_schemas.py支持三种形态授权码流程默认grant_typeauthorization_code。PKCE 与 RFC 7591 动态客户端注册由 MCP SDK 处理client_id可选。通过回环 HTTP 服务器_OAuthCallbackServer捕获?code...state...重定向token 缓存到磁盘默认~/.swarms/mcp_auth/server.json权限 0600交互式授权只弹一次浏览器客户端凭证流程grant_typeclient_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无头环境设为FalseURL 改为打印到日志、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.pyget_crypto_price——实时币价8000okx_crypto_server.pyget_okx_crypto_price——OKX 币价8001agent_as_tool_server.pycreate_agent——把整个 swarms Agent 包装成一个 MCP 工具8000streamable_http_server.py有状态 vs 无状态 streamable HTTP 传输配置8000运行方式与接入python examples/mcp/servers/crypto_price_server.pyfrom swarms import Agent agent Agent( agent_nameCrypto-Agent, model_namegpt-4o-mini, mcp_urlhttp://localhost:8000/mcp, max_loops1, ) 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。MCPDeployerswarms/structs/mcp_deployer.py把一个Agent、任何带run()方法的 swarm、或普通 callable 包装成带鉴权层的 MCP 服务器。每个目标成为一个以其名字命名的工具接收task参数和可选的img。传列表或{工具名: 目标}字典可以在一台服务器上同时服务多个 Agent 和 swarmadd_tool()可在启动前继续注册。from swarms import Agent, MCPDeployer agent Agent(agent_nameResearcher, model_namegpt-5.4, max_loops1) MCPDeployer(agent, api_keys[sk-local-dev], port8000).run()另一个 Agent 这样连接from swarms.schemas.mcp_schemas import MCPConnection # Agent(mcp_urlMCPConnection(urlhttp://127.0.0.1:8000/mcp, api_keysk-local-dev))示例总览示例目标鉴权传输独立运行single_agent_api_key.py单个 Agent静态api_keysstreamable HTTP持续服务sequential_workflow_as_tool.pySequentialWorkflow静态api_keysstreamable HTTP持续服务multiple_agents_one_server.py两个 Agent 一个SequentialWorkflow 两个函数各为独立工具静态api_keysstreamable HTTP持续服务custom_auth_per_tenant.py单个 Agent异步auth可调用对象读取x-tenantstreamable HTTP持续服务owner_key_or_tenant_auth.py单个 Agent同步auth环境中的 owner key或白名单x-tenantstreamable HTTP持续服务token_verifier_with_scopes.py单个 AgentTokenVerifierrequired_scopesstreamable HTTP持续服务env_keys_and_extra_tools.py一个 Agent 两个普通函数api_key_envstreamable HTTP持续服务background_server_and_client_agent.py单个 Agent静态api_keysstreamable HTTP是服务、调用、停止plain_function_json_response.py普通函数无 LLM静态api_keysstreamable HTTP、JSON 响应是无需 LLM keysse_transport.py单个 Agent静态api_keysSSE持续服务stdio_transport.py单个 Agent无宿主机即边界stdio由 MCP 宿主启动鉴权优先级MCPDeployer的鉴权层按以下优先级生效源码注释与此一致见 mcp_deployer.py 与 mcp_deployer/README.mdauthcallable(credential, headers)自定义校验支持同步或异步。返回真值放行返回 dict 则保留为该请求的 claims返回假值或抛异常则拒绝token_verifier使用mcp包的TokenVerifier协议强制校验required_scopes与过期时间api_keys[...]与api_key_envVAR静态密钥常数时间比较allow_anonymousTrue显式开启匿名未配置任何鉴权时构造函数直接拒绝构建。客户端可以用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_attempts3每次失败按 2 的指数退避重试2**attempt秒可用retry_attempts调整本地服务器没启动指向localhost:8000的示例报连接错误时先确认crypto_price_server.py是否在另一终端运行密钥别硬编码优先使用env:VAR或${VAR}形式从环境变量读取模型与工具不匹配多服务器场景记得给足max_loops让模型有空间在不同服务器之间往返调用工具如04_multi_server_agent.py使用max_loops2。总结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),仅供参考