fix: improve CLI error messages in register and policy commands#314
Conversation
The register command did a bare import of AgentIdentity inside the function body with no error handling. If agentmesh is not installed, Python dumps a raw traceback instead of a clear message. Wrapped the import in a try/except ImportError block that tells the user what to run. The policy command caught all exceptions as a single bare Exception and printed only the error object. Split it into FileNotFoundError, JSON/YAML parse errors, and a general fallback so each case gives a message that points to the actual problem. Related to issue microsoft#307.
🤖 AI Agent: test-generator🧪 Test Coverage Analysis
|
There was a problem hiding this comment.
🤖 AI Agent: code-reviewer
Review Summary
This PR improves error handling in the register and policy commands of the agent-mesh package by providing more user-friendly error messages. The changes address the issue of raw Python tracebacks being displayed, which could confuse users. The fixes include wrapping imports in a try/except block and providing specific error messages for common exceptions.
The changes are generally well-implemented and improve the usability of the CLI. However, there are a few areas that require attention to ensure robustness, security, and maintainability.
🔴 CRITICAL
- Unvalidated Exception Messages in
policyCommand- The
policycommand directly includes the exception message (e) in the output forjson.JSONDecodeErrorandyaml.YAMLError. This could potentially expose sensitive information (e.g., file paths or debug information) to the user, which is a security risk. - Recommendation: Avoid directly exposing exception messages. Instead, provide a generic error message and log the detailed exception for debugging purposes. For example:
except (json.JSONDecodeError, yaml.YAMLError): console.print(f"[red]Error: Failed to parse {policy_file}. Ensure the file is valid JSON or YAML.[/red]") logger.exception("Failed to parse policy file: %s", policy_file)
- The
💡 SUGGESTION
-
Use Specific Exception Types for ImportError
- While the
try/except ImportErrorblock in theregistercommand is a good improvement, it could be more specific. For example, ifagentmesh.identityhas submodules, an unrelatedImportErrorin one of those submodules could trigger this block incorrectly. - Recommendation: Use
importlibto check for the module's existence or validate the exception's context:try: from agentmesh.identity import AgentIdentity except ImportError as e: if "agentmesh.identity" in str(e): console.print("[red]Error: agentmesh is not installed. Run: pip install agentmesh[/red]") return raise
- While the
-
Add Unit Tests for Error Scenarios
- The PR mentions manual verification, but automated tests should be added to ensure these error-handling paths are covered. This will prevent regressions in the future.
- Recommendation: Use
pytestto mock scenarios such as:ImportErrorfor theregistercommand.FileNotFoundError,JSONDecodeError, andYAMLErrorfor thepolicycommand.
def test_register_import_error(mocker): mocker.patch("agentmesh.cli.main.AgentIdentity", side_effect=ImportError) result = runner.invoke(app, ["register", "test-agent"]) assert "Error: agentmesh is not installed" in result.output def test_policy_file_not_found(mocker): result = runner.invoke(app, ["policy", "nonexistent-file"]) assert "Error: Policy file not found" in result.output
-
Consider Logging Errors
- While the CLI provides user-friendly error messages, it would be beneficial to log detailed error information for debugging purposes.
- Recommendation: Use Python's
loggingmodule to log exceptions at an appropriate level (e.g.,logger.errororlogger.exception).
-
Backward Compatibility
- While this PR does not introduce breaking changes to the public API, the improved error messages may change the CLI's output format. If any downstream automation or scripts parse these messages, they could break.
- Recommendation: Document this change in the release notes and ensure that any dependent systems are updated accordingly.
🟡 WARNING
- Potential Breaking Change in CLI Output
- The updated error messages in the
policycommand change the format of the output. If users or systems rely on the previous output format, this could cause issues. - Recommendation: Clearly document the change in CLI behavior in the release notes and consider providing a transition period or a compatibility flag if necessary.
- The updated error messages in the
💡 Additional Suggestions
-
Use Constants for Error Messages
- To improve maintainability and consistency, consider defining error messages as constants at the top of the file or in a separate module. This will make it easier to manage and update messages in the future.
-
Add Type Annotations
- The functions
registerandpolicylack type annotations for their parameters and return types. Adding type hints improves code readability and helps with static analysis. - Example:
def register(agent_dir: str, name: Optional[str] = None) -> None: def policy(policy_file: str, validate: bool) -> None:
- The functions
-
Consider Using a Custom Exception for Policy Parsing
- Instead of handling
json.JSONDecodeErrorandyaml.YAMLErrorseparately, consider wrapping them in a custom exception (e.g.,PolicyParsingError). This would simplify error handling and make the code more readable.
- Instead of handling
Final Assessment
- The PR addresses the issue effectively and improves the user experience of the CLI.
- However, there are critical security concerns regarding unvalidated exception messages and potential breaking changes in CLI output.
- With the suggested improvements, this PR can be merged safely.
Action Items
- Address the critical security issue by sanitizing exception messages.
- Add automated tests for the new error-handling paths.
- Consider logging detailed error information.
- Document the changes in CLI output to mitigate potential breaking changes.
|
Welcome to the Agent Governance Toolkit! Thanks for your first pull request. |
🤖 AI Agent: breaking-change-detector🔍 API Compatibility ReportSummaryThis pull request modifies CLI error handling in the Findings
Migration GuideNo migration steps are required as this pull request does not introduce any breaking changes. Existing code and users of the CLI commands will benefit from clearer error messages without requiring modifications. Notes
✅ No breaking changes detected. |
🤖 AI Agent: docs-sync-checker📝 Documentation Sync ReportIssues Found
Suggestions
Example Docstring Suggestionsdef register(agent_dir: str, name: str = None):
"""
Registers an agent with the given directory and optional name.
Args:
agent_dir (str): The directory containing the agent's files.
name (str, optional): The name to assign to the agent. Defaults to None.
Behavior:
- If `agentmesh` is not installed, prints an error message and exits early.
- Simulates the registration process and generates an agent identity.
Returns:
None
"""def policy(policy_file: str, validate: bool):
"""
Loads and optionally validates a policy file.
Args:
policy_file (str): The path to the policy file to load.
validate (bool): Whether to validate the policy file after loading.
Behavior:
- Prints an error message if the file is not found.
- Handles JSON and YAML parsing errors with specific error messages.
- Prints a success message if policies are loaded successfully.
Returns:
None
"""If these changes are addressed, the documentation will be in sync. Let us know if you need further assistance! |
🤖 AI Agent: contributor-guideHi @first-time-contributor! 👋 Welcome to the microsoft/agent-governance-toolkit community, and thank you for opening this pull request! 🎉 We're so excited to have you here, and we appreciate you taking the time to improve the project. Let's dive into your contribution together! 🌟 What You Did Well
🛠 Suggestions for ImprovementWhile your PR is already in great shape, here are a few suggestions to align it even more closely with our project conventions:
📚 Helpful ResourcesHere are some resources to help you with the suggestions above:
✅ Next Steps
If you have any questions or need help with anything, don't hesitate to ask. We're here to support you! 😊 Thank you again for your contribution — you're helping make this project better for everyone. 🚀 Looking forward to your updates! 🙌 |
🤖 AI Agent: security-scannerSecurity Review of PRThis PR improves error handling in the 1. Prompt Injection Defense Bypass
2. Policy Engine Circumvention
3. Trust Chain Weaknesses
4. Credential Exposure
5. Sandbox Escape
6. Deserialization Attacks
7. Race Conditions
8. Supply Chain
Summary of Findings
Suggested Fixes for This PR
Final AssessmentThis PR improves error handling and user experience, but it introduces a potential supply chain risk and does not address existing deserialization risks. Addressing these issues would further strengthen the security posture of the toolkit. |
Fixes #307
Description
Two CLI commands in packages/agent-mesh/src/agentmesh/cli/main.py had error handling problems that caused raw Python tracebacks to appear instead of useful messages.
The register command imported AgentIdentity inside the function body with no try/except. If agentmesh is not installed the user sees a full traceback instead of being told what to run. Wrapped the import in a try/except ImportError that prints a clear install instruction and returns early.
The policy command caught all exceptions as a single bare Exception and printed only the exception object. Split it into FileNotFoundError, JSONDecodeError and YAMLError, and a general fallback so each case gives a message that points to the actual problem.
Type of Change
Packages Affected
How Was This Tested?
AI Usage Disclosure