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工程化)

发表评论