11"""Refactored MCP Sequential Thinking Server with separated concerns and reduced complexity."""
22
33import asyncio
4+ import math
45import sys
6+ from collections import Counter
57from collections .abc import AsyncIterator
68from contextlib import asynccontextmanager
79from html import escape
2830load_dotenv ()
2931logger = setup_logging ()
3032
33+
3134# Application state container for dependency injection
3235class ApplicationContainer :
3336 """Dependency injection container for application state."""
@@ -45,7 +48,9 @@ async def get_thought_processor(self) -> ThoughtProcessor:
4548
4649 async with self ._processor_lock :
4750 if self .thought_processor is None :
48- logger .info ("Initializing ThoughtProcessor with Multi-Thinking workflow" )
51+ logger .info (
52+ "Initializing ThoughtProcessor with Multi-Thinking workflow"
53+ )
4954 self .thought_processor = ThoughtProcessor (self .server_state .session )
5055 return self .thought_processor
5156
@@ -54,6 +59,7 @@ def cleanup(self) -> None:
5459 self .server_state = None
5560 self .thought_processor = None
5661
62+
5763# Application container instance
5864_app_container = ApplicationContainer ()
5965
@@ -122,7 +128,14 @@ def sanitize_and_validate_input(text: str, max_length: int, field_name: str) ->
122128 )
123129
124130 # Multiple bracket/parentheses check
125- bracket_count = text .count ("(" ) + text .count (")" ) + text .count ("[" ) + text .count ("]" ) + text .count ("{" ) + text .count ("}" )
131+ bracket_count = (
132+ text .count ("(" )
133+ + text .count (")" )
134+ + text .count ("[" )
135+ + text .count ("]" )
136+ + text .count ("{" )
137+ + text .count ("}" )
138+ )
126139 if bracket_count > 20 : # Reasonable threshold for normal text
127140 raise ValueError (
128141 f"Excessive brackets/parentheses detected in { field_name } ({ bracket_count } found). "
@@ -263,7 +276,9 @@ async def sequentialthinking(
263276 f"• Consider reducing request frequency\n "
264277 f"• Break complex tasks into smaller chunks"
265278 )
266- logger .warning (f"Rate limit exceeded for thought #{ thoughtNumber } : { e .limit_type } " )
279+ logger .warning (
280+ f"Rate limit exceeded for thought #{ thoughtNumber } : { e .limit_type } "
281+ )
267282 return error_msg
268283 except ValueError as e :
269284 # Request size validation error
@@ -274,7 +289,9 @@ async def sequentialthinking(
274289 f"• Split into multiple sequential thoughts\n "
275290 f"• Remove unnecessary details or formatting"
276291 )
277- logger .warning (f"Request size validation failed for thought #{ thoughtNumber } : { e } " )
292+ logger .warning (
293+ f"Request size validation failed for thought #{ thoughtNumber } : { e } "
294+ )
278295 return error_msg
279296
280297 try :
@@ -385,9 +402,10 @@ def run() -> None:
385402 """Run the MCP server with enhanced error handling and graceful shutdown."""
386403 try :
387404 config = ServerConfig .from_environment ()
388- logger .info (f"Starting Sequential Thinking Server with { config .provider } provider" )
389- except Exception as e :
390- print (_format_startup_error (e ))
405+ logger .info (
406+ f"Starting Sequential Thinking Server with { config .provider } provider"
407+ )
408+ except Exception :
391409 sys .exit (ProcessingDefaults .EXIT_CODE_ERROR )
392410
393411 try :
@@ -403,8 +421,7 @@ def run() -> None:
403421
404422 except Exception as e :
405423 error_msg = _format_server_runtime_error (e )
406- logger .error (error_msg )
407- print (error_msg )
424+ logger .exception (error_msg )
408425 sys .exit (ProcessingDefaults .EXIT_CODE_ERROR )
409426
410427 finally :
@@ -500,14 +517,12 @@ def main() -> None:
500517 try :
501518 run ()
502519 except KeyboardInterrupt :
503- print ("\n 👋 Server stopped by user. Goodbye!" )
504520 sys .exit (0 )
505521 except SystemExit :
506522 # Re-raise SystemExit without additional handling
507523 raise
508524 except Exception as e :
509- error_msg = _format_startup_error (e )
510- print (error_msg )
525+ _format_startup_error (e )
511526 try :
512527 logger .critical (f"Fatal error in main: { e } " , exc_info = True )
513528 except :
0 commit comments