Token导航 LogoToken导航TokenDH.com
MCP SSE Client Python logo
AI代理stdio官方级别未说明来源级核验

MCP SSE Client Python

MCP Server

一个用于与远程模型上下文协议(MCP)端点交互的Python工具包,支持服务器发送事件(SSE)和多种LLM集成,适用于AI工具交互和实时流式通信场景。

工具数

0

提示词数

0

GitHub Stars

25

资源数

0
实时通信PythonClaudeClaude

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

作者 / 组织

zanetworker

提供方

zanetworker

最后核验

2026/5/17 20:21

快速接入

先看主来源和安装命令,再打开仓库或文档;下面只保留这个条目的关键接入事实。

命令预览

pip install -e .

详细介绍

MCP游乐场

一个用于与远程模型上下文协议(MCP)端点交互的全面Python工具包。目前支持服务器发送事件(SSE),并计划支持流式HTTP协议。

🎯 项目重点

MCP游乐场 是专门为 远程MCP客户端功能,提供强大的工具,用于通过网络协议连接到MCP服务器并与之交互:

  • ✅ 服务器发送事件(SSE) -实时流媒体的全面实施
  • 🔄 流式HTTP -计划在未来发布
  • 🤖 LLM集成 -AI驱动的工具选择和执行
  • 🧪 交互式测试 -全面的测试环境

🚀 快速开始

几分钟内起床跑步:

# Clone the repository
git clone https://github.com/zanetworker/mcp-playground.git
cd mcp-playground

# Install the package
pip install -e .

# Try the interactive Streamlit app
cd mcp-streamlit-app
pip install -r requirements.txt
streamlit run app.py

alt text

🚨 重要: 连接到MCP服务器时,始终使用以结尾的URL /sse 例子: http://localhost:8000/sse (不是 http://localhost:8000)

环境变量

为了方便起见,您可以通过环境变量设置API密钥和OpenRouter配置:

# Required for LLM providers
export OPENAI_API_KEY="your-openai-key"
export ANTHROPIC_API_KEY="your-anthropic-key"
export OPENROUTER_API_KEY="your-openrouter-key"

# Optional OpenRouter configuration for better rankings
export OPENROUTER_SITE_URL="https://your-site.com"
export OPENROUTER_SITE_NAME="Your App Name"

*Streamlit界面突出显示 /sse URL要求,附带有用的工具提示和验证。*

🛠️ 支持的协议

当前支持

  • 服务器发送事件(SSE) -与MCP服务器的实时流通信
  • HTTP/HTTPS -标准请求-响应模式

计划支持

  • 流式HTTP -增强的HTTP流媒体功能
  • 双向通信 -双向实时通信
  • gRPC流媒体 -高性能流媒体协议

🤖 LLM提供商支持

MCP Playground与多家LLM提供商集成,实现智能工具选择:

  • OpenAI:GPT-4o、GPT-4、GPT-3.5涡轮增压
  • Anthropic:克劳德3作品集,克劳德3十四行诗,克劳德3俳句
  • 奥拉马:Llama 3、Mistral和其他本地托管的模型
  • OpenRouter:通过统一的API访问100多个模型

📋 核心功能

1.远程MCP客户端

轻松连接到任何远程MCP端点并与可用工具交互:

import asyncio
from mcp_playground import MCPClient

async def main():
    # Connect to a remote MCP endpoint with optional timeout and retry settings
    # IMPORTANT: URL must end with /sse for Server-Sent Events
    client = MCPClient(
        "http://localhost:8000/sse",  # Note the /sse suffix!
        timeout=30.0,      # Connection timeout in seconds
        max_retries=3      # Maximum retry attempts
    )
    
    # List available tools
    tools = await client.list_tools()
    print(f"Found {len(tools)} tools")
    
    # Invoke a calculator tool
    result = await client.invoke_tool(
        "calculator", 
        {"x": 10, "y": 5, "operation": "add"}
    )
    print(f"Result: {result.content}")  # Output: Result: 15
    print(f"Success: {result.error_code == 0}")

asyncio.run(main())

2.LLM电动工具选择

让AI根据自然语言查询选择合适的工具:

import os
from mcp_playground import MCPClient, OpenAIBridge

# Connect to MCP endpoint and create an LLM bridge
client = MCPClient("http://localhost:8000/sse")
bridge = OpenAIBridge(
    client,
    api_key=os.environ.get("OPENAI_API_KEY"),
    model="gpt-4o"
)

# Process a natural language query
result = await bridge.process_query(
    "Convert this PDF to text: https://example.com/document.pdf"
)

# The LLM automatically selects the appropriate tool and parameters
if result["tool_call"]:
    print(f"Tool: {result['tool_call']['name']}")
    print(f"Result: {result['tool_result'].content}")

3.命令行界面

该软件包包括一个强大的CLI工具,用于交互式测试和分析:

# Run the CLI tool (note the /sse suffix in the endpoint URL)
python -m mcp_playground.examples.llm_example --provider openai --endpoint http://localhost:8000/sse

配置选项:

usage: llm_example.py [-h] [--provider {openai,anthropic,ollama}]
                     [--openai-model {gpt-4o,gpt-4-turbo,gpt-4,gpt-3.5-turbo}]
                     [--anthropic-model {claude-3-opus-20240229,claude-3-sonnet-20240229,claude-3-haiku-20240307}]
                     [--ollama-model OLLAMA_MODEL] [--ollama-host OLLAMA_HOST]
                     [--endpoint ENDPOINT] [--openai-key OPENAI_KEY]
                     [--anthropic-key ANTHROPIC_KEY]

4.交互式测试环境

附带的Streamlit应用程序提供了一个全面的测试界面:

主要特点:

  • 多种聊天模式:

- 自动模式:LLM会自动决定何时使用工具 - 聊天模式:无需MCP工具的直接对话 - 工具模式:始终尝试使用MCP工具

  • 多LLM支持:OpenAI、Anthropic、Ollama和OpenRouter集成
  • 动态配置:连接到任何具有实时状态的MCP端点
  • 工具发现:自动检测和显示可用工具
  • 漂亮的响应格式:结构化数据的特殊格式
  • 错误处理:强大的连接管理,错误信息清晰

要运行Streamlit应用程序:

cd mcp-streamlit-app
pip install -r requirements.txt
streamlit run app.py

📦 安装

来源

git clone https://github.com/zanetworker/mcp-playground.git
cd mcp-playground
pip install -e .

使用pip(一旦发布)

pip install mcp-playground

🔧 api参考

MCP客户端

client = MCPClient(endpoint, timeout=30.0, max_retries=3)

参数:

  • endpoint:MCP端点URL(必须是http或https,并以结尾 /sse)
  • timeout:连接超时(秒)(默认值:30.0)
  • max_retries:最大重试次数(默认值:3)

⚠️ URL要求:

  • 端点URL 必须 以...结束 /sse 用于服务器发送事件通信
  • 正确URL示例:

- http://localhost:8000/sse - https://my-mcp-server.com/sse - http://192.168.1.100:3000/sse

方法

async list_tools() -> List[ToolDef]

列出MCP端点的可用工具。

async invoke_tool(tool_name: str, kwargs: Dict[str, Any]) -> ToolInvocationResult

使用参数调用特定工具。

async check_connection() -> bool

检查MCP端点是否可访问。

get_endpoint_info() -> Dict[str, Any]

获取有关已配置终结点的信息。

错误处理

客户端包括针对特定异常类型的稳健错误处理:

from mcp_playground import MCPClient, MCPConnectionError, MCPTimeoutError

try:
    client = MCPClient("http://localhost:8000/sse")
    tools = await client.list_tools()
except MCPConnectionError as e:
    print(f"Connection failed: {e}")
except MCPTimeoutError as e:
    print(f"Operation timed out: {e}")

LLM桥梁

OpenAIBridge

bridge = OpenAIBridge(mcp_client, api_key, model="gpt-4o")

人行天桥

bridge = AnthropicBridge(mcp_client, api_key, model="claude-3-opus-20240229")

奥拉马布里奇

bridge = OllamaBridge(mcp_client, model="llama3", host=None)

OpenRouterBridge

bridge = OpenRouterBridge(mcp_client, api_key, model="anthropic/claude-3-opus")

🔄 高级功能

重试逻辑和弹性

客户端包括具有指数回退的自动重试逻辑:

# Configure custom retry behavior
client = MCPClient(
    "http://localhost:8000/sse",
    timeout=60.0,     # Longer timeout for slow servers
    max_retries=5     # More retry attempts
)

# The client automatically retries failed operations
# with exponential backoff: 1s, 2s, 4s, 8s, 16s

连接健康监控

# Check if endpoint is reachable before operations
if await client.check_connection():
    tools = await client.list_tools()
else:
    print("Server is not reachable")

# Get detailed endpoint information
info = client.get_endpoint_info()
print(f"Connected to: {info['hostname']}:{info['port']}")

📋 需求

  • Python 3.8+
  • mcp>=0.1.0 (模型上下文协议库)
  • pydantic>=2.0.0 (数据验证)
  • openai>=1.70.0 (用于OpenAI集成)
  • anthropic>=0.15.0 (用于人类整合)
  • ollama>=0.1.7 (用于Ollama集成)
  • streamlit (用于交互式测试应用程序)

🐛 故障排除

常见问题

“任务组中未处理的错误”错误: 这通常发生在异步兼容性问题上。Streamlit应用程序会自动处理此问题,但对于自定义实现,请确保正确的异步上下文管理。

连接超时:

  • 增加超时参数: MCPClient(endpoint, timeout=60.0)
  • 检查MCP服务器是否正在运行且可访问
  • 验证端点URL是否正确,并以结尾 /sse

导入错误:

  • 确保安装了所有依赖项: pip install -e .
  • 检查Python版本兼容性(3.8+)

LLM集成问题:

  • 验证API密钥设置是否正确
  • 检查型号名称是否与支持的版本匹配
  • 对于Ollama,确保服务在本地运行

🚀 路线图

即将推出的功能

  • 流式HTTP支持 -增强的HTTP流媒体功能
  • WebSocket集成 -实时双向通信
  • 连接池 -提高了多个连接的性能
  • 高级缓存 -工具定义和结果的智能缓存
  • 监控仪表板 -MCP连接的实时监控
  • 插件系统 -自定义协议的可扩展架构

🤝 发展

有关开发设置、贡献指南和可用make命令的信息,请参阅 Developpent.md.

📄 许可证

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

🙏 致谢

  • 模型上下文协议(MCP)规范和社区
  • 用于LLM API访问的OpenAI、Anthropic和Ollama
  • Streamlit用于交互式测试框架

目录标签

目录标签

实时通信PythonClaudeMCP协议本地部署LLM集成Python工具包AI工具交互

支持客户端

Claude

接入字段

传输方式(transport,传输协议)

stdio

鉴权方式(authType,认证方式)

none

工具数量(toolCount,工具数)

0

资源数量(resourceCount,资源数)

0

提示词数量(promptCount,提示词数)

0

权限和风险

stdionone部署方式未说明

接入前请确认传输方式、认证方式和部署位置,并根据实际工具能力限制访问范围。

安装前确认

不要直接授予不必要的文件、网络或账号权限;先核对安装命令和配置内容。

来源信息

继续浏览同类 MCP