fix: replace unwrap() with proper error handling in MCP server#189
fix: replace unwrap() with proper error handling in MCP server#189Bortlesboat wants to merge 2 commits intogoogleworkspace:mainfrom
Conversation
🦋 Changeset detectedLatest commit: 4721bed The changes in this PR will be included in the next version bump. Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
Summary of ChangesHello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request significantly enhances the stability and reliability of the MCP server by replacing panic-prone Highlights
Changelog
Activity
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
Replace panic-prone unwrap() calls with safe alternatives: - Use unwrap_or for clap arg with default value - Use if-let pattern for JSON-RPC id extraction - Use match for tools_cache access - Return validation error instead of unwrap on parts.last() - Break server loop on stdout pipe errors instead of silently continuing to process requests that can never be delivered Also adds unit test coverage for build_mcp_cli, walk_resources, and handle_request.
5f3f358 to
68e2365
Compare
There was a problem hiding this comment.
Code Review
This pull request does a good job of improving error handling in the MCP server by replacing several unwrap() calls with safer alternatives. The changes to handle broken stdout pipes and the addition of unit tests are also valuable improvements. I've found a couple of places where the new error handling logic is on an unreachable path, which could be confusing. My review includes suggestions to make these cases clearer and more explicit.
I am having trouble creating individual review comments. Click here to see my feedback.
src/mcp_server.rs (393-395)
This ok_or_else call is on an unreachable path. The split method on a &str always returns a non-empty iterator, so parts.last() will never be None. The original unwrap() was safe. Since the goal of this PR is to remove unwrap(), using expect() with an explanation is a good alternative to document why this operation is safe.
let method_name = parts.last().expect("split() on a &str always yields at least one element");src/mcp_server.rs (200-206)
The None branch of this match is unreachable because the if block on line 197 guarantees that tools_cache is Some. While the current fallback to an empty array is safe, it can be misleading for future maintainers. Using unreachable! makes the code's invariant explicit and will cause a panic if this assumption is ever violated, which is helpful for debugging.
let tools = match tools_cache.as_ref() {
Some(t) => json!(t),
None => unreachable!("tools_cache is guaranteed to be populated by the check above"),
};
Ok(json!({
"tools": tools
}))
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #189 +/- ##
==========================================
+ Coverage 56.21% 56.92% +0.70%
==========================================
Files 38 38
Lines 13853 13973 +120
==========================================
+ Hits 7788 7954 +166
+ Misses 6065 6019 -46 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request significantly improves the robustness of the MCP server by replacing several unwrap() calls with proper error handling and adding checks for broken stdout pipes. The changes are well-implemented and the addition of unit tests is a great enhancement. I have one suggestion to further improve error handling by replacing an expect() call with ok_or_else to align with the PR's goal of avoiding panics, as mentioned in the description.
| let method_name = parts | ||
| .last() | ||
| .expect("split() on a &str always yields at least one element"); |
There was a problem hiding this comment.
While parts.last() is not expected to be None here due to the parts.len() < 3 check, using expect() still introduces a potential panic. The pull request description mentions replacing this with .ok_or_else(), which would be a more robust approach that aligns better with the goal of removing panics. Returning a GwsError::Validation would be safer if the invariant ever changes.
| let method_name = parts | |
| .last() | |
| .expect("split() on a &str always yields at least one element"); | |
| let method_name = parts | |
| .last() | |
| .ok_or_else(|| GwsError::Validation("Invalid tool name format".to_string()))?; |
Summary
unwrap()calls with safe alternatives inmcp_server.rsbuild_mcp_cli,walk_resources, andhandle_requestContinues the work from #109 which addressed some MCP server unwraps.
Changes
get_one("services").unwrap().unwrap_or("")req.get("id").unwrap()afteris_none()checkif let Some(id)patterntools_cache.as_ref().unwrap()matchexpressionparts.last().unwrap().ok_or_else()with validation errorlet _ =(silent)Test plan
cargo test,cargo clippy,cargo fmt