Repository navigation
feat: add parallel tool calling support - #214
franciscojavierarceo merged 14 commits into
Conversation
Forward parallel_tool_calls to upstream inference and execute gateway built-in tool calls concurrently with bounded, per-tool safety controls. Align behavior with OpenAI reference recordings by: - validating missing function and custom tool call outputs - supporting batched web-search queries - preserving typed MCP and web-search output lifecycles - emitting mcp_list_tools discovery only once per stored chain - retaining discovery history without exposing it to model input - adding streaming and non-streaming cassette parity coverage Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
…-call Signed-off-by: maral <[email protected]>
| emit_gateway_start_events(&event_plans[..first_gateway_run_len], stream_accumulator, stream_sender)?; | ||
|
|
||
| let gateway_results = execute_output_calls(output_items, registry).await?; | ||
| let gateway_results = GatewayRound::new().execute(output_items, registry).await?; |
There was a problem hiding this comment.
gateway_event_plans skips Gateway(None) calls such as file_search and code_interpreter, while the streaming engine still counts them here. this leaves event_plans shorter than the gateway-call count and causes an out-of-bounds slice panic. we need to retain a positional plan for every gateway-owned call or key plans by output index.
There was a problem hiding this comment.
I addressed this by replacing the separately derived gateway-call and event-plan lists with a single GatewayScheduler.
The scheduler first creates one GatewayCallPlan for every gateway-owned call in model-output order. Each plan owns the original item index, execution binding, timeout policy, and lifecycle event plan. Gateway(None) is represented explicitly as MissingHandler, so calls such as unconfigured file_search and code_interpreter retain their positional slot and produce an error function_call_output instead of being skipped.
Execution uses bounded concurrency through max_concurrent_gateway_calls. Handlers that support parallel execution may overlap, while handlers that do not are protected by a per-tool-name semaphore. Each call retains its timeout, and results and SSE lifecycle events are emitted according to the planned output order regardless of completion order. The upstream parallel_tool_calls field remains a model-generation preference; it does not replace the gateway’s execution-safety policy.
I also removed the untyped ToolEntry.config: serde_json::Value path. ToolHandler now declares its public ToolParams, and GatewayExecutor declares its ExecutionParams. For example, MCP validates and normalizes an McpToolParam, but each discovered tool executes with its own McpDiscoveredToolParam.
GatewayBinding::new pairs the concrete executor with its correctly typed parameters before type-erasing that pair for storage in the heterogeneous registry. The scheduler therefore receives a complete binding and never handles raw configuration JSON or tool-specific type checks. Tool handlers remain responsible for their lifecycle projection through GatewayToolEventPlan, while the scheduler owns indexes, ordering, concurrency, and SSE framing.
I added scheduler_retains_event_slot_for_gateway_tool_without_handler as a regression test for the reported panic path.
| mcp_servers: file.mcp_servers.clone(), | ||
| mcp_allowed_hosts, | ||
| messages_gateway_tool_aliases: file.messages_gateway.tool_aliases.clone(), | ||
| max_concurrent_gateway_calls: max_concurrent_gateway_calls as usize, |
There was a problem hiding this comment.
tools.max_concurrent_gateway_calls accepts 0 from TOML because the nonzero check only applies to environment-provided values. that reaches .buffered(0), which polls no calls, so the request hangs before the per-call timeout can start. we need to validate the resolved value or represent it as NonZeroUsize.
There was a problem hiding this comment.
@franciscojavierarceo Fixed. max_concurrent_gateway_calls is now represented as NonZeroUsize from TOML/environment parsing through scheduler execution, making .buffered(0) unrepresentable. A configured value of 0 is rejected during parsing.
I also removed the process-global OnceLock. Each ExecutionContext now owns its scheduler policy and passes it explicitly to GatewayScheduler. Added regression tests for TOML/environment zero rejection and enforcement of the configured scheduler window.
| .map_err(|e| ToolError::Config(format!("invalid web_search config: {e}")))?; | ||
| let response = self.provider.search(&args, &config).await?; | ||
| let queries = args.all_queries(); | ||
| let responses = |
There was a problem hiding this comment.
the queries array has no length bound, and try_join_all starts every provider request concurrently inside one gateway slot. one model-generated call can therefore bypass max_concurrent_gateway_calls, launch thousands of outbound requests, and aggregate all results in memory. we need to enforce maxItems and execute searches through a bounded stream or shared semaphore.
There was a problem hiding this comment.
@franciscojavierarceo Addressed. Batched web search remains supported to match OpenAI behavior, but queries is now capped at five through both maxItems in the model-visible schema and runtime validation.
I also replaced try_join_all with an ordered bounded stream. Each provider request acquires a shared semaphore initialized from max_concurrent_gateway_calls, so concurrent batched calls cannot bypass the configured outbound concurrency limit. Tests cover oversized batches and concurrency across simultaneous web search calls.
| .cloned() | ||
| .map(|call| self.run_one(call, registry)), | ||
| ) | ||
| .buffered(max_concurrent_gateway_calls()) |
There was a problem hiding this comment.
buffered preserves result order internally, so a slow first call prevents completed later calls from leaving the queue and stops the window from refilling. same-tool waiters also consume global slots before acquiring their permit, which can block unrelated tools for the full timeout. we need to execute unordered with original indexes, keep exclusion waiters outside the active global window, and restore output order afterward.
There was a problem hiding this comment.
@franciscojavierarceo addressed. I replaced the ordered buffered window with join_all backed by an explicit scheduler-local semaphore.
Each call now acquires its same-tool exclusion permit before acquiring global execution capacity, so exclusion waiters no longer block unrelated tools. Because join_all polls all planned calls while preserving input order, completed later calls immediately release their global slot without requiring index sorting afterward.
Added regression tests covering both same-tool waiter starvation and execution-window refilling behind a slow earlier call.
| /// `ExecutionContext::from_config`. Subsequent calls are no-ops: the value is | ||
| /// fixed for the lifetime of the process. | ||
| pub fn set_max_concurrent_gateway_calls(value: usize) { | ||
| let _ = MAX_CONCURRENT_GATEWAY_CALLS.set(value); |
There was a problem hiding this comment.
the OnceLock silently discards subsequent set failures, so the first ExecutionContext fixes gateway concurrency for the entire process. later contexts can accept a different configuration while continuing to use the first value. we should store the limit on ExecutionContext and pass it into each GatewayRound.
| /// followed by at least one historical item and is therefore suppressed. | ||
| pub(crate) fn mcp_list_tool_items(&self) -> impl Iterator<Item = &McpListTools> { | ||
| self.mcp_list_tools_items | ||
| .values() |
There was a problem hiding this comment.
mcp_list_tool_items iterates HashMap::values(), replacing the previous declaration-ordered representation. with multiple MCP servers, response order and streaming output_index assignments can change between processes. we should preserve declaration order with a Vec or IndexMap.
There was a problem hiding this comment.
@franciscojavierarceo mcp_list_tools_items now uses IndexMap<String, Vec<McpListTools>>, preserving MCP declaration order while retaining keyed lookup and per-server history. Blocking responses and streaming lifecycle output_index assignments are therefore deterministic. Added a regression test verifying insertion/declaration order is preserved.
| match self.client_visible_error() { | ||
| Self::ConversationLocked { .. } | ||
| | Self::Tool(ToolError::Config(_)) | ||
| | Self::Tool(ToolError::Config(_) | ToolError::MissingOutput { .. }) |
There was a problem hiding this comment.
error_param and the error serializer make MissingOutput diverge from the OpenAI reference cassette: the message gains a tool error: prefix, param: "input" is omitted, and code becomes "invalid_request_error" instead of null. we should special-case this validation error so the public envelope matches the recorded reference.
There was a problem hiding this comment.
@franciscojavierarceo this is indeed an invalid-request error: OpenAI returns HTTP 400, which the SDK exposes as openai.BadRequestError, while the inner error object contains type: "invalid_request_error" and code: null.
I initially assumed the gateway should repeat the error type in code, but to match the OpenAI response exactly, I updated the gateway to preserve HTTP 400 and invalid_request_error while emitting the exact message, param: "input", and code: null.
| // Only a currently declared MCP server can emit discovery in | ||
| // this request. Ignore history for labels absent from the | ||
| // current registry instead of turning it into a new candidate. | ||
| if let Some(items) = self.mcp_list_tools_items.get_mut(&list_tools.server_label) { |
There was a problem hiding this comment.
cache_listed_mcp_tools suppresses current discovery whenever history contains the same server_label, even when the earlier discovery failed or the declaration and tool set changed. this can hide a valid current discovery lifecycle from the client. we should suppress only an equivalent prior successful discovery.
There was a problem hiding this comment.
@franciscojavierarceo MCP discovery is now suppressed only when the current result is successful and history contains an equivalent successful tool set. Previous failures, changed tool definitions, and current discovery failures remain visible to the client. Comparison ignores generated lifecycle IDs while covering all public tool fields and order. Added regression tests for each case.
| match item { | ||
| InputItem::FunctionCall(call) => pending.push(call.call_id.clone()), | ||
| InputItem::CustomToolCall(call) => pending.push(call.call_id.clone()), | ||
| InputItem::FunctionCallOutput(output) => pending.retain(|call_id| *call_id != output.call_id), |
There was a problem hiding this comment.
pending_calls uses retain, so one output clears every pending call sharing its call_id; empty IDs are accepted as well. duplicate or missing IDs can therefore bypass the new one-output-per-call validation. we should reject empty and duplicate IDs and enforce one-to-one call/output matching.
There was a problem hiding this comment.
@franciscojavierarceo pending_calls now rejects empty or duplicate call_id values and enforces one-to-one, same-kind matching between calls and outputs. Each output removes exactly one pending entry; unmatched, repeated, or function/custom mismatched outputs return InvalidRequest. Added focused coverage for all invalid cases, and the full two-thread test suite passes.
Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
…-call Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
There was a problem hiding this comment.
Pull request overview
Adds end-to-end support for parallel_tool_calls in the typed Responses pipeline, aligning gateway behavior with OpenAI reference recordings while keeping gateway execution concurrency bounded and deterministic (stable output order + streaming sequence numbers).
Changes:
- Forward
parallel_tool_callsupstream (defaulting tofalsewhen omitted) and enable concurrent execution of gateway-executed built-in tool calls with a configurable concurrency window. - Rework tool registry/execution ownership to explicitly distinguish client execution vs gateway execution, and cache/suppress repeated MCP
mcp_list_toolsemission across continuations. - Expand test + cassette coverage for parallel built-in, mixed, client-only, and failure/omission scenarios; add config/env plumbing for
max_concurrent_gateway_calls.
Reviewed changes
Copilot reviewed 66 out of 71 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| TERMINOLOGY.md | Updates tool registry terminology and ownership wording. |
| ROADMAP.md | Updates roadmap section to reflect completed parallel tool calling work (#181). |
| README.md | Documents new [tools] max_concurrent_gateway_calls config and env override. |
| docs/guides/harness-cli-testing.md | Updates CLI testing guide to reflect new parallel behavior and removes obsolete warning reference. |
| docs/design/mcp-gateway-integration.md | Documents one-time-per-server-label MCP discovery emission and registry lifecycle caching. |
| docs/design/codex-integration.md | Updates Codex tool-shape semantics and continuation behavior notes. |
| crates/agentic-server/tests/responses_test.rs | Adds gateway-to-upstream integration test for parallel_tool_calls: true with built-ins. |
| crates/agentic-server/tests/compaction_test.rs | Updates test harness web-search executor to the new typed ToolHandler/GatewayExecutor params. |
| crates/agentic-server/src/server.rs | Removes startup warning claiming parallel tool calls are unsupported. |
| crates/agentic-server/src/main.rs | Adds config/env parsing for AGENTIC_MAX_CONCURRENT_GATEWAY_CALLS (NonZeroUsize). |
| crates/agentic-server/src/config_file.rs | Adds [tools] max_concurrent_gateway_calls to TOML config schema + validation tests. |
| crates/agentic-server/src/agentic_harness.rs | Advertises supports_parallel_tool_calls: true for Codex home generation. |
| crates/agentic-server-core/tests/web_search_tool_test.rs | Updates web-search tests for typed params and adds assertions preventing duplicated model input on continuation. |
| crates/agentic-server-core/tests/tool_normalization_test.rs | Updates web-search schema expectations to support query or queries (anyOf). |
| crates/agentic-server-core/tests/support/mod.rs | Extends cassette request-body capture struct with parallel_tool_calls + previous_response_id. |
| crates/agentic-server-core/tests/stateful_responses_integration.rs | Updates continuation test setup to include explicit tool outputs in input items. |
| crates/agentic-server-core/tests/parallel_tool_calls_test.rs | New end-to-end cassette parity test for parallel built-in tool calls (streaming + non-streaming). |
| crates/agentic-server-core/tests/mcp_tool_test.rs | Updates MCP registry assertions to use ToolOwnership instead of handler presence. |
| crates/agentic-server-core/tests/custom_tool_test.rs | Updates custom-tool registry assertions to use ToolOwnership instead of handler presence. |
| crates/agentic-server-core/tests/cassettes/record_parallel_tool_call_cassettes.sh | New recorder script for parallel-tool-call cassette suites (openai/gateway). |
| crates/agentic-server-core/tests/cassettes/record_cassette.py | Adds --parallel-tool-calls + --append; supports Python module tool outputs to model omissions/failures. |
| crates/agentic-server-core/tests/cassettes/parallel_tool_calls/tools-mixed.json | New tool declarations for mixed built-in + client tool scenarios. |
| crates/agentic-server-core/tests/cassettes/parallel_tool_calls/tools-client-only.json | New tool declarations for client-only parallel tool scenarios. |
| crates/agentic-server-core/tests/cassettes/parallel_tool_calls/tools-builtin-only.json | New tool declarations for built-in-only (web_search_preview + mcp) scenarios. |
| crates/agentic-server-core/tests/cassettes/parallel_tool_calls/tool_outputs.py | New Python fake tool outputs for cassette recording (success/failure/omission). |
| crates/agentic-server-core/tests/cassettes/parallel_tool_calls/parallel-mixed-openai-reference-gpt-5.6-nonstreaming.yaml | New OpenAI reference cassette for mixed parallel tools (non-streaming). |
| crates/agentic-server-core/tests/cassettes/parallel_tool_calls/parallel-mixed-gateway-Qwen-Qwen3.5-35B-A3B-FP8-nonstreaming.yaml | New gateway cassette for mixed parallel tools (non-streaming). |
| crates/agentic-server-core/tests/cassettes/parallel_tool_calls/parallel-failures-gateway-Qwen-Qwen3.5-35B-A3B-FP8-nonstreaming.yaml | New gateway cassette covering failures + omitted outputs (non-streaming). |
| crates/agentic-server-core/tests/cassettes/parallel_tool_calls/parallel-client-gateway-Qwen-Qwen3.5-35B-A3B-FP8-nonstreaming.yaml | New gateway cassette for client-only parallel tools (non-streaming). |
| crates/agentic-server-core/src/types/request_response.rs | Forwards explicit parallel_tool_calls; defaults omitted to false; updates unit tests. |
| crates/agentic-server-core/src/types/io/output.rs | Extends web-search action to carry queries; makes MCP list tool comparable; updates continuation shaping. |
| crates/agentic-server-core/src/types/io/input.rs | Adds internal InputItem::McpListTools and strips it from model input. |
| crates/agentic-server-core/src/tool/registry.rs | Refactors ToolEntry to explicit ToolOwnership + GatewayBinding; adds MCP discovery suppression cache. |
| crates/agentic-server-core/src/tool/ownership.rs | New module: binds typed executor params + per-tool-name same-tool concurrency policy. |
| crates/agentic-server-core/src/tool/normalize.rs | Moves tool validation/normalization to typed param interfaces (no serde_json::Value boundary). |
| crates/agentic-server-core/src/tool/mod.rs | Exposes new ownership types + GatewayToolEventPlan. |
| crates/agentic-server-core/src/tool/mcp/registry.rs | Binds discovered MCP tool params to the MCP executor via GatewayBinding. |
| crates/agentic-server-core/src/tool/mcp/handler.rs | Removes MCP side-map; uses typed params for normalization/execution; declares MCP same-tool parallel safe. |
| crates/agentic-server-core/src/tool/handler.rs | Introduces typed ToolHandler/GatewayExecutor params; adds MissingOutput error + gateway event planning hooks. |
| crates/agentic-server-core/src/tool/function.rs | Switches function-tool validation/normalization to typed params and simplifies registry insertion. |
| crates/agentic-server-core/src/tool/executors.rs | Refactors executor registration; ensures web-search handler always exists (spec-only fallback). |
| crates/agentic-server-core/src/tool/custom.rs | Switches custom-tool validation/normalization to typed params and simplifies registry insertion. |
| crates/agentic-server-core/src/tool/codex.rs | Switches namespace-tool validation/normalization/insertion to typed params. |
| crates/agentic-server-core/src/storage/types/item.rs | Preserves MCP list-tools output as internal input items for continuation lifecycle decisions. |
| crates/agentic-server-core/src/executor/upstream.rs | Emits MCP discovery lifecycle from the new registry iterator. |
| crates/agentic-server-core/src/executor/request.rs | Adds gateway scheduler policy to execution context; updates executor registration API. |
| crates/agentic-server-core/src/executor/rehydrate.rs | Rejects continuations missing required tool outputs; preserves MCP list-tools history for registry caching. |
| crates/agentic-server-core/src/executor/pending_calls.rs | New helper to detect unresolved client-executed calls in history/input sequences. |
| crates/agentic-server-core/src/executor/mod.rs | Wires in new pending_calls module. |
| crates/agentic-server-core/src/executor/gateway_accumulator.rs | Reuses unified OpenAI-compatible error object for SSE error events; adds MissingOutput SSE test. |
| crates/agentic-server-core/src/executor/error.rs | Centralizes OpenAI-compatible error object building; ensures MissingOutput matches OpenAI contract. |
| crates/agentic-server-core/src/executor/engine.rs | Refactors tool-loop execution to new scheduler/policy plumbing and one-time MCP discovery emission in streaming. |
| crates/agentic-server-core/src/executor/compaction.rs | Excludes internal MCP-list items from “meaningful context” checks. |
| crates/agentic-server-core/src/config.rs | Adds DEFAULT_MAX_CONCURRENT_GATEWAY_CALLS + runtime config field for max concurrent gateway calls. |
| CHANGELOG.md | Notes behavior changes for parallel tool calling, bounded execution, and MCP discovery caching. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| /// Panics if `queries` is empty. | ||
| #[must_use] | ||
| pub fn new(query: impl Into<String>, sources: Vec<WebSearchSource>) -> Self { | ||
| pub fn new(queries: Vec<String>, sources: Vec<WebSearchSource>) -> Self { | ||
| let query = queries.first().expect("queries must have at least one entry").clone(); | ||
| Self { |
There was a problem hiding this comment.
Fixed in #230. I replaced both web-search constructors with fallible try_new APIs returning a typed WebSearchActionError, added the empty-query regression case, and kept the valid wire shape covered.
| | `function` | Client-owned. Preserve the declaration and return matching calls to the client. | | ||
| | `namespace` | Client-owned Codex grouping for function tools. Flatten members only for upstream requests, then restore returned calls. | | ||
| | `custom` | Client-owned freeform tool. Preserve its opaque format and forward it natively. | |
There was a problem hiding this comment.
Fixed in #230. I replaced the ownership wording with the project’s preferred client-executed and gateway-executed terminology across the Codex integration docs and related Rustdoc.
## Summary - Follow up on review feedback from #214 by replacing the panic-prone `WebSearchActionSearch::new` and `WebSearchCall::new` constructors with fallible `try_new(...)` APIs backed by a typed `WebSearchActionError`. - Preserve the existing valid web-search wire shape and adapt gateway output construction to the fallible API. - Align the Codex integration docs and Rustdoc with the preferred client-executed and gateway-executed tool terminology. - Record the constructor migration and terminology cleanup in the Unreleased changelog. ## Test Coverage All 13 changed code paths are covered, including empty-query rejection, valid serialization, gateway start/completion output, and streaming/non-streaming integration flows. ## Pre-Landing Review No blocking issues found. The adversarial review noted one unreachable swallowed-error path guarded by the existing non-empty query fallback. ## Documentation - `CHANGELOG.md`: clarified tool-execution terminology and documented the fallible constructor migration. - `output.rs`: aligned Rustdoc with gateway-executed built-in tool terminology. - `codex-integration.md`: clarified client-executed continuation behavior. Coverage is adequate for the shipped public surface; no architecture diagram drift was found. ## Test Plan - [x] `cargo fmt --all -- --check` - [x] `cargo clippy --workspace --all-targets -- -D warnings` - [x] `cargo test --workspace` - [x] `pre-commit run --all-files` - [x] `mkdocs build --strict` --------- Signed-off-by: Francisco Javier Arceo <[email protected]>
## Summary Anthropic defines `max_uses` on the web search tool as a hard cap on searches: "The `max_uses` parameter limits the number of searches performed." The Messages loops charge that budget once per tool call. That was exact when #174 added it, because a call carried one `query`. #214 then let the shared `web_search` function tool batch up to five `queries` per call, and that tool is what a native declaration is normalized to for the upstream model. One call can therefore run five searches, and `max_uses: N` allows up to `5N`. With `max_uses: 2` and a model that asks for eight searches over three tool rounds: | Round | Call | Queries | `main` | This PR | | --- | --- | --- | --- | --- | | 1 | `t1` | 3 | runs 3 searches | refused | | 1 | `t2` | 1 | runs 1 search | runs 1 search | | 1 | `t3` | 2 | refused | refused | | 2 | `t4` | 1 | refused | runs 1 search | | 3 | `t5` | 1 | refused | refused | | | Searches performed | | **4** | **2** | The budget now counts searches: - Each gateway call is admitted in model order, before any call starts, only if the remaining budget covers every query it would run. The count comes from the web search handler's own argument parser, so it is the number of searches the handler would perform. - A call the budget cannot cover is refused whole with the existing `max_uses` `tool_result` and leaves the budget for a later call that fits. A call's result is therefore either the output of the call the model made or the `max_uses` error, never the output of a shortened call. - A call whose arguments cannot be parsed performs no search and is no longer charged. An admitted call is charged for the searches it requests whatever their outcome, as a call was before. - Requests without `max_uses`, aliased client tools, mixed client and gateway rounds, and the normalized tool schema are unchanged, so batching stays available. Both loops now dispatch through one function, `executor/messages_tools.rs`, so JSON and SSE cannot apply the rule differently. The streaming path had no `max_uses` test; it has one now. `messages_stream.rs` loses three production lines and stays under its file-size cap. The README and `ARCHITECTURE.md` state the budget unit. Related: #313 and Enterprise Readiness #316 (bounded, predictable built-in tool execution for Messages). ## Test Plan Red on unmodified `main` (d162633) and green with this change. The red run used a separate worktree at `main` with only the test files applied and the workspace crates rebuilt from that worktree. - `native_web_search_max_uses_counts_every_batched_query` and `messages_stream_max_uses_counts_every_batched_query` run the scenario in the table through the JSON and SSE loops and assert the queries the search backend received and every fed-back `tool_result`. On `main` four searches reach the backend. - `native_web_search_malformed_calls_do_not_use_the_budget` and its streaming twin put an empty `queries` list and a non-object input ahead of a valid search under `max_uses: 1`. On `main` the malformed call uses up the budget and the valid search never runs. - `messages_web_search_budget_test.rs` drives the table scenario through the HTTP gateway with `stream: false` and `stream: true`, against an inference and a search backend on a real listener. On `main` both fail with four searches. - Controls that pass on `main` and here: a batch the budget covers runs in full, a request without `max_uses` is not limited, and one search per call is limited as before on both transports. - Unit tests cover `requested_searches` against the handler's parser and the admission rule of the budget. - Against the real `agentic-server` binary with a stdlib inference and search backend, over JSON and SSE: the upstream model is offered the batched `queries` parameter, the binary built from `main` runs four searches under `max_uses: 2`, and the one built from this commit runs exactly two and returns `200` with the final answer and no gateway call. - `pre-commit run --all-files` (including `rust-file-sizes` with `RUST_FILE_SIZE_BASE=origin/main`), `cargo fmt -- --check`, `cargo clippy --all-targets -- -D warnings`, and `cargo test --no-fail-fast` across the workspace pass on the exact commit from a clean worktree. Signed-off-by: Chuyue Wang <[email protected]>
Summary
This PR adds end-to-end parallel tool calling support to the typed Responses API (#181) and aligns gateway behavior
with the OpenAI reference behavior captured in matched cassettes.
Previously, the gateway forced
parallel_tool_calls: falseupstream and executed gateway-executed built-in toolcalls serially. This change:
parallel_tool_callsmodel-generation preference for function, custom, built-in, and mixedtool declarations, while preserving the existing
falsedefault when the field is omitted;window (
tools.max_concurrent_gateway_calls, default5), while preserving model call order in public output;unrelated tools in the same round; MCP and web search explicitly support same-tool parallel execution;
calls to complete; and
lifecycle events around concurrent execution.
The tool registry and execution path were also reworked to make this behavior explicit.
ToolOwnershipnow separatesclient-executed tools from gateway-executed built-in tools, and
GatewayBindingcarries the executor and its same-toolconcurrency policy.
GatewayExecutorowns the started and completed public-output projections for its tool type, andGatewayRoundowns bounded dispatch, per-call timeouts, result ordering, and output shaping. For MCP, typed handlermetadata replaces the duplicated registry side table that could drift out of sync with the main tool entries.
OpenAI parity and correctness fixes found during cassette comparison
The parallel-call recordings exposed several independent bugs in addition to the main feature:
Missing function call outputs were accepted. A continuation could omit the
function_call_outputorcustom_tool_call_outputfor a pending client-executed call and the gateway wouldcontinue with a
200. Rehydration now detects unresolved call IDs in both stored-response and conversationhistory and rejects the continuation with a
400 invalid_request_error, matching the reference behavior.One web-search call could not batch multiple queries. The normalized web-search schema only accepted a
singular
query, despite the publicweb_search_call.actionalready supportingqueries. The schema now acceptseither form, and one call can fan out multiple independent provider requests concurrently and aggregate their
results into one web-search output item.
Mixed built-in rounds could expose an MCP call as a raw
function_call. This occurred when MCP and anothergateway-executed built-in tool ran in the same round. Handler-owned public-output projection and explicit registry
ownership now ensure MCP and web-search calls retain their correct public item types in both streaming and
non-streaming responses.
mcp_list_toolsdiscovery was repeated on every turn. The matched cassettes established an otherwiseundocumented OpenAI behavior: an MCP server's discovery item and lifecycle are exposed on the first response in a
stored chain, and later
previous_response_idturns behave as though that discovery is cached rather than emittingit again. The gateway now retains
mcp_list_toolsin item history and lets the request-scoped registry group currentand historical discovery records by
server_label. Discovery is emitted only when that server has no prior listrecord, and the streaming path consumes the lifecycle after the first inference round.
mcp_list_toolsis history metadata, not model context:InOutItem::into_input_itemspreserves it for registrylifecycle decisions, while
ResponsesInput::model_inputand compaction remove it before inference. Likewise, theoriginal model-facing
function_callandfunction_call_outputitems are the single persisted source for executedweb-search and MCP calls; public
web_search_callandmcp_callitems are no longer lossily reconstructed into asecond copy of model input during rehydration.
Test Plan
OpenAI and gateway cassette coverage
Each scenario was recorded against both the OpenAI reference endpoint and the gateway in streaming and non-streaming
modes with
parallel_tool_calls: true.parallel-builtin-onlymcp_list_toolsis emitted only on the first turn.parallel-mixedparallel-clientparallel-failuresAutomated integration and unit coverage
parallel_tool_calls_testloads the OpenAI and gatewayparallel-builtin-onlycassettes for both response modes andcompares the three-turn request chain, normalized query/argument contracts, two-call grouping per turn, public
output types and order, terminal statuses, SSE lifecycle counts, contiguous sequence numbers, and first-turn-only
MCP discovery.
parallel_tool_calls: true,false, and omitted behavior for client-executed,built-in, and mixed tool declarations, including an HTTP gateway-to-upstream integration check.
opt into same-tool parallelism, stable model call ordering, per-call timeout isolation, and missing-provider error
isolation.
previous_response_idand conversation continuations.compaction input, is ignored for servers absent from the active request, and is emitted only once for blocking and
streaming continuations.
Commands used for focused verification:
cargo build --release cargo test -p agentic-server-core --test parallel_tool_calls_test cargo fmt --all -- --check