diff --git a/crates/tool_parser/src/parsers/helpers.rs b/crates/tool_parser/src/parsers/helpers.rs
index d57bea2634..ac34fd82e8 100644
--- a/crates/tool_parser/src/parsers/helpers.rs
+++ b/crates/tool_parser/src/parsers/helpers.rs
@@ -423,7 +423,13 @@ pub(crate) fn handle_json_tool_streaming(
// them either because only this branch populates `prev_tool_call_arr`.
// `current_tool_name_sent` implies `current_tool_id >= 0`.
if *current_tool_name_sent {
- let Some(cur_arguments) = current_tool_call.get("arguments") else {
+ // A complete call without arguments takes `{}`, as in the
+ // non-streaming parse.
+ let empty_obj = Value::Object(serde_json::Map::new());
+ let Some(cur_arguments) = current_tool_call
+ .get("arguments")
+ .or_else(|| is_complete.then_some(&empty_obj))
+ else {
return Ok(result);
};
let tool_id = *current_tool_id as usize;
diff --git a/crates/tool_parser/src/parsers/minimax_m2.rs b/crates/tool_parser/src/parsers/minimax_m2.rs
index f219512b39..8097889f15 100644
--- a/crates/tool_parser/src/parsers/minimax_m2.rs
+++ b/crates/tool_parser/src/parsers/minimax_m2.rs
@@ -467,7 +467,15 @@ impl ToolParser for MinimaxM2Parser {
let tool_id = self.current_tool_id as usize;
if tool_id < self.streamed_args_for_tool.len() {
let current_streamed = &self.streamed_args_for_tool[tool_id];
- if !current_streamed.is_empty() && !current_streamed.ends_with('}') {
+ if current_streamed.is_empty() {
+ // No parameters: `{}`, as in the non-streaming parse.
+ calls.push(ToolCallItem {
+ tool_index: tool_id,
+ name: None,
+ parameters: "{}".to_string(),
+ });
+ self.streamed_args_for_tool[tool_id].push_str("{}");
+ } else if !current_streamed.ends_with('}') {
// Count opening and closing braces to check if JSON is complete
let open_braces = current_streamed.matches('{').count();
let close_braces = current_streamed.matches('}').count();
diff --git a/crates/tool_parser/tests/tool_parser_cohere.rs b/crates/tool_parser/tests/tool_parser_cohere.rs
index 8a5da2ccca..81a23ad25b 100644
--- a/crates/tool_parser/tests/tool_parser_cohere.rs
+++ b/crates/tool_parser/tests/tool_parser_cohere.rs
@@ -250,6 +250,42 @@ async fn test_cohere_streaming_basic() {
assert_eq!(tool_names[0], "get_weather");
}
+#[tokio::test]
+async fn test_cohere_streaming_empty_parameters() {
+ // A streamed call without parameters ends with `{}`, as parse_complete returns.
+ let tools = common::create_test_tools();
+ for chunks in [
+ vec![
+ "<|START_ACTION|>",
+ r#"{"tool_name": "get_weather"}"#,
+ "<|END_ACTION|>",
+ ],
+ vec![
+ "<|START_ACTION|>",
+ "{",
+ "\"tool_name\"",
+ ": ",
+ "\"get_weather\"",
+ "}",
+ "<|END_ACTION|>",
+ ],
+ ] {
+ let mut parser = CohereParser::new();
+ let mut name = None;
+ let mut arguments = String::new();
+ for chunk in chunks {
+ let result = parser.parse_incremental(chunk, &tools).await.unwrap();
+ for call in result.calls {
+ assert_eq!(call.tool_index, 0);
+ name = call.name.or(name);
+ arguments.push_str(&call.parameters);
+ }
+ }
+ assert_eq!(name.as_deref(), Some("get_weather"));
+ assert_eq!(arguments, "{}");
+ }
+}
+
#[tokio::test]
async fn test_cohere_reset() {
let mut parser = CohereParser::new();
diff --git a/crates/tool_parser/tests/tool_parser_minimax_m2.rs b/crates/tool_parser/tests/tool_parser_minimax_m2.rs
index ea31ad8bce..7ed608795d 100644
--- a/crates/tool_parser/tests/tool_parser_minimax_m2.rs
+++ b/crates/tool_parser/tests/tool_parser_minimax_m2.rs
@@ -548,6 +548,35 @@ async fn test_minimax_empty_parameters() {
assert_eq!(args, serde_json::json!({}));
}
+#[tokio::test]
+async fn test_minimax_streaming_empty_parameters() {
+ // A streamed call without parameters ends with `{}`, as parse_complete returns.
+ let tools = create_test_tools();
+ for chunks in [
+ vec!["\n\n\n"],
+ vec![
+ "",
+ "\n",
+ "\n",
+ "\n",
+ ],
+ ] {
+ let mut parser = MinimaxM2Parser::new();
+ let mut name = None;
+ let mut arguments = String::new();
+ for chunk in chunks {
+ let result = parser.parse_incremental(chunk, &tools).await.unwrap();
+ for call in result.calls {
+ assert_eq!(call.tool_index, 0);
+ name = call.name.or(name);
+ arguments.push_str(&call.parameters);
+ }
+ }
+ assert_eq!(name.as_deref(), Some("get_weather"));
+ assert_eq!(arguments, "{}");
+ }
+}
+
#[tokio::test]
async fn test_minimax_multiline_parameter_values() {
let parser = MinimaxM2Parser::new();
diff --git a/crates/tool_parser/tests/tool_parser_streaming_flush.rs b/crates/tool_parser/tests/tool_parser_streaming_flush.rs
index cf5f36ce6b..7fd736325b 100644
--- a/crates/tool_parser/tests/tool_parser_streaming_flush.rs
+++ b/crates/tool_parser/tests/tool_parser_streaming_flush.rs
@@ -9,7 +9,7 @@
//! empty stream — no tool_call deltas AND no content deltas — while the
//! non-streaming path correctly fell back to returning the text as content.
//!
-//! Four properties are covered here:
+//! Five properties are covered here:
//! 1. Text that is definitively not a declared tool call (complete JSON with
//! a missing or undeclared name) is surfaced as normal text mid-stream
//! instead of being buffered forever or silently dropped, while legitimate
@@ -22,6 +22,8 @@
//! 4. A call whose name and arguments both land in one chunk streams *both*
//! in that chunk. There is no later parser call to fall back on, so a name
//! without arguments would reach the client as an unusable tool call.
+//! 5. A complete call without arguments streams `{}`, as the non-streaming
+//! parse returns, rather than a name alone.
mod common;
use common::{create_test_tools, streaming_helpers};
@@ -368,6 +370,38 @@ async fn streaming_never_swallows_content() {
}
}
+#[tokio::test]
+async fn a_call_without_arguments_streams_an_empty_object() {
+ let cases: [(&str, MakeParser, &[&str]); 4] = [
+ ("json", json, &[r#"{"name": "get_weather"}"#]),
+ ("llama", llama, &[r#"{"name": "get_weather"}"#]),
+ (
+ "mistral",
+ mistral,
+ &[r#"[TOOL_CALLS] [{"name": "get_weather"}]"#],
+ ),
+ (
+ "qwen",
+ qwen,
+ &["\n{\"name\": \"get_weather\"}\n"],
+ ),
+ ];
+ for (label, make, whole) in cases {
+ for feed in [Feed::Chunks(whole), Feed::Realistic(whole[0])] {
+ let mut parser = make();
+ let (text, calls) = stream(parser.as_mut(), &feed).await;
+ assert_eq!(text, "", "[{label}] streamed content");
+ assert_eq!(
+ announced(&calls),
+ Some("get_weather"),
+ "[{label}] tool call"
+ );
+ assert_eq!(streamed_args(&calls), "{}", "[{label}] arguments");
+ assert_eq!(parser.take_unstreamed_normal_text(), "", "[{label}] flush");
+ }
+ }
+}
+
#[tokio::test]
async fn partial_declared_name_keeps_buffering() {
let mut parser = LlamaParser::new();
diff --git a/model_gateway/src/routers/grpc/regular/processor.rs b/model_gateway/src/routers/grpc/regular/processor.rs
index 190c3698c7..a92f3af0b6 100644
--- a/model_gateway/src/routers/grpc/regular/processor.rs
+++ b/model_gateway/src/routers/grpc/regular/processor.rs
@@ -755,12 +755,13 @@ impl ResponseProcessor {
.and_then(|v| v.as_str().map(String::from))
});
- let stop_reason = if tool_calls.is_some() || finish_reason_str == "tool_calls" {
+ // Parsed calls do not override a truncation, as in Chat.
+ let stop_reason = if finish_reason_str == "length" {
+ Some(messages::StopReason::MaxTokens)
+ } else if tool_calls.is_some() || finish_reason_str == "tool_calls" {
Some(messages::StopReason::ToolUse)
} else if stop_sequence.is_some() {
Some(messages::StopReason::StopSequence)
- } else if finish_reason_str == "length" {
- Some(messages::StopReason::MaxTokens)
} else {
Some(messages::StopReason::EndTurn)
};
diff --git a/model_gateway/src/routers/grpc/regular/responses/common.rs b/model_gateway/src/routers/grpc/regular/responses/common.rs
index ee06ae88a2..0272041a97 100644
--- a/model_gateway/src/routers/grpc/regular/responses/common.rs
+++ b/model_gateway/src/routers/grpc/regular/responses/common.rs
@@ -214,6 +214,20 @@ pub(super) fn apply_mcp_tool_call_limit(
)
}
+/// Whether a server call among `calls` has arguments that are not JSON. A
+/// parser can report a call's name before its arguments, so a call whose
+/// output was cut short or failed to parse arrives without them. Like the
+/// calls of a truncated or failed generation, it must not be dispatched.
+pub(super) fn has_unfinished_mcp_call(
+ calls: &[ExtractedToolCall],
+ session: &McpToolSession<'_>,
+) -> bool {
+ calls.iter().any(|call| {
+ session.has_exposed_tool(&call.name)
+ && serde_json::from_str::(&call.arguments).is_err()
+ })
+}
+
/// Extract all tool calls from chat response (for parallel tool call support)
pub(super) fn extract_all_tool_calls_from_chat(
response: &openai_protocol::chat::ChatCompletionResponse,
diff --git a/model_gateway/src/routers/grpc/regular/responses/non_streaming.rs b/model_gateway/src/routers/grpc/regular/responses/non_streaming.rs
index 909eba028f..1bea28c23b 100644
--- a/model_gateway/src/routers/grpc/regular/responses/non_streaming.rs
+++ b/model_gateway/src/routers/grpc/regular/responses/non_streaming.rs
@@ -18,8 +18,9 @@ use tracing::{debug, error, trace};
use super::{
common::{
apply_mcp_tool_call_limit, build_next_request, convert_mcp_tools_to_chat_tools,
- extract_all_tool_calls_from_chat, load_conversation_history, prepare_chat_tools_and_choice,
- ExtractedToolCall, McpToolCallLimit, ResponsesCallContext, ToolLoopState,
+ extract_all_tool_calls_from_chat, has_unfinished_mcp_call, load_conversation_history,
+ prepare_chat_tools_and_choice, ExtractedToolCall, McpToolCallLimit, ResponsesCallContext,
+ ToolLoopState,
},
conversions,
};
@@ -216,12 +217,14 @@ pub(super) async fn execute_tool_loop(
.collect();
// A truncated or failed generation must never dispatch tools, even if a complete
- // call was parsed before the engine stopped. Match the streaming loop.
+ // call was parsed before the engine stopped, and neither must a server call the
+ // generation did not finish. Match the streaming loop.
let generation_interrupted = chat_response
.choices
.first()
.and_then(|choice| choice.finish_reason.as_deref())
- .is_some_and(|reason| matches!(reason, "length" | "failed" | "error"));
+ .is_some_and(|reason| matches!(reason, "length" | "failed" | "error"))
+ || has_unfinished_mcp_call(&tool_calls, &session);
if tool_calls.is_empty() || generation_interrupted {
// No more tool calls, we're done
trace!(
diff --git a/model_gateway/src/routers/grpc/regular/responses/streaming.rs b/model_gateway/src/routers/grpc/regular/responses/streaming.rs
index b94a9d4769..299d81b325 100644
--- a/model_gateway/src/routers/grpc/regular/responses/streaming.rs
+++ b/model_gateway/src/routers/grpc/regular/responses/streaming.rs
@@ -38,8 +38,8 @@ use uuid::Uuid;
use super::{
common::{
apply_mcp_tool_call_limit, build_next_request, convert_mcp_tools_to_chat_tools,
- extract_all_tool_calls_from_chat, prepare_chat_tools_and_choice, ExtractedToolCall,
- McpToolCallLimit, ResponsesCallContext, ToolLoopState,
+ extract_all_tool_calls_from_chat, has_unfinished_mcp_call, prepare_chat_tools_and_choice,
+ ExtractedToolCall, McpToolCallLimit, ResponsesCallContext, ToolLoopState,
},
conversions,
};
@@ -685,6 +685,10 @@ async fn execute_tool_loop_streaming_internal(
// Check for tool calls (extract all of them for parallel execution)
let tool_calls = extract_all_tool_calls_from_chat(&accumulated_response);
+ // Neither can a server call the generation did not finish.
+ if has_unfinished_mcp_call(&tool_calls, &session) {
+ break None;
+ }
if !tool_calls.is_empty() {
trace!(
diff --git a/model_gateway/src/routers/grpc/regular/streaming.rs b/model_gateway/src/routers/grpc/regular/streaming.rs
index fa22f92c1a..92026b08c5 100644
--- a/model_gateway/src/routers/grpc/regular/streaming.rs
+++ b/model_gateway/src/routers/grpc/regular/streaming.rs
@@ -2663,13 +2663,15 @@ impl StreamingProcessor {
.await?;
}
- // Phase 4: Emit message_delta with stop_reason and usage
- let stop_reason = if has_tool_calls || finish_reason_str == "tool_calls" {
+ // Phase 4: Emit message_delta with stop_reason and usage. A truncation
+ // stays max_tokens after a tool call started, as Chat keeps `length`:
+ // the call may be cut short.
+ let stop_reason = if finish_reason_str == "length" {
+ Some(messages::StopReason::MaxTokens)
+ } else if has_tool_calls || finish_reason_str == "tool_calls" {
Some(messages::StopReason::ToolUse)
} else if matched_stop.is_some() {
Some(messages::StopReason::StopSequence)
- } else if finish_reason_str == "length" {
- Some(messages::StopReason::MaxTokens)
} else {
Some(messages::StopReason::EndTurn)
};
diff --git a/model_gateway/src/routers/grpc/regular/streaming/eof_tests.rs b/model_gateway/src/routers/grpc/regular/streaming/eof_tests.rs
index 2787a00d01..9236d23947 100644
--- a/model_gateway/src/routers/grpc/regular/streaming/eof_tests.rs
+++ b/model_gateway/src/routers/grpc/regular/streaming/eof_tests.rs
@@ -17,7 +17,10 @@ use tokio::{net::TcpListener, task::JoinHandle};
use tonic::codec::Codec;
use super::*;
-use crate::{routers::common::sse::SseReceiver, worker::WorkerRegistry};
+use crate::{
+ routers::{common::sse::SseReceiver, grpc::regular::processor::ResponseProcessor},
+ worker::WorkerRegistry,
+};
#[derive(Default)]
struct CharacterTokenizer {
@@ -464,6 +467,108 @@ async fn messages_eof_emits_thinking_tail_before_block_stop() {
}
}
+/// A Messages response to `text` through the `qwen_xml` tool parser, which
+/// reports a call's name before its arguments: the type of each content block
+/// and the stop reason.
+async fn qwen_xml_messages(text: &str, finish: &str, stream: bool) -> (Vec, String) {
+ let resolver = || {
+ utils::ParserResolver::new(
+ Arc::new(WorkerRegistry::new()),
+ Some("qwen_xml".to_string()),
+ None,
+ )
+ };
+ let request = serde_json::from_value::(serde_json::json!({
+ "model": "eof-test", "max_tokens": 16,
+ "messages": [{"role": "user", "content": "weather?"}],
+ "tools": [{"name": "lookup", "input_schema": {"type": "object", "properties": {}}}]
+ }))
+ .expect("messages request");
+ let spec = MessagesResponseSpec::from(&request);
+ let mut last = complete(0, finish);
+ if let Some(GenerationEvent::Complete(complete)) = &mut last.response {
+ complete.output_ids = text.chars().map(u32::from).collect();
+ }
+ let (grpc_stream, server) = scripted_stream(vec![chunk(0, text), last], "0").await;
+ let tokenizer: Arc = Arc::new(CharacterTokenizer::default());
+ let read = if stream {
+ let processor = StreamingProcessor::new(
+ ToolParserFactory::new(),
+ ReasoningParserFactory::new(),
+ resolver(),
+ "vllm",
+ );
+ let (tx, rx) = sse_channel();
+ let result = processor
+ .process_messages_streaming_chunks(
+ grpc_stream,
+ dispatch(),
+ tokenizer,
+ (None, None, false, false, false),
+ spec,
+ &tx,
+ None,
+ )
+ .await;
+ drop(tx);
+ assert!(result.is_ok(), "{result:?}");
+ let events = collect_events(rx).await;
+ let blocks = events
+ .iter()
+ .filter(|event| event["type"] == "content_block_start")
+ .map(|event| event["content_block"]["type"].as_str().unwrap().to_string())
+ .collect();
+ let delta = events.iter().find(|event| event["type"] == "message_delta");
+ let stop_reason = &delta.unwrap()["delta"]["stop_reason"];
+ (blocks, stop_reason.as_str().unwrap().to_string())
+ } else {
+ let processor = ResponseProcessor::new(
+ ToolParserFactory::new(),
+ ReasoningParserFactory::new(),
+ resolver(),
+ );
+ let mut decoder = utils::create_stop_decoder(&tokenizer, None, None, false, false, false);
+ let message = processor
+ .process_non_streaming_messages_response(
+ context::ExecutionResult::Single {
+ stream: grpc_stream,
+ },
+ spec,
+ dispatch(),
+ tokenizer,
+ &mut decoder,
+ )
+ .await
+ .unwrap_or_else(|response| panic!("{}", response.status()));
+ let message = serde_json::to_value(message).unwrap();
+ let blocks = message["content"].as_array().unwrap().iter();
+ let blocks = blocks
+ .map(|block| block["type"].as_str().unwrap().to_string())
+ .collect();
+ (blocks, message["stop_reason"].as_str().unwrap().to_string())
+ };
+ server.abort();
+ read
+}
+
+#[tokio::test]
+async fn messages_truncated_after_a_tool_call_starts_stop_at_max_tokens() {
+ // The output ends inside a call the parser already named, or after a
+ // whole call. Only an output that finished calls a tool.
+ let cut = "\n\n\nPar";
+ let whole = "\n\n\n\nThen";
+ for (text, stream) in [(cut, true), (whole, true), (whole, false)] {
+ for (finish, stop_reason) in [("length", "max_tokens"), ("stop", "tool_use")] {
+ let (blocks, got) = qwen_xml_messages(text, finish, stream).await;
+ assert!(
+ blocks.iter().any(|block| block == "tool_use"),
+ "{text:?} {finish} stream={stream}: {blocks:?}"
+ );
+ assert_eq!(got, stop_reason, "{text:?} {finish} stream={stream}");
+ }
+ }
+}
+
#[tokio::test]
async fn deepseek_usage_rides_on_the_last_finish_chunk() {
for options in [
diff --git a/model_gateway/tests/grpc_responses_stream_contract_test.rs b/model_gateway/tests/grpc_responses_stream_contract_test.rs
index 55cb35d54a..58a859a7d8 100644
--- a/model_gateway/tests/grpc_responses_stream_contract_test.rs
+++ b/model_gateway/tests/grpc_responses_stream_contract_test.rs
@@ -592,6 +592,56 @@ async fn mcp_unfinished_generation_never_dispatches_tools() {
}
}
+#[tokio::test]
+async fn mcp_call_without_json_arguments_never_dispatches() {
+ // The parser names the server call, but the output ends before the
+ // call's arguments start.
+ for stream in [false, true] {
+ let mut mcp = common::mock_mcp_server::MockMCPServer::start()
+ .await
+ .unwrap();
+ let (response, _) = responses_result_with_output(
+ json!([{"type":"mcp","server_label":"test-tools","server_url":mcp.url(),"require_approval":"never"}]),
+ Some("\n{\"name\":\"brave_web_search\""), None, "completed", stream,
+ ).await;
+ mcp.stop().await;
+ assert_eq!(mcp.call_count(), 0, "stream={stream}: {response}");
+ assert_executed_mcp_queries(&response, &[]);
+ assert!(
+ !response["output"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .any(|i| i["type"] == "function_call"),
+ "{response}"
+ );
+ }
+}
+
+#[tokio::test]
+async fn mcp_call_without_arguments_runs_with_an_empty_object() {
+ // A whole server call that takes no arguments.
+ for stream in [false, true] {
+ let mut mcp = common::mock_mcp_server::MockMCPServer::start()
+ .await
+ .unwrap();
+ let (response, _) = responses_result_with_output(
+ json!([{"type":"mcp","server_label":"test-tools","server_url":mcp.url(),"require_approval":"never"}]),
+ Some("\n{\"name\":\"brave_web_search\"}\n\n"), Some(1), "completed", stream,
+ ).await;
+ mcp.stop().await;
+ assert_eq!(mcp.call_count(), 1, "stream={stream}: {response}");
+ let calls: Vec<_> = response["output"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .filter(|i| i["type"] == "mcp_call")
+ .collect();
+ assert_eq!(calls.len(), 1, "stream={stream}: {response}");
+ assert_eq!(calls[0]["arguments"], "{}", "stream={stream}: {response}");
+ }
+}
+
#[tokio::test]
async fn mcp_mixed_batch_executes_server_prefix_and_returns_client_function() {
for stream in [false, true] {