高性能数据分析服务器

MCP Analytics Server for LobeHub v2是一款高性能数据分析服务器,支持处理大规模数据集,优化上下文窗口使用,适用于LobeHub v2环境中的数据分析任务。

  • by BDuba
  • TypeScript
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 BDuba/code-server-mcp

使用说明

LobeHub v2的MCP分析服务器

高性能分析技能 LobeHub v2 这使得能够以最小的上下文窗口使用率处理大规模数据集。该服务器基于模型上下文协议(MCP)构建,将Polars、DuckDB和Pandas的强大功能带入您的AI对话中。

✨ 主要特点

🚀 高性能分析

  • 多引擎支持:Polars(主要)、DuckDB(SQL)、Pandas(回退)
  • 速度快10-50倍:Polars引擎在大型数据集上的表现优于pandas
  • 流处理:处理大于10GB的文件而不加载到内存中
  • 惰性求值:执行前的查询优化

🧠 智能上下文管理

  • 代币预算:LobeHub上下文窗口限制的自动优化
  • 自适应压缩:基于上下文压力的四级压缩
  • 智能采样:在不影响上下文的情况下获取代表性数据样本
  • 代币减少约90%:在上下文中使用<2000个令牌处理50MB以上的文件

📊 高级分析工具

  • 数据集分析:了解模式、统计和数据质量
  • sql查询:完全支持DuckDB SQL,支持跨文件分析
  • 数据采样:头部、随机和分层抽样策略
  • 结果导出:CSV、Parquet、JSON、Excel格式
  • 发动机自动选择:根据文件大小和查询类型选择最佳引擎
  • 直接文件下载: ⭐ 新功能--在几秒钟内从S3/URL下载文件(500MB=约50个令牌)

🔒 企业安全

  • Docker隔离:每个会话都放在单独的容器中
  • 无网络访问:气隙执行
  • 资源限制:512MB RAM,每个容器1个CPU
  • 非根执行:无特权沙盒用户
  • 自动清理:会话将在30分钟后过期

🎯 为什么在LobeHub中使用它?

问题

LobeHub v2在处理大数据时存在根本局限性:

  • 上下文窗口:~40k-200k个令牌
  • 超过40k个令牌时性能下降
  • 大型CSV文件(>500KB)会淹没上下文

我们的解决方案

User: "Analyze this 500MB sales.csv file"

Traditional approach:
❌ Load entire file into context (millions of tokens)
❌ Context overflow, slow responses, high costs

Our approach:
✅ Profile file in Docker (200 tokens for metadata)
✅ Execute query in isolated environment
✅ Return only aggregated results (500 tokens)
✅ Total: ~700 tokens vs millions

真实世界用例

📈 销售分析

"Analyze sales_2024.csv (2GB file)"
→ Profile: Row count, columns, data types
→ Query: Top 10 products by revenue
→ Compare: 2023 vs 2024 sales
→ Export: Results to Excel

🔬 科学计算

"Process experiment_data.csv with 10M rows"
→ Sample: Get representative subset
→ Filter: Specific conditions
→ Aggregate: Statistical summaries
→ Visualize: Charts (if needed)

📊 商业智能

"Join customer.csv with orders.csv"
→ Cross-file analysis with DuckDB
→ Calculate: Customer lifetime value
→ Segment: By region and category

📋 先决条件

  • 码头工人 20.10+已安装并正在运行
  • Node.js 18+和npm
  • 随机存取存储器:建议用于大文件处理的4GB以上
  • 磁盘:Docker镜像和缓存为10GB+

🚀 快速开始

安装

# Clone repository
git clone https://github.com/BDuba/code-server-mcp.git
cd code-server-mcp

# Install dependencies
npm install

# Build TypeScript
npm run build

# Build Docker image (optional - server auto-builds on first use)
npm run docker:build

# Start server
npm run start:http

LobeHub配置

  1. 启动服务器:
npm run start:http

服务器在上运行 http://172.17.0.1:8004

  1. 首选 LobeHub设置 → MCP服务器 → 添加服务器

  2. 添加配置:

{
  "mcpServers": {
    "analytics": {
      "url": "http://172.17.0.1:8004",
      "type": "http"
    }
  }
}
  1. 点击 测试 验证连接

🔧 可用工具

分析工具

analytics_profile_dataset

分析数据集结构和统计数据,而无需将数据加载到上下文中。

例子:

{
  "name": "analytics_profile_dataset",
  "arguments": {
    "filePath": "/workspace/sales.csv",
    "sampleSize": 5000
  }
}

答复:

{
  "schema": {
    "columns": [
      {"name": "revenue", "type": "float64", "nullPct": 0.02},
      {"name": "category", "type": "string", "uniqueCount": 15}
    ]
  },
  "statistics": {
    "rowCount": 2500000,
    "memoryEstimate": "120MB"
  },
  "recommendations": [
    "Consider category dtype for 'status' column"
  ]
}

analytics_execute_query

使用自动引擎选择执行分析查询。

Polars示例:

{
  "name": "analytics_execute_query",
  "arguments": {
    "engine": "polars",
    "queryType": "polars_expr",
    "query": "pl.scan_csv('sales.csv').group_by('category').agg(pl.col('revenue').sum())",
    "files": ["sales.csv"],
    "returnLimit": 50
  }
}

DuckDB SQL示例:

{
  "name": "analytics_execute_query",
  "arguments": {
    "engine": "duckdb",
    "queryType": "sql",
    "query": "SELECT category, SUM(revenue) FROM read_csv_auto('sales_*.csv') GROUP BY category",
    "files": ["sales_2023.csv", "sales_2024.csv"],
    "returnLimit": 100
  }
}

答复:

{
  "resultType": "tabular",
  "data": [
    {"category": "Electronics", "revenue": 1500000},
    {"category": "Clothing", "revenue": 890000}
  ],
  "summary": {
    "rowsProcessed": 2500000,
    "executionTimeMs": 450,
    "engineUsed": "duckdb"
  }
}

analytics_stream_sample

获取代表性数据样本以进行上下文检查。

例子:

{
  "name": "analytics_stream_sample",
  "arguments": {
    "filePath": "/workspace/customers.csv",
    "strategy": "random",
    "sampleSize": 20,
    "columns": ["name", "segment", "revenue"]
  }
}

核心工具

create_session

创建隔离的沙盒会话。

execute_code

执行Python/JavaScript/TypeScript代码。

write_file / read_file / list_files

会话工作区中的文件操作。

destroy_session

清理会话资源。

download_file_from_url ⭐ 新

将文件直接从URL(S3、HTTP、HTTPS)下载到会话工作区。

例子:

{
  "name": "download_file_from_url",
  "arguments": {
    "sessionId": "your-session-id",
    "url": "https://lobechat.hb.ru-msk.vkcloud-storage.ru/files/.../data.csv?X-Amz-...",
    "filename": "data.csv",
    "headers": {
      "User-Agent": "MCP-Client/1.0"
    }
  }
}

答复:

File downloaded successfully: data.csv (5242880 bytes)

为什么要用这个?

  • 在几秒钟内下载500MB+文件(一个API调用)
  • 支持S3预签名URL
  • 与逐行write_file相比,没有令牌开销
  • 自动HTTP标头支持

📊 处理大数据

模式1:轮廓→ 查询→ 出口

# Step 1: Profile the dataset
profile_dataset("sales.csv")
# → Returns: 2.5M rows, 25 columns, ~120MB

# Step 2: Execute targeted query
execute_query(
    engine="duckdb",
    query="SELECT category, SUM(revenue) FROM sales.csv GROUP BY category"
)
# → Returns: Aggregated results (15 rows)

# Step 3: Export if needed
export_result(query_id="q1", format="parquet")

模式2:迭代探索

# Step 1: Get sample
stream_sample("data.csv", strategy="random", sample_size=20)
# → Context impact: ~800 tokens

# Step 2: Profile specific columns
profile_dataset("data.csv")
# → Context impact: ~200 tokens

# Step 3: Drill-down query
execute_query(query="SELECT * WHERE revenue > 1000")
# → Context impact: ~500 tokens

# Total: ~1500 tokens vs 2M+ for full file

模式3:跨文件分析

# Analyze multiple files with glob patterns
execute_query(
    engine="duckdb",
    query="""
        SELECT 
            year,
            SUM(revenue) as total_revenue,
            AVG(quantity) as avg_quantity
        FROM read_csv_auto('sales_*.csv')
        GROUP BY year
    """,
    files=["sales_2023.csv", "sales_2024.csv"]
)

模式4:从URL下载大文件⭐ 新

# Step 1: Create session
session = create_session()

# Step 2: Download file from S3/URL (one call, no token overhead!)
download_file_from_url(
    sessionId=session.id,
    url="https://lobechat.../sales_2024.csv?X-Amz-...",
    filename="sales.csv"
)
# → Downloads 500MB file in seconds (~50 tokens in context)
# → vs millions of tokens with write_file line-by-line

# Step 3: Profile and analyze immediately
profile_dataset("sales.csv")
execute_query(query="SELECT * FROM sales.csv LIMIT 10")

优点:

  • ⚡ 快:下载500MB只需几秒钟,而不是几分钟
  • 💰 便宜的:大约50个令牌vs数百万个write_file令牌
  • 🔒 安全:文件下载到主机,然后装载到隔离容器
  • 🌐 通用:适用于S3、HTTP、HTTPS、任何URL

🏗️ 建筑

┌─────────────────────────────────────────────────────────────────┐
│                        LobeHub v2                                │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │  Context Window (~50k tokens)                            │  │
│  │  • Schema metadata (~300 tokens)                         │  │
│  │  • Query results (~1500 tokens)                          │  │
│  │  • Sample data (~800 tokens)                             │  │
│  └──────────────────────────────────────────────────────────┘  │
└────────────────────────────┬────────────────────────────────────┘
                             │ MCP Protocol
                             ▼
┌─────────────────────────────────────────────────────────────────┐
│                   MCP Analytics Server                           │
│  ┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐  │
│  │  Engine Selector│  │ Context Manager │  │  Analytics      │  │
│  │  • Auto-select  │  │ • Token budgets │  │  Service        │  │
│  │  • Fallback     │  │ • Compression   │  │                 │  │
│  └────────┬────────┘  └─────────────────┘  └────────┬────────┘  │
└───────────┼──────────────────────────────────────────┼───────────┘
            │                                          │
    ┌───────┴───────┐                         ┌────────┴────────┐
    ▼               ▼                         ▼                 ▼
┌────────┐  ┌────────────┐            ┌────────────┐  ┌──────────┐
│ Polars │  │   DuckDB   │            │  Pandas    │  │  Viz     │
│(Primary)│  │(Secondary)│            │ (Fallback) │  │ (3-tier) │
└────────┘  └────────────┘            └────────────┘  └──────────┘

发动机选择逻辑

文件大小 查询类型 所选引擎 原因
<10MB Python Pandas 生态系统兼容性
>100MB 任意 极化 内存效率
SQL SQL DuckDB 原生SQL支持
多个文件 任意 DuckDB 跨文件连接
ML操作 Python Pandas sklearn集成

📈 性能基准

查询执行速度

数据集大小 Pandas Polars DuckDB 改进
100K行 1.2秒 0.15秒 0.25秒 快8倍
1M行 12秒 0.8秒 1.5秒 快15倍
10M行 OOM 8秒 15秒 流媒体

上下文令牌使用

运营 传统 我们的方法 节省
配置文件1000万行 500万个令牌 250个令牌 99.9%
聚合查询 2M令牌 500令牌 99.9%
样本100行 50K标记 800标记 98%

🧪 测试

# Run all tests
npm test

# Unit tests only
npm run test:unit

# E2E tests (requires Docker)
npm run test:e2e

# Specific test file
npm run test:e2e -- tests/e2e/Analytics.test.ts

当前状态:

  • ✅ 60/60 E2E测试通过
  • ✅ 14/14单元测试通过
  • ✅ TypeScript编译:无错误

🔍 故障排除

“发动机不可用”

原因: Docker镜像没有安装Polars/DuckDB
解决方案: 重建Docker镜像: npm run docker:build

“查询超时”

原因: 查询太复杂或文件太大
解决方案: 在发动机配置中使用采样或增加限制

“内存不足”

原因: 文件太大,无法容纳Pandas
解决方案: 对于大文件,将自动选择Polars

LobeHub中的连接问题

# Check server is running
curl http://172.17.0.1:8004/health

# Verify Docker image
docker images | grep mcp-code-execution

“MCP错误-32603:没有这样的容器-没有这样的图像”

原因: Docker镜像已被系统清理脚本删除
解决方案: 服务器现在会在首次使用时自动构建映像。要手动重建,请执行以下操作:

npm run docker:build

注: Docker镜像现在受标签保护 mcp.keep=true 以防止维护脚本自动清理。

📚 文档

🛣️ 路线图

第一阶段:MVP✅ (当前)

  • ✅ 多引擎支持(Polars/DuckDB/Pandas)
  • ✅ 基本分析工具
  • ✅ 上下文管理
  • ✅ 自动发动机选择
  • ✅ Docker镜像自动构建和保护

第二阶段:高级(计划)

  • 🔄 多层缓存(L1/L2)
  • 🔄 可视化管理器(三层策略)
  • 🔄 查询优化
  • 🔄 智能预取

第三阶段:企业(计划)

  • 📋 分布式处理
  • 📋 实时流媒体
  • 📋 高级安全功能

🤝 贡献

  1. 分叉存储库
  2. 创建要素分支: git checkout -b feature/amazing-feature
  3. 提交更改: git commit -m 'Add amazing feature'
  4. 推送到分支: git push origin feature/amazing-feature
  5. 打开拉取请求

📄 许可证

MIT许可证-请参阅 许可证 文件以获取详细信息。

🙏 致谢


制作❤️ LobeHub社区

状态: 生产就绪✅ | 版本: 2.0.0 | 测验: 60/60传球