--- story_id: story_5_1 sprint_id: sprint_5 phase: Phase 1 - Foundation status: not_started priority: P0 story_points: 8 assignee: backend estimated_days: 3 created_date: 2025-11-06 dependencies: [] --- # Story 5.1: MCP Protocol Handler Implementation **Phase**: Phase 1 - Foundation (Week 1-2) **Priority**: P0 CRITICAL **Estimated Effort**: 8 Story Points (3 days) ## User Story **As a** ColaFlow System **I want** to implement a JSON-RPC 2.0 protocol handler for MCP communication **So that** AI agents (Claude, ChatGPT) can communicate with ColaFlow using the MCP protocol ## Business Value This is the foundational infrastructure for M2 MCP Server. Without this, AI agents cannot communicate with ColaFlow. This Story enables all future MCP Resources and Tools. **Impact**: - Enables AI integration foundation - Supports 11 Resources + 10 Tools in future Stories - 100% required for M2 milestone completion ## Acceptance Criteria ### AC1: MCP Protocol Parsing - [ ] JSON-RPC 2.0 messages correctly parsed - [ ] Request validation (jsonrpc: "2.0", method, params, id) - [ ] Error responses conform to JSON-RPC 2.0 spec - [ ] Invalid requests return proper error codes (-32700, -32600, -32602) ### AC2: Initialize Handshake - [ ] MCP `initialize` method implemented - [ ] Server capabilities returned (resources, tools, prompts) - [ ] Protocol version negotiation works (1.0) - [ ] Client initialization validated ### AC3: Request Routing - [ ] Route requests to Resource handlers (e.g., `resources/list`, `resources/read`) - [ ] Route requests to Tool handlers (e.g., `tools/list`, `tools/call`) - [ ] Route requests to Prompt handlers (e.g., `prompts/list`) - [ ] Method not found returns -32601 error ### AC4: Response Generation - [ ] Success responses with `result` field - [ ] Error responses with `error` field (code, message, data) - [ ] Request ID correctly echoed in response - [ ] Notification support (no `id` field) ### AC5: Testing - [ ] Unit test coverage > 80% - [ ] Integration tests for initialize handshake - [ ] Error handling tests (invalid JSON, missing fields) - [ ] Performance test: protocol overhead < 5ms ## Technical Design ### Architecture ``` ┌─────────────────────────────────────┐ │ ASP.NET Core Controller │ │ POST /mcp (JSON-RPC endpoint) │ └───────────────┬─────────────────────┘ │ ┌───────────────┴─────────────────────┐ │ McpProtocolHandler │ │ - Parse JSON-RPC 2.0 │ │ - Validate request │ │ - Route to handler │ │ - Format response │ └───────────────┬─────────────────────┘ │ ┌─────────┴─────────┐ │ │ ┌─────┴──────┐ ┌──────┴──────┐ │ Resource │ │ Tool │ │ Dispatcher │ │ Dispatcher │ └────────────┘ └─────────────┘ ``` ### Key Interfaces ```csharp public interface IMcpProtocolHandler { Task HandleRequestAsync( McpRequest request, CancellationToken cancellationToken); } public class McpRequest { public string JsonRpc { get; set; } = "2.0"; public string Method { get; set; } public object? Params { get; set; } public string? Id { get; set; } } public class McpResponse { public string JsonRpc { get; set; } = "2.0"; public object? Result { get; set; } public McpError? Error { get; set; } public string? Id { get; set; } } public class McpError { public int Code { get; set; } public string Message { get; set; } public object? Data { get; set; } } ``` ### MCP Error Codes ```csharp public enum McpErrorCode { ParseError = -32700, // Invalid JSON InvalidRequest = -32600, // Invalid Request object MethodNotFound = -32601, // Method does not exist InvalidParams = -32602, // Invalid method parameters InternalError = -32603, // Internal JSON-RPC error Unauthorized = -32001, // Authentication failed Forbidden = -32002, // Authorization failed NotFound = -32003, // Resource not found ValidationFailed = -32004 // Request validation failed } ``` ### Initialize Handshake Flow ```json // Request { "jsonrpc": "2.0", "method": "initialize", "params": { "protocolVersion": "1.0", "clientInfo": { "name": "Claude Desktop", "version": "1.0.0" } }, "id": 1 } // Response { "jsonrpc": "2.0", "result": { "protocolVersion": "1.0", "serverInfo": { "name": "ColaFlow MCP Server", "version": "1.0.0" }, "capabilities": { "resources": { "supported": true }, "tools": { "supported": true }, "prompts": { "supported": true } } }, "id": 1 } ``` ## Tasks ### Task 1: Create Core Protocol Infrastructure (6 hours) - [ ] Create `IMcpProtocolHandler` interface - [ ] Create `McpRequest`, `McpResponse`, `McpError` DTOs - [ ] Implement `McpProtocolHandler` class - [ ] Add JSON serialization configuration (System.Text.Json) - [ ] Create ASP.NET Core controller endpoint `POST /mcp` **Files to Create**: - `ColaFlow.Modules.Mcp/Contracts/IMcpProtocolHandler.cs` - `ColaFlow.Modules.Mcp/DTOs/McpRequest.cs` - `ColaFlow.Modules.Mcp/DTOs/McpResponse.cs` - `ColaFlow.Modules.Mcp/DTOs/McpError.cs` - `ColaFlow.Modules.Mcp/Services/McpProtocolHandler.cs` - `ColaFlow.Modules.Mcp/Controllers/McpController.cs` ### Task 2: Implement Initialize Handshake (4 hours) - [ ] Implement `initialize` method handler - [ ] Return server capabilities (resources, tools, prompts) - [ ] Protocol version validation (support 1.0) - [ ] Client info parsing and logging **Files to Modify**: - `ColaFlow.Modules.Mcp/Services/McpProtocolHandler.cs` ### Task 3: Implement Request Routing (6 hours) - [ ] Create `IMcpResourceDispatcher` interface - [ ] Create `IMcpToolDispatcher` interface - [ ] Implement method-based routing logic - [ ] Handle `resources/list`, `resources/read` methods - [ ] Handle `tools/list`, `tools/call` methods - [ ] Return -32601 for unknown methods **Files to Create**: - `ColaFlow.Modules.Mcp/Contracts/IMcpResourceDispatcher.cs` - `ColaFlow.Modules.Mcp/Contracts/IMcpToolDispatcher.cs` - `ColaFlow.Modules.Mcp/Services/McpResourceDispatcher.cs` - `ColaFlow.Modules.Mcp/Services/McpToolDispatcher.cs` ### Task 4: Error Handling & Validation (4 hours) - [ ] Implement JSON parsing error handling (ParseError -32700) - [ ] Validate request structure (InvalidRequest -32600) - [ ] Validate method parameters (InvalidParams -32602) - [ ] Create exception-to-error-code mapping - [ ] Add structured logging (Serilog) **Files to Create**: - `ColaFlow.Modules.Mcp/Exceptions/McpException.cs` - `ColaFlow.Modules.Mcp/Middleware/McpExceptionHandler.cs` ### Task 5: Unit Tests (4 hours) - [ ] Test JSON-RPC request parsing - [ ] Test initialize handshake - [ ] Test request routing (valid methods) - [ ] Test error handling (invalid requests) - [ ] Test protocol overhead performance (< 5ms) **Files to Create**: - `ColaFlow.Modules.Mcp.Tests/Services/McpProtocolHandlerTests.cs` - `ColaFlow.Modules.Mcp.Tests/Controllers/McpControllerTests.cs` ### Task 6: Integration Tests (4 hours) - [ ] Test end-to-end initialize handshake - [ ] Test routing to Resources (mock handler) - [ ] Test routing to Tools (mock handler) - [ ] Test error responses (invalid JSON, missing fields) **Files to Create**: - `ColaFlow.Modules.Mcp.Tests/Integration/McpProtocolIntegrationTests.cs` ## Testing Strategy ### Unit Tests (Target: > 80% coverage) - Protocol parsing logic - Request validation - Error code mapping - Method routing - Response formatting ### Integration Tests - Initialize handshake flow - Request/response round-trip - Error handling end-to-end - Performance benchmarks ### Manual Testing Checklist - [ ] Send valid initialize request → success - [ ] Send invalid JSON → ParseError -32700 - [ ] Send request without `method` → InvalidRequest -32600 - [ ] Send unknown method → MethodNotFound -32601 - [ ] Measure protocol overhead < 5ms ## Dependencies **Prerequisites**: - .NET 9 ASP.NET Core project structure - System.Text.Json (JSON serialization) - Serilog (logging) **Blocks**: - Story 5.5 (Core MCP Resources) - Needs protocol handler - Story 5.11 (Core MCP Tools) - Needs protocol handler ## Risks & Mitigation | Risk | Impact | Probability | Mitigation | |------|--------|-------------|------------| | MCP spec changes | High | Medium | Version control, quick adaptation | | JSON parsing performance | Medium | Low | Use System.Text.Json (fastest) | | Request routing complexity | Medium | Medium | Simple method name mapping | | Protocol overhead > 5ms | Medium | Low | Benchmark early, optimize if needed | ## Definition of Done - [ ] Code compiles without warnings - [ ] All unit tests passing (> 80% coverage) - [ ] All integration tests passing - [ ] Code reviewed and approved - [ ] XML documentation for public APIs - [ ] Performance benchmark < 5ms protocol overhead - [ ] Logging implemented (request/response at DEBUG level) - [ ] Exception handling complete - [ ] Initialize handshake works end-to-end ## Notes ### Why This Story Matters - **Foundation for M2**: All MCP features depend on this - **Protocol Compliance**: JSON-RPC 2.0 compatibility ensures AI tool integration - **Performance**: Low overhead design enables high throughput ### Key Design Decisions 1. **Custom .NET Implementation**: No Node.js SDK dependency 2. **System.Text.Json**: Fastest JSON serialization in .NET 3. **Method-Based Routing**: Simple string matching for method dispatch 4. **Stateless Handler**: Each request independent, easy to scale ### Reference Materials - MCP Protocol Specification: https://modelcontextprotocol.io/docs - JSON-RPC 2.0 Spec: https://www.jsonrpc.org/specification - Sprint 5 Plan: `docs/plans/sprint_5.md` - Architecture Design: `docs/M2-MCP-SERVER-ARCHITECTURE.md`