# MCP SDK Migration Plan

**Date**: 2025-11-12
**Status**: In Progress
**SDK Version**: ModelContextProtocol v0.4.0-preview.3

---

## Migration Strategy

We are migrating to the official Microsoft Model Context Protocol C# SDK while **preserving ColaFlow's unique Diff Preview and PendingChange approval mechanism**.

### Hybrid Approach

- **Use SDK for**: Protocol handling, transport layer, auto-discovery
- **Keep Custom**: Diff Preview, PendingChange workflow, multi-tenant isolation, authentication

---

## Completed Steps

### ✅ Step 1: Install SDK Packages (Completed)

**Packages Installed**:
- `ModelContextProtocol` v0.4.0-preview.3 → Infrastructure project
- `ModelContextProtocol.AspNetCore` v0.4.0-preview.3 → Infrastructure + API projects

**Files Modified**:
- `ColaFlow.Modules.Mcp.Infrastructure.csproj`
- `ColaFlow.API.csproj`

### ✅ Step 2: Create SDK-based Components (Completed)

**New Files Created**:

1. **SdkTools/CreateIssueSdkTool.cs** ✅
   - Attribute-based Tool definition using `[McpServerToolType]` and `[McpServerTool]`
   - Preserves Diff Preview mechanism
   - Returns PendingChange ID instead of direct execution

2. **SdkResources/ProjectsSdkResource.cs** ✅
   - Attribute-based Resource definition using `[McpServerResourceType]` and `[McpServerResource]`
   - Implements `ListProjectsAsync()` and `GetProjectAsync()`

3. **SdkPrompts/ProjectManagementPrompts.cs** ✅ (NEW FEATURE)
   - Implements Prompts功能 (previously missing in ColaFlow)
   - Provides 5 prompt templates:
     - `GeneratePrdPrompt` - Generate PRD for Epic
     - `SplitEpicToStoriesPrompt` - Break down Epic into Stories
     - `GenerateAcceptanceCriteriaPrompt` - Create acceptance criteria
     - `AnalyzeSprintProgressPrompt` - Analyze Sprint progress
     - `GenerateRetrospectivePrompt` - Sprint retrospective

### ✅ Step 3: Update Program.cs (Completed)

**Changes Made**:
- Kept `AddMcpModule()` for custom services (Diff Preview, PendingChange, etc.)
- Added SDK server registration with auto-discovery:
  ```csharp
  builder.Services.AddMcpServer(options =>
  {
      options.ServerInfo = new Microsoft.Extensions.AI.ServerInfo
      {
          Name = "ColaFlow MCP Server",
          Version = "1.0.0"
      };
  })
  .WithToolsFromAssembly(typeof(CreateIssueSdkTool).Assembly)
  .WithResourcesFromAssembly(typeof(ProjectsSdkResource).Assembly)
  .WithPromptsFromAssembly(typeof(ProjectManagementPrompts).Assembly);
  ```
- Added SDK endpoint mapping: `app.MapMcp("/mcp-sdk");`
- Legacy `/mcp` endpoint still handled by custom middleware

---

## Next Steps

### 🔄 Step 4: Migrate Remaining Tools (10 tools to migrate)

**Current Tools to Migrate**:
1. ✅ `CreateIssueTool` → `CreateIssueSdkTool` (Done)
2. ⏳ `UpdateIssueTool` → `UpdateIssueSdkTool`
3. ⏳ `UpdateIssueStatusTool` → `UpdateIssueStatusSdkTool`
4. ⏳ `AssignIssueTool` → `AssignIssueSdkTool`
5. ⏳ `CreateSprintTool` → `CreateSprintSdkTool`
6. ⏳ `StartSprintTool` → `StartSprintSdkTool`
7. ⏳ `AddCommentTool` → `AddCommentSdkTool`
8. ⏳ `CreateEpicTool` → `CreateEpicSdkTool`
9. ⏳ `LinkIssuesTool` → `LinkIssuesSdkTool`
10. ⏳ `CreateProjectTool` → `CreateProjectSdkTool`

**Pattern to Follow** (from CreateIssueSdkTool):
```csharp
[McpServerToolType]
public class XxxSdkTool
{
    // Constructor injection
    public XxxSdkTool(IDependencies...) { }

    [McpServerTool]
    [Description("Tool description")]
    public async Task<string> MethodNameAsync(
        [Description("param desc")] ParamType param,
        CancellationToken cancellationToken = default)
    {
        // 1. Validate input
        // 2. Generate Diff Preview
        // 3. Create PendingChange
        // 4. Return PendingChange info (NOT direct result)
    }
}
```

### 🔄 Step 5: Migrate Remaining Resources (10 resources to migrate)

**Current Resources to Migrate**:
1. ✅ `ProjectsListResource` → `ProjectsSdkResource.ListProjectsAsync()` (Done)
2. ✅ `ProjectsGetResource` → `ProjectsSdkResource.GetProjectAsync()` (Done)
3. ⏳ `IssuesSearchResource` → `IssuesSdkResource.SearchIssuesAsync()`
4. ⏳ `IssuesGetResource` → `IssuesSdkResource.GetIssueAsync()`
5. ⏳ `SprintsCurrentResource` → `SprintsSdkResource.GetCurrentSprintAsync()`
6. ⏳ `UsersListResource` → `UsersSdkResource.ListUsersAsync()`
7. ⏳ `EpicsListResource` → (Can be part of IssuesResource with type filter)
8. ⏳ `StoriesListResource` → (Can be part of IssuesResource with type filter)
9. ⏳ `TasksListResource` → (Can be part of IssuesResource with type filter)
10. ⏳ `SprintsBacklogResource` → `SprintsSdkResource.GetBacklogAsync()`
11. ⏳ `ReportsBurndownResource` → `ReportsSdkResource.GetBurndownAsync()`

### 🔄 Step 6: Test SDK Integration

**Testing Checklist**:
- [ ] Test SDK endpoint `/mcp-sdk` responds to `initialize`
- [ ] Test Tools discovery via `tools/list`
- [ ] Test Resources discovery via `resources/list`
- [ ] Test Prompts discovery via `prompts/list` (new feature!)
- [ ] Test Tool execution with Diff Preview mechanism
- [ ] Test Resource reading with tenant isolation
- [ ] Test Prompt retrieval
- [ ] Verify legacy `/mcp` endpoint still works

### 🔄 Step 7: Update Documentation

**Documents to Update**:
- [ ] `docs/architecture/mcp-server-architecture.md` - Add SDK section
- [ ] `README.md` - Update MCP integration instructions
- [ ] API documentation - Document new `/mcp-sdk` endpoint
- [ ] Create migration guide for future SDK updates

### 🔄 Step 8: Deprecate Legacy Implementation (Optional)

**Decision Point**: Should we keep both implementations?

**Option A: Keep Both** (Recommended for now)
- `/mcp` - Legacy custom implementation
- `/mcp-sdk` - New SDK-based implementation
- Allows gradual migration and A/B testing

**Option B: Full Migration**
- Remove custom middleware
- Only use `/mcp-sdk`
- Requires thorough testing

---

## Architecture Diagram

```
┌─────────────────────────────────────────────────────────────┐
│                     ColaFlow MCP Server                      │
├─────────────────────────────────────────────────────────────┤
│                                                               │
│  ┌────────────────────┐      ┌────────────────────────┐    │
│  │ Legacy Endpoint    │      │ SDK Endpoint           │    │
│  │ POST /mcp          │      │ POST /mcp-sdk          │    │
│  │ (Custom Middleware)│      │ (Official SDK)         │    │
│  └────────────────────┘      └────────────────────────┘    │
│           │                            │                     │
│           ├──────────┬─────────────────┤                    │
│           │          │                 │                     │
│  ┌────────▼────┐  ┌──▼──────────┐  ┌──▼──────────────┐    │
│  │ IMcpTool    │  │ [McpTool]   │  │ [McpResource]   │    │
│  │ (Legacy)    │  │ (SDK-based) │  │ (SDK-based)     │    │
│  └────────┬────┘  └──┬──────────┘  └──┬──────────────┘    │
│           │          │                 │                     │
│           └──────────┼─────────────────┘                    │
│                      │                                       │
│           ┌──────────▼──────────┐                           │
│           │ Diff Preview Service │ (Preserved)              │
│           │ PendingChange Service│ (Preserved)              │
│           │ Multi-tenant Context │ (Preserved)              │
│           └─────────────────────┘                           │
│                                                               │
└─────────────────────────────────────────────────────────────┘
```

---

## Key Design Decisions

### ✅ Preserve Diff Preview Mechanism

**Why**: This is ColaFlow's core competitive advantage for safe AI collaboration.

**How**: SDK Tools return PendingChange ID instead of direct execution results.

### ✅ Keep Custom Services

**Services Preserved**:
- `IPendingChangeService` - Manages approval workflow
- `DiffPreviewService` - Generates change previews
- `IMcpApiKeyService` - API key authentication
- `ITenantContext` - Multi-tenant isolation
- `IMcpNotificationService` - SignalR real-time notifications

### ✅ Add Prompts Feature

**New Capability**: Prompts were missing in ColaFlow but supported by SDK.

**Value**: Provides AI with pre-defined templates for common project management tasks.

---

## Risks and Mitigations

| Risk | Impact | Mitigation |
|------|--------|------------|
| SDK API Changes | High | SDK is preview version, lock to v0.4.0-preview.3 |
| Dual Endpoints Confusion | Medium | Clear documentation, deprecation plan |
| Performance Regression | Medium | Load testing before production |
| Breaking Changes | High | Keep legacy endpoint as fallback |

---

## Success Criteria

- [x] SDK packages installed successfully
- [x] At least 1 Tool migrated with Diff Preview preserved
- [x] At least 1 Resource migrated
- [x] Prompts feature implemented
- [ ] All 10 Tools migrated
- [ ] All 11 Resources migrated
- [ ] SDK endpoint passes all integration tests
- [ ] Documentation updated
- [ ] No performance degradation

---

## Timeline

**Estimated Time**: 5-7 days

- **Day 1**: ✅ Setup and initial migration (Completed)
- **Day 2-3**: Migrate remaining Tools
- **Day 4**: Migrate remaining Resources
- **Day 5**: Testing and bug fixes
- **Day 6**: Documentation
- **Day 7**: Review and production readiness

---

## Notes

- SDK version `0.4.0-preview.3` is a preview release - expect potential breaking changes
- Official SDK does NOT support Diff Preview natively - we've adapted it
- Legacy implementation will remain as fallback during transition
- This migration brings us into compliance with MCP specification while maintaining unique features

---

**Last Updated**: 2025-11-12
**Migration Lead**: Claude (ColaFlow Coordinator)
**Status**: 40% Complete (3/8 major steps done)
