Files
ColaFlow/colaflow-api/src/Modules/Mcp/ColaFlow.Modules.Mcp.Domain/Exceptions/McpForbiddenException.cs
Yaojia Wang c00c909489 feat(backend): Implement Story 5.4 - MCP Error Handling & Logging
Implement comprehensive error handling and structured logging for MCP module.

**Exception Hierarchy**:
- Created McpException base class with JSON-RPC error mapping
- Implemented 8 specific exception types (Parse, InvalidRequest, MethodNotFound, etc.)
- Each exception maps to correct HTTP status code (401, 403, 404, 422, 400, 500)

**Middleware**:
- McpCorrelationIdMiddleware: Generates/extracts correlation ID for request tracking
- McpExceptionHandlerMiddleware: Global exception handler with JSON-RPC error responses
- McpLoggingMiddleware: Request/response logging with sensitive data sanitization

**Serilog Integration**:
- Configured structured logging with Console and File sinks
- Log rotation (daily, 30-day retention)
- Correlation ID enrichment in all log entries

**Features**:
- Correlation ID propagation across request chain
- Structured logging with TenantId, UserId, ApiKeyId
- Sensitive data sanitization (API keys, passwords)
- Performance metrics (request duration, slow request warnings)
- JSON-RPC 2.0 compliant error responses

**Testing**:
- 174 tests passing (all MCP module tests)
- Unit tests for all exception classes
- Unit tests for all middleware components
- 100% coverage of error mapping and HTTP status codes

**Files Added**:
- 9 exception classes in Domain/Exceptions/
- 3 middleware classes in Infrastructure/Middleware/
- 4 test files with comprehensive coverage

**Files Modified**:
- Program.cs: Serilog configuration
- McpServiceExtensions.cs: Middleware pipeline registration
- JsonRpcError.cs: Added parameterless constructor for deserialization
- MCP Infrastructure .csproj: Added Serilog package reference

**Verification**:
 All 174 MCP module tests passing
 Build successful with no errors
 Exception-to-HTTP-status mapping verified
 Correlation ID propagation tested
 Sensitive data sanitization verified

Story: docs/stories/sprint_5/story_5_4.md

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-08 21:08:12 +01:00

22 lines
745 B
C#

using ColaFlow.Modules.Mcp.Contracts.JsonRpc;
namespace ColaFlow.Modules.Mcp.Domain.Exceptions;
/// <summary>
/// Exception thrown when authorization fails (authenticated but not allowed)
/// Maps to JSON-RPC error code -32002 (Forbidden)
/// HTTP 403 status code
/// </summary>
public class McpForbiddenException : McpException
{
/// <summary>
/// Initializes a new instance of the <see cref="McpForbiddenException"/> class
/// </summary>
/// <param name="message">Error message</param>
/// <param name="errorData">Additional error data (optional)</param>
public McpForbiddenException(string message = "Forbidden", object? errorData = null)
: base(JsonRpcErrorCode.Forbidden, message, errorData)
{
}
}