Fixes to detect optional parameters in tool conversion used by "nat mcp serve"#1126
Conversation
Parameters with default values were incorrectly marked as required in MCP tool schemas. Now checking for PydanticUndefined and properly extracting default values from Pydantic fields to correctly identify optional parameters. Signed-off-by: Anuradha Karuppiah <anuradhak@nvidia.com>
Signed-off-by: Anuradha Karuppiah <anuradhak@nvidia.com>
WalkthroughAdds Changes
Sequence Diagram(s)mermaid Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes
Pre-merge checks and finishing touchesImportant Pre-merge checks failedPlease resolve all errors before merging. Addressing warnings is optional. ❌ Failed checks (1 error)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro 📒 Files selected for processing (2)
🧰 Additional context used📓 Path-based instructions (8)**/*.py📄 CodeRabbit inference engine (.cursor/rules/general.mdc)
Files:
{tests/**/*.py,examples/*/tests/**/*.py}📄 CodeRabbit inference engine (.cursor/rules/general.mdc)
Files:
{tests/**/*.py,examples/*/tests/**/*.py,packages/*/tests/**/*.py}📄 CodeRabbit inference engine (.cursor/rules/general.mdc)
Files:
{**/*.py,**/*.sh,**/*.md,**/*.toml,**/*.y?(a)ml,**/*.json,**/*.txt,**/*.ini,**/*.cfg,**/*.ipynb}📄 CodeRabbit inference engine (.cursor/rules/general.mdc)
Files:
**/*⚙️ CodeRabbit configuration file
Files:
tests/**/*.py⚙️ CodeRabbit configuration file
Files:
{src/**/*.py,packages/*/src/**/*.py}📄 CodeRabbit inference engine (.cursor/rules/general.mdc)
Files:
src/nat/**/*📄 CodeRabbit inference engine (.cursor/rules/general.mdc)
Files:
⚙️ CodeRabbit configuration file
Files:
🧬 Code graph analysis (2)tests/nat/front_ends/mcp/test_tool_converter.py (1)
src/nat/front_ends/mcp/tool_converter.py (2)
🔇 Additional comments (8)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (2)
src/nat/front_ends/mcp/tool_converter.py (1)
112-113: Consider unpacking only the needed value.The
_is_optionalvariable is assigned but never used. You could simplify by only unpacking the default value.Apply this diff:
- # Check if field is optional and get its default value - _is_optional, param_default = is_field_optional(field) + # Get the default value for the field (Parameter.empty if required) + _, param_default = is_field_optional(field)Or even more explicit:
- # Check if field is optional and get its default value - _is_optional, param_default = is_field_optional(field) + # Get the default value for the field (Parameter.empty if required) + param_default = is_field_optional(field)[1]tests/nat/front_ends/mcp/test_tool_converter.py (1)
604-681: LGTM: Integration tests validate runtime behavior.These tests effectively validate that the wrapper correctly handles optional parameters at runtime: when omitted, when provided, and when explicitly set to None. The tests use proper async mocking and observability context setup.
Optional: Consider verifying the actual kwargs passed to the function.
While the current tests verify that
acall_invokeis called, they don't inspect the actual arguments passed. You could add assertions to verify that defaults are correctly applied:# In test_wrapper_with_optional_parameters_omitted call_kwargs = mock_function.acall_invoke.call_args[1] assert call_kwargs["required_str"] == "test" assert call_kwargs["required_int"] == 123 # Verify defaults were applied by Pydantic model validationHowever, this may be testing Pydantic's behavior rather than your wrapper logic, so it's optional.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
src/nat/front_ends/mcp/tool_converter.py(3 hunks)tests/nat/front_ends/mcp/test_tool_converter.py(6 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
**/*.py
📄 CodeRabbit inference engine (.cursor/rules/general.mdc)
**/*.py: In code comments use the abbreviations: nat (API namespace/CLI), nvidia-nat (package), NAT (env var prefixes); never use these abbreviations in documentation
Follow PEP 20 and PEP 8 for Python style
Run yapf with column_limit=120; yapf is used for formatting (run second)
Indent with 4 spaces (no tabs) and end each file with a single trailing newline
Use ruff (ruff check --fix) as a linter (not formatter) per pyproject.toml; fix warnings unless explicitly ignored
Respect Python naming schemes: snake_case for functions/variables, PascalCase for classes, UPPER_CASE for constants
When re-raising exceptions, use bare raise to preserve stack trace; log with logger.error(), not logger.exception()
When catching and logging without re-raising, use logger.exception() to capture full stack trace
Provide Google-style docstrings for every public module, class, function, and CLI command
Docstring first line must be a concise description ending with a period
Validate and sanitize all user input, especially in web or CLI interfaces
Prefer httpx with SSL verification enabled by default and follow OWASP Top-10 recommendations
Use async/await for I/O-bound work (HTTP, DB, file I/O)
Cache expensive computations with functools.lru_cache or an external cache when appropriate
Leverage NumPy vectorized operations when beneficial and feasible
Files:
src/nat/front_ends/mcp/tool_converter.pytests/nat/front_ends/mcp/test_tool_converter.py
{src/**/*.py,packages/*/src/**/*.py}
📄 CodeRabbit inference engine (.cursor/rules/general.mdc)
{src/**/*.py,packages/*/src/**/*.py}: All importable Python code must live under src/ or packages//src/
All public APIs must have Python 3.11+ type hints on parameters and return values
Prefer typing/collections.abc abstractions (e.g., Sequence over list)
Use typing.Annotated for units or metadata when useful
Treat pyright warnings as errors during development
Files:
src/nat/front_ends/mcp/tool_converter.py
src/nat/**/*
📄 CodeRabbit inference engine (.cursor/rules/general.mdc)
src/nat/**/* contains core functionality; changes should prioritize backward compatibility
Files:
src/nat/front_ends/mcp/tool_converter.py
⚙️ CodeRabbit configuration file
This directory contains the core functionality of the toolkit. Changes should prioritize backward compatibility.
Files:
src/nat/front_ends/mcp/tool_converter.py
{**/*.py,**/*.sh,**/*.md,**/*.toml,**/*.y?(a)ml,**/*.json,**/*.txt,**/*.ini,**/*.cfg,**/*.ipynb}
📄 CodeRabbit inference engine (.cursor/rules/general.mdc)
{**/*.py,**/*.sh,**/*.md,**/*.toml,**/*.y?(a)ml,**/*.json,**/*.txt,**/*.ini,**/*.cfg,**/*.ipynb}: Every file must start with the standard SPDX Apache-2.0 header
Confirm copyright years are up to date when a file is changed
All source files must include the SPDX Apache-2.0 header template (copy from an existing file)
Files:
src/nat/front_ends/mcp/tool_converter.pytests/nat/front_ends/mcp/test_tool_converter.py
**/*
⚙️ CodeRabbit configuration file
**/*: # Code Review Instructions
- Ensure the code follows best practices and coding standards. - For Python code, follow
PEP 20 and
PEP 8 for style guidelines.- Check for security vulnerabilities and potential issues. - Python methods should use type hints for all parameters and return values.
Example:def my_function(param1: int, param2: str) -> bool: pass- For Python exception handling, ensure proper stack trace preservation:
- When re-raising exceptions: use bare
raisestatements to maintain the original stack trace,
and uselogger.error()(notlogger.exception()) to avoid duplicate stack trace output.- When catching and logging exceptions without re-raising: always use
logger.exception()
to capture the full stack trace information.Documentation Review Instructions - Verify that documentation and comments are clear and comprehensive. - Verify that the documentation doesn't contain any TODOs, FIXMEs or placeholder text like "lorem ipsum". - Verify that the documentation doesn't contain any offensive or outdated terms. - Verify that documentation and comments are free of spelling mistakes, ensure the documentation doesn't contain any
words listed in the
ci/vale/styles/config/vocabularies/nat/reject.txtfile, words that might appear to be
spelling mistakes but are listed in theci/vale/styles/config/vocabularies/nat/accept.txtfile are OK.Misc. - All code (except .mdc files that contain Cursor rules) should be licensed under the Apache License 2.0,
and should contain an Apache License 2.0 header comment at the top of each file.
- Confirm that copyright years are up-to date whenever a file is changed.
Files:
src/nat/front_ends/mcp/tool_converter.pytests/nat/front_ends/mcp/test_tool_converter.py
{tests/**/*.py,examples/*/tests/**/*.py}
📄 CodeRabbit inference engine (.cursor/rules/general.mdc)
Unit tests live in tests/ or examples/*/tests and use markers defined in pyproject.toml (e.g., integration)
Files:
tests/nat/front_ends/mcp/test_tool_converter.py
{tests/**/*.py,examples/*/tests/**/*.py,packages/*/tests/**/*.py}
📄 CodeRabbit inference engine (.cursor/rules/general.mdc)
{tests/**/*.py,examples/*/tests/**/*.py,packages/*/tests/**/*.py}: Use pytest with pytest-asyncio for async code
Test functions should be named with test_ prefix using snake_case
Extract frequently repeated test code into pytest fixtures
Pytest fixtures should define the name argument in @pytest.fixture and the function should be prefixed fixture_ using snake_case
Mock external services with pytest_httpserver or unittest.mock; avoid live endpoints
Mark slow tests with @pytest.mark.slow to skip in default test suite
Mark integration tests requiring external services with @pytest.mark.integration and follow nat-tests guidelines
Files:
tests/nat/front_ends/mcp/test_tool_converter.py
tests/**/*.py
⚙️ CodeRabbit configuration file
tests/**/*.py: - Ensure that tests are comprehensive, cover edge cases, and validate the functionality of the code. - Test functions should be named using thetest_prefix, using snake_case. - Any frequently repeated code should be extracted into pytest fixtures. - Pytest fixtures should define the name argument when applying the pytest.fixture decorator. The fixture
function being decorated should be named using thefixture_prefix, using snake_case. Example:
@pytest.fixture(name="my_fixture")
def fixture_my_fixture():
pass
Files:
tests/nat/front_ends/mcp/test_tool_converter.py
🧬 Code graph analysis (1)
tests/nat/front_ends/mcp/test_tool_converter.py (2)
src/nat/front_ends/mcp/tool_converter.py (2)
is_field_optional(39-63)create_function_wrapper(66-241)src/nat/utils/type_utils.py (1)
is_optional(207-218)
🔇 Additional comments (5)
src/nat/front_ends/mcp/tool_converter.py (2)
21-21: LGTM: Necessary imports added.The new imports (
Any,FieldInfo,PydanticUndefined) are correctly added to support the optional field detection logic.Also applies to: 25-26
39-63: LGTM: Well-implemented optional field detection.The function correctly identifies optional Pydantic fields by checking
is_required(), explicit defaults, anddefault_factory. The logic properly returns the actual default value when available, orNonefor factory-based defaults, making it suitable for function signature construction.tests/nat/front_ends/mcp/test_tool_converter.py (3)
16-16: LGTM: Comprehensive test schemas.The imports and test schemas are well-structured, covering all necessary scenarios: all-required, all-optional, mixed, and Union-with-None types. This provides excellent test coverage for the optional field detection functionality.
Also applies to: 29-29, 46-76
92-203: LGTM: Thorough unit test coverage foris_field_optional.The test class provides comprehensive coverage of the new utility function, including edge cases like falsy defaults (0, False), default_factory handling, and Union types with None. The tests follow pytest conventions and use clear Arrange-Act-Assert patterns.
407-553: LGTM: Comprehensive validation of wrapper parameter schemas.These tests effectively validate that
create_function_wrappercorrectly translates Pydantic field optionality into function signature defaults. The tests cover all scenarios (required, optional, mixed, Union types) and verify that annotations and order are preserved. The comment at line 486 helpfully explains thedefault_factory→Nonemapping.
Signed-off-by: Anuradha Karuppiah <anuradhak@nvidia.com>
thanks for the review @yczhang-nv! |
|
/merge |
…cp serve" (NVIDIA#1126) Parameters with default values were incorrectly marked as required in MCP tool schemas. Now checking for PydanticUndefined and properly extracting default values from Pydantic fields to correctly identify optional parameters. This PR also adds comprehensive unit tests for the tool schema conversion - I am familiar with the [Contributing Guidelines](https://github.com/NVIDIA/NeMo-Agent-Toolkit/blob/develop/docs/source/resources/contributing.md). - We require that all contributors "sign-off" on their commits. This certifies that the contribution is your original work, or you have rights to submit it under the same license, or a compatible license. - Any contribution which contains commits that are not Signed-Off will not be accepted. - When the PR is ready for review, new or existing tests cover these changes. - When the PR is ready for review, the documentation is up to date with these changes. * **New Features** * Improved detection and handling of optional parameters and default/default-factory values in tool wrapper generation, with unified validation and consistent invocation behavior for workflows and regular functions. * Ensures parameter descriptions, order, and type annotations are preserved in generated wrappers. * **Tests** * Added comprehensive tests covering optional/default combinations, wrapper signatures, execution paths, and observability propagation. Authors: - Anuradha Karuppiah (https://github.com/AnuradhaKaruppiah) Approvers: - Yuchen Zhang (https://github.com/yczhang-nv) URL: NVIDIA#1126 Signed-off-by: Will Killian <wkillian@nvidia.com>
Description
Parameters with default values were incorrectly marked as required in MCP tool schemas. Now checking for PydanticUndefined and properly extracting default values from Pydantic fields to correctly identify optional parameters.
This PR also adds comprehensive unit tests for the tool schema conversion
By Submitting this PR I confirm:
Summary by CodeRabbit
New Features
Tests