Files
ColaFlow/docs/architecture/mcp-server-architecture.md
Yaojia Wang b11c6447b5
Some checks failed
Code Coverage / Generate Coverage Report (push) Has been cancelled
Tests / Run Tests (9.0.x) (push) Has been cancelled
Tests / Docker Build Test (push) Has been cancelled
Tests / Test Summary (push) Has been cancelled
Sync
2025-11-08 18:13:48 +01:00

50 KiB
Raw Blame History

MCP Server 基础架构说明文档

文档版本: 1.0 创建日期: 2025-11-06 目标阶段: M2 (2025-12-01 至 2026-03-31) 受众: 产品经理、后端工程师、架构师


目录

  1. MCP Server 概述
  2. 整体架构设计
  3. 暴露的 Resources资源
  4. 暴露的 Tools工具
  5. 安全性设计
  6. 技术实现方案
  7. 实现路线图

1. MCP Server 概述

1.1 MCP 协议简介

MCP (Model Context Protocol) 是由 Anthropic 提出的一种标准化协议,用于连接 AI 模型与外部数据源和工具。MCP 协议定义了三种核心能力:

  • Resources资源: 只读数据暴露,让 AI 读取应用数据
  • Tools工具: 可执行操作,让 AI 调用功能接口
  • Prompts提示词: 预设的提示词模板,提升 AI 交互质量

MCP 的核心价值:

  • 标准化:统一的协议规范,任何 AI 工具都能接入
  • 安全性:细粒度的权限控制和审批机制
  • 可扩展:模块化设计,易于添加新功能
  • 开放生态:促进 AI 工具和应用之间的互操作性

1.2 ColaFlow MCP Server 的定位

ColaFlow MCP Server 是连接 AI 工具和 ColaFlow 项目管理系统的桥梁,它的核心定位是:

让 AI 成为真正的团队成员

  • AI 能够读取项目数据Projects, Epics, Stories, Tasks, Sprints
  • AI 能够执行项目操作(创建任务、更新状态、分配人员)
  • AI 的所有写操作都需要人工审批Diff Preview 机制)
  • 所有 AI 操作都有完整的审计追踪

1.3 与 AI Agent 的交互方式

┌─────────────────────────────────────────────────────────────┐
│                      AI Agent Workflow                       │
└─────────────────────────────────────────────────────────────┘

User Request → AI Agent (Claude/ChatGPT)
                    ↓
      1. Query Resources (只读操作)
         colaflow://projects.list
         colaflow://issues.search?status=InProgress
                    ↓
      2. Generate Response with Tool Calls
         "I found 5 open tasks. Would you like me to
          create a new Epic for the login feature?"
                    ↓
      3. User Confirms → AI Calls Tool
         create_epic(title="User Login Feature")
                    ↓
      4. MCP Server Generates Diff Preview
         {
           "operation": "CREATE",
           "entityType": "Epic",
           "afterData": { "title": "User Login Feature", ... }
         }
                    ↓
      5. Human Approval in ColaFlow Dashboard
         ✅ Approve → Execute operation
         ❌ Reject → Log rejection
                    ↓
      6. Return Result to AI
         "Epic created successfully. ID: epic-123"
                    ↓
      AI → User: "Done! The Epic has been created."

关键流程说明:

  1. 读操作Resources: 直接返回数据,无需审批
  2. 写操作Tools: 先生成 Diff Preview等待人工审批
  3. 审批后执行: 审批通过后自动执行实际操作
  4. 实时通知: 通过 SignalR WebSocket 实时通知用户

1.4 业务价值

对产品经理:

  • 减少 50% 手动创建任务的时间
  • AI 自动生成 PRD 和验收标准
  • 自动化的进度报告和风险检测

对开发团队:

  • 自然语言即可操作项目系统
  • 减少在 Jira 系统中的手动操作
  • AI 辅助任务估算和 Sprint 规划

对企业客户:

  • 完整的审批和审计机制(合规要求)
  • 支持私有化部署(数据安全)
  • 开放的 MCP 协议(避免供应商锁定)

2. 整体架构设计

2.1 架构分层

ColaFlow MCP Server 采用 Clean Architecture + CQRS + DDD 设计模式,与现有后端系统无缝集成。

┌───────────────────────────────────────────────────────────────┐
│                      Presentation Layer                        │
│  ┌─────────────────────────────────────────────────────────┐  │
│  │  MCP Protocol Handler (JSON-RPC 2.0 over stdio/SSE)     │  │
│  │  - McpResourceController                                 │  │
│  │  - McpToolController                                     │  │
│  │  - McpPromptController                                   │  │
│  └─────────────────────────────────────────────────────────┘  │
│  ┌─────────────────────────────────────────────────────────┐  │
│  │  REST API for MCP Management                             │  │
│  │  - /api/mcp/keys (API Key 管理)                          │  │
│  │  - /api/mcp/pending-changes (Diff Preview 审批)          │  │
│  │  - /api/mcp/audit-logs (审计日志查询)                     │  │
│  └─────────────────────────────────────────────────────────┘  │
└───────────────────────────────────────────────────────────────┘
                              ↓
┌───────────────────────────────────────────────────────────────┐
│                      Application Layer                         │
│  ┌─────────────────────────────────────────────────────────┐  │
│  │  MCP Services                                            │  │
│  │  - McpResourceService (读取项目数据)                      │  │
│  │  - McpToolService (执行工具操作)                          │  │
│  │  - McpPromptService (生成提示词)                          │  │
│  │  - DiffPreviewService (生成变更预览)                      │  │
│  │  - PendingChangeService (管理待审批变更)                  │  │
│  └─────────────────────────────────────────────────────────┘  │
│  ┌─────────────────────────────────────────────────────────┐  │
│  │  CQRS Command/Query Handlers                             │  │
│  │  - CreateApiKeyCommandHandler                            │  │
│  │  - ApprovePendingChangeCommandHandler                    │  │
│  │  - GetPendingChangesQueryHandler                         │  │
│  └─────────────────────────────────────────────────────────┘  │
└───────────────────────────────────────────────────────────────┘
                              ↓
┌───────────────────────────────────────────────────────────────┐
│                       Domain Layer                             │
│  ┌─────────────────────────────────────────────────────────┐  │
│  │  MCP Aggregates                                          │  │
│  │  - McpApiKey (API 密钥聚合根)                            │  │
│  │  - PendingChange (待审批变更聚合根)                       │  │
│  │  - DiffPreview (变更预览值对象)                          │  │
│  └─────────────────────────────────────────────────────────┘  │
│  ┌─────────────────────────────────────────────────────────┐  │
│  │  Domain Events                                           │  │
│  │  - ApiKeyCreatedEvent                                    │  │
│  │  - PendingChangeCreatedEvent                             │  │
│  │  - PendingChangeApprovedEvent                            │  │
│  │  - PendingChangeRejectedEvent                            │  │
│  └─────────────────────────────────────────────────────────┘  │
└───────────────────────────────────────────────────────────────┘
                              ↓
┌───────────────────────────────────────────────────────────────┐
│                    Infrastructure Layer                        │
│  ┌─────────────────────────────────────────────────────────┐  │
│  │  Data Access                                             │  │
│  │  - McpApiKeyRepository (EF Core)                         │  │
│  │  - PendingChangeRepository (EF Core)                     │  │
│  │  - Redis Cache (热数据缓存)                              │  │
│  └─────────────────────────────────────────────────────────┘  │
│  ┌─────────────────────────────────────────────────────────┐  │
│  │  External Services                                       │  │
│  │  - SignalR Hub (实时通知)                                │  │
│  │  - AuditLogService (审计日志)                            │  │
│  │  - ProjectService (现有项目模块)                          │  │
│  │  - IssueService (现有任务模块)                            │  │
│  └─────────────────────────────────────────────────────────┘  │
└───────────────────────────────────────────────────────────────┘

架构分层职责:

  1. Presentation Layer展示层

    • 处理 MCP 协议通信JSON-RPC 2.0
    • 处理 REST API 请求
    • 认证和授权验证
    • 输入验证和错误处理
  2. Application Layer应用层

    • 业务流程编排
    • CQRS 命令和查询处理
    • 领域事件分发
    • 跨聚合根协调
  3. Domain Layer领域层

    • 核心业务逻辑
    • 聚合根和值对象
    • 领域事件定义
    • 业务规则验证
  4. Infrastructure Layer基础设施层

    • 数据持久化PostgreSQL + EF Core
    • 缓存Redis
    • 外部服务集成
    • 技术实现细节

2.2 核心组件及职责

2.2.1 MCP Protocol Handler

职责: 处理 MCP 协议的请求和响应

核心功能:

  • 解析 MCP 协议消息JSON-RPC 2.0 格式)
  • 路由请求到对应的 Resource/Tool/Prompt 处理器
  • 格式化响应数据符合 MCP 规范
  • 错误处理和异常转换

关键接口:

public interface IMcpProtocolHandler
{
    Task<McpResponse> HandleRequestAsync(
        McpRequest request,
        CancellationToken cancellationToken);
}

2.2.2 McpResourceService

职责: 暴露只读数据资源

核心功能:

  • 注册和管理所有 MCP Resources
  • 查询项目数据Projects, Issues, Sprints, Users
  • 应用租户隔离和权限过滤
  • 数据格式转换和优化

Resource 注册机制:

public interface IMcpResource
{
    string Uri { get; }
    string Name { get; }
    string Description { get; }
    string MimeType { get; }

    Task<McpResourceContent> GetContentAsync(
        McpResourceRequest request,
        CancellationToken cancellationToken);
}

2.2.3 McpToolService

职责: 执行写操作工具

核心功能:

  • 注册和管理所有 MCP Tools
  • 执行工具操作CREATE/UPDATE/DELETE
  • 生成 Diff Preview
  • 与 PendingChangeService 协同处理审批流程

Tool 执行流程:

public interface IMcpTool
{
    string Name { get; }
    string Description { get; }
    McpToolInputSchema InputSchema { get; }

    Task<McpToolResult> ExecuteAsync(
        McpToolCall toolCall,
        CancellationToken cancellationToken);
}

2.2.4 DiffPreviewService

职责: 生成变更预览

核心功能:

  • 生成 before/after 数据快照
  • 计算数据差异JSON diff
  • 格式化 diff 输出(人类可读)
  • 验证变更的安全性

Diff 数据结构:

public class DiffPreview
{
    public string ToolName { get; set; }
    public string Operation { get; set; } // CREATE, UPDATE, DELETE
    public string EntityType { get; set; }
    public Guid? EntityId { get; set; }
    public object? BeforeData { get; set; }
    public object? AfterData { get; set; }
    public DiffField[] ChangedFields { get; set; }
    public bool RequiresApproval { get; set; }
    public DateTime CreatedAt { get; set; }
}

public class DiffField
{
    public string FieldName { get; set; }
    public object? OldValue { get; set; }
    public object? NewValue { get; set; }
}

2.2.5 PendingChangeService

职责: 管理待审批的变更

核心功能:

  • 创建待审批变更记录
  • 存储 Diff Preview 数据
  • 处理审批/拒绝操作
  • 24小时自动过期机制
  • 发送实时通知

状态流转:

PendingApproval → Approved → Executed
                ↘ Rejected
                ↘ Expired (24h)
                ↘ Cancelled

2.2.6 McpApiKeyService

职责: 管理 MCP API 密钥

核心功能:

  • 生成 API KeySHA-256 哈希存储)
  • 验证 API Key
  • 权限范围控制(只读/读写)
  • IP 白名单验证
  • 使用统计和速率限制

2.3 与现有后端 API 的集成方式

MCP Server 不是独立的服务,而是 ColaFlow 后端系统的一个模块。集成方式:

方式 1: 直接调用现有服务

// MCP Tool 内部调用现有的 CQRS Command
public class CreateIssueTool : IMcpTool
{
    private readonly IMediator _mediator;

    public async Task<McpToolResult> ExecuteAsync(...)
    {
        // 调用现有的 CreateIssueCommand
        var result = await _mediator.Send(new CreateIssueCommand
        {
            ProjectId = input.ProjectId,
            Title = input.Title,
            Type = input.Type
        });

        return new McpToolResult { ... };
    }
}

方式 2: 共享数据仓储

// MCP Resource 直接查询现有数据
public class ProjectsListResource : IMcpResource
{
    private readonly IProjectRepository _projectRepo;

    public async Task<McpResourceContent> GetContentAsync(...)
    {
        // 复用现有的 Repository
        var projects = await _projectRepo.GetAllAsync(tenantId);

        return new McpResourceContent { ... };
    }
}

方式 3: 领域事件订阅

// 监听现有的领域事件
public class IssueCreatedEventHandler : INotificationHandler<IssueCreatedEvent>
{
    public async Task Handle(IssueCreatedEvent e, ...)
    {
        // 如果是 MCP 操作触发的,发送通知
        if (e.TriggeredByMcp)
        {
            await _realtimeService.NotifyUserAsync(...);
        }
    }
}

2.4 数据流向

2.4.1 读操作数据流Resource

AI Agent → MCP Protocol Handler → McpResourceService
                                        ↓
                                  [权限验证]
                                        ↓
                            ProjectRepository / IssueRepository
                                        ↓
                                 [租户过滤]
                                        ↓
                                 PostgreSQL Query
                                        ↓
                                [Redis Cache (可选)]
                                        ↓
                            格式化为 MCP Resource Content
                                        ↓
                              返回给 AI Agent

性能优化:

  • Redis 缓存热数据TTL 5分钟
  • 分页查询(默认 limit=50
  • 只返回必要字段(精简 JSON

2.4.2 写操作数据流Tool

AI Agent → MCP Protocol Handler → McpToolService
                                        ↓
                                  [API Key 验证]
                                        ↓
                            DiffPreviewService 生成预览
                                        ↓
                         PendingChangeService 创建待审批记录
                                        ↓
                              存储到 PostgreSQL
                                        ↓
                          SignalR 通知用户(实时推送)
                                        ↓
                          返回 Diff Preview 给 AI Agent

                                        ↓
                        [用户在 Dashboard 审批]
                                        ↓
                          ✅ Approve → 执行实际操作
                          ❌ Reject → 记录日志
                                        ↓
                          通知 AI Agent 最终结果

3. 暴露的 Resources资源

3.1 Resource 概述

Resources 是只读的数据接口,让 AI 能够查询 ColaFlow 的项目数据。所有 Resources 都遵循租户隔离原则。

3.2 Resource URI 设计规范

URI 格式: colaflow://[entity].[action]?[params]

命名规则:

  • 使用小写字母和点号分隔
  • 动作使用标准 CRUD 动词list, get, search
  • 支持 query 参数传递过滤条件

示例:

colaflow://projects.list
colaflow://projects.get/abc123
colaflow://issues.search?status=InProgress&assignee=user123
colaflow://sprints.current

3.3 核心 Resources 列表

3.3.1 Projects Resources

1. colaflow://projects.list

获取当前租户的所有项目列表

返回数据结构:

{
  "projects": [
    {
      "id": "uuid",
      "name": "ColaFlow Development",
      "key": "COLA",
      "description": "Main development project",
      "status": "Active",
      "owner": {
        "id": "uuid",
        "name": "John Doe"
      },
      "issueCount": 145,
      "memberCount": 8,
      "createdAt": "2024-01-01T00:00:00Z"
    }
  ]
}

2. colaflow://projects.get/{id}

获取单个项目的详细信息

返回数据结构:

{
  "project": {
    "id": "uuid",
    "name": "ColaFlow Development",
    "key": "COLA",
    "description": "...",
    "status": "Active",
    "owner": { "id": "uuid", "name": "John Doe" },
    "statistics": {
      "totalIssues": 145,
      "openIssues": 32,
      "inProgressIssues": 15,
      "completedIssues": 98
    },
    "recentActivity": [
      {
        "type": "IssueCreated",
        "user": "Jane Smith",
        "timestamp": "2024-11-05T10:30:00Z",
        "description": "Created task COLA-146"
      }
    ]
  }
}

3.3.2 Issues Resources

3. colaflow://issues.search

搜索任务(支持高级过滤)

支持的查询参数:

  • projectId: 项目 ID
  • type: Epic / Story / Task / Bug
  • status: Backlog / Todo / InProgress / Review / Done
  • priority: Low / Medium / High / Critical
  • assignee: 用户 ID
  • sprint: Sprint ID
  • q: 关键词搜索(标题和描述)
  • limit: 返回数量(默认 50
  • offset: 分页偏移量

返回数据结构:

{
  "issues": [
    {
      "id": "uuid",
      "key": "COLA-146",
      "title": "Implement MCP Server",
      "type": "Epic",
      "status": "InProgress",
      "priority": "High",
      "assignee": {
        "id": "uuid",
        "name": "John Doe"
      },
      "project": {
        "id": "uuid",
        "name": "ColaFlow Development"
      },
      "sprint": {
        "id": "uuid",
        "name": "Sprint 5"
      },
      "estimatedHours": 80,
      "actualHours": 35,
      "createdAt": "2024-11-01T00:00:00Z",
      "updatedAt": "2024-11-05T14:30:00Z"
    }
  ],
  "total": 145,
  "limit": 50,
  "offset": 0
}

4. colaflow://issues.get/{id}

获取单个任务的详细信息(包括评论、附件、历史)

返回数据结构:

{
  "issue": {
    "id": "uuid",
    "key": "COLA-146",
    "title": "Implement MCP Server",
    "description": "Complete implementation of MCP protocol...",
    "type": "Epic",
    "status": "InProgress",
    "priority": "High",
    "assignee": { ... },
    "reporter": { ... },
    "project": { ... },
    "sprint": { ... },
    "parent": {
      "id": "uuid",
      "key": "COLA-100",
      "title": "M2 Phase"
    },
    "children": [
      {
        "id": "uuid",
        "key": "COLA-147",
        "title": "Implement Resources"
      }
    ],
    "acceptanceCriteria": [
      "All 11 resources implemented",
      "Performance < 200ms"
    ],
    "comments": [
      {
        "id": "uuid",
        "author": "Jane Smith",
        "text": "Started implementation today",
        "createdAt": "2024-11-05T09:00:00Z"
      }
    ],
    "activityHistory": [ ... ]
  }
}

5. colaflow://epics.list

列出所有 Epic

6. colaflow://stories.list

列出所有 Story

7. colaflow://tasks.list

列出所有 Task

: 这三个 Resources 本质上是 issues.search 的快捷方式,预设了 type 过滤条件。

3.3.3 Sprints Resources

8. colaflow://sprints.current

获取当前活跃的 Sprint

返回数据结构:

{
  "sprint": {
    "id": "uuid",
    "name": "Sprint 5",
    "goal": "Complete MCP Server implementation",
    "status": "Active",
    "startDate": "2024-11-01T00:00:00Z",
    "endDate": "2024-11-14T23:59:59Z",
    "progress": {
      "totalIssues": 12,
      "completedIssues": 5,
      "remainingIssues": 7,
      "totalStoryPoints": 34,
      "completedStoryPoints": 13
    },
    "burndown": [
      { "date": "2024-11-01", "remaining": 34 },
      { "date": "2024-11-02", "remaining": 32 },
      { "date": "2024-11-05", "remaining": 21 }
    ]
  }
}

9. colaflow://sprints.backlog

获取 Backlog 中的任务

3.3.4 Users Resources

10. colaflow://users.list

列出当前租户的所有团队成员

返回数据结构:

{
  "users": [
    {
      "id": "uuid",
      "email": "john@example.com",
      "fullName": "John Doe",
      "role": "Admin",
      "status": "Active",
      "avatar": "https://...",
      "statistics": {
        "assignedIssues": 8,
        "completedIssues": 42
      }
    }
  ]
}

3.3.5 Reports Resources

11. colaflow://reports.burndown/{sprintId}

获取指定 Sprint 的燃尽图数据

3.4 资源的组织结构

Resources 按照业务领域组织:

colaflow://
├── projects.*        # 项目相关
│   ├── list
│   └── get/{id}
├── issues.*          # 任务相关
│   ├── search
│   ├── get/{id}
│   ├── (epics.list)
│   ├── (stories.list)
│   └── (tasks.list)
├── sprints.*         # Sprint 相关
│   ├── current
│   └── backlog
├── users.*           # 用户相关
│   └── list
└── reports.*         # 报告相关
    └── burndown/{id}

3.5 权限控制机制

租户隔离:

  • 所有 Resources 自动应用 TenantId 过滤
  • 通过 EF Core Global Query Filter 实现
  • 用户只能访问自己租户的数据

角色权限:

  • Owner/Admin: 所有 Resources 可访问
  • Member: 只能访问自己参与的项目
  • Viewer: 只读访问,不能修改
  • Guest: 受限的只读访问

API Key 权限:

  • 创建 API Key 时指定 Resource 白名单
  • 例如:只允许读取 projects.*issues.search
  • 超出权限范围返回 403 Forbidden

敏感数据过滤:

  • 不返回密码哈希、API Key 等敏感字段
  • 不返回其他租户的数据
  • 审计日志中的敏感操作需要额外权限

4. 暴露的 Tools工具

4.1 Tool 概述

Tools 是可执行的操作接口,让 AI 能够修改 ColaFlow 的数据。所有写操作都需要通过 Diff Preview 和人工审批。

4.2 Tool 分类

4.2.1 读取类工具

虽然 Resources 已经提供了读取能力,但某些复杂查询需要专用工具:

1. search_issues (高级搜索)

支持复杂的 JQLJira Query Language风格查询

输入参数:

{
  "query": "project = COLA AND status = InProgress AND assignee = currentUser()",
  "orderBy": "priority DESC, createdAt ASC",
  "limit": 50
}

4.2.2 写入类工具(需审批)

2. create_project

创建新项目

输入参数:

{
  "name": "New Product Feature",
  "key": "NPF",
  "description": "A new product feature for Q1 2025",
  "ownerId": "uuid"
}

Diff Preview 示例:

{
  "operation": "CREATE",
  "entityType": "Project",
  "afterData": {
    "name": "New Product Feature",
    "key": "NPF",
    "status": "Active",
    "owner": "John Doe",
    "createdAt": "2024-11-06T10:00:00Z"
  },
  "requiresApproval": true
}

3. create_issue

创建新任务

输入参数:

{
  "projectId": "uuid",
  "title": "Implement user login",
  "description": "Add JWT-based authentication",
  "type": "Story",
  "priority": "High",
  "assigneeId": "uuid",
  "estimatedHours": 16,
  "acceptanceCriteria": [
    "User can login with email/password",
    "JWT token is returned"
  ]
}

4. update_issue

更新任务详情

输入参数:

{
  "issueId": "uuid",
  "title": "Implement user login (updated)",
  "description": "Add JWT + OAuth authentication",
  "priority": "Critical",
  "estimatedHours": 24
}

Diff Preview 示例:

{
  "operation": "UPDATE",
  "entityType": "Issue",
  "entityId": "uuid",
  "changedFields": [
    {
      "fieldName": "description",
      "oldValue": "Add JWT-based authentication",
      "newValue": "Add JWT + OAuth authentication"
    },
    {
      "fieldName": "priority",
      "oldValue": "High",
      "newValue": "Critical"
    },
    {
      "fieldName": "estimatedHours",
      "oldValue": 16,
      "newValue": 24
    }
  ],
  "requiresApproval": true
}

5. update_status

更改任务状态

输入参数:

{
  "issueId": "uuid",
  "status": "InProgress",
  "comment": "Started working on this task"
}

审批策略:

  • 可配置:某些状态流转可以无需审批(如 Todo → InProgress
  • 关键状态变更需要审批(如 InProgress → Done

6. assign_issue

分配任务给用户

输入参数:

{
  "issueId": "uuid",
  "assigneeId": "uuid"
}

7. create_sprint

创建新 Sprint

输入参数:

{
  "projectId": "uuid",
  "name": "Sprint 6",
  "goal": "Complete authentication module",
  "startDate": "2024-11-15",
  "endDate": "2024-11-28",
  "capacity": 80
}

8. start_sprint

启动 Sprint

输入参数:

{
  "sprintId": "uuid",
  "issueIds": ["uuid1", "uuid2", "uuid3"]
}

9. add_comment

添加评论

输入参数:

{
  "issueId": "uuid",
  "text": "This task is blocked by COLA-123"
}

审批策略:

  • 评论通常不需要审批(可配置)
  • 如果包含敏感信息可以启用审批

10. create_epic

创建 Epic

输入参数:

{
  "projectId": "uuid",
  "title": "User Authentication System",
  "description": "Complete authentication module with JWT and OAuth",
  "priority": "High"
}

11. link_issues

关联任务(父子关系)

输入参数:

{
  "parentId": "uuid",
  "childId": "uuid",
  "linkType": "Parent-Child"
}

4.2.3 分析类工具

12. analyze_burndown

分析燃尽图趋势

输入参数:

{
  "sprintId": "uuid"
}

输出:

{
  "sprint": "Sprint 5",
  "status": "OnTrack",
  "summary": "The team is on track to complete 34 story points by 2024-11-14.",
  "insights": [
    "Daily completion rate: 2.5 points/day",
    "Predicted completion: 2024-11-13 (1 day early)",
    "Risk: 2 high-priority tasks still in Todo"
  ]
}

4.3 Diff Preview 机制的设计思路

核心理念: "预览 → 审批 → 执行" 三步走

为什么需要 Diff Preview:

  1. 安全性: 防止 AI 误操作(如删除重要数据)
  2. 透明性: 用户清楚知道 AI 将要做什么
  3. 合规性: 满足企业审计要求
  4. 可回滚: 审批拒绝后不会执行操作

Diff Preview 的生成流程:

Tool 调用 → 收集当前数据 (Before)
              ↓
          模拟执行操作
              ↓
          生成变更后数据 (After)
              ↓
          计算字段差异 (Changed Fields)
              ↓
          格式化为人类可读的 Diff
              ↓
          存储为 PendingChange 记录
              ↓
          返回 Diff Preview 给 AI

Diff 格式设计:

{
  "pendingChangeId": "uuid",
  "toolName": "update_issue",
  "operation": "UPDATE",
  "entityType": "Issue",
  "entityId": "uuid",
  "entityKey": "COLA-146",
  "summary": "Update issue title, description, and priority",
  "beforeData": {
    "title": "Implement MCP Server",
    "description": "Complete implementation...",
    "priority": "High"
  },
  "afterData": {
    "title": "Implement MCP Server (updated)",
    "description": "Complete implementation with Diff Preview...",
    "priority": "Critical"
  },
  "changedFields": [
    {
      "fieldName": "title",
      "displayName": "Title",
      "oldValue": "Implement MCP Server",
      "newValue": "Implement MCP Server (updated)",
      "diffHtml": "<del>Implement MCP Server</del> <ins>Implement MCP Server (updated)</ins>"
    },
    {
      "fieldName": "priority",
      "displayName": "Priority",
      "oldValue": "High",
      "newValue": "Critical",
      "diffHtml": "<span class='old'>High</span> → <span class='new'>Critical</span>"
    }
  ],
  "requiresApproval": true,
  "createdAt": "2024-11-06T10:30:00Z",
  "expiresAt": "2024-11-07T10:30:00Z",
  "createdBy": {
    "id": "uuid",
    "name": "AI Assistant (via John Doe)"
  }
}

审批界面展示:

前端 Dashboard 会显示:

  • 操作摘要: "Update issue COLA-146: title, description, priority"
  • 变更对比: 左侧显示旧值,右侧显示新值,高亮差异
  • 影响范围: 影响的实体数量、关联任务等
  • 审批按钮: Approve / Reject / ⏸️ Later

自动过期机制:

  • PendingChange 创建后 24 小时未审批自动过期
  • 后台定时任务(每小时执行一次)清理过期记录
  • 过期后 AI 会收到通知:"Change request expired"

5. 安全性设计

5.1 认证机制JWT Token + API Key

MCP Server 支持两种认证方式:

5.1.1 JWT Token 认证

适用场景: Web 前端通过浏览器访问 MCP Server

流程:

User → Login API → JWT Token
                      ↓
User → MCP Request (携带 JWT)
                      ↓
       MCP Server 验证 JWT → 提取 TenantId、UserId
                      ↓
                执行操作(应用租户隔离)

JWT Claims:

{
  "sub": "user-uuid",
  "tenant_id": "tenant-uuid",
  "tenant_slug": "acme",
  "email": "john@example.com",
  "role": "Admin",
  "exp": 1699200000
}

5.1.2 API Key 认证

适用场景: AI 工具Claude Desktop, ChatGPT通过 MCP 协议访问

API Key 格式:

colaflow_sk_live_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6

生成和存储:

  1. 用户在 Dashboard 创建 API Key
  2. 系统生成 40 字符随机字符串
  3. 使用 BCrypt 哈希后存储到数据库
  4. 前16字符作为 prefix 明文存储(用于识别)
  5. 完整 Key 只展示一次(创建时)

验证流程:

AI Tool → MCP Request (Header: Authorization: Bearer API_KEY)
                      ↓
       MCP Server 提取 API Key
                      ↓
       查询数据库(根据 key_prefix
                      ↓
       BCrypt 验证哈希
                      ↓
       验证 IP 白名单(可选)
                      ↓
       验证权限范围Resources/Tools 白名单)
                      ↓
       提取关联的 TenantId、UserId
                      ↓
       执行操作

数据库表结构:

CREATE TABLE mcp_api_keys (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
    user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    key_hash VARCHAR(64) NOT NULL UNIQUE,
    key_prefix VARCHAR(16) NOT NULL,
    name VARCHAR(255) NOT NULL,
    description TEXT,
    permissions JSONB NOT NULL,
    ip_whitelist JSONB,
    status INT NOT NULL DEFAULT 1,
    last_used_at TIMESTAMP NULL,
    usage_count BIGINT NOT NULL DEFAULT 0,
    created_at TIMESTAMP NOT NULL DEFAULT NOW(),
    expires_at TIMESTAMP NOT NULL,
    revoked_at TIMESTAMP NULL,

    INDEX idx_key_prefix (key_prefix),
    INDEX idx_tenant_user (tenant_id, user_id),
    INDEX idx_expires_at (expires_at)
);

5.2 授权和权限控制

5.2.1 租户隔离

实现方式: EF Core Global Query Filter

所有查询自动添加 WHERE tenant_id = current_tenant_id

modelBuilder.Entity<Issue>().HasQueryFilter(i =>
    i.TenantId == _tenantContext.CurrentTenantId);

防止跨租户访问:

  • 即使用户知道其他租户的资源 ID也无法访问
  • 需要显式使用 IgnoreQueryFilters() 才能跨租户查询(仅限系统管理员)

5.2.2 角色权限RBAC

基于现有的 RBAC 系统:

角色 Resources 权限 Tools 权限 特殊权限
Owner 所有 Resources 所有 Tools 创建 API Key
Admin 所有 Resources 所有 Tools 审批 Pending Changes
Member 参与的项目 有限 Tools 只能修改自己的任务
Viewer 参与的项目 只读
Guest 受限 Resources 临时访问

5.2.3 API Key 权限范围

创建 API Key 时,用户可以指定:

1. 资源白名单:

{
  "allowedResources": [
    "colaflow://projects.list",
    "colaflow://issues.search",
    "colaflow://issues.get/*"
  ]
}

2. 工具白名单:

{
  "allowedTools": [
    "create_issue",
    "update_status",
    "add_comment"
  ]
}

3. 只读模式:

{
  "readOnly": true
}

4. IP 白名单:

{
  "ipWhitelist": [
    "192.168.1.0/24",
    "10.0.0.1"
  ]
}

5.3 AI 的读写权限分级

Level 0: 只读 (Read-Only)

  • 允许: 所有 Resources
  • 禁止: 所有 Tools
  • 适用场景: AI 只用于查询和分析

Level 1: 有限写入 (Limited Write)

  • 允许: 所有 Resources + 部分 Tools
  • 需审批: 所有写操作
  • 允许的 Tools: create_issue, update_status, add_comment
  • 适用场景: 日常项目管理辅助

Level 2: 完全写入 (Full Write)

  • 允许: 所有 Resources + 所有 Tools
  • 需审批: 所有写操作(除非配置为自动审批)
  • 适用场景: 高级自动化

Level 3: 自动化 (Automation)

  • 允许: 所有 Resources + 所有 Tools
  • 部分操作自动审批(如状态更新、评论)
  • 关键操作仍需审批(如删除、权限变更)
  • 适用场景: 完全信任的自动化流程

配置示例:

{
  "apiKeyName": "Claude Assistant",
  "permissionLevel": "Limited Write",
  "readOnly": false,
  "autoApproveTools": ["add_comment", "update_status"],
  "requireApprovalTools": ["create_issue", "update_issue", "delete_issue"]
}

5.4 敏感数据保护

5.4.1 字段级过滤

某些字段不应该暴露给 AI

敏感字段列表:

  • password_hash
  • api_key_hash
  • jwt_refresh_token
  • email_verification_token
  • password_reset_token
  • sso_config.client_secret

实现方式:

使用 DTOData Transfer Object模式只返回安全字段

public class UserDto
{
    public Guid Id { get; set; }
    public string Email { get; set; }
    public string FullName { get; set; }
    public string Role { get; set; }
    // 不包含 PasswordHash, ApiKeys 等敏感字段
}

5.4.2 数据脱敏

对于某些敏感信息,返回脱敏后的数据:

  • Email: john****@example.com
  • Phone: 138****5678
  • IP: 192.168.***.***

5.5 审计日志

所有 MCP 操作都记录到审计日志:

日志内容:

{
  "tenantId": "uuid",
  "userId": "uuid",
  "action": "McpToolExecuted",
  "entityType": "Issue",
  "entityId": "uuid",
  "toolName": "update_issue",
  "beforeData": { ... },
  "afterData": { ... },
  "ipAddress": "192.168.1.100",
  "userAgent": "Claude Desktop MCP Client",
  "apiKeyId": "uuid",
  "pendingChangeId": "uuid",
  "approvedBy": "uuid",
  "timestamp": "2024-11-06T10:30:00Z"
}

审计查询:

  • 按用户查询(谁做了什么)
  • 按实体查询(某个任务的所有变更历史)
  • 按时间范围查询
  • 按操作类型查询CREATE/UPDATE/DELETE

审计日志保留策略:

  • 热数据30天: PostgreSQL
  • 温数据90天: PostgreSQL 表分区
  • 冷数据1年: 归档到 S3/Azure Blob
  • 合规数据7年: 冷存储 + 加密

6. 技术实现方案

6.1 MCP Server 技术栈选型

选型决策: 自定义 .NET 9 实现(不使用官方 Node.js SDK

理由:

  1. 原生集成: 与现有 ASP.NET Core 后端无缝集成
  2. 性能优势: .NET 9 性能优于 Node.js特别是并发场景
  3. 类型安全: C# 强类型系统减少运行时错误
  4. 无额外依赖: 不需要部署 Node.js 环境
  5. 团队技能: 团队已熟悉 .NET 生态

实现方式: 手动实现 MCP 协议规范JSON-RPC 2.0

6.2 与后端 ASP.NET Core API 的通信方式

方式 1: 直接调用现有服务(推荐)

MCP Server 作为后端系统的一个模块,直接调用现有的 Application Layer 服务:

// MCP Tool 内部调用 CQRS Command
public class CreateIssueTool : IMcpTool
{
    private readonly IMediator _mediator;

    public async Task<McpToolResult> ExecuteAsync(...)
    {
        var result = await _mediator.Send(new CreateIssueCommand
        {
            ProjectId = input.ProjectId,
            Title = input.Title,
            Type = input.Type
        });

        return new McpToolResult { ... };
    }
}

优点:

  • 零网络延迟
  • 共享事务上下文
  • 复用现有业务逻辑
  • 统一的异常处理

方式 2: HTTP API 调用(备选)

如果 MCP Server 部署为独立服务:

public class CreateIssueTool : IMcpTool
{
    private readonly HttpClient _httpClient;

    public async Task<McpToolResult> ExecuteAsync(...)
    {
        var response = await _httpClient.PostAsJsonAsync(
            "/api/issues",
            new { projectId, title, type });

        response.EnsureSuccessStatusCode();
        var issue = await response.Content.ReadFromJsonAsync<Issue>();

        return new McpToolResult { ... };
    }
}

优点:

  • 服务解耦
  • 独立扩展
  • 可单独部署

决策: M2 阶段采用方式 1直接调用M4 阶段考虑服务拆分时采用方式 2。

6.3 性能优化考虑

6.3.1 缓存策略

Redis 缓存层:

查询请求 → 检查 Redis 缓存
              ↓
          缓存命中 → 直接返回
              ↓
          缓存未命中 → 查询数据库
              ↓
          写入 Redis (TTL 5分钟)
              ↓
          返回结果

缓存的数据:

  • Projects List高频访问
  • Current Sprint高频访问
  • User List高频访问
  • Issue Details中频访问TTL 2分钟

缓存失效策略:

  • 数据更新时主动失效(通过领域事件)
  • TTL 自动过期5分钟
  • 手动刷新接口(管理员操作)

6.3.2 查询优化

数据库索引:

-- Issues 表优化
CREATE INDEX idx_issues_tenant_project ON issues(tenant_id, project_id);
CREATE INDEX idx_issues_tenant_status ON issues(tenant_id, status);
CREATE INDEX idx_issues_tenant_assignee ON issues(tenant_id, assignee_id);
CREATE INDEX idx_issues_tenant_sprint ON issues(tenant_id, sprint_id);
CREATE INDEX idx_issues_full_text ON issues USING gin(to_tsvector('english', title || ' ' || description));

-- PendingChanges 表优化
CREATE INDEX idx_pending_changes_tenant_status ON mcp_pending_changes(tenant_id, status);
CREATE INDEX idx_pending_changes_expires ON mcp_pending_changes(expires_at) WHERE status = 'PendingApproval';

分页查询:

  • 默认 limit=50
  • 最大 limit=100
  • 使用 offset-based 分页(简单场景)
  • 使用 cursor-based 分页(大数据集)

只查询必要字段:

var issues = await _context.Issues
    .Where(i => i.ProjectId == projectId)
    .Select(i => new IssueDto
    {
        Id = i.Id,
        Title = i.Title,
        Status = i.Status
        // 不加载 Description, Comments 等大字段
    })
    .ToListAsync();

6.3.3 并发控制

乐观并发控制:

使用 EF Core 的 RowVersion / Timestamp 字段:

public class Issue
{
    [Timestamp]
    public byte[] RowVersion { get; set; }
}

// 更新时检查版本
var issue = await _context.Issues.FindAsync(id);
issue.Title = newTitle;

try
{
    await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
    throw new ConcurrencyException("Issue has been modified by another user");
}

分布式锁:

使用 Redis 分布式锁防止并发冲突:

await using var lock = await _distributedLock.AcquireAsync($"issue:{issueId}", TimeSpan.FromSeconds(10));

if (lock == null)
{
    throw new ResourceLockedException("Issue is being modified by another operation");
}

// 执行更新操作

6.3.4 异步处理

后台任务:

某些耗时操作通过后台队列异步处理:

  • 审计日志写入(使用 Channel 队列)
  • 邮件通知发送(使用 Hangfire
  • 数据统计计算(使用 BackgroundService

SignalR 实时推送:

审批完成后通过 WebSocket 推送结果,无需 AI 轮询。

6.4 可扩展性设计

6.4.1 插件化架构

MCP Resources/Tools/Prompts 采用插件化设计,便于扩展:

public interface IMcpPlugin
{
    string Name { get; }
    string Version { get; }
    void Register(IMcpRegistry registry);
}

public class CustomPlugin : IMcpPlugin
{
    public string Name => "CustomIssueTools";
    public string Version => "1.0.0";

    public void Register(IMcpRegistry registry)
    {
        registry.RegisterResource(new CustomResource());
        registry.RegisterTool(new CustomTool());
        registry.RegisterPrompt(new CustomPrompt());
    }
}

插件加载方式:

  • 自动扫描程序集Reflection
  • 配置文件指定appsettings.json
  • 动态加载 DLL高级场景

6.4.2 多租户扩展

水平扩展:

  • MCP Server 无状态设计,可部署多个实例
  • 负载均衡Nginx / Azure Load Balancer
  • Session affinityWebSocket 需要)

数据库扩展:

  • 读写分离(主从复制)
  • 按租户分片(大租户独立数据库)
  • PostgreSQL 表分区(按租户 ID

6.4.3 版本控制

MCP 协议支持版本号:

{
  "jsonrpc": "2.0",
  "method": "initialize",
  "params": {
    "protocolVersion": "2024-11-05",
    "capabilities": {
      "resources": {},
      "tools": {},
      "prompts": {}
    }
  }
}

版本策略:

  • 向后兼容old API Key 仍可使用)
  • 废弃警告Deprecated 字段)
  • 强制升级BREAKING CHANGE

7. 实现路线图

7.1 MVP 阶段功能范围

目标: 验证技术可行性,实现核心功能

功能范围:

  • 5 个核心 Resourcesprojects.list, issues.search, sprints.current, users.list, issues.get
  • 3 个核心 Toolscreate_issue, update_status, add_comment
  • 2 个核心 Promptsgenerate_prd, split_epic_to_stories
  • API Key 认证(创建、验证、撤销)
  • Diff Preview 机制(生成、存储、审批)
  • 基础审计日志

不包含:

  • 高级查询工具
  • 复杂权限配置
  • IP 白名单
  • 自动化审批规则

预计时间: 4 周

7.2 核心功能优先级

优先级 功能模块 工作量 依赖
P0 MCP Protocol Handler 3天
P0 API Key 管理(创建、验证) 2天 MCP Protocol Handler
P0 Resources 实现5个 3天 API Key
P0 Diff Preview Service 2天 Resources
P0 PendingChange 管理 2天 Diff Preview
P0 Tools 实现3个 3天 PendingChange
P0 审批流程(前端 UI 2天 PendingChange
P1 Prompts 实现2个 2天 Tools
P1 审计日志集成 1天 已有 Audit Log 系统
P1 Claude Desktop 集成 PoC 2天 所有核心功能

总工时: 22 天(约 4.5 周)

7.3 分阶段实现建议

Phase 1: FoundationWeek 1-2

目标: 建立 MCP 基础设施

交付物:

  • MCP Protocol HandlerJSON-RPC 2.0 解析和路由)
  • API Key 聚合根和仓储
  • API Key 认证中间件
  • 基础的错误处理和日志记录

验收标准:

  • MCP 协议 initialize 握手成功
  • API Key 创建和验证通过
  • 未授权请求返回 401
  • 错误响应符合 MCP 规范

Phase 2: ResourcesWeek 3-4

目标: 实现只读数据暴露

交付物:

  • 5 个核心 Resources 实现
  • Resource 注册和发现机制
  • 租户隔离验证
  • Redis 缓存集成

验收标准:

  • 所有 5 个 Resources 返回正确数据
  • 租户隔离 100% 生效
  • 响应时间 < 200ms
  • 缓存命中率 > 80%

Phase 3: Tools & Diff PreviewWeek 5-6

目标: 实现写操作和 Diff Preview

交付物:

  • DiffPreviewService 实现
  • PendingChange 聚合根和仓储
  • 3 个核心 Tools 实现
  • SignalR 实时通知集成

验收标准:

  • Diff Preview 准确显示变更
  • PendingChange 正确存储和查询
  • SignalR 推送工作正常
  • 24小时自动过期机制生效

Phase 4: Approval WorkflowWeek 7-8

目标: 实现审批流程

交付物:

  • 审批 API 端点approve/reject
  • 审批后自动执行逻辑
  • 前端审批界面Dashboard
  • 审计日志集成

验收标准:

  • 审批通过后自动执行操作
  • 审批拒绝后记录日志
  • 前端界面清晰展示 Diff
  • 审计日志完整记录

Phase 5: Prompts & IntegrationWeek 9-10

目标: 实现提示词和 AI 集成

交付物:

  • 2 个核心 Prompts 实现
  • Claude Desktop 配置文件
  • MCP 集成测试(端到端)
  • 用户文档和使用指南

验收标准:

  • Claude Desktop 成功连接
  • AI 能够查询项目数据
  • AI 能够创建任务(需审批)
  • 完整的端到端流程测试通过

Phase 6: Testing & HardeningWeek 11-12

目标: 质量保证和生产就绪

交付物:

  • 单元测试覆盖率 > 80%
  • 集成测试套件
  • 性能测试和优化
  • 安全审计和漏洞修复

验收标准:

  • 所有测试通过
  • 性能达标API < 200ms
  • 无 CRITICAL 安全漏洞
  • 文档完整且准确

Phase 7: Documentation & PoCWeek 13-16

目标: 文档和概念验证

交付物:

  • MCP API 完整文档
  • AI 集成最佳实践指南
  • 视频演示Demo
  • 内部培训材料

验收标准:

  • 外部开发者能根据文档集成
  • 演示视频清晰展示价值
  • 团队成员完成培训

8. 总结

8.1 核心设计原则

  1. 安全优先: 所有写操作需审批,完整审计追踪
  2. 租户隔离: 100% 数据隔离,无跨租户访问
  3. 性能保证: API < 200ms缓存命中率 > 80%
  4. 可扩展性: 插件化设计,便于添加新 Resources/Tools
  5. 向后兼容: 版本控制,避免 Breaking Changes

8.2 技术亮点

  • 自定义 MCP 实现: 不依赖 Node.js与 .NET 后端无缝集成
  • Diff Preview 机制: 创新的"预览 → 审批 → 执行"流程
  • CQRS + DDD: 清晰的架构分层,易于维护和测试
  • SignalR 实时通知: 无需轮询,审批结果即时推送
  • 多层缓存: Redis + 应用层缓存,性能优化

8.3 风险与缓解

风险 影响 概率 缓解措施
MCP 协议规范变更 版本控制,快速适配新规范
AI 误操作导致数据损坏 Diff Preview + 审批 + 审计
性能瓶颈(高并发) Redis 缓存 + 水平扩展
安全漏洞API Key 泄露) BCrypt 哈希 + IP 白名单 + 速率限制
审批流程过于繁琐 可配置自动审批规则

8.4 后续演进方向

M3 阶段ChatGPT 集成):

  • 支持 ChatGPT Plugin 协议
  • 实现对话式项目管理
  • AI 生成完整 PRD → Epic → Stories 闭环

M4 阶段(外部系统集成):

  • GitHub Actions 触发 ColaFlow 更新
  • Slack 消息自动创建任务
  • 日历同步 Sprint 时间线

M5 阶段(企业级功能):

  • 多 AI Agent 协作PM AI + Dev AI + QA AI
  • AI 决策审批工作流
  • 自定义 AI Prompt 市场

文档结束

如有疑问或需要更详细的技术设计,请联系架构师团队。