2828from typing import Any , Callable , Dict , Optional , Tuple
2929
3030import uvicorn
31-
32- # from mcp.server.fastmcp import Context, FastMCP
33- from fastmcp import Context , FastMCP
31+ from mcp .server .fastmcp import Context , FastMCP
3432from pydantic import BaseModel
3533from starlette .requests import Request
3634from starlette .responses import JSONResponse
@@ -104,8 +102,11 @@ def __init__(
104102 self .adapter = adapter
105103
106104 # Create FastMCP server
107- self .mcp = FastMCP (name = server_name )
108-
105+ self .mcp = FastMCP (
106+ server_name ,
107+ host = "0.0.0.0" ,
108+ port = int (os .environ .get ("PORT" , 8000 )),
109+ )
109110 # Store host and port for later use in run() method
110111 self .host = "0.0.0.0"
111112 self .port = int (os .environ .get ("PORT" , 8000 ))
@@ -129,6 +130,7 @@ def __init__(
129130
130131 self .pool = ThreadPoolExecutor (max_workers = max_workers )
131132
133+ # Reset with seed if provided
132134 self .env , self .obs , _info = self ._new_env (seed = seed )
133135
134136 # Register tools and control plane endpoints
@@ -220,7 +222,8 @@ async def reset_session_endpoint(request: Request) -> JSONResponse:
220222 if not session_id :
221223 return JSONResponse ({"error" : "Missing mcp-session-id header" }, status_code = 400 )
222224 if session_id in self .sessions :
223- env , obs , _ = self ._new_env (seed = seed )
225+ loop = asyncio .get_running_loop ()
226+ env , obs , info = await loop .run_in_executor (self .pool , self ._new_env , seed )
224227 with self .session_lock :
225228 self .sessions [session_id ] = {
226229 "env" : env ,
@@ -269,17 +272,10 @@ async def endpoint_handler(request: Request) -> JSONResponse:
269272 {"error" : f"Session { session_id } not found" },
270273 status_code = 404 ,
271274 )
272- start_time = time .time ()
273- logger .info (
274- f"### 🔍 NEW_ENV_START: timestamp: { start_time } , session_id: { session_id [:8 ] if len (session_id ) > 8 else session_id } ..."
275- )
275+
276276 loop = asyncio .get_running_loop ()
277277 env , obs , info = await loop .run_in_executor (self .pool , self ._new_env , None )
278- # env, obs, info = self._new_env(None)
279- end_time = time .time ()
280- logger .info (
281- f"### 🔍 NEW_ENV_END: timestamp: { end_time } , elapsed: { end_time - start_time :.6f} s, session_id: { session_id [:8 ] if len (session_id ) > 8 else session_id } ..."
282- )
278+
283279 # Initialize session state with extracted seed from session ID
284280 session_data = {
285281 "env" : env ,
@@ -294,6 +290,7 @@ async def endpoint_handler(request: Request) -> JSONResponse:
294290 result = await func (session_data = session_data )
295291 else :
296292 result = func (session_data = session_data )
293+
297294 return JSONResponse (result )
298295
299296 except Exception as e :
@@ -484,78 +481,26 @@ def get_info_endpoint(self, session_data: Dict[str, Any]) -> Dict[str, Any]:
484481 @control_plane_endpoint ("/control/initial_state" )
485482 async def get_initial_state_endpoint (self , session_data : Dict [str , Any ]) -> Dict [str , Any ]:
486483 """Get initial state for this session."""
487- endpoint_start = time .time ()
488484 session_id = session_data .get ("session_id" , "unknown" )
489- logger .info (
490- f"### 🌟 ENDPOINT_START: get_initial_state_endpoint, timestamp: { endpoint_start } , session_id: { session_id [:8 ] if len (session_id ) > 8 else session_id } ..."
491- )
492-
493- env_check_start = time .time ()
494- logger .info (
495- f"### 🔍 ENV_CHECK_START: timestamp: { env_check_start } , elapsed: { env_check_start - endpoint_start :.6f} s, session_id: { session_id [:8 ] if len (session_id ) > 8 else session_id } ..."
496- )
497-
498485 env = session_data .get ("env" )
499486 obs = session_data .get ("obs" )
500-
501- env_check_end = time .time ()
502- logger .info (
503- f"### 🔍 ENV_CHECK_END: timestamp: { env_check_end } , elapsed: { env_check_end - endpoint_start :.6f} s, duration: { env_check_end - env_check_start :.6f} s, env: { env is not None } , obs: { obs is not None } , session_id: { session_id [:8 ] if len (session_id ) > 8 else session_id } ..."
504- )
505-
506487 if env and obs is not None :
507- format_start = time .time ()
508- logger .info (
509- f"### 🔄 FORMAT_OBS_START: timestamp: { format_start } , elapsed: { format_start - endpoint_start :.6f} s, session_id: { session_id [:8 ] if len (session_id ) > 8 else session_id } ..."
510- )
511-
512488 try :
513489 formatted_obs = self .format_observation (obs , env )
514-
515- format_end = time .time ()
516- logger .info (
517- f"### 🔄 FORMAT_OBS_END: timestamp: { format_end } , elapsed: { format_end - endpoint_start :.6f} s, duration: { format_end - format_start :.6f} s, session_id: { session_id [:8 ] if len (session_id ) > 8 else session_id } ..."
518- )
519-
520- endpoint_end = time .time ()
521- logger .info (
522- f"### ✅ ENDPOINT_SUCCESS_END: timestamp: { endpoint_end } , total_duration: { endpoint_end - endpoint_start :.6f} s, session_id: { session_id [:8 ] if len (session_id ) > 8 else session_id } ..."
523- )
524-
525490 return formatted_obs
526491 except Exception as e :
527- error_time = time .time ()
528- logger .error (
529- f"### ❌ FORMAT_OBS_ERROR: timestamp: { error_time } , elapsed: { error_time - endpoint_start :.6f} s, error: { str (e )} , session_id: { session_id [:8 ] if len (session_id ) > 8 else session_id } ..."
530- )
531-
492+ logger .error (f"❌ Error in format_observation: { e } " )
532493 return {
533494 "error" : f"Failed to format observation: { str (e )} " ,
534495 "observation_type" : str (type (obs )),
535496 "session_id" : session_data .get ("session_id" , "unknown" ),
536497 }
537498 else :
538- fallback_start = time .time ()
539- logger .info (
540- f"### 🔄 FALLBACK_START: timestamp: { fallback_start } , elapsed: { fallback_start - endpoint_start :.6f} s, session_id: { session_id [:8 ] if len (session_id ) > 8 else session_id } ..."
541- )
542-
543499 # Fallback if session data is not available
544500 result = {
545501 "observation" : "session_not_initialized" ,
546502 "session_id" : session_data .get ("session_id" , "unknown" ),
547503 }
548-
549- fallback_end = time .time ()
550- logger .info (
551- f"### 🔄 FALLBACK_END: timestamp: { fallback_end } , elapsed: { fallback_end - endpoint_start :.6f} s, duration: { fallback_end - fallback_start :.6f} s, session_id: { session_id [:8 ] if len (session_id ) > 8 else session_id } ..."
552- )
553-
554- endpoint_end = time .time ()
555- logger .info (
556- f"### ✅ ENDPOINT_FALLBACK_END: timestamp: { endpoint_end } , total_duration: { endpoint_end - endpoint_start :.6f} s, session_id: { session_id [:8 ] if len (session_id ) > 8 else session_id } ..."
557- )
558-
559504 return result
560505
561506 def _get_session_control_plane_from_data (self , session_data : Dict [str , Any ]) -> Dict [str , Any ]:
@@ -623,9 +568,9 @@ async def run_with_high_concurrency():
623568
624569 config = uvicorn .Config (
625570 starlette_app ,
626- host = self .host ,
627- port = self .port ,
628- log_level = "info" , # Use default log level instead of accessing settings
571+ host = self .mcp . settings . host ,
572+ port = self .mcp . settings . port ,
573+ log_level = self . mcp . settings . log_level . lower () , # Use default log level instead of accessing settings
629574 proxy_headers = True ,
630575 forwarded_allow_ips = "*" ,
631576 # HIGH CONCURRENCY SETTINGS
0 commit comments