@@ -186,8 +186,6 @@ export class McpClient {
186186 for ( const toolCall of Object . values ( finalToolCalls ) ) {
187187 const toolName = toolCall . function . name ?? "unknown" ;
188188 /// TODO(Fix upstream type so this is always a string)^
189- const toolArgs = toolCall . function . arguments === "" ? { } : JSON . parse ( toolCall . function . arguments ) ;
190-
191189 const toolMessage : ChatCompletionInputMessageTool = {
192190 role : "tool" ,
193191 tool_call_id : toolCall . id ,
@@ -198,11 +196,29 @@ export class McpClient {
198196 messages . push ( toolMessage ) ;
199197 return yield toolMessage ;
200198 }
199+ let toolArgs : Record < string , unknown > = { } ;
200+ try {
201+ toolArgs = toolCall . function . arguments === "" ? { } : JSON . parse ( toolCall . function . arguments ) ;
202+ } catch ( error ) {
203+ if ( error instanceof SyntaxError ) {
204+ toolMessage . content = `Invalid JSON generated by the model: ${ error . message } ` ;
205+ messages . push ( toolMessage ) ;
206+ yield toolMessage ;
207+ continue ;
208+ } else {
209+ throw error ;
210+ }
211+ }
212+
201213 /// Get the appropriate session for this tool
202214 const client = this . clients . get ( toolName ) ;
203215 if ( client ) {
204- const result = await client . callTool ( { name : toolName , arguments : toolArgs , signal : opts . abortSignal } ) ;
205- toolMessage . content = ResultFormatter . format ( result ) ;
216+ try {
217+ const result = await client . callTool ( { name : toolName , arguments : toolArgs , signal : opts . abortSignal } ) ;
218+ toolMessage . content = ResultFormatter . format ( result ) ;
219+ } catch ( error ) {
220+ toolMessage . content = `Error: MCP tool call failed with error message: ${ error } ` ;
221+ }
206222 } else {
207223 toolMessage . content = `Error: No session found for tool: ${ toolName } ` ;
208224 }
0 commit comments