Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Consolidate session state reset logic and improve cancellation cleanup#2615

Merged
jlowin merged 1 commit intomainfrom
improve-cancelled-connection-cleanup
Dec 14, 2025
Merged

Consolidate session state reset logic and improve cancellation cleanup#2615
jlowin merged 1 commit intomainfrom
improve-cancelled-connection-cleanup

Conversation

@jlowin
Copy link
Member

@jlowin jlowin commented Dec 14, 2025

Follow-up to #2614 that consolidates the session state reset logic and adds robustness improvements to the cancellation cleanup path.

Changes:

  • Extract _reset_session_state() helper to consolidate duplicated state reset logic between _context_manager and the cancellation cleanup
  • Add 3-second timeouts to cleanup awaits to prevent hanging on stuck tasks/transports
  • Add anyio.CancelScope(shield=True) to protect cleanup from outer cancellation
  • Log errors during cleanup at debug level instead of silently suppressing them
  • Add documentation explaining why session_task must remain an asyncio.Task (anyio's structured concurrency doesn't allow tasks to escape their task group)

@marvin-context-protocol marvin-context-protocol bot added enhancement Improvement to existing functionality. For issues and smaller PR improvements. client Related to the FastMCP client SDK or client-side functionality. labels Dec 14, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 14, 2025

Walkthrough

The pull request refactors session state management in the FastMCP client by introducing a private _reset_session_state(full=False) helper method that centralizes state reset logic. The helper resets session-related state, and when full=True, also clears session_task and nesting_counter. During cancellation handling in _connect, the code now uses guarded cleanup with anyio CancelScope shielding and timeouts for both session_task and transport closure, with error logging for failures. The context manager cleanup now delegates to this helper instead of directly resetting state. Normal operation behavior remains unchanged.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% 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 accurately describes the main changes: consolidating session state reset logic and improving cancellation cleanup, which aligns perfectly with the changeset.
Description check ✅ Passed The description covers all required sections including clear summary, specific changes, and contributions checklist items, though some checklist boxes are unchecked indicating incomplete review preparation.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch improve-cancelled-connection-cleanup

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d26b04f and d238569.

📒 Files selected for processing (1)
  • src/fastmcp/client/client.py (4 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.py

📄 CodeRabbit inference engine (AGENTS.md)

**/*.py: Write Python code with Python ≥3.10 and include full type annotations
Use specific exception types in error handling - never use bare except
Prioritize readable, understandable code - clarity over cleverness; avoid obfuscated or confusing patterns even if they're shorter

Files:

  • src/fastmcp/client/client.py
🧠 Learnings (1)
📓 Common learnings
Learnt from: jlowin
Repo: jlowin/fastmcp PR: 0
File: :0-0
Timestamp: 2025-12-01T15:48:05.095Z
Learning: PR #2505 in fastmcp adds NEW functionality to get_access_token(): it now first checks request.scope["user"] for the token (which never existed before), then falls back to _sdk_get_access_token() (the only thing the original code did). This is not a reversal of order but entirely new functionality to fix stale token issues.
🪛 Ruff (0.14.8)
src/fastmcp/client/client.py

542-542: Do not catch blind exception: Exception

(BLE001)


554-554: Do not catch blind exception: Exception

(BLE001)

⏰ 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). (4)
  • GitHub Check: Run tests: Python 3.13 on ubuntu-latest
  • GitHub Check: Run tests: Python 3.10 on ubuntu-latest
  • GitHub Check: Run tests with lowest-direct dependencies
  • GitHub Check: Run tests: Python 3.10 on windows-latest
🔇 Additional comments (3)
src/fastmcp/client/client.py (3)

327-339: Clean extraction of reset logic.

The helper method correctly centralizes the state reset logic with appropriate granularity via the full parameter. The docstring clearly explains when to use full=True.


420-421: LGTM!

Correctly delegates to the new helper with full=False (default), preserving the original behavior while centralizing the logic.


536-557: Robust cancellation cleanup with appropriate defensive error handling.

The shielded cleanup with timeouts correctly prevents hanging during cancellation scenarios. The broad Exception catches (flagged by static analysis as BLE001) are appropriate here—this is cleanup code where any failure should be logged and swallowed to ensure the cleanup path completes and the original CancelledError is re-raised.

One minor observation: the two cleanup blocks follow identical patterns, which is good for consistency.


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.

@jlowin jlowin merged commit 0cd3690 into main Dec 14, 2025
13 checks passed
@jlowin jlowin deleted the improve-cancelled-connection-cleanup branch December 14, 2025 14:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

client Related to the FastMCP client SDK or client-side functionality. enhancement Improvement to existing functionality. For issues and smaller PR improvements.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant