智能模型路由服务

MCP Router是一个智能模型上下文协议路由器,用于Cursor IDE,能根据查询分析、复杂度和用户偏好策略自动选择最佳LLM模型。

  • by ashcastelinocs124
  • Python
  • 本地部署
  • 2 星标
  • 更新于
在 GitHub 查看 AI-Castle-Labs/mcp-router

使用说明

🚀 MCP路由器

Cursor IDE的智能模型上下文协议路由器

根据查询分析、复杂性和您的首选策略,自动为每个任务选择最佳的LLM模型。


📐 系统架构

┌─────────────────────────────────────────────────────────────────────────────┐
│                              CURSOR IDE                                      │
│  ┌────────────────────────────────────────────────────────────────────────┐ │
│  │                         User Query                                      │ │
│  │   "Refactor this authentication system across multiple files"          │ │
│  └──────────────────────────────┬─────────────────────────────────────────┘ │
│                                 │                                            │
│                                 ▼                                            │
│  ┌────────────────────────────────────────────────────────────────────────┐ │
│  │                      MCP Router Server                                  │ │
│  │  ┌──────────────────┐    ┌───────────────────┐   ┌──────────────────┐  │ │
│  │  │  Query Analyzer  │───▶│   Model Scorer    │──▶│ Routing Decision │  │ │
│  │  │                  │    │                   │   │                  │  │ │
│  │  │ • Task Type      │    │ • Quality Score   │   │ • Selected Model │  │ │
│  │  │ • Complexity     │    │ • Cost Score      │   │ • Confidence     │  │ │
│  │  │ • Requirements   │    │ • Speed Score     │   │ • Reasoning      │  │ │
│  │  │ • Token Estimate │    │ • Strategy Weight │   │ • Alternatives   │  │ │
│  │  └──────────────────┘    └───────────────────┘   └──────────────────┘  │ │
│  └──────────────────────────────┬─────────────────────────────────────────┘ │
│                                 │                                            │
│                                 ▼                                            │
│  ┌────────────────────────────────────────────────────────────────────────┐ │
│  │                     Model Registry (17 Models)                          │ │
│  │                                                                         │ │
│  │  ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────────┐   │ │
│  │  │  FLAGSHIP   │ │  REASONING  │ │ NATIVE/FAST │ │  BUDGET/LEGACY  │   │ │
│  │  │             │ │             │ │             │ │                 │   │ │
│  │  │ • GPT-5.2   │ │ • o3        │ │ • Composer1 │ │ • GPT-4o-mini   │   │ │
│  │  │ • Claude4.5 │ │ • o3-mini   │ │ • Gemini 3  │ │ • Claude Haiku  │   │ │
│  │  │   Opus     │ │ • Claude3.7 │ │   Pro/Flash │ │ • DeepSeek V3   │   │ │
│  │  │ • Claude4.5 │ │   Sonnet   │ │             │ │ • DeepSeek R1   │   │ │
│  │  │   Sonnet   │ │             │ │             │ │                 │   │ │
│  │  └─────────────┘ └─────────────┘ └─────────────┘ └─────────────────┘   │ │
│  └──────────────────────────────┬─────────────────────────────────────────┘ │
│                                 │                                            │
│                                 ▼                                            │
│  ┌────────────────────────────────────────────────────────────────────────┐ │
│  │                    Cursor Executes Query                                │ │
│  │            (Using its own API keys for selected model)                  │ │
│  └────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘

数据流

┌──────────┐      ┌──────────────┐      ┌───────────────┐      ┌────────────┐
│  Query   │─────▶│   Analyze    │─────▶│     Score     │─────▶│  Recommend │
└──────────┘      └──────────────┘      └───────────────┘      └────────────┘
                         │                      │                      │
                         ▼                      ▼                      ▼
                  ┌─────────────┐       ┌─────────────┐       ┌─────────────┐
                  │ Task Type:  │       │ Apply       │       │ Model:      │
                  │ • reasoning │       │ Strategy:   │       │ Claude 4.5  │
                  │ • code_gen  │       │ • balanced  │       │ Sonnet      │
                  │ • edit      │       │ • quality   │       │             │
                  │ Complexity: │       │ • speed     │       │ Confidence: │
                  │ • medium    │       │ • cost      │       │ 88.45%      │
                  └─────────────┘       └─────────────┘       └─────────────┘

✨ 特性

特性 描述
🤖 智能路由 根据查询分析自动选择最佳模型
🧠 上下文感知路由 使用聊天记录和对话上下文进行更智能的模型选择
📊 4路由策略 balanced / cost / speed / quality
🔍 查询分析 检测任务类型、复杂性和特殊要求
💬 聊天历史分析 分析对话模式、主题、文件、语言和复杂性
💰 成本估算 执行前估算成本
⚡ 17型号 OpenAI、Anthropic、谷歌、Cursor、DeepSeek的最新2025款车型
🔧 光标本机 需要零个API键-游标处理执行

🏆 支持的型号(2025)

第1层:旗舰模型(复杂架构和重构)

模型 提供商 上下文 成本(入/出) 质量
GPT-5.2 OpenAI 25.6万 5.00美元/15.00美元 0.99/0.98
克劳德4.5作品 人类学 20万 25美元/75美元 0.99/0.99
克劳德4.5十四行诗 人像 20万 5.00美元/25.00美元 0.97/0.98

第二层:推理模型(思维链)

模型 提供商 上下文 成本(入/出) 质量
臭氧 OpenAI 20万 10美元/400美元 0.99/0.95
o3迷你(高) OpenAI 128K 1.50美元/6.00美元 0.95/0.92
克劳德3.7十四行诗 人像 20万 4.00美元/20.00美元 0.96/0.96

第3层:原生和快速模型

模型 提供商 上下文 成本(入/出) 质量
作曲家1 光标 128K 0.10美元/0.30美元 0.88/0.92美元
双子座3 Pro 谷歌 2米 $2.00/$8.00 0.96/0.94
双子座3闪光 谷歌 100万 0.10美元/0.40美元 0.88/0.90美元

第4层:预算/遗留模型

模型 提供者 上下文 质量
GPT-4o/GPT-4o-mini OpenAI 128K 0.95/0.85
克劳德3.5十四行诗/俳句 人物画 200K 0.96/0.88
Gemini 2.0 Pro/Flash 谷歌 2M/1M 0.94/0.85
DeepSeek V3 DeepSeek 128K 0.92/0.94
DeepSeek R1 DeepSeek 128K 0.96/0.92

🚀 快速开始

1.安装

git clone https://github.com/AI-Castle-Labs/mcp-router.git
cd mcp-router
pip install -r requirements.txt
pip install mcp  # MCP SDK for Cursor integration

2.配置光标

添加 ~/.cursor/mcp.json:

{
  "version": "1.0",
  "mcpServers": {
    "mcp-router": {
      "command": "python3",
      "args": ["/path/to/mcp-router/src/mcp_server.py"],
      "env": {}
    }
  }
}

注: 不需要API密钥!游标使用自己的键处理所有API调用。

3.重新启动游标

MCP路由器将出现在您的代理工具中。与以下内容一起使用:

  • @mcp-router get_model_recommendation "your task description"
  • @mcp-router analyze_query "your query"
  • @mcp-router list_models

💻 CLI使用情况

# Route a query (shows which model would be selected)
python main.py route "Explain how neural networks work"

# Route with strategy
python main.py route "Refactor this codebase" --strategy quality

# List all registered models
python main.py list

# Show routing statistics
python main.py stats

输出示例

============================================================
Routing Decision
============================================================
Query: Refactor this complex authentication system...

Selected Model: Claude 4.5 Sonnet
Model ID: claude-4.5-sonnet
Provider: anthropic
Confidence: 88.45%

Reasoning: Model is optimized for code_edit tasks; Selected for highest quality

Alternatives:
  - Composer 1 (composer-1)
  - Claude 3.5 Haiku (claude-3-5-haiku-20241022)
  - GPT-4o-mini (gpt-4o-mini)

🎯 路由策略

策略 描述 最适合
balanced 同等优化成本、速度和质量 通用
quality 优先考虑最高能力模型 复杂任务、重构
speed 优先考虑最快的响应时间 快速编辑,简单任务
cost 优先考虑最便宜的型号 注重预算的使用

🐍 Python API

from src.router import MCPRouter

# Initialize router (loads 17 default models)
router = MCPRouter()

# Route a query
decision = router.route(
    "Analyze this codebase architecture",
    strategy="quality"
)

print(f"Selected: {decision.selected_model.name}")
print(f"Model ID: {decision.selected_model.model_id}")
print(f"Confidence: {decision.confidence:.1%}")
print(f"Reasoning: {decision.reasoning}")

# Get alternatives
for alt in decision.alternatives[:3]:
    print(f"  Alternative: {alt.name}")

📁 项目结构

mcp-router/
├── src/
│   ├── router.py          # Core routing logic + 17 model definitions
│   ├── mcp_server.py       # MCP server for Cursor integration
│   ├── client.py           # API client for model execution
│   └── cursor_wrapper.py   # Cursor-specific utilities
├── config/
│   └── cursor_mcp_config.json  # Template for Cursor config
├── scripts/
│   └── setup_cursor.sh     # Automated setup script
├── docs/
│   ├── cursor_integration.md
│   ├── QUICKSTART_CURSOR.md
│   └── AGENT_SETTINGS.md
├── main.py                 # CLI entry point
├── requirements.txt
└── README.md

🔧 添加自定义模型

from src.router import MCPRouter, ModelCapabilities, TaskType

router = MCPRouter()

router.register_model(ModelCapabilities(
    name="My Custom Model",
    provider="custom",
    model_id="custom-model-v1",
    supports_reasoning=True,
    supports_code=True,
    supports_streaming=True,
    max_tokens=8192,
    context_window=32000,
    cost_per_1k_tokens_input=1.0,
    cost_per_1k_tokens_output=2.0,
    avg_latency_ms=600,
    reasoning_quality=0.85,
    code_quality=0.90,
    speed_score=0.80,
    preferred_tasks=[TaskType.CODE_GENERATION],
    api_key_env_var="CUSTOM_API_KEY"
))

🎮 光标命令

创建 .cursor/commands/route.md:

---
description: "Get model recommendation from MCP router for the current task"
---

Use the MCP router to determine the best model for the task at hand.

1. Analyze the current context
2. Call `@mcp-router get_model_recommendation` with task description
3. Present the recommendation with confidence and alternatives
4. Suggest switching models if needed

📊 MCP工具可用

工具 说明
route_query 路由查询并获取模型推荐(支持chat_history)
get_model_recommendation 无需执行即可获取推荐(支持chat_history)
analyze_chat_summary 分析聊天历史文本以提取路由信号
list_models 列出所有17个已注册的模特
get_routing_stats 获取使用统计数据
analyze_query 分析查询特征

具有聊天历史记录的上下文感知路由

路由器现在可以分析聊天记录,以做出更明智的路由决策:

// Example: Using chat history for context-aware routing
{
  "query": "Fix the authentication bug we discussed",
  "strategy": "quality",
  "chat_history": [
    {
      "role": "user",
      "content": "I'm working on auth.py and users can't log in",
      "timestamp": 1704067200
    },
    {
      "role": "assistant",
      "content": "Let me check the authentication flow...",
      "timestamp": 1704067205
    }
  ]
}

路由器分析聊天记录以检测:

  • 上下文深度:基于令牌计数的浅/中/深
  • 主导任务类型:代码生成、编辑、调试等。
  • 编程语言:检测Python、JavaScript、Rust等。
  • 提到的文件:跟踪正在处理的文件
  • 错误模式:标识调试会话
  • 话题:认证、数据库、API、测试等。
  • 复杂性:基于文件、语言和对话深度

这些信号影响模型选择:

  • 深层背景→ 具有较大上下文窗口的模型
  • 调试会话→ 高推理模型
  • 多文件任务→ 以代码为中心的模型
  • 多种语言→ 具有Polyglot功能的型号

🤝 贡献

  1. 克隆该仓库
  2. 创建要素分支
  3. 进行更改
  4. 提交拉取请求

📄 许可证

MIT许可证-请参阅 许可证 了解详情。


Built for the Cursor IDE ecosystem
AI Castle Labs