MCP客户端库

一个统一的MCP(模型上下文协议)客户端库,使任何LLM能够连接到MCP服务器并构建具有工具访问权限的自定义代理。

  • by iOSDevSK
  • Python
  • 本地部署
  • 2 星标
  • 更新于
在 GitHub 查看 iosdevsk/mcp-client

使用说明

MCP使用客户端

一个统一的MCP(模型上下文协议)客户端库,使任何LLM都能连接到MCP服务器,并使用工具访问构建自定义代理。该库提供了一个高级Python接口,用于将兼容LangChain的LLM连接到MCP工具,如网页浏览、文件操作等。

特性

  • 🔧 多运输支持:通过stdio、HTTP、WebSocket或沙盒执行连接
  • 🤖 LangChain集成:适用于任何与LangChain兼容的LLM
  • 📊 高级令牌计数:精确的令牌跟踪和管理
  • 🛡️ 安全第一:内置安全最佳实践和沙盒
  • ⚡ 高性能:异步/等待架构,实现最佳性能
  • 🎯 代理框架:具有对话记忆的高级代理接口
  • 📈 可观测性:内置遥测和监测支持

快速开始

安装

pip install -e ".[dev,anthropic,openai,e2b,search]"

基本用法

import asyncio
from mcp_use import MCPClient

async def main():
    # Initialize client with configuration
    client = MCPClient()
    
    # Connect to MCP servers
    await client.connect_to_server("playwright", {
        "command": "npx",
        "args": ["@playwright/mcp@latest"]
    })
    
    # Use tools
    tools = await client.get_available_tools()
    result = await client.call_tool("browse_web", {"url": "https://example.com"})
    
    print(result)

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

代理使用

from mcp_use.agents import MCPAgent
from langchain_openai import ChatOpenAI

# Create LLM
llm = ChatOpenAI(model="gpt-4")

# Create agent with MCP tools
agent = MCPAgent(
    llm=llm,
    config_path="mcp_config.json"
)

# Use the agent
response = await agent.run("Browse to example.com and summarize the content")
print(response)

配置

创建一个 mcp_config.json 文件:

{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": ["@playwright/mcp@latest"],
      "env": { "DISPLAY": ":1" }
    },
    "filesystem": {
      "command": "python",
      "args": ["-m", "mcp_server_filesystem", "/path/to/files"]
    }
  }
}

代币计数系统

图书馆包括一个先进的代币计数系统:

from mcp_use.token_counting import TokenCountingFactory

# Create token counter
counter = TokenCountingFactory.create_counter(
    provider="openai",
    model="gpt-4",
    openai_api_key="your-key"
)

# Count tokens
usage = await counter.count_tokens(messages)
print(f"Input: {usage.input_tokens}, Output: {usage.output_tokens}")

建筑

核心组件

  • MCP客户端:MCP服务器管理的主要入口点
  • MCPAgent:使用LangChain的高级代理接口
  • MCP会话:单个MCP服务器连接管理
  • 连接器:传输层抽象(stdio、HTTP、WebSocket、沙盒)
  • 服务器管理器:动态服务器选择功能

支持的交通工具

  • 标准输入输出:基于流程的MCP服务器
  • 超文本传输协议:带SSE的基于HTTP的MCP服务器
  • 网络套接字:基于WebSocket的MCP服务器
  • 沙盒:E2B沙盒执行以确保安全

发展

设置

# Create virtual environment
python -m venv env
source env/bin/activate  # On Windows: env\Scripts\activate

# Install for development
pip install -e ".[dev,search]"

测试

# Run all tests
pytest

# Run with coverage
pytest --cov=mcp_use --cov-report=html

# Run specific test types
pytest tests/unit/          # Unit tests
pytest tests/integration/   # Integration tests

代码质量

# Format and lint
ruff check --fix
ruff format

# Type checking
mypy mcp_use/

例子

Web浏览代理

from mcp_use.agents import MCPAgent
from langchain_anthropic import ChatAnthropic

agent = MCPAgent(
    llm=ChatAnthropic(model="claude-3-sonnet-20240229"),
    config={
        "mcpServers": {
            "playwright": {
                "command": "npx",
                "args": ["@playwright/mcp@latest"]
            }
        }
    }
)

result = await agent.run("Find the latest news on AI developments")

文件操作

config = {
    "mcpServers": {
        "filesystem": {
            "command": "python",
            "args": ["-m", "mcp_server_filesystem", "./documents"]
        }
    }
}

agent = MCPAgent(llm=your_llm, config=config)
result = await agent.run("Analyze all Python files in the project")

多服务器设置

config = {
    "mcpServers": {
        "web": {
            "command": "npx",
            "args": ["@playwright/mcp@latest"]
        },
        "files": {
            "command": "python",
            "args": ["-m", "mcp_server_filesystem", "./data"]
        },
        "database": {
            "url": "http://localhost:8080/mcp"
        }
    }
}

安全

  • 基于环境变量的API密钥管理
  • 通过E2B提供沙盒执行支持
  • 工具访问限制 disallowed_tools
  • 适当的资源清理和连接管理

贡献

  1. 分叉存储库
  2. 创建要素分支
  3. 进行更改
  4. 添加测试
  5. 运行测试套件
  6. 提交拉取请求

许可证

此项目根据MIT许可证获得许可-有关详细信息,请参阅许可证文件。

链接

支持

对于问题和疑问:

  • 在GitHub上创建问题
  • 检查文档
  • 查看示例目录