Repository navigation
feat: add compile-time OpenAPI spec generation via utoipa - #229
Conversation
There was a problem hiding this comment.
Pull request overview
Adds feature-gated OpenAPI 3.1 generation (via utoipa) to agentic-server, exposing the generated spec at GET /openapi.json and wiring a Swagger UI under /swagger-ui/, while annotating all HTTP handlers and a large set of core wire types with schema metadata.
Changes:
- Introduces
openapifeature (default-on) inagentic-serverand propagates anopenapifeature intoagentic-server-corefor schema derives. - Adds
utoipa::pathannotations across all HTTP handlers and a newopenapimodule that builds the OpenAPI doc + security scheme + Swagger UI router. - Adds integration-style tests that fetch
/openapi.jsonand/swagger-ui/and validate basic spec structure.
Reviewed changes
Copilot reviewed 23 out of 24 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
| crates/agentic-server/tests/openapi_test.rs | Adds runtime tests for /openapi.json and /swagger-ui/. |
| crates/agentic-server/src/openapi.rs | Defines ApiDoc OpenAPI doc, security modifier, error schemas, Swagger UI router, and spec-shape unit tests. |
| crates/agentic-server/src/lib.rs | Conditionally exports the new openapi module behind the feature gate. |
| crates/agentic-server/src/handler/http/responses.rs | Adds utoipa::path metadata for /v1/responses and /v1/responses/compact. |
| crates/agentic-server/src/handler/http/models.rs | Adds utoipa::path metadata for /health, /ready, and /v1/models. |
| crates/agentic-server/src/handler/http/mod.rs | Makes HTTP submodules pub(crate) so OpenAPI path references can resolve. |
| crates/agentic-server/src/handler/http/messages.rs | Adds utoipa::path metadata for /v1/messages and /v1/messages/count_tokens. |
| crates/agentic-server/src/handler/http/conversations.rs | Adds utoipa::path metadata for /v1/conversations. |
| crates/agentic-server/src/app.rs | Merges Swagger UI/OpenAPI router into public routes when openapi is enabled. |
| crates/agentic-server/Cargo.toml | Adds openapi feature (default-on) and optional utoipa* dependencies. |
| crates/agentic-server-core/src/types/tools/params.rs | Adds OpenAPI schema support for tool parameter types (including manual schemas). |
| crates/agentic-server-core/src/types/request_response.rs | Adds ToSchema derives for Responses request/response payload types. |
| crates/agentic-server-core/src/types/messages/request.rs | Adds ToSchema derives and manual schemas for untagged / complex message request shapes. |
| crates/agentic-server-core/src/types/messages/mod.rs | Re-exports additional message types needed by schema registration. |
| crates/agentic-server-core/src/types/io/usage.rs | Adds ToSchema derives for usage structs. |
| crates/agentic-server-core/src/types/io/tools.rs | Adds manual OpenAPI schema for ToolChoice and derives for related tool-choice types. |
| crates/agentic-server-core/src/types/io/output.rs | Adds ToSchema derives and manual schemas for output event item types. |
| crates/agentic-server-core/src/types/io/mod.rs | Re-exports additional IO types needed by schema registration. |
| crates/agentic-server-core/src/types/io/input.rs | Adds ToSchema derives and manual schemas for input item/content unions. |
| crates/agentic-server-core/src/types/event.rs | Adds ToSchema derives for status enums used in schemas. |
| crates/agentic-server-core/Cargo.toml | Adds openapi feature and optional utoipa dependency. |
| Cargo.toml | Adds workspace deps for utoipa, utoipa-axum, and utoipa-swagger-ui. |
| Cargo.lock | Locks transitive deps introduced by the new OpenAPI/Swagger UI crates. |
Suppressed comments (1)
crates/agentic-server-core/src/types/tools/params.rs:313
CodexNamespaceMemberis also#[serde(tag = "type")], but this schema only referencesFunctionToolParamand does not include the requiredtypediscriminator property (nor theunknownvariant). This makes the generated OpenAPI schema inaccurate for clients consumingCodexNamespaceToolParam.tools. Recommend emitting an object schema that includestypeand the variant payload (e.g.,allOfwith{type: "function"}+FunctionToolParam, plus anunknownfallback if desired).
impl utoipa::PartialSchema for CodexNamespaceMember {
fn schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
utoipa::openapi::schema::OneOfBuilder::new()
.discriminator(Some(utoipa::openapi::schema::Discriminator::new("type")))
.item(utoipa::openapi::Ref::from_schema_name("FunctionToolParam"))
.into()
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
4b1e085 to
bd6c928
Compare
|
@maralbahari Thanks for the valuable review. Addressed all of them. |
thanks. kindly fix the CI for approval |
Done. Fixed remaining rustfmt issues due to rustup version mismatch. |
maralbahari
left a comment
There was a problem hiding this comment.
Thanks for the work on this.
Left four more inline comments. Two bits of context on where they came from:
- I ran a local
cargo buildon the branch and hit a build-time network fetch pulled in by the Swagger UI dependency. That is the one I would want sorted before merge. - #214 landed after you opened this, and the rebase left a couple of the hand-written schemas slightly behind the types they describe.
The rest are small.
|
@avinashsingh77 could you please resolve merge conflicts. Thanks |
d3859ad to
3b7a7c0
Compare
|
@maralbahari Please review and approve. |
franciscojavierarceo
left a comment
There was a problem hiding this comment.
the feature currently isn't exercised by CI, and several published schemas do not match request and response shapes that the runtime and existing tests accept. requesting changes so the generated contract is usable by clients and tested whenever openapi is enabled.
|
franciscojavierarceo
left a comment
There was a problem hiding this comment.
the earlier schema fixes are present, but two endpoint schemas still reject shapes the handlers support. details inline; these findings are from source and existing test fixtures, not a fresh full-suite run.
Add feature-gated (`openapi`) OpenAPI 3.1 spec served at /openapi.json with Swagger UI at /swagger-ui/. Covers all HTTP endpoints (Responses, Messages, Conversations, health/ready, models) with full request/response schemas including tagged enums, serde aliases, and untagged unions. Includes 9 unit tests validating path coverage, schema ref resolution, OpenAPI 3.1 meta-schema conformance, and per-variant fixture validation for InputItem, OutputItem, and ResponsesTool. Co-Authored-By: Claude Opus 4.6 <[email protected]> Signed-off-by: Avinash Singh <[email protected]>
Signed-off-by: Avinash Singh <[email protected]>
Signed-off-by: Avinash Singh <[email protected]>
Signed-off-by: Avinash Singh <[email protected]>
118e4b4 to
190ecbf
Compare
Thanks @franciscojavierarceo for the thorough review. Both endpoint schema issues are fixed, and I've added two new systematic test functions to prevent this class of bug going forward:
|
Signed-off-by: Francisco Javier Arceo <[email protected]>
…ntracts (#373) ## Summary issue: #229 PR 1 teaches the gateway to represent multi-agent Responses items, but does not run agents. This PR adds the HTTP runtime: a stored request with `multi_agent.enabled: true` can spawn and coordinate subagents, return their work in one Responses result or SSE stream, and resume the tree through `previous_response_id`. The `multi_agent` option belongs to the gateway; it is not forwarded as a provider option. The gateway exposes collaboration actions to the model as gateway-owned function tools while retaining ordinary client tools such as web search, MCP, and local shell. This is separate from `parallel_tool_calls`, which controls tool-call parallelism within a model turn rather than agent lifecycles. Request admission requires `store: true`, rejects a zero concurrency limit, and rejects reasoning summaries and explicit compaction triggers with multi-agent enabled. An omitted `max_concurrent_subagents` uses three active descendant slots; the root is separate from that limit. The gateway validates continuation against the stored tree, rather than trusting client-supplied collaboration transcript items to recreate an agent. ## Implementation and review boundary - `EngineOrchestration` selects the existing single-agent path or a `MultiAgentRun`. The response coordinator owns the agent registry, task ownership, mailboxes, pending client calls, shared response budget, completion, and persistence. Each agent has its own `AgentPipeline`, tool registry, context, and round progress. This split lets agent tasks run concurrently without creating an independent public response per child. Collaboration functions implement spawning, messaging, follow-up, waiting, interruption, and listing; per-agent guidance narrows the assigned job and discourages unnecessary delegation and waits. - Each upstream agent round is identified separately. A bounded agent-frame channel feeds one public response assembler, which assigns public output positions and SSE sequence numbers and emits a single terminal response. Streaming delivery acknowledges accepted frames and cancels outstanding work when the client stream is dropped. The merge with current main keeps its execution and inference-round telemetry in this path. Nonstreaming uses the same agent results and response assembly. - A versioned `StoredTreeSnapshot` records the canonical agent tree, histories, and pending-call relationships. Checkpoint loading validates references and limits before constructing live tasks. Typed `commit_tree` methods on the existing response and conversation handlers persist the tree with the public result; storage serialization remains at that boundary. Continuations match client outputs to their owning agent and call ID. Public encrypted agent-message content remains separate from gateway-owned canonical mail. - Automatic compaction works on an immutable resolved prefix for one agent. `CompactionPlan` carries the agent identity and context generation; `CompactionCommit::{Applied, Stale}` replaces that prefix only if the generation still matches. This preserves intervening mail, pending calls, and appended history. Discovery items and prompt-cache settings are retained through the compaction request. The existing single-agent compaction path is still available when multi-agent is disabled. The runtime code is divided across `engine/agent_turn.rs`, `engine/multi_agent/*`, `executor/multi_agent/*`, and pipeline delivery/projection modules so the coordinator, per-agent execution, registry, collaboration actions, streaming, checkpoint validation, and compaction each have a clear owner. The resulting file-size baseline change removes the old oversized `engine.rs` entry; a narrow documented allowance covers the expanded request-admission module. ### Recorded scenario comparison Gateway: `Qwen/Qwen3.6-35B-A3B-FP8`. OpenAI reference: `gpt-5.6-sol`. Counts represent unique calls across each complete session, including client-tool continuations, rather than repeated SSE appearances. Model-generated text, reasoning, names, and action counts are not expected to match exactly. **Proposals** Prompt: Delegate retrieval and assessment of proposals alpha and beta, then recommend one using the returned data. Tests parallel delegation and client-owned function-call continuation. | Metric | OpenAI nonstream | Gateway nonstream | OpenAI stream | Gateway stream | |---|---:|---:|---:|---:| | Successful spawns | 2 | 2 | 2 | 2 | | Collaboration calls | 17 | 6 | 18 | 9 | | Waits / timeouts | 4 / 4 | 4 / 2 | 7 / 5 | 1 / 0 | | Function calls / returned outputs | 6 / 6 | 4 / 4 | 4 / 4 | 2 / 2 | | Completed | Yes | Yes | Yes | Yes | Gateway streaming recovered from six invalid `list_agents` requests containing `timeout_ms`. **Review** Prompt: Delegate correctness, security, and test-coverage review of a Python cache using `pickle.loads` on unauthenticated input, then consolidate findings. Tests agent creation, messaging, and completion without external tools. | Metric | OpenAI nonstream | Gateway nonstream | OpenAI stream | Gateway stream | |---|---:|---:|---:|---:| | Successful spawns | 3 | 3 | 3 | 3 | | Collaboration calls | 6 | 9 | 7 | 7 | | Waits / timeouts | 3 / 0 | 4 / 0 | 3 / 1 | 4 / 1 | | Agent messages | 6 | 6 | 6 | 6 | | Completed | Yes | Yes | Yes | Yes | Gateway nonstreaming rejected one extra spawn at the concurrency limit. **Mixed tools** Prompt: Delegate Python CSV web research, tiktoken research through the remote GitMCP server, and the local-shell calculation `python3 -c 'print(sum(range(1, 11)))'`, then combine the findings. Tests mixed tool ownership and continuation with mocked client shell outputs. | Metric | OpenAI nonstream | Gateway nonstream | OpenAI stream | Gateway stream | |---|---:|---:|---:|---:| | Successful spawns | 3 | 3 | 4 | 3 | | Collaboration calls | 18 | 16 | 24 | 13 | | Waits / timeouts | 7 / 4 | 9 / 5 | 11 / 6 | 6 / 0 | | Web / MCP calls | 2 / 2 | 1 / 2 | 2 / 2 | 2 / 4 | | Shell calls / returned outputs | 3 / 3 | 2 / 2 | 4 / 4 | 2 / 2 | | Completed | Yes | Yes | Yes | Yes | OpenAI streaming created a replacement fourth agent over the session; the limit applies to concurrent subagents. Gateway repeated some shell work. Shell outputs are scripted fixtures, not actual shell executions. All twelve recordings reached completed responses. Collaboration calls have matching outputs, and streaming sequence and item-identity checks passed. Successful gateway `list_agents` results use `agent_name` and `agent_status`, including completed answer text. The Rust cassette comparison tests passed: **7 passed, 0 failed, 1 optional test ignored** (`cargo test -p agentic-server-core --test multi_agent_contract_test --offline -- --test-threads=2`). | Client-owned tools | OpenAI nonstream | Gateway nonstream | OpenAI stream | Gateway stream | |---|---:|---:|---:|---:| | Successful spawns | 3 | 3 | 3 | 3 | | Collaboration calls | 8 | 5 | 15 | 5 | | Waits / timeouts | 2 / 1 | 2 / 0 | 4 / 3 | 2 / 0 | | Tool-search calls / returned outputs | 6 / 6 | 2 / 2 | 6 / 6 | 2 / 2 | | Discovered function calls / returned outputs | 2 / 2 | 2 / 2 | 4 / 4 | 2 / 2 | | Custom calls / returned outputs | 1 / 1 | 1 / 1 | 1 / 1 | 1 / 1 | | Completed | Yes | Yes | Yes | Yes | ## Stack and scope This is PR 2 of 2, branch `multi-agent-http-support-pr-2` at `96494f8`, targeting PR 1 `multi-agent-http-support-pr-1` at `b8e71e6`. ## Test Plan - `cargo test` - `recoded cassettes` --------- Signed-off-by: maral <[email protected]>
Summary
Adds a feature-gated (
openapi, default-on) OpenAPI 3.1 spec served at GET /openapi.json, covering all 8 HTTP endpoints with request/response schemas, Bearer auth, and error envelopes.~40 types auto-derive ToSchema; ~15 complex types (untagged enums, custom serde) get manual PartialSchema + ToSchema impls.
Zero-cost when the feature is disabled.
Test Plan
cargo check --features openapi— compiles with OpenAPI enabledcargo check --no-default-features— compiles with OpenAPI disabled (zero-cost gate)cargo clippy --features openapi --all-targets— zero warningscargo test --features openapi— all tests passcargo test --no-default-features— all tests pass without the featurespec_contains_expected_paths— all 8 endpoint paths presentspec_contains_core_schemas— core schemas registeredspec_has_security_scheme—bearer_authscheme presentspec_serializes_to_valid_json— valid OpenAPI 3.x JSONspec_schema_refs_resolve— all$refpointers resolvespec_validates_against_openapi_3_1_meta_schema— formal validation against OpenAPI 3.1 meta-schemaGET /openapi.jsonreturns valid spec with all paths/schemasGET /swagger-ui/returns HTMRelated #218