Skip to content

Conversation

@verveguy
Copy link

@verveguy verveguy commented Jan 5, 2026

Summary

  • Fix mcp-hmr initializing AsyncReloader with an empty watch path ("").
  • Derive a stable watch directory from the provided target (file path or importable module), with fallback to cwd.

Why

Watching "" can result in no files being watched (or watcher errors), causing hot reload to silently not work.

Notes

  • path:attr targets watch the parent directory of the file.
  • module:attr targets watch the directory containing the module/package on disk via find_spec().

Test plan

  • Run mcp-hmr <target>:<attr>
  • Edit a file under the target module and confirm reload triggers without restarting the MCP client.

@gemini-code-assist
Copy link

Summary of Changes

Hello @verveguy, 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 resolves a critical bug in the mcp-hmr hot reload functionality. Previously, the reloader could be initialized with an invalid watch path, leading to silent failures. The changes introduce a robust mechanism to dynamically determine the appropriate directory to monitor for changes, ensuring that hot reloading works reliably for both file-based and module-based targets.

Highlights

  • Hot Reload Fix: Addresses an issue where mcp-hmr's AsyncReloader was initialized with an empty watch path, potentially causing hot reload to fail silently.
  • Dynamic Watch Path Resolution: Introduces a new internal function, _resolve_watch_path, to intelligently determine a stable and valid directory to watch for changes, based on whether the target is a file path or an importable module.
  • Improved Reliability: Ensures that the hot reload mechanism consistently monitors the correct files, significantly improving the reliability and functionality of the mcp-hmr tool.
Using Gemini Code Assist

The 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 /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

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 .gemini/ folder in the base of the repository. Detailed instructions can be found here.

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

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey - I've found 1 issue, and left some high level feedback:

  • Consider handling the case where module_or_path is a directory (not a file and not an importable module) explicitly, so that a user-supplied package directory is watched directly instead of silently falling back to Path.cwd().
  • In _resolve_watch_path, next(iter(spec.submodule_search_locations)) will raise if the iterable is empty; it may be safer to guard this with a default or an explicit check on its length/content before calling next().
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Consider handling the case where `module_or_path` is a directory (not a file and not an importable module) explicitly, so that a user-supplied package directory is watched directly instead of silently falling back to `Path.cwd()`.
- In `_resolve_watch_path`, `next(iter(spec.submodule_search_locations))` will raise if the iterable is empty; it may be safer to guard this with a default or an explicit check on its length/content before calling `next()`.

## Individual Comments

### Comment 1
<location> `packages/mcp-hmr/mcp_hmr.py:33-35` </location>
<code_context>
+    # module:attr target
+    spec = find_spec(module_or_path)
+    if spec is not None:
+        if spec.origin:
+            # For packages, origin points at __init__.py; for modules, origin is the .py file.
+            return str(Path(spec.origin).resolve().parent)
+        if spec.submodule_search_locations:
+            # Namespace packages may have no origin; use their search location.
</code_context>

<issue_to_address>
**issue:** Guard against non-filesystem `spec.origin` values (e.g. built-in or frozen modules).

For built-in / frozen / namespace-like modules, `spec.origin` can be non-path strings (e.g. `'built-in'`), so `Path(spec.origin).resolve()` may yield bogus directories like `<cwd>/built-in` and make the reloader watch unintended paths. It would be safer to first verify that `spec.origin` is an existing file (e.g. `Path(spec.origin).is_file()`), and otherwise fall back to `submodule_search_locations` or the final fallback logic.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request fixes an issue where the hot-reloader would fail silently by not watching any files. The introduction of the _resolve_watch_path function is a good solution to correctly determine the directory to watch. The implementation is solid, but I have one suggestion to improve its robustness when handling different types of Python modules.

Comment on lines 33 to 35
if spec.origin:
# For packages, origin points at __init__.py; for modules, origin is the .py file.
return str(Path(spec.origin).resolve().parent)

Choose a reason for hiding this comment

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

medium

The check if spec.origin: is not fully robust. For built-in modules (e.g., sys), spec.origin is the string 'built-in', which is truthy. This causes Path('built-in').resolve().parent to be evaluated, which will likely resolve to the current working directory. While this may be the intended fallback behavior, the code is not explicit and relies on a side effect.

A more robust approach is to use spec.has_location, which is specifically designed to check if a module is associated with a file path. This makes the intent clearer and avoids ambiguity with built-in or other non-file-based modules.

Suggested change
if spec.origin:
# For packages, origin points at __init__.py; for modules, origin is the .py file.
return str(Path(spec.origin).resolve().parent)
if spec.has_location:
# For packages, origin points at __init__.py; for modules, origin is the .py file.
return str(Path(spec.origin).resolve().parent)

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 5, 2026

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

📝 Walkthrough

fix(mcp-hmr): watch target directory by default

Adds _resolve_watch_path() helper to compute a concrete watch directory for hot reload and updates the reloader to use it, fixing silent failures when AsyncReloader was initialized with an empty path.

Changes:

  • New _resolve_watch_path(module_or_path: str) -> str:
    • For file paths: watch the parent directory.
    • For directory paths: watch the directory itself.
    • For importable modules: watch the module/package directory (via find_spec() — origin or submodule_search_locations).
    • Falls back to the current working directory if resolution fails.
  • Reloader now calls _resolve_watch_path(module) when initializing AsyncReloader (replacing the previous empty-string path).
  • Reloader also excludes the mcp_hmr file from error filtering (error_filter.exclude_filenames.add(__file__)).

Impact: File watching is now stable across module/path targets and platforms, restoring reliable hot reload behavior without manual workarounds.

Walkthrough

A new helper _resolve_watch_path(module_or_path: str) -> str was added in packages/mcp-hmr/mcp_hmr.py to compute a directory to watch for hot-reload. It handles file paths (watch parent), directory paths (watch as-is), importable modules (derive package directory via module origin or namespace locations), and falls back to the current working directory. Reloader initialization was changed to call this helper instead of using a hard-coded empty watch path.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Possibly related PRs

  • mcp-hmr #39 — Modifies the same file and reloader/run_with_hmr logic; related to watcher path resolution changes.

Pre-merge checks

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix(mcp-hmr): watch target directory by default' directly describes the main change: replacing the empty watch path with a dynamic, resolved target directory.
Description check ✅ Passed The description clearly explains the problem (empty watch path causes hot reload to fail), the solution (derive stable watch directory), and provides a concrete test plan.

📜 Recent review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between c22c709 and 53aee10.

📒 Files selected for processing (1)
  • packages/mcp-hmr/mcp_hmr.py
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Sourcery review
🔇 Additional comments (3)
packages/mcp-hmr/mcp_hmr.py (3)

12-33: LGTM! Clear documentation and robust path handling.

The docstring effectively explains the rationale, and the file/directory path logic is straightforward and correct.


36-53: Excellent! All previous concerns have been addressed.

The implementation now properly handles edge cases flagged in earlier reviews:

  • Exception handling for find_spec() is comprehensive (lines 36-39)
  • has_location check prevents issues with built-in/frozen modules (line 44)
  • Additional is_file() guard ensures origin is a real filesystem path (line 46)
  • Safe handling of submodule_search_locations prevents empty iterator issues (line 51-53)

The defensive coding here is solid.


55-55: LGTM! Sensible fallback and correct usage.

Falling back to the current working directory is reasonable when the target cannot be resolved. The integration at line 129 cleanly replaces the problematic empty string initialization.

Also applies to: 129-129


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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 74959af and c22c709.

📒 Files selected for processing (1)
  • packages/mcp-hmr/mcp_hmr.py
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Sourcery review
🔇 Additional comments (1)
packages/mcp-hmr/mcp_hmr.py (1)

114-114: Proper fix for the empty watch path issue.

The change from an empty string to dynamically resolved path correctly addresses the silent failure issue described in the PR objectives.

@verveguy
Copy link
Author

verveguy commented Jan 5, 2026

Pushed an update to address review feedback: guard spec.origin via spec.has_location + Path(...).is_file(), wrap find_spec() in try/except, avoid next(iter(...)) on empty submodule_search_locations, and handle directory targets explicitly. Commit: 53aee10.

@verveguy
Copy link
Author

verveguy commented Jan 5, 2026

Update: addressed the review feedback in commit 53aee10.

_resolve_watch_path() is now defensive and explicit:

  • If the target string is an existing file path → watch its parent directory.
  • If it’s an existing directory path → watch that directory directly.
  • If it’s an importable module → resolve via find_spec():
    • use spec.has_location + Path(spec.origin).is_file() before trusting spec.origin (avoids "built-in"/frozen origins),
    • otherwise fall back to the first entry in spec.submodule_search_locations if present.
  • find_spec() is wrapped to avoid propagating import-related exceptions.
  • Final fallback remains cwd.

This should prevent “watch nothing” / “watch a bogus path” edge cases while preserving the intended behavior for both path:attr and module:attr targets.

@CNSeniorious000
Copy link
Member

Thanks @verveguy! I'll take a look later today.

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.

2 participants