fastmcp 2.12.1__py3-none-any.whl → 2.13.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fastmcp/__init__.py +2 -2
- fastmcp/cli/cli.py +56 -36
- fastmcp/cli/install/__init__.py +2 -0
- fastmcp/cli/install/claude_code.py +7 -16
- fastmcp/cli/install/claude_desktop.py +4 -12
- fastmcp/cli/install/cursor.py +20 -30
- fastmcp/cli/install/gemini_cli.py +241 -0
- fastmcp/cli/install/mcp_json.py +4 -12
- fastmcp/cli/run.py +15 -94
- fastmcp/client/__init__.py +9 -9
- fastmcp/client/auth/oauth.py +117 -206
- fastmcp/client/client.py +123 -47
- fastmcp/client/elicitation.py +6 -1
- fastmcp/client/logging.py +18 -14
- fastmcp/client/oauth_callback.py +85 -171
- fastmcp/client/sampling.py +1 -1
- fastmcp/client/transports.py +81 -26
- fastmcp/contrib/component_manager/__init__.py +1 -1
- fastmcp/contrib/component_manager/component_manager.py +2 -2
- fastmcp/contrib/component_manager/component_service.py +7 -7
- fastmcp/contrib/mcp_mixin/README.md +35 -4
- fastmcp/contrib/mcp_mixin/__init__.py +2 -2
- fastmcp/contrib/mcp_mixin/mcp_mixin.py +54 -7
- fastmcp/experimental/sampling/handlers/openai.py +2 -2
- fastmcp/experimental/server/openapi/__init__.py +5 -8
- fastmcp/experimental/server/openapi/components.py +11 -7
- fastmcp/experimental/server/openapi/routing.py +2 -2
- fastmcp/experimental/utilities/openapi/__init__.py +10 -15
- fastmcp/experimental/utilities/openapi/director.py +16 -10
- fastmcp/experimental/utilities/openapi/json_schema_converter.py +6 -2
- fastmcp/experimental/utilities/openapi/models.py +3 -3
- fastmcp/experimental/utilities/openapi/parser.py +37 -16
- fastmcp/experimental/utilities/openapi/schemas.py +33 -7
- fastmcp/mcp_config.py +3 -4
- fastmcp/prompts/__init__.py +1 -1
- fastmcp/prompts/prompt.py +32 -27
- fastmcp/prompts/prompt_manager.py +16 -101
- fastmcp/resources/__init__.py +5 -5
- fastmcp/resources/resource.py +28 -20
- fastmcp/resources/resource_manager.py +9 -168
- fastmcp/resources/template.py +119 -27
- fastmcp/resources/types.py +30 -24
- fastmcp/server/__init__.py +1 -1
- fastmcp/server/auth/__init__.py +9 -5
- fastmcp/server/auth/auth.py +80 -47
- fastmcp/server/auth/handlers/authorize.py +326 -0
- fastmcp/server/auth/jwt_issuer.py +236 -0
- fastmcp/server/auth/middleware.py +96 -0
- fastmcp/server/auth/oauth_proxy.py +1556 -265
- fastmcp/server/auth/oidc_proxy.py +412 -0
- fastmcp/server/auth/providers/auth0.py +193 -0
- fastmcp/server/auth/providers/aws.py +263 -0
- fastmcp/server/auth/providers/azure.py +314 -129
- fastmcp/server/auth/providers/bearer.py +1 -1
- fastmcp/server/auth/providers/debug.py +114 -0
- fastmcp/server/auth/providers/descope.py +229 -0
- fastmcp/server/auth/providers/discord.py +308 -0
- fastmcp/server/auth/providers/github.py +31 -6
- fastmcp/server/auth/providers/google.py +50 -7
- fastmcp/server/auth/providers/in_memory.py +27 -3
- fastmcp/server/auth/providers/introspection.py +281 -0
- fastmcp/server/auth/providers/jwt.py +48 -31
- fastmcp/server/auth/providers/oci.py +233 -0
- fastmcp/server/auth/providers/scalekit.py +238 -0
- fastmcp/server/auth/providers/supabase.py +188 -0
- fastmcp/server/auth/providers/workos.py +37 -15
- fastmcp/server/context.py +194 -67
- fastmcp/server/dependencies.py +56 -16
- fastmcp/server/elicitation.py +1 -1
- fastmcp/server/http.py +57 -18
- fastmcp/server/low_level.py +121 -2
- fastmcp/server/middleware/__init__.py +1 -1
- fastmcp/server/middleware/caching.py +476 -0
- fastmcp/server/middleware/error_handling.py +14 -10
- fastmcp/server/middleware/logging.py +158 -116
- fastmcp/server/middleware/middleware.py +30 -16
- fastmcp/server/middleware/rate_limiting.py +3 -3
- fastmcp/server/middleware/tool_injection.py +116 -0
- fastmcp/server/openapi.py +15 -7
- fastmcp/server/proxy.py +22 -11
- fastmcp/server/server.py +744 -254
- fastmcp/settings.py +65 -15
- fastmcp/tools/__init__.py +1 -1
- fastmcp/tools/tool.py +173 -108
- fastmcp/tools/tool_manager.py +30 -112
- fastmcp/tools/tool_transform.py +13 -11
- fastmcp/utilities/cli.py +67 -28
- fastmcp/utilities/components.py +7 -2
- fastmcp/utilities/inspect.py +79 -23
- fastmcp/utilities/json_schema.py +21 -4
- fastmcp/utilities/json_schema_type.py +4 -4
- fastmcp/utilities/logging.py +182 -10
- fastmcp/utilities/mcp_server_config/__init__.py +3 -3
- fastmcp/utilities/mcp_server_config/v1/environments/base.py +1 -2
- fastmcp/utilities/mcp_server_config/v1/environments/uv.py +10 -45
- fastmcp/utilities/mcp_server_config/v1/mcp_server_config.py +8 -7
- fastmcp/utilities/mcp_server_config/v1/schema.json +5 -1
- fastmcp/utilities/mcp_server_config/v1/sources/base.py +0 -1
- fastmcp/utilities/openapi.py +11 -11
- fastmcp/utilities/tests.py +93 -10
- fastmcp/utilities/types.py +87 -21
- fastmcp/utilities/ui.py +626 -0
- {fastmcp-2.12.1.dist-info → fastmcp-2.13.2.dist-info}/METADATA +141 -60
- fastmcp-2.13.2.dist-info/RECORD +144 -0
- {fastmcp-2.12.1.dist-info → fastmcp-2.13.2.dist-info}/WHEEL +1 -1
- fastmcp/cli/claude.py +0 -144
- fastmcp-2.12.1.dist-info/RECORD +0 -128
- {fastmcp-2.12.1.dist-info → fastmcp-2.13.2.dist-info}/entry_points.txt +0 -0
- {fastmcp-2.12.1.dist-info → fastmcp-2.13.2.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,476 @@
|
|
|
1
|
+
"""A middleware for response caching."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Sequence
|
|
4
|
+
from logging import Logger
|
|
5
|
+
from typing import Any, TypedDict
|
|
6
|
+
|
|
7
|
+
import mcp.types
|
|
8
|
+
import pydantic_core
|
|
9
|
+
from key_value.aio.adapters.pydantic import PydanticAdapter
|
|
10
|
+
from key_value.aio.protocols.key_value import AsyncKeyValue
|
|
11
|
+
from key_value.aio.stores.memory import MemoryStore
|
|
12
|
+
from key_value.aio.wrappers.limit_size import LimitSizeWrapper
|
|
13
|
+
from key_value.aio.wrappers.statistics import StatisticsWrapper
|
|
14
|
+
from key_value.aio.wrappers.statistics.wrapper import (
|
|
15
|
+
KVStoreCollectionStatistics,
|
|
16
|
+
)
|
|
17
|
+
from mcp.server.lowlevel.helper_types import ReadResourceContents
|
|
18
|
+
from pydantic import BaseModel, Field
|
|
19
|
+
from typing_extensions import NotRequired, Self, override
|
|
20
|
+
|
|
21
|
+
from fastmcp.prompts.prompt import Prompt
|
|
22
|
+
from fastmcp.resources.resource import Resource
|
|
23
|
+
from fastmcp.server.middleware.middleware import CallNext, Middleware, MiddlewareContext
|
|
24
|
+
from fastmcp.tools.tool import Tool, ToolResult
|
|
25
|
+
from fastmcp.utilities.logging import get_logger
|
|
26
|
+
|
|
27
|
+
logger: Logger = get_logger(name=__name__)
|
|
28
|
+
|
|
29
|
+
# Constants
|
|
30
|
+
ONE_HOUR_IN_SECONDS = 3600
|
|
31
|
+
FIVE_MINUTES_IN_SECONDS = 300
|
|
32
|
+
|
|
33
|
+
ONE_MB_IN_BYTES = 1024 * 1024
|
|
34
|
+
|
|
35
|
+
GLOBAL_KEY = "__global__"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class CachableReadResourceContents(BaseModel):
|
|
39
|
+
"""A wrapper for ReadResourceContents that can be cached."""
|
|
40
|
+
|
|
41
|
+
content: str | bytes
|
|
42
|
+
mime_type: str | None = None
|
|
43
|
+
|
|
44
|
+
def get_size(self) -> int:
|
|
45
|
+
return len(self.model_dump_json())
|
|
46
|
+
|
|
47
|
+
@classmethod
|
|
48
|
+
def get_sizes(cls, values: Sequence[Self]) -> int:
|
|
49
|
+
return sum(item.get_size() for item in values)
|
|
50
|
+
|
|
51
|
+
@classmethod
|
|
52
|
+
def wrap(cls, values: Sequence[ReadResourceContents]) -> list[Self]:
|
|
53
|
+
return [cls(content=item.content, mime_type=item.mime_type) for item in values]
|
|
54
|
+
|
|
55
|
+
@classmethod
|
|
56
|
+
def unwrap(cls, values: Sequence[Self]) -> list[ReadResourceContents]:
|
|
57
|
+
return [
|
|
58
|
+
ReadResourceContents(content=item.content, mime_type=item.mime_type)
|
|
59
|
+
for item in values
|
|
60
|
+
]
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class CachableToolResult(BaseModel):
|
|
64
|
+
content: list[mcp.types.ContentBlock]
|
|
65
|
+
structured_content: dict[str, Any] | None
|
|
66
|
+
meta: dict[str, Any] | None
|
|
67
|
+
|
|
68
|
+
@classmethod
|
|
69
|
+
def wrap(cls, value: ToolResult) -> Self:
|
|
70
|
+
return cls(
|
|
71
|
+
content=value.content,
|
|
72
|
+
structured_content=value.structured_content,
|
|
73
|
+
meta=value.meta,
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
def unwrap(self) -> ToolResult:
|
|
77
|
+
return ToolResult(
|
|
78
|
+
content=self.content,
|
|
79
|
+
structured_content=self.structured_content,
|
|
80
|
+
meta=self.meta,
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class SharedMethodSettings(TypedDict):
|
|
85
|
+
"""Shared config for a cache method."""
|
|
86
|
+
|
|
87
|
+
ttl: NotRequired[int]
|
|
88
|
+
enabled: NotRequired[bool]
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class ListToolsSettings(SharedMethodSettings):
|
|
92
|
+
"""Configuration options for Tool-related caching."""
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class ListResourcesSettings(SharedMethodSettings):
|
|
96
|
+
"""Configuration options for Resource-related caching."""
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class ListPromptsSettings(SharedMethodSettings):
|
|
100
|
+
"""Configuration options for Prompt-related caching."""
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class CallToolSettings(SharedMethodSettings):
|
|
104
|
+
"""Configuration options for Tool-related caching."""
|
|
105
|
+
|
|
106
|
+
included_tools: NotRequired[list[str]]
|
|
107
|
+
excluded_tools: NotRequired[list[str]]
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class ReadResourceSettings(SharedMethodSettings):
|
|
111
|
+
"""Configuration options for Resource-related caching."""
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class GetPromptSettings(SharedMethodSettings):
|
|
115
|
+
"""Configuration options for Prompt-related caching."""
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class ResponseCachingStatistics(BaseModel):
|
|
119
|
+
list_tools: KVStoreCollectionStatistics | None = Field(default=None)
|
|
120
|
+
list_resources: KVStoreCollectionStatistics | None = Field(default=None)
|
|
121
|
+
list_prompts: KVStoreCollectionStatistics | None = Field(default=None)
|
|
122
|
+
read_resource: KVStoreCollectionStatistics | None = Field(default=None)
|
|
123
|
+
get_prompt: KVStoreCollectionStatistics | None = Field(default=None)
|
|
124
|
+
call_tool: KVStoreCollectionStatistics | None = Field(default=None)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class ResponseCachingMiddleware(Middleware):
|
|
128
|
+
"""The response caching middleware offers a simple way to cache responses to mcp methods. The Middleware
|
|
129
|
+
supports cache invalidation via notifications from the server. The Middleware implements TTL-based caching
|
|
130
|
+
but cache implementations may offer additional features like LRU eviction, size limits, and more.
|
|
131
|
+
|
|
132
|
+
When items are retrieved from the cache they will no longer be the original objects, but rather no-op objects
|
|
133
|
+
this means that response caching may not be compatible with other middleware that expects original subclasses.
|
|
134
|
+
|
|
135
|
+
Notes:
|
|
136
|
+
- Caches `tools/call`, `resources/read`, `prompts/get`, `tools/list`, `resources/list`, and `prompts/list` requests.
|
|
137
|
+
- Cache keys are derived from method name and arguments.
|
|
138
|
+
"""
|
|
139
|
+
|
|
140
|
+
def __init__(
|
|
141
|
+
self,
|
|
142
|
+
cache_storage: AsyncKeyValue | None = None,
|
|
143
|
+
list_tools_settings: ListToolsSettings | None = None,
|
|
144
|
+
list_resources_settings: ListResourcesSettings | None = None,
|
|
145
|
+
list_prompts_settings: ListPromptsSettings | None = None,
|
|
146
|
+
read_resource_settings: ReadResourceSettings | None = None,
|
|
147
|
+
get_prompt_settings: GetPromptSettings | None = None,
|
|
148
|
+
call_tool_settings: CallToolSettings | None = None,
|
|
149
|
+
max_item_size: int = ONE_MB_IN_BYTES,
|
|
150
|
+
):
|
|
151
|
+
"""Initialize the response caching middleware.
|
|
152
|
+
|
|
153
|
+
Args:
|
|
154
|
+
cache_storage: The cache backend to use. If None, an in-memory cache is used.
|
|
155
|
+
list_tools_settings: The settings for the list tools method. If None, the default settings are used (5 minute TTL).
|
|
156
|
+
list_resources_settings: The settings for the list resources method. If None, the default settings are used (5 minute TTL).
|
|
157
|
+
list_prompts_settings: The settings for the list prompts method. If None, the default settings are used (5 minute TTL).
|
|
158
|
+
read_resource_settings: The settings for the read resource method. If None, the default settings are used (1 hour TTL).
|
|
159
|
+
get_prompt_settings: The settings for the get prompt method. If None, the default settings are used (1 hour TTL).
|
|
160
|
+
call_tool_settings: The settings for the call tool method. If None, the default settings are used (1 hour TTL).
|
|
161
|
+
max_item_size: The maximum size of items eligible for caching. Defaults to 1MB.
|
|
162
|
+
"""
|
|
163
|
+
|
|
164
|
+
self._backend: AsyncKeyValue = cache_storage or MemoryStore()
|
|
165
|
+
|
|
166
|
+
# When the size limit is exceeded, the put will silently fail
|
|
167
|
+
self._size_limiter: LimitSizeWrapper = LimitSizeWrapper(
|
|
168
|
+
key_value=self._backend, max_size=max_item_size, raise_on_too_large=False
|
|
169
|
+
)
|
|
170
|
+
self._stats: StatisticsWrapper = StatisticsWrapper(key_value=self._size_limiter)
|
|
171
|
+
|
|
172
|
+
self._list_tools_settings: ListToolsSettings = (
|
|
173
|
+
list_tools_settings or ListToolsSettings()
|
|
174
|
+
)
|
|
175
|
+
self._list_resources_settings: ListResourcesSettings = (
|
|
176
|
+
list_resources_settings or ListResourcesSettings()
|
|
177
|
+
)
|
|
178
|
+
self._list_prompts_settings: ListPromptsSettings = (
|
|
179
|
+
list_prompts_settings or ListPromptsSettings()
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
self._read_resource_settings: ReadResourceSettings = (
|
|
183
|
+
read_resource_settings or ReadResourceSettings()
|
|
184
|
+
)
|
|
185
|
+
self._get_prompt_settings: GetPromptSettings = (
|
|
186
|
+
get_prompt_settings or GetPromptSettings()
|
|
187
|
+
)
|
|
188
|
+
self._call_tool_settings: CallToolSettings = (
|
|
189
|
+
call_tool_settings or CallToolSettings()
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
self._list_tools_cache: PydanticAdapter[list[Tool]] = PydanticAdapter(
|
|
193
|
+
key_value=self._stats,
|
|
194
|
+
pydantic_model=list[Tool],
|
|
195
|
+
default_collection="tools/list",
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
self._list_resources_cache: PydanticAdapter[list[Resource]] = PydanticAdapter(
|
|
199
|
+
key_value=self._stats,
|
|
200
|
+
pydantic_model=list[Resource],
|
|
201
|
+
default_collection="resources/list",
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
self._list_prompts_cache: PydanticAdapter[list[Prompt]] = PydanticAdapter(
|
|
205
|
+
key_value=self._stats,
|
|
206
|
+
pydantic_model=list[Prompt],
|
|
207
|
+
default_collection="prompts/list",
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
self._read_resource_cache: PydanticAdapter[
|
|
211
|
+
list[CachableReadResourceContents]
|
|
212
|
+
] = PydanticAdapter(
|
|
213
|
+
key_value=self._stats,
|
|
214
|
+
pydantic_model=list[CachableReadResourceContents],
|
|
215
|
+
default_collection="resources/read",
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
self._get_prompt_cache: PydanticAdapter[mcp.types.GetPromptResult] = (
|
|
219
|
+
PydanticAdapter(
|
|
220
|
+
key_value=self._stats,
|
|
221
|
+
pydantic_model=mcp.types.GetPromptResult,
|
|
222
|
+
default_collection="prompts/get",
|
|
223
|
+
)
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
self._call_tool_cache: PydanticAdapter[CachableToolResult] = PydanticAdapter(
|
|
227
|
+
key_value=self._stats,
|
|
228
|
+
pydantic_model=CachableToolResult,
|
|
229
|
+
default_collection="tools/call",
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
@override
|
|
233
|
+
async def on_list_tools(
|
|
234
|
+
self,
|
|
235
|
+
context: MiddlewareContext[mcp.types.ListToolsRequest],
|
|
236
|
+
call_next: CallNext[mcp.types.ListToolsRequest, Sequence[Tool]],
|
|
237
|
+
) -> Sequence[Tool]:
|
|
238
|
+
"""List tools from the cache, if caching is enabled, and the result is in the cache. Otherwise,
|
|
239
|
+
otherwise call the next middleware and store the result in the cache if caching is enabled."""
|
|
240
|
+
if self._list_tools_settings.get("enabled") is False:
|
|
241
|
+
return await call_next(context)
|
|
242
|
+
|
|
243
|
+
if cached_value := await self._list_tools_cache.get(key=GLOBAL_KEY):
|
|
244
|
+
return cached_value
|
|
245
|
+
|
|
246
|
+
tools: Sequence[Tool] = await call_next(context=context)
|
|
247
|
+
|
|
248
|
+
# Turn any subclass of Tool into a Tool
|
|
249
|
+
cachable_tools: list[Tool] = [
|
|
250
|
+
Tool(
|
|
251
|
+
name=tool.name,
|
|
252
|
+
title=tool.title,
|
|
253
|
+
description=tool.description,
|
|
254
|
+
parameters=tool.parameters,
|
|
255
|
+
output_schema=tool.output_schema,
|
|
256
|
+
annotations=tool.annotations,
|
|
257
|
+
meta=tool.meta,
|
|
258
|
+
tags=tool.tags,
|
|
259
|
+
enabled=tool.enabled,
|
|
260
|
+
)
|
|
261
|
+
for tool in tools
|
|
262
|
+
]
|
|
263
|
+
|
|
264
|
+
await self._list_tools_cache.put(
|
|
265
|
+
key=GLOBAL_KEY,
|
|
266
|
+
value=cachable_tools,
|
|
267
|
+
ttl=self._list_tools_settings.get("ttl", FIVE_MINUTES_IN_SECONDS),
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
return cachable_tools
|
|
271
|
+
|
|
272
|
+
@override
|
|
273
|
+
async def on_list_resources(
|
|
274
|
+
self,
|
|
275
|
+
context: MiddlewareContext[mcp.types.ListResourcesRequest],
|
|
276
|
+
call_next: CallNext[mcp.types.ListResourcesRequest, Sequence[Resource]],
|
|
277
|
+
) -> Sequence[Resource]:
|
|
278
|
+
"""List resources from the cache, if caching is enabled, and the result is in the cache. Otherwise,
|
|
279
|
+
otherwise call the next middleware and store the result in the cache if caching is enabled."""
|
|
280
|
+
if self._list_resources_settings.get("enabled") is False:
|
|
281
|
+
return await call_next(context)
|
|
282
|
+
|
|
283
|
+
if cached_value := await self._list_resources_cache.get(key=GLOBAL_KEY):
|
|
284
|
+
return cached_value
|
|
285
|
+
|
|
286
|
+
resources: Sequence[Resource] = await call_next(context=context)
|
|
287
|
+
|
|
288
|
+
# Turn any subclass of Resource into a Resource
|
|
289
|
+
cachable_resources: list[Resource] = [
|
|
290
|
+
Resource(
|
|
291
|
+
name=resource.name,
|
|
292
|
+
title=resource.title,
|
|
293
|
+
description=resource.description,
|
|
294
|
+
tags=resource.tags,
|
|
295
|
+
meta=resource.meta,
|
|
296
|
+
mime_type=resource.mime_type,
|
|
297
|
+
annotations=resource.annotations,
|
|
298
|
+
enabled=resource.enabled,
|
|
299
|
+
uri=resource.uri,
|
|
300
|
+
)
|
|
301
|
+
for resource in resources
|
|
302
|
+
]
|
|
303
|
+
|
|
304
|
+
await self._list_resources_cache.put(
|
|
305
|
+
key=GLOBAL_KEY,
|
|
306
|
+
value=cachable_resources,
|
|
307
|
+
ttl=self._list_resources_settings.get("ttl", FIVE_MINUTES_IN_SECONDS),
|
|
308
|
+
)
|
|
309
|
+
|
|
310
|
+
return cachable_resources
|
|
311
|
+
|
|
312
|
+
@override
|
|
313
|
+
async def on_list_prompts(
|
|
314
|
+
self,
|
|
315
|
+
context: MiddlewareContext[mcp.types.ListPromptsRequest],
|
|
316
|
+
call_next: CallNext[mcp.types.ListPromptsRequest, Sequence[Prompt]],
|
|
317
|
+
) -> Sequence[Prompt]:
|
|
318
|
+
"""List prompts from the cache, if caching is enabled, and the result is in the cache. Otherwise,
|
|
319
|
+
otherwise call the next middleware and store the result in the cache if caching is enabled."""
|
|
320
|
+
if self._list_prompts_settings.get("enabled") is False:
|
|
321
|
+
return await call_next(context)
|
|
322
|
+
|
|
323
|
+
if cached_value := await self._list_prompts_cache.get(key=GLOBAL_KEY):
|
|
324
|
+
return cached_value
|
|
325
|
+
|
|
326
|
+
prompts: Sequence[Prompt] = await call_next(context=context)
|
|
327
|
+
|
|
328
|
+
# Turn any subclass of Prompt into a Prompt
|
|
329
|
+
cachable_prompts: list[Prompt] = [
|
|
330
|
+
Prompt(
|
|
331
|
+
name=prompt.name,
|
|
332
|
+
title=prompt.title,
|
|
333
|
+
description=prompt.description,
|
|
334
|
+
tags=prompt.tags,
|
|
335
|
+
meta=prompt.meta,
|
|
336
|
+
enabled=prompt.enabled,
|
|
337
|
+
arguments=prompt.arguments,
|
|
338
|
+
)
|
|
339
|
+
for prompt in prompts
|
|
340
|
+
]
|
|
341
|
+
|
|
342
|
+
await self._list_prompts_cache.put(
|
|
343
|
+
key=GLOBAL_KEY,
|
|
344
|
+
value=cachable_prompts,
|
|
345
|
+
ttl=self._list_prompts_settings.get("ttl", FIVE_MINUTES_IN_SECONDS),
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
return cachable_prompts
|
|
349
|
+
|
|
350
|
+
@override
|
|
351
|
+
async def on_call_tool(
|
|
352
|
+
self,
|
|
353
|
+
context: MiddlewareContext[mcp.types.CallToolRequestParams],
|
|
354
|
+
call_next: CallNext[mcp.types.CallToolRequestParams, ToolResult],
|
|
355
|
+
) -> ToolResult:
|
|
356
|
+
"""Call a tool from the cache, if caching is enabled, and the result is in the cache. Otherwise,
|
|
357
|
+
otherwise call the next middleware and store the result in the cache if caching is enabled."""
|
|
358
|
+
tool_name = context.message.name
|
|
359
|
+
|
|
360
|
+
if self._call_tool_settings.get(
|
|
361
|
+
"enabled"
|
|
362
|
+
) is False or not self._matches_tool_cache_settings(tool_name=tool_name):
|
|
363
|
+
return await call_next(context=context)
|
|
364
|
+
|
|
365
|
+
cache_key: str = f"{tool_name}:{_get_arguments_str(context.message.arguments)}"
|
|
366
|
+
|
|
367
|
+
if cached_value := await self._call_tool_cache.get(key=cache_key):
|
|
368
|
+
return cached_value.unwrap()
|
|
369
|
+
|
|
370
|
+
tool_result: ToolResult = await call_next(context=context)
|
|
371
|
+
cachable_tool_result: CachableToolResult = CachableToolResult.wrap(
|
|
372
|
+
value=tool_result
|
|
373
|
+
)
|
|
374
|
+
|
|
375
|
+
await self._call_tool_cache.put(
|
|
376
|
+
key=cache_key,
|
|
377
|
+
value=cachable_tool_result,
|
|
378
|
+
ttl=self._call_tool_settings.get("ttl", ONE_HOUR_IN_SECONDS),
|
|
379
|
+
)
|
|
380
|
+
|
|
381
|
+
return cachable_tool_result.unwrap()
|
|
382
|
+
|
|
383
|
+
@override
|
|
384
|
+
async def on_read_resource(
|
|
385
|
+
self,
|
|
386
|
+
context: MiddlewareContext[mcp.types.ReadResourceRequestParams],
|
|
387
|
+
call_next: CallNext[
|
|
388
|
+
mcp.types.ReadResourceRequestParams, Sequence[ReadResourceContents]
|
|
389
|
+
],
|
|
390
|
+
) -> Sequence[ReadResourceContents]:
|
|
391
|
+
"""Read a resource from the cache, if caching is enabled, and the result is in the cache. Otherwise,
|
|
392
|
+
otherwise call the next middleware and store the result in the cache if caching is enabled."""
|
|
393
|
+
if self._read_resource_settings.get("enabled") is False:
|
|
394
|
+
return await call_next(context=context)
|
|
395
|
+
|
|
396
|
+
cache_key: str = str(context.message.uri)
|
|
397
|
+
cached_value: list[CachableReadResourceContents] | None
|
|
398
|
+
|
|
399
|
+
if cached_value := await self._read_resource_cache.get(key=cache_key):
|
|
400
|
+
return CachableReadResourceContents.unwrap(values=cached_value)
|
|
401
|
+
|
|
402
|
+
value: Sequence[ReadResourceContents] = await call_next(context=context)
|
|
403
|
+
cached_value = CachableReadResourceContents.wrap(values=value)
|
|
404
|
+
|
|
405
|
+
await self._read_resource_cache.put(
|
|
406
|
+
key=cache_key,
|
|
407
|
+
value=cached_value,
|
|
408
|
+
ttl=self._read_resource_settings.get("ttl", ONE_HOUR_IN_SECONDS),
|
|
409
|
+
)
|
|
410
|
+
|
|
411
|
+
return CachableReadResourceContents.unwrap(values=cached_value)
|
|
412
|
+
|
|
413
|
+
@override
|
|
414
|
+
async def on_get_prompt(
|
|
415
|
+
self,
|
|
416
|
+
context: MiddlewareContext[mcp.types.GetPromptRequestParams],
|
|
417
|
+
call_next: CallNext[
|
|
418
|
+
mcp.types.GetPromptRequestParams, mcp.types.GetPromptResult
|
|
419
|
+
],
|
|
420
|
+
) -> mcp.types.GetPromptResult:
|
|
421
|
+
"""Get a prompt from the cache, if caching is enabled, and the result is in the cache. Otherwise,
|
|
422
|
+
otherwise call the next middleware and store the result in the cache if caching is enabled."""
|
|
423
|
+
if self._get_prompt_settings.get("enabled") is False:
|
|
424
|
+
return await call_next(context=context)
|
|
425
|
+
|
|
426
|
+
cache_key: str = f"{context.message.name}:{_get_arguments_str(arguments=context.message.arguments)}"
|
|
427
|
+
|
|
428
|
+
if cached_value := await self._get_prompt_cache.get(key=cache_key):
|
|
429
|
+
return cached_value
|
|
430
|
+
|
|
431
|
+
value: mcp.types.GetPromptResult = await call_next(context=context)
|
|
432
|
+
|
|
433
|
+
await self._get_prompt_cache.put(
|
|
434
|
+
key=cache_key,
|
|
435
|
+
value=value,
|
|
436
|
+
ttl=self._get_prompt_settings.get("ttl", ONE_HOUR_IN_SECONDS),
|
|
437
|
+
)
|
|
438
|
+
|
|
439
|
+
return value
|
|
440
|
+
|
|
441
|
+
def _matches_tool_cache_settings(self, tool_name: str) -> bool:
|
|
442
|
+
"""Check if the tool matches the cache settings for tool calls."""
|
|
443
|
+
|
|
444
|
+
if included_tools := self._call_tool_settings.get("included_tools"):
|
|
445
|
+
if tool_name not in included_tools:
|
|
446
|
+
return False
|
|
447
|
+
|
|
448
|
+
if excluded_tools := self._call_tool_settings.get("excluded_tools"):
|
|
449
|
+
if tool_name in excluded_tools:
|
|
450
|
+
return False
|
|
451
|
+
|
|
452
|
+
return True
|
|
453
|
+
|
|
454
|
+
def statistics(self) -> ResponseCachingStatistics:
|
|
455
|
+
"""Get the statistics for the cache."""
|
|
456
|
+
return ResponseCachingStatistics(
|
|
457
|
+
list_tools=self._stats.statistics.collections.get("tools/list"),
|
|
458
|
+
list_resources=self._stats.statistics.collections.get("resources/list"),
|
|
459
|
+
list_prompts=self._stats.statistics.collections.get("prompts/list"),
|
|
460
|
+
read_resource=self._stats.statistics.collections.get("resources/read"),
|
|
461
|
+
get_prompt=self._stats.statistics.collections.get("prompts/get"),
|
|
462
|
+
call_tool=self._stats.statistics.collections.get("tools/call"),
|
|
463
|
+
)
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
def _get_arguments_str(arguments: dict[str, Any] | None) -> str:
|
|
467
|
+
"""Get a string representation of the arguments."""
|
|
468
|
+
|
|
469
|
+
if arguments is None:
|
|
470
|
+
return "null"
|
|
471
|
+
|
|
472
|
+
try:
|
|
473
|
+
return pydantic_core.to_json(value=arguments, fallback=str).decode()
|
|
474
|
+
|
|
475
|
+
except TypeError:
|
|
476
|
+
return repr(arguments)
|
|
@@ -6,9 +6,12 @@ import traceback
|
|
|
6
6
|
from collections.abc import Callable
|
|
7
7
|
from typing import Any
|
|
8
8
|
|
|
9
|
+
import anyio
|
|
9
10
|
from mcp import McpError
|
|
10
11
|
from mcp.types import ErrorData
|
|
11
12
|
|
|
13
|
+
from fastmcp.exceptions import NotFoundError
|
|
14
|
+
|
|
12
15
|
from .middleware import CallNext, Middleware, MiddlewareContext
|
|
13
16
|
|
|
14
17
|
|
|
@@ -61,7 +64,7 @@ class ErrorHandlingMiddleware(Middleware):
|
|
|
61
64
|
error_key = f"{error_type}:{method}"
|
|
62
65
|
self.error_counts[error_key] = self.error_counts.get(error_key, 0) + 1
|
|
63
66
|
|
|
64
|
-
base_message = f"Error in {method}: {error_type}: {
|
|
67
|
+
base_message = f"Error in {method}: {error_type}: {error!s}"
|
|
65
68
|
|
|
66
69
|
if self.include_traceback:
|
|
67
70
|
self.logger.error(f"{base_message}\n{traceback.format_exc()}")
|
|
@@ -88,23 +91,24 @@ class ErrorHandlingMiddleware(Middleware):
|
|
|
88
91
|
|
|
89
92
|
if error_type in (ValueError, TypeError):
|
|
90
93
|
return McpError(
|
|
91
|
-
ErrorData(code=-32602, message=f"Invalid params: {
|
|
94
|
+
ErrorData(code=-32602, message=f"Invalid params: {error!s}")
|
|
92
95
|
)
|
|
93
|
-
elif error_type in (FileNotFoundError, KeyError):
|
|
96
|
+
elif error_type in (FileNotFoundError, KeyError, NotFoundError):
|
|
94
97
|
return McpError(
|
|
95
|
-
ErrorData(code=-32001, message=f"Resource not found: {
|
|
98
|
+
ErrorData(code=-32001, message=f"Resource not found: {error!s}")
|
|
96
99
|
)
|
|
97
100
|
elif error_type is PermissionError:
|
|
98
101
|
return McpError(
|
|
99
|
-
ErrorData(code=-32000, message=f"Permission denied: {
|
|
102
|
+
ErrorData(code=-32000, message=f"Permission denied: {error!s}")
|
|
100
103
|
)
|
|
104
|
+
# asyncio.TimeoutError is a subclass of TimeoutError in Python 3.10, alias in 3.11+
|
|
101
105
|
elif error_type in (TimeoutError, asyncio.TimeoutError):
|
|
102
106
|
return McpError(
|
|
103
|
-
ErrorData(code=-32000, message=f"Request timeout: {
|
|
107
|
+
ErrorData(code=-32000, message=f"Request timeout: {error!s}")
|
|
104
108
|
)
|
|
105
109
|
else:
|
|
106
110
|
return McpError(
|
|
107
|
-
ErrorData(code=-32603, message=f"Internal error: {
|
|
111
|
+
ErrorData(code=-32603, message=f"Internal error: {error!s}")
|
|
108
112
|
)
|
|
109
113
|
|
|
110
114
|
async def on_message(self, context: MiddlewareContext, call_next: CallNext) -> Any:
|
|
@@ -116,7 +120,7 @@ class ErrorHandlingMiddleware(Middleware):
|
|
|
116
120
|
|
|
117
121
|
# Transform and re-raise
|
|
118
122
|
transformed_error = self._transform_error(error)
|
|
119
|
-
raise transformed_error
|
|
123
|
+
raise transformed_error from error
|
|
120
124
|
|
|
121
125
|
def get_error_stats(self) -> dict[str, int]:
|
|
122
126
|
"""Get error statistics for monitoring."""
|
|
@@ -196,10 +200,10 @@ class RetryMiddleware(Middleware):
|
|
|
196
200
|
delay = self._calculate_delay(attempt)
|
|
197
201
|
self.logger.warning(
|
|
198
202
|
f"Request {context.method} failed (attempt {attempt + 1}/{self.max_retries + 1}): "
|
|
199
|
-
f"{type(error).__name__}: {
|
|
203
|
+
f"{type(error).__name__}: {error!s}. Retrying in {delay:.1f}s..."
|
|
200
204
|
)
|
|
201
205
|
|
|
202
|
-
await
|
|
206
|
+
await anyio.sleep(delay)
|
|
203
207
|
|
|
204
208
|
# Re-raise the last error if all retries failed
|
|
205
209
|
if last_error:
|