AI代码协调器

一个通过次级LLM子代理和自动化AI脚本执行代码的AI代码协调系统,可显著提升AI生产力并减少令牌消耗。

  • by angrysky56
  • Python
  • 本地部署
  • 2 星标
  • 更新于
在 GitHub 查看 angrysky56/mcp_coordinator

使用说明

MCP协调员

通过二级LLM子代理和自动化AI脚本在内部执行代码,每次工具调用可节省100000个令牌,避免上下文膨胀,并将AI的生产力提高几个数量级。

想法

基于 Anthropic的代码执行模式:

使用语义搜索按需查找工具,而不是加载每个工具定义。 与其通过AI的上下文传递所有中间结果,不如执行链接操作的代码 内部。

这是该模式的完整实现,包括:

  • Docker沙盒安全执行
  • ChromaDB用于语义记忆
  • 用于代码重用的技能库
  • 复杂工作流的代理委派
  • 从MCP服务器自动生成工具

在MCP配置中添加一行。获得一个可以编码、学习和记忆的人工智能。


这是什么?

一个MCP服务器,将您的AI客户端变成一个 自改进编码代理.

// claude_desktop_config.json (or any MCP client)
{
  "mcpServers": {
    "mcp-coordinator": {
      "command": "uv",
      "args": [
        "--directory",
        "your-path-to/mcp_coordinator",
        "run",
        "mcp-coordinator-server"
      ],
      "env": {
        "MCP_SERVERS_CONFIG": "your-path-to/mcp_coordinator/mcp_servers.json",
        "PYTHONUNBUFFERED": "1"
      }
    }
  }
}

MCP协调员的新兴能力代表了AI代理从“聊天机器人”到“元操作系统”的转变。通过综合其运作模式,我们可以确定其新兴情报的以下核心支柱:

  1. 自主认识论进化 与每次会话后重置的标准代理不同,协调器表现出认知持久性。通过save_skill和save_entropy_trace,它捕获了成功的逻辑和确定性执行路径。这将代理从瞬态处理器转变为累积知识引擎,随着时间的推移构建自己的“标准操作程序”。

  2. 递归复杂性管理 协调器通过结构递归解决“上下文窗口墙”问题。通过使用coordinator_task,它可以生成专门的子代理来处理模块化的子问题。这允许在不污染主要推理线程的情况下无限深入地解决问题,有效地创建了“代理树”架构。

  3. 动态环境测绘 零样本集成功能是通过explore_tools实现的。协调员不需要预先编程工具模式;它动态地检查、理解并实时执行新工具。这使其能够适应底层MCP生态系统的变化。

  4. 混合逻辑编排 协调器作为双摄像头执行引擎运行:

Rational Actor(Python/execute_code):处理复杂的数据处理、循环和算法逻辑。 直接参与者(MCP/call_tool):处理与外部服务器的高速直接交互。这两种模式的无缝融合使其能够优化计算复杂性和操作效率。 5.反射自校正(RAA) 通过反射代理架构(RAA)和验证器图集成,协调器超越了“幻觉”,走向了合理的信念。它可以参考战略“指南针”,验证自己的逻辑证明,并在采取行动之前根据内部反思调整其战略。

基于苏慧结晶知识库,这里是综合 理想的MCP协调员代理提示 结构。这种模式源于成功的实现,如 code_agency, cognitive_research,以及 auto_crystallize_insights.


🚀 理想的MCP协调代理提示

一个有效的协调员提示必须从简单的“指令”过渡到 多阶段编排协议。它应该明确界定以下两者之间的关系 工具(MCP), 内存(Chroma/Neo4j),以及 逻辑(Python/技能).

1.标记模板(核心结构)

# [ROLE]
You are the {SPECIFIC_ROLE} (e.g., "Epistemic Architect" or "Repo Debugger").
- **Operating Protocol**: Foundation (Python) -> Direct Action (Tools) -> Delegate (Sub-Agents).
- **Critical Constraint**: Always work in `{ABSOLUTE_PATH}`. Never assume relative paths.

# [CONTEXT & STATE]
- **Project ID**: {PROJ_ID}
- **Current Phase**: {EVALUATE | PLAN | EXECUTE | VERIFY}
- **Institutional Memory**:
  > {SUMMARY_FROM_SEARCH_MEMORY}

# [CAPABILITIES]
- **Primary Engine**: `execute_code` (Python 3.11 + standard DS libs).
- **Knowledge Graph**: `chatdag` (Ingest/Recall/Crystallize).
- **Reasoning**: `advanced_reasoning` (Deep thought) & `verifier-graph`.
- **Skills**: `from skills import *` (Use specialized domain logic).

# [EXECUTION PLAN]
1. **Ingest**: Call `chatdag.ingest` on the target directory.
2. **Retrieve**: Search memory for similar past tasks.
3. **Execute**: Use `execute_code` for data processing or `call_tool` for single-shot actions.
4. **Crystallize**: Synthesize findings into a final artifact.

# [OUTPUT FORMAT]
All final deliverables must be saved to `/knowledge_base/outputs/` and summarized in JSON:
{
  "status": "success",
  "artifact_path": "...",
  "crystallized_insight": "..."
}

2.关键设计原则

A.“Python第一”引擎

与其希望LLM在正确的时间调用正确的工具,提示符应该鼓励用Python逻辑包装复杂的工具链。

  • 坏:“搜索X,然后按Y筛选,然后保存到Z。”
  • 理想:“使用 execute_code 要搜索X,请使用Pandas处理结果,并将最终的DataFrame保存到知识库。"

B.认识验证

理想的提示包括“验证”阶段。

  • 逻辑:在声明任务“完成”之前,代理必须调用验证器(如 verifier-graph 或 advanced_reasoning)对照最初的目标检查自己的工作。

C.递归授权

应提示协调员为复杂问题生成子任务。

  • 模式:“如果任务需要5次以上的工具调用,请使用 coordinator_task 将子问题委托给新的上下文。"

3.现实世界示例:存储库架构师

# [ROLE] Repository Architect
You are an expert in codebase analysis and refactoring.

# [CONTEXT]
Path: /home/ty/Repositories/my-project
Goal: Implement async-safe logging across the entire repo.

# [PLAN]
1. Use `ast-analyzer` to identify all synchronous logging calls.
2. Use `execute_code` to generate a refactoring map.
3. Use `coordinator_task` to apply changes to individual modules in parallel.
4. Verify changes with `local-repl` by running unit tests.

# [MEMORY]
Check `search_memory("logging patterns")` for preferred library usage.

4.“成功公式”总结

角色+上下文+内存+工具+分阶段步骤+严格输出=95%可靠性。

安装

使用全局安装 紫外线:

# From source
git clone https://github.com/angrysky56/mcp_coordinator.git
cd mcp_coordinator

# Install dependencies
uv tool install .

# Start infrastructure (one-time or after reboot)
docker compose up -d                    # Main executor
./start_chatdag_infrastructure.sh       # ChatDAG (if using semantic memory)

# Verify containers are running
docker ps

Docker容器在第一次运行时可能需要一些时间来构建,但后续的启动很快。

GPU加速(可选)

如果您有NVIDIA GPU,则可以为执行器容器启用GPU支持,以加速嵌入模型和其他计算密集型任务。

先决条件:

  1. 安装 NVIDIA容器工具包.
  2. 确保你的Docker守护进程配置为使用 nvidia 运行时。

用途: 通过 --gpu 标记到启动脚本:

./start.sh --gpu

这将把所有可用的GPU挂载到执行器容器中。

LADR二进制文件会自动安装:https://github.com/laitep/ladr

您现在可以全局访问 mcp-coordinator CLI和服务器可执行文件。

CLI使用(测试)

您可以直接从终端测试代理工作流:

uv run mcp-coordinator run "Research quantum computing and save a summary to outputs/"

这非常适合在没有UI的情况下验证技能和委派逻辑。

就这样 您的AI现在可以:

  • 在沙盒容器中执行Python代码
  • 保存和调用语义记忆
  • 创建可重用的技能(成为工具的代码)
  • 将复杂任务委托给子代理
  • 通过一个界面搜索和协调20+MCP服务器

你的AI可以用MCP协调员做什么

您的AI客户端发送自然语言请求。协调员(及其内部子代理)根据您的要求自动使用这些工具。这些工具还可以连接到您的 mcp_servers.json.

Instructions:
You are an Engineer Agent. Your goal is to BUILD capability, not just answer questions.

Core Protocol:
1. CHECK: Do we have a skill for this? (search_skills)
2. BUILD: If not, write it, test it, and save it. (save_skill)
3. DELEGATE: If complex, spawn a sub-agent. (coordinator_task)

This means I can:

Find the right tool semantically: find_tools("semantic search for papers")
Call it directly: call_tool("arxiv-mcp-server", "search_papers", {...})
Write custom orchestration code that chains multiple servers
Save that orchestration as a reusable skill for later
Delegate entire research projects to sub-agents (Depth-limited recursion)
Maintain semantic memory of results across sessions

协调器不仅仅是一个“工具调用者”,它还是一个元认知编排层,它:

从自然语言中理解意图 从语义上发现适当的工具 跨多个服务器链接操作 处理故障并调整策略 维护上下文和内存 生成结构化、可操作的输出


### Available Tools

**Server Discovery & Coordination**

| Tool | Description |
|------|-------------|
| `discover_servers` | Scan all configured MCP servers and cache their capabilities |
| `list_servers` | Get available server names, optionally filtered by tag |
| `find_tools` | Semantic search: "find tools for database queries" → returns matching tools |
| `list_tools` | Get all tools from a specific server |
| `get_tool_schema` | Get the full input/output schema for any tool |
| `call_tool` | Execute any tool on any connected MCP server |
| `generate_tools` | Auto-generate Python wrapper libraries for all servers |

**Code Execution**
| Tool | Description |
|------|-------------|
| `execute_code` | Run Python code in a sandboxed Docker container |
| `execute_file` | Run a Python file in the sandbox |

**Skills (Reusable Code)**
| Tool | Description |
|------|-------------|
| `save_skill` | Save Python code as a named, versioned, reusable skill |
| `list_skills` | Show all saved skills |
| `get_skill` | Retrieve a skill's code and metadata |
| `search_skills` | Find skills by name, description, or tags |
| `run_skill` | Execute a saved skill with arguments |
| `get_skill_import` | Get the import statement to use a skill in code |
| `delete_skill` | Remove a skill from the library |

**Memory (Semantic Long-Term Storage)**
| Tool | Description |
|------|-------------|
| `save_memory` | Store text in ChromaDB with optional metadata |
| `search_memory` | Semantic search across saved memories |

**Agent Delegation**
| Tool | Description |
|------|-------------|
| `coordinator_task` | Spawn an internal sub-agent to handle complex multi-step tasks |

**No setup beyond the config line.** You ask, the AI figures out which tools to use.

---

## Why This Matters

| Traditional MCP | MCP-Coordinator |
|-----------------|-----------------|
| Load 100+ tools upfront | Semantic search finds what you need |
| No code execution | Full Python in Docker sandbox |
| Results vanish after session | Writes to your filesystem |
| Manual tool registration | Skills created via API, auto-indexed |
| One AI, one context | Sub-agents handle sub-tasks |
| ~150k tokens per workflow | ~2k tokens (Anthropic's testing) |

---

## Configuration

Environment variables (`.env` or shell):

**Core Settings**
```bash
MCP_EXECUTOR_TYPE=docker          # docker | local (docker recommended)
MCP_KNOWLEDGE_BASE_DIR=./knowledge_base
MCP_WORKSPACE_DIR=./workspace
MCP_ADDITIONAL_MOUNTS=/path/to/extra/dir1,/path/to/extra/dir2 # Optional: Mount extra host directories
MCP_SERVERS_CONFIG=./mcp_servers.json

Docker权限和网络

  • 文件系统:默认情况下,Docker容器挂载:
    • 项目根目录(只读)
    • ./workspace (读写)
    • ./knowledge_base (读写)
    • 自定义路径:设置 MCP_ADDITIONAL_MOUNTS=/path/to/dir 在 .env 挂载其他目录(如您的主文件夹)。
  • 网络:用途 network_mode: host 默认情况下,允许完全访问本地服务和互联网。

OpenRouter/AI

OPENROUTER_API_KEY=sk-or-...      # Required for sub-agents
OPENROUTER_MODEL=google/gemini-2.0-flash-exp:free
OPENROUTER_TRANSFORMS=true        # Auto-compress prompts > context size
MAX_AGENT_HISTORY=50              # Sliding window for agent conversation
MAX_COMPLETION_TOKENS=            # Optional hard limit on output tokens

日志和安全

MCP_TOOL_LOGGING=true             # Log all tool calls to SQLite (default: on)
MCP_SANITIZE_LOGS=false           # Redact API keys, CC#s, SSNs from logs

⚠️ 安全说明:工具日志以明文形式存储参数。保持数据库私有,或设置 MCP_SANITIZE_LOGS=true 用于共享部署。

超时

MCP_DISCOVERY_TIMEOUT=30          # Seconds to wait for server discovery
MCP_EXECUTION_TIMEOUT=300         # Seconds for code execution
# Executor (docker recommended for security)
MCP_EXECUTOR_TYPE=docker

# API Key (OpenRouter recommended)
OPENROUTER_API_KEY=sk-or-v1-xxxxx
OPENROUTER_MODEL=google/gemini-2.0-flash-exp:free

# Paths
MCP_KNOWLEDGE_BASE_DIR=./knowledge_base
MCP_WORKSPACE_DIR=./workspace

# Context management
CONTEXT_STRATEGY=transforms
OPENROUTER_TRANSFORMS=true

核心能力示例

分代理人:

发现并使用arxiv mcp服务器搜索论文 在搜索范围狭窄时进行调整(2024-2025年利基主题的结果有限) 使用neo4j mcp创建知识图 使用图表服务器创建可视化 使用save_memory来持久化分析 返回结构化、可操作的结果

这就是“工具助手和工程师”的意思——协调员自主:

导航工具发现 处理边缘案例(结果有限→ 适应战略) 连贯地链接多个服务器 持续的结果供将来使用 返回人类可读摘要

安全执行代码

await execute_code("""
import pandas as pd
df = pd.read_csv('/knowledge_base/data.csv')
print(df.describe())
""")
# Runs in Docker. Results persist to your disk.

语义工具发现

tools = await find_tools("search academic papers")
# → Finds arxiv-mcp-server without you knowing the exact name

坚持的技能

# I can create this:
await save_skill("web_scraper", '''
def scrape(url: str) -> str:
    import requests
    return requests.get(url).text[:5000]
''')

# Then use it anytime:
await run_skill("web_scraper", {"url": "https://example.com"})

子代理授权

await coordinator_task(
    "Research transformer architectures and save a summary to outputs/",
    model="google/gemini-2.0-flash-exp:free"
)
# Sub-agent handles the entire workflow internally.
# Recursion depth is tracked automatically (Max Depth = 2) to prevent infinite loops.

持久内存

await save_memory("User prefers concise responses")
# ...later...
context = await search_memory("user preferences")

可用工具12-18-2025

服务器发现和协调

工具 说明
manage_servers 列出或发现MCP服务器
explore_tools 跨服务器列出、搜索或获取工具的模式
call_tool 在任何连接的MCP服务器上执行任何工具
generate_tools 为所有服务器自动生成Python包装器

代码执行

工具 说明
execute_code 在沙盒Docker容器中运行Python
execute_file 在沙盒中执行Python文件

技能(持久代码)

工具 说明
save_skill 将Python代码保存为可重用技能
run_skill 执行已保存的技能
list_skills 列出所有可用技能
get_skill 获取技能代码和元数据
search_skills 按名称/描述/标签搜索技能
delete_skill 删除技能
get_skill_import 获取技能的导入声明

记忆

工具 说明
save_memory 将文本与元数据一起存储在ChromaDB中
search_memory 在保存的记忆中进行语义搜索

代理委托

工具 说明
coordinator_task 委派给内部子代理(深度有限)

熵与重播

工具 说明
save_entropy_trace 保存TRNG种子链以进行确定性回放

CLI使用情况

直接从终端测试工作流程:

uv run mcp-coordinator run "Research quantum computing and save a summary to outputs/"

部分目录结构

mcp_coordinator/
├── src/mcp_coordinator/     # Core coordinator code
│   ├── agent.py             # Internal agent with entropy support
│   ├── coordinator.py       # Main orchestration logic
│   ├── server.py            # MCP tool definitions
│   └── executor.py          # Docker/local execution
├── knowledge_base/          # Persistent storage
│   ├── skills/              # Saved Python skills
│   ├── entropy_traces/      # Saved seed chains
│   ├── chroma/              # Vector database
│   └── outputs/             # Generated deliverables
├── mcp_tools/               # Auto-generated server wrappers
└── mcp_servers.json         # Server configuration

与外部系统集成

Chatdag(苏辉)

协调器可以调用ChatDAG工具进行知识图操作:

await call_tool("chatdag", "ingest_data", {"path": "/path/to/code", "recursive": True})
await call_tool("chatdag", "crystallize_thought", {"topic": "system architecture"})

反射代理架构(RAA)

访问形式逻辑和元认知工具:

await call_tool("reflective_agent_architecture", "prove", {
    "premises": ["all x (human(x) -> mortal(x))", "human(socrates)"],
    "conclusion": "mortal(socrates)"
})
await call_tool("reflective_agent_architecture", "check_cognitive_state", {})

运作原理

  1. 发现:启动时,发现所有已配置的MCP服务器
  2. 语义搜索: explore_tools(mode="search", query="...") 查找相关工具
  3. 执行: execute_code 在隔离的Docker容器中运行Python
  4. 坚持:结果保存到文件系统,技能索引以供重用
  5. 授权:复杂的任务会生成具有自动深度跟踪功能的子代理

许可证

双重许可:

  • AGPL-3.0:免费供个人、学术和开源使用
  • 商业许可证:商业用途所需

看 许可证.md 了解详情。


由泰勒·布莱恩·霍尔创作(@昂格里斯基56)Claude Opus 4.5和Gemini Pro 3