Skip to content

feat: support MCP connectors on /v1/messages - #425

Draft
skyloevil wants to merge 4 commits into
vllm-project:mainfrom
skyloevil:codex/messages-mcp-connector-418
Draft

skyloevil wants to merge 4 commits into
vllm-project:mainfrom
skyloevil:codex/messages-mcp-connector-418

Conversation

@skyloevil

@skyloevil skyloevil commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Implement the mcp-client-2025-11-20 connector on /v1/messages and /v1/messages/count_tokens, based on main 432b80d and the merged #431/#468 foundations.

  • Model MCP toolsets, configuration and interpreted replay blocks with typed variants/conversions. Share MCP/native call and output projection between JSON and SSE, and recognize hosted tool-search versions through one exact capability policy.
  • Return mixed client/MCP calls before MCP execution. Validate the client's actual replayed arguments and complete outputs, then resume pending calls once through the existing scheduler. Invalid, incomplete or canceled streams cannot dispatch calls or turn invalid arguments into executable {}.
  • Preserve main's registry bindings, sequential budget admission, permits, execution timeout, tool-stage observability, native server-tool projections and MCP trace propagation. Replay native server tools before lowering MCP history, including in token counting, so combined call/output pairs remain intact.
  • Preserve configuration overrides and cache boundaries. Strip connector credentials before inference, redact debug/header output, and keep local certificate trust injection confined to a test feature.
  • Restore pending MCP calls from Messages thread checkpoints. Continue with the matching client tool results and current MCP credentials, with the authorization token excluded from the checkpoint.

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-15 pinned-catalog beta is outside this scope.

Closes #418.

Test Plan

  • All seven remote workflows passed on 4b7fd36. GitHub recorded 15 passing checks and two expected skips for website deployment and PyPI publication. The Claude Code and Codex smoke tests passed.
  • HTTPS handler acceptance. All 11 tests passed, including thread checkpoint continuation across JSON and SSE, success/failure, TLS/bearer checks, both exact hosted-search versions, configuration overrides, mixed continuation counts, multiple pending calls, escaped/Unicode argument reconstruction, cancellation, truncation, malformed streams and combined MCP/native replay through Messages and count_tokens.
  • Core coverage includes typed declarations, schema/serde agreement, opaque replay fields, duplicate identifiers, cache boundaries, disabled-tool replay and the existing scheduling/budget/lifecycle regressions.
  • cargo test --workspace --locked --offline --no-fail-fast passed 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.
  • The normal production dependency feature graph excludes 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.

@maralbahari

Copy link
Copy Markdown
Collaborator

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 order

Anthropic documents that when client and server tools are called in the same group, the API returns stop_reason: "tool_use" without executing the pending server tool. It explicitly says mcp_tool_use follows this behavior.

Here, complete_mcp_calls_in_client_round executes MCP immediately, and the streaming path does the same through is_terminal_mcp_round. The mixed-call test expects an MCP result in the first response, so it currently locks in behavior that differs from the documentation.

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 types

The typed server/configuration declarations and shared registry are useful, but ToolParam combines function tools and MCP toolsets through optional fields and a string discriminator. messages_connector.rs then rewrites declarations and history through raw JSON indexing.

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 contract

JSON uses project_mcp_round, while streaming separately rewrites call starts, folds argument deltas, emits results, and decides terminal MCP execution.

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 cassettes

The 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:

  • Successful calls and tool failures.
  • Tool configuration defaults and per-tool overrides.
  • Mixed client/MCP calls and continuation.
  • Streaming argument reconstruction, block ordering, and terminal events.
  • Stop reasons and usage semantics.

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 {"text":"hello"} instead of reconstructing it from the emitted deltas. That bypasses the exact behavior this continuation test should verify. Please reconstruct the streamed message and replay that actual result.

I’d encourage extending the Rust patterns already practiced in this repo such as ResponsesTool, RoundIngestion, SlotState, and StreamDelivery to the Messages MCP normalization and projection paths. Discovery and dispatch are already shared; stronger types and clearer ownership here would reduce raw JSON manipulation and prevent JSON and streaming behavior from drifting apart.

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.

@skyloevil
skyloevil marked this pull request as draft October 9, 2026 03:09
@skyloevil

Copy link
Copy Markdown
Contributor Author

@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:

  1. Messages tool-type refactor: distinct typed declarations and explicit conversions for fields interpreted by the gateway, preserving opaque provider fields and existing behavior. Only independently useful changes would be extracted; MCP-specific history and execution state would stay with the feature.
  2. MCP connector feature (this PR): complete the typed MCP history/content conversions, shared JSON/streaming projection and execution policy, and explicit versioned tool-search capability policy. Include documentation-driven integration tests using scripted inference responses and a controlled local MCP server: successful and failed calls, configuration overrides, mixed-call execution counts of 0 then 1, invalid continuations, no re-execution of completed history, streamed argument reconstruction, block ordering, terminal events, stop reasons, and usage handling.
  3. Reference recording and compatibility follow-up: extend the recorder and add paired, sanitized Anthropic/gateway recordings against the same controlled MCP server, normalizing nondeterministic IDs. Native Anthropic MCP connector access is not currently available to me, so this part would follow when access is available, or with help from someone who can run the recorder.

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.

haoshan98 pushed a commit that referenced this pull request Oct 16, 2026
## 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]>
maralbahari added a commit that referenced this pull request Oct 27, 2026
## 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]>
@skyloevil
skyloevil force-pushed the codex/messages-mcp-connector-418 branch from 912c34f to 04cc834 Compare October 31, 2026 16:22
@skyloevil
skyloevil marked this pull request as ready for review October 31, 2026 16:23

Copy link
Copy Markdown
Contributor Author

@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 mcp-client-2025-11-20 must be completed before merging, or whether the documentation-driven synthetic tests are acceptable for this PR with live recordings in a follow-up?

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]>

@maralbahari maralbahari left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. One declaration adapter. map_tool / registry_tools should map ToolParam::McpToolset to ToolDeclaration::Mcp, resolving its server from mcp_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 through McpHandler::normalize. This removes connector_tools, the server lookup inside normalize_connector, and most of the raw Value editing.
  2. The registry stays the only registry. Remove GatewayToolMap.mcp_tools, MessagesRequestContext.gateway_tools, and gateway_tools_or. Read the MCP identity (server_label, tool_name) from the registry entry and its binding, as Responses does, and build the Messages mcp_tool_use / mcp_tool_result blocks from it. Only the tool side is shared. Anthropic has no per-item lifecycle events like OpenAI's response.mcp_call.*, so the Messages output stays plain content blocks, using the generic content_block_start / delta / stop events.
  3. Keep the shared types protocol-neutral. Don't add messages_config to McpToolParam or apply_messages_config to tool/. The enabled/disabled filter can be expressed as a neutral tool filter on McpToolParam that both APIs could use.
  4. One Rust type per wire block, owned by types/messages/content.rs. Projection, replay and pending detection should all use it.
  5. Decide the pending-MCP case once, in decide_round, as a MessagesRoundDecision variant. The JSON and SSE paths then match on that variant. They shouldn't recompute it from strings.
  6. Route count_tokens through ParsedMessagesRequest / MessagesRequestContext, so that one preparation function serves both endpoints.
  7. Keep the diff to the feature. Moving complete_round / execute_round / take_round into messages_stream/round.rs and moving McpToolParam into types/tools/mcp.rs are 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(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)>,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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> {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Several issues in this function:

  • It validates the wire shape (non-empty unique names, config.kind != "url", an https:// prefix, exactly one toolset per server) inside tool/. Validation of wire fields belongs on the owning type in types/messages/parameters.rs, e.g. kind as an enum and a validate/TryFrom on McpServer, so every entry point gets it.
  • It fills McpToolParam with seven None placeholders and require_approval: Some("never".to_owned()). A From/TryFrom conversion that sits beside From<&ResponsesTool> in tool/declaration.rs would 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_connector has to look each toolset up again by server_label. Mapping McpToolset inside map_tool fixes 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(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@maralbahari
maralbahari marked this pull request as draft November 16, 2026 08:24
@maralbahari

Copy link
Copy Markdown
Collaborator

@skyloevil converted to draft PR once everything is addressed and ready for review please open again

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support the MCP connector on /v1/messages

2 participants