6行代碼讓你的應用也能調用Mcp工具!
目前,很多的使用MCP的案例都是基于Cursor,Claude Desktop等客戶端展開的,那么如何在現有的系統里通過代碼集成呢?
今天,介紹一個很不錯的MCP客戶端庫mcp-use,集成非常簡單,僅需 6 行代碼即可創建第一個支持 MCP 的Agent,可與任何支持工具調用的 Langchain 支持的 LLM(OpenAI、Anthropic、Groq、LLama 等)配合使用,不僅支持本地MCP Server,還支持sse協議下的遠程MCP 服務器,這樣就可以和Dify這樣框架集成(??Dify也支持MCP了!??)解鎖更多能力,同時還可以在單個Agent中同時調用多個 MCP Server。
下面是一個使用案例:
import asyncio
import os
from dotenv import load_dotenv
from langchain_anthropic import ChatAnthropic
from mcp_use import MCPAgent, MCPClient
async def main():
# Load environment variables
load_dotenv()
# Create configuration dictionary
config = {
"mcpServers": {
"playwright": {
"command": "npx",
"args": ["@playwright/mcp@latest"],
"env": {
"DISPLAY": ":1"
}
}
}
}
# Create MCPClient from configuration dictionary
client = MCPClient.from_dict(config)
# Create LLM
llm = ChatAnthropic(model="claude-3-7-sonnet-20250219")
# Create agent with the client
agent = MCPAgent(llm=llm, client=client, max_steps=30)
# Run the query
result = await agent.run(
"Find the best restaurant in San Francisco",
)
print(f"\nResult: {result}")
if __name__ == "__main__":
asyncio.run(main())
也可以通過mcp文件加載,這就使得我們可以無縫的將cursor等客戶端的配置平滑遷移過來使用:
client = MCPClient.from_config_file(
os.path.join("browser_mcp.json")
)
{
"mcpServers": {
"playwright": {
"command": "npx",
"args": ["@playwright/mcp@latest"],
"env": {
"DISPLAY": ":1"
}
}
}
}
有了它,可以很方便的實現一些過去挺麻煩的操作,比如驗證碼橫行的當下,利用這種方式,可以輕易繞過,順利獲得數據。
繞過微信仿抓取策略
驗證碼
作者提供了很多的示例,感興趣的可以查看。
??https://github.com/mcp-use/mcp-use??
本文轉載自????AI工程化??,作者:ully
贊
收藏
回復
分享
微博
QQ
微信
舉報

回復
相關推薦