支持 MCP 的七大 AI 框架

大模型向量数据库机器学习

使用 Python 和 Typescript 框架创建 AI 应用,这些框架可借助 MCP 服务器为大型语言模型(LLMs)提供上下文。

picture.image

AI 代理工具包[1]为开发者提供了各种 API,使 AI 解决方案具备执行任务的工具,并确保结果准确,从而提升用户满意度。然而,将这些工具集成进 AI 应用并进行管理可能十分复杂。本文将向你介绍一种为 LLMs 和代理提供上下文的行业标准 —— Model Context Protocol(MCP)[2]

LLM 上下文提供方式与规范

默认情况下,如果不给大型语言模型(LLMs)和 AI 聊天机器人[3]提供适当的上下文,它们将无法获取实时信息、执行代码、调用外部工具与 API,甚至无法代表用户使用网络浏览器。开发者可以通过以下方法来解决 LLM 与代理的这一限制:

•Composio[4]:Composio 提供了集成 AI 代理和 LLM 的规范和工具库。除了 Composio 现有的预构建工具库外,他们最近还发布了 Composio MCP ,允许开发者连接 100 多个 MCP 服务器到 IDE 中。点击上方链接查看 Composio MCP [5]工具分类,将多个应用连接至 MCP 支持的 IDE(如 Cursor、Claude 和 Windsurf)中的项目。•Agents.json[6]:一种基于 OpenAI 标准构建的规范,旨在确保 AI 代理[7]与 API 和外部工具之间的交互顺畅且功能增强。尽管 Agents.json 是一个很好的规范,但其使用并不广泛,也未被像 MCP 那样广泛采纳。可参考其 GitHub 仓库[8]了解详情并开始使用。•MCP :MCP 为开发者提供了最佳方式,以向 LLMs 和 AI 助手提供上下文数据以解决问题。例如,你可以构建一个 MCP 文档服务器,为 IDE 和代理框架提供完整的文档访问,就像使用 llms.txt[9]文件一样。

什么是 MCP?

可以把 MCP 看作是大型语言模型(LLMs)的第三次进化。

•在第一次进化中,LLMs 可以准确回答用户的提示内容,前提是这些查询存在于其训练数据中。在这个阶段,它们无法对训练数据之外的提示做出有意义的回应,因为它们无法访问外部工具。•在第二次进化中,我们为 LLM 提供了额外的上下文(工具),虽然这些工具不一定容易操作,但能够帮助 LLM 更准确地预测和回答用户意图。•第三次进化仍然由 LLM 与工具组成,但我们构建了一套完善的基础设施,使它们可以访问外部应用程序,并确保系统易于维护。

picture.image

在构建 AI 服务时,你的数据可能托管在云端,比如一个 AI 助手应用,在企业环境中负责处理客户支持[10]工单。MCP 是由 Anthropic[11] 提出的一个开源协议 ,你可以使用它将企业数据连接至 AI 系统。

MCP 提供了一种标准化方式,用于连接和通信内容存储库(如 GitHub、Notion)、开发环境、网页工具和业务工具[12],以支持 AI 助手技术的发展。MCP 的一个非常流行并不断增长的应用场景是 AI 辅助编程 。目前已有数百个 MCP 与开发环境及工具(如 Cursor[13]、Windsurf[14])完成集成,开发者可借此连接外部应用并进行交互式开发。

注意: 本文旨在介绍如何将 MCP 实现于使用 Python 和 TypeScript 构建的 AI 助手与代理系统中,不涉及基于 IDE 的 MCP 集成。

MCP 的工作原理

在 LLMs 与智能代理的上下文中,MCP 的作用是帮助它们对超出内置知识范围的用户请求做出有意义的回应 。举个例子:你让 ChatGPT 向某个 Slack 频道发送消息、检查你的日历是否有空、并与同事安排今天的会议。你可能会对 ChatGPT 的回应感到失望,因为它无法访问这些外部应用程序。而通过实现 MCP,可以让这些 AI 助手输出真正有用的结果

picture.image

开发者通常提出的第一个问题就是:“MCP 是如何工作的?”MCP 的基本操作流程如下,用户向代理发送一个请求。代理判断应该调用哪个 MCP 服务器和工具,以获取执行该操作所需的相关信息。代理再利用某个具体工具返回的数据,来回应用户的请求。

为什么要在 AI 代理和基于 LLM 的应用中采用 MCP?

MCP 正逐渐成为一种标准,它帮助开发者构建能够与外部应用有效通信的 AI 系统 。微软最近在其 Copilot Studio[15] 中宣布集成 MCP,旨在简化 AI 应用与代理访问工具的方式。同时,OpenAI 也宣布[16]将在旗下产品中支持 MCP,包括 Agents SDK[17] 和 ChatGPT 桌面应用程序。当然,直接将工具集成到 AI 助手中并没有错,但对于一个包含多个代理、承担多项任务的 AI 系统来说,这种方式将变得非常笨重。例如,一个复杂的 AI 系统可能需要执行多项任务,比如读取并回复电子邮件,进行网页数据抓取,完成财务分析,获取实时天气信息 。在这种情况下,通过 MCP 实现统一、可维护的工具调用机制,是更合理也更高效的选择。

集成工具的 AI 代理

picture.image

在上图中,有三个外部工具连接到了 LLM。如果将来工具数量增加到 100 个甚至更多,管理和保障这些工具的安全将变得非常令人头痛。一种更优的方案是:通过 MCP 注册表访问这些相同的工具,甚至更多(100+)的工具,如下一个章节所示。

集成 MCP 的 AI 代理

picture.image

在此图中,我们将智能代理系统所需的多个工具通过 MCP 服务器整合接入 ,从而为用户提供更一致、更流畅的使用体验。MCP 的方式使得工具的集中管理与安全控制更加容易。

使用 MCP 相较于传统工具集成方式的优势

与传统方式相比,将工具与 AI 代理集成时,MCP 具有多个关键优势。比如没有 MCP 时,集成工具会遇到很多问题,比如由于 AI 基础设施不兼容,在进行多次 API 调用时可能会出现各种错误。在 MCP 出现之前,每一个要添加到代理中的工具都需要定制开发,通常需要几周才能实现。

架构清晰灵活 :不同于预构建的 AI 工具规范,MCP 拥有简洁且灵活的架构,方便与工具和 API 交互。•改进的外部工具访问与管理能力 :MCP 为 AI 模型提供标准化接口,实现 LLM 与第三方系统之间的无缝通信。•解决独立工具实现的局限性 :MCP 工具适用于单用户和团队协作的场景。•社区驱动 :MCP 拥有丰富的开源服务器和开发者生态系统,已在开发社区广泛应用于多种场景。•内建身份认证与权限控制 :MCP 拥有强大的内置身份验证系统。例如,使用 Composio 提供的 MCP 工具时,你可以为 Google Sheets 或 Gmail 用户进行认证。•工具搜索便捷 :MCP 让查找、集成外部工具变得更加简单,而不再需要手动安装、配置、调试。•可扩展性强 :MCP 容易扩展至多用户与多种应用场景。•行业标准 :虽然你也可以通过硬编码方式为 AI 应用提供上下文,但 MCP 提供了一套行业标准,帮助代理与 LLM 获取所需上下文信息。

MCP 服务器的类型

picture.image

Anthropic 对 MCP 的规范中定义了两种用于将工具接入 AI 代理和项目的服务器形式:

SSE(Server-Sent Events) :通过 HTTP 连接到远程服务。•STDIO :允许执行本地命令,并通过标准输入/输出进行通信。

你所选择用于构建 AI 应用的框架会提供必要的类,以便连接到这些 MCP 服务器。

访问 MCP 注册表/服务器生态系统

目前有多个开源库提供托管的 MCP 工具资源,用于增强 LLM 和代理的能力,确保其生成响应的可靠性 。这些托管的 MCP 工具库被称为“注册表”(Registries),它们提供经过精选的服务集合。你可以使用这些注册表的工具将 AI 应用连接至服务,比如uvx,基于 Python 的工具,无需安装即可使用。还有Docker 版本,用于运行 MCP 工具的容器化部署方式。基于 npx 的服务器,需安装 Node.js,可快速启动 MCP 服务。

GitHub 上的 MCP 服务器集合 :包含社区构建的服务器与更多 MCP 资源。•Glama Registry :面向生产环境的开源 MCP 服务器,专为开发者准备。•Smithery Registry :通过 Smithery,开发者可访问 2000+ MCP 服务器,增强 AI 代理和 LLM 的能力。•OpenTools :提供用于 MCP 工具的生成式 API。你可以接入数百个现成的 MCP 工具,直接应用于你的 AI 项目中。利用 OpenTools API,开发者可扩展 LLM 的能力,比如网页搜索,获取实时地理位置数据,网页爬取。该 API 支持 Curl、Python 和 TypeScript 。你可以访问 OpenTools 的快速入门指南以开始使用该 API。

  
from openai importOpenAI  
  
client =OpenAI(  
    base_url="https://api.opentools.com",  
    api_key="<OPENTOOLS_API_KEY>"  
)  
  
completion = client.chat.completions.create(  
    model="anthropic/claude-3.7-sonnet",  
    messages=[  
{"role":"user","content":"Compare specs of top 5 EVs on caranddriver.com"}  
],  
    tools=[{"type":"mcp","ref":"firecrawl"}]  
)

•PulseMCP Registry[18]:通过 PulseMCP,你可以浏览各种托管的 MCP 工具及其在 AI 项目中的应用场景。
👉 访问 PulseMCP News[19],了解最近流行的 MCP 服务器与应用。•mcp.run[20]:该注册表为开发者提供数百个适用于企业场景的 MCP 应用,便于快速接入使用。•Composio Registry[21]:Composio 提供基于 SSE(Server-Sent Events)的 MCP 服务器,支持多种 AI 框架的工具集成,用于构建 AI 应用程序。•guMCP[22]:由 Gumloop 提供的 guMCP,是一个免费、开源且完全托管的 MCP 注册表[23],可无缝集成至任意 AI 应用。

将 MCP 集成到 LLM 和智能代理中的七大客户端框架

尽管 MCP 目前已成为开发者社区的热门话题,大家纷纷讨论如何将其集成到 AI 应用和智能代理中,但要选择合适的 MCP 客户端框架并不容易。我们进行了调研,整理出以下 7 个领先的 MCP 客户端平台,适用于基于 Python 和 TypeScript 的代理工作流与 AI 助手开发。

注意: 以下内容聚焦于将 MCP 集成进用于构建 AI 解决方案的框架,而非像 Cursor 或 Windsurf 这类 AI 编程编辑器的集成方式。

1. 使用 OpenAI Agents SDK 构建 Git MCP Agent

picture.image

当你使用 OpenAI Agents SDK[24] 构建代理时,可以借助 SDK 提供的 MCPServerStdioMCPServerSse 类连接到社区构建的 MCP 服务器。下面是一个 MCP Agent 的示例实现:它连接本地 Git 仓库的根目录,并根据用户的请求对该仓库内容作出响应。

  
import asyncio  
import shutil  
import streamlit as st  
from agents importAgent,Runner, trace  
from agents.mcp importMCPServer,MCPServerStdio  
  
# 执行 Git 查询任务  
async def query_git_repo(mcp_server:MCPServer, directory_path: str, query: str):  
    agent =Agent(  
        name="Assistant",  
        instructions=f"Answer questions about the localgit repository at {directory_path}, use that for repo_path",  
        mcp_servers=[mcp_server],  
)  
with st.spinner(f"Running query: {query}"):  
        result = await Runner.run(starting_agent=agent, input=query)  
return result.final_output  
  
# 查询封装  
def run_query(directory_path, query):  
ifnot shutil.which("uvx"):  
        st.error("uvx 未安装,请运行 `pip install uvx` 进行安装。")  
return  
  
    async def execute_query():  
        async withMCPServerStdio(  
            cache_tools_list=True,  
params={  
"command":"python",  
"args":["-m","mcp_server_git","--repository", directory_path]  
},  
)as server:  
with trace(workflow_name="MCP Git Query"):  
                result = await query_git_repo(server, directory_path, query)  
                st.markdown("### 查询结果")  
                st.write(result)  
  
    asyncio.run(execute_query())  
  
# 主页面逻辑(同步版本)  
def main_streamlit_app():  
    st.title("本地 Git 仓库查询助手")  
    st.write("可通过自然语言查询本地 Git 仓库的信息。")  
  
    directory_path = st.text_input("请输入 Git 仓库路径:")  
  
if directory_path:  
        col1, col2 = st.columns(2)  
with col1:  
if st.button("最频繁的贡献者"):  
                query ="Who's the most frequent contributor?"  
                run_query(directory_path, query)  
  
with col2:  
if st.button("最近提交摘要"):  
                query ="Summarize the last change in the repository."  
                run_query(directory_path, query)  
  
        custom_query = st.text_input("或输入你自己的查询内容:")  
if st.button("运行自定义查询")and custom_query:  
            run_query(directory_path, custom_query)  
  
if __name__ =="__main__":  
    st.set_page_config(page_title="Local Git Repo Explorer", page_icon="📊", layout="centered")  
    main_streamlit_app()

上面的代码将 StreamlitOpenAI MCP Agent 集成,借助 Git MCP 服务器 ,你可以通过自然语言与本地 Git 仓库进行“对话”。请先安装以下依赖包:

pip install streamlit openai-agents mcp-server-git•然后,请将你的 OpenAI API 密钥导出到环境变量中export OPENAI\_API\_KEY=sk-....。运行该 Python 文件后,你将看到如下界面。

你可以在 GitHub 上探索其他 OpenAI MCP[25]示例项目。

使用 OpenAI Agents SDK 进行 MCP 集成,有一个重要优势是该功能可以自动记录并展示你的代理在执行 MCP 操作过程中的详细信息,比如工具列表请求,POST 请求响应记录,函数调用的数据获取记录。下图展示了本节 Git MCP 示例运行后的追踪记录示意图,你可以在 OpenAI Dashboard[26] 中查看所有操作日志和运行历史信息。

💡 借助 Dashboard,开发者可以轻松调试代理逻辑,追踪工具调用链路,优化 AI 应用流程。

2. 使用 Praison AI 构建 MCP AI 代理

picture.image

Praison AI 是一个基于 Python 的 AI 框架,用于构建多智能体系统(团队型代理)。它提供了极其简便的方式,仅用一行代码即可将 MCP 工具服务器集成进代理工作流,就像使用传统工具一样轻松。

下列示例展示了如何将 Airbnb MCP 服务器Praison AI 代理 结合,通过 Streamlit 页面 帮助用户在指定位置查找公寓。要创建你的第一个基于 Praison AI 的 MCP 代理,请先安装以下依赖项:

pip install praisonaiagents mcp streamlit•将你的 OpenAI API 密钥导出为环境变量export OPENAI\_API\_KEY='sk-proj-qZIGbi....

新建一个 Python 文件,例如streamlit\_praison\_airbnb\_mcp\_agent.py,然后将以下代码填入该文件中。

  
import streamlit as st  
from praisonaiagents importAgent, MCP  
  
st.title("🏠 Airbnb Booking Assistant")  
  
# 创建代理(MCP 工具通过 npx 启动 Airbnb 服务)  
@st.cache_resource  
def get_agent():  
returnAgent(  
        instructions="""You help book apartments on Airbnb.""",  
        llm="gpt-4o-mini",# 使用 GPT-4o-mini 模型  
        tools=MCP("npx -y @openbnb/mcp-server-airbnb --ignore-robots-txt")  
)  
  
# 初始化聊天记录  
if"messages"notin st.session_state:  
    st.session_state.messages =[]  
  
# 显示聊天记录  
for message in st.session_state.messages:  
with st.chat_message(message["role"]):  
        st.markdown(message["content"])  
  
# 用户输入表单  
with st.form("booking_form"):  
    st.subheader("请输入您的预订信息")  
  
    destination = st.text_input("目的地:","巴黎")  
  
    col1, col2 = st.columns(2)  
with col1:  
        check_in = st.date_input("入住日期")  
with col2:  
        check_out = st.date_input("退房日期")  
  
    adults = st.number_input("成人人数:", min_value=1, max_value=10, value=2)  
  
    submitted = st.form_submit_button("搜索住宿")  
  
if submitted:  
        search_agent = get_agent()  
  
# 构建查询内容  
        query = f"I want to book an apartment in {destination} from {check_in.strftime('%m/%d/%Y')} to {check_out.strftime('%m/%d/%Y')} for {adults} adults"  
  
# 添加用户输入到聊天记录  
        st.session_state.messages.append({"role":"user","content": query})  
  
# 显示用户输入  
with st.chat_message("user"):  
            st.markdown(query)  
  
# 获取代理响应  
with st.chat_message("assistant"):  
with st.spinner("正在查找住宿信息..."):  
                response = search_agent.start(query)  
                st.markdown(response)  
  
# 添加助手响应到聊天记录  
        st.session_state.messages.append({"role":"assistant","content": response})  
  
# 跟进问题输入  
if st.session_state.messages:  
    prompt = st.chat_input("对住宿还有其他问题?可以继续提问")  
if prompt:  
        search_agent = get_agent()  
  
# 添加用户输入到聊天记录  
        st.session_state.messages.append({"role":"user","content": prompt})  
  
# 显示用户输入  
with st.chat_message("user"):  
            st.markdown(prompt)  
  
# 获取代理响应  
with st.chat_message("assistant"):  
with st.spinner("思考中..."):  
                response = search_agent.start(prompt)  
                st.markdown(response)  
  
# 添加助手响应到聊天记录  
        st.session_state.messages.append({"role":"assistant","content": response})

运行上述示例代码后,系统将调用所需的 Airbnb MCP 工具 ,帮助你在指定位置查找可用的公寓,实际效果如下所示:

picture.image

你可能已经注意到,我们只用一行代码就为代理添加了 MCP 支持,tools = MCP("npx -y @openbnb/mcp-server-airbnb --ignore-robots-txt"),其中npx 表示运行 MCP 服务器所需执行的命令;-y 是传递给该命令的命令行参数;--ignore-robots-txt是传递给工具的选项之一,用于跳过 robots.txt 限制。想了解更多关于 MCP 服务器配置和调用方式,请参考 OpenAI Agents SDK 文档中的 MCP Servers[27] 部分。

3. 在 LangChain AI 应用中使用 MCP

LangChain 已支持通过工具调用(Tool Calling)方式接入 MCP ,这项支持允许你通过 Python 函数配置,连接不同的 MCP 服务器并检索工具,用于在 AI 项目中执行各类任务,下方示例代码展示了如何连接到一个安全的 MCP 文件系统服务器,使得大型语言模型(LLM)能够准确回答关于你提供的任意文件的问题。

  
# Copyright (C) 2024 Andrew Wason  
# SPDX-License-Identifier: MIT  
  
import asyncio  
import pathlib  
import sys  
import typing as t  
  
from langchain_core.messages importAIMessage,BaseMessage,HumanMessage  
from langchain_core.output_parsers importStrOutputParser  
from langchain_core.tools importBaseTool  
from langchain_groq importChatGroq  
from mcp importClientSession,StdioServerParameters  
from mcp.client.stdio import stdio_client  
  
from langchain_mcp importMCPToolkit  
  
# 主推理执行函数:运行模型与工具交互  
async def run(tools: list[BaseTool], prompt: str)-> str:  
    model =ChatGroq(model_name="llama-3.1-8b-instant", stop_sequences=None)# 需设置 GROQ_API_KEY  
    tools_map ={tool.name: tool for tool in tools}  
    tools_model = model.bind_tools(tools)  
    messages: list[BaseMessage]=[HumanMessage(prompt)]  
    ai_message = t.cast(AIMessage, await tools_model.ainvoke(messages))  
    messages.append(ai_message)  
  
# 执行工具调用  
for tool_call in ai_message.tool_calls:  
        selected_tool = tools_map[tool_call["name"].lower()]  
        tool_msg = await selected_tool.ainvoke(tool_call)  
        messages.append(tool_msg)  
  
return await (tools_model |StrOutputParser()).ainvoke(messages)  
  
# 主程序入口  
async def main(prompt: str)->None:  
# 配置 MCP 文件系统工具(通过 npx 启动)  
    server_params =StdioServerParameters(  
        command="npx",  
        args=["-y","@modelcontextprotocol/server-filesystem", str(pathlib.Path(__file__).parent.parent)],  
)  
  
    async with stdio_client(server_params)as(read, write):  
        async withClientSession(read, write)as session:  
            toolkit =MCPToolkit(session=session)  
            await toolkit.initialize()  
            response = await run(toolkit.get_tools(), prompt)  
print(response)  
  
# 默认命令:读取并总结 README.md 文件  
if __name__ =="__main__":  
    prompt = sys.argv[1]if len(sys.argv)>1else"Read and summarize the file ./readme.md"  
    asyncio.run(main(prompt))

在运行上述 Python 脚本之前,请确保已安装以下依赖项:

pip install langchain-core langchain-groq langchain-mcp

上述 MCP 配置使用的是 npx 类型的服务器,因此你需要全局安装 MCP 文件系统工具包。

npm install -g @modelcontextprotocol/server-filesystem

当你安装完所有依赖项,并将一个文件(如 ./readme.md)放入项目中,并在脚本中引用它,如示例所示:prompt = "Read and summarize the file ./readme.md",然后运行该脚本,你将看到类似于下图所示的输出效果:

picture.image

📌 注意: 本示例代码摘自 LangChain 的 GitHub 仓库[28]。

4. 在 Chainlit AI 应用中使用 MCP

picture.image

Chainlit 是一个用于构建 Python AI 应用的平台。它原生支持 MCP 服务器,你可以在应用中配置 MCP 工具发现机制,并将工具调用集成到应用的执行流程中,从而提升任务处理效果。Chainlit 支持通过 服务器发送事件(SSE)命令行(stdio) 方式连接 MCP 服务。在下方示例中,我们将一个 Chainlit 应用连接到 Linear MCP 服务器 ,以便实现对 Linear 中 问题(issues)项目(projects)团队(teams) 的管理。你可以使用该示例中的 Linear 工具, 创建问题,更新问题,搜索问题,获取用户的所有问题,为问题添加评论。

⚙️ 配置 Chainlit 应用以连接 MCP 服务器

将 Chainlit 应用连接至 MCP 工具服务器。

1.注册 MCP 连接 : 你需要实现 Chainlit 的异步钩子函数 on\_mcp\_connect, 用于在应用启动时建立 MCP 连接。你也可以通过on\_mcp\_disconnect函数安全清理资源。

  
# pip install chainlit  
  
import chainlit as cl  
from mcp importClientSession  
  
@cl.on_mcp_connect  
async def on_mcp_connect(connection, session:ClientSession):  
"""Called when an MCP connection is established"""  
# Your connection initialization code here  
# This handler is required for MCP to work  
  
@cl.on_mcp_disconnect  
async def on_mcp_disconnect(name: str, session:ClientSession):  
"""Called when an MCP connection is terminated"""  
# Optional handler: Cleanup your code here

2.配置 MCP 客户端(适用于 Chainlit、LangChain、Mastra) :为了使 MCP 服务器能够与 Chainlit 应用配合使用,客户端应通过 Chainlit 的用户界面(UI)提供连接详情。该配置包括以下内容。

picture.image

连接名称 :一个唯一标识符,用于表示该连接的名称。•客户端类型 :你需要指定使用哪种客户端类型,支持以下两种: sse:服务器发送事件(Server-Sent Events),此时需要填写一个 URL 端点;stdio:标准输入/输出方式,此时需要填写一个完整的命令(如:npx your-tool-packageuvx your-tool-package)。例如,以下是一个使用 stdio 类型的完整命令:

npx -y linear-mcp-server --tools=all --api-key=lin\_api\_your\_linear\_API\_Key

当成功建立 MCP 服务器连接后,你可以通过 MCP 会话(Session)执行所需工具。最终,你可以将 MCP 工具无缝集成到 Chainlit 应用中的模型或代理中,通过工具调用(Tool Call)完成任务执行。你可以在 Chainlit 官方 GitHub[29] 示例项目 中找到完整的 Linear MCP 集成源代码。

当你从 GitHub 获取上述源代码后,运行应用并在 Chainlit 的界面中输入以下 MCP 启动命令:npx -y linear-mcp-server --tools=all --api-key=lin\_api\_your\_linear\_API\_Key你就可以在界面中创建或更新 Linear 的 问题(Issues) 和 项目(Projects)。

5. 为 Agno AI 代理集成 MCP

Agno 是一个用于构建复杂代理工作流的 Python 框架。它因其简单、易用,以及与 MCP 服务器的无缝集成而广受欢迎。本节中的 MCP 实现示例与一个包含四个独立代理的多智能体团队集成,这些代理包括 Airbnb、Google Maps、网页搜索和天气 MCP 代理。Agno 的多代理协同工作,提供指定位置的旅行相关信息。

📋 前置条件

要测试本节中的 Agno MCP 实现示例,请确保完成以下准备工作:

1.安装 Agno、DuckDuckGo 和 Exa:pip install -U openai agno duckduckgo-search exa-py``。2.获取一个 GOOGLE\_MAPS\_API\_KEY[30] 并将其添加到项目的.env文件中。3.获取一个 APIFY\_TOKEN[31] 并将其添加到.env`文件中。4.验证 Google 地址 API[32] 的可用性。

picture.image

配置 Agno MCP 多代理团队

在此步骤中,你应当定义 MCP 服务器参数,并使用 AsyncExitStack 管理多个上下文管理器。然后,创建代理并运行它们。

  
# Define server parameters  
    airbnb_server_params =StdioServerParameters(  
        command="npx",  
        args=["-y","@openbnb/mcp-server-airbnb","--ignore-robots-txt"],  
        env=env,  
)  
  
    maps_server_params =StdioServerParameters(  
        command="npx", args=["-y","@modelcontextprotocol/server-google-maps"], env=env  
)  
  
# Use contextlib.AsyncExitStack to manage multiple async context managers  
    async with contextlib.AsyncExitStack()as stack:  
# Create stdio clients for each server  
        airbnb_client, _ = await stack.enter_async_context(stdio_client(airbnb_server_params))  
        maps_client, _ = await stack.enter_async_context(stdio_client(maps_server_params))  
  
# Create all agents  
        airbnb_agent =Agent(  
            name="Airbnb",  
            role="Airbnb Agent",  
            model=OpenAIChat("gpt-4o"),  
            tools=[airbnb_client],  
            instructions=dedent("""\  
You are an agent that can find Airbnb listings for a given location.\  
"""),  
            add_datetime_to_instructions=True,  
)

从 Agno 的 GitHub 仓库获取完整的源代码[33]。安装所需的依赖包,完成上述所有配置,并运行完整的 GitHub 示例代码后,你将看到类似如下预览的输出结果。

picture.image

6. 在 Upsonic 代理中使用 MCP

Upsonic[34]是一个用于创建 AI 代理的 Python 框架。使用 Upsonic,你可以构建自己的代理、为代理定义任务,并通过 MCP 工具[35]来处理每一个任务定义,如下方示例代码所示。

  
import os  
from dotenv import load_dotenv  
from upsonic importTask,Agent,Direct  
from upsonic.client.tools importSearch# Adding Search as a fallback tool  
  
# Load environment variables from .env file  
load_dotenv()  
  
# Get the OpenAI API key from environment variables  
openai_api_key = os.getenv("OPENAI_API_KEY")  
ifnot openai_api_key:  
raiseValueError("OPENAI_API_KEY not found in .env file")  
  
# Set your OpenAI API key for the session  
os.environ["OPENAI_API_KEY"]= openai_api_key  
  
# Define the HackerNews MCP tool  
# Using the correct MCP setup for HackerNews based on Upsonic documentation  
classHackerNewsMCP:  
    command ="uvx"  
    args =["mcp-hn"]  
# No environment variables are needed for this MCP  
  
# Create a task to analyze the latest HackerNews stories  
# Adding Search as a fallback in case HackerNews MCP fails  
task =Task(  
"Analyze the top 5 HackerNews stories for today. Provide a brief summary of each story, "  
"identify any common themes or trends, and highlight which stories might be most relevant "  
"for someone interested in AI and software development.",  
    tools=[HackerNewsMCP,Search]# Include both HackerNews MCP and Search tools  
)  
  
# Create an agent specialized in tech news analysis  
agent =Agent(  
"Tech News Analyst",  
    company_url="https://news.ycombinator.com/",  
    company_objective="To provide insightful analysis of tech industry news and trends"  
)  
  
# Execute the task with the agent and print the results  
print("Analyzing HackerNews stories...")  
agent.print_do(task)  
  
# Alternatively, you can use a Direct LLM call if the task is straightforward  
# print("Direct analysis of HackerNews stories...")  
# Direct.print_do(task)  
  
# If you want to access the response programmatically:  
# agent.do(task)  
# result = task.response  
# print(result)

在上述示例中,我们在 Upsonic 中创建了一个 AI 代理,用于获取 Hackernews 上最近发布的前五条新闻。如果你使用以下命令安装 Upsonic 并运行上面的 Python 代码:pip install upsonic,你应该会看到类似下图的输出结果。

7. 在 Mastra 代理中使用 MCP

Mastra[36]是一个基于 TypeScript 的框架,用于构建原型和可投入生产环境的 AI 代理。与 Chainlit 类似,Mastra 提供了一种标准化的方式,通过 stdiosse 连接接入 MCP 服务器,以访问各种工具。

要将你的 Mastra 代理连接到 MCP 服务器,你需要使用框架提供的 MCPConfiguration 类。该类可以在任意 Mastra 的智能体工作流中,处理多个服务器连接,包括生命周期管理、命名空间(namespacing)以及工具管理等。

1.创建 MCPConfiguration 类的一个实例,并添加服务器配置;2.使用 getTools()getToolsets() 方法获取 MCP 工具。

下方示例代码展示了如何在 Mastra 代理中基本实现 MCP 服务器连接。

  
import{MCPConfiguration}from"@mastra/mcp";  
import{Agent}from"@mastra/core/agent";  
import{ openai }from"@ai-sdk/openai";  
  
const mcp =newMCPConfiguration({  
  servers:{  
    stockPrice:{  
      command:"npx",  
      args:["tsx","stock-price.ts"],  
      env:{  
        API_KEY:"your-api-key",  
},  
},  
    weather:{  
      url:new URL("http://localhost:8080/sse"),  
},  
},  
});  
  
// Create an agent with access to all tools  
const agent =newAgent({  
  name:"Multi-tool Agent",  
  instructions:"You have access to multiple tool servers.",  
  model: openai("gpt-4"),  
  tools: await mcp.getTools(),  
});

👉 想了解更多内容,请参考 Mastra 的 MCPConfiguration[37]类相关文档。

面向 LLM 应用与代理的 MCP:挑战与未来展望

本教程介绍了 MCP,并解释了它为何在开发者社区中迅速流行。我们还重点展示了 MCP 与诸如 Cursor 和 Windsurf 等 IDE 的集成情况。除了上述内容,我们还在七个不同的 Python 与 TypeScript 框架中实现了 MCP,
用于构建基于 LLM 的应用、AI 助手以及智能代理。

目前,MCP 生态系统正在围绕多个关键方面展开标准化讨论。未来可能会出现一种标准化方式来安装 MCP 应用 , 就像我们现在在 Python 中使用 pip install 安装包一样。同时,PulseMCP 也正在努力,尝试让 MCP 工具的浏览与发现过程变得更加便捷。

更多信息

山行AI希望本文能够对您有所帮助,更多信息请查看:https://medium.com/@amosgyamfi/the-top-7-mcp-supported-ai-frameworks-a8e5030c87ab,如有帮助,请帮忙点赞、转发、评论,谢谢!

References

[1] AI 代理工具包:https://getstream.io/blog/ai-agent-toolkits/
[2]Model Context Protocol(MCP):https://modelcontextprotocol.io/introduction
[3]AI 聊天机器人:https://getstream.io/chat/solutions/ai-integration/
[4]Composio:https://composio.dev/
[5]Composio MCP :https://mcp.composio.dev/?\_gl=1*1tcsvb5*\_ga*MTk0ODc0NjU2OS4xNzM3MjM1ODgx*\_ga\_J9WD56TEBS*MTc0MjQ1NTUwMC4yMC4wLjE3NDI0NTU1MDAuMC4wLjA.*\_ga\_YKMWVQS9W0*MTc0MjQ1NTUwMC4yMC4wLjE3NDI0NTU1MDAuNjAuMC4xNjQwNzI1NjY1
[6]Agents.json:https://docs.wild-card.ai/agentsjson/introduction
[7]AI 代理:https://getstream.io/blog/xai-python-multi-agent/
[8]GitHub 仓库:https://github.com/wild-card-ai/agents-json
[9]llms.txt:https://llmstxt.org/
[10]客户支持:https://getstream.io/blog/build-a-customer-support-chat-bot-with-luis-react-hooks-azure-serverless-and-stream/
[11]Anthropic:https://www.anthropic.com/
[12]业务工具:https://github.com/atharvagupta2003/mcp-stripe
[13]Cursor:https://docs.cursor.com/context/model-context-protocol
[14]Windsurf:https://docs.windsurf.com/windsurf/getting-started
[15]Copilot Studio:https://www.microsoft.com/en-us/microsoft-copilot/blog/copilot-studio/introducing-model-context-protocol-mcp-in-copilot-studio-simplified-integration-with-ai-apps-and-agents/
[16]宣布:https://x.com/sama/status/1904957253456941061
[17]Agents SDK:https://openai.github.io/openai-agents-python/
[18]PulseMCP Registry:https://www.pulsemcp.com/
[19]PulseMCP News:https://www.pulsemcp.com/posts0
[20]mcp.run:https://www.mcp.run/
[21]Composio Registry:https://mcp.composio.dev/
[22]guMCP:https://www.gumloop.com/mcp
[23]MCP 注册表:https://github.com/gumloop/GuMCP
[24]OpenAI Agents SDK:https://openai.github.io/openai-agents-python/mcp/
[25]OpenAI MCP:(https://github.com/openai/agents
[26]OpenAI Dashboard:https://platform.openai.com/
[27]MCP Servers:https://openai.github.io/openai-agents-python/ref/mcp/server/
[28]GitHub 仓库:https://github.com/rectalogic/langchain-mcp/tree/main
[29]GitHub:https://github.com/Chainlit/cookbook/tree/main/mcp-linear
[30]GOOGLE_MAPS_API_KEY:https://console.cloud.google.com/projectselector2/google/maps-apis/credentials?pli=1
[31]APIFY_TOKEN:https://console.apify.com/settings/integrations
[32]Google 地址 API:https://console.cloud.google.com/apis/api/addressvalidation.googleapis.com
[33]源代码:https://github.com/agno-agi/agno/blob/main/cookbook/examples/teams/coordinate/travel\_planner\_mcp\_team.py
[34]Upsonic:https://docs.upsonic.ai/introduction
[35]MCP 工具:https://docs.upsonic.ai/concepts/mcp\_tools
[36]Mastra:https://mastra.ai/
[37]MCPConfiguration: https://mastra.ai/en/reference/tools/mcp-client

0
0
0
0
关于作者
关于作者

文章

0

获赞

0

收藏

0

相关资源
火山引擎大规模机器学习平台架构设计与应用实践
围绕数据加速、模型分布式训练框架建设、大规模异构集群调度、模型开发过程标准化等AI工程化实践,全面分享如何以开发者的极致体验为核心,进行机器学习平台的设计与实现。
相关产品
评论
未登录
看完啦,登录分享一下感受吧~
暂无评论