You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The built-in versions include custom logger support, proper formatting, and **DetailedTimingMiddleware** provides operation-specific hooks like `on_call_tool` and `on_read_resource` for granular timing.
451
451
452
+
### Caching Middleware
453
+
454
+
Caching middleware is essential for improving performance and reducing server load. FastMCP provides caching middleware at `fastmcp.server.middleware.caching`.
455
+
456
+
Here's how to use the full version:
457
+
458
+
```python
459
+
from fastmcp.server.middleware.caching import ResponseCachingMiddleware
460
+
461
+
mcp.add_middleware(ResponseCachingMiddleware())
462
+
```
463
+
464
+
Out of the box, it caches call/list tool, resources, and prompts to an in-memory cache. Sending a notification of a tool/resource/prompt change will invalidate the cache for the affected method. List calls are stored under global keys, if you share a key_value backend across servers, keep this in mind and consider using the PrefixCollectionsWrapper in py-key-value-aio to namespace collections by server.
465
+
466
+
Each method can be configured individually, for example, caching list tools for 30 seconds, skipping caching for tools other than `tool1` and not caching and requests to read resources:
467
+
468
+
```python
469
+
from fastmcp.server.middleware.caching import ResponseCachingMiddleware, CallToolSettings, ListToolsSettings, ReadResourceSettings
470
+
471
+
mcp.add_middleware(ResponseCachingMiddleware(
472
+
list_tools_settings=ListToolsSettings(
473
+
ttl=30,
474
+
),
475
+
call_tool_settings=CallToolSettings(
476
+
included_tools=["tool1"],
477
+
),
478
+
read_resource_settings=ReadResourceSettings(
479
+
enabled=False
480
+
)
481
+
))
482
+
```
483
+
484
+
It can also be configured to cache to disk:
485
+
486
+
```python
487
+
from fastmcp.server.middleware.caching import ResponseCachingMiddleware
488
+
from key_value.aio.stores.disk import DiskStore
489
+
490
+
mcp.add_middleware(ResponseCachingMiddleware(
491
+
cache_storage=DiskStore(directory="cache"),
492
+
))
493
+
```
494
+
495
+
See the Contrib modules for caching middleware implementations that support additional features like distributed caching.
496
+
452
497
### Logging Middleware
453
498
454
499
Request and response logging is crucial for debugging, monitoring, and understanding usage patterns in your MCP server. FastMCP provides comprehensive logging middleware at `fastmcp.server.middleware.logging`.
0 commit comments