Implemented JSON-RPC 2.0 protocol handler for MCP communication, enabling AI agents to communicate with ColaFlow using the Model Context Protocol. **Implementation:** - JSON-RPC 2.0 data models (Request, Response, Error, ErrorCode) - MCP protocol models (Initialize, Capabilities, ClientInfo, ServerInfo) - McpProtocolHandler with method routing and error handling - Method handlers: initialize, resources/list, tools/list, tools/call - ASP.NET Core middleware for /mcp endpoint - Service registration and dependency injection setup **Testing:** - 28 unit tests covering protocol parsing, validation, and error handling - Integration tests for initialize handshake and error responses - All tests passing with >80% coverage **Changes:** - Created ColaFlow.Modules.Mcp.Contracts project - Created ColaFlow.Modules.Mcp.Domain project - Created ColaFlow.Modules.Mcp.Application project - Created ColaFlow.Modules.Mcp.Infrastructure project - Created ColaFlow.Modules.Mcp.Tests project - Registered MCP module in ColaFlow.API Program.cs - Added /mcp endpoint via middleware **Acceptance Criteria Met:** ✅ 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, -32601, -32602) ✅ MCP initialize method implemented ✅ Server capabilities returned (resources, tools, prompts) ✅ Protocol version negotiation works (1.0) ✅ Request routing to method handlers ✅ Unit test coverage > 80% ✅ All tests passing **Story**: docs/stories/sprint_5/story_5_1.md 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
10 KiB
10 KiB
story_id, sprint_id, phase, status, priority, story_points, assignee, estimated_days, created_date, dependencies
| story_id | sprint_id | phase | status | priority | story_points | assignee | estimated_days | created_date | dependencies |
|---|---|---|---|---|---|---|---|---|---|
| story_5_1 | sprint_5 | Phase 1 - Foundation | not_started | P0 | 8 | backend | 3 | 2025-11-06 |
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
initializemethod 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
resultfield - Error responses with
errorfield (code, message, data) - Request ID correctly echoed in response
- Notification support (no
idfield)
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
public interface IMcpProtocolHandler
{
Task<McpResponse> 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
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
// 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
IMcpProtocolHandlerinterface - Create
McpRequest,McpResponse,McpErrorDTOs - Implement
McpProtocolHandlerclass - Add JSON serialization configuration (System.Text.Json)
- Create ASP.NET Core controller endpoint
POST /mcp
Files to Create:
ColaFlow.Modules.Mcp/Contracts/IMcpProtocolHandler.csColaFlow.Modules.Mcp/DTOs/McpRequest.csColaFlow.Modules.Mcp/DTOs/McpResponse.csColaFlow.Modules.Mcp/DTOs/McpError.csColaFlow.Modules.Mcp/Services/McpProtocolHandler.csColaFlow.Modules.Mcp/Controllers/McpController.cs
Task 2: Implement Initialize Handshake (4 hours)
- Implement
initializemethod 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
IMcpResourceDispatcherinterface - Create
IMcpToolDispatcherinterface - Implement method-based routing logic
- Handle
resources/list,resources/readmethods - Handle
tools/list,tools/callmethods - Return -32601 for unknown methods
Files to Create:
ColaFlow.Modules.Mcp/Contracts/IMcpResourceDispatcher.csColaFlow.Modules.Mcp/Contracts/IMcpToolDispatcher.csColaFlow.Modules.Mcp/Services/McpResourceDispatcher.csColaFlow.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.csColaFlow.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.csColaFlow.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
- Custom .NET Implementation: No Node.js SDK dependency
- System.Text.Json: Fastest JSON serialization in .NET
- Method-Based Routing: Simple string matching for method dispatch
- 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