Metadata-Version: 2.4
Name: mcporch
Version: 1.1.2
Summary: Local-first AI orchestration bridge connecting Web AI (ChatGPT, Claude, Gemini) and MCP coding agents.
Author-email: Karthikeyan <engineertechlabs@users.noreply.github.com>
License: MIT
Project-URL: Homepage, https://github.com/engineertechlabs/MCPOrchestrator
Project-URL: Repository, https://github.com/engineertechlabs/MCPOrchestrator
Project-URL: Issues, https://github.com/engineertechlabs/MCPOrchestrator/issues
Keywords: mcp,ai-agents,orchestration,chatgpt,claude,gemini,fastapi
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: fastapi<1,>=0.115
Requires-Dist: uvicorn[standard]<1,>=0.30
Requires-Dist: pydantic<3,>=2.8
Requires-Dist: httpx<1,>=0.27
Requires-Dist: mcp<2,>=1.9
Dynamic: license-file

# MCPOrchestrator

[![CI](https://github.com/engineertechlabs/MCPOrchestrator/actions/workflows/ci.yml/badge.svg)](https://github.com/engineertechlabs/MCPOrchestrator/actions/workflows/ci.yml)
[![Release](https://img.shields.io/badge/version-v1.0.0-blue.svg)](https://github.com/engineertechlabs/MCPOrchestrator/releases/tag/v1.0.0)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
[![Python 3.11+](https://img.shields.io/badge/python-3.11+-3776ab.svg)](https://www.python.org/)
[![MCP Compatible](https://img.shields.io/badge/MCP-Compatible-blueviolet.svg)](https://modelcontextprotocol.io/)

**MCPOrchestrator** is a local-first AI orchestration bridge that connects:
1. **ChatGPT, Claude, or Gemini Web** (for planning and independent verification) via a Manifest V3 browser extension,
2. **Any MCP-compatible AI coding agent** (Antigravity, Cursor, Claude Code, etc.) via a standard stdio FastMCP server, and
3. **A FastAPI + SQLite orchestrator** that manages tasks, leases, retries, and event history on `127.0.0.1:18421`.

## Quick Start (`pip install mcporch`)

```bash
# 1. Install the package
pip install mcporch

# 2. Extract Chromium & Firefox extensions + print MCP config
mcporchestrator setup

# 3. Start the local server (or run: mcporchestrator install-service)
mcporchestrator start
```

---

## Architecture

```text
+-------------------+       HTTP (127.0.0.1:18421)       +------------------------+
|  FastAPI Backend  | <-------------------------------> |   Browser Extension    |
|  + SQLite Queue   |   GET /bridge/next                |  (Chromium /   |
|  (backend/app.py) |   POST /bridge/response           |   Firefox/Safari)      |
+-------------------+   POST /bridge/release            +-----------+------------+
         ^                                                          |
         | HTTP (httpx)                                             | DOM Automation
         v                                                          v
+-------------------+       stdio (MCP)                 +------------------------+
|   FastMCP Server  | <-------------------------------> |  https://chatgpt.com/  |
| (mcp-server/ |   mcporch_get_task               |  (Logged-in Session)   |
|     server.py)    |   mcporch_heartbeat              +------------------------+
+-------------------+   mcporch_submit_result
         ^
         |
         v
+-------------------+
|  MCP AI Client    |
| (Any MCP-Enabled  |
|   Coding Agent)   |
+-------------------+
```

### Task Lifecycle

1. **Create task (`POST /tasks`)**: Stores the task in SQLite (`status = planning`) and queues a `plan` prompt in `bridge_queue`.
2. **ChatGPT planning**: The browser extension polls `GET /bridge/next`, injects the prompt into an open, empty `chatgpt.com` composer, submits it, waits for streaming completion, and posts the plan to `POST /bridge/response` (`status = agent_pending`).
3. **Agent execution**: Your MCP-enabled AI tool calls `mcporch_get_task` (`GET /agent/next`), receives the plan and a 15-minute `lease_token`, implements and tests the work locally, optionally extends the lease via `mcporch_heartbeat`, and submits evidence via `mcporch_submit_result` (`POST /agent/report`, `status = verifying`).
4. **Independent verification**: MCPOrchestrator queues a `verify` prompt for ChatGPT containing the acceptance criteria and execution report. ChatGPT returns a structured JSON verdict:
   - `PASS` (all criteria explicitly `PASS`) → `complete`
   - `NEEDS_REWORK` → increments `retry_count` (up to `MAX_RETRIES`, default `3`) and returns to `agent_pending` with corrective instructions; exceeds max retries → `failed`
   - `FAIL` / unparseable verdict → `manual_review`

---

## Important Boundary

- The browser extension automates the `https://chatgpt.com/` web UI; it is **not** an official ChatGPT API and relies on page DOM selectors.
- Keep one `chatgpt.com` tab open, logged in, visible, and with an empty composer when running tasks.
- Do **not** use this tool to bypass authentication, CAPTCHAs, rate limits, or security prompts.

---

## Project Structure

```text
MCPOrchestrator/
├── mcp-server/
│   ├── requirements.txt       # MCP server Python dependencies (mcp, httpx)
│   └── server.py              # Stdio FastMCP server exposing MCPOrchestrator tools
├── backend/
│   ├── __init__.py
│   └── app.py                 # FastAPI orchestrator, SQLite schema, lease & retry logic
├── chromium-extension/          # Manifest V3 extension for Chromium browsers (v1.0.0)
│   ├── background.js          # Service worker: localhost API proxy & tab lock cleanup
│   ├── bridge_utils.js        # ProseMirror extraction, prompt verification, state machine
│   ├── content.js             # ChatGPT DOM lifecycle, insertion, submission, capture
│   ├── coordinator.js         # Serialized cross-tab lock & bounded retry/backoff tracker
│   └── manifest.json
├── firefox-extension/         # Manifest V3 extension for Firefox 109+ (v1.0.0)
│   ├── background.js
│   ├── bridge_utils.js
│   ├── content.js
│   ├── coordinator.js
│   └── manifest.json
├── tests/
│   ├── bridge.test.js         # Extension unit tests (Node.js built-in node:test)
│   └── test_backend.py        # Backend API & lease tests (Python unittest)
├── CONTRIBUTING.md
├── LICENSE                    # MIT License
├── README.md
└── requirements.txt           # Backend Python dependencies
```

---

## Prerequisites

- **OS**: Linux, macOS, or Windows
- **Python**: 3.11 or newer (`python3 --version` / `python --version`)
- **Node.js**: 20 or newer (`node --version`) — only needed to run extension unit tests and syntax checks
- **Browser**:
  - Chromium-based: **any Chromium-based browser**
  - **Firefox** 109+
  - **Safari** (macOS, via Apple's web extension converter)
- **AI Client**: Any tool supporting **MCP** over stdio (any MCP-compatible AI coding client, etc.)

---

## Step 1 — Backend Setup

### 1.1 Clone the repository

```bash
git clone https://github.com/engineertechlabs/MCPOrchestrator.git
cd MCPOrchestrator
```

### 1.2 Create a Python virtual environment and install dependencies

**Linux / macOS:**

```bash
# Create an isolated virtual environment inside .venv/
python3 -m venv .venv

# Activate the virtual environment in your current shell
source .venv/bin/activate

# Install FastAPI, Uvicorn, Pydantic, and HTTPX
pip install -r requirements.txt
```

**Windows (PowerShell):**

```powershell
# Create an isolated virtual environment inside .venv\
python -m venv .venv

# Activate the virtual environment in PowerShell
.\.venv\Scripts\Activate.ps1

# Install FastAPI, Uvicorn, Pydantic, and HTTPX
pip install -r requirements.txt
```

### 1.3 Start the FastAPI backend (CLI or OS background service)

You can run the generalized CLI directly via `python -m backend.cli` (or install `mcporchestrator` into your venv with `pip install -e .`):

```bash
# Start in the foreground (Linux, macOS, Windows)
python -m backend.cli start
```

Or install it as a **native user-level background service** (no `sudo` or Administrator rights required):
- **Linux**: `~/.config/systemd/user/mcporchestrator.service` (`systemd --user`)
- **macOS**: `~/Library/LaunchAgents/com.mcporchestrator.server.plist` (`launchd`)
- **Windows**: `MCPOrchestratorServer` in Task Scheduler (`ONLOGON` via `pythonw.exe`)

```bash
# Install and start the background service
python -m backend.cli install-service

# Check server health
python -m backend.cli status

# Stop and remove the background service
python -m backend.cli uninstall-service
```

*(You can also pass `--port`, `--host`, `--reload`, or `--dry-run` on `install-service` / `uninstall-service`.)*

**Optional environment variables:**

| Variable | Default | Purpose |
| --- | --- | --- |
| `MCPORCH_DB` | `backend/mcporchestrator.sqlite3` | Custom path for the SQLite database file |
| `MCPORCH_PORT` | `18421` | Local HTTP port for the backend |
| `MCPORCH_API_TOKEN` | _(empty)_ | Optional shared secret token (`X-MCPOrchestrator-Token` / `Bearer`) |
| `MCPORCH_MAX_RETRIES` | `3` | Maximum automatic `NEEDS_REWORK` retries per task |

### 1.4 Verify the backend is running

```bash
curl -s http://127.0.0.1:18421/health
```

Expected output:

```json
{"ok":true,"service":"mcporchestrator","version":"1.0.0"}
```

Interactive Swagger API docs are also available at `http://127.0.0.1:18421/docs`.

---

## Step 2 — Browser Extension Setup

### Option A: Chromium-based browsers (any Chromium-based browser)

1. Open your browser's extension page:
   - Chromium: `chrome://extensions` (or `brave://extensions` / `edge://extensions`)
   - Brave: `brave://extensions`
   - Edge: `edge://extensions`
2. Enable **Developer mode** (top-right toggle).
3. Click **Load unpacked** and select the `chromium-extension/` folder inside `MCPOrchestrator`.
4. Open `https://chatgpt.com/`, log in, and open a conversation with an empty composer.

### Option B: Firefox (109+)

1. Open `about:debugging#/runtime/this-firefox`.
2. Click **Load Temporary Add-on...**.
3. Select `firefox-extension/manifest.json` inside `MCPOrchestrator`.
4. Open `https://chatgpt.com/`, log in, and keep that tab visible with an empty composer.

### Option C: Safari (macOS)

Convert the Chromium extension into a Safari Web Extension Xcode project:

```bash
xcrun safari-web-extension-converter chromium-extension/
```

Build and enable the resulting extension in Safari Settings → Extensions, granting access to `chatgpt.com` and `127.0.0.1`.

### Multi-Tab & Draft Safety Behavior

- Only **one** `chatgpt.com` tab can acquire the processing lock (`chrome.storage.session`, 60s TTL, 20s heartbeat) at a time.
- Hidden/background tabs and tabs with an existing user draft or attachment are skipped automatically and never overwritten.
- Closing, reloading, or navigating away from the active tab releases the lock immediately.

---

## Step 3 — MCP Server Setup (Any MCP-Compatible AI Tool)

### 3.1 Install MCP server dependencies

With your `.venv` activated:

```bash
pip install -r mcp-server/requirements.txt
```

### 3.2 Add MCPOrchestrator to your AI tool's MCP configuration

Replace `/ABSOLUTE/PATH/TO/MCPOrchestrator` with the full path to your cloned folder.

**Linux / macOS:**

```json
{
  "mcpServers": {
    "mcporchestrator": {
      "command": "/ABSOLUTE/PATH/TO/MCPOrchestrator/.venv/bin/python",
      "args": ["/ABSOLUTE/PATH/TO/MCPOrchestrator/mcp-server/server.py"],
      "env": {
        "MCPORCH_URL": "http://127.0.0.1:18421"
      }
    }
  }
}
```

**Windows (use double backslashes `\\` in JSON):**

```json
{
  "mcpServers": {
    "mcporchestrator": {
      "command": "C:\\ABSOLUTE\\PATH\\TO\\MCPOrchestrator\\.venv\\Scripts\\python.exe",
      "args": ["C:\\ABSOLUTE\\PATH\\TO\\MCPOrchestrator\\mcp-server\\server.py"],
      "env": {
        "MCPORCH_URL": "http://127.0.0.1:18421"
      }
    }
  }
}
```

**Where to place this config:**
- **Claude Desktop**: `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS) or `%APPDATA%\Claude\claude_desktop_config.json` (Windows)
- **Cursor / Windsurf / Cline / Claude Code**: Add the `mcporchestrator` block to your tool's `mcpServers` JSON configuration.

Restart or reload your AI tool's MCP servers and confirm these 8 tools appear:
- `mcporch_create_task` — Create a new task and queue its planning prompt
- `mcporch_wait_for_task` — Wait until a task reaches `agent_pending` or a terminal status
- `mcporch_task_status` — Check task status, plan, report, and verification verdict
- `mcporch_list_tasks` — List recent tasks
- `mcporch_cancel_task` — Cancel an active task (`manual_review`)
- `mcporch_get_task` — Lease the next `agent_pending` task (optionally filtered by `project_path`)
- `mcporch_heartbeat` — Extend the active execution lease
- `mcporch_submit_result` — Submit execution summary and test evidence for verification

---

## Step 4 — End-to-End Usage Walkthrough

### 4.1 Create a task

**Linux / macOS:**

```bash
curl -X POST http://127.0.0.1:18421/tasks \
  -H 'Content-Type: application/json' \
  -d '{
    "title": "Add authentication",
    "project_path": "/home/USER/projects/example",
    "objective": "Implement registration, login, logout and password reset.",
    "acceptance_criteria": [
      "Registration validates email and password",
      "Login creates a secure session",
      "Logout invalidates the session",
      "Automated tests cover success and failure cases"
    ]
  }'
```

**Windows (PowerShell):**

```powershell
$body = @{
  title = "Add authentication"
  project_path = "C:\Users\USER\projects\example"
  objective = "Implement registration, login, logout and password reset."
  acceptance_criteria = @(
    "Registration validates email and password",
    "Login creates a secure session",
    "Logout invalidates the session",
    "Automated tests cover success and failure cases"
  )
} | ConvertTo-Json

Invoke-RestMethod -Method Post -Uri "http://127.0.0.1:18421/tasks" -ContentType "application/json" -Body $body
```

### 4.2 Let ChatGPT plan

Keep your `chatgpt.com` tab visible with an empty composer. Within ~3 seconds, the extension injects the planning prompt, submits it, waits for ChatGPT to finish generating, and posts the plan back to MCPOrchestrator (`status` becomes `agent_pending`).

### 4.3 Execute with your MCP AI agent

Prompt your MCP-connected AI agent:

> Check the MCPOrchestrator MCP tools. Call `mcporch_get_task` and follow the returned task, plan, and acceptance criteria. Inspect the project before editing, create a Git checkpoint before changes, implement the task, run real tests, and call `mcporch_submit_result` with the summary, test evidence, unresolved issues, and changed files. Use `mcporch_heartbeat` if execution takes longer than 10 minutes.

### 4.4 Inspect task state and event history

```bash
# List recent tasks
curl -s http://127.0.0.1:18421/tasks | python3 -m json.tool

# Inspect a specific task (including plan, execution_report, and verification verdict)
curl -s http://127.0.0.1:18421/tasks/<TASK_ID> | python3 -m json.tool

# Inspect the full event audit trail
curl -s http://127.0.0.1:18421/tasks/<TASK_ID>/events | python3 -m json.tool
```

---

## API Reference

| Method & Path | Consumer | Purpose |
| --- | --- | --- |
| `GET /health` | Diagnostics | Health check (`{"ok": true, "service": "mcporchestrator", "version": "1.0.0"}`) |
| `POST /tasks` | User / CLI | Create a new task (`409` if another task is still active) |
| `GET /tasks` | User / UI | List recent tasks (`?limit=20`) |
| `GET /tasks/{task_id}` | User / UI | Get task details (strips `agent_lease_token`) |
| `GET /tasks/{task_id}/events` | User / UI | Get ordered event log for a task |
| `GET /tasks/{task_id}/stream` | User / UI / CLI | Server-Sent Events (SSE) live stream of status and `bridge_progress` |
| `POST /tasks/{task_id}/followup` | User / MCP Server | Queue a follow-up question in the task's active Web AI thread |
| `POST /tasks/{task_id}/cancel` | User / CLI | Cancel an active task (`manual_review`) and free the queue |
| `POST /tasks/{task_id}/reset-bridge-lease` | User / CLI | Return a `delivered` queue item back to `pending` |
| `GET /bridge/next` | Extension | Reclaim expired leases and lease next `pending` prompt (`?worker_id=...&host=...`) |
| `POST /bridge/progress` | Extension | Report live Web AI generation progress (`stage`, `chars`, `detail`) |
| `POST /bridge/stalled` | Extension | Immediately requeue or escalate stalled Web AI responses |
| `POST /bridge/release` | Extension | Release a pre-submission lease back to `pending` |
| `POST /bridge/response` | Extension | Submit ChatGPT/Claude/Gemini response (idempotent on exact replay) |
| `GET /agent/next` | MCP Server | Reclaim expired agent leases and lease next `agent_pending` task |
| `POST /agent/heartbeat` | MCP Server | Extend active `executing` agent lease by 15 minutes |
| `POST /agent/report` | MCP Server | Submit implementation report (`exit_code`, `diff_summary`) and queue `verify` prompt |

---

## Continuous Communication & Advanced Features

- **Read Open Chat Context (`mcporch_read_chat`)**: Instantly read the last `N` messages from your currently open ChatGPT/Claude/Gemini tab without sending a prompt.
- **20s-Safe Wait Slices + Live Progress**: `mcporch_wait_for_task` waits in safe slices (default `20s`, max `45s`) and returns `still_working=True` with live `bridge_progress` (`stage`, `chars`) so IDE agents never give up on slow responses.
- **Multi-Turn Follow-Up (`mcporch_ask_followup`)**: Coding agents (and the dashboard **Inspect** modal) can ask follow-up questions in the active Web AI thread, with full `followups` history returned by `GET /tasks/{task_id}`.
- **Closed-Loop Verification**: Pass `wait_for_verdict=True`, `exit_code`, and `diff_summary` to `mcporch_submit_result` to receive ChatGPT's verification verdict directly.
- **Cross-Model Routing**: Set `planner_host` and `verifier_host` (`any`, `chatgpt.com`, `claude.ai`, `gemini.google.com`) on `POST /tasks` or in the **New Task** UI to plan with one AI and verify with another.
- **Task Dependency Chaining**: Pass `depends_on_task_id` on `POST /tasks` to hold a task in `waiting_dependency` until the parent task reaches `complete`.
- **CLI Live Watch & Extension Packaging**:
  - `.venv/bin/python -m backend.cli watch <TASK_ID>` streams live SSE updates in your terminal.
  - `python3 scripts/package_extensions.py` builds `dist/mcporchestrator-chromium.zip` and `dist/mcporchestrator-firefox.zip`.
  - Set `MCPORCH_WEBHOOK_URL` to receive JSON webhook notifications on `complete`, `manual_review`, or `failed`.

---

## Testing & Validation

Run all backend and extension checks locally without modifying the live SQLite database:

```bash
# 1. Run Python backend unit tests (uses isolated temporary SQLite databases)
.venv/bin/python -m unittest discover -s tests -v

# 2. Check JavaScript syntax for both Chromium and Firefox extensions
node --check chromium-extension/*.js firefox-extension/*.js

# 3. Validate extension manifests
python3 -m json.tool chromium-extension/manifest.json > /dev/null
python3 -m json.tool firefox-extension/manifest.json > /dev/null

# 4. Run extension unit tests (normalization, verification, state machine, cross-tab lock, retries)
node --test tests/bridge.test.js
```

---

## Troubleshooting

- **`409 Conflict: Task ... is still active`**: The MVP intentionally allows one active task at a time so ChatGPT conversations don't cross-wire. Wait for the current task to reach `complete`, `failed`, or `manual_review`.
- **`[MCPOrchestrator] Skipping queue poll because ChatGPT composer contains an existing draft`**: Clear any leftover draft or attachment in your visible `chatgpt.com` tab. MCPOrchestrator will never overwrite user-authored drafts.
- **`Extension context invalidated` in browser console**: Normal after clicking **Reload** in your browser extensions page — the old content script stops automatically; just refresh the `chatgpt.com` tab.
- **MCP tools not appearing**: Verify `mcp-server/requirements.txt` is installed in the exact Python interpreter referenced by `command` in `mcp_config.json`, then restart your MCP client.

---

## Safety & Limitations

- Local development orchestrator: keep bound to `127.0.0.1` and never expose publicly without authentication.
- ChatGPT web DOM selectors may require updates if OpenAI changes `chatgpt.com` frontend markup.
- Always work on a disposable Git branch or checkpoint when letting an agent modify code.

## License

Released under the [MIT License](LICENSE).
