6行代碼讓你的應(yīng)用也能調(diào)用Mcp工具!
目前,很多的使用MCP的案例都是基于Cursor,Claude Desktop等客戶端展開的,那么如何在現(xiàn)有的系統(tǒng)里通過代碼集成呢?
今天,介紹一個(gè)很不錯(cuò)的MCP客戶端庫(kù)mcp-use,集成非常簡(jiǎn)單,僅需 6 行代碼即可創(chuàng)建第一個(gè)支持 MCP 的Agent,可與任何支持工具調(diào)用的 Langchain 支持的 LLM(OpenAI、Anthropic、Groq、LLama 等)配合使用,不僅支持本地MCP Server,還支持sse協(xié)議下的遠(yuǎn)程MCP 服務(wù)器,這樣就可以和Dify這樣框架集成(??Dify也支持MCP了!??)解鎖更多能力,同時(shí)還可以在單個(gè)Agent中同時(shí)調(diào)用多個(gè) MCP Server。
下面是一個(gè)使用案例:
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"
}
}
}
}
有了它,可以很方便的實(shí)現(xiàn)一些過去挺麻煩的操作,比如驗(yàn)證碼橫行的當(dāng)下,利用這種方式,可以輕易繞過,順利獲得數(shù)據(jù)。
繞過微信仿抓取策略
驗(yàn)證碼
作者提供了很多的示例,感興趣的可以查看。
??https://github.com/mcp-use/mcp-use??
本文轉(zhuǎn)載自????AI工程化??,作者:ully
贊
收藏
回復(fù)
分享
微博
QQ
微信
舉報(bào)

回復(fù)
相關(guān)推薦