Skip to content

Latest commit

 

History

History
266 lines (220 loc) · 7.59 KB

File metadata and controls

266 lines (220 loc) · 7.59 KB

Taiwan Stock Agent - Error Handling System

Overview

A comprehensive, production-ready error handling system has been implemented for the Taiwan Stock Agent MCP server. This system provides structured error responses, proper validation, retry mechanisms, and circuit breaker patterns for robust operation.

Key Components

1. Custom Exception Hierarchy

Base Exception: TwStockAgentError

  • Structured error information with codes, severity, and context
  • Error enrichment capabilities
  • MCP protocol compliance
  • JSON serialization support

Specialized Exceptions:

  • Stock Exceptions: StockNotFoundError, InvalidStockCodeError, StockDataUnavailableError, StockMarketClosedError
  • API Exceptions: RateLimitError, DataSourceUnavailableError, ExternalAPIError, TimeoutError
  • Cache Exceptions: CacheConnectionError, CacheKeyError, CacheSerializationError
  • MCP Exceptions: MCPValidationError, MCPResourceError, MCPToolError
  • Validation Exceptions: ParameterValidationError, DataFormatError, TypeValidationError

2. Input Validation System

Stock Code Validation:

  • Taiwan stock code format validation (4-6 digits)
  • Support for ETFs (0050-0999) and regular stocks (1000-9999)
  • Stock type detection and market classification
  • Bulk validation capabilities

Parameter Validation:

  • Type checking and conversion
  • Range validation
  • Enum validation
  • String length validation
  • Date format validation

3. Error Context and Enrichment

Error Context: ErrorContext

  • Correlation IDs for tracking
  • Timestamps
  • Stock codes
  • Operation names
  • User IDs
  • Request IDs
  • Additional metadata

Error Enrichment: ErrorEnricher

  • Automatic context addition
  • Exception type mapping
  • Severity determination
  • Cause chain preservation

4. Production Error Handling Patterns

Retry Manager:

  • Exponential backoff with jitter
  • Configurable retry policies
  • Non-retryable error detection
  • Maximum retry limits

Circuit Breaker:

  • Failure threshold monitoring
  • Automatic state management (CLOSED/OPEN/HALF_OPEN)
  • Service recovery detection
  • Graceful degradation

Error Decorators:

  • @with_error_handling - Synchronous error handling
  • @with_async_error_handling - Asynchronous error handling
  • @with_retry - Retry mechanism
  • @mcp_error_handler - MCP tool error handling

5. MCP Protocol Integration

MCP Error Handler: MCPErrorHandler

  • Tool error handling
  • Resource error handling
  • Validation error handling
  • JSON-RPC compliant responses

Response Formatter: MCPResponseFormatter

  • Stock data formatting
  • Price data formatting
  • Error response formatting
  • Metadata preservation

6. Logging and Monitoring

Structured Logging: ErrorLogger

  • Severity-based log levels
  • Correlation ID tracking
  • Context preservation
  • Configurable output

Implementation Examples

Basic Error Handling

from tw_stock_agent.exceptions import StockNotFoundError
from tw_stock_agent.utils.validation import StockCodeValidator

# Validate stock code
try:
    validated_code = StockCodeValidator.validate_stock_code("2330")
except InvalidStockCodeError as e:
    print(f"Error: {e.message}")
    print(f"Suggestions: {e.suggestions}")

Service Layer with Decorators

@with_async_error_handling(operation="fetch_stock_data")
@with_retry(max_retries=3, base_delay=1.0)
async def fetch_stock_data(stock_code: str):
    # Service implementation
    pass

MCP Tool Error Handling

@mcp_error_handler("get_stock_data")
async def get_stock_data_tool(stock_code: str):
    try:
        return await get_stock_data(stock_code)
    except TwStockAgentError as e:
        # Automatically handled by decorator
        raise

Circuit Breaker Usage

circuit_breaker = CircuitBreaker(failure_threshold=3)

async def api_call():
    return await circuit_breaker.acall(external_api_function)

Error Response Formats

Standard Error Response

{
  "error": true,
  "error_code": "STOCK_NOT_FOUND",
  "message": "Stock with code '9999' was not found",
  "severity": "medium",
  "timestamp": "2023-12-01T10:00:00.000000",
  "correlation_id": "abc123-def456-ghi789",
  "stock_code": "9999",
  "suggestions": [
    "Verify the stock code is correct",
    "Check if the stock is listed on Taiwan stock exchanges"
  ]
}

MCP Error Response

{
  "error": {
    "code": "STOCK_NOT_FOUND",
    "message": "Stock with code '9999' was not found",
    "data": {
      "severity": "medium",
      "correlation_id": "abc123-def456-ghi789",
      "timestamp": "2023-12-01T10:00:00.000000",
      "suggestions": ["Verify the stock code is correct"],
      "context": {
        "stock_code": "9999",
        "operation": "tool_execution_get_stock_data"
      }
    }
  }
}

Validation Rules

Taiwan Stock Codes

  • Format: 4-6 digits only
  • ETFs: 0050-0999 (e.g., 0050 for Taiwan 50 ETF)
  • Regular Stocks: 1000-9999 (e.g., 2330 for TSMC)
  • Reserved Codes: 0000-0003, 9999 (invalid)

Common Stock Examples

  • 2330 - Taiwan Semiconductor (TSMC)
  • 2317 - Hon Hai Precision (Foxconn)
  • 1301 - Formosa Plastics Corp
  • 0050 - Taiwan Top 50 ETF
  • 1101 - Taiwan Cement Corp

Testing

The error handling system includes comprehensive tests:

Unit Tests

  • Exception creation and serialization
  • Validation logic
  • Error enrichment
  • Retry mechanisms
  • Circuit breaker functionality
  • MCP error handling

Integration Tests

  • End-to-end error flows
  • Service layer integration
  • MCP protocol compliance
  • Concurrent error handling
  • Real-world scenarios

Running Tests

# Run all error handling tests
uv run pytest tests/unit/test_exceptions.py -v
uv run pytest tests/unit/test_validation.py -v
uv run pytest tests/unit/test_error_handler.py -v
uv run pytest tests/unit/test_mcp_error_handler.py -v

# Run integration tests
uv run pytest tests/integration/test_error_handling_integration.py -v

Benefits

  1. Robust Error Handling: Comprehensive coverage of all error scenarios
  2. Production Ready: Circuit breakers, retries, and graceful degradation
  3. Developer Friendly: Clear error messages and helpful suggestions
  4. MCP Compliant: Proper JSON-RPC error responses
  5. Debuggable: Correlation IDs and structured logging
  6. Maintainable: Clean exception hierarchy and error handling patterns
  7. Performance: Efficient error processing with minimal overhead
  8. Testable: Comprehensive test coverage for all components

File Structure

tw_stock_agent/
├── exceptions/
│   ├── __init__.py          # Exception exports
│   ├── base.py              # Base exception classes
│   ├── stock_exceptions.py  # Stock-specific exceptions
│   ├── api_exceptions.py    # API-related exceptions
│   ├── cache_exceptions.py  # Cache-related exceptions
│   ├── mcp_exceptions.py    # MCP protocol exceptions
│   └── validation_exceptions.py # Validation exceptions
├── utils/
│   ├── error_handler.py     # Error handling utilities
│   ├── validation.py        # Input validation
│   └── mcp_error_handler.py # MCP error handling
└── services/
    └── stock_service.py     # Updated with error handling

tests/
├── unit/
│   ├── test_exceptions.py
│   ├── test_validation.py
│   ├── test_error_handler.py
│   └── test_mcp_error_handler.py
└── integration/
    └── test_error_handling_integration.py

This error handling system provides a solid foundation for building reliable, production-ready applications with the Taiwan Stock Agent MCP server.