Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions crates/protocols/src/responses.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1549,6 +1549,31 @@ pub enum ResponseInputOutputItem {
#[serde(skip_serializing_if = "Option::is_none")]
reason: Option<String>,
},
/// Client-stitched MCP tool inventory item. Echoes the output-side
/// `mcp_list_tools` shape so a prior assistant turn can be replayed as
/// input.
#[serde(rename = "mcp_list_tools")]
McpListTools {
id: String,
server_label: String,
tools: Vec<McpToolInfo>,
},
/// Client-stitched completed MCP tool call. Echoes the output-side
/// `mcp_call` shape so a prior tool execution can be replayed as input
/// without re-executing the tool.
#[serde(rename = "mcp_call")]
McpCall {
id: String,
server_label: String,
name: String,
arguments: String,
output: String,
status: String,
#[serde(skip_serializing_if = "Option::is_none")]
approval_request_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
error: Option<String>,
},
/// `type: "image_generation_call"` — round-trip form for an image generated
/// in a prior turn. Spec (OpenAI Responses API, multi-turn image-edit
/// flow): clients may resubmit only `{ type, id }` to reference a prior
Expand Down Expand Up @@ -2944,6 +2969,8 @@ impl GenerationRequest for ResponsesRequest {
| ResponseInputOutputItem::FunctionCallOutput { .. }
| ResponseInputOutputItem::McpApprovalRequest { .. }
| ResponseInputOutputItem::McpApprovalResponse { .. }
| ResponseInputOutputItem::McpListTools { .. }
| ResponseInputOutputItem::McpCall { .. }
| ResponseInputOutputItem::ImageGenerationCall { .. }
| ResponseInputOutputItem::Compaction { .. }
| ResponseInputOutputItem::ComputerCall { .. }
Expand Down Expand Up @@ -3228,6 +3255,8 @@ fn validate_input_item(item: &ResponseInputOutputItem) -> Result<(), ValidationE
ResponseInputOutputItem::FunctionToolCall { .. } => {}
ResponseInputOutputItem::McpApprovalRequest { .. } => {}
ResponseInputOutputItem::McpApprovalResponse { .. } => {}
ResponseInputOutputItem::McpListTools { .. } => {}
ResponseInputOutputItem::McpCall { .. } => {}
ResponseInputOutputItem::ImageGenerationCall { .. } => {}
ResponseInputOutputItem::Compaction { .. } => {}
ResponseInputOutputItem::ComputerCall { .. } => {}
Expand Down
82 changes: 82 additions & 0 deletions crates/protocols/tests/responses.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2028,6 +2028,88 @@ fn test_custom_tool_call_output_validation_rejects_empty_text_and_parts() {
);
}

/// Client-stitched transcripts may carry `mcp_list_tools` and `mcp_call`
/// items echoing prior output. Protocol validation must accept them
/// structurally so the router-side preparation layer can normalize them.
#[test]
fn response_input_accepts_mcp_trace_items() {
use validator::Validate;

let request: ResponsesRequest = serde_json::from_value(json!({
"model": "gpt-5.4",
"store": false,
"input": [
{
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": "search something"}],
},
{
"type": "mcp_list_tools",
"id": "mcpl_123",
"server_label": "deepwiki",
"tools": [],
},
{
"type": "mcp_call",
"id": "mcp_123",
"server_label": "deepwiki",
"name": "ask_question",
"arguments": "{\"query\":\"something\"}",
"output": "{\"result\":\"ok\"}",
"status": "completed",
},
],
}))
.expect("request should deserialize");

request
.validate()
.expect("mcp trace items should pass structural validation");

let ResponseInput::Items(items) = &request.input else {
panic!("expected items input");
};

assert!(
items
.iter()
.any(|item| matches!(item, ResponseInputOutputItem::McpListTools { .. })),
"mcp_list_tools should deserialize as an input item",
);
assert!(
items
.iter()
.any(|item| matches!(item, ResponseInputOutputItem::McpCall { .. })),
"mcp_call should deserialize as an input item",
);

let serialized = serde_json::to_value(&request).expect("serialize");
assert_eq!(serialized["input"][1]["type"], json!("mcp_list_tools"));
assert_eq!(serialized["input"][2]["type"], json!("mcp_call"));
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

/// Optional fields on `mcp_call` (`approval_request_id`, `error`) should
/// be omitted from serialized output when unset, matching the output-side
/// contract and keeping spec parity on re-emit.
#[test]
fn mcp_call_input_omits_optional_fields_when_unset() {
let item = ResponseInputOutputItem::McpCall {
id: "mcp_abc".to_string(),
server_label: "deepwiki".to_string(),
name: "ask_question".to_string(),
arguments: "{}".to_string(),
output: "ok".to_string(),
status: "completed".to_string(),
approval_request_id: None,
error: None,
};

let v = serde_json::to_value(&item).expect("serialize");
assert!(v.get("approval_request_id").is_none());
assert!(v.get("error").is_none());
Comment thread
zhaowenzi marked this conversation as resolved.
Resolved
}

// ---------------------------------------------------------------------------
// T6 — containerized `shell` tool + call/output items
// ---------------------------------------------------------------------------
Expand Down
2 changes: 2 additions & 0 deletions model_gateway/benches/routing_allocation_bench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ fn extract_text_for_routing_old(req: &ResponsesRequest) -> String {
ResponseInputOutputItem::FunctionCallOutput { output, .. } => Some(output.clone()),
ResponseInputOutputItem::McpApprovalRequest { .. } => None,
ResponseInputOutputItem::McpApprovalResponse { .. } => None,
ResponseInputOutputItem::McpListTools { .. } => None,
ResponseInputOutputItem::McpCall { .. } => None,
ResponseInputOutputItem::ImageGenerationCall { .. } => None,
ResponseInputOutputItem::Compaction { .. } => None,
ResponseInputOutputItem::ComputerCall { .. } => None,
Expand Down
116 changes: 100 additions & 16 deletions model_gateway/src/routers/grpc/harmony/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -495,8 +495,11 @@ impl HarmonyBuilder {
let mut prev_outputs: Vec<&ResponseInputOutputItem> = Vec::new();

for item in items {
let msg = self.parse_response_item_to_harmony_message(item, &prev_outputs)?;
all_messages.push(msg);
if let Some(msg) =
self.parse_response_item_to_harmony_message(item, &prev_outputs)?
{
all_messages.push(msg);
}

// Track function tool calls so that function_call_output can find the name
if matches!(item, ResponseInputOutputItem::FunctionToolCall { .. }) {
Expand Down Expand Up @@ -529,7 +532,7 @@ impl HarmonyBuilder {
&self,
item: &ResponseInputOutputItem,
prev_outputs: &[&ResponseInputOutputItem],
) -> Result<HarmonyMessage, String> {
) -> Result<Option<HarmonyMessage>, String> {
match item {
// Regular message (user or assistant)
ResponseInputOutputItem::Message { role, content, .. } => {
Expand Down Expand Up @@ -558,7 +561,7 @@ impl HarmonyBuilder {

let text = text_parts.join("\n");

Ok(HarmonyMessage {
Ok(Some(HarmonyMessage {
author: Author {
role: harmony_role,
name: None,
Expand All @@ -567,7 +570,7 @@ impl HarmonyBuilder {
content: vec![Content::Text(TextContent { text })],
channel: None,
content_type: None,
})
}))
}

// Reasoning content (chain-of-thought)
Expand All @@ -583,7 +586,7 @@ impl HarmonyBuilder {
let text = reasoning_texts.join("\n");

// Reasoning goes in the "analysis" channel for Harmony
Ok(HarmonyMessage {
Ok(Some(HarmonyMessage {
author: Author {
role: Role::Assistant,
name: None,
Expand All @@ -592,7 +595,7 @@ impl HarmonyBuilder {
content: vec![Content::Text(TextContent { text })],
channel: Some("analysis".to_string()),
content_type: None,
})
}))
}

// Function tool call (with optional output)
Expand All @@ -615,7 +618,7 @@ impl HarmonyBuilder {
output_preview = %output_str.chars().take(100).collect::<String>(),
"Building tool result message with Tool role (recipient=assistant, no channel)"
);
Ok(HarmonyMessage {
Ok(Some(HarmonyMessage {
author: Author {
role: Role::Tool,
name: Some(author_name),
Expand All @@ -626,7 +629,7 @@ impl HarmonyBuilder {
})],
channel: None,
content_type: None,
})
}))
} else {
// Tool call - assistant message in commentary channel with recipient
// msg.with_channel("commentary").with_recipient(f"functions.{name}")
Expand All @@ -636,7 +639,7 @@ impl HarmonyBuilder {
recipient = %recipient,
"Building tool call message with recipient"
);
Ok(HarmonyMessage {
Ok(Some(HarmonyMessage {
author: Author {
role: Role::Assistant,
name: None,
Expand All @@ -647,7 +650,7 @@ impl HarmonyBuilder {
})],
channel: Some("commentary".to_string()),
content_type: Some("json".to_string()),
})
}))
}
}

Expand All @@ -672,7 +675,7 @@ impl HarmonyBuilder {
// Create Tool message with "functions.{name}" prefix
// IMPORTANT: Must include recipient="assistant" for parser to recognize it.
// We keep channel=None to minimize what the model might copy.
Ok(HarmonyMessage {
Ok(Some(HarmonyMessage {
author: Author {
role: Role::Tool,
name: Some(format!("functions.{call}")),
Expand All @@ -683,7 +686,7 @@ impl HarmonyBuilder {
})],
channel: None,
content_type: None,
})
}))
}

// Simple input message (usually user message)
Expand Down Expand Up @@ -717,7 +720,7 @@ impl HarmonyBuilder {
}
};

Ok(HarmonyMessage {
Ok(Some(HarmonyMessage {
author: Author {
role: harmony_role,
name: None,
Expand All @@ -726,12 +729,21 @@ impl HarmonyBuilder {
content: vec![Content::Text(TextContent { text })],
channel: None,
content_type: None,
})
}))
}

ResponseInputOutputItem::McpApprovalResponse { .. }
| ResponseInputOutputItem::McpApprovalRequest { .. }
| ResponseInputOutputItem::ComputerCall { .. }
| ResponseInputOutputItem::McpListTools { .. }
| ResponseInputOutputItem::McpCall { .. } => {
warn!(
function = "parse_response_item_to_harmony_message",
"Skipping replayed MCP trace item during Harmony conversion"
);
Ok(None)
}

ResponseInputOutputItem::ComputerCall { .. }
| ResponseInputOutputItem::ComputerCallOutput { .. } => {
warn!(
function = "parse_response_item_to_harmony_message",
Expand Down Expand Up @@ -1044,3 +1056,75 @@ impl Default for HarmonyBuilder {
Self::new()
}
}

#[cfg(test)]
mod tests {
use openai_protocol::responses::{
ResponseContentPart, ResponseInput, ResponseInputOutputItem, ResponsesRequest,
};

use super::HarmonyBuilder;

#[test]
fn test_construct_input_messages_skips_replayed_mcp_trace_items() {
let request = ResponsesRequest {
previous_response_id: Some("resp_prev".to_string()),
input: ResponseInput::Items(vec![
ResponseInputOutputItem::Message {
id: "msg_user".to_string(),
role: "user".to_string(),
content: vec![ResponseContentPart::InputText {
text: "hello".to_string(),
}],
status: None,
phase: None,
},
ResponseInputOutputItem::McpApprovalRequest {
id: "mcpr_1".to_string(),
server_label: "mock".to_string(),
name: "brave_web_search".to_string(),
arguments: "{\"query\":\"hello\"}".to_string(),
},
ResponseInputOutputItem::McpApprovalResponse {
id: Some("mcprr_1".to_string()),
approval_request_id: "mcpr_1".to_string(),
approve: true,
reason: None,
},
ResponseInputOutputItem::McpListTools {
id: "mcp_list_1".to_string(),
server_label: "mock".to_string(),
tools: vec![],
},
ResponseInputOutputItem::McpCall {
id: "mcp_1".to_string(),
server_label: "mock".to_string(),
name: "brave_web_search".to_string(),
arguments: "{\"query\":\"hello\"}".to_string(),
output: "{\"result\":\"world\"}".to_string(),
status: "completed".to_string(),
approval_request_id: None,
error: None,
},
ResponseInputOutputItem::Message {
id: "msg_assistant".to_string(),
role: "assistant".to_string(),
content: vec![ResponseContentPart::OutputText {
text: "done".to_string(),
annotations: vec![],
logprobs: None,
}],
status: None,
phase: None,
},
]),
..Default::default()
};

let messages = HarmonyBuilder::new()
.construct_input_messages_with_harmony(&request)
.expect("replayed MCP trace items are skipped");

assert_eq!(messages.len(), 2);
}
Comment thread
zhaowenzi marked this conversation as resolved.
Resolved
}
Loading
Loading