From 60a6f349d92b887977ec87404f253f34ef20e5e8 Mon Sep 17 00:00:00 2001
From: tonyxwz <16152581+tonyxwz@users.noreply.github.com>
Date: Thu, 4 Dec 2025 11:30:56 +0100
Subject: [PATCH] docs update
---
docs/servers/middleware.mdx | 28 ++++++++++++++++++-
.../test_initialization_middleware.py | 6 ++--
2 files changed, 31 insertions(+), 3 deletions(-)
diff --git a/docs/servers/middleware.mdx b/docs/servers/middleware.mdx
index 341d91046..8ffd683c0 100644
--- a/docs/servers/middleware.mdx
+++ b/docs/servers/middleware.mdx
@@ -108,6 +108,32 @@ This hierarchy allows you to target your middleware logic with the right level o
The `on_initialize` hook receives the client's initialization request but **returns `None`** rather than a result. The initialization response is handled internally by the MCP protocol and cannot be modified by middleware. This hook is useful for client detection, logging connections, or initializing session state, but not for modifying the initialization handshake itself.
+**Example:**
+
+```python
+from fastmcp.server.middleware import Middleware, MiddlewareContext
+from mcp import McpError
+from mcp.types import ErrorData
+
+class InitializationMiddleware(Middleware):
+ async def on_initialize(self, context: MiddlewareContext, call_next):
+ # Check client capabilities before initialization
+ client_info = context.message.params.get("clientInfo", {})
+ client_name = client_info.get("name", "unknown")
+
+ # Reject unsupported clients BEFORE call_next
+ if client_name == "unsupported-client":
+ raise McpError(ErrorData(code=-32000, message="This client is not supported"))
+
+ # Log successful initialization
+ await call_next(context)
+ print(f"Client {client_name} initialized successfully")
+```
+
+
+If you raise `McpError` in `on_initialize` **after** calling `call_next()`, the error will only be logged and will not be sent to the client. The initialization response has already been sent at that point. Always raise `McpError` **before** `call_next()` if you want to reject the initialization.
+
+
### MCP Session Availability in Middleware
@@ -787,4 +813,4 @@ class CustomHeaderMiddleware(Middleware):
return result
mcp.add_middleware(CustomHeaderMiddleware())
-```
\ No newline at end of file
+```
diff --git a/tests/server/middleware/test_initialization_middleware.py b/tests/server/middleware/test_initialization_middleware.py
index a1b55a8bf..a34920a4a 100644
--- a/tests/server/middleware/test_initialization_middleware.py
+++ b/tests/server/middleware/test_initialization_middleware.py
@@ -366,6 +366,8 @@ async def test_middleware_mcp_error_after_call_next():
middleware = PostProcessingErrorMiddleware()
server.add_middleware(middleware)
- # Connection succeeds because responder._completed check prevents re-responding
+ # Error is logged but not re-raised to prevent duplicate response
async with Client(server):
- assert middleware.error_raised is True
+ pass
+
+ assert middleware.error_raised is True