Skip to main content
Glama
README.md
# Antigravity Agent Hub (`antigravity-mcp`)

> **English** | [简体中文](README.zh-CN.md)

[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![Python 3.11+](https://img.shields.io/badge/Python-3.11%2B-3776AB.svg)](https://www.python.org/downloads/)
[![MCP Protocol](https://img.shields.io/badge/MCP-4%20Domain%20OP%20Tools-0B8284.svg)](#4-domain-op-mcp-tools-27-operations)
[![Project Isolation](https://img.shields.io/badge/Isolation-Strict%20Per--Project%20%26%20Profile-0B8284.svg)](#strict-project-isolation)
[![Zero-Dep SDK](https://img.shields.io/badge/agy__sdk-Zero%20External%20Deps-2E7D32.svg)](libs/agy_sdk/README.md)

**A persistent local Agent Hub, real-time Web Console, strictly project-isolated 4-tool `stdio` MCP bridge, shell CLI, and zero-dependency Python SDK for [Google Antigravity CLI (`agy`)](https://antigravity.google/).**

Turn Google Antigravity CLI (`agy`) into a fleet of isolated, long-lived, multi-session coding agents that you can orchestrate from **Claude Code**, **Claude Desktop**, **Cursor**, **Windsurf**, **Codex**, **Antigravity**, your **browser**, or any **Python application** — with strict project boundaries, zero polling token waste, zero recursive MCP storms, and zero global config pollution.

![Antigravity Agent Hub Web Console](docs/assets/console-preview.png)

---

## One-Click AI Install Prompt (Claude Code / Cursor / Codex / Antigravity)

Copy and paste the prompt below directly into **Claude Code** (or any MCP-capable coding agent with shell access) inside the project where you want to install `agy-hub`:

```text
Please install and configure Antigravity Agent Hub (https://github.com/jackche8/antigravity-mcp) as a strictly project-isolated MCP server for my current workspace:

1. Check prerequisites: verify `git`, `uv`, and `agy --version` are installed on PATH. If any is missing, tell me before proceeding.
2. Install the hub outside this repository at `~/.local/share/antigravity-mcp` (clone if absent, otherwise `git pull --ff-only`), then run `uv sync --python 3.12` inside `~/.local/share/antigravity-mcp`.
3. Check whether the local daemon is healthy at `http://127.0.0.1:4319/api/health`. If not running, start `~/.local/share/antigravity-mcp/.venv/bin/agy-agent daemon` detached in the background (logging to `~/.local/share/agy-hub/daemon.log`) and verify `agy-agent hub status` returns `status=ok`.
4. Register `agy-hub` as a PROJECT-SCOPED MCP server bound strictly to my current project directory (`$PWD`) so agents in this project are completely isolated from other projects:
   - If you are Claude Code, run:
     `claude mcp add --scope project agy-hub -- "$HOME/.local/share/antigravity-mcp/.venv/bin/agy-mcp" --cwd "$PWD" --hub-url http://127.0.0.1:4319`
   - Otherwise, add `"agy-hub"` to this project's `.mcp.json` using `"command": "<HOME>/.local/share/antigravity-mcp/.venv/bin/agy-mcp"` and `"args": ["--cwd", "<CURRENT_PROJECT_ABS_PATH>", "--hub-url", "http://127.0.0.1:4319"]`.
   - Do NOT commit personal absolute paths in `.mcp.json` if the repository is shared; add `.mcp.json` to `.git/info/exclude` if needed.
5. Verify the setup by calling `agent(op="list")` (after MCP reload if required) and confirm `project_cwd` matches my current project directory, then print the Web Console URL `http://127.0.0.1:4319/`.
```

### Quick Claude Code CLI Setup (1 Command)

Once cloned and synced to `~/.local/share/antigravity-mcp` with the daemon running:

```bash
# Inside your target project directory — strictly scoped to this project only
claude mcp add --scope project agy-hub -- \
  "$HOME/.local/share/antigravity-mcp/.venv/bin/agy-mcp" \
  --cwd "$PWD" \
  --hub-url http://127.0.0.1:4319
```

> **Tip for multi-project Claude Code users:** Always pass `--scope project` + `--cwd "$PWD"` (or rely on MCP `roots/list` without hardcoding another folder) so each repository gets its own isolated agent pool.

---

## Strict Project Isolation

Multi-agent setups break fast when agents bleed across repositories, inherit your personal `~/.gemini/GEMINI.md`, or spawn infinite recursive subagents. Antigravity Agent Hub enforces **three hard isolation boundaries**:

| Isolation Layer | Enforcement Mechanism | What It Guarantees |
|---|---|---|
| **1. Strict Project `cwd` Scope** | Every `stdio` MCP connection resolves and locks to a single project (`--cwd` → MCP `roots/list` → `os.getcwd()`). Every `agent_id` call verifies `_normalize_cwd(agent.cwd) == project_cwd`. | Claude Code in **Project A** can only list, message, compact, cancel, or manage agents in **Project A**. Any cross-project `agent_id` fails closed with **`403 PROJECT_SCOPE_VIOLATION`**. Cross-project management stays strictly in the Web Console, REST API, and `agy-agent projects` CLI. |
| **2. Per-Agent `--gemini-dir` Profile Isolation** | Each persistent agent runs inside its own isolated profile directory under `~/.local/share/agy-hub/profiles/<agent_id>/` (auth is shared cleanly without copying user rule files). | Global `~/.gemini/GEMINI.md` and `AGENTS.md` are **never** leaked into managed agents. Unselected workspace/global MCP servers are explicitly shadow-disabled (`{"command": "/bin/false", "disabled": true}`) so each agent sees **only** the MCP tools you attach to it. |
| **3. 3-Layer Hard Anti-Recursion** | `inherit_mcp` defaults to `false`; `discover_mcp_catalog` flags self-referencing `agy-hub`/`agy-mcp` servers; profile generation shadows them out even if `inherit_mcp=true`; explicit mounts are rejected. | Subagents can **never** mount `agy-hub` or recursively spawn sub-subagents (`400 RECURSIVE_MCP_FORBIDDEN`). |

---

## Why Antigravity Agent Hub?

| Capability | What it gives you |
|---|---|
| **Zero-Dependency Python SDK (`libs/agy_sdk`)** | Pure Python `>=3.11` stdlib (`dependencies = []`, zero implicit `os.environ` reads). Embed `AgyAgent` (async + persistent-loop sync), `CallbackManager`, `StateOwner`, `ProfileStore`, `AcpClient`, `ModelCatalog`, `UsageClient`, `AgyRuntimeClient`, and 5-file `discover_mcp_catalog` directly into any Python project. |
| **Single-Source Local Daemon** | FastAPI + SSE + SQLite WAL (`127.0.0.1:4319`, persistent state under `~/.local/share/agy-hub/`). Web Console, MCP bridge, and CLI all talk to one authoritative daemon — never competing over SQLite locks or duplicate `agy` subprocesses. |
| **Compact 4-Tool MCP Bridge (27 Ops)** | Exposes just **4 domain tools** (`agent`, `session`, `mcp`, `hub`) using a uniform `(op, params)` protocol with built-in `op="help"`. Avoids context-window bloat from dozens of flat tools while preserving full capability. |
| **Async Dispatch + Shell `wait`** | `agent(op="send")` dispatches non-blockingly and returns `turn_id` + `wait_command` (`agy-agent wait <agent_id> --turn <turn_id>`). Calling agents block cleanly in shell instead of burning context tokens polling status. |
| **Quota-Aware `system_prompt_mode`** | A global switch (`GET/PUT /api/settings` or console topbar) lets new sessions default to **`append`** (standard quota rate via `agy`'s default agent) or opt into **`replace`** (`--agent <id>`, full system prompt replacement). |
| **5-File MCP Discovery & Live Hot-Reconnect** | Auto-discovers MCP configs across 5 global/project files and supports per-agent or batch `start` / `stop` / `reconnect` with immediate `agy acp` prewarm — reloading updated MCP configs while keeping `conversation_id` history intact. |
| **Real-Time Bilingual Web Console (`EN / 中文`) & Runtime Manager** | Defaults to English with a 1-click `EN / 中文` header toggle persisted across reloads. Live SSE token/thinking/tool-call streaming, collapsible project→agent tree, multi-session drawer, 6 slash commands (`/new`, `/compact`, `/model`, `/history`, `/usage`, `/help`), hot model switching, sandboxed HTML previews, live 5h/Weekly quota gauges, and `agy` CLI version/outdated-ACP lifecycle management. |

> **Language support:** Both the GitHub homepage (`README.md` / `README.zh-CN.md`) and the local Web Console (`http://127.0.0.1:4319/`) support **English (default)** and **Simplified Chinese** via a 1-click toggle. The Python SDK, MCP tool schemas/instructions, CLI help, and REST API are English; the built-in `/help` page and 3 starter presets currently remain in Chinese (contributions welcome!).

---

## Architecture

```mermaid
flowchart LR
    MCP["MCP Clients<br/>(Claude Code, Cursor, Codex, etc.)"] -->|stdio JSON-RPC · locked to project cwd| Bridge["agy-mcp / agy-agent mcp<br/>(4 Domain OP Tools)"]
    CLI["Shell / Scripts"] --> CliBin["agy-agent CLI"]
    Browser["Web Browser"] -->|REST + SSE| WebUI["Web Console<br/>(src/agy_hub/web/)"]

    Bridge -->|HubClient HTTP| Daemon
    CliBin -->|HubClient HTTP| Daemon
    WebUI -->|REST + SSE| Daemon

    subgraph Daemon["Persistent Local Daemon (FastAPI · 127.0.0.1:4319)"]
        API["api/ (REST + SSE + /help)"] --> BIZ["biz/ (Agent, Session, MCP, Preset, Project, Runtime, Settings)"]
        BIZ --> LOGIC["logic/ (SQLite WAL, EventBus, Uploads, Migrations)"]
    end

    Daemon --> SDK["libs/agy_sdk (Zero-Dep Pure Stdlib SDK)"]
    SDK --> ACP1["Project A · Isolated agy acp<br/>(--gemini-dir profile_a)"]
    SDK --> ACP2["Project B · Isolated agy acp<br/>(--gemini-dir profile_b)"]
```

---

## Manual Quick Start

### Prerequisites

- **Python `>= 3.11`** (tested with Python 3.12 via [`uv`](https://docs.astral.sh/uv/))
- **[Google Antigravity CLI (`agy`)](https://antigravity.google/)** installed and authenticated locally (`agy --version`)
- **Node.js** (only required for running the verification gate's JS syntax checks)

### Install & Start the Daemon

```bash
# 1. Clone into a shared local directory (outside your individual project repos)
git clone https://github.com/jackche8/antigravity-mcp.git ~/.local/share/antigravity-mcp
cd ~/.local/share/antigravity-mcp

# 2. Install dependencies (automatically installs libs/agy_sdk in editable mode)
uv sync --python 3.12

# 3. Start the persistent local daemon (default: http://127.0.0.1:4319/)
uv run agy-agent daemon

# 4. In another terminal, verify daemon health or open http://127.0.0.1:4319/
uv run agy-agent hub status
```

On Linux desktops, you can also start the daemon in the background and open the console in one command:

```bash
./scripts/desktop_launch.sh
```

---

## MCP Client Configuration Examples

### Project-Scoped `.mcp.json` (Claude Code / Cursor / Windsurf / Antigravity)

Place this in your project root (keeps every project isolated to its own `--cwd`):

```json
{
  "mcpServers": {
    "agy-hub": {
      "command": "/path/to/antigravity-mcp/.venv/bin/agy-mcp",
      "args": [
        "--cwd",
        "/path/to/your/project",
        "--hub-url",
        "http://127.0.0.1:4319"
      ]
    }
  }
}
```

### Dynamic `roots/list` Config via `uv` (Auto-Binds to Client's Active Project)

For MCP clients that send MCP `roots/list` (such as Claude Code, Cursor, or Antigravity):

```json
{
  "mcpServers": {
    "agy-hub": {
      "command": "uv",
      "args": [
        "--directory",
        "/path/to/antigravity-mcp",
        "run",
        "agy-agent",
        "mcp"
      ]
    }
  }
}
```

> If the daemon is not running, the MCP bridge fails explicitly with `HUB_UNREACHABLE` instead of silently spawning competing background processes.

---

## 4 Domain OP MCP Tools (27 Operations)

Instead of flooding your LLM context with 20+ separate tool schemas, `agy-mcp` exposes **4 domain tools** using a uniform `tool(op="<action>", params={...})` contract. Every tool supports `op="help"` (with optional `params={"op": "<action>"}`) for exact parameter schemas and examples.

### Recommended Zero-Guess AI Workflow

1. **Discover once:** Call `agent(op="list")` to inspect active agents in the current project, defaults, compact presets, and mountable `available_mcps` in a single round trip.
2. **Reuse or create:** Send to an existing idle agent with `agent(op="send")`, or spawn a specialized worker with `agent(op="create", params={...})`.
3. **Wait without burning tokens:** `agent(op="send")` returns immediately with `turn_id` and `wait_command`. Run `agy-agent wait <agent_id> --turn <turn_id>` in shell instead of polling `agent(op="messages")`.
4. **Compact or hot-reload MCPs:** Use `session(op="compact")` on long threads and `mcp(op="start|stop|reconnect")` to reload MCP servers on the fly while preserving conversation history.

### Tool & Operation Matrix

| Tool | Operations | Purpose |
|---|---|---|
| **`agent`** *(10 ops)* | `list`, `create`, `update`, `send`, `messages`, `cancel`, `close`, `reopen`, `delete`, `help` | Full lifecycle and messaging for persistent project-scoped agents (async dispatch with `interrupt=true, wait=false` by default). |
| **`session`** *(5 ops)* | `list`, `create`, `switch`, `compact`, `help` | Manage multiple Hub-scoped conversation sessions per agent and run in-place context compaction checkpoints. |
| **`mcp`** *(6 ops)* | `catalog`, `status`, `start`, `stop`, `reconnect`, `help` | Inspect the 5-file MCP catalog, check live per-agent/project MCP status, toggle mounted MCPs without losing config, or hot-reconnect with immediate `agy acp` prewarm. |
| **`hub`** *(6 ops)* | `guide`, `usage`, `models`, `preset_list`, `preset_create`, `help` | Read the full usage guide, check live 5h/Weekly Antigravity quota, list available models, and list/create reusable role presets. |

---

## Standalone Python SDK (`libs/agy_sdk`)

`libs/agy_sdk` is a **zero-dependency** Python `>=3.11` package (`dependencies = []`) — no FastAPI, Pydantic, HTTPX, or MCP dependencies required. Install it directly or vendor `libs/agy_sdk/src/agy_sdk` into any Python project:

```bash
pip install -e ./libs/agy_sdk
```

```python
import asyncio
from agy_sdk import (
    AgyAgent,
    AgyAgentConfig,
    CallbackManager,
    ModelCatalog,
    TurnResult,
    UsageClient,
)

callbacks = CallbackManager()
callbacks.subscribe("on_text_delta", lambda p: print(p["delta"], end="", flush=True))


class MyStateOwner:
    def on_turn_finished(self, *, agent_id: str, result: TurnResult) -> None:
        print(f"\n[{agent_id}] {result.status} in {result.duration_ms}ms")


async def run_async() -> None:
    cfg = AgyAgentConfig(
        cwd="/path/to/workspace",
        model="gemini-4-neon-xhigh",
        system_prompt="You are a concise engineering assistant.",
        inherit_mcp=False,
    )
    async with AgyAgent(cfg, callbacks=callbacks, state_owner=MyStateOwner()) as agent:
        result = await agent.send("Summarize README.md in 3 bullets.")
        print(result.text, result.usage)


# Synchronous API backed by a lazy persistent background event loop
def run_sync() -> None:
    with AgyAgent(AgyAgentConfig(cwd="/path/to/workspace")) as agent:
        r1 = agent.send_sync("Remember token: ALPHA_42")
        r2 = agent.send_sync("Repeat the token.")
        assert r1.session_id == r2.session_id
        print(r2.text)


# Zero-quota metadata probes
models, _err = ModelCatalog().get_models()
usage = UsageClient().get_usage()
print([m.id for m in models], [(b.group, b.window_5h) for b in usage.buckets])

asyncio.run(run_async())
```

See [libs/agy_sdk/README.md](libs/agy_sdk/README.md) for the complete SDK reference (isolated profiles, `SystemPromptMode`, 5-file MCP discovery, `AgyRuntimeClient`, callbacks, and error hierarchy).

---

## `agy-agent` CLI Reference

All client subcommands support `--json` and `--hub-url <url>` (or `AGY_HUB_URL`):

```bash
# Daemon, health check, and stdio MCP bridge
uv run agy-agent daemon [--host 127.0.0.1] [--port 4319] [--data-dir PATH] [--auto-update]
uv run agy-agent hub status [--json]
uv run agy-agent mcp [--cwd PATH] [--hub-url URL]

# Agents: list, send, and zero-token blocking wait
uv run agy-agent list [--cwd PATH] [--origin mcp|human|cli] [--status STATUS] [--json]
uv run agy-agent send <agent_id> "<prompt>" [--no-interrupt] [--wait] [--timeout 120] [--json]
uv run agy-agent wait <agent_id> [--turn <turn_id>] [--timeout 300] [--json]
# wait exit codes: 0=completed  2=cancelled  1=error/unreachable  124=timeout (turn keeps running)

# Quota & available models (zero model quota cost)
uv run agy-agent usage [--refresh] [--json]
uv run agy-agent models [--refresh] [--json]

# Workspace projects
uv run agy-agent projects list [--json]
uv run agy-agent projects add <cwd> [--name NAME] [--json]
uv run agy-agent projects rename <project_id> <name> [--json]
uv run agy-agent projects delete <project_id> [--json]

# Multi-session management & in-place context compaction
uv run agy-agent sessions list <agent_id> [-q KEYWORD] [--json]
uv run agy-agent sessions new <agent_id> [--title TITLE] [--json]
uv run agy-agent sessions switch <agent_id> <session_id> [--json]
uv run agy-agent sessions compact <agent_id> [--focus TEXT] [--wait] [--timeout 120] [--json]
uv run agy-agent sessions delete <agent_id> <session_id> [--json]

# Agent-mounted MCP lifecycle & batch hot-reconnect
uv run agy-agent mcps catalog [--cwd PATH] [--json]
uv run agy-agent mcps status [--agent ID | --project-id ID | --cwd PATH] [--name NAME] [--json]
uv run agy-agent mcps start <agent_id> <name> [--interrupt] [--json]
uv run agy-agent mcps stop <agent_id> <name> [--interrupt] [--json]
uv run agy-agent mcps reconnect [--agent ID] [--name NAME] [--interrupt] [--only-running] [--json]

# Antigravity CLI (agy) version & outdated ACP process management
uv run agy-agent runtime status [--json]
uv run agy-agent runtime update [--json]
uv run agy-agent runtime recycle [--all-idle | --interrupt-running] [--agent ID ...] [--json]
```

### Environment Variables

Only top-level entrypoints read environment variables (`agy_sdk` and `agy_hub/logic` never read `os.environ` implicitly):

| Variable | Default | Description |
|---|---|---|
| `AGY_HUB_HOST` | `127.0.0.1` | Daemon bind host |
| `AGY_HUB_PORT` | `4319` | Daemon bind port |
| `AGY_HUB_DATA_DIR` | `~/.local/share/agy-hub` | SQLite WAL database, isolated profiles, and temporary upload directory |
| `AGY_HUB_URL` | `http://127.0.0.1:4319` | Target daemon URL for CLI and MCP bridge |
| `AGY_GEMINI_DIR` | `~/.gemini` | Global Gemini/Antigravity config root (used for auth sharing & catalog discovery) |
| `AGY_BIN` | `agy` | Path or executable name for the Google Antigravity CLI |
| `AGY_HUB_AUTO_UPDATE` | `false` | Check/run `agy update` in background on daemon startup |
| `AGY_UPDATE_TIMEOUT_SEC` | `120.0` | Timeout (seconds) for `agy update` execution |

---

## Key Engineering Details

- **Global `system_prompt_mode` (`append` vs `replace`):** Controlled via `GET/PUT /api/settings` or the Web Console sidebar switch and applied to newly created sessions (existing sessions keep their creation mode). Default `append` runs via `agy`'s default agent at standard quota rate and layers `system_prompt` on top of the native prompt; `replace` launches `--agent <id>` to replace the native prompt completely while preserving built-in tools (both enforce a 24 KB limit, failing with `400 SYSTEM_PROMPT_TOO_LARGE`).
- **5-File MCP Auto-Discovery:** Discovers MCP definitions in deterministic precedence across `<cwd>/.agents/mcp_config.json` / `.agent/mcp_config.json`, `<cwd>/.gemini/settings.json`, `<cwd>/.mcp.json`, `~/.gemini/config/mcp_config.json`, and `~/.gemini/settings.json`, plus standard `{"mcpServers": {...}}` JSON imports.
- **Web Console Slash Commands:** Type `/` in the console composer for keyboard-navigable `/new [title]`, `/compact [focus]`, `/model [keyword]`, `/history`, `/usage`, and `/help` (strict first-token matching guarantees pasted file paths like `/home/user/notes.txt` never trigger slash commands).
- **Single-Source Help Endpoint:** Open `http://127.0.0.1:4319/help` (HTML), `http://127.0.0.1:4319/help?format=md` (raw Markdown), or `GET /api/help` (JSON) — all served from the same guide as MCP `hub(op="guide")`.

---

## Project Layout & Verification Gate

```text
libs/agy_sdk/               # Zero-dependency pure-stdlib Python SDK
src/agy_hub/
├── logic/                  # Pure logic: Pydantic models, SQLite WAL, migrations, EventBus, HubClient, MCP ops
├── biz/                    # Business services: Agent, Session, Compact, MCP, Preset, Project, Runtime, Settings
├── api/                    # FastAPI REST + SSE + /help routers
├── mcp_bridge/             # Project-scoped 4-tool stdio MCP server (talks only via HubClient)
├── cli.py                  # agy-agent CLI entrypoint (talks only via HubClient)
└── web/                    # Real-time Web Console (pure UI components <- biz REST/SSE/Store wiring)
tests/                      # SDK unit, AST architecture guards, logic, biz, API/SSE, MCP/CLI & Playwright E2E
scripts/gate.py             # Unified single-entry verification gate
```

Run the full offline verification gate (Ruff, `mypy --strict`, `node --check`, AST architectural guards, SDK/backend/API/MCP/CLI tests, and Playwright browser E2E):

```bash
uv run python scripts/gate.py
```

Optionally include live smoke tests against your local `agy` binary:

```bash
uv run python scripts/gate.py --live-agy
```

---

## Contributing & License

Contributions, bug reports, and localization pull requests (additional languages or `/help` i18n) are welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for architecture rules and development setup.

Licensed under the [MIT License](LICENSE).

TDQS

A3.9/5.0

Scored across 4 tools

Disambiguation4/5

The four top-level tools cover distinct domains: sessions, agents, MCP servers, and hub metadata/presets. Some overlap remains between session management and agent turn history (agent.messages accepts session_id), and MCP config appears both in agent updates and mcp operations, but the boundaries are mostly clear.

Naming Consistency5/5

All four tool names are lowercase single-noun domain labels (session, agent, mcp, hub), giving a highly predictable top-level naming pattern. The sub-operations also mostly follow lowercase snake_case, with only minor noun/verb variation inside each dispatcher.

Tool Count4/5

Four tools is a sensible top-level grouping for a meta-server, but each tool multiplexes 6-10 operations, so the effective surface is around 28 actions. This is appropriate but quite heavily bundled, making individual operations less discoverable than separate tools would be.

Completeness4/5

The set covers the core lifecycle well: session list/create/switch/compact, agent create/update/send/cancel/close/reopen/delete, MCP catalog/status/start/stop/reconnect, and hub guide/usage/models/presets. Minor gaps remain, such as session rename/delete and preset update/delete/get beyond preset_list and preset_create.

Maintenance

ActivityNo data
ResponsivenessOutdated data