Repository navigation
Conversation
|
Thanks for the work on this and for reusing the shared MCP discovery and execution infrastructure. I have a few concerns about Anthropic compatibility, the maintainability of the Messages transformations, and streaming validation that I’d like us to address before merging. 1. Mixed client/MCP calls appear to execute in the wrong orderAnthropic documents that when client and server tools are called in the same group, the API returns Here, Please defer the pending MCP call until the client supplies its result, and cover that continuation in both JSON and streaming. 2. The gateway-owned protocol transformations need stronger typesThe typed server/configuration declarations and shared registry are useful, but Preserving opaque provider fields is reasonable, but fields the gateway interprets and generates should have typed variants and explicit conversions. Arbitrary tool arguments and JSON Schema can remain JSON. Please model the supported tool declarations as distinct variants and use typed conversions for MCP history and public content blocks. 3. JSON and streaming should share the same MCP projection contractJSON uses Compared with the Responses pipeline’s typed ingestion and lifecycle projection, this creates more places for behavior to drift and makes maintenance harder. Please centralize MCP call/result projection and execution policy, with transport-specific serialization around it. Versioned tool-search identifiers should live in an explicit capability policy rather than scattered string checks. 4. Please add recorded Anthropic-versus-gateway cassettesThe local HTTPS and malformed-stream tests are useful, but this PR adds no recorded Messages MCP reference cassettes. The existing Responses MCP recorder captures paired OpenAI and gateway scenarios; we need equivalent Anthropic reference recordings for the supported MCP beta, using the same controlled MCP server. Please cover:
Compare the recorded protocol behavior after normalizing nondeterministic values such as generated IDs. In particular, the mixed streaming continuation test replaces the MCP input with hardcoded I’d encourage extending the Rust patterns already practiced in this repo such as Feel free to split this work into multiple PRs if needed, so the design changes, compatibility fixes, and recorded cassette coverage can each be reviewed more easily. |
|
@maralbahari Thanks for the detailed feedback. I'd like to confirm the split and validation approach before proceeding. The mixed client/MCP execution-order fix is already pushed in 912c34f: pending MCP calls wait for the client results, with JSON and streaming continuation coverage. The streaming tests now reconstruct arguments from the emitted deltas rather than substituting a hardcoded input. The stronger typing and shared projection work still needs to be completed. I propose three PRs in total, retaining this draft as the feature PR:
The documentation-driven fixtures would be explicitly labeled as synthetic tests, not represented as captured Anthropic cassettes. They establish conformance to the documented rules but do not replace evidence of the live service's behavior. Would this split work for you? In particular, would you accept the documented-contract tests as the feature PR's validation, with real reference recordings in a follow-up, or should those recordings remain a prerequisite for merging the feature PR? I'll keep #425 in draft while the implementation and this validation boundary are being resolved. |
## Summary Messages tool declarations currently combine every kind behind an optional string discriminator. Replace that struct with explicit `Function`, `WebSearch`, `WebFetch`, and opaque `Provider` variants, with exhaustive conversion into the existing tool layer. Supported native declarations retain their original protocol version and opaque extension fields; serialization borrows the declaration rather than cloning it. This is the independently reviewable type foundation extracted from #425, following the [typing feedback](#425 (comment)) and [proposed split](#425 (comment)). It does not depend on the MCP connector. MCP history conversions, execution/projection changes, and reference recordings remain separate work; acceptance of the proposed recording follow-up is still under discussion. Rebased onto upstream `main` at `8d6fa8421bf1df8a0419baf005be66cdde748870`, including #424. Following the [version compatibility review](#431 (comment)), classification and request validation now share the exact native-version capability tables in `types/messages/tools/versions.rs`, re-exported at their existing public paths. All three search and four fetch versions retain their declared `type`. Search declarations carry `allowed_domains`, `blocked_domains`, and `user_location` into the registry and execution backend. This preserves #424's direct-call restrictions and version-specific validation; it does not add dynamic filtering or silently support future versions. Preserve the HTTP wire contract, execution ownership, operator aliases, and exact JSON/SSE pass-through. Existing Rust import paths remain available; Rust callers use enum variants instead of the former struct literal. The architecture documents the shared version policy and extension path. ## Test Plan - RED: after rebasing, the retained #424 registry test fails for `web_search_20260209` with `allowed_domains = None`, reproducing the review finding. The repaired test passes for every supported search version, including blocked domains. - `cargo test --workspace`: 2,330 passed, 0 failed, 18 ignored. - `cargo clippy --workspace --all-targets --locked -- -D warnings`. - `cargo fmt --all -- --check`, `git diff --check`, and all pre-commit hooks using pre-commit 4.4.0. - Classify and round-trip every supported search/fetch version without rewriting its discriminator; preserve opaque unknown versions, including near-miss dates and suffixed known types. - Differential parsing/serialization checks against the pre-refactor shape across 200 kind/name/schema combinations, plus nulls, malformed fields, duplicate keys, and opaque extensions. - Retain #424's registry and HTTP version/caller/capability tests. Expand JSON and SSE execution tests to check allowed and blocked domains separately plus user location for every search version; retain fetch execution tests for every supported fetch version. - OpenAPI schema/Serde agreement and unchanged HTTP JSON/SSE provider-tool forwarding. --------- Signed-off-by: zitian.zhao <[email protected]> Co-authored-by: Francisco Javier Arceo <[email protected]>
## Summary Share JSON/SSE round decisions (continue gateway execution, return client calls, finish, and client-call `end_turn` correction) and completed `MessagesToolCall` data with typed argument errors. Parse streamed arguments once for history and dispatch while keeping malformed input non-executable. Rebased on current main (`a7dc7b5`). Reuse its registry bindings and `GatewaySchedulerPolicy` (#437), preserving model-order budget admission, permit acquisition/concurrency limits, timeout after permits, tool-stage timing/error status, and cancellation. Existing ingestion validation, live delivery, opaque history and usage remain intact. Follow-up to #431, tracked by #418 ([split plan](#418 (comment))). MCP-specific projection and pending-call continuation remain in #425. Kept as draft for review of this independent refactor. ## Test Plan - 14 shared synthetic scenarios on JSON and SSE cover named/client/mixed/truncated rounds, stop reasons, escaped/Unicode arguments, history and usage. - Messages unit tests: 71 passed, including all 8 existing scheduling/lifecycle tests. JSON/SSE, web-fetch and execution-trace integration targets: 86 passed, including live delivery, cancellation, invalid streams/arguments and typed tool stages. - `cargo test --workspace --locked --no-fail-fast`: 2,723 passed, 0 failed, 18 ignored; includes existing HTTP budget/ownership tests and cassette replays. - `cargo clippy --workspace --all-targets --locked -- -D warnings`, formatting, diff checks and all pre-commit 4.4.0 hooks passed. The first sandboxed unit run could not bind localhost for 4 mock-server tests; the rerun with local-port access passed all 71. No new recordings were added. Feature-enabled Linux and PostgreSQL coverage runs in repository CI. Signed-off-by: zitian.zhao <[email protected]> Co-authored-by: Maral <[email protected]>
Signed-off-by: zitian.zhao <[email protected]>
912c34f to
04cc834
Compare
Signed-off-by: zitian.zhao <[email protected]>
|
@maralbahari Following up on the earlier validation proposal: the typed declarations, shared JSON/SSE projection, and mixed-call continuation changes are now implemented, and CI is green on 4509893. I don't currently have access to a native Anthropic API environment with MCP connector support. Could you please confirm whether paired live Anthropic/gateway recordings for If recordings are required before merging, could you or another contributor with access help capture and share sanitized Anthropic requests, responses, and raw SSE events against the same controlled MCP server? I can prepare reproducible recording instructions and incorporate the captures into replay tests and comparisons. The current fixtures remain explicitly labeled as synthetic; live Anthropic parity has not been verified. |
Merge upstream main into codex/messages-mcp-connector-418. Preserve the test-only MCP certificate feature and optional PDF search feature. Signed-off-by: zitian zhao <[email protected]>
Signed-off-by: zitian.zhao <[email protected]>
maralbahari
left a comment
There was a problem hiding this comment.
Thanks for working through the previous round. The mixed-call ordering now matches Anthropic's documented behavior, the streaming continuation test rebuilds its arguments from the emitted deltas, and the declarations and content blocks are typed. Those were the right fixes.
Recordings. Please finish the design first. I can help record the cassettes after that. Until we have that evidence, though, we can't conclude that the behavior is correct.
Architecture. This is the main blocker now. The feature works, but it was built as a separate Messages-only system next to the shared MCP path, not as an extension of that path. Responses already has a single owner for each step below. The Messages connector should reuse those owners and add only a Messages wire adapter. Today each step has a second, Messages-specific copy:
| Step | Responses on main (the pattern to follow) | This PR |
|---|---|---|
Wire declaration to ToolDeclaration |
From<&ResponsesTool> / responses_declarations in tool/declaration.rs, keeping the request's tool order |
connector_tools() in tool/mcp/messages.rs, appended after registry_tools(), so the request order is lost |
| Registry construction | build_tool_registry in executor/engine/agent_turn.rs, using build_with_handlers_guarded with the response budget and the materialization permit |
MessagesRequestContext::prepare_registry in messages_context/registry.rs, built a second time in prepare_messages_count_tokens. Both use the unguarded build_with_handlers |
| Recording discovered tools on the request | record_discovered_mcp_tools, writing into the typed request |
normalize_connector editing raw["tools"] by hand |
| Discovered tools to upstream function tools | McpHandler::normalize, then discovered_mcp_function_tool |
a hand-built ToolParam::Function inside normalize_connector |
| MCP identity (server, tool name) | the registry entry: ToolEntry { tool_type: Mcp, server_label } plus the bound McpDiscoveredToolParam |
a new GatewayToolMap.mcp_tools: HashMap<String, (String, String)>, a per-request copy in ctx.gateway_tools, and gateway_tools_or(fallback) |
| Identity used for the public call/result | McpDiscoveredToolParam bound in the registry, read by GatewayExecutor::started_output / public_output |
GatewayToolMap::public_mcp_call(&Value) and client_tool_result, which scans the content for each result |
Wire types for mcp_tool_use / mcp_tool_result |
one OutputItem::McpCall |
four separate types: KnownContentBlock::McpTool*, McpContentBlock, ConnectorHistoryBlock, PendingMcpCall |
| Pending-call policy | decided once (CallLedger, pending_calls.rs) |
mixed_mcp_continuation(bool, Option<&str>) called from four places, plus the same invalid-arguments check written twice |
Requested direction:
- One declaration adapter.
map_tool/registry_toolsshould mapToolParam::McpToolsettoToolDeclaration::Mcp, resolving its server frommcp_servers. Declarations then mirror the request in order, as they do for Responses. Discovered tools are written back into the typed declaration, and upstream normalization runs throughMcpHandler::normalize. This removesconnector_tools, the server lookup insidenormalize_connector, and most of the rawValueediting. - The registry stays the only registry. Remove
GatewayToolMap.mcp_tools,MessagesRequestContext.gateway_tools, andgateway_tools_or. Read the MCP identity (server_label,tool_name) from the registry entry and its binding, as Responses does, and build the Messagesmcp_tool_use/mcp_tool_resultblocks from it. Only the tool side is shared. Anthropic has no per-item lifecycle events like OpenAI'sresponse.mcp_call.*, so the Messages output stays plain content blocks, using the genericcontent_block_start/delta/stopevents. - Keep the shared types protocol-neutral. Don't add
messages_configtoMcpToolParamorapply_messages_configtotool/. The enabled/disabled filter can be expressed as a neutral tool filter onMcpToolParamthat both APIs could use. - One Rust type per wire block, owned by
types/messages/content.rs. Projection, replay and pending detection should all use it. - Decide the pending-MCP case once, in
decide_round, as aMessagesRoundDecisionvariant. The JSON and SSE paths then match on that variant. They shouldn't recompute it from strings. - Route
count_tokensthroughParsedMessagesRequest/MessagesRequestContext, so that one preparation function serves both endpoints. - Keep the diff to the feature. Moving
complete_round/execute_round/take_roundintomessages_stream/round.rsand movingMcpToolParamintotypes/tools/mcp.rsare unrelated relocations. Please drop them or split them into a separate PR.
There is also a smaller routing change (inline on messages_context.rs): any request that carries mcp_servers is now sent to the gateway. The gateway rejects the deprecated mcp-client-2025-04-04 shape, which main currently passes through.
I'd expect this restructuring to make the PR noticeably smaller, because most of messages_connector.rs, replay.rs, tool/mcp/messages.rs and the tool_seam.rs additions turn into calls to existing code. If it helps, please post a short design comment covering items 1, 2 and 5 before rewriting, and I'll confirm the shape.
| /// | ||
| /// # Errors | ||
| /// Returns validation, discovery-budget, or serialization errors before inference begins. | ||
| pub async fn prepare_registry( |
There was a problem hiding this comment.
This adds a second place that constructs a registry, and prepare_messages_count_tokens (messages_connector.rs:22) repeats the same sequence a third time: registry_tools + connector_tools + build_with_handlers + validate_connector_discovery + normalize_connector. For Responses, registry construction lives in the executor (engine/agent_turn.rs::build_tool_registry). It uses build_with_handlers_guarded, so MCP discovery is charged to the response budget and takes a materialization permit from GatewaySchedulerPolicy. This path skips both, so concurrent Messages requests can run MCP discovery without the limits that Responses enforces. Please keep a single Messages preparation function, owned by the executor and shared by /v1/messages and count_tokens, that calls the guarded builder with the same policy.
The thread-only early return at line 24 also gives threads and non-thread requests different behavior for the same mcp_servers body. See the routing comment on messages_context.rs:70.
| pub struct GatewayToolMap { | ||
| /// client tool name (as the model calls it) → canonical executor key. | ||
| aliases: HashMap<String, String>, | ||
| mcp_tools: HashMap<String, (String, String)>, |
There was a problem hiding this comment.
This is a second MCP registry. The ToolRegistry already holds the same data: ToolEntry has tool_type == ToolType::Mcp and server_label, and the binding carries McpDiscoveredToolParam { server_label, tool_name, internal_name }. Keeping both means two sources of truth that need syncing, which is why normalize_connector inserts into the map, prepare_registry copies it into ctx.gateway_tools, and both loops call gateway_tools_or(&exec_ctx.messages_gateway_tools). mcp_internal_name also does a linear reverse scan over an untyped tuple. Please look up the identity through the registry, and keep GatewayToolMap for what it's for: operator aliases and web_fetch ownership.
public_mcp_call(&Value) (line 120) and project_pending_mcp (line 281) also put raw-JSON projection logic into types/. That projection belongs in the executor, next to the existing native-tool projection, and should build the Messages blocks from the identity in the registry binding. It shouldn't reuse public_output itself, because that returns the OpenAI OutputItem::McpCall, which has no Messages counterpart.
| /// Messages connector selection, applied before registration. | ||
| #[serde(skip)] | ||
| #[cfg_attr(feature = "openapi", schema(ignore))] | ||
| pub(crate) messages_config: Option<McpToolsetConfig>, |
There was a problem hiding this comment.
McpToolParam is the protocol-neutral declaration shared by both APIs, and with this field types/tools now imports from types/messages. tool/mcp/registry.rs::apply_messages_config then branches on a Messages-only config inside the shared registry. Both reverse the layering in ARCHITECTURE.md. The concepts are already neutral: "this tool is enabled" is a filter (Responses has allowed_tools), and defer_loading already exists on the param. Please model the filter as a neutral field that the Messages adapter fills from default_config / configs, so tool/ never sees Messages types.
McpToolsetConfig::effective (types/messages/mcp.rs:27) returns an unnamed (bool, bool), and callers read .0 / .1. A small named struct would make those call sites readable.
| /// | ||
| /// # Errors | ||
| /// Rejects ambiguous server identities and missing or duplicate toolsets before I/O. | ||
| pub fn connector_tools(servers: &[McpServer], tools: &[ToolParam]) -> Result<Vec<ToolDeclaration>, ToolError> { |
There was a problem hiding this comment.
Several issues in this function:
- It validates the wire shape (non-empty unique names,
config.kind != "url", anhttps://prefix, exactly one toolset per server) insidetool/. Validation of wire fields belongs on the owning type intypes/messages/parameters.rs, e.g.kindas an enum and avalidate/TryFromonMcpServer, so every entry point gets it. - It fills
McpToolParamwith sevenNoneplaceholders andrequire_approval: Some("never".to_owned()). AFrom/TryFromconversion that sits besideFrom<&ResponsesTool>intool/declaration.rswould keep both adapters in one place. - It returns the MCP declarations after all other tools, so they no longer follow the request's tool order. That's why
normalize_connectorhas to look each toolset up again byserver_label. MappingMcpToolsetinsidemap_toolfixes this.
| /// Expand connector declarations without changing history. Native server-tool | ||
| /// replay must retain each call/result pair in its original assistant message; | ||
| /// MCP history is lowered only after that replay has completed. | ||
| pub(super) fn normalize_connector( |
There was a problem hiding this comment.
This still edits declarations through raw JSON (raw["tools"].as_array_mut(), body.remove("mcp_servers"), extra.get("defer_loading")), which was point 2 of the earlier review. At line 178 it also builds the upstream function tool by hand from discovered.tool, which duplicates McpHandler::normalize and discovered_mcp_function_tool in tool/mcp/handler.rs. When Responses changes how an MCP tool is lowered, for example its schema handling or loaded_tool_names filtering, Messages won't follow. Please go through the handler's normalize and convert the resulting FunctionTool to a Messages tool in one From impl.
has_mcp_state (line 52) is a third raw-JSON scan of the request, alongside parsed.typed.mcp_servers and MessageContent::has_mcp_blocks. The typed request already answers this question.
| Ok(parsed) => Ok((parsed.is_thread() || has_gateway_tool(parsed.tools(), gateway_map)).then_some(parsed)), | ||
| Ok(parsed) => Ok((parsed.is_thread() | ||
| || has_gateway_tool(parsed.tools(), gateway_map) | ||
| || parsed.typed.mcp_servers.is_some() |
There was a problem hiding this comment.
Minor. parse_for_gateway now sends any request with mcp_servers to the gateway. On main, a request with mcp_servers and no gateway tool is proxied unchanged. connector_tools then rejects every server that lacks an mcp_toolset ("each MCP server must have exactly one mcp_toolset"). That covers the mcp-client-2025-04-04 shape, which McpServerFingerprint still models through tool_configuration. Anthropic marks that beta as deprecated, so dropping it is reasonable, but it should be a deliberate choice and not a side effect. prepare_registry already makes this exception for threads (line 24 of registry.rs), so threads and non-thread requests currently behave differently for the same body. Please pick one rule for both. Either route to the connector only when the request declares an mcp_toolset or replays mcp_tool_* blocks, which keeps the pass-through, or reject the old shape with a clear "deprecated beta, migrate to mcp_toolset" error. Add a test for whichever you choose.
| } | ||
|
|
||
| impl ClientToolUse { | ||
| pub(super) fn streamed(self) -> (Value, String) { |
There was a problem hiding this comment.
streamed returns an untyped (Value, String), and serde_json::to_value(...).unwrap_or_default() (lines 222 and 228) turns a serialization failure into null content, which is then sent to the client. with_empty_input exists only to support this. Please return a typed start-block/argument pair and propagate the error. This is also the spot where the MCP projection should become a variant of the existing native projection (ExecutedCall.server_result), so it stops scanning content with client_tool_result for each result (line 242). Build the call block from the identity in the registry binding at admission, like native calls. Streaming should stay the same as for server_tool_use: start with empty input, send arguments as input_json_delta, and deliver the result whole in content_block_start. That's the only pattern Anthropic documents, so please don't add per-call lifecycle states modeled on OpenAI's mcp_call events.
| } | ||
| } | ||
| let mut executors = state.exec_ctx.gateway_executors.clone(); | ||
| match prepare_messages_count_tokens(&bytes, &state.exec_ctx.messages_gateway_tools, &mut executors).await { |
There was a problem hiding this comment.
This re-reads bytes as untyped JSON and runs a separate preparation path. It should decode once into ParsedMessagesRequest and call the same executor-owned preparation as /v1/messages. Then token counting can't diverge from execution in normalization, discovery limits or validation.
| @@ -0,0 +1,128 @@ | |||
| //! Completed round handling for Messages streams. Ingestion owns the buffered | |||
There was a problem hiding this comment.
Most of this file is complete_round, execute_round, terminal_content, take_round and round_decision moved out of messages_stream.rs, with small edits. Moving them makes the actual behavior change hard to review in a feature PR. Please keep them where they were and change them in place, or move them in a separate PR. The same applies to moving McpToolParam out of types/tools/params.rs.
|
|
||
| // Inspect the discriminator before decoding its fields: an MCP toolset has no | ||
| // function name, and malformed known declarations must never enter the fallback. | ||
| struct DeclarationFields; |
There was a problem hiding this comment.
Replacing the derived WireTool decode with a hand-written Visitor and a hard-coded list of duplicate-checked field names means that list must be updated every time a field is added. The repo skill asks for custom deserialization only when derive can't express the contract. An internally tagged or adjacently dispatched enum with ToolParam::McpToolset as its own variant should be able to do this with derives. If it can't, please add a comment explaining why.
|
@skyloevil converted to draft PR once everything is addressed and ready for review please open again |
Summary
Implement the
mcp-client-2025-11-20connector on/v1/messagesand/v1/messages/count_tokens, based on main432b80dand the merged #431/#468 foundations.{}.The supported remote transport is Streamable HTTP. Deferred loading requires an upstream-hosted Anthropic search implementation; this PR does not add one. The newer
mcp-client-2026-09-15pinned-catalog beta is outside this scope.Closes #418.
Test Plan
4b7fd36. GitHub recorded 15 passing checks and two expected skips for website deployment and PyPI publication. The Claude Code and Codex smoke tests passed.cargo test --workspace --locked --offline --no-fail-fastpassed with 3,140 passed and 26 ignored before an equivalent lint-only change. The final code passed all 29 focused MCP, thread HTTP, and thread replay tests.cargo clippy --workspace --all-targets --locked --offline -- -D warnings, formatting, diff checks and all pre-commit 4.4.0 hooks passed.mcp-test-support.Tests are synthetic, documentation-driven checks using controlled MCP servers and scripted inference. No captured YAML was hand-authored. Paired live Anthropic/gateway reference recordings requested in review remain outstanding because native API access is unavailable; maintainer acceptance of deferring that evidence has not been confirmed. Ready for review does not claim that this remaining merge-validation requirement has been satisfied.