# 🧠 Hive Mind MCP - LLM Orchestrator

**A powerful Model Context Protocol (MCP) server that enables advanced Multi-LLM collaboration workflows.**

Transform simple chat interactions into sophisticated "Council of Experts" sessions. This orchestrator connects OpenAI, Anthropic, DeepSeek, Google Gemini, and Local models (Ollama) to debate, refine, and validate code and content autonomously.

## ✨ Key Features

* **👥 Collaborative Refine**: A "Drafter" model writes code, while a "Council" of critics (Claude + DeepSeek) reviews it iteratively.
* **🏰 Round Table**: Run a full *Round Table* — Independent generation from 3+ models, cross-critique, and final consensus synthesis.

    ```mermaid
    graph TD
        User[User Query] --> Moderator
        Moderator -->|Ask| A[Model A]
        Moderator -->|Ask| B[Model B]
        Moderator -->|Ask| C[Model C]
        A -->|Draft| XT[Cross-Critique]
        B -->|Draft| XT
        C -->|Draft| XT
        XT -->|Feedback| Moderator
        Moderator -->|Synthesize| Final[Consensus Answer]
    ```

* **📊 Observability Dashboard**: Real-time Streamlit dashboard to track costs, sessions, and artifacts.
* **🔌 Dynamic Plugins**: Drop-in `.py` files to add new LLM providers instantly without restarting.
* **🌍 Global Configuration**: Centralized config with easy overrides for models and API keys.

---

## 🛠️ Installation

### Option A: From PyPI (Recommended)

Install the library directly using pip:

```bash
pip install hive-mind-mcp
```

### Option B: For Developers (Source)

```bash
git clone https://github.com/franciscojunqueira/hive-mind-mcp.git
cd mcp-llm-orchestrator
pip install -e .
```

All commands will be available via the `hive-mind` CLI.

---

## ⚙️ Configuration

The orchestrator uses a hierarchical configuration system:

1. **Local Project**: `.env` in the current directory (Priority).
2. **Global User**: `~/.mcp_orchestrator/.env` (Fallback).

### 1. Initialize

Run this command to create your configuration file:

```bash
hive-mind init
```

*This will create a `.env` file if it doesn't exist.*

### 2. Add API Keys

Paste your keys into the `.env` file:

```ini
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-...
DEEPSEEK_API_KEY=sk-...
```

---

## 🤖 Antigravity Integration (Agentic Mode)

You can run these workflows directly inside your AI coding assistant (Antigravity) without touching the terminal:

### 1. Slash Commands

Simply type the command in the chat:

* `/round_table "Topic"` - Runs a full consensus session.
* `/debate "Topic"` - Runs a collaborative refinement.
* `/review "Content"` - Checks code/text for safety and logic errors.
* `/analyze` - Analyzes the project.

### 2. Natural Language

You can also just ask:
> "Agent, run a round table to decide the best database for this project."

**User Request:**
> "Run the round table now on the review of the ARCHITECTURE.md document. Send them the source code for context with map-reduce"

**Agent Execution:**

```bash
hive-mind round_table "Review the attached ARCHITECTURE.md file. Does it accurately reflect the codebase structure in src/? Identify any missing features or inconsistencies." --context src/ ARCHITECTURE.md --map-reduce
```

![Antigravity Workflow](docs/images/antigravity_workflow.png)

---

## 🚀 CLI Usage Guide

The logic is built into the `hive-mind` command (formerly aliased as `mcp`).

### ⚡ Quick Guide: Which Command to Use?

| Command | Goal | Best For | Example |
| :--- | :--- | :--- | :--- |
| **`round_table`** | **Consensus** | Big decisions, architecture, ambiguity. | *"What DB should we use?"* |
| **`debate`** | **Refinement** | Writing complex code, fixing tough bugs. | *"Write a thread-safe Queue"* |
| **`review`** | **Verification** | Auditing code, security checks, sanity checks. | *"Check this file for bugs"* |
| **`analyze`** | **Understanding** | Learning large codebases, finding patterns. | *"Explain how auth works"* |
| **`models`** | **Discovery** | Listing/Searching available models. | *"List all GPT models"* |

---

### 1. Dashboard & Observability

Visualize your costs and session history in real-time.

| Budget & Overview | Analytics & Insights |
| :---: | :---: |
| ![Budget](docs/images/dashboard_preview-1.png) | ![Analytics](docs/images/dashboard_preview-2.png) |

**New Features:**

* **🗓️ Date Filtering**: Filter costs and analytics by custom date ranges.
* **🏷️ Provider & Type Filters**: Drill down into specific providers (OpenAI, Anthropic) or session types (Round Table, Debate).
* **📉 Clean Visuals**: Interactive charts with dual-axis cost tracking and responsive layouts.

**Session Explorer (Audit Traces)**
![Explorer](docs/images/dashboard_preview-3.png)
*> Deep dive into every decision made by the Council.*

```bash
# Launch the dashboard
hive-mind dashboard
```

* **💰 Budget**: Track daily spend limit vs actuals with granular provider filtering.
* **📊 Analytics**: See which models are winning debates and analyze session trends.
* **🗂️ Explorer**: Browse artifacts and metadata from previous Round Tables.

### 2. Round Table (`hive-mind round_table`)

**Consensus Engine:** Simulates a council of 3 diversity models (e.g., GPT-4, Claude, DeepSeek) debating a problem.

* **Best for:** Architecture decisions, ambiguous questions, strategy.
* **Workflow:** Independent Generation -> Cross-Critique -> Synthesis.

```bash
hive-mind round_table "What is the best architecture for this app?" --context README.md
```

### 3. Debate (`hive-mind debate`)

**Refinement Engine:** An iterative loop where a "Drafter" writes and "Reviewers" critique.

* **Best for:** Writing complex code, refactoring, fixing bugs.
* **Workflow:** Draft -> Critique -> Refine -> Critique -> Final.

```bash
hive-mind debate "Write a thread-safe Singleton" --max-turns 5
```

### 4. Review (`hive-mind review`)

**Evaluation Engine:** Submits existing content/code to the Council for a "Safety & Logic Check".

* **Best for:** Security audits, code review, checking generated content.
* **Workflow:** Reviewer 1 -> Pass/Fail + Reviewer 2 -> Pass/Fail -> Aggregated Report.

```bash
hive-mind review src/security.py --reviewers openai:gpt-4o anthropic:claude-3-opus
```

### 5. Analyze (`hive-mind analyze`)

**Map-Reduce Engine:** Summarizes large codebases file-by-file before answering.

* **Best for:** "How does this project work?", "Find security flaws in src/".
* **Workflow:** Chunk Files -> Summarize Each -> Aggregate -> Final Answer.

```bash
hive-mind analyze src "Explain the auth flow"
```

---

## 🔌 Plugins System

Expand the orchestrator with custom providers without modifying core code.

1. Create a `plugins/` directory in your current folder.
2. Add a python file (e.g., `plugins/my_custom_llm.py`).
3. Define a class inheriting from `LLMProvider` with `PROVIDER_NAME`.

The orchestrator will automatically discover and load it!

---

## ❓ Troubleshooting

| Issue | Cause | Fix |
| :--- | :--- | :--- |
| `NotFoundError` (Anthropic) | Model ID deprecated or invalid. | Update `ANTHROPIC_MODELS` in `.env` with new IDs (e.g., `claude-sonnet-4-5...`). |
| `SettingsError` / JSON | Env var has spaces or bad format. | Ensure lists in `.env` are comma-separated without brackets: `MODEL_A,MODEL_B`. |
| `401 Unauthorized` | Invalid API Key. | check `hive-mind config` and verify keys. |
| Dashboard Empty | No artifacts found. | Run a `round_table` command first to generate data. |

---

## 🤝 Contributing

Contributions are welcome! Please see [ARCHITECTURE.md](ARCHITECTURE.md) for system design details.
