# AI + Human 协作 Demo 指南

## 概述

本文档演示 ColaFlow 的核心特性：AI 通过 MCP 协议安全地读写项目数据，人类通过审批机制保持对系统的控制权。

**Demo 场景**：AI 助手读取项目信息，提议创建一个新 Epic，人类审批后系统执行变更。

---

## 1. 环境准备

### 1.1 启动后端服务

```bash
cd colaflow-api
dotnet run
```

后端服务运行在 `http://localhost:5000`（或 `https://localhost:5001`）

### 1.2 启动前端服务

```bash
cd colaflow-web
npm run dev
```

前端服务运行在 `http://localhost:3000`

### 1.3 创建测试用户

```bash
# 注册测试用户
curl -X POST http://localhost:5000/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "username": "demo_user",
    "email": "demo@colaflow.com",
    "password": "Demo@12345"
  }'
```

### 1.4 登录获取 JWT Token

```bash
curl -X POST http://localhost:5000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "demo@colaflow.com",
    "password": "Demo@12345"
  }'
```

**响应示例**：
```json
{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "id": "user-uuid",
    "username": "demo_user",
    "email": "demo@colaflow.com"
  }
}
```

保存返回的 `token`，后续所有请求需要使用。

### 1.5 创建测试项目

```bash
curl -X POST http://localhost:5000/api/projects \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "ColaFlow Demo",
    "key": "DEMO",
    "description": "AI + Human 协作演示项目"
  }'
```

**响应示例**：
```json
{
  "id": "project-uuid",
  "name": "ColaFlow Demo",
  "key": "DEMO",
  "description": "AI + Human 协作演示项目"
}
```

保存返回的 `id`，后续步骤需要使用。

### 1.6 创建 MCP API Key

```bash
curl -X POST http://localhost:5000/api/mcp/keys \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "AI Assistant Demo",
    "description": "用于演示 AI 协作功能",
    "expiresInDays": 30
  }'
```

**响应示例**：
```json
{
  "id": "key-uuid",
  "name": "AI Assistant Demo",
  "key": "mcp_live_1234567890abcdef",
  "createdAt": "2025-11-09T10:00:00Z",
  "expiresAt": "2025-12-09T10:00:00Z"
}
```

**重要**：保存返回的 `key`，这是 AI 调用 MCP 协议的凭证，只显示一次！

---

## 2. 完整 Demo 流程（7步）

### Step 1: AI 连接和认证

AI 客户端使用 MCP API Key 连接到 ColaFlow MCP Server。

**测试连接**：
```bash
curl -X POST http://localhost:5000/mcp \
  -H "Authorization: Bearer mcp_live_1234567890abcdef" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "initialize",
    "params": {
      "protocolVersion": "2024-11-05",
      "capabilities": {
        "roots": {
          "listChanged": true
        }
      },
      "clientInfo": {
        "name": "ColaFlow AI Assistant",
        "version": "1.0.0"
      }
    },
    "id": 1
  }'
```

**响应示例**：
```json
{
  "jsonrpc": "2.0",
  "result": {
    "protocolVersion": "2024-11-05",
    "capabilities": {
      "resources": {},
      "tools": {}
    },
    "serverInfo": {
      "name": "ColaFlow MCP Server",
      "version": "1.0.0"
    }
  },
  "id": 1
}
```

---

### Step 2: AI 读取项目数据

#### 2.1 列出可用资源

```bash
curl -X POST http://localhost:5000/mcp \
  -H "Authorization: Bearer mcp_live_1234567890abcdef" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "resources/list",
    "id": 2
  }'
```

**响应示例**：
```json
{
  "jsonrpc": "2.0",
  "result": {
    "resources": [
      {
        "uri": "colaflow://projects/project-uuid",
        "name": "Project: ColaFlow Demo",
        "description": "项目详情和配置",
        "mimeType": "application/json"
      },
      {
        "uri": "colaflow://projects/project-uuid/epics",
        "name": "Epics in ColaFlow Demo",
        "description": "项目的所有 Epic",
        "mimeType": "application/json"
      }
    ]
  },
  "id": 2
}
```

#### 2.2 读取项目详情

```bash
curl -X POST http://localhost:5000/mcp \
  -H "Authorization: Bearer mcp_live_1234567890abcdef" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "resources/read",
    "params": {
      "uri": "colaflow://projects/project-uuid"
    },
    "id": 3
  }'
```

**响应示例**：
```json
{
  "jsonrpc": "2.0",
  "result": {
    "contents": [
      {
        "uri": "colaflow://projects/project-uuid",
        "mimeType": "application/json",
        "text": "{\"id\":\"project-uuid\",\"name\":\"ColaFlow Demo\",\"key\":\"DEMO\",\"description\":\"AI + Human 协作演示项目\",\"epicCount\":0,\"storyCount\":0,\"taskCount\":0}"
      }
    ]
  },
  "id": 3
}
```

#### 2.3 读取项目的 Epic 列表

```bash
curl -X POST http://localhost:5000/mcp \
  -H "Authorization: Bearer mcp_live_1234567890abcdef" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "resources/read",
    "params": {
      "uri": "colaflow://projects/project-uuid/epics"
    },
    "id": 4
  }'
```

**响应示例**：
```json
{
  "jsonrpc": "2.0",
  "result": {
    "contents": [
      {
        "uri": "colaflow://projects/project-uuid/epics",
        "mimeType": "application/json",
        "text": "{\"epics\":[]}"
      }
    ]
  },
  "id": 4
}
```

---

### Step 3: AI 提议创建 Epic

AI 分析项目数据后，决定创建一个新的 Epic。

#### 3.1 列出可用工具

```bash
curl -X POST http://localhost:5000/mcp \
  -H "Authorization: Bearer mcp_live_1234567890abcdef" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "tools/list",
    "id": 5
  }'
```

**响应示例**：
```json
{
  "jsonrpc": "2.0",
  "result": {
    "tools": [
      {
        "name": "create_issue",
        "description": "创建新的 Epic、Story 或 Task",
        "inputSchema": {
          "type": "object",
          "properties": {
            "type": {
              "type": "string",
              "enum": ["EPIC", "STORY", "TASK"],
              "description": "Issue 类型"
            },
            "title": {
              "type": "string",
              "description": "Issue 标题"
            },
            "description": {
              "type": "string",
              "description": "Issue 描述"
            },
            "project_id": {
              "type": "string",
              "description": "项目 ID（Epic 必需）"
            },
            "epic_id": {
              "type": "string",
              "description": "Epic ID（Story 必需）"
            },
            "story_id": {
              "type": "string",
              "description": "Story ID（Task 必需）"
            }
          },
          "required": ["type", "title"]
        }
      }
    ]
  },
  "id": 5
}
```

#### 3.2 调用 create_issue Tool

```bash
curl -X POST http://localhost:5000/mcp \
  -H "Authorization: Bearer mcp_live_1234567890abcdef" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "tools/call",
    "params": {
      "name": "create_issue",
      "arguments": {
        "type": "EPIC",
        "title": "用户认证系统",
        "description": "实现用户注册、登录、JWT 认证和 OAuth 集成功能",
        "project_id": "project-uuid"
      }
    },
    "id": 6
  }'
```

---

### Step 4: 系统生成 Diff Preview 和 PendingChange

系统接收到 AI 的创建请求后，不会立即执行，而是：

1. **生成 Diff Preview**：显示即将发生的变更
2. **创建 PendingChange**：等待人类审批
3. **返回响应给 AI**

**响应示例**：
```json
{
  "jsonrpc": "2.0",
  "result": {
    "content": [
      {
        "type": "text",
        "text": "已创建待审批的变更请求。\n\nPendingChange ID: pending-change-uuid\n状态: PENDING\n\n变更预览:\n=== 新建 Epic ===\n标题: 用户认证系统\n描述: 实现用户注册、登录、JWT 认证和 OAuth 集成功能\n项目: ColaFlow Demo (DEMO)\n\n此变更需要人类审批后才会执行。"
      }
    ],
    "isError": false
  },
  "id": 6
}
```

**系统内部流程**：
1. 创建 `PendingChange` 记录（状态：PENDING）
2. 生成 Diff Preview JSON
3. 触发 SignalR 实时通知到前端

---

### Step 5: 前端收到 SignalR 实时通知

前端通过 SignalR 实时接收到新的 PendingChange 通知。

#### 5.1 SignalR 连接示例（JavaScript）

```javascript
// 在前端应用中建立 SignalR 连接
import * as signalR from "@microsoft/signalr";

const connection = new signalR.HubConnectionBuilder()
  .withUrl("http://localhost:5000/hubs/mcp", {
    accessTokenFactory: () => "YOUR_JWT_TOKEN"
  })
  .withAutomaticReconnect()
  .build();

// 监听 PendingChange 事件
connection.on("PendingChangeCreated", (pendingChange) => {
  console.log("新的待审批变更:", pendingChange);

  // 显示通知
  showNotification({
    title: "AI 提议新变更",
    message: `${pendingChange.operation}: ${pendingChange.metadata.title}`,
    action: "查看详情"
  });

  // 更新 UI
  updatePendingChangesList(pendingChange);
});

connection.on("PendingChangeApproved", (pendingChange) => {
  console.log("变更已审批:", pendingChange);
  showNotification({
    title: "变更已执行",
    message: `Epic "${pendingChange.metadata.title}" 已创建`,
    type: "success"
  });
});

connection.on("PendingChangeRejected", (pendingChange) => {
  console.log("变更已拒绝:", pendingChange);
  showNotification({
    title: "变更已拒绝",
    message: `AI 提议的变更已被拒绝`,
    type: "warning"
  });
});

// 启动连接
await connection.start();
console.log("SignalR 已连接");
```

#### 5.2 前端 UI 显示

前端收到通知后，应显示：

**PendingChange 列表项**：
```
┌─────────────────────────────────────────────────┐
│ 🤖 AI 提议新变更 - 等待审批                     │
├─────────────────────────────────────────────────┤
│ 操作: CREATE_EPIC                                │
│ 标题: 用户认证系统                               │
│ 描述: 实现用户注册、登录、JWT 认证和 OAuth...   │
│ 项目: ColaFlow Demo (DEMO)                       │
│ 时间: 2025-11-09 10:30:25                        │
│                                                   │
│ [查看详情] [批准] [拒绝]                         │
└─────────────────────────────────────────────────┘
```

**Diff Preview 对话框**：
```json
{
  "operation": "CREATE_EPIC",
  "before": null,
  "after": {
    "title": "用户认证系统",
    "description": "实现用户注册、登录、JWT 认证和 OAuth 集成功能",
    "project_id": "project-uuid",
    "project_name": "ColaFlow Demo",
    "status": "TODO"
  },
  "changes": [
    "+ Epic: 用户认证系统",
    "+ 项目: ColaFlow Demo (DEMO)",
    "+ 状态: TODO"
  ]
}
```

---

### Step 6: 人类审批变更

用户在前端点击 "批准" 或 "拒绝" 按钮。

#### 6.1 获取 PendingChange 列表

```bash
curl -X GET http://localhost:5000/api/mcp/pending-changes \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

**响应示例**：
```json
{
  "items": [
    {
      "id": "pending-change-uuid",
      "mcpApiKeyId": "key-uuid",
      "operation": "CREATE_EPIC",
      "status": "PENDING",
      "metadata": {
        "type": "EPIC",
        "title": "用户认证系统",
        "description": "实现用户注册、登录、JWT 认证和 OAuth 集成功能",
        "project_id": "project-uuid"
      },
      "diffPreview": "{\"operation\":\"CREATE_EPIC\",\"after\":{...}}",
      "createdAt": "2025-11-09T10:30:25Z"
    }
  ],
  "total": 1,
  "page": 1,
  "pageSize": 20
}
```

#### 6.2 获取 PendingChange 详情

```bash
curl -X GET http://localhost:5000/api/mcp/pending-changes/pending-change-uuid \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

#### 6.3 批准变更

```bash
curl -X POST http://localhost:5000/api/mcp/pending-changes/pending-change-uuid/approve \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json"
```

**响应示例**：
```json
{
  "id": "pending-change-uuid",
  "status": "APPROVED",
  "approvedAt": "2025-11-09T10:35:00Z",
  "approvedBy": "user-uuid",
  "executedAt": "2025-11-09T10:35:00Z",
  "resultData": {
    "epic_id": "epic-uuid",
    "epic_key": "DEMO-1",
    "title": "用户认证系统"
  }
}
```

#### 6.4 拒绝变更（可选）

```bash
curl -X POST http://localhost:5000/api/mcp/pending-changes/pending-change-uuid/reject \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "reason": "需要更详细的需求描述"
  }'
```

**响应示例**：
```json
{
  "id": "pending-change-uuid",
  "status": "REJECTED",
  "rejectedAt": "2025-11-09T10:35:00Z",
  "rejectedBy": "user-uuid",
  "rejectionReason": "需要更详细的需求描述"
}
```

---

### Step 7: 系统执行变更并通知 AI

人类批准后，系统自动执行以下流程：

1. **执行变更**：调用业务逻辑创建 Epic
2. **更新 PendingChange 状态**：APPROVED + 记录执行结果
3. **SignalR 通知前端**：`PendingChangeApproved` 事件
4. **（可选）通知 AI**：通过回调机制通知 AI 变更已执行

**系统内部流程**：
```csharp
// PendingChangeService.ApproveAsync()
public async Task<PendingChange> ApproveAsync(Guid id, Guid userId)
{
    var pendingChange = await GetByIdAsync(id);

    // 1. 执行变更
    var result = await _changeExecutor.ExecuteAsync(pendingChange);

    // 2. 更新状态
    pendingChange.Approve(userId, result);
    await _repository.UpdateAsync(pendingChange);

    // 3. 通知前端
    await _hubContext.Clients.User(userId.ToString())
        .SendAsync("PendingChangeApproved", pendingChange);

    return pendingChange;
}
```

**AI 可以查询执行结果**：
```bash
curl -X POST http://localhost:5000/mcp \
  -H "Authorization: Bearer mcp_live_1234567890abcdef" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "resources/read",
    "params": {
      "uri": "colaflow://projects/project-uuid/epics"
    },
    "id": 7
  }'
```

**响应示例**：
```json
{
  "jsonrpc": "2.0",
  "result": {
    "contents": [
      {
        "uri": "colaflow://projects/project-uuid/epics",
        "mimeType": "application/json",
        "text": "{\"epics\":[{\"id\":\"epic-uuid\",\"key\":\"DEMO-1\",\"title\":\"用户认证系统\",\"description\":\"实现用户注册、登录、JWT 认证和 OAuth 集成功能\",\"status\":\"TODO\",\"createdAt\":\"2025-11-09T10:35:00Z\"}]}"
      }
    ]
  },
  "id": 7
}
```

---

## 3. 演示要点

### 3.1 安全性：Human-in-the-Loop

**核心机制**：
- AI 不能直接修改数据，所有写操作必须经过人类审批
- PendingChange 作为安全隔离层
- 审批权限基于用户角色和项目权限

**演示重点**：
1. 展示 AI 调用 `create_issue` 后，数据库中**没有**立即创建 Epic
2. 展示 `PendingChange` 表中的待审批记录（状态：PENDING）
3. 展示人类审批后，Epic 才真正创建

**SQL 查询示例**：
```sql
-- 查看 PendingChange
SELECT * FROM PendingChanges WHERE Status = 'PENDING';

-- 查看 Epics（审批前应为空）
SELECT * FROM Epics WHERE ProjectId = 'project-uuid';

-- 人类批准后再查看
SELECT * FROM Epics WHERE ProjectId = 'project-uuid';
-- 应该看到新创建的 Epic
```

---

### 3.2 透明性：Diff Preview

**核心机制**：
- 每个 PendingChange 都包含 `diffPreview` JSON
- 清晰展示变更前后的对比
- 支持复杂变更（UPDATE、DELETE）

**Diff Preview 结构**：
```json
{
  "operation": "CREATE_EPIC",
  "before": null,  // CREATE 操作 before 为 null
  "after": {
    "title": "用户认证系统",
    "description": "实现用户注册、登录、JWT 认证和 OAuth 集成功能",
    "project_id": "project-uuid",
    "project_name": "ColaFlow Demo",
    "status": "TODO"
  },
  "changes": [
    "+ Epic: 用户认证系统",
    "+ 项目: ColaFlow Demo (DEMO)",
    "+ 状态: TODO"
  ]
}
```

**UPDATE 操作示例**：
```json
{
  "operation": "UPDATE_EPIC",
  "before": {
    "title": "用户认证系统",
    "status": "TODO"
  },
  "after": {
    "title": "用户认证系统 v2.0",
    "status": "IN_PROGRESS"
  },
  "changes": [
    "~ 标题: 用户认证系统 → 用户认证系统 v2.0",
    "~ 状态: TODO → IN_PROGRESS"
  ]
}
```

---

### 3.3 实时性：SignalR

**核心机制**：
- 前端通过 SignalR 实时接收变更通知
- 支持多用户协作场景
- 减少轮询，提升性能

**演示场景**：
1. **单用户场景**：
   - 用户 A 创建 API Key 给 AI
   - AI 提议变更
   - 用户 A 立即收到通知（浏览器右上角弹窗）

2. **多用户场景**：
   - 用户 A 创建 API Key 给 AI
   - AI 提议变更
   - 用户 A 和用户 B（同一项目成员）都收到通知
   - 用户 B 先批准
   - 用户 A 看到变更已执行的通知

**SignalR 事件流程**：
```
AI 调用 Tool
    ↓
PendingChange 创建
    ↓
SignalR: PendingChangeCreated → 前端显示通知
    ↓
人类批准
    ↓
PendingChange 执行
    ↓
SignalR: PendingChangeApproved → 前端更新 UI
```

---

### 3.4 多租户隔离

**核心机制**：
- 每个 MCP API Key 关联一个用户
- PendingChange 只能由 Key 的所有者审批
- 跨项目隔离（用户只能访问自己的项目）

**演示验证**：
```bash
# 用户 A 创建 API Key
curl -X POST http://localhost:5000/api/mcp/keys \
  -H "Authorization: Bearer USER_A_JWT_TOKEN" \
  -d '{"name": "AI Key A"}'

# AI 使用 Key A 创建变更
curl -X POST http://localhost:5000/mcp \
  -H "Authorization: Bearer mcp_live_key_a" \
  -d '{...}'

# 用户 B 尝试批准（应该失败 - 403 Forbidden）
curl -X POST http://localhost:5000/api/mcp/pending-changes/{id}/approve \
  -H "Authorization: Bearer USER_B_JWT_TOKEN"

# 用户 A 批准（成功）
curl -X POST http://localhost:5000/api/mcp/pending-changes/{id}/approve \
  -H "Authorization: Bearer USER_A_JWT_TOKEN"
```

---

## 4. 前端界面演示建议

### 4.1 MCP Dashboard 页面

**位置**：`/mcp/dashboard`

**功能区域**：

1. **API Keys 管理**
   - 列表显示所有 API Keys
   - 创建新 Key 按钮
   - 删除/禁用 Key 操作

2. **待审批变更列表**
   - 实时更新（SignalR）
   - 过滤：ALL / PENDING / APPROVED / REJECTED
   - 排序：创建时间、状态

3. **变更详情对话框**
   - Diff Preview 可视化
   - 批准/拒绝按钮
   - 变更历史记录

**截图建议**：
- 截图1：MCP Dashboard 主界面（显示 3 个 API Keys，2 个待审批变更）
- 截图2：点击 "查看详情" 后的 Diff Preview 对话框
- 截图3：批准后的成功通知（右上角 Toast）

---

### 4.2 PendingChange 卡片设计

```
┌─────────────────────────────────────────────────────────────┐
│ 🤖 AI Assistant Demo                      ⏰ 2 分钟前       │
├─────────────────────────────────────────────────────────────┤
│ 操作: CREATE_EPIC                           状态: ⏳ 待审批  │
│                                                               │
│ 📝 标题: 用户认证系统                                        │
│ 📋 描述: 实现用户注册、登录、JWT 认证和 OAuth 集成功能      │
│ 📁 项目: ColaFlow Demo (DEMO)                                │
│                                                               │
│ ┌─────────────────────────────────────────┐                 │
│ │ Diff Preview:                            │                 │
│ │ + Epic: 用户认证系统                    │                 │
│ │ + 项目: ColaFlow Demo (DEMO)            │                 │
│ │ + 状态: TODO                             │                 │
│ └─────────────────────────────────────────┘                 │
│                                                               │
│ [🔍 查看详情]  [✅ 批准]  [❌ 拒绝]                          │
└─────────────────────────────────────────────────────────────┘
```

---

### 4.3 实时通知设计

**Toast 通知（右上角）**：

**新变更通知**：
```
┌─────────────────────────────────────┐
│ 🤖 AI 提议新变更                    │
│ CREATE_EPIC: 用户认证系统           │
│ [查看] [批准] [关闭]                │
└─────────────────────────────────────┘
```

**批准成功通知**：
```
┌─────────────────────────────────────┐
│ ✅ 变更已执行                       │
│ Epic "用户认证系统" 已创建          │
│ [查看 Epic] [关闭]                  │
└─────────────────────────────────────┘
```

---

## 5. 高级演示场景

### 5.1 批量操作：AI 创建多个 Story

**场景描述**：
AI 读取 Epic "用户认证系统" 后，提议创建 3 个 Story。

**AI 调用**：
```bash
# Story 1: 用户注册
curl -X POST http://localhost:5000/mcp \
  -H "Authorization: Bearer mcp_live_1234567890abcdef" \
  -d '{
    "jsonrpc": "2.0",
    "method": "tools/call",
    "params": {
      "name": "create_issue",
      "arguments": {
        "type": "STORY",
        "title": "用户注册功能",
        "description": "实现邮箱注册、密码强度验证、邮箱验证",
        "epic_id": "epic-uuid"
      }
    },
    "id": 10
  }'

# Story 2: 用户登录
curl -X POST http://localhost:5000/mcp \
  -H "Authorization: Bearer mcp_live_1234567890abcdef" \
  -d '{
    "jsonrpc": "2.0",
    "method": "tools/call",
    "params": {
      "name": "create_issue",
      "arguments": {
        "type": "STORY",
        "title": "用户登录功能",
        "description": "实现 JWT Token 登录、Remember Me、多端登录",
        "epic_id": "epic-uuid"
      }
    },
    "id": 11
  }'

# Story 3: OAuth 集成
curl -X POST http://localhost:5000/mcp \
  -H "Authorization: Bearer mcp_live_1234567890abcdef" \
  -d '{
    "jsonrpc": "2.0",
    "method": "tools/call",
    "params": {
      "name": "create_issue",
      "arguments": {
        "type": "STORY",
        "title": "OAuth 第三方登录",
        "description": "集成 GitHub、Google、Microsoft OAuth 登录",
        "epic_id": "epic-uuid"
      }
    },
    "id": 12
  }'
```

**演示要点**：
- 前端同时收到 3 个 PendingChange 通知
- 人类可以选择性批准（例如：批准 Story 1 和 2，拒绝 Story 3）
- 展示批量审批功能（勾选多个 → 批量批准）

---

### 5.2 UPDATE 操作：AI 更新 Epic 状态

**场景描述**：
AI 检测到 Epic 下所有 Story 已完成，提议将 Epic 状态更新为 DONE。

**AI 调用**：
```bash
curl -X POST http://localhost:5000/mcp \
  -H "Authorization: Bearer mcp_live_1234567890abcdef" \
  -d '{
    "jsonrpc": "2.0",
    "method": "tools/call",
    "params": {
      "name": "update_issue",
      "arguments": {
        "issue_id": "epic-uuid",
        "status": "DONE"
      }
    },
    "id": 20
  }'
```

**Diff Preview**：
```json
{
  "operation": "UPDATE_EPIC",
  "before": {
    "id": "epic-uuid",
    "key": "DEMO-1",
    "title": "用户认证系统",
    "status": "IN_PROGRESS",
    "completedStories": 3,
    "totalStories": 3
  },
  "after": {
    "id": "epic-uuid",
    "key": "DEMO-1",
    "title": "用户认证系统",
    "status": "DONE",
    "completedStories": 3,
    "totalStories": 3
  },
  "changes": [
    "~ 状态: IN_PROGRESS → DONE"
  ]
}
```

---

### 5.3 DELETE 操作：AI 删除重复 Task

**场景描述**：
AI 检测到有重复的 Task，提议删除。

**AI 调用**：
```bash
curl -X POST http://localhost:5000/mcp \
  -H "Authorization: Bearer mcp_live_1234567890abcdef" \
  -d '{
    "jsonrpc": "2.0",
    "method": "tools/call",
    "params": {
      "name": "delete_issue",
      "arguments": {
        "issue_id": "task-uuid"
      }
    },
    "id": 30
  }'
```

**Diff Preview**：
```json
{
  "operation": "DELETE_TASK",
  "before": {
    "id": "task-uuid",
    "key": "DEMO-1-1",
    "title": "设计数据库 Schema",
    "status": "TODO",
    "story": "用户注册功能"
  },
  "after": null,
  "changes": [
    "- Task: 设计数据库 Schema (DEMO-1-1)",
    "- 从 Story: 用户注册功能 中删除"
  ]
}
```

**安全考虑**：
- DELETE 操作应该有更严格的审批流程
- 可以设置规则：某些类型的变更需要多人审批
- 可以设置时间窗口：DELETE 操作需要等待 24 小时后才能执行

---

## 6. 监控和审计

### 6.1 Audit Log

所有 MCP 操作都应记录在 `AuditLogs` 表中。

**查询示例**：
```bash
curl -X GET "http://localhost:5000/api/audit-logs?entityType=PendingChange&page=1&pageSize=20" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

**响应示例**：
```json
{
  "items": [
    {
      "id": "log-uuid-1",
      "entityType": "PendingChange",
      "entityId": "pending-change-uuid",
      "action": "CREATED",
      "performedBy": "AI Assistant Demo (MCP Key)",
      "performedAt": "2025-11-09T10:30:25Z",
      "metadata": {
        "operation": "CREATE_EPIC",
        "title": "用户认证系统"
      }
    },
    {
      "id": "log-uuid-2",
      "entityType": "PendingChange",
      "entityId": "pending-change-uuid",
      "action": "APPROVED",
      "performedBy": "demo_user",
      "performedAt": "2025-11-09T10:35:00Z",
      "metadata": {
        "approver_id": "user-uuid"
      }
    },
    {
      "id": "log-uuid-3",
      "entityType": "Epic",
      "entityId": "epic-uuid",
      "action": "CREATED",
      "performedBy": "System (via PendingChange)",
      "performedAt": "2025-11-09T10:35:00Z",
      "metadata": {
        "pending_change_id": "pending-change-uuid",
        "key": "DEMO-1",
        "title": "用户认证系统"
      }
    }
  ],
  "total": 3
}
```

---

### 6.2 MCP Analytics

**Dashboard 指标**：
- 总 API 调用次数
- PendingChange 批准率
- 平均审批时长
- AI 提议的准确率（被批准的比例）

**查询示例**：
```bash
curl -X GET "http://localhost:5000/api/mcp/analytics?startDate=2025-11-01&endDate=2025-11-30" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

**响应示例**：
```json
{
  "totalApiCalls": 1523,
  "totalPendingChanges": 87,
  "approvedChanges": 72,
  "rejectedChanges": 10,
  "pendingChanges": 5,
  "approvalRate": 0.828,
  "averageApprovalTime": "00:05:32",
  "topOperations": [
    {"operation": "CREATE_TASK", "count": 45},
    {"operation": "UPDATE_TASK", "count": 20},
    {"operation": "CREATE_STORY", "count": 12}
  ]
}
```

---

## 7. 常见问题排查

### 7.1 SignalR 连接失败

**问题**：前端无法连接到 SignalR Hub

**检查**：
```bash
# 1. 检查后端 SignalR 配置
# Program.cs 中应该有：
builder.Services.AddSignalR();
app.MapHub<McpHub>("/hubs/mcp");

# 2. 检查 CORS 配置
# 确保允许 SignalR 所需的 Headers
app.UseCors(policy => policy
    .WithOrigins("http://localhost:3000")
    .AllowAnyHeader()
    .AllowAnyMethod()
    .AllowCredentials()); // SignalR 需要

# 3. 测试连接
# 浏览器控制台应该看到：
# SignalR: Connection started
```

---

### 7.2 MCP API Key 认证失败

**问题**：AI 调用 MCP 接口返回 401 Unauthorized

**检查**：
```bash
# 1. 验证 Key 格式
# 正确格式: mcp_live_xxxxxxxxxxxx
# 错误格式: xxxxxxxxxxxx (缺少前缀)

# 2. 验证 Key 是否过期
curl -X GET http://localhost:5000/api/mcp/keys \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
# 检查 expiresAt 字段

# 3. 验证 Authorization Header
# 正确: Authorization: Bearer mcp_live_xxxxxxxxxxxx
# 错误: Authorization: mcp_live_xxxxxxxxxxxx (缺少 Bearer)
```

---

### 7.3 PendingChange 执行失败

**问题**：批准 PendingChange 后返回 500 错误

**检查**：
```bash
# 1. 查看后端日志
# 应该有详细的错误堆栈

# 2. 检查数据完整性
# 例如：Epic 关联的 Project 是否存在
SELECT * FROM Projects WHERE Id = 'project-uuid';

# 3. 检查业务逻辑验证
# 例如：Story 必须关联到 Epic
# Task 必须关联到 Story
```

---

## 8. 总结

本 Demo 展示了 ColaFlow 的核心创新：**AI + Human 协作**的项目管理模式。

**关键价值**：
1. **安全可控**：Human-in-the-Loop 确保 AI 不会失控
2. **透明可信**：Diff Preview 让人类清晰了解 AI 的提议
3. **高效协作**：实时通知让人类快速响应 AI 的请求
4. **可审计性**：完整的操作日志确保合规性

**下一步**：
- 集成 Claude/ChatGPT MCP 客户端
- 实现更复杂的 Prompt 工程（智能拆解需求）
- 支持批量审批和审批规则引擎
- 实现 AI 自主学习（根据历史审批记录优化提议）

---

**演示清单**：
- [ ] 环境准备（后端、前端、数据库）
- [ ] 创建测试用户和项目
- [ ] 创建 MCP API Key
- [ ] AI 读取项目数据
- [ ] AI 提议创建 Epic
- [ ] 前端收到 SignalR 通知
- [ ] 人类查看 Diff Preview
- [ ] 人类批准变更
- [ ] 验证 Epic 已创建
- [ ] 查看 Audit Log

**预计演示时长**：15-20 分钟
