Repository navigation
fix(providers): reject non-object tool-call arguments instead of panicking #9832
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 11 commits
956e37a
3ad8e98
2aa8189
c7a9d6f
5597831
d6fd0db
318d489
6be421d
8bc3cf5
a926b55
2cd76c8
8ba8df2
dd5a6af
00f8525
b4a8407
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -260,11 +260,27 @@ pub fn format_messages_with_options( | |
|
|
||
| tool_calls.as_array_mut().unwrap().push(tool_call_json); | ||
| } | ||
| Err(e) => { | ||
| output.push(json!({ | ||
| "role": "tool", | ||
| "content": format!("Error: {}", e), | ||
| "tool_call_id": request.id | ||
| Err(_e) => { | ||
| // An unparseable tool call still needs a valid assistant | ||
| // `tool_calls` entry. Emitting the error as a bare `role:"tool"` | ||
| // message (the old behavior) leaves the paired tool response — | ||
| // which carries the parse error — as an orphan `role:"tool"` with | ||
| // no preceding assistant `tool_calls`, which strict | ||
| // OpenAI-compatible APIs reject. Emit a placeholder call with the | ||
| // same id so the history stays well-formed; the error rides on the | ||
| // following tool response. | ||
| let tool_calls = converted | ||
| .as_object_mut() | ||
| .unwrap() | ||
| .entry("tool_calls") | ||
| .or_insert(json!([])); | ||
| tool_calls.as_array_mut().unwrap().push(json!({ | ||
| "id": request.id, | ||
| "type": "function", | ||
| "function": { | ||
| "name": "unparseable_tool_call", | ||
| "arguments": "{}", | ||
| } | ||
| })); | ||
| } | ||
| }, | ||
|
|
@@ -654,14 +670,43 @@ pub fn response_to_message(response: &Value) -> anyhow::Result<Message> { | |
| )); | ||
| } else { | ||
| match safely_parse_json(&arguments_str) { | ||
| Ok(params) => { | ||
| // Valid JSON, and an object: the normal path. | ||
| Ok(params) if params.is_object() => { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
This guard only protects the non-streaming Useful? React with 👍 / 👎. |
||
| content.push(MessageContent::tool_request_with_metadata( | ||
| id, | ||
| Ok(CallToolRequestParams::new(function_name) | ||
| .with_arguments(object(params))), | ||
| metadata.as_ref(), | ||
| )); | ||
| } | ||
| // Valid JSON but NOT an object (a bare array/string/number). | ||
| // Weaker models emit this; surface a tool error so the model | ||
| // retries with a proper object instead of crashing the run | ||
| // (rmcp's `object()` debug-asserts on non-objects). | ||
| Ok(other) => { | ||
| let error = ErrorData { | ||
| code: ErrorCode::INVALID_PARAMS, | ||
| message: Cow::from(format!( | ||
| "Tool arguments for id {} must be a JSON object, got {}. Raw arguments: '{}'", | ||
| id, | ||
| match other { | ||
| Value::Array(_) => "an array", | ||
| Value::String(_) => "a string", | ||
| Value::Number(_) => "a number", | ||
| Value::Bool(_) => "a boolean", | ||
| Value::Null => "null", | ||
| Value::Object(_) => unreachable!(), | ||
| }, | ||
| arguments_str | ||
| )), | ||
| data: None, | ||
| }; | ||
| content.push(MessageContent::tool_request_with_metadata( | ||
| id, | ||
| Err(error), | ||
| metadata.as_ref(), | ||
|
Comment on lines
+752
to
+755
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
For the newly handled case where a model emits valid JSON that is not an object, this creates a Useful? React with 👍 / 👎. |
||
| )); | ||
| } | ||
| Err(e) => { | ||
| let error = ErrorData { | ||
| code: ErrorCode::INVALID_PARAMS, | ||
|
|
@@ -1103,13 +1148,29 @@ where | |
| }; | ||
|
|
||
| let content = match parsed { | ||
| Ok(params) => { | ||
| // Valid JSON, and an object: the normal path. | ||
| Ok(params) if params.is_object() => { | ||
| MessageContent::tool_request_with_metadata( | ||
| id.clone(), | ||
| Ok(CallToolRequestParams::new(function_name.clone()).with_arguments(object(params))), | ||
| metadata.as_ref(), | ||
| ) | ||
| }, | ||
| // Valid JSON but NOT an object (a bare array/string/number). | ||
| // Surface a tool error so the model retries instead of | ||
| // crashing the run (rmcp's `object()` debug-asserts on | ||
| // non-objects). Mirrors the non-streaming decoder. | ||
| Ok(_) => { | ||
| let error = ErrorData { | ||
| code: ErrorCode::INVALID_PARAMS, | ||
| message: Cow::from(format!( | ||
| "Tool arguments for id {} must be a JSON object. Raw arguments: '{}'", | ||
| id, arguments | ||
| )), | ||
| data: None, | ||
| }; | ||
| MessageContent::tool_request_with_metadata(id.clone(), Err(error), metadata.as_ref()) | ||
| } | ||
| Err(e) => { | ||
| let error = ErrorData { | ||
| code: ErrorCode::INVALID_PARAMS, | ||
|
|
@@ -1945,6 +2006,36 @@ mod tests { | |
| Ok(()) | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_response_to_message_non_object_arguments() -> anyhow::Result<()> { | ||
| // Weaker models sometimes emit tool arguments that are valid JSON but | ||
| // not an object (here, a bare array). This must surface as a tool error, | ||
| // NOT panic via rmcp's `object()` debug-assert. | ||
| let mut response: Value = serde_json::from_str(OPENAI_TOOL_USE_RESPONSE)?; | ||
| response["choices"][0]["message"]["tool_calls"][0]["function"]["arguments"] = | ||
| json!("[1, 2, 3]"); | ||
|
|
||
| let message = response_to_message(&response)?; | ||
|
|
||
| if let MessageContent::ToolRequest(request) = &message.content[0] { | ||
| match &request.tool_call { | ||
| Err(ErrorData { | ||
| code: ErrorCode::INVALID_PARAMS, | ||
| message: msg, | ||
| data: None, | ||
| }) => { | ||
| assert!(msg.contains("must be a JSON object")); | ||
| assert!(msg.contains("an array")); | ||
| } | ||
| _ => panic!("Expected InvalidParameters error for non-object args"), | ||
| } | ||
| } else { | ||
| panic!("Expected ToolRequest content"); | ||
| } | ||
|
|
||
| Ok(()) | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_response_to_message_empty_argument() -> anyhow::Result<()> { | ||
| let mut response: Value = serde_json::from_str(OPENAI_TOOL_USE_RESPONSE)?; | ||
|
|
@@ -2733,6 +2824,38 @@ data: [DONE]"#; | |
| panic!("Expected tool call message with nested extra_content metadata"); | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn test_streaming_non_object_arguments_does_not_panic() -> anyhow::Result<()> { | ||
| // Streamed tool call whose arguments are valid JSON but NOT an object. | ||
| // Must yield an INVALID_PARAMS tool error, not panic via rmcp `object()`. | ||
| let response_lines = r#"data: {"model":"test-model","choices":[{"delta":{"role":"assistant","tool_calls":[{"id":"call_bad","function":{"name":"test_tool","arguments":"[1, 2, 3]"},"type":"function","index":0}]},"index":0,"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":100,"completion_tokens":10,"total_tokens":110},"object":"chat.completion.chunk","id":"test-id","created":1234567890} | ||
| data: [DONE]"#; | ||
|
|
||
| let response_stream = | ||
| tokio_stream::iter(response_lines.lines().map(|line| Ok(line.to_string()))); | ||
| let messages = response_to_streaming_message(response_stream); | ||
| pin!(messages); | ||
|
|
||
| while let Some(Ok((message, _usage))) = messages.next().await { | ||
| if let Some(msg) = message { | ||
| if let MessageContent::ToolRequest(request) = &msg.content[0] { | ||
| match &request.tool_call { | ||
| Err(ErrorData { | ||
| code: ErrorCode::INVALID_PARAMS, | ||
| message: m, | ||
| .. | ||
| }) => { | ||
| assert!(m.contains("must be a JSON object")); | ||
| return Ok(()); | ||
| } | ||
| _ => panic!("expected INVALID_PARAMS for non-object streamed args"), | ||
| } | ||
| } | ||
| } | ||
| } | ||
| panic!("expected a tool request message"); | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn test_streaming_response_extracts_inline_think_blocks() -> anyhow::Result<()> { | ||
| let response_lines = concat!( | ||
|
|
@@ -3554,4 +3677,48 @@ data: [DONE]"#; | |
| assert!(!is_valid_function_name("hello world")); | ||
| assert!(!is_valid_function_name("hello@world")); | ||
| } | ||
|
|
||
| #[test] | ||
| fn formatter_post_parse_error_history_is_wellformed() { | ||
| use rmcp::model::{ErrorCode, ErrorData}; | ||
| let err = ErrorData::new( | ||
| ErrorCode::INVALID_PARAMS, | ||
| "Tool arguments for id call_bad must be a JSON object".to_string(), | ||
| None, | ||
| ); | ||
| // Shape the agent loop builds today for a failed parse: | ||
| let request_msg = Message::assistant().with_tool_request("call_bad", Err(err.clone())); | ||
| let mut final_resp = Message::user(); | ||
| final_resp.add_tool_response_with_metadata("call_bad", Err(err), None); | ||
| let messages = vec![ | ||
| Message::user().with_text("do the thing"), | ||
| request_msg, | ||
| final_resp, | ||
| ]; | ||
|
|
||
| let spec = format_messages(&messages, &ImageFormat::OpenAi); | ||
|
|
||
| let mut open = std::collections::HashSet::new(); | ||
| for m in &spec { | ||
| match m.get("role").and_then(|v| v.as_str()) { | ||
| Some("assistant") => { | ||
| for tc in m | ||
| .get("tool_calls") | ||
| .and_then(|v| v.as_array()) | ||
| .into_iter() | ||
| .flatten() | ||
| { | ||
| if let Some(id) = tc.get("id").and_then(|v| v.as_str()) { | ||
| open.insert(id.to_string()); | ||
| } | ||
| } | ||
| } | ||
| Some("tool") => { | ||
| let id = m.get("tool_call_id").and_then(|v| v.as_str()).unwrap_or(""); | ||
| assert!(open.contains(id), "orphan role:tool message for id {id:?}"); | ||
| } | ||
| _ => {} | ||
| } | ||
| } | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2194,46 +2194,73 @@ impl Agent { | |
| .collect(); | ||
|
|
||
| for request in frontend_requests.iter().chain(remaining_requests.iter()) { | ||
| if request.tool_call.is_ok() { | ||
| let mut request_msg = Message::assistant() | ||
| .with_id(format!("msg_{}", Uuid::new_v4())); | ||
|
|
||
| // Providers like Kimi require reasoning_content on all assistant | ||
| // messages with tool_calls when thinking mode is enabled. | ||
| for rc in &reasoning_content { | ||
| request_msg = request_msg.with_content(rc.clone()); | ||
| } | ||
| let mut request_msg = Message::assistant() | ||
| .with_id(format!("msg_{}", Uuid::new_v4())); | ||
|
|
||
| request_msg = request_msg | ||
| .with_tool_request_with_metadata( | ||
| request.id.clone(), | ||
| request.tool_call.clone(), | ||
| request.metadata.as_ref(), | ||
| request.tool_meta.clone(), | ||
| ); | ||
| let final_response = request_to_response_map | ||
| // Providers like Kimi require reasoning_content on all assistant | ||
| // messages with tool_calls when thinking mode is enabled. | ||
| for rc in &reasoning_content { | ||
| request_msg = request_msg.with_content(rc.clone()); | ||
| } | ||
|
|
||
| // For an unparseable tool call (Err), store a valid | ||
| // placeholder Ok tool-call in history instead of the Err. This | ||
| // keeps the conversation well-formed through EVERY provider | ||
| // formatter's normal Ok path — so we don't have to special-case | ||
| // each formatter's Err arm — and preserves provider metadata | ||
| // (e.g. thought signatures), which is passed through below and | ||
| // copied by the Ok path. The actual parse error rides on the | ||
| // paired tool response. | ||
| let history_tool_call = match &request.tool_call { | ||
| Ok(_) => request.tool_call.clone(), | ||
| Err(_) => Ok(CallToolRequestParams::new( | ||
| "unparseable_tool_call", | ||
| ) | ||
| .with_arguments(serde_json::Map::new())), | ||
|
Comment on lines
+2314
to
+2319
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When a provider returns an unparseable argument payload for a valid tool, this stores the history as a call to Useful? React with 👍 / 👎. |
||
| }; | ||
| request_msg = request_msg | ||
| .with_tool_request_with_metadata( | ||
| request.id.clone(), | ||
| history_tool_call, | ||
| request.metadata.as_ref(), | ||
|
Comment on lines
+2321
to
+2325
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When Useful? React with 👍 / 👎.
Comment on lines
+2321
to
+2325
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Fresh evidence: Bedrock still emits Useful? React with 👍 / 👎. |
||
| request.tool_meta.clone(), | ||
| ); | ||
|
|
||
| let final_response = match &request.tool_call { | ||
| Ok(_) => request_to_response_map | ||
| .remove(&request.id) | ||
| .unwrap_or_else(|| Message::user().with_generated_id()); | ||
| // Response placeholder is created before tools run, so clamp request to avoid inverted ordering. | ||
| if request_msg.created > final_response.created { | ||
| request_msg.created = final_response.created; | ||
| .unwrap_or_else(|| Message::user().with_generated_id()), | ||
| Err(error) => { | ||
| error!("Tool call could not be parsed: {error}"); | ||
| let mut response = request_to_response_map | ||
| .remove(&request.id) | ||
| .unwrap_or_else(|| Message::user().with_generated_id()); | ||
| // Only feed the parse error back if this id isn't | ||
| // already answered. In Chat mode the skip branch above | ||
| // already added a tool response for it; adding another | ||
| // here would duplicate the tool_call_id (which strict | ||
| // providers reject). | ||
| let already_answered = response.content.iter().any(|c| { | ||
| matches!(c, MessageContent::ToolResponse(r) if r.id == request.id) | ||
| }); | ||
| if !already_answered { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Fresh evidence in this revision is that Useful? React with 👍 / 👎. |
||
| response.add_tool_response_with_metadata( | ||
| request.id.clone(), | ||
| Err(error.clone()), | ||
| request.metadata.as_ref(), | ||
| ); | ||
| } | ||
| response | ||
| } | ||
| messages_to_add.push(request_msg); | ||
| yield AgentEvent::Message(final_response.clone()); | ||
| messages_to_add.push(final_response); | ||
| } else { | ||
| error!( | ||
| "Tool call could not be parsed: {}", | ||
| request.tool_call.as_ref().unwrap_err(), | ||
| ); | ||
| yield AgentEvent::Message( | ||
| Message::assistant().with_text( | ||
| "A tool call could not be parsed — the response may have been truncated. Try breaking the task into smaller steps or resending your message." | ||
| ) | ||
| ); | ||
| exit_chat = true; | ||
| break; | ||
| }; | ||
|
|
||
| // Response placeholder is created before tools run, so clamp request to avoid inverted ordering. | ||
| if request_msg.created > final_response.created { | ||
| request_msg.created = final_response.created; | ||
| } | ||
| messages_to_add.push(request_msg); | ||
| yield AgentEvent::Message(final_response.clone()); | ||
| messages_to_add.push(final_response); | ||
| } | ||
|
|
||
| no_tools_called = false; | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When the malformed tool call carried provider metadata, this placeholder drops it even though the normal
Okbranch copies everyrequest.metadatafield onto the replayed tool call. The new decoders keep metadata onToolRequest(Err)(for example streamed OpenAI-compatible calls attachthoughtSignature/extra_contentbefore returning the error), and the retry path inagent.rsnow relies on this formatter to replay that assistant call. For Gemini-style OpenAI-compatible endpoints, losing the thought signature on exactly these parse-error retries can make the next request fail or lose reasoning continuity before the model gets a chance to correct the arguments; copy the metadata onto the placeholder as theOkbranch does.Useful? React with 👍 / 👎.