Error Handling & Recovery
Relevant source files
The following files were used as context for generating this wiki page:
Error Handling & Recovery in the Sequential Thinking MCP v2 project ensures system reliability and state consistency through a multi-layered exception hierarchy and markdown-based persistence. The system catches failures at the tool level and returns structured error messages to the Model Context Protocol (MCP) client while maintaining the ability to recover full session states from crashes.
Sources: memory-bank/memories/67944906-43bc-4c85-9424-f2261850bc97.md, README.md:144-148
Exception Architecture
The system utilizes a specific exception hierarchy to categorize failures. The UnifiedSessionManager raises these exceptions when business logic constraints or storage operations fail.
Core Exception Types
| Exception | Description |
|---|---|
NoActiveSessionError | Raised when a tool requires an active session but none is loaded. |
ValidationError | Raised when input data (e.g., confidence scores) fails integrity checks. |
SessionNotFoundError | Raised when requesting a session ID that does not exist in the storage directory. |
StorageError | Raised during failures in directory creation or file writing operations. |
BranchError | Raised for invalid branch operations, such as merging non-existent branches. |
MemoryError | Raised during failures in memory persistence or retrieval. |
Sources: errors.py, session_manager.py:20-29, memory-bank/memories/67944906-43bc-4c85-9424-f2261850bc97.md
Error Propagation Flow
The following diagram illustrates how errors propagate from the core logic to the MCP transport layer.
The diagram shows the sequence where the UnifiedSessionManager initiates an error, which the MCPToolsHandler catches to prevent server crashes, ultimately resulting in a structured JSON response from main.py.
Sources: memory-bank/sessions/7a56026e-0a71-42e5-a577-ae854a3ae896.md:Thought 3, session_manager.py:143-145
Data Validation Mechanisms
The system performs defensive checks before persisting data to ensure long-term integrity.
- Confidence Bounds: The
add_thoughtmethod validates that confidence scores remain between 0 and 1. If the value is outside this range, the system raises aValidationError. - Required Fields: Methods like
create_branchcheck for empty strings in names, purposes, and source thought IDs. - Post-Initialization Validation: Models include validation for proper tag parsing and required metadata fields.
Sources: session_manager.py:113-115, session_manager.py:136-141, memory-bank/memories/67944906-43bc-4c85-9424-f2261850bc97.md
# session_manager.py:113-115
# Example of confidence validation
if not (0 <= confidence <= 1):
raise ValidationError("Thought confidence must be between 0 and 1")
Session Recovery and Persistence
Recovery is achieved through "Modernization" features that ensure no data loss occurs during unexpected shutdowns.
Automatic State Restoration
During initialization, the UnifiedSessionManager attempts to recover the last active session.
- The manager checks the
index.mdregistry for the most recent session ID. - If an ID is found,
load_sessionreads the corresponding markdown file inmemory-bank/sessions/. - The
_parse_session_markdownmethod re-hydrates theUnifiedSessionobject, including thoughts and architecture decisions. - Memories are independently re-hydrated from
memory-bank/memories/to ensure full data restoration.
Sources: session_manager.py:34-39, session_manager.py:469-476, memory-bank/memories/67944906-43bc-4c85-9424-f2261850bc97.md
Crash Recovery Flow
This sequence shows the restoration process triggered upon server restart, leveraging the directory structure to rebuild state.
Sources: session_manager.py:38-39, session_manager.py:535-542
Storage Safety
The system uses defensive directory management to prevent StorageError exceptions.
- Directory Guarantee: The
_ensure_directoriesmethod executes during every initialization. It createssessions,memories, andpatternsfolders if they are missing. - Atomic Updates: Although storage is text-based, the system updates the
index.mdregistry every time a new session starts to ensure the recovery pointer is always current.
Sources: session_manager.py:41-47, session_manager.py:100-111
Integration Testing for Errors
The testing infrastructure specifically targets failure scenarios to ensure graceful degradation. Integration tests verify:
- Operations performed without an active session return error dictionaries instead of raising unhandled exceptions.
- The system handles malformed exports and non-existent session loads correctly.
Sources: tests/test_integration.py:257-279, memory-bank/memories/67944906-43bc-4c85-9424-f2261850bc97.md
# tests/test_integration.py:257-263
def test_error_handling_and_recovery(self, full_setup):
"""Test error handling in various failure scenarios."""
session_manager, tools_handler = full_setup
# 1. Test operations without session
assert "error" in tools_handler.add_thought("Test")
assert "error" in tools_handler.store_memory("Test")
Error handling and recovery provide the foundation for "Production-Ready" operations, allowing the MCP server to maintain structured reasoning across multiple agent interactions even if the host environment is unstable.
Sources: memory-bank/memories/67944906-43bc-4c85-9424-f2261850bc97.md