AppBuilder调用MCP组件COOKBOOK
更新时间:2025-03-14
一、MCP介绍
1. 什么是MCP协议
Model Context Protocol (MCP)是Anthropic推出的一个开放协议,提供了一种将 AI 模型连接到不同数据源和工具的标准化方式,可实现应用与外部数据源和工具之间的无缝集成。
1.1 总体架构
MCP 的核心是client-server架构,其中一个主机应用程序可以连接到多个服务器。
- MCP Hosts: 希望通过 MCP 访问数据的程序,例如 Claude Desktop、IDE 或 AI 工具
- MCP Clients: 与服务器保持 1:1 连接的协议客户端
- MCP Servers: 通过MCP协议公开特定功能的程序
- Local Data Sources: MCP协议可以安全访问的本机文件、数据库、服务等
- Remote Services: MCP Server可以访问的远程服务
1.2 MCP Server主要分类
- Resources: 上下文和数据,供用户或人工智能模型使用
- Prompts: 为用户提供模板化的消息和工作流程
- Tools: AI模型调用的工具,使模型能够与外部系统交互,例如查询数据库、调用 API 或执行计算
1.3 MCP Server主要特征
- 每个工具都由名称唯一标识,并包含描述其架构的元数据
- 大模型可以根据其上下文理解和用户的提示自动发现和调用工具
1.4 MCP Server示例
- MCP quick-start server: weather server
- MCP example servers: example servers
2. 使用MCP有哪些好处
- 开发者可通过AppBuilder SDK调用MCP Server生态中的工具,结合已有Agent,打造一个端云结合的进阶Agent,查看详细示例
- 同时,基于AppBuilder SDK开发的组件可轻松转为MCP Server,被其他开发者调用,查看详细示例
二、Agent应用调用MCP组件,打造端云结合的进阶Agent
示例效果:查询今天头条消息,并获取其中一个网页,在本地打开。
1. 创建Agent
在AppBuilder界面创建一个包含百度AI搜索组件的Agent,并发布。
2. 保存MCP Server代码
我们使用Playwright 作为MCP Server,将代码保存为 mcp_playwright.py
。
3. 执行Agent
用户可复用下面的代码,替换为自己的token、app_id。执行Agent。
import os
import asyncio
import appbuilder
from appbuilder.core.console.appbuilder_client.async_event_handler import (
AsyncAppBuilderEventHandler,
)
from appbuilder.modelcontextprotocol.client import MCPClient
class MyEventHandler(AsyncAppBuilderEventHandler):
def __init__(self, mcp_client):
super().__init__()
self.mcp_client = mcp_client
def get_current_weather(self, location=None, unit="摄氏度"):
return "{} 的温度是 {} {}".format(location, 20, unit)
async def interrupt(self, run_context, run_response):
thought = run_context.current_thought
# 绿色打印
print("\033[1;31m", "-> Agent 中间思考: ", thought, "\033[0m")
tool_output = []
for tool_call in run_context.current_tool_calls:
tool_res = ""
if tool_call.function.name == "get_current_weather":
tool_res = self.get_current_weather(**tool_call.function.arguments)
else:
print(
"\033[1;32m",
"MCP工具名称: {}, MCP参数:{}\n".format(
tool_call.function.name, tool_call.function.arguments
),
"\033[0m",
)
mcp_server_result = await self.mcp_client.call_tool(
tool_call.function.name, tool_call.function.arguments
)
print("\033[1;33m", "MCP结果: {}\n\033[0m".format(mcp_server_result))
for i, content in enumerate(mcp_server_result.content):
if content.type == "text":
tool_res += mcp_server_result.content[i].text
tool_output.append(
{
"tool_call_id": tool_call.id,
"output": tool_res,
}
)
return tool_output
async def success(self, run_context, run_response):
print("\n\033[1;34m", "-> Agent 非流式回答: ", run_response.answer, "\033[0m")
async def agent_run(client, mcp_client, query):
tools = mcp_client.tools
conversation_id = await client.create_conversation()
with await client.run_with_handler(
conversation_id=conversation_id,
query=query,
tools=tools,
event_handler=MyEventHandler(mcp_client),
) as run:
await run.until_done()
### 用户需替换成自己的
os.environ["APPBUILDER_TOKEN"] = (
"xxxx"
)
async def main():
#### 用户需替换成自己的app_id
app_id = "xxx"
appbuilder_client = appbuilder.AsyncAppBuilderClient(app_id)
mcp_client = MCPClient()
await mcp_client.connect_to_server("./mcp_playwright.py")
print(mcp_client.tools)
await agent_run(
appbuilder_client,
mcp_client,
"先搜索今日头条新闻,取出其中一个url,在用playwright_nagative打开这个url",
)
await appbuilder_client.http_client.session.close()
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
打开网页:
Agent返回:
三、将AppBuilder 组件转化为MCP Server Tool
1. 如何定义自己的MCP Server Tool
MCP协议提供两种方式定义server:low-level server 和 FastMCP server。其中low-level是基础接口,FastMCP是高级封装,是 MCP 协议的核心接口。它处理连接管理、协议合规性和消息路由。
下面提供一个使用FastMCP定义自己的MCP Server Tool的简单示例:
from mcp.server.fastmcp import FastMCP
# Create a named server
mcp = FastMCP("My App")
# Define a tool
@mcp.tool()
def add(a: int, b: int) -> int:
"""Tool that executes an addition"""
result = a + b
return result
2. 如何将AppBuilder组件转换为MCP Server Tool
下面是一个简单的Server示例,将AppBuilder组件转换为MCP Server Tool:
"""server.py"""
import os
from appbuilder.modelcontextprotocol.server import MCPComponentServer
from appbuilder.core.components.v2 import Translation
from appbuilder.core.components.v2 import Text2Image
os.environ['APPBUILDER_TOKEN'] = '你的APPBUILDER_TOKEN'
# 定义server
server = MCPComponentServer(name="AB Component Server")
# 初始化组件实例
translation = Translation()
text2image = Text2Image()
# 把组件作为tool添加到server
server.add_component(translation)
server.add_component(text2image)
# 启动server
server.run()
3. Claude Client使用AppBuilder组件
3.1 配置claude服务器
首先需要安装Claude桌面版,并填写配置文件 claude_desktop_config.json
,配置claude服务器。不同系统的配置文件路径:
- macOS:
~/Library/Application Support/Claude/claude_desktop_config.json
- Windows:
%APPDATA%\Claude\claude_desktop_config.json
详情请参考:For Claude Desktop Users
claude_desktop_config.json
示例:
{
"mcpServers": {
"AB Component Server": {
"command": "/abs-path/to/python",
"args": [
"/abs-path/to/server.py"
]
}
}
}
配置文件说明:
- command: 启动命令,这里需要填写python解释器的绝对路径
- args: 启动参数,这里需要填写Server脚本的绝对路径
3.2 打开claude桌面版
配置完成后,重新打开claude桌面版,可以看到已定义的工具:
3.3 使用工具
使用工具,可以看到组件的输入输出及整体效果: