From 0ce74e4dbf45ae5071afb652e71dac5152b535ef Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 5 Oct 2026 06:00:24 +0200 Subject: [PATCH] feat: continue Messages with failed or empty tool results (#27) --- control-plane/src/messages.rs | 87 +++++++++++++++++++++++++++++++++-- docs/api-contract.md | 11 ++++- scripts/smoke-messages.py | 44 +++++++++++++++++- 3 files changed, 135 insertions(+), 7 deletions(-) diff --git a/control-plane/src/messages.rs b/control-plane/src/messages.rs index 3991325b..48097ef9 100644 --- a/control-plane/src/messages.rs +++ b/control-plane/src/messages.rs @@ -135,10 +135,14 @@ enum Block { }, ToolResult { tool_use_id: String, + #[serde(default = "empty_tool_result")] content: Value, is_error: Option, }, } +fn empty_tool_result() -> Value { + Value::String(String::new()) +} fn blocks(value: Value) -> Result, String> { match value { Value::String(text) => Ok(vec![Block::Text { text }]), @@ -221,10 +225,15 @@ impl Request { is_error, } if role == "user" => { flush(&mut text, &mut input); - if is_error == Some(true) { - return Err("is_error tool results are not supported".into()); - } - input.push(json!({"type":"function_call_output","call_id":tool_use_id,"output":text_only(content)?})); + let text = text_only(content)?; + // The local template has text tool outputs, not a separate error bit. + // Keep the bit and exact normalized content together in the tool role. + let output = if is_error == Some(true) { + json!({"is_error":true,"content":text}).to_string() + } else { + text + }; + input.push(json!({"type":"function_call_output","call_id":tool_use_id,"output":output})); } _ => { return Err( @@ -540,3 +549,73 @@ fn stream_response(mut body: Body) -> Response { }); Sse::new(Events(receiver)).into_response() } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn tool_results_preserve_errors_empty_content_and_success_bytes() { + let text = "failure 🌍\n\"quote\" \\ path\u{0000}"; + let make = |result: Value| { + serde_json::from_value::(json!({"model":"fixture","max_tokens":8,"messages":[ + {"role":"user","content":"Do it"}, + {"role":"assistant","content":[{"type":"tool_use","id":"call","name":"work","input":{}}]}, + {"role":"user","content":[result]} + ]})).unwrap().into_responses() + }; + for error in [None, Some(false), Some(true)] { + for content in [ + None, + Some(json!(text)), + Some(json!([])), + Some(json!([ + {"type":"text","text":text}, {"type":"text","text":"last"} + ])), + ] { + let normalized = match &content { + None => String::new(), + Some(Value::String(s)) => s.clone(), + Some(Value::Array(parts)) if parts.is_empty() => String::new(), + _ => format!("{text}\nlast"), + }; + let mut result = json!({"type":"tool_result","tool_use_id":"call"}); + if let Some(content) = content { + result["content"] = content; + } + if let Some(error) = error { + result["is_error"] = json!(error); + } + let (native, _) = make(result).unwrap(); + let output = native["input"][2]["output"].as_str().unwrap(); + assert_eq!(native["input"][2]["call_id"], "call"); + assert_eq!(native["input"][2]["type"], "function_call_output"); + assert_eq!(native["input"].as_array().unwrap().len(), 3); + if error == Some(true) { + assert_eq!( + serde_json::from_str::(output).unwrap(), + json!({"is_error":true,"content":normalized}) + ); + } else { + assert_eq!(output, normalized); + } + } + } + for content in [ + Value::Null, + json!(3), + json!({}), + json!([{"type":"image","source":{}}]), + ] { + assert!(make(json!({"type":"tool_result","tool_use_id":"call","content":content,"is_error":true})).is_err()); + } + for flag in [json!("true"), json!(1), json!({})] { + assert!( + serde_json::from_value::( + json!({"type":"tool_result","tool_use_id":"call","is_error":flag}) + ) + .is_err() + ); + } + } +} diff --git a/docs/api-contract.md b/docs/api-contract.md index 7ed7e202..1582357e 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -67,13 +67,20 @@ temperature (0..1) and top_p. Text parts join with newlines; consecutive turns o the same role combine. This initial subset requires first and last user messages; assistant prefill is rejected. Assistant `tool_use` carries an object `input` and ID; user `tool_result` returns the same `tool_use_id` and text or text blocks. +Omitted result `content` means empty text; explicit null and non-text blocks remain +invalid. [Client-tool errors](https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls) +with `is_error: true` are supported. Because the native template has text tool +outputs, the adapter serializes `{"content":"","is_error":true}` +as that call's tool output, preserving the flag and text (including escaped +control characters). Normal/`is_error: false` results retain their existing text +unchanged. Counting and serving share this conversion. This supports transport +of failures; recovery behavior still requires model qualification. Tool names, arguments, results and choice policies reuse native validation. Thinking is disabled (omitted or `{"type":"disabled"}`); requests are stateless. Thinking/redacted signatures, images/documents, cache_control, nonempty stop_sequences, server tools, top_k, metadata, structured-output options, -`is_error: true` tool results, beta headers and unknown fields are rejected before -GEN. This does not implement all Messages features or certify a Claude SDK agent. +beta headers and unknown fields are rejected before GEN. This does not implement all Messages features or certify a Claude SDK agent. `POST /v1/messages/count_tokens` follows the [token count response shape](https://platform.claude.com/docs/en/api/messages/count_tokens) and returns `{"input_tokens": N}`. It accepts `model`, `messages`, optional `system`, diff --git a/scripts/smoke-messages.py b/scripts/smoke-messages.py index 98c4ae1c..be52a020 100644 --- a/scripts/smoke-messages.py +++ b/scripts/smoke-messages.py @@ -247,6 +247,48 @@ done assert measured == len(expected_wire.split()[-1].split(',')) code, result = request('POST', path, {**base, 'messages': transcript, 'tools': [tool]}) assert code == 200 and wire()[-1] == expected_wire and result['content'] == [{'type': 'text', 'text': 'Continued'}], result + # Tool execution failures and empty results continue in the tool role. + error_text = 'Connection failed 🌍\n"quoted" \\ path\u0000' + variants = [ + ([{'content': [{'type': 'text', 'text': error_text}], 'is_error': True}, {}], + [json.dumps({'content': error_text, 'is_error': True}, ensure_ascii=False, separators=(',', ':'), sort_keys=True), '']), + ([{'is_error': True}, {'content': [], 'is_error': False}], + ['{"content":"","is_error":true}', '']), + ([{'content': 'Found 🌍', 'is_error': False}, {'content': 'Found 🌍'}], + ['Found 🌍', 'Found 🌍']), + ] + for fields, expected_outputs in variants: + results = [{'type': 'tool_result', 'tool_use_id': b['id'], **f} for b, f in zip(calls, fields)] + transcript = base['messages'] + [{'role': 'assistant', 'content': streamed['content']}, {'role': 'user', 'content': results}] + current = {**base, 'messages': transcript, 'tools': [tool]} + native_input = base['messages'] + [{'type': 'function_call', 'call_id': b['id'], 'name': b['name'], 'arguments': json.dumps(b['input'], separators=(',', ':'))} for b in calls] + [{'type': 'function_call_output', 'call_id': b['id'], 'output': v} for b, v in zip(calls, expected_outputs)] + measured = count(current) + output('Continued after result') + assert request('POST', '/v1/responses', {**native_base, 'input': native_input, 'tools': [native_tool]})[0] == 200 + expected_wire = wire()[-1] + assert measured == len(expected_wire.split()[-1].split(',')) + code, result = request('POST', path, current) + assert code == 200 and wire()[-1] == expected_wire and result['stop_reason'] == 'end_turn', result + assert result['content'] == [{'type': 'text', 'text': 'Continued after result'}] + code, events = request('POST', path, {**current, 'stream': True}) + assert code == 200 and wire()[-1] == expected_wire + assert normalized(rebuild(events)) == normalized(result) + before = wire() + for bad in [ + {'content': None, 'is_error': True}, {'is_error': 'true'}, + {'content': [{'type': 'image', 'source': {}}], 'is_error': True}, + {'tool_use_id': 'orphan', 'is_error': True}, + {'tool_use_id': calls[1]['id'], 'is_error': True}, + ]: + bad_results = [{'type': 'tool_result', 'tool_use_id': calls[0]['id'], **bad}, + {'type': 'tool_result', 'tool_use_id': calls[1]['id']}] + current = {**base, 'tools': [tool], 'messages': base['messages'] + [ + {'role': 'assistant', 'content': streamed['content']}, {'role': 'user', 'content': bad_results}]} + for streaming in [False, True]: + code, value = request('POST', path, {**current, 'stream': streaming}) + assert code == 400 and value['type'] == 'error', value + count(current, 400) + assert wire() == before for text, extra, reason in [(tool_text.replace('lookup', 'wrong'), {'tools': [tool]}, 'stop'), ('A', {'tools': [tool], 'tool_choice': {'type': 'any'}}, 'stop'), (tool_text[:35], {'tools': [tool]}, 'length')]: output(text, reason) code, value = request('POST', path, {**base, **extra}) @@ -310,7 +352,7 @@ done if process.returncode != 0: logs.seek(0) raise AssertionError(logs.read().decode()) - print('Messages count/actual GEN equality/no mutation/outage + JSON/named live SSE/block order/tools/continuation/usage/header auth/errors/STOP/fresh: PASS; actual GEN and greedy parity tolerance=0, CPU only') + print('Messages error/empty/parallel tool results + count/actual GEN equality/no mutation/outage + JSON/named live SSE/block order/tools/continuation/usage/header auth/errors/STOP/fresh: PASS; actual GEN and greedy parity tolerance=0, CPU only') if __name__ == '__main__':