Skip to content

fix(mcp): preserve seed validators and annotated request injection - #5708

Merged
yaoyu-33 merged 3 commits into
mainfrom
yuya/fix-mcp-seed-validation
Nov 6, 2026
Merged

yaoyu-33 merged 3 commits into
mainfrom
yuya/fix-mcp-seed-validation

Conversation

@yaoyu-33

@yaoyu-33 yaoyu-33 commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

MCP seed wrapping discarded Annotated metadata, so incomplete typed session envelopes could bypass the seed validator and allocate cookie-owned state. Preserve annotation metadata when building the wrapped endpoint and unwrap it only when recognizing an injected Request.

This independent fix is extracted from #5480. The shared resources lifecycle PR is #5709; all nine environment migrations depend on that lifecycle PR. No separate issue is needed for this focused regression fix.

Validation on 365a029e967edcc9ea1a98a0eed22755d4c7f8a9 (Python 3.13.14):

  • python -m pytest -o addopts='' -o log_cli=false --import-mode=importlib --tb=short -q tests/unit_tests/server_runtime/test_mcp_auto_exposure.py tests/unit_tests/server_runtime/test_mcp_seed_validation.py: 68 passed.
  • Tests exercise the real MCP-wrapped HTTP route: malformed typed seeds return 422 without allocation, cookie rows with scalar task IDs remain valid, valid typed seeds return MCP tool grants, and Annotated[Request, ...] remains injected correctly. Three malformed-seed cases fail against the preceding wrapper.
  • pre-commit run --all-files and git diff --check passed. The private guardwords catalog was unavailable, so that scan was skipped. Commit includes DCO sign-off.

Model rollout: N/A for this annotation-preservation fix itself; HTTP validation is exercised directly. The dependent weather migration separately runs a real model through MCP. This PR changes no model prompts, scoring, or tool semantics. Full repository CI remains required.

@copy-pr-bot

copy-pr-bot Bot commented Nov 5, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@svcnvidia-nemo-ci svcnvidia-nemo-ci left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

SHIP

LGTM — no concerns found. I reviewed all three changed files and traced the affected seed validation, request injection, session identity, and MCP grant consumers. The wrapper change preserves annotation metadata while unwrapping it only for Request recognition. The regression tests cover malformed typed seeds, valid typed and cookie seeds, and annotated Request injection.

This was static inspection; I didn't execute tests.

Note: formal approval is not available for this request, so this review is posted as a comment only.

Review generated by codex. This was a full review. Request a full review with /review reset=true.

yaoyu-33 and others added 2 commits November 5, 2026 23:06
The wrapper strips Annotated only to recognize an injected Request. A
validator written directly on the body parameter, the form an author is
most likely to write, was covered only through a union arm, so a wrapper
that stripped every parameter still passed.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
@yaoyu-33

yaoyu-33 commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 5617af5

Comment on lines +602 to +603
# Preserve Annotated metadata, including the BeforeValidator that prevents malformed typed seeds
# from falling back to the permissive cookie-seed model instead of returning 422.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The validator this comment names lives in the dependent environment PRs, not in this module or on main. A reader of mcp_auto_exposure.py will not find it. The general reason is also broader: on main the wrapper dropped Body(embed=True), Header()/Depends() markers and union_mode too, not just validators. Could the comment state the general rule?

Suggested change
# Preserve Annotated metadata, including the BeforeValidator that prevents malformed typed seeds
# from falling back to the permissive cookie-seed model instead of returning 422.
# Keep Annotated metadata: FastAPI reads validators, union_mode and Body/Header/Depends markers from it,
# so stripping it would change what the wrapped route accepts.

Comment on lines 607 to 610
request_param_name = next(
(n for n, p in signature.parameters.items() if hints.get(n, p.annotation) is Request), None
(n for n, p in signature.parameters.items() if _strip_annotated(hints.get(n, p.annotation)) is Request),
None,
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This module reads a handler's annotations in two places, and they disagree with FastAPI in three ways. Since this PR fixes one of them, could it fix all three here so the two readers stay consistent?

  1. bind_route still drops Annotated metadata. It calls get_type_hints(endpoint) without include_extras (L190) and uses the result only for string annotations. So a tool route behaves differently depending on how its module writes annotations:
    • With from __future__ import annotations, a route with body: Annotated[Model, BeforeValidator(...)] binds for direct dispatch and skips the validator. Over HTTP the input gets a 422; through MCP call_direct it is accepted.
    • With concrete annotations, the same route is refused at startup, and so is request: Annotated[Request, ...].
  2. A subclass of Request is not recognised. Both here and in bind_route the check is is Request, but FastAPI checks for a subclass (lenient_issubclass(type_annotation, Request) in fastapi/dependencies/utils.py). A handler declaring request: MyRequest gets a second request parameter prepended. FastAPI fills only one request slot, so every wrapped call fails with KeyError: '__nemo_gym_request'.
  3. A rewritten __signature__ loses its body model. The params line below takes hints (built from __annotations__) over every signature annotation, not only string ones. If a factory sets __signature__ to body: Model while __annotations__ still says Any, the original route accepts the body, but the wrapped route returns 422 for a missing query parameter. bind_route already handles this case (L195-L198), and the comment on the params line describes that rule too.

One option is a pair of helpers that both readers call, so they cannot drift apart again:

def _param_annotation(name: str, param: inspect.Parameter, hints: dict[str, Any]) -> Any:
    """Return a handler parameter's annotation as FastAPI reads it."""
    # A concrete object on the signature wins (a factory may rewrite __signature__); hints resolve deferred strings.
    return hints.get(name, param.annotation) if isinstance(param.annotation, str) else param.annotation


def _is_request(annotation: Any) -> bool:
    """Whether FastAPI injects the live Request into a parameter with this annotation."""
    base = _strip_annotated(annotation)
    return isinstance(base, type) and issubclass(base, Request)

bind_route would then call get_type_hints(endpoint, include_extras=True), resolve each annotation through _param_annotation, and test _is_request(annotation). A deferred Annotated body then gets the same loud refusal as a concrete one, and Annotated[Request, ...] binds in both cases. A test for each of the three cases would pin it down. The deferred one can live in test_mcp_auto_exposure.py, which already uses from __future__ import annotations.

@ananthsub

Copy link
Copy Markdown
Contributor

Thanks for pulling this fix out on its own. The change is correct and small, and the new tests are real regression tests: the seed validation file fails on main (all three malformed-seed cases and the directly annotated body case return 200 instead of 422) and passes at this head. With the _strip_annotated call removed, the annotated Request tests fail with a KeyError.

The fix covers more than validators. On main, MCP wrapping dropped every Annotated extra on a seed handler. Besides BeforeValidator, it also lost:

  • Body(embed=True): an embedded payload was accepted and silently replaced by defaults.
  • Header() and Depends(): these turned into required query parameters, so every call returned 422.
  • Field(union_mode=...): interactive_browser's seed body uses it. Valid seeds pick the same union arm either way, so no behavior change was observed there.

This PR makes the wrapped route match the unwrapped one in all of these cases. It may be worth one sentence in the description, since reviewers of the dependent environment PRs will look for it.

Please fold the other annotation-reading gaps into this PR (details in the inline comment on the Request detection). This module reads handler annotations in two places, and both still differ from FastAPI:

  • bind_route drops Annotated metadata for deferred annotations, so a tool route's body validator is skipped over MCP while HTTP returns 422.
  • A subclass of Request is not recognised as the request.
  • In the seed wrapper, a rewritten __signature__ loses its body model.

One shared helper for both readers would fix all three and keep them from drifting apart.

Separately, and not for this PR: if the session hook raises after a handler has allocated state, the caller gets a 500 but the state stays allocated. That belongs with the seed lifecycle work rather than annotation handling.

Design

flowchart TD
    H["seed_session handler<br/>body: Annotated[Model, BeforeValidator]"] --> T["get_type_hints(include_extras=True)<br/>metadata kept"]
    T --> R{"_strip_annotated(hint) is Request?"}
    R -- yes --> U["reuse the handler's Request param"]
    R -- no --> I["prepend __nemo_gym_request"]
    U --> S["stamp __signature__ / __annotations__"]
    I --> S
    S --> F["FastAPI validates body with metadata"]
    F -- malformed --> X["422, handler and mint_metadata not called"]
    F -- valid --> M["handler runs, then MCP token minted"]
Loading

@weijiac0619

Copy link
Copy Markdown
Contributor

LGTM. +1 on folding the other annotation-reading gaps into this PR with shared helpers and stating the general rule

@yaoyu-33
yaoyu-33 enabled auto-merge November 6, 2026 18:39
@yaoyu-33
yaoyu-33 added this pull request to the merge queue Nov 6, 2026
@github-actions

github-actions Bot commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/42273987823

Merged via the queue into main with commit 966145f Nov 6, 2026
107 of 110 checks passed
@yaoyu-33
yaoyu-33 deleted the yuya/fix-mcp-seed-validation branch November 6, 2026 19:03

This branch was previously deployed

1 inactive deployment
public — 5617af5a Deployed Nov 6, 2026 by copy-pr-bot[bot] via release / finalize / notify #10583
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.

4 participants