AI Hub MCP Server
# AI Hub
> **English** | [简体中文](./README.zh-CN.md)
[](https://github.com/Siq5005/ai-hub/releases/tag/v2.0.0)
[](./LICENSE)
[](https://nodejs.org/)
[](https://modelcontextprotocol.io/)
**AI Hub** is a local-first, zero-polling **Multi-CLI AI Orchestrator, MCP Server & Real-Time Data Hub**.
It lets a lead coding agent (such as **Antigravity**) delegate read-only codebase scouting to **DSH CLI** and heavy backend planning, chunked implementation, and double-blind L2 reviews to **Codex CLI** — while tracking real token usage across all three agents, enforcing local security boundaries, and persisting versioned interface contracts in SQLite.
---
## Why AI Hub?
- **Save expensive lead-agent quota**: Offload high-volume read-only codebase scans to fast, low-cost CLI inspectors (`dsh_inspect`) and chunked backend/script/test work to dedicated backend CLIs (`codex_exec_backend`).
- **True double-blind planning & review**: Run independent architecture proposals (`codex_plan_backend(blind_mode=true)`) and blocking L2 reviews (`codex_review(blind_mode=true)`) without leaking lead-agent bias.
- **Zero-polling async wakeup**: Long tasks automatically detach (`async: true` or `soft_wait_sec`) and return a shell-safe `wait-run.mjs` SSE waiter — no MCP 3-minute timeouts, no `sleep` polling loops.
- **Honest, real token accounting**: Collects exact token usage from all three agents (Codex JSONL, DSH multi-frame Zstandard sessions, and Antigravity transcripts) with explicit `reported` vs `unknown` semantics and strict isolation of demo runs.
- **Local security floor by default**: Loopback-only HTTP server with per-instance random session tokens, zero wildcard CORS, strict `Host`/`Origin` enforcement, CSRF-resistant writes, child env allowlists, secret redaction, and single-instance SQLite ownership locking.
---
## Architecture
```mermaid
flowchart TB
Lead["Lead Agent (Antigravity / MCP Host)"]
MCP["AI Hub MCP Server (stdio JSON-RPC)"]
Disp["Unified Dispatcher\n(Concurrency + Canonical Workdir Write Mutex)"]
DB[("SQLite WAL + PRAGMA user_version\nruns / run_logs / contracts / contract_revisions")]
HTTP["Loopback HTTP + SSE Server (127.0.0.1)\nRandom Token Auth + Host/Origin Guard"]
UI["Live Dashboard\n(Embedded MCP App & Standalone Browser)"]
Wait["wait-run.mjs\n(Zero-Polling SSE Wakeup)"]
Codex["Codex CLI Adapter\n(plan / exec / L2 review)\nEnv Allowlist + JSONL Usage"]
DSH["DSH CLI Adapter\n(L1 Read-Only Scout + Git Guard)\nMulti-Frame Zstd Usage"]
Usage["Usage Collectors\n(Transcript + Zstd + Backfill)"]
Lead <-->|MCP Tools & App| MCP
MCP --> Disp
Disp --> Codex
Disp --> DSH
Codex --> DB
DSH --> DB
Usage --> DB
MCP --> DB
DB --> HTTP
HTTP <-->|X-AI-Hub-Token / SSE| UI
HTTP <-->|Bearer Token / SSE| Wait
```
---
## Key Features (v2.0.0)
### 1. Multi-CLI Orchestration & Adapter Registry
- Formal adapter descriptors in [`src/adapters.mjs`](./src/adapters.mjs) (`antigravity`, `codex`, `dsh`) declaring capabilities, sandbox policy, allowed child env prefixes, and usage sources, exposed via `GET /api/adapters`.
- Canonical worktree write mutex in [`src/dispatch.mjs`](./src/dispatch.mjs) prevents concurrent write jobs from colliding in the same repository (including subdirectories and symlinks), while exempting isolated `--worktree` runs.
- Configurable **Persona Presets** (`default` neutral open-source labels vs `neon-trio`) switchable from Dashboard Settings or `AI_HUB_PERSONA`.
### 2. Real Token Usage Across All 3 Agents
| Agent | Usage Source | Accounting Semantics |
| :--- | :--- | :--- |
| **Codex CLI** | Native JSONL stream `usage` | Distinguishes explicitly reported `0` from absent (`null`) |
| **DSH CLI** | Local `.zstd` session logs via Node built-in multi-frame `zstdDecompressSync` | Sums `inputTokens + cacheReadTokens + cacheWriteTokens` and `outputTokens` |
| **Antigravity** | Local `transcript.jsonl` time-window collector + optional explicit args | Sums `input_tokens + cache_read_tokens` and `output_tokens` |
- Idempotent historical backfill runs on primary startup and on-demand via `POST /api/usage/backfill` (`app_backfill_usage`).
- Query aggregated usage & delegation ratio via `GET /api/usage?window=24h|7d|30d|all` or MCP `hub_get_usage`. Demo runs are isolated into `totals.demo_runs`.
### 3. Versioned Contracts & Decision / Pitfall Log
- Transactional SQLite schema migrations (`PRAGMA user_version` `0 → 1 → 2`).
- Categorize shared project knowledge by `kind`: `contract` | `decision` | `pitfall` | `guardrail`, scoped by `workspace_id`.
- Immutable `contract_revisions` history with optimistic concurrency control (`expected_revision` → `409 CONFLICT`).
### 4. Security Floor
- **Loopback HTTP Auth**: Generates a 32-byte random hex token written atomically (`0600`) to `<dataDir>/hub-auth.json`. Removes `Access-Control-Allow-Origin: *`, validates `Host` and `Origin` (`403 FORBIDDEN`), requires `Authorization: Bearer` or `X-AI-Hub-Token` on all `POST` endpoints (CSRF-resistant), and aborts `>1 MB` payloads with `413` + graceful socket close.
- **Subprocess Isolation & Redaction**: [`src/security.mjs`](./src/security.mjs) passes only an explicit environment allowlist per runner (never leaking unrelated host credentials) and redacts API keys, Bearer tokens, and PEM private keys before SQLite persistence.
- **Single-Instance Ownership Lock**: `<dataDir>/hub.lock` prevents a secondary MCP instance from erroneously failing live `running` tasks owned by an active instance.
---
## Requirements
- **Node.js `^22.15.0 || >=23.8.0`** (uses built-in `node:sqlite` and native `node:zlib` Zstandard decompression; zero native C++ addons to compile).
- Optional CLIs on `PATH` (or configured via Settings / `extraPaths` / `AI_HUB_EXTRA_PATHS`):
- `codex` (OpenAI Codex CLI)
- `dsh` (DeepSeek Harness CLI)
- Or toggle **Demo Mode** to explore the full hub workflow without local CLIs.
---
## Quick Start
```bash
git clone https://github.com/Siq5005/ai-hub.git
cd ai-hub
npm install
npm run build
npm test
npm run check:release
```
### Verification & Release Commands
| Command | What It Does |
| :--- | :--- |
| `npm run build` | Bundles the single-file Dashboard HTML and stages the complete plugin into `build-plugin/` |
| `npm test` | Runs all 28 live end-to-end mechanical guard checks (`test/verify.mjs`) against `build-plugin/` |
| `npm run check:release` | Verifies version alignment, required OSS files, staged artifacts, and zero personal paths/secrets |
| `npm run deploy` | Atomically deploys `build-plugin/` to `~/.gemini/config/plugins/ai-hub` (or `AI_HUB_DEPLOY_DIR`) with backup/rollback and preserves `data/` |
### Configuration
Copy and adapt [`config.example.json`](./config.example.json) into your data directory (default `~/.gemini/config/plugins/ai-hub/data/config.json`, or override via `AI_HUB_DATA_DIR`).
Key environment overrides (never written back into `config.json`):
- `AI_HUB_DATA_DIR` — custom SQLite/config directory
- `AI_HUB_HTTP_PORT` — preferred loopback HTTP port (default `19889`, auto-fallback if occupied)
- `AI_HUB_PERSONA` — `default` or `neon-trio`
- `AI_HUB_EXTRA_PATHS` — delimiter-separated absolute directories appended to CLI lookup `PATH`
- `AI_HUB_DEPLOY_DIR` — custom plugin install target for `npm run deploy`
---
## MCP Tools & HTTP API Reference
### MCP Tools
| Tool | Description |
| :--- | :--- |
| `open_ai_hub` | Open the real-time Dashboard (`overview` / `runs` / `contracts` / `settings`) |
| `hub_sync_agent_status` | Report lead agent state (`planning` / `running` / `idle` / `error`) and record run tokens |
| `dsh_inspect` | Run strictly read-only L1 codebase scouting, style, or security audits |
| `codex_plan_backend` | Run read-only architecture planning (supports `blind_mode: true`) |
| `codex_exec_backend` | Run chunked backend/script/test implementation (`resume_session_id`, `use_worktree`, `test_cmd`) |
| `codex_review` | Run L2 blocking review (`blind_mode: true`, `scope: "diff" \| "files"`, `high_risk`) |
| `hub_create_contract` | Create or revise a versioned contract, decision, pitfall, or guardrail (`expected_revision`) |
| `hub_list_contracts` | List compact contracts filtered by `workspace_id`, `kind`, and `status` |
| `hub_get_summary` | Return multi-agent status, CLI health, and recent runs |
| `hub_get_usage` | Return real usage & delegation analytics (`24h` / `7d` / `30d` / `all`) |
### Loopback HTTP Endpoints (`127.0.0.1:<port>`)
- `GET /health` — minimal liveness probe (`{ ok, service, version }`, unauthenticated)
- `GET /` — standalone Dashboard (sets `HttpOnly; SameSite=Strict` cookie + `<meta name="ai-hub-token">`)
- `GET /api/state` · `GET /api/events` (SSE) · `GET /api/adapters` · `GET /api/usage?window=7d`
- `GET /api/runs/:id` · `GET /api/contracts` · `GET /api/contracts/:id`
- `POST /api/dispatch` · `POST /api/runs/:id/kill` · `POST /api/config` · `POST /api/contracts` · `POST /api/usage/backfill` · `POST /api/clear`
---
## Roadmap
- **v2.1 · Dashboard Visual & UX Overhaul (Next)**: Redesign the Dashboard UI with richer visual hierarchy, interactive run diff/log viewer, contract revision diff view, responsive layout polish, and smoother motion.
- **v2.2 · Pluggable External CLI Adapters**: Declarative custom CLI adapter definitions (Claude Code, Gemini CLI, OpenCode, etc.) via config without code changes.
- **v2.3 · Workspace Context Packs**: One-click export/injection of active contracts, decisions, and pitfall guardrails when starting fresh agent sessions.
---
## Contributing & License
Contributions, bug reports, and ideas are warmly welcome — see [CONTRIBUTING.md](./CONTRIBUTING.md).
Released under the [MIT License](./LICENSE).
TDQS
Scored across 18 tools
The four dispatch tools (dsh_inspect, codex_plan_backend, codex_exec_backend, codex_review) are well separated by agent and sandbox mode, but the app_* and hub_* families overlap heavily: hub_get_summary vs app_get_dashboard_state, hub_list_contracts vs app_get_contract, app_quick_dispatch vs dsh_inspect/codex_plan_backend, and hub_get_usage vs app_backfill_usage. The 'app-only' label helps an agent exclude some tools, but boundaries between read/status tools remain fuzzy.
Names use several prefixes (hub_, app_, codex_, dsh_) plus a bare open_ai_hub, and verbs are mostly verb_noun but not uniformly (hub_sync_agent_status vs codex_plan_backend vs app_kill_run). The grouping by prefix is readable and intentional, but it is a mixed convention rather than a single predictable pattern.
18 tools is on the heavy side, and roughly half are app-only UI helpers (dashboard state, logs, config, kill, clear) that inflate the surface for an agent. The dispatch and contract tools each earn their place, but the set is borderline for the stated scope.
The domain (agent dispatch, review, status reporting, contracts, usage, run control) is broadly covered: dispatch in read-only and write modes, review, contract create/revise and list, summaries, usage, config, kill and clear. Minor gaps exist, such as no general (non-app) tool to fetch a single contract by ID or to list runs individually.