@@ -119,26 +119,42 @@ async def _run_server(self, server_params: StdioServerParameters) -> None:
119119 try :
120120 while True :
121121 # Get message from local server
122- session_message = await self ._read_stream .receive ()
123- message = session_message .message
124- # For responses, determine which request_id to use
125- if self ._is_response (message ):
126- message_id = self ._get_message_id (message )
127- if message_id and message_id in self ._active_requests :
128- # Use the stored request_id for this response
129- request_id = self ._active_requests [message_id ]
130- # Send with the matched request_id
131- await self ._send_message (message , request_id )
132- # Clean up the mapping after use
133- del self ._active_requests [message_id ]
122+ session_message = None
123+ try :
124+ session_message = await self ._read_stream .receive ()
125+ message = session_message .message
126+ # For responses, determine which request_id to use
127+ if self ._is_response (message ):
128+ message_id = self ._get_message_id (message )
129+ if message_id and message_id in self ._active_requests :
130+ # Use the stored request_id for this response
131+ request_id = self ._active_requests [message_id ]
132+ # Send with the matched request_id
133+ await self ._send_message (message , request_id )
134+ # Clean up the mapping after use
135+ del self ._active_requests [message_id ]
136+ else :
137+ # If no mapping found, use the last known request_id
138+ await self ._send_message (
139+ message , self ._last_request_id
140+ )
134141 else :
135- # If no mapping found, use the last known request_id
136- await self ._send_message (
137- message , self ._last_request_id
138- )
139- else :
140- # For non-responses, use the last known request_id
141- await self ._send_message (message , self ._last_request_id )
142+ # For non-responses, use the last known request_id
143+ await self ._send_message (message , self ._last_request_id )
144+ except Exception as e :
145+ if session_message :
146+ logger .info (session_message )
147+ logger .error (
148+ f"Error processing message for session { self ._session_id } : { e } " ,
149+ exc_info = True ,
150+ )
151+ await self ._send_message (
152+ JSONRPCError (
153+ code = - 32000 ,
154+ message = f"Error processing message: { session_message } { e } " ,
155+ ),
156+ self ._last_request_id ,
157+ )
142158 finally :
143159 # Cancel the consumer when we exit the loop
144160 consumer_task .cancel ()
@@ -158,6 +174,7 @@ async def _run_server(self, server_params: StdioServerParameters) -> None:
158174 self ._server_stderr_output = stderr_temp .read ().decode (
159175 "utf-8" , errors = "replace"
160176 )
177+ logger .error (self ._server_stderr_output )
161178 # The context managers will handle cleanup of resources
162179
163180 def _run_server_callback (self , task ):
0 commit comments