mcp-use代码示例详解:从基础到高级应用
【免费下载链接】mcp-use 项目地址: https://gitcode.com/gh_mirrors/mc/mcp-use
mcp-use是GitHub加速计划中的重要项目,提供了Python和TypeScript两种语言的SDK,使开发者能够轻松集成和使用MCP(Model Context Protocol)功能。本文将从基础的聊天功能到高级的多服务器配置和结构化输出,详细解析mcp-use的各类代码示例,帮助开发者快速上手并掌握核心应用场景。
基础聊天功能实现
基础聊天功能是mcp-use最常用的场景之一,通过MCPAgent和MCPClient的配合,可以快速构建具有上下文记忆能力的对话系统。
Python版本实现
Python版本的聊天示例位于examples/python/chat_example.py,主要实现了以下功能:
- 使用环境变量加载配置
- 创建支持多服务器的MCPClient实例
- 配置并启用对话记忆功能
- 实现交互式聊天循环,支持历史记录管理
核心代码片段:
async def run_memory_chat():
# 加载环境变量
load_dotenv()
# 配置多服务器
config = {
"mcpServers": {"playwright": {"command": "npx", "args": ["@playwright/mcp@latest"], "env": {"DISPLAY": ":1"}}}
}
# 创建客户端和LLM
client = MCPClient(config=config)
llm = ChatOpenAI(model="gpt-5")
# 创建带记忆功能的Agent
agent = MCPAgent(
llm=llm,
client=client,
max_steps=15,
memory_enabled=True, # 启用内置对话记忆
)
# 交互式聊天循环
while True:
user_input = input("\nYou: ")
# 处理退出命令
if user_input.lower() in ["exit", "quit"]:
print("Ending conversation...")
break
# 处理清除历史命令
if user_input.lower() == "clear":
agent.clear_conversation_history()
print("Conversation history cleared.")
continue
# 获取并打印AI响应
print("\nAssistant: ", end="", flush=True)
response = await agent.run(user_input)
print(response)
TypeScript版本实现
TypeScript版本的聊天示例位于examples/typescript/client/chat_example.ts,提供了与Python版本类似的功能,但使用了Node.js的异步模式和事件驱动编程模型。
核心代码片段:
async function runMemoryChat() {
// 配置多服务器
const config = {
mcpServers: {
airbnb: {
command: 'npx',
args: ['-y', '@openbnb/mcp-server-airbnb', '--ignore-robots-txt'],
},
},
}
// 创建客户端和LLM
const client = new MCPClient(config)
const llm = new ChatOpenAI({ model: 'gpt-4o-mini' })
// 创建带记忆功能的Agent
const agent = new MCPAgent({
llm,
client,
maxSteps: 15,
memoryEnabled: true, // 启用内置对话记忆
})
// 创建命令行交互界面
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
})
// 交互式聊天循环
while (true) {
const userInput = await new Promise(resolve => rl.question('\nYou: ', resolve))
// 处理退出命令
if (userInput.toLowerCase() === 'exit' || userInput.toLowerCase() === 'quit') {
console.error('Ending conversation...')
break
}
// 处理清除历史命令
if (userInput.toLowerCase() === 'clear') {
agent.clearConversationHistory()
console.error('Conversation history cleared.')
continue
}
// 获取并打印AI响应
process.stdout.write('\nAssistant: ')
const response = await agent.run(userInput)
console.error(response)
}
}
流式响应处理
流式响应是高级交互体验的关键功能,允许应用实时展示AI的思考过程和中间结果,而不需要等待完整响应生成。
Python流式示例
Python版本的流式示例位于examples/python/stream_example.py,展示了如何使用异步迭代器处理流式响应:
async def main():
# 加载环境变量和配置
load_dotenv()
config = {
"mcpServers": {"playwright": {"command": "npx", "args": ["@playwright/mcp@latest"], "env": {"DISPLAY": ":1"}}}
}
# 创建客户端、LLM和Agent
client = MCPClient(config=config)
llm = ChatAnthropic(model="claude-sonnet-4-5")
agent = MCPAgent(llm=llm, client=client, max_steps=30)
# 流式处理响应
async for step in agent.stream(
"Can you go on github and tell me how many stars the mcp-use project has?",
max_steps=30,
):
if isinstance(step, str):
# 处理最终结果
print("-------------Result--------------------------")
print("Result:", step)
else:
# 处理中间步骤
action, observation = step
print("-------------Log--------------------------")
print("Log:", action.log)
print("-------------Calling--------------------------")
print("Calling:", action.tool)
print("-------------Input--------------------------")
print("Input:", action.tool_input)
print("-------------Observation--------------------------")
print("Observation:", observation)
TypeScript流式示例
TypeScript版本的流式示例位于examples/typescript/client/stream_example.ts,提供了更细粒度的事件处理能力:
async function streamingExampleWithFinalResult() {
// 初始化客户端和Agent
const client = new MCPClient(everythingServer)
const llm = new ChatAnthropic({ model: 'claude-sonnet-4-20250514', temperature: 0 })
const agent = new MCPAgent({
llm,
client,
maxSteps: 8,
verbose: false,
})
// 创建流生成器
const stream = agent.stream("What tools do you have access to? Please test 2-3 of them.")
let stepNumber = 1
let result: string = ''
// 手动迭代流以捕获步骤和最终结果
while (true) {
const { done, value } = await stream.next()
if (done) {
// 生成器完成,value包含最终结果
result = value
break
} else {
// 处理中间步骤
console.log(`\n🔧 Step ${stepNumber}: ${value.action.tool}`)
console.log(` Input: ${JSON.stringify(value.action.toolInput)}`)
console.log(` Result: ${value.observation.slice(0, 100)}${value.observation.length > 100 ? '...' : ''}`)
stepNumber++
}
}
// 打印最终结果
console.log(`\n${'='.repeat(50)}`)
console.log('🎯 FINAL RESULT:')
console.log('='.repeat(50))
console.log(result)
}
TypeScript版本还提供了基于事件的细粒度流处理方式,可以捕获LLM的每个token输出:
async function streamEventsExample() {
// 使用streamEvents进行token级流式处理
const eventStream = agent.streamEvents(query)
for await (const event of eventStream) {
switch (event.event) {
case 'on_chain_start':
console.log('🏁 Agent execution started')
break
case 'on_tool_start':
console.log(`\n🔧 Tool started: ${event.name}`)
if (event.data?.input) {
console.log(` Input: ${JSON.stringify(event.data.input)}`)
}
break
case 'on_chat_model_stream':
// 处理LLM的token级输出
if (event.data?.chunk?.text) {
const textContent = event.data.chunk.text
if (typeof textContent === 'string' && textContent.length > 0) {
process.stdout.write(textContent)
}
}
break
// 处理其他事件类型...
}
}
}
多服务器配置与集成
mcp-use的强大之处在于能够同时连接和管理多个MCP服务器,从而整合不同来源的工具和能力。
Python多服务器示例
Python版本的多服务器示例位于examples/python/multi_server_example.py,展示了如何配置和使用多个不同功能的服务器:
async def run_multi_server_example():
# 创建多服务器配置
config = {
"mcpServers": {
"airbnb": {
"command": "npx",
"args": ["-y", "@openbnb/mcp-server-airbnb", "--ignore-robots-txt"],
},
"playwright": {
"command": "npx",
"args": ["@playwright/mcp@latest"],
"env": {"DISPLAY": ":1"},
},
"filesystem": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-filesystem",
"YOUR_DIRECTORY_HERE",
],
},
}
}
# 创建支持多服务器的客户端
client = MCPClient.from_dict(config)
# 创建LLM和Agent
llm = ChatAnthropic(model="claude-sonnet-4-5")
agent = MCPAgent(llm=llm, client=client, max_steps=30)
# 在单个查询中使用不同服务器的工具
result = await agent.run(
"Search for a nice place to stay in Barcelona on Airbnb, "
"then use Google to find nearby restaurants and attractions."
"Write the result in the current directory in restaurant.txt",
max_steps=30,
)
print(result)
多服务器架构允许Agent根据任务需求自动选择合适的工具,无需开发者手动管理服务器切换。例如,上述代码可以让Agent自动使用Airbnb服务器搜索住宿,使用Playwright服务器搜索附近餐厅,再使用文件系统服务器保存结果。
结构化输出应用
结构化输出功能允许开发者定义清晰的数据模型,使AI能够返回格式规范、易于处理的结果,而不是非结构化的文本。
Python结构化输出示例
Python版本的结构化输出示例位于examples/python/structured_output.py,使用Pydantic模型定义输出结构:
# 定义输出数据模型
class CityInfo(BaseModel):
"""Comprehensive information about a city"""
name: str = Field(description="Official name of the city")
country: str = Field(description="Country where the city is located")
region: str = Field(description="Region or state within the country")
population: int = Field(description="Current population count")
area_km2: float = Field(description="Area in square kilometers")
# 更多字段...
async def main():
# 配置客户端和Agent
client = MCPClient(config=config)
llm = ChatOpenAI(model="gpt-5")
agent = MCPAgent(llm=llm, client=client, max_steps=50)
# 请求结构化输出
result: CityInfo = await agent.run(
"""
Research comprehensive information about the city of Padova (also known as Padua) in Italy.
Visit multiple reliable sources like Wikipedia, official city websites, tourism sites,
and university websites to gather detailed information.
""",
output_schema=CityInfo, # 指定输出数据模型
max_steps=50,
)
# 使用结构化结果
print(f"Name: {result.name}")
print(f"Country: {result.country}")
print(f"Population: {result.population:,}")
print(f"Area: {result.area_km2} km²")
# 打印其他字段...
通过定义明确的数据模型,开发者可以获得类型安全的输出结果,避免了繁琐的字符串解析和数据验证工作。这在需要处理复杂数据结构或集成到现有系统时特别有用。
示例代码的实际应用场景
mcp-use的各类示例代码覆盖了从简单聊天到复杂多服务器集成的广泛应用场景,以下是一些典型的使用案例:
自动化研究助手
利用Playwright服务器和结构化输出功能,可以构建自动化研究助手,自动收集、整理和格式化信息:
# 参考[examples/python/structured_output.py](https://link.gitcode.com/i/a1e1902aa07ada97233ded03ec59d8e4)
多平台内容聚合
通过多服务器配置,可以同时从多个平台(如Airbnb、Blender等)获取信息并进行整合:
# 参考[examples/python/multi_server_example.py](https://link.gitcode.com/i/73d6daa937450949a58ea2a974e17581)
实时交互式应用
使用流式响应功能,可以构建实时交互应用,展示AI的思考过程并提供即时反馈:
// 参考[examples/typescript/client/stream_example.ts](https://link.gitcode.com/i/ec2276476b67b63cc33139165a699f77)
总结与进阶学习
通过本文介绍的各类代码示例,开发者可以快速掌握mcp-use的核心功能和使用方法。从基础的聊天功能到高级的多服务器配置和结构化输出,mcp-use提供了灵活而强大的工具集,帮助构建智能、高效的AI应用。
官方文档提供了更详细的API参考和高级用法说明:
要深入学习mcp-use,建议从简单示例开始,逐步尝试更复杂的功能组合,并参考官方提供的完整示例代码库:
通过灵活运用mcp-use的各项功能,开发者可以构建出功能丰富、交互友好的AI应用,充分发挥大语言模型与各类工具的协同能力。
【免费下载链接】mcp-use 项目地址: https://gitcode.com/gh_mirrors/mc/mcp-use
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考





