# Architecture Overview

## System Architecture

```mermaid
---
config:
  theme: neo

---
graph TB
    subgraph AgentLayer["Agent Layer"]
        A["AI Agent<br/>(Cursor / Claude Desktop / etc.)"]
    end

    subgraph GridBridge["MCP Grid Bridge Server"]
        direction TB
        
        subgraph MetaTools["Meta-Tools (21 total)"]
            MT["Local Management<br/>(9 tools)"]
            OAT["OpenAPI Adapter<br/>(6 tools)"]
            EPT["Enterprise Platform<br/>(6 tools)"]
        end

        subgraph CoreServices["Core Services"]
            direction LR
            REG["Server<br/>Registry"]
            IM["Instance<br/>Manager"]
            TP["Tool<br/>Proxy"]
            MC["Metrics<br/>Collector"]
            CS["Credential<br/>Store"]
        end

        MGMT["Management API<br/>(REST + WebSocket)"]
    end

    subgraph ServerInstances["Dynamic Server Instances"]
        direction TB
        PW1["Playwright 1<br/>(chromium)"]
        PW2["Playwright 2<br/>(firefox)"]
        SQL["SQLite<br/>MCP"]
        GH["GitHub<br/>MCP"]
        TIME["Time<br/>MCP"]
    end

    subgraph Extension["VS Code Extension"]
        SB["Sidebar<br/>Tree Views"]
        DASH["Dashboard<br/>Webview"]
        MKT["Marketplace<br/>Browser"]
    end

    A <-->|"MCP Protocol<br/>(stdio / streamable HTTP)"| MetaTools
    MT --> CoreServices
    OAT --> CoreServices
    EPT --> CoreServices
    IM -->|"stdio per instance"| ServerInstances
    MGMT <-->|"REST + WS<br/>(localhost:19420)"| Extension

    style AgentLayer fill:#e8f4f8,stroke:#1a73e8
    style GridBridge fill:#f3e8ff,stroke:#7c3aed
    style ServerInstances fill:#e8ffe8,stroke:#16a34a
    style Extension fill:#f0f9ff,stroke:#0284c7
```

---

## Design Principles (SOLID)

### Single Responsibility

Each module has exactly one job:

```mermaid
graph LR
    subgraph Modules["Module Responsibilities"]
        direction TB
        A["registry/catalog.py"] -->|"CRUD on server database"| A1["Server Registry"]
        B["registry/models.py"] -->|"Data structures + validation"| B1["Data Models"]
        C["instances/connector.py"] -->|"Single MCP connection"| C1["Protocol Adapter"]
        D["instances/manager.py"] -->|"Lifecycle + resources"| D1["Process Pool"]
        E["meta_tools.py"] -->|"Agent-facing interface"| E1["9 Tool Functions"]
        F["metrics/collector.py"] -->|"Record + query metrics"| F1["SQLite Metrics"]
        G["credentials/store.py"] -->|"Store + retrieve creds"| G1["Memory + Env"]
        H["api/management.py"] -->|"Extension communication"| H1["REST + WS API"]
        I["config/settings.py"] -->|"Configuration"| I1["Pydantic Settings"]
    end
```

### Open/Closed

- **Credential stores** -- Implement `CredentialStore` ABC to add new backends (Vault, Keyring) without touching existing code
- **Server entries** -- Add categories, transport types, and config options via the data model
- **Catalog sources** -- Drop YAML files into `catalog/` to add new servers

### Liskov Substitution

- `MemoryStore`, `EnvironmentStore`, `CompositeStore` all implement `CredentialStore` -- interchangeable
- Any MCP server (stdio or HTTP) works through the same `MCPConnection` interface

### Interface Segregation

- Agents see only 21 meta-tools (not 100+ from all servers)
- Management API is separate from MCP protocol
- Metrics collection is opt-in, doesn't affect core

### Dependency Inversion

- `InstanceManager` depends on `ServerCatalog` and `MetricsCollector` abstractions
- `CredentialStore` is injected, not hardcoded
- Settings are centralized via environment variables

---

## Design Patterns

```mermaid
graph TB
    subgraph Patterns
        SING["Singleton<br/>BridgeSettings"] -->|"Single config source"| CFG["config/settings.py"]
        FACT["Factory<br/>MCPConnection"] -->|"stdio vs HTTP"| CONN["instances/connector.py"]
        FAC["Facade<br/>meta_tools"] -->|"Simple interface<br/>to complex subsystem"| MT["meta_tools.py"]
        STRAT["Strategy<br/>CredentialStore"] -->|"Swappable backends"| CRED["credentials/store.py"]
        COMP["Composite<br/>CompositeStore"] -->|"Chain stores"| CHAIN["Memory → Env → Keyring"]
        OBS["Observer<br/>WebSocket broadcast"] -->|"Real-time updates"| WS["api/management.py"]
        REPO["Repository<br/>ServerCatalog"] -->|"Abstract persistence"| DB["registry/catalog.py"]
        PROXY["Proxy<br/>call_tool"] -->|"Forward to MCP server"| FWD["instances/manager.py"]
    end
```

---

## Data Flows

### Agent Tool Call

```mermaid
sequenceDiagram
    participant Agent as AI Agent
    participant MT as meta_tools.py
    participant IM as InstanceManager
    participant MC as MCPConnection
    participant S as Server Process
    participant Met as MetricsCollector

    Agent->>MT: call_tool(instance_id, "navigate", args)
    MT->>IM: validate ownership + state
    IM->>MC: proxy call to server
    MC->>S: MCP tools/call (stdio)
    S-->>MC: Tool result
    MC-->>IM: Result
    IM->>Met: record_tool_call(latency, success)
    IM-->>MT: ToolCallResult
    MT-->>Agent: Formatted response
```

### Server Lifecycle

```mermaid
stateDiagram-v2
    [*] --> Registered: YAML catalog / import / API
    Registered --> Configured: configure_server(server_id, config)
    Configured --> Starting: activate_server(instance_id)
    Starting --> Active: Tools discovered successfully
    Starting --> Failed: Startup timeout / error
    Active --> Active: call_tool() / parallel_call()
    Active --> Idle: No calls for idle_timeout_seconds
    Idle --> Active: New tool call arrives
    Idle --> ShuttingDown: Auto-shutdown triggered
    Active --> ShuttingDown: deactivate_server()
    ShuttingDown --> Stopped: Process terminated, resources freed
    Failed --> Configured: Can retry activation
    Stopped --> [*]
```

### Extension Communication

```mermaid
sequenceDiagram
    participant Ext as VS Code Extension
    participant API as Management API
    participant Bridge as MCP Grid Bridge
    participant WS as WebSocket

    Ext->>API: GET /api/servers
    API-->>Ext: Server list

    Ext->>API: GET /api/instances
    API-->>Ext: Active instances

    Ext->>API: GET /api/metrics/summary
    API-->>Ext: Dashboard data

    Ext->>WS: Connect /ws
    WS-->>Ext: Real-time events
    Note over WS,Ext: instance_started, tool_called,<br/>instance_stopped, metrics_updated
```

---

## Technology Stack

| Component | Technology | Rationale |
|-----------|-----------|-----------|
| MCP Framework | FastMCP v2 | Most adopted MCP server framework for Python |
| Data Validation | Pydantic v2 | Type safety, JSON schema auto-generation |
| Configuration | pydantic-settings | Environment variable overrides with type coercion |
| Database | SQLite via aiosqlite | Embedded, zero-config, fully async |
| Catalog Files | YAML | Human-readable, version-controllable |
| HTTP API | Starlette | Lightweight async framework with WebSocket support |
| System Monitoring | psutil | Cross-platform CPU/memory metrics |
| MCP Protocol | mcp SDK | Official MCP client implementation |
| HTTP Client | httpx / aiohttp | Async HTTP for OpenAPI executor |
| Extension | TypeScript + VS Code API | Native IDE integration |
| Marketplace | GitHub Pages | Free, reliable, CDN-backed hosting |

---

## Security Architecture

```mermaid
flowchart TB
    subgraph Local["Your Machine (localhost only)"]
        subgraph Bridge["MCP Grid Bridge"]
            CRED["Credentials<br/>(memory only)"]
            API["Management API<br/>(127.0.0.1:19420)"]
            METRICS["Metrics DB<br/>(counts + latency only)"]
        end

        subgraph Ext["VS Code Extension"]
            SEC["SecretStorage<br/>(OS Keychain)"]
        end
    end

    subgraph External["External (user-initiated only)"]
        MCP["MCP Servers<br/>(stdio subprocess)"]
        OAPI["REST APIs<br/>(OpenAPI calls)"]
        ENT["Enterprise Platform<br/>(WSS)"]
        CAT["Marketplace Catalog<br/>(read-only sync)"]
    end

    CRED -.->|"In-memory only"| CRED
    Bridge --> MCP
    Bridge -->|"User-initiated"| OAPI
    Bridge -->|"User-initiated"| ENT
    Ext -->|"Hourly check"| CAT

    style Local fill:#e8ffe8,stroke:#16a34a
    style External fill:#fff3e0,stroke:#ea580c
```

**Key guarantees:**
- Management API binds to `127.0.0.1` only (never `0.0.0.0`)
- Credentials never logged, never in metrics, never on disk
- Instance ownership verified before every tool call
- System resource limits prevent denial-of-service
- Per-agent session isolation prevents cross-session access
