Skip to content

feat: handle error from the initialize middleware#2531

Merged
jlowin merged 4 commits intoPrefectHQ:mainfrom
tonyxwz:handle-error-in-init-middleware
Dec 10, 2025
Merged

feat: handle error from the initialize middleware#2531
jlowin merged 4 commits intoPrefectHQ:mainfrom
tonyxwz:handle-error-in-init-middleware

Conversation

@tonyxwz
Copy link
Copy Markdown
Contributor

@tonyxwz tonyxwz commented Dec 3, 2025

Description

In some situation, the initialize middleware can check the status of the server and decide to raise an error.

Example use case: in a FastMCPProxy, an initialization middleware overrides the on_initialize method and connect to the underlying proxied client. If the proxy client respond with error, I want to pass this error to the client.

Contributors Checklist

Review Checklist

  • I have self-reviewed my changes
  • My Pull Request is ready for review

@marvin-context-protocol marvin-context-protocol Bot added enhancement Improvement to existing functionality. For issues and smaller PR improvements. server Related to FastMCP server implementation or server-side functionality. labels Dec 3, 2025
with responder:
await responder.respond(e.error)
else:
# Don't re-raise: prevents responding to initialize request twice
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@tonyxwz tonyxwz marked this pull request as ready for review December 3, 2025 22:38
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Dec 3, 2025

Walkthrough

Server middleware handling now catches McpError raised during initialization: if the responder is not yet completed the error is sent via the responder; if already completed the error is logged and not re-raised. Documentation (docs/servers/middleware.mdx) adds an InitializationMiddleware example showing pre-call_next rejection, warns that raising McpError after call_next() won’t reach the client, and fixes a malformed code fence in the custom header example.

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main change: handling errors from initialize middleware, which accurately reflects the primary objective of the PR.
Description check ✅ Passed The description includes all required sections with relevant details: context for the feature, use case, and completed checklist items demonstrating proper workflow adherence.
Linked Issues check ✅ Passed The PR successfully implements the requirements from issue #2552: allows middleware to raise McpError during initialization, propagates it to the client, and supports credential validation scenarios.
Out of Scope Changes check ✅ Passed All changes (error handling in low_level.py and documentation in middleware.mdx) are directly aligned with the scope of handling initialize middleware errors and are not extraneous.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 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 5e62a62 and 73c4102.

⛔ Files ignored due to path filters (1)
  • tests/server/middleware/test_initialization_middleware.py is excluded by none and included by none
📒 Files selected for processing (1)
  • src/fastmcp/server/low_level.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/fastmcp/server/low_level.py

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
Copy Markdown
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: 0

🧹 Nitpick comments (1)
src/fastmcp/server/low_level.py (1)

107-122: Consider using logging.exception for better debugging.

The error handling logic correctly prevents duplicate responses by checking responder._completed before attempting to respond with the error. However, when logging the error at line 119, consider using logging.exception instead of logging.error to automatically include the traceback, which aids debugging.

Apply this diff:

                 else:
                     # Don't re-raise: prevents responding to initialize request twice
-                    logger.error(
+                    logger.exception(
                         "Received McpError but responder is already completed. "
                         "Cannot send error response as response was already sent."
                     )

Note: The code accesses the private _completed attribute (line 114). While this appears intentional based on the past review comment referencing the MCP SDK's session implementation, be aware that relying on private attributes may be fragile if the upstream library changes its internals.

Based on static analysis hints from Ruff (TRY400).

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ee63405 and 0128b2f.

⛔ Files ignored due to path filters (1)
  • tests/server/middleware/test_initialization_middleware.py is excluded by none and included by none
📒 Files selected for processing (2)
  • docs/servers/middleware.mdx (2 hunks)
  • src/fastmcp/server/low_level.py (2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
docs/**/*.mdx

📄 CodeRabbit inference engine (docs/.cursor/rules/mintlify.mdc)

docs/**/*.mdx: Use clear, direct language appropriate for technical audiences
Write in second person ('you') for instructions and procedures in MDX documentation
Use active voice over passive voice in MDX technical documentation
Employ present tense for current states and future tense for outcomes in MDX documentation
Maintain consistent terminology throughout all MDX documentation
Keep sentences concise while providing necessary context in MDX documentation
Use parallel structure in lists, headings, and procedures in MDX documentation
Lead with the most important information using inverted pyramid structure in MDX documentation
Use progressive disclosure in MDX documentation: present basic concepts before advanced ones
Break complex procedures into numbered steps in MDX documentation
Include prerequisites and context before instructions in MDX documentation
Provide expected outcomes for each major step in MDX documentation
End sections with next steps or related information in MDX documentation
Use descriptive, keyword-rich headings for navigation and SEO in MDX documentation
Focus on user goals and outcomes rather than system features in MDX documentation
Anticipate common questions and address them proactively in MDX documentation
Include troubleshooting for likely failure points in MDX documentation
Provide multiple pathways (beginner vs advanced) but offer an opinionated path to avoid overwhelming users in MDX documentation
Always include complete, runnable code examples that users can copy and execute in MDX documentation
Show proper error handling and edge case management in MDX code examples
Use realistic data instead of placeholder values in MDX code examples
Include expected outputs and results for verification in MDX code examples
Test all code examples thoroughly before publishing in MDX documentation
Specify language and include filename when relevant in MDX code examples
Add explanatory comments for complex logic in MDX code examples
Document all API...

Files:

  • docs/servers/middleware.mdx
src/**/*.py

📄 CodeRabbit inference engine (AGENTS.md)

src/**/*.py: Python source code must be version ≥3.10 with full type annotations
Prioritize readable, understandable code - clarity over cleverness; avoid obfuscated or confusing patterns even if they're shorter
Never use bare except in code - be specific with exception types

Files:

  • src/fastmcp/server/low_level.py
🧬 Code graph analysis (1)
src/fastmcp/server/low_level.py (2)
src/fastmcp/server/context.py (1)
  • fastmcp (152-157)
src/fastmcp/server/server.py (1)
  • _apply_middleware (437-446)
🪛 Ruff (0.14.7)
src/fastmcp/server/low_level.py

119-122: Use logging.exception instead of logging.error

Replace with exception

(TRY400)

⏰ 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: Run tests: Python 3.10 on windows-latest
🔇 Additional comments (2)
docs/servers/middleware.mdx (1)

111-134: Excellent documentation of initialization error handling.

The InitializationMiddleware example clearly demonstrates the correct pattern for rejecting clients before call_next(), and the warning appropriately explains the constraint on error propagation after the responder completes. This aligns perfectly with the implementation changes and provides users with actionable guidance.

As per coding guidelines, the documentation uses clear, direct language with active voice and provides a complete, runnable code example with proper error handling.

src/fastmcp/server/low_level.py (1)

10-10: LGTM: Import necessary for error handling.

The McpError import is required for the new exception handling in the initialization flow.

@marvin-context-protocol
Copy link
Copy Markdown
Contributor

Test Failure Analysis

Summary: Windows-specific pytest worker crash on Python 3.10 when running test_settings_from_environment_issue_1749.

Root Cause: The test failure is a Windows-specific infrastructure issue with pytest-xdist workers, not a direct failure of the test logic. The test spawns a subprocess using PythonStdioTransport, and on Windows + Python 3.10, the worker crashes with ConnectionResetError: [WinError 10054] when the subprocess terminates.

The PR's new error handling code in src/fastmcp/server/low_level.py lines 107-122 is functionally correct - all 9 new middleware tests pass, including error handling scenarios. However, there's a minor code quality issue:

Suggested Fix: In the error handling block (lines 117-122), after logging the error, the function should explicitly return None to maintain code clarity and match the expected return type:

else:
    # Don't re-raise: prevents responding to initialize request twice
    logger.error(
        "Received McpError but responder is already completed. "
        "Cannot send error response as response was already sent."
    )
    return None  # Add explicit return

Why This Failure Might Be Transient:

  1. The test passes on Linux (verified locally on Python 3.12)
  2. All 9 new middleware tests pass, including 3 specifically testing error handling
  3. The error occurs in pytest_retry/server.py, not in FastMCP code
  4. Windows subprocess handling in pytest-xdist can be flaky

Recommendation:

  • Add the explicit return None for code clarity
  • Re-run the CI to see if the failure reproduces (it may be a transient Windows/pytest-xdist issue)
  • If it persists, consider marking this specific test with @pytest.mark.client_process to exclude it from parallel execution
Detailed Analysis

Test Failure Log:

worker 'gw1' crashed while running 'tests/server/test_server.py::TestSettingsFromEnvironment::test_settings_from_environment_issue_1749'
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

What the test does:

  • Creates a temporary Python script that sets up a FastMCP server with Azure auth
  • Runs it as a subprocess via PythonStdioTransport
  • Connects to it and lists tools

Why it might crash on Windows:

  • Windows handles subprocess cleanup differently than Linux
  • pytest-xdist workers use socket-based communication that can be interrupted
  • Python 3.10's asyncio implementation on Windows has known issues with subprocess management

Evidence this isn't a logic error:

$ uv run pytest tests/server/middleware/test_initialization_middleware.py -xvs
======= 9 passed in 0.12s =======

All new error handling tests pass, including:

  • test_middleware_mcp_error_during_initialization
  • test_middleware_mcp_error_before_call_next
  • test_middleware_mcp_error_after_call_next
Related Files
  • src/fastmcp/server/low_level.py:107-122 - Error handling code added by this PR
  • tests/server/test_server.py:1434-1472 - The failing test
  • tests/server/middleware/test_initialization_middleware.py:292-373 - New passing tests

@tonyxwz tonyxwz force-pushed the handle-error-in-init-middleware branch from 0128b2f to 82d9875 Compare December 3, 2025 22:45
Copy link
Copy Markdown
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: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0128b2f and 82d9875.

⛔ Files ignored due to path filters (1)
  • tests/server/middleware/test_initialization_middleware.py is excluded by none and included by none
📒 Files selected for processing (2)
  • docs/servers/middleware.mdx (2 hunks)
  • src/fastmcp/server/low_level.py (2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
docs/**/*.mdx

📄 CodeRabbit inference engine (docs/.cursor/rules/mintlify.mdc)

docs/**/*.mdx: Use clear, direct language appropriate for technical audiences
Write in second person ('you') for instructions and procedures in MDX documentation
Use active voice over passive voice in MDX technical documentation
Employ present tense for current states and future tense for outcomes in MDX documentation
Maintain consistent terminology throughout all MDX documentation
Keep sentences concise while providing necessary context in MDX documentation
Use parallel structure in lists, headings, and procedures in MDX documentation
Lead with the most important information using inverted pyramid structure in MDX documentation
Use progressive disclosure in MDX documentation: present basic concepts before advanced ones
Break complex procedures into numbered steps in MDX documentation
Include prerequisites and context before instructions in MDX documentation
Provide expected outcomes for each major step in MDX documentation
End sections with next steps or related information in MDX documentation
Use descriptive, keyword-rich headings for navigation and SEO in MDX documentation
Focus on user goals and outcomes rather than system features in MDX documentation
Anticipate common questions and address them proactively in MDX documentation
Include troubleshooting for likely failure points in MDX documentation
Provide multiple pathways (beginner vs advanced) but offer an opinionated path to avoid overwhelming users in MDX documentation
Always include complete, runnable code examples that users can copy and execute in MDX documentation
Show proper error handling and edge case management in MDX code examples
Use realistic data instead of placeholder values in MDX code examples
Include expected outputs and results for verification in MDX code examples
Test all code examples thoroughly before publishing in MDX documentation
Specify language and include filename when relevant in MDX code examples
Add explanatory comments for complex logic in MDX code examples
Document all API...

Files:

  • docs/servers/middleware.mdx
src/**/*.py

📄 CodeRabbit inference engine (AGENTS.md)

src/**/*.py: Python source code must be version ≥3.10 with full type annotations
Prioritize readable, understandable code - clarity over cleverness; avoid obfuscated or confusing patterns even if they're shorter
Never use bare except in code - be specific with exception types

Files:

  • src/fastmcp/server/low_level.py
🧬 Code graph analysis (1)
src/fastmcp/server/low_level.py (2)
src/fastmcp/server/context.py (2)
  • fastmcp (152-157)
  • error (441-455)
src/fastmcp/server/server.py (1)
  • _apply_middleware (437-446)
🪛 Ruff (0.14.7)
src/fastmcp/server/low_level.py

119-122: Use logging.exception instead of logging.error

Replace with exception

(TRY400)

⏰ 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: Run tests: Python 3.10 on windows-latest
🔇 Additional comments (3)
src/fastmcp/server/low_level.py (1)

10-10: LGTM!

The McpError import is correctly placed and necessary for the new error handling logic.

docs/servers/middleware.mdx (2)

816-816: LGTM!

The closing code fence fix ensures proper Markdown rendering of the CustomHeaderMiddleware example.


111-135: Example is correct per MCP specification.

The context.message.params.get("clientInfo", {}) access pattern is valid. Per the MCP protocol specification, InitializeRequest.params contains the clientInfo object with required name and version fields. The example properly accesses clientInfo and defensively provides a fallback value. The code is syntactically correct and the warning about error timing after call_next() accurately reflects the implementation behavior.

Comment thread src/fastmcp/server/low_level.py
@tonyxwz tonyxwz force-pushed the handle-error-in-init-middleware branch from 82d9875 to a386391 Compare December 4, 2025 10:31
Copy link
Copy Markdown
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: 0

🧹 Nitpick comments (1)
src/fastmcp/server/low_level.py (1)

118-123: Consider using ERROR level for exception logging.

The current code uses logger.warning with exc_info=e, which does include exception details (addressing the diagnostics concern from the past review). However, a previous review suggested using logger.exception() (ERROR level) instead of logger.error() for better visibility.

When an McpError is raised but cannot be communicated to the client, this represents a significant issue worthy of ERROR-level logging—even though it's a defensive edge case. While WARNING is defensible (the client received a successful response, and this prevents double-responding), ERROR level would make this exception more visible during debugging and aligns with the past review suggestion.

If ERROR level is appropriate, apply this diff:

-                        logger.warning(
+                        logger.exception(
                             "Received McpError but responder is already completed. "
                             "Cannot send error response as response was already sent.",
-                            exc_info=e,
                         )

Note: logger.exception() automatically includes exception info when called in an except block, so the exc_info parameter can be removed.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 82d9875 and a386391.

⛔ Files ignored due to path filters (1)
  • tests/server/middleware/test_initialization_middleware.py is excluded by none and included by none
📒 Files selected for processing (2)
  • docs/servers/middleware.mdx (2 hunks)
  • src/fastmcp/server/low_level.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • docs/servers/middleware.mdx
🧰 Additional context used
📓 Path-based instructions (1)
src/**/*.py

📄 CodeRabbit inference engine (AGENTS.md)

src/**/*.py: Python source code must use Python ≥3.10 with full type annotations
Never use bare except - be specific with exception types
Prioritize readable, understandable code - clarity over cleverness; avoid obfuscated or confusing patterns even if shorter
Follow existing patterns and maintain consistency in code organization and style

Files:

  • src/fastmcp/server/low_level.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: Run tests: Python 3.10 on windows-latest
🔇 Additional comments (2)
src/fastmcp/server/low_level.py (2)

10-10: LGTM! Import is correctly added.

The McpError import is necessary for the exception handling in the middleware application and follows the existing import structure.


107-116: LGTM! Error handling logic is sound.

The try/except block correctly catches McpError from middleware and propagates it to the client when the responder hasn't completed yet. The defensive check on responder._completed (though a private attribute) prevents double-response errors, and the context manager ensures proper cleanup.

wzxxing added a commit to wzxxing/mcp-proxy-for-aws that referenced this pull request Dec 4, 2025
wzxxing added a commit to wzxxing/mcp-proxy-for-aws that referenced this pull request Dec 4, 2025
wzxxing added a commit to wzxxing/mcp-proxy-for-aws that referenced this pull request Dec 4, 2025
wzxxing added a commit to aws/mcp-proxy-for-aws that referenced this pull request Dec 4, 2025
Copy link
Copy Markdown
Member

@jlowin jlowin left a comment

Choose a reason for hiding this comment

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

Thanks @tonyxwz!

Copy link
Copy Markdown
Member

@jlowin jlowin left a comment

Choose a reason for hiding this comment

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

Actually sorry @tonyxwz, when I tried to resolve the merge conflict I found that tests fail with MCP SDK 1.23+ (which is what the main branch / FastMCP 2.14) requires. Perhaps there were some changes to how its internals work with regrad to initialization? If you wouldn't mind reviewing that, we can get this merged once compatible. Thanks!

@tonyxwz
Copy link
Copy Markdown
Contributor Author

tonyxwz commented Dec 7, 2025

@jlowin thank for reviewing. I will take a look at the failed test.

In some situation, the initialize middleware can check the status of the
server and decide to raise an error.

Example use case: in a FastMCPProxy, an initialization middleware
overrides the on_initialize method and connect to the underlying proxied
client. When client respond with error, I want to pass this error to the
client.
@tonyxwz tonyxwz force-pushed the handle-error-in-init-middleware branch from a386391 to 5e62a62 Compare December 10, 2025 11:15
Copy link
Copy Markdown
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

♻️ Duplicate comments (1)
src/fastmcp/server/low_level.py (1)

111-127: Fix exc_info parameter in logger call.

The exception handling logic correctly prevents duplicate responses. However, the logging call uses a non-standard pattern:

Line 126: Use exc_info=True instead of exc_info=e. The standard Python logging idiom when inside an exception handler is exc_info=True, which automatically captures the current exception context via sys.exc_info(). While passing the exception instance (exc_info=e) is technically valid and supported since Python 3.2+, it deviates from the standard pattern established across Python code.

Apply this fix:

                     logger.warning(
                         "Received McpError but responder is already completed. "
                         "Cannot send error response as response was already sent.",
-                        exc_info=e,
+                        exc_info=True,
                     )
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a386391 and 5e62a62.

⛔ Files ignored due to path filters (1)
  • tests/server/middleware/test_initialization_middleware.py is excluded by none and included by none
📒 Files selected for processing (2)
  • docs/servers/middleware.mdx (2 hunks)
  • src/fastmcp/server/low_level.py (2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
docs/**/*.mdx

📄 CodeRabbit inference engine (docs/.cursor/rules/mintlify.mdc)

docs/**/*.mdx: Use clear, direct language appropriate for technical audiences
Write in second person ('you') for instructions and procedures in MDX documentation
Use active voice over passive voice in MDX technical documentation
Employ present tense for current states and future tense for outcomes in MDX documentation
Maintain consistent terminology throughout all MDX documentation
Keep sentences concise while providing necessary context in MDX documentation
Use parallel structure in lists, headings, and procedures in MDX documentation
Lead with the most important information using inverted pyramid structure in MDX documentation
Use progressive disclosure in MDX documentation: present basic concepts before advanced ones
Break complex procedures into numbered steps in MDX documentation
Include prerequisites and context before instructions in MDX documentation
Provide expected outcomes for each major step in MDX documentation
End sections with next steps or related information in MDX documentation
Use descriptive, keyword-rich headings for navigation and SEO in MDX documentation
Focus on user goals and outcomes rather than system features in MDX documentation
Anticipate common questions and address them proactively in MDX documentation
Include troubleshooting for likely failure points in MDX documentation
Provide multiple pathways (beginner vs advanced) but offer an opinionated path to avoid overwhelming users in MDX documentation
Always include complete, runnable code examples that users can copy and execute in MDX documentation
Show proper error handling and edge case management in MDX code examples
Use realistic data instead of placeholder values in MDX code examples
Include expected outputs and results for verification in MDX code examples
Test all code examples thoroughly before publishing in MDX documentation
Specify language and include filename when relevant in MDX code examples
Add explanatory comments for complex logic in MDX code examples
Document all API...

Files:

  • docs/servers/middleware.mdx
src/**/*.py

📄 CodeRabbit inference engine (AGENTS.md)

src/**/*.py: Python source code must use Python ≥3.10 with full type annotations
Never use bare except - be specific with exception types
Prioritize readable, understandable code - clarity over cleverness; avoid obfuscated or confusing patterns even if shorter
Follow existing patterns and maintain consistency in code organization and style

Files:

  • src/fastmcp/server/low_level.py
🧬 Code graph analysis (1)
src/fastmcp/server/low_level.py (2)
src/fastmcp/server/context.py (3)
  • fastmcp (150-155)
  • error (454-468)
  • warning (438-452)
src/fastmcp/server/server.py (1)
  • _apply_middleware (919-928)
⏰ 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). (3)
  • GitHub Check: Run tests: Python 3.10 on ubuntu-latest
  • GitHub Check: Run tests: Python 3.10 on windows-latest
  • GitHub Check: Run tests with lowest-direct dependencies
🔇 Additional comments (3)
src/fastmcp/server/low_level.py (1)

10-10: LGTM! Import is correctly placed.

The McpError import is necessary for catching initialization errors raised by middleware.

docs/servers/middleware.mdx (2)

816-816: LGTM! Code fence properly terminated.

This fixes the malformed code fence for the CustomHeaderMiddleware example, ensuring proper markdown rendering.


111-135: Excellent documentation with clear example and warnings.

This InitializationMiddleware example effectively demonstrates:

  • Pre-validation rejection by raising McpError before call_next()
  • Accessing client information from the initialize request
  • Proper error code usage (-32000 for application errors)
  • Post-initialization logging after successful initialization

The warning box correctly explains the critical timing constraint: errors raised after call_next() won't reach the client because the response has already been sent. This aligns with the implementation pattern in the codebase.

The code example follows MDX documentation best practices: uses second person in warnings, includes complete runnable code, provides warnings for likely failure points, and uses clear technical language. The context.message.params.get("clientInfo", {}) pattern follows standard MCP protocol conventions for accessing initialization request parameters.

Comment thread src/fastmcp/server/low_level.py Outdated
- Update tests to catch McpError specifically instead of generic Exception
- Remove commented-out code in low_level.py
@jlowin
Copy link
Copy Markdown
Member

jlowin commented Dec 10, 2025

@tonyxwz I've made some changes that I think resolve the errors, including some that fixed error handling more broadly

@jlowin jlowin merged commit 03b62d2 into PrefectHQ:main Dec 10, 2025
7 checks passed
@tonyxwz
Copy link
Copy Markdown
Contributor Author

tonyxwz commented Dec 11, 2025

Thanks @jlowin, I was not able to figure out the fix you did in #2591 fast enough.

wzxxing added a commit to wzxxing/mcp-proxy-for-aws that referenced this pull request Jan 16, 2026
@wzxxing wzxxing mentioned this pull request Jan 16, 2026
8 tasks
wzxxing added a commit to wzxxing/mcp-proxy-for-aws that referenced this pull request Jan 16, 2026
wzxxing added a commit to wzxxing/mcp-proxy-for-aws that referenced this pull request Jan 19, 2026
anasstahr pushed a commit to wzxxing/mcp-proxy-for-aws that referenced this pull request Mar 24, 2026
anasstahr pushed a commit to aws/mcp-proxy-for-aws that referenced this pull request Mar 24, 2026
* fix: add kwargs to http client factory

* chore: upgrade fastmcp to v2.14.1

* feat: remove the fastmcp patch

change merged to upstream: PrefectHQ/fastmcp#2531

* fix: upgrade to the latest on_initialize method signature

* test: validate the patch merged in fastmcp works as expected

* fix pyright issues
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement Improvement to existing functionality. For issues and smaller PR improvements. server Related to FastMCP server implementation or server-side functionality.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Handle the McpError from the middleware when initialize the session

2 participants