Repository navigation
fix(mcp): preserve seed validators and annotated request injection - #5708
Conversation
Signed-off-by: yaoyu-33 <[email protected]>
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
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.
Signed-off-by: yaoyu-33 <[email protected]>
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]>
|
/ok to test 5617af5 |
| # Preserve Annotated metadata, including the BeforeValidator that prevents malformed typed seeds | ||
| # from falling back to the permissive cookie-seed model instead of returning 422. |
There was a problem hiding this comment.
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?
| # 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. |
| 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, | ||
| ) |
There was a problem hiding this comment.
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?
bind_routestill dropsAnnotatedmetadata. It callsget_type_hints(endpoint)withoutinclude_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 withbody: Annotated[Model, BeforeValidator(...)]binds for direct dispatch and skips the validator. Over HTTP the input gets a 422; through MCPcall_directit is accepted. - With concrete annotations, the same route is refused at startup, and so is
request: Annotated[Request, ...].
- With
- A subclass of
Requestis not recognised. Both here and inbind_routethe check isis Request, but FastAPI checks for a subclass (lenient_issubclass(type_annotation, Request)infastapi/dependencies/utils.py). A handler declaringrequest: MyRequestgets a second request parameter prepended. FastAPI fills only one request slot, so every wrapped call fails withKeyError: '__nemo_gym_request'. - A rewritten
__signature__loses its body model. Theparamsline below takeshints(built from__annotations__) over every signature annotation, not only string ones. If a factory sets__signature__tobody: Modelwhile__annotations__still saysAny, the original route accepts the body, but the wrapped route returns 422 for a missing query parameter.bind_routealready handles this case (L195-L198), and the comment on theparamsline 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.
|
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 The fix covers more than validators. On
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:
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"]
|
|
LGTM. +1 on folding the other annotation-reading gaps into this PR with shared helpers and stating the general rule |
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/42273987823 |
MCP seed wrapping discarded
Annotatedmetadata, 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 injectedRequest.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.Annotated[Request, ...]remains injected correctly. Three malformed-seed cases fail against the preceding wrapper.pre-commit run --all-filesandgit diff --checkpassed. 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.