Back to MCP directory
publicPublicdnsLocal runtime

mcp-use

MCP-Use是一个开源库,允许开发者将任何支持工具调用的LLM连接到MCP服务器,构建具有工具访问能力的自定义代理。

article

README

🚀 MCP-Use 使用指南

MCP-Use 为开发者提供了便捷的方式来连接和使用多个 MCP 服务,可与不同的大语言模型集成,拓展工具应用场景。

🚀 快速开始

安装 MCP-Use

通过以下命令安装 MCP-Use:

pip install mcp-use

快速上手示例

以下代码展示了如何快速使用 MCP-Use:

import asyncio
from mcp_use.client import MCPClient
from mcp_use.adapters.langchain_adapter import LangChainAdapter
from dotenv import load_dotenv

load_dotenv()

async def main():
    client = MCPClient.from_config_file("examples/browser_mcp.json")
    adapter = LangChainAdapter()
    tools = await adapter.create_tools(client)
    
    # 创建一个绑定工具的LLM
    llm_with_tools = llm.bind_tools(tools)
    result = await llm_with_tools.ainvoke("你能使用什么工具?")
    print(result)

if __name__ == "__main__":
    asyncio.run(main())

💻 使用示例

基础用法

使用多个 MCP 服务

import asyncio
from mcp_use.client import MCPClient
from langchain_openai import ChatOpenAI

async def main():
    client = MCPClient.from_config_files(
        config_files=["config1.json", "config2.json"]
    )
    
    # 创建代理
    async with client:
        llm = ChatOpenAI(model="gpt-4")
        tools = await client.get_tools()
        
        # 使用所有可用工具
        result = await llm.invoke("你能做什么?", tools=tools)
        print(result)

asyncio.run(main())

通过 HTTP 连接 MCP 服务

import asyncio
from mcp_use.client import MCPClient
from langchain_openai import ChatOpenAI

async def main():
    client = MCPClient.from_url("ws://localhost:3000/ws")
    
    async with client:
        llm = ChatOpenAI(model="gpt-4")
        tools = await client.get_tools()
        
        result = await llm.invoke("你能使用什么工具?", tools=tools)
        print(result)

asyncio.run(main())

高级用法

自定义代理

import asyncio
from mcp_use.client import MCPClient, BaseMCPAdapter
from typing import Any

class CustomAdapter(BaseMCPAdapter):
    async def get_action(self, observation: Any) -> str:
        # 实现自定义逻辑
        pass
    
async def main():
    client = MCPClient.from_config_file("config.json")
    
    adapter = CustomAdapter()
    async with client:
        action = await adapter.get_action("观察结果")
        print(action)

asyncio.run(main())

📚 详细文档

快速入门步骤

  1. 安装依赖
pip install mcp-use langchain openai anthropic playwright
  1. 创建配置文件 config.json 内容示例:
{
    "browser": {
        "type": "playwright",
        "args": {"headless": false}
    },
    "file_system": {
        "root": "./data"
    }
}

配置 MCP 客户端

  • 从文件加载配置
client = MCPClient.from_config_file("config.json")
  • 从 URL 加载配置
client = MCPClient.from_url("ws://localhost:3000/ws")

创建代理

async with client:
    # 获取可用工具
    tools = await client.get_tools()
    
    # 使用 OpenAI 模型
    llm = ChatOpenAI(model="gpt-4")
    result = await llm.invoke("任务描述", tools=tools)

客户端 API

  • MCPClient:管理多个 MCP 服务连接。
  • BaseMCPAdapter:定义适配器接口,用于与不同 MCP 实现交互。

工具示例

from mcp_use.tools import (
    Tool,
    BrowserTool,
    FileSystemTool,
    DatabaseTool,
    SearchEngineTool
)

🔧 技术细节

高级功能

并发执行

import asyncio
from mcp_use.client import MCPClient
from langchain_openai import ChatOpenAI

async def main():
    client = MCPClient.from_config_file("config.json")
    
    async with client:
        # 创建多个任务
        tasks = []
        for i in range(5):
            task = asyncio.create_task(client.request(f"第{i+1}个请求"))
            tasks.append(task)
        
        # 等待所有任务完成
        results = await asyncio.gather(*tasks)
        print(results)

asyncio.run(main())

扩展工具集

from mcp_use import Tool

class CustomTool(Tool):
    def __init__(self, custom_param: str):
        super().__init__()
        self.custom_param = custom_param
    
    async def execute(self, command: str) -> str:
        # 自定义逻辑
        return f"自定义工具执行结果:{command}"

调试与故障排除

启用调试日志

export MCP_USE_DEBUG=1

常见问题

  • 连接问题:检查网络和目标服务状态。
  • 权限问题:确保有足够的权限访问资源。

🤝 项目贡献

提交代码

  1. Fork 仓库
  2. 创建新分支
  3. 提交更改
  4. Push 到远程
  5. 提交 Pull Request

👥 社区支持

加入社区 Discord:

https://discord.gg/example

📄 许可证

MIT 许可证

👨‍💻 贡献者

  • 开发者:[你的名字]
  • 贡献者列表:[contributor1], [contributor2]
help

Runtime guide

cloud

Hosted runtime

Hosted servers run from a provider-managed environment. You usually connect the MCP client to the hosted endpoint or follow the provider's authorization flow, without keeping a local process alive

  1. Open provider connection page
  2. Authorize or copy endpoint
  3. Connect from your MCP client
terminal

Local runtime / other methods

Local servers run on your own machine or infrastructure. You normally copy the server_config into your MCP client, install the required package, and provide env variables from env_schema when needed

  1. Copy server_config
  2. Install required package
  3. Fill env variables and restart client