# MCP Grid -- Enterprise AI Platform Integration Guide

> **Classification**: Internal Reference Architecture  
> **Version**: 1.0.0  
> **Date**: 2026-02-15  
> **Author**: IB-QA Engineering  

**All company names, tokens, endpoints, and personal identifiers in this document are masked or replaced with generic enterprise placeholders. This document describes patterns and architecture, not specific implementation secrets.**

---

## Table of Contents

1. [Executive Summary](#1-executive-summary)
2. [Architecture Overview](#2-architecture-overview)
3. [Authentication & Authorization Patterns](#3-authentication--authorization-patterns)
4. [WebSocket Protocol Specification](#4-websocket-protocol-specification)
5. [REST API Patterns](#5-rest-api-patterns)
6. [MCP Server Component Model](#6-mcp-server-component-model)
7. [Workflow Chain Execution Model](#7-workflow-chain-execution-model)
8. [Tool Invocation Protocol](#8-tool-invocation-protocol)
9. [Error Handling & Resilience Patterns](#9-error-handling--resilience-patterns)
10. [Enterprise Privacy & Security Guarantees](#10-enterprise-privacy--security-guarantees)
11. [MCP Grid Plugin Integration Design](#11-mcp-grid-plugin-integration-design)
12. [UX/UI Patterns for Enterprise Configuration](#12-uxui-patterns-for-enterprise-configuration)
13. [Phase Roadmap](#13-phase-roadmap)

---

## 1. Executive Summary

This document captures the architecture and integration patterns observed from a production enterprise AI workflow platform. The platform enables users to compose **Work Chains** (workflow sequences) that orchestrate multiple AI models, MCP servers, and data connectors to perform complex tasks such as impact analysis, code review, and automated reporting.

MCP Grid's Phase 4 integration will expose these enterprise workflow chains as **dynamic MCP tools**, allowing AI agents in VS Code/Cursor to trigger, configure, and consume enterprise workflows directly from the IDE.

### Key Capabilities Captured

| Capability | Pattern |
|-----------|---------|
| **Authentication** | SSO + MFA → Auth0 OIDC → JWT token (platform) + Microsoft OAuth2 → JWT token (Azure DevOps) + PAT (GitHub) |
| **Real-time Execution** | AWS API Gateway WebSocket with JWT auth in query param |
| **Streaming Responses** | Chunked JSON messages over WebSocket |
| **Tool Orchestration** | Agent-driven tool_use_request/tool_use_response cycle with auto-approval |
| **Component Model** | MCP servers use `Streamable HTTP` transport with Bearer auth |
| **Heartbeat** | Client sends `{"action": "heartbeat"}` every ~27s; server replies `{"message": "pong"}` |
| **Error Recovery** | MCP client session timeout → automatic retry with re-initialization |

---

## 2. Architecture Overview

```mermaid
graph TB
    subgraph Platform["Enterprise AI Platform"]
        FE["Frontend<br/>(React + Vite SPA)"]
        REST["REST API (v2)<br/>CloudFront/CDN + API Gateway"]
        WS["WebSocket Gateway<br/>AWS API Gateway<br/>wss://...?Auth=JWT"]

        ENGINE["Workflow Engine<br/>(Agent Orchestrator)"]

        subgraph Components["Component Registry"]
            LLMs["LLMs<br/>Claude, GPT,<br/>Gemini, Llama,<br/>Mistral"]
            MCP["MCP Servers<br/>AzDevOps, GitHub,<br/>Outlook, Teams"]
            DATA["Data Connectors<br/>S3, SharePoint,<br/>etc."]
            VDB["Vector DB<br/>(BYOD /<br/>OpenSearch)"]
        end
    end

    subgraph Plugin["MCP Grid Plugin (VS Code/Cursor)"]
        GRID["MCP Grid Bridge"]
    end

    FE --> REST
    FE --> WS
    REST --> ENGINE
    WS --> ENGINE
    ENGINE --> Components
    Platform --> Plugin

    style Platform fill:#f0f9ff,stroke:#0284c7
    style Components fill:#e8ffe8,stroke:#16a34a
    style Plugin fill:#f3e8ff,stroke:#7c3aed
```

### Data Flow Summary

```
User → Frontend (React SPA) → REST API (workflow fetch, component catalog)
                             → WebSocket (real-time chain execution)
                             → Microsoft OAuth2 (Azure DevOps token)
                             → Manual PAT entry (GitHub token)
```

---

## 3. Authentication & Authorization Patterns

### 3.1 Platform Authentication (SSO + MFA + OIDC)

The platform uses a **three-layer authentication** approach:

```
┌──────────────┐     ┌──────────────┐     ┌──────────────┐     ┌──────────────┐
│   User        │────▶│  Enterprise  │────▶│     MFA      │────▶│   Identity   │
│   Browser     │     │  SSO (SAML/  │     │   Provider   │     │   Platform   │
│               │◀────│  OIDC)       │◀────│  (Push Auth) │◀────│  (Auth0/     │
│               │     │              │     │              │     │   Okta)      │
└──────────────┘     └──────────────┘     └──────────────┘     └──────────────┘
```

**Step-by-step flow:**

1. **User visits platform** → Redirected to Enterprise SSO (e.g., PingFederate)
2. **SSO authentication** → Username/password validated against corporate directory
3. **MFA challenge** → Push notification sent to authenticator app (e.g., PingID)
4. **MFA approval** → User approves on mobile device
5. **Token exchange** → SSO redirects to Identity Platform (e.g., Auth0) with authorization code
6. **OIDC token issued** → JWT token with claims:
   - `federated_user_id` — Corporate user identifier
   - `federated_provider_id` — SSO provider name
   - `euuid` — Enterprise unique user identifier
   - `asset_id` — License/asset identifier
   - Standard OIDC claims: `sub`, `aud`, `iat`, `exp`, `scope`
7. **Platform access** → JWT stored in browser, sent as `Authorization: Bearer <JWT>` on REST APIs, or `?Authorization=<JWT>` on WebSocket connections

**JWT Token Structure (decoded header):**
```json
{
  "alg": "RS256",
  "typ": "JWT",
  "kid": "<KEY_ID>"
}
```

**JWT Claims (masked):**
```json
{
  "https://enterprise.com/federated_user_id": "E12345",
  "https://enterprise.com/federated_provider_id": "ENTERPRISE_SSO",
  "https://enterprise.com/euuid": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
  "https://enterprise.com/assetID": "a0000000",
  "iss": "https://auth.enterprise.com/",
  "sub": "auth0|xxxxxxxxxxxxxxxxxxxxxxxx",
  "aud": [
    "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    "https://main.ciam.enterprise.com/userinfo"
  ],
  "iat": 1771144188,
  "exp": 1771230588,
  "scope": "openid profile email",
  "azp": "<CLIENT_ID>"
}
```

**Key observations for MCP Grid:**
- Token lifetime: ~24 hours (`exp - iat = 86400`)
- Scopes: `openid profile email` (standard OIDC)
- The platform JWT is used for both REST and WebSocket auth
- **MCP Grid must NEVER store this token** — it should be held in memory only during the active session

### 3.2 Azure DevOps Authentication (Microsoft OAuth2)

The platform integrates with Azure DevOps using a **separate Microsoft OAuth2 flow**:

```
┌──────────────┐     ┌──────────────────────┐     ┌──────────────────┐
│   Frontend    │────▶│  login.microsoft     │────▶│  Azure DevOps    │
│   (MSAL.js)  │     │  online.com          │     │  REST APIs       │
│               │◀────│  /oauth2/v2.0/token  │     │  (dev.azure.com) │
└──────────────┘     └──────────────────────┘     └──────────────────┘
```

**Token Request Pattern:**
```
POST https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/token
Content-Type: application/x-www-form-urlencoded

client_id=<CLIENT_ID>
&scope=499b84ac-1321-427f-aa17-267ca6975798/.default
&grant_type=authorization_code
&redirect_uri=https://<PLATFORM_HOST>/ai-platform/chains/use/...
&code=<AUTH_CODE>
```

**Key details:**
- **Tenant ID**: Microsoft Entra (Azure AD) tenant ID
- **Scope**: `499b84ac-1321-427f-aa17-267ca6975798/.default` — This is the well-known Azure DevOps resource ID
- **Client ID**: Registered application in Microsoft Entra
- **MSAL.js**: Frontend uses Microsoft Authentication Library for the OAuth2 flow
- **Token type**: Standard Microsoft JWT (different from platform JWT)

**Azure DevOps API chain (auto-populated after auth):**
```
1. GET https://app.vssps.visualstudio.com/_apis/profile/profiles/me?api-version=7.1
   → Returns: displayName, publicAlias, emailAddress

2. GET https://app.vssps.visualstudio.com/_apis/accounts?memberid={publicAlias}&api-version=7.1
   → Returns: list of organizations [{accountName, accountUri, accountId}]

3. GET https://dev.azure.com/{org}/_apis/projects?$top=1000&api-version=7.1
   → Returns: list of projects [{name, id, state, visibility}]

4. GET https://dev.azure.com/{org}/_apis/projects/{projectId}/teams?$top=1000&api-version=7.1
   → Returns: list of teams [{name, id, description}]
```

**MCP Grid integration point:**
The Azure DevOps JWT is passed as `modelparams.tool_<ID>.azure_devops_token` in the WebSocket payload. The MCP Grid plugin should replicate this OAuth2 flow to auto-populate project/team selectors.

### 3.3 GitHub Authentication (Personal Access Token)

GitHub integration uses a manual **Personal Access Token (PAT)** entry:

```
User → Pastes GitHub PAT into UI text field
     → Token sent as modelparams.tool_<ID>.github_token in WebSocket payload
     → Backend uses PAT to authenticate with GitHub Copilot MCP endpoint
```

**MCP endpoint discovered:**
```
https://api.githubcopilot.com/mcp
```

**MCP Grid UX improvement opportunity:** Instead of a plain text field, provide:
- PAT validation (test API call)
- Repository dropdown (fetch repos via `GET https://api.github.com/user/repos`)
- Typeahead search for repository names

---

## 4. WebSocket Protocol Specification

### 4.1 Connection

```
URL: wss://<API_GATEWAY_ID>.execute-api.<REGION>.amazonaws.com/<STAGE>?Authorization=<JWT_TOKEN>
```

**Key properties:**
- AWS API Gateway WebSocket API
- JWT token passed as query parameter (not header — WebSocket limitation)
- Single persistent connection per browser session
- Multiple workflow executions can share the same connection

### 4.2 Message Types

#### Client → Server Messages

**Heartbeat** (sent every ~27 seconds):
```json
{"action": "heartbeat"}
```

**Execute Workflow** (`SendMessageV2`):
```json
{
  "action": "SendMessageV2",
  "workflow_id": "<UUID>",
  "query": "<USER_PROMPT>",
  "is_persistence_allowed": false,
  "modelparams": {
    "vector_db_<ID>": {
      "size": "57"
    },
    "tool_<AZURE_DEVOPS_ID>": {
      "azure_devops_projects": "",
      "azure_devops_teams": "<TEAM_ID_1>,<TEAM_ID_2>",
      "azure_devops_token": "<MICROSOFT_JWT>"
    },
    "tool_<GITHUB_ID>": {
      "github_token": "<GITHUB_PAT>"
    }
  },
  "input_variables": {
    "manual_entry_<TIMESTAMP>_<HASH1>": "<VALUE_1>",
    "manual_entry_<TIMESTAMP>_<HASH2>": "<VALUE_2>",
    "manual_entry_<TIMESTAMP>_<HASH3>": "<VALUE_3>",
    "manual_entry_<TIMESTAMP>_<HASH4>": "<COMMA_SEPARATED_IDS>"
  },
  "conversation_id": null
}
```

**Field descriptions:**

| Field | Type | Description |
|-------|------|-------------|
| `action` | string | Always `"SendMessageV2"` |
| `workflow_id` | UUID | Identifies the workflow chain to execute |
| `query` | string | The user's prompt/instruction for the agent |
| `is_persistence_allowed` | boolean | Whether to persist conversation history |
| `modelparams` | object | Per-component configuration (tokens, settings) |
| `modelparams.tool_<ID>` | object | Configuration for a specific MCP server component |
| `input_variables` | object | Template variable values from UI form fields |
| `conversation_id` | string\|null | Previous conversation ID for continuation; `null` for new |

### 4.3 Server → Client Messages

#### Heartbeat Response
```json
{"message": "pong"}
```

#### Streaming Answer Chunks
```json
{"agent_<ID>": {"answer": "<TEXT_CHUNK>"}}
```

Answer chunks arrive as small fragments (often single words or phrases) and must be concatenated client-side to form the complete response.

#### Tool Use Request (Auto-Approved)
```json
{
  "agent_<ID>": {
    "tool_use_request": {
      "event_id": "toolu_<UNIQUE_ID>",
      "event_type": "tool_use",
      "tool_use_id": "toolu_<UNIQUE_ID>",
      "request_id": "<SESSION_UUID>",
      "tool_name": "get_work_item",
      "tool_input": {
        "work_item_id": "12345"
      },
      "modified_tool_input": null,
      "tool_output": null,
      "tool_status": null,
      "approval_status": "approved",
      "reason": "Tool 'get_work_item' has been auto-approved for execution",
      "node_name": "agent_<ID>",
      "created_at": "2026-02-15T08:59:37.501230+00:00",
      "updated_at": "2026-02-15T08:59:37.501240+00:00"
    }
  }
}
```

#### Tool Use Response (Success)
```json
{
  "agent_<ID>": {
    "tool_use_response": {
      "tool_output": [
        {"text": "{...JSON response from tool...}"}
      ],
      "tool_status": "success",
      "tool_exception": null,
      "cancel_message": null,
      "updated_at": "2026-02-15T08:59:40.123456+00:00",
      "event_id": "toolu_<UNIQUE_ID>"
    }
  }
}
```

#### Tool Use Response (Error)
```json
{
  "agent_<ID>": {
    "tool_use_response": {
      "tool_output": [
        {"text": "Error: <ERROR_MESSAGE>"}
      ],
      "tool_status": "error",
      "tool_exception": "<DETAILED_ERROR>",
      "cancel_message": null,
      "updated_at": "2026-02-15T09:00:46.367680+00:00",
      "event_id": "toolu_<UNIQUE_ID>"
    }
  }
}
```

#### Agent Execution Stats (End of Run)
```json
{
  "agent_<ID>": {
    "agent_execution_stats": {
      "stop_reason": "end_turn",
      "total_cycles": 10,
      "total_duration": 78.382,
      "average_cycle_time": 7.838,
      "tool_usage": {
        "get_work_item": {
          "tool_info": {
            "tool_use_id": "toolu_<ID>",
            "name": "get_work_item",
            "input_params": {"work_item_id": "12345"}
          },
          "execution_stats": {
            "call_count": 2,
            "success_count": 2,
            "error_count": 0,
            "total_time": 19.771,
            "average_time": 9.886,
            "success_rate": 1.0
          }
        },
        "search_work_items": { "..." : "..." },
        "update_work_item": { "..." : "..." }
      }
    }
  }
}
```

#### Agent Reasoning Traces (Debug/Inspection)
```json
{
  "agent_<ID>": {
    "agent_reasoning": {
      "traces": [
        {
          "id": "<UUID>",
          "name": "Cycle 1",
          "parent_id": null,
          "start_time": 1771146355.371,
          "end_time": null,
          "duration": null,
          "children": [
            {
              "id": "<UUID>",
              "name": "stream_messages",
              "parent_id": "<PARENT_UUID>",
              "start_time": 1771146355.371,
              "end_time": 1771146361.788,
              "duration": 6.416,
              "assistant_text": "I'll analyze the work items...",
              "children": []
            },
            {
              "id": "<UUID>",
              "name": "Tool: get_work_item",
              "parent_id": "<PARENT_UUID>",
              "start_time": 1771146361.853,
              "end_time": 1771146371.0,
              "duration": 9.147,
              "children": []
            }
          ]
        }
      ]
    }
  }
}
```

### 4.4 Message Sequence Diagram

```mermaid
sequenceDiagram
    participant C as Client
    participant GW as WebSocket Gateway
    participant E as Agent Engine

    C->>GW: heartbeat
    GW-->>C: {"message":"pong"}

    C->>GW: SendMessageV2
    GW->>E: Forward to engine

    E-->>GW: stream_messages
    GW-->>C: answer chunk "I'll analyze..."
    GW-->>C: answer chunk "..."

    E-->>GW: tool invocation
    GW-->>C: tool_use_request (get_work_item)
    E-->>GW: tool result
    GW-->>C: tool_use_response (success)

    E-->>GW: continue generation
    GW-->>C: answer chunk "Based on..."

    E-->>GW: next tool
    GW-->>C: tool_use_request (search_items)
    GW-->>C: tool_use_response

    Note over C,E: Cycles repeat for all agent turns

    E-->>GW: execution complete
    GW-->>C: agent_execution_stats
    E-->>GW: debug traces
    GW-->>C: agent_reasoning

    C->>GW: heartbeat
    GW-->>C: {"message":"pong"}
```

---

## 5. REST API Patterns

### 5.1 API Base URLs

| Service | Base URL | Purpose |
|---------|----------|---------|
| Frontend | `https://<PLATFORM_HOST>/ai-platform` | React SPA |
| Core API (v1) | `https://<API_HOST>/v1/` | User, org, assets, filters |
| Core API (v2) | `https://<API_HOST>/v2/` | Workflows, components |
| Common Services | `https://<COMMON_HOST>/v1/` | Favorites, shared services |
| Azure DevOps | `https://dev.azure.com/{org}/` | ADO project/team/work items |
| Azure Identity | `https://app.vssps.visualstudio.com/` | Profile, accounts |
| Microsoft Auth | `https://login.microsoftonline.com/{tenant}/` | OAuth2 token exchange |

### 5.2 Key Endpoints

**User & Organization:**
```
GET  /v1/user                    → Current user profile
GET  /v1/organisation            → Organization details
GET  /v1/asset                   → Licensed assets
GET  /v1/user_favorites          → Bookmarked workflows
```

**Workflow Management:**
```
GET  /v2/workflow_trimmed?page_size=20&sort=created_on&order=desc
     &title=<SEARCH>&is_owned_by_me=true
     → Paginated workflow listing with optional filters

GET  /v2/workflow/<WORKFLOW_UUID>
     → Full workflow definition including system prompt, components, variables

GET  /v1/workflow_filters
     → Available filter options for the workflow listing
```

**Component Catalog:**
```
GET  /v2/components?component_type=all
     → Full catalog of available LLMs, MCP servers, data connectors

GET  /v1/component?task_id=query
     → Components filtered by task type
```

### 5.3 Workflow Definition Structure

A workflow (chain) definition includes:

```json
{
  "workflow_id": "<UUID>",
  "title": "Impact Analysis Agent",
  "description": "...",
  "system_prompt": "## PHASE 1: DATA AGGREGATION\n...\n## PHASE 6: ...",
  "components": [
    {
      "component_id": "<UUID>",
      "component_name": "Claude Opus 4.5",
      "component_type": "llm",
      "component_family": "Anthropic",
      "position": 0
    },
    {
      "component_id": "<UUID>",
      "component_name": "Azure DevOps MCP Server",
      "component_type": "tool",
      "component_family": "McpStreamableHttp",
      "api_type": "mcp",
      "tool_config": {
        "endpoint": "https://<MCP_ENDPOINT>",
        "auth_type": "bearer",
        "headers": {}
      },
      "model_params": [
        {"key": "azure_devops_projects", "type": "text", "label": "Projects"},
        {"key": "azure_devops_teams", "type": "multiselect", "label": "Teams"},
        {"key": "azure_devops_token", "type": "secret", "label": "Token"}
      ]
    },
    {
      "component_id": "<UUID>",
      "component_name": "GitHub MCP Server",
      "component_type": "tool",
      "component_family": "McpStreamableHttp",
      "api_type": "mcp",
      "model_params": [
        {"key": "github_token", "type": "secret", "label": "Token"}
      ]
    },
    {
      "component_id": "<UUID>",
      "component_name": "Bring Your Own Data (BYOD)",
      "component_type": "vector_db",
      "component_family": "OpenSearch",
      "model_params": [
        {"key": "size", "type": "number", "label": "Result Count"}
      ]
    }
  ],
  "input_variables": [
    {"key": "manual_entry_<TS>_<HASH>", "label": "UI Repository Name", "type": "text"},
    {"key": "manual_entry_<TS>_<HASH>", "label": "API Repository Name", "type": "text"},
    {"key": "manual_entry_<TS>_<HASH>", "label": "Product Name", "type": "text"},
    {"key": "manual_entry_<TS>_<HASH>", "label": "Work Item IDs", "type": "text"}
  ]
}
```

---

## 6. MCP Server Component Model

### 6.1 Component Families

MCP servers in the enterprise platform use the `McpStreamableHttp` component family:

| Property | Value |
|----------|-------|
| `component_type` | `tool` |
| `component_family` | `McpStreamableHttp` |
| `api_type` | `mcp` |
| Transport | Streamable HTTP (MCP standard) |
| Auth | Bearer token (platform JWT or service-specific token) |

### 6.2 Available MCP Server Types (Observed)

| Server | Description | Auth Method |
|--------|-------------|-------------|
| Azure DevOps | Work items, projects, teams, boards | Microsoft OAuth2 JWT |
| GitHub | Repositories, issues, PRs, code search | GitHub PAT |
| Microsoft Outlook | Email, calendar integration | Microsoft Graph token |
| Microsoft Teams | Channel messages, notifications | Microsoft Graph token |
| ServiceNow | Incident management, ITSM | ServiceNow API token |
| Alation | Data catalog, metadata discovery | Alation API key |
| Datadog | Monitoring, alerts, dashboards | Datadog API/App keys |

### 6.3 MCP Server Tool Inventory (Azure DevOps)

Tools observed during workflow execution:

| Tool Name | Input Parameters | Description |
|-----------|-----------------|-------------|
| `get_work_item` | `work_item_id: string` | Fetch a single work item by ID |
| `search_work_items` | `azure_devops_project: string, query: string` | Execute a WIQL query |
| `update_work_item` | `azure_devops_project: string, work_item_id: number, custom_fields: string` | Update fields/tags on a work item |
| `list_projects` | (none) | List all accessible projects |

**WIQL query examples observed:**
```sql
-- Fetch specific work items
SELECT [System.Id], [System.Title], [System.State], [System.Description],
       [System.WorkItemType], [Microsoft.VSTS.Common.AcceptanceCriteria]
FROM WorkItems WHERE [System.Id] IN (12345, 67890)

-- Search for related bugs
SELECT [System.Id], [System.Title], [System.State], [System.WorkItemType]
FROM WorkItems
WHERE [System.WorkItemType] = 'Bug'
  AND ([System.Title] CONTAINS 'Feature A' OR [System.Title] CONTAINS 'Feature B')
ORDER BY [System.CreatedDate] DESC

-- Find closed user stories
SELECT [System.Id], [System.Title], [System.State], [System.WorkItemType]
FROM WorkItems
WHERE [System.WorkItemType] = 'User Story'
  AND [System.State] = 'Closed'
  AND [System.Tags] CONTAINS 'Product X'
ORDER BY [System.CreatedDate] DESC
```

---

## 7. Workflow Chain Execution Model

### 7.1 Execution Phases (Observed Pattern)

The "Impact Analysis Agent" workflow follows a structured multi-phase execution:

```
PHASE 1: DATA AGGREGATION
  └─ Fetch work item details via get_work_item
  └─ Cross-reference with WIQL queries via search_work_items

PHASE 2: TAG AUGMENTATION
  └─ Analyze existing tags
  └─ Update work items with analysis tags via update_work_item

PHASE 3: CROSS-REFERENCE ANALYSIS
  └─ Search for related bugs and stories
  └─ Query vector database (BYOD) for historical context

PHASE 4: IMPACT ASSESSMENT
  └─ Agent reasoning over aggregated data
  └─ Generate impact analysis report

PHASE 5: TESTING SCENARIOS
  └─ Derive test scenarios from impact analysis
  └─ Suggest automation priorities

PHASE 6: EFFORT ESTIMATION
  └─ Break down into tasks
  └─ Estimate effort per area
```

### 7.2 Agent Execution Metrics (Real Example, Masked)

```
Total cycles: 10
Total duration: 78.38 seconds
Average cycle time: 7.84 seconds
Tool calls: 18
  - get_work_item: 2 calls, 100% success, avg 9.9s
  - search_work_items: 8 calls, 75% success, avg 4.2s
  - update_work_item: 6 calls, 50% success (MCP session errors), avg 3.1s
  - list_projects: 2 calls, 100% success, avg 2.8s
Stop reason: end_turn
```

---

## 8. Tool Invocation Protocol

### 8.1 Request → Approval → Execution → Response

```
1. Agent decides to use a tool
2. Platform sends tool_use_request with approval_status: "approved"
   (auto-approval is the default; manual approval can be configured)
3. Platform executes the tool against the MCP server
4. Platform sends tool_use_response with result or error
5. Agent incorporates result and continues reasoning
```

### 8.2 Auto-Approval

All tool calls observed were auto-approved:
```json
"approval_status": "approved",
"reason": "Tool 'get_work_item' has been auto-approved for execution"
```

The platform supports configurable approval policies per tool, per workflow, or per organization.

### 8.3 Error Recovery Pattern

When MCP server sessions timeout:
```
tool_use_request (update_work_item) → sent
tool_use_response → Error: MCP client session not running
tool_use_request (retry same call) → sent
tool_use_response → Error: MCP client session not running
...agent adjusts strategy and continues with available data...
```

**Key observation:** The agent is resilient to tool failures — it adjusts its approach and continues with the data it has, rather than failing the entire workflow.

---

## 9. Error Handling & Resilience Patterns

### 9.1 MCP Client Session Timeout

**Error pattern:**
```
Error: the client session is not running. Ensure the agent is used within
the MCP client context manager.
```

**Root cause:** The MCP server's HTTP session expired or the connection pool was exhausted.

**Mitigation for MCP Grid:**
- Implement automatic session re-initialization on timeout
- Use connection pooling with health checks
- Configure retry with exponential backoff (max 3 retries)

### 9.2 GitHub MCP Endpoint Error

**Error pattern:**
```
Client error '400 Bad Request' for url 'https://api.githubcopilot.com/mcp'
```

**Root cause:** Invalid or expired GitHub PAT.

**Mitigation for MCP Grid:**
- Validate PAT before workflow execution
- Provide clear error message to user
- Support PAT refresh without re-running entire workflow

### 9.3 WebSocket Reconnection

**Observed behavior:**
- Multiple WebSocket connections can exist simultaneously (session 1 for failed run, session 2 for retry)
- Each new workflow execution can open a new WebSocket or reuse existing
- Heartbeat failure triggers automatic reconnection

---

## 10. Enterprise Privacy & Security Guarantees

### 10.1 Data Flow Boundaries

```mermaid
flowchart TB
    subgraph Local["USER'S LOCAL MACHINE"]
        subgraph IDE["VS Code / Cursor IDE"]
            EXT["Extension UI"]
        end
        subgraph Bridge["MCP Grid Bridge"]
            T1["✓ Tokens in memory only"]
            T2["✓ No disk persistence of creds"]
            T3["✓ Localhost-only API binding"]
            T4["✓ Per-session isolation"]
        end
        IDE <--> Bridge
    end

    subgraph Platform["Enterprise AI Platform<br/>(customer's own infrastructure)"]
        P["REST API + WebSocket"]
    end

    Bridge -->|"Outbound only<br/>(HTTPS/WSS)"| Platform

    style Local fill:#e8ffe8,stroke:#16a34a
    style Platform fill:#f0f9ff,stroke:#0284c7
```

### 10.2 Security Principles

| Principle | Implementation |
|-----------|---------------|
| **Token locality** | All tokens (platform JWT, Azure DevOps JWT, GitHub PAT) are stored ONLY in the extension's in-memory state. Never written to disk, never logged. |
| **Transport security** | All connections use TLS 1.3 (HTTPS/WSS). No plaintext traffic. |
| **Session isolation** | Each workflow execution gets its own isolated context. Tokens are not shared across sessions. |
| **No credential forwarding** | MCP Grid never forwards credentials to any service other than the explicitly configured enterprise platform. |
| **Audit trail** | All tool calls are logged locally (metrics DB) without credential values. Enterprise can audit via their own platform logs. |
| **Zero telemetry** | MCP Grid does not phone home. No analytics, no crash reports, no usage data sent externally. |
| **Credential masking** | In all logs, UI displays, and error messages, token values are replaced with `<REDACTED>`. |

### 10.3 Compliance Checklist

- [x] SOC 2 Type II compatible (no persistent credential storage)
- [x] GDPR compatible (no PII collected by MCP Grid)
- [x] Enterprise firewall friendly (outbound HTTPS/WSS only)
- [x] Air-gap compatible (can operate without internet if platform is on-premise)
- [x] Secrets management ready (supports OS keychain, HashiCorp Vault integration)

---

## 11. MCP Grid Plugin Integration Design

### 11.1 New Meta-Tools for Enterprise Platform Integration

In addition to the existing 9 meta-tools, the enterprise integration adds:

| Tool | Purpose |
|------|---------|
| `connect_platform` | Authenticate to an enterprise AI platform via browser-based SSO |
| `list_workflows` | Browse available workflow chains on the connected platform |
| `get_workflow_details` | Fetch full workflow definition including components and variables |
| `configure_workflow` | Set input variables and model parameters for a workflow |
| `execute_workflow` | Trigger workflow execution via WebSocket and stream results |
| `get_execution_status` | Check ongoing workflow execution status and progress |
| `list_platform_components` | Browse the platform's component catalog |

### 11.2 New Python Modules

```
src/mcp_bridge/
  platforms/                    # Enterprise platform integrations
    __init__.py
    base.py                     # Abstract platform adapter interface
    websocket_adapter.py        # WebSocket connection management
    auth/
      __init__.py
      sso_browser.py            # Browser-based SSO capture
      microsoft_oauth.py        # Microsoft OAuth2 / MSAL flow
      token_manager.py          # In-memory token lifecycle management
    workflow/
      __init__.py
      executor.py               # WebSocket-based workflow execution
      streaming.py              # Answer chunk aggregation
      heartbeat.py              # Heartbeat keepalive manager
    models/
      __init__.py
      workflow.py               # Workflow, Component, InputVariable models
      messages.py               # WebSocket message type models
      execution.py              # ExecutionStats, ToolUsage models
```

### 11.3 Extension UI Components (VS Code/Cursor)

```
extension/src/
  views/
    platformPanel.ts            # Main platform connection panel
    workflowBrowser.ts          # Workflow listing with search/filter
    workflowRunner.ts           # Execution view with streaming output
    configForm.ts               # Dynamic form for workflow input variables
  providers/
    platformTreeProvider.ts     # Sidebar tree: Platforms → Workflows → Components
    executionTreeProvider.ts    # Active/past execution history tree
  auth/
    ssoWebview.ts               # Embedded browser for SSO login
    msalAuth.ts                 # Microsoft OAuth2 flow handler
    tokenStore.ts               # VS Code SecretStorage integration
  adapters/
    azureDevOpsAdapter.ts       # Project/team selector with auto-populate
    githubAdapter.ts            # PAT validation + repo dropdown
```

---

## 12. UX/UI Patterns for Enterprise Configuration

### 12.1 Azure DevOps Configuration Flow

```
┌───────────────────────────────────────────────┐
│ Azure DevOps Configuration                     │
│                                                │
│ ┌─ Sign In ─────────────────────────────────┐ │
│ │ [Sign in with Microsoft]  ← OAuth2 popup  │ │
│ └───────────────────────────────────────────┘ │
│                                                │
│ ┌─ Organization ────────────────────────────┐ │
│ │ ▼ [Select Organization]                    │ │  ← Auto-populated from
│ │   ├── org-alpha                            │ │     /accounts API
│ │   └── org-beta                             │ │
│ └───────────────────────────────────────────┘ │
│                                                │
│ ┌─ Project ─────────────────────────────────┐ │
│ │ ▼ [Select Project]                         │ │  ← Auto-populated from
│ │   ├── ProjectAlpha (id: xxx)               │ │     /projects API
│ │   ├── ProjectBeta  (id: yyy)               │ │
│ │   └── ProjectGamma (id: zzz)               │ │
│ └───────────────────────────────────────────┘ │
│                                                │
│ ┌─ Teams ───────────────────────────────────┐ │
│ │ ☑ Team Engineering                         │ │  ← Multi-select from
│ │ ☑ Team Product Management                  │ │     /teams API
│ │ ☐ Team Design                              │ │
│ │ ☐ Team QA                                  │ │
│ └───────────────────────────────────────────┘ │
│                                                │
│ [Save Configuration]                           │
└───────────────────────────────────────────────┘
```

### 12.2 GitHub Configuration Flow (Enhanced)

```
┌───────────────────────────────────────────────┐
│ GitHub Configuration                           │
│                                                │
│ ┌─ Token ───────────────────────────────────┐ │
│ │ GitHub PAT: [••••••••••••••••] [Validate]  │ │
│ │ Status: ✓ Valid (scopes: repo, read:org)   │ │
│ └───────────────────────────────────────────┘ │
│                                                │
│ ┌─ Repository ──────────────────────────────┐ │
│ │ 🔍 [Type to search repositories...]        │ │  ← Typeahead search
│ │   ├── org/repo-frontend     ★ 42          │ │     via GitHub API
│ │   ├── org/repo-api          ★ 28          │ │
│ │   └── org/repo-shared-lib   ★ 15          │ │
│ └───────────────────────────────────────────┘ │
│                                                │
│ [Save Configuration]                           │
└───────────────────────────────────────────────┘
```

### 12.3 Work Item ID Input (Enhanced)

```
┌───────────────────────────────────────────────┐
│ Work Item IDs                                  │
│                                                │
│ 🔍 [Type ID or title to search...]             │  ← Typeahead search
│   ├── #12345 - Flow-Through Entity Support     │     via search_work_items
│   ├── #12346 - Currency Management Updates     │
│   └── #12347 - Unit Relationship Fixes         │
│                                                │
│ Selected: [#12345] [#12347]  [×]               │  ← Tag-style chips
│                                                │
└───────────────────────────────────────────────┘
```

---

## 13. Phase Roadmap

### Phase 2 (Current): Core Extension & Bridge

| Task | Status | Description |
|------|--------|-------------|
| VS Code extension sidebar | ✅ Built | Tree views for servers, instances, metrics |
| Management API | ✅ Built | REST + WebSocket for extension communication |
| Bridge server | ✅ Built | 9 meta-tools, instance management, metrics |
| Live testing | 🔲 Pending | Verify extension + bridge work end-to-end |
| PyPI publish | 🔲 Pending | Package and publish Python backend |
| VS Code Marketplace | 🔲 Pending | Package and publish extension |

### Phase 3: Advanced Features

| Task | Priority | Description |
|------|----------|-------------|
| OpenAPI-to-MCP adapter | P0 | Convert OpenAPI specs → dynamic MCP tools |
| WebSocket-to-MCP adapter | P0 | Expose WebSocket endpoints as MCP tools |
| MCP Server Marketplace | P1 | Web catalog at `mcp.qabots.diy` |
| Enterprise privacy framework | P0 | Document and enforce data locality guarantees |
| Auto-discovery | P2 | Detect installed MCP servers automatically |
| IB-QA web portal | P1 | `qabots.diy` homepage on Cloudflare Pages |

### Phase 4: Enterprise AI Platform Integration

| Task | Priority | Description |
|------|----------|-------------|
| Platform adapter interface | P0 | Abstract base for any enterprise AI platform |
| SSO browser capture | P0 | Embedded webview for enterprise SSO + MFA |
| Microsoft OAuth2 integration | P0 | MSAL-based Azure DevOps token management |
| WebSocket workflow executor | P0 | Real-time chain execution with streaming |
| Heartbeat manager | P1 | Automatic keepalive for long-running workflows |
| Dynamic form generation | P1 | Auto-generate UI from workflow input_variables |
| Azure DevOps project/team picker | P1 | Auto-populated selectors from ADO APIs |
| GitHub repo dropdown | P1 | PAT-based typeahead repository search |
| Work Item ID typeahead | P2 | WIQL-powered work item search |
| Component catalog browser | P2 | Browse platform's MCP server catalog |
| Execution history | P2 | Track past workflow runs with stats |
| Error retry logic | P1 | Automatic re-initialization on MCP session timeout |
| React Flow visualization | P3 | Agent execution node graph (like platform UI) |

### Phase 4b: Standalone Client Plugin

A **separate repository** (`tr-ai-platform-mcp`) will be created as a standalone
MCP server plugin specifically for the client's AI Platform. This serves as:
- A **directly deliverable product** for the client to use internally
- A **reference implementation** demonstrating enterprise platform integration
- An **inspiration source** for the generic adapter in MCP Grid's Phase 4

| Task | Priority | Description |
|------|----------|-------------|
| Standalone MCP server | P0 | FastMCP server with direct workflow execution tools |
| SSO browser auth capture | P0 | Webview-based SSO + MFA flow for token acquisition |
| WebSocket executor | P0 | Open-send-receive-close pattern for chain execution |
| Azure DevOps OAuth2 | P0 | MSAL-based token flow for ADO integration |
| GitHub PAT validation | P1 | Validate and test PAT before workflow execution |
| Workflow browser tool | P1 | List and search available workflow chains |
| Dynamic input form | P1 | Auto-generate prompts from workflow input_variables |

### Phase 5: Ecosystem & Scaling

| Task | Priority | Description |
|------|----------|-------------|
| Multi-platform support | P1 | Adapters for additional enterprise AI platforms |
| npm package | P2 | Node.js agent support |
| Community catalog | P2 | Open-source MCP server contributions |
| Performance benchmarking | P3 | Automated MCP server latency/reliability testing |
| IB-QA organization site | P1 | Dynamic template for `qabots.diy` |

### Roadmap: VS Code Chat UI for Workflow Chains

A future enhancement (not in current scope) to add a persistent chat webview
panel inside VS Code/Cursor where users can have ongoing conversations with
workflow chains, similar to the enterprise platform's web UI. This requires:
- Persistent WebSocket connections with full heartbeat management
- Conversation continuation via `conversation_id`
- Rich markdown rendering of agent responses
- Interactive tool approval (for non-auto-approved tools)
- React Flow-style node visualization

**Deferred until**: More enterprise patterns are captured from additional clients.

---

## Appendix A: Tool Names Observed in Workflow Execution

| Tool | Source MCP Server | Invocation Count | Success Rate |
|------|------------------|------------------|--------------|
| `get_work_item` | Azure DevOps | 4 | 100% |
| `search_work_items` | Azure DevOps | 12 | ~75% |
| `update_work_item` | Azure DevOps | 8 | ~50% (session timeouts) |
| `list_projects` | Azure DevOps | 2 | 100% |

## Appendix B: Input Variable Patterns

| Variable Key Pattern | UI Label | Type | Example Value |
|---------------------|----------|------|---------------|
| `manual_entry_<TS>_<HASH>` | UI Repository Name | text | `org\\repo-frontend` |
| `manual_entry_<TS>_<HASH>` | API Repository Name | text | `org\\repo-api` |
| `manual_entry_<TS>_<HASH>` | Product Name | text | `Product X` |
| `manual_entry_<TS>_<HASH>` | Work Item IDs | text | `12345, 67890` |

**Note:** The backslash-escaped format `org\\repo-name` is used for GitHub repository references within the platform.

## Appendix C: WebSocket Connection Lifecycle

```
1. Page load → Frontend obtains platform JWT
2. User opens workflow → Frontend fetches workflow definition via REST
3. User configures inputs → Frontend collects modelparams and input_variables
4. User clicks "Send" → Frontend opens WebSocket with JWT in query param
5. Frontend sends SendMessageV2 → Agent engine begins execution
6. Client maintains heartbeat every ~27 seconds
7. Server streams answer chunks, tool requests/responses
8. Agent completes → Server sends execution_stats and reasoning traces
9. Connection stays alive for follow-up messages or new conversations
10. On page navigation/close → WebSocket is closed by client
```

---

*Document generated by MCP Grid Architecture Team. All enterprise-specific data has been masked.*
