fastmcp 2.13.2__py3-none-any.whl → 2.14.0__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.
Files changed (74) hide show
  1. fastmcp/__init__.py +0 -21
  2. fastmcp/cli/__init__.py +0 -3
  3. fastmcp/cli/__main__.py +5 -0
  4. fastmcp/cli/cli.py +8 -22
  5. fastmcp/cli/install/shared.py +0 -15
  6. fastmcp/cli/tasks.py +110 -0
  7. fastmcp/client/auth/oauth.py +9 -9
  8. fastmcp/client/client.py +665 -129
  9. fastmcp/client/elicitation.py +11 -5
  10. fastmcp/client/messages.py +7 -5
  11. fastmcp/client/roots.py +2 -1
  12. fastmcp/client/tasks.py +614 -0
  13. fastmcp/client/transports.py +37 -5
  14. fastmcp/contrib/component_manager/component_service.py +4 -20
  15. fastmcp/dependencies.py +25 -0
  16. fastmcp/experimental/sampling/handlers/openai.py +1 -1
  17. fastmcp/experimental/server/openapi/__init__.py +15 -13
  18. fastmcp/experimental/utilities/openapi/__init__.py +12 -38
  19. fastmcp/prompts/prompt.py +33 -33
  20. fastmcp/resources/resource.py +29 -12
  21. fastmcp/resources/template.py +64 -54
  22. fastmcp/server/auth/__init__.py +0 -9
  23. fastmcp/server/auth/auth.py +127 -3
  24. fastmcp/server/auth/oauth_proxy.py +47 -97
  25. fastmcp/server/auth/oidc_proxy.py +7 -0
  26. fastmcp/server/auth/providers/in_memory.py +2 -2
  27. fastmcp/server/auth/providers/oci.py +2 -2
  28. fastmcp/server/context.py +66 -72
  29. fastmcp/server/dependencies.py +464 -6
  30. fastmcp/server/elicitation.py +285 -47
  31. fastmcp/server/event_store.py +177 -0
  32. fastmcp/server/http.py +15 -3
  33. fastmcp/server/low_level.py +56 -12
  34. fastmcp/server/middleware/middleware.py +2 -2
  35. fastmcp/server/openapi/__init__.py +35 -0
  36. fastmcp/{experimental/server → server}/openapi/components.py +4 -3
  37. fastmcp/{experimental/server → server}/openapi/routing.py +1 -1
  38. fastmcp/{experimental/server → server}/openapi/server.py +6 -5
  39. fastmcp/server/proxy.py +50 -37
  40. fastmcp/server/server.py +731 -532
  41. fastmcp/server/tasks/__init__.py +21 -0
  42. fastmcp/server/tasks/capabilities.py +22 -0
  43. fastmcp/server/tasks/config.py +89 -0
  44. fastmcp/server/tasks/converters.py +205 -0
  45. fastmcp/server/tasks/handlers.py +356 -0
  46. fastmcp/server/tasks/keys.py +93 -0
  47. fastmcp/server/tasks/protocol.py +355 -0
  48. fastmcp/server/tasks/subscriptions.py +205 -0
  49. fastmcp/settings.py +101 -103
  50. fastmcp/tools/tool.py +80 -44
  51. fastmcp/tools/tool_transform.py +1 -12
  52. fastmcp/utilities/components.py +3 -3
  53. fastmcp/utilities/json_schema_type.py +4 -4
  54. fastmcp/utilities/mcp_config.py +1 -2
  55. fastmcp/utilities/mcp_server_config/v1/mcp_server_config.py +1 -1
  56. fastmcp/{experimental/utilities → utilities}/openapi/README.md +7 -35
  57. fastmcp/utilities/openapi/__init__.py +63 -0
  58. fastmcp/{experimental/utilities → utilities}/openapi/formatters.py +5 -5
  59. fastmcp/{experimental/utilities → utilities}/openapi/json_schema_converter.py +1 -1
  60. fastmcp/utilities/tests.py +11 -5
  61. fastmcp/utilities/types.py +8 -0
  62. {fastmcp-2.13.2.dist-info → fastmcp-2.14.0.dist-info}/METADATA +5 -4
  63. {fastmcp-2.13.2.dist-info → fastmcp-2.14.0.dist-info}/RECORD +71 -59
  64. fastmcp/server/auth/providers/bearer.py +0 -25
  65. fastmcp/server/openapi.py +0 -1087
  66. fastmcp/utilities/openapi.py +0 -1568
  67. /fastmcp/{experimental/server → server}/openapi/README.md +0 -0
  68. /fastmcp/{experimental/utilities → utilities}/openapi/director.py +0 -0
  69. /fastmcp/{experimental/utilities → utilities}/openapi/models.py +0 -0
  70. /fastmcp/{experimental/utilities → utilities}/openapi/parser.py +0 -0
  71. /fastmcp/{experimental/utilities → utilities}/openapi/schemas.py +0 -0
  72. {fastmcp-2.13.2.dist-info → fastmcp-2.14.0.dist-info}/WHEEL +0 -0
  73. {fastmcp-2.13.2.dist-info → fastmcp-2.14.0.dist-info}/entry_points.txt +0 -0
  74. {fastmcp-2.13.2.dist-info → fastmcp-2.14.0.dist-info}/licenses/LICENSE +0 -0
fastmcp/server/openapi.py DELETED
@@ -1,1087 +0,0 @@
1
- """FastMCP server implementation for OpenAPI integration."""
2
-
3
- from __future__ import annotations
4
-
5
- import enum
6
- import json
7
- import re
8
- import warnings
9
- from collections import Counter
10
- from collections.abc import Callable
11
- from dataclasses import dataclass, field
12
- from re import Pattern
13
- from typing import TYPE_CHECKING, Any, Literal
14
-
15
- import httpx
16
- from mcp.types import ToolAnnotations
17
- from pydantic.networks import AnyUrl
18
-
19
- import fastmcp
20
- from fastmcp.exceptions import ToolError
21
- from fastmcp.resources import Resource, ResourceTemplate
22
- from fastmcp.server.dependencies import get_http_headers
23
- from fastmcp.server.server import FastMCP
24
- from fastmcp.tools.tool import Tool, ToolResult
25
- from fastmcp.utilities import openapi
26
- from fastmcp.utilities.logging import get_logger
27
- from fastmcp.utilities.openapi import (
28
- HTTPRoute,
29
- _combine_schemas,
30
- extract_output_schema_from_responses,
31
- format_array_parameter,
32
- format_deep_object_parameter,
33
- format_description_with_responses,
34
- )
35
-
36
- if TYPE_CHECKING:
37
- from fastmcp.server import Context
38
-
39
- logger = get_logger(__name__)
40
-
41
- HttpMethod = Literal["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"]
42
-
43
-
44
- def _slugify(text: str) -> str:
45
- """
46
- Convert text to a URL-friendly slug format that only contains lowercase
47
- letters, uppercase letters, numbers, and underscores.
48
- """
49
- if not text:
50
- return ""
51
-
52
- # Replace spaces and common separators with underscores
53
- slug = re.sub(r"[\s\-\.]+", "_", text)
54
-
55
- # Remove non-alphanumeric characters except underscores
56
- slug = re.sub(r"[^a-zA-Z0-9_]", "", slug)
57
-
58
- # Remove multiple consecutive underscores
59
- slug = re.sub(r"_+", "_", slug)
60
-
61
- # Remove leading/trailing underscores
62
- slug = slug.strip("_")
63
-
64
- return slug
65
-
66
-
67
- # Type definitions for the mapping functions
68
- RouteMapFn = Callable[[HTTPRoute, "MCPType"], "MCPType | None"]
69
- ComponentFn = Callable[
70
- [
71
- HTTPRoute,
72
- "OpenAPITool | OpenAPIResource | OpenAPIResourceTemplate",
73
- ],
74
- None,
75
- ]
76
-
77
-
78
- class MCPType(enum.Enum):
79
- """Type of FastMCP component to create from a route.
80
-
81
- Enum values:
82
- TOOL: Convert the route to a callable Tool
83
- RESOURCE: Convert the route to a Resource (typically GET endpoints)
84
- RESOURCE_TEMPLATE: Convert the route to a ResourceTemplate (typically GET with path params)
85
- EXCLUDE: Exclude the route from being converted to any MCP component
86
- IGNORE: Deprecated, use EXCLUDE instead
87
- """
88
-
89
- TOOL = "TOOL"
90
- RESOURCE = "RESOURCE"
91
- RESOURCE_TEMPLATE = "RESOURCE_TEMPLATE"
92
- # PROMPT = "PROMPT"
93
- EXCLUDE = "EXCLUDE"
94
-
95
-
96
- # Keep RouteType as an alias to MCPType for backward compatibility
97
- class RouteType(enum.Enum):
98
- """
99
- Deprecated: Use MCPType instead.
100
-
101
- This enum is kept for backward compatibility and will be removed in a future version.
102
- """
103
-
104
- TOOL = "TOOL"
105
- RESOURCE = "RESOURCE"
106
- RESOURCE_TEMPLATE = "RESOURCE_TEMPLATE"
107
- IGNORE = "IGNORE"
108
-
109
-
110
- @dataclass(kw_only=True)
111
- class RouteMap:
112
- """Mapping configuration for HTTP routes to FastMCP component types."""
113
-
114
- methods: list[HttpMethod] | Literal["*"] = field(default="*")
115
- pattern: Pattern[str] | str = field(default=r".*")
116
- route_type: RouteType | MCPType | None = field(default=None)
117
- tags: set[str] = field(
118
- default_factory=set,
119
- metadata={"description": "A set of tags to match. All tags must match."},
120
- )
121
- mcp_type: MCPType | None = field(
122
- default=None,
123
- metadata={"description": "The type of FastMCP component to create."},
124
- )
125
- mcp_tags: set[str] = field(
126
- default_factory=set,
127
- metadata={
128
- "description": "A set of tags to apply to the generated FastMCP component."
129
- },
130
- )
131
-
132
- def __post_init__(self):
133
- """Validate and process the route map after initialization."""
134
- # Handle backward compatibility for route_type, deprecated in 2.5.0
135
- if self.mcp_type is None and self.route_type is not None:
136
- if fastmcp.settings.deprecation_warnings:
137
- warnings.warn(
138
- "The 'route_type' parameter is deprecated and will be removed in a future version. "
139
- "Use 'mcp_type' instead with the appropriate MCPType value.",
140
- DeprecationWarning,
141
- stacklevel=2,
142
- )
143
- if isinstance(self.route_type, RouteType):
144
- if fastmcp.settings.deprecation_warnings:
145
- warnings.warn(
146
- "The RouteType class is deprecated and will be removed in a future version. "
147
- "Use MCPType instead.",
148
- DeprecationWarning,
149
- stacklevel=2,
150
- )
151
- # Check for the deprecated IGNORE value
152
- if self.route_type == RouteType.IGNORE:
153
- if fastmcp.settings.deprecation_warnings:
154
- warnings.warn(
155
- "RouteType.IGNORE is deprecated and will be removed in a future version. "
156
- "Use MCPType.EXCLUDE instead.",
157
- DeprecationWarning,
158
- stacklevel=2,
159
- )
160
-
161
- # Convert from RouteType to MCPType if needed
162
- if isinstance(self.route_type, RouteType):
163
- route_type_name = self.route_type.name
164
- if route_type_name == "IGNORE":
165
- route_type_name = "EXCLUDE"
166
- self.mcp_type = getattr(MCPType, route_type_name)
167
- else:
168
- self.mcp_type = self.route_type
169
- elif self.mcp_type is None:
170
- raise ValueError("`mcp_type` must be provided")
171
-
172
- # Set route_type to match mcp_type for backward compatibility
173
- if self.route_type is None:
174
- self.route_type = self.mcp_type
175
-
176
-
177
- # Default route mapping: all routes become tools.
178
- # Users can provide custom route_maps to override this behavior.
179
- DEFAULT_ROUTE_MAPPINGS = [
180
- RouteMap(mcp_type=MCPType.TOOL),
181
- ]
182
-
183
-
184
- def _determine_route_type(
185
- route: openapi.HTTPRoute,
186
- mappings: list[RouteMap],
187
- ) -> RouteMap:
188
- """
189
- Determines the FastMCP component type based on the route and mappings.
190
-
191
- Args:
192
- route: HTTPRoute object
193
- mappings: List of RouteMap objects in priority order
194
-
195
- Returns:
196
- The RouteMap that matches the route, or a catchall "Tool" RouteMap if no match is found.
197
- """
198
- # Check mappings in priority order (first match wins)
199
- for route_map in mappings:
200
- # Check if the HTTP method matches
201
- if route_map.methods == "*" or route.method in route_map.methods:
202
- # Handle both string patterns and compiled Pattern objects
203
- if isinstance(route_map.pattern, Pattern):
204
- pattern_matches = route_map.pattern.search(route.path)
205
- else:
206
- pattern_matches = re.search(route_map.pattern, route.path)
207
-
208
- if pattern_matches:
209
- # Check if tags match (if specified)
210
- # If route_map.tags is empty, tags are not matched
211
- # If route_map.tags is non-empty, all tags must be present in route.tags (AND condition)
212
- if route_map.tags:
213
- route_tags_set = set(route.tags or [])
214
- if not route_map.tags.issubset(route_tags_set):
215
- # Tags don't match, continue to next mapping
216
- continue
217
-
218
- # We know mcp_type is not None here due to post_init validation
219
- assert route_map.mcp_type is not None
220
- logger.debug(
221
- f"Route {route.method} {route.path} matched mapping to {route_map.mcp_type.name}"
222
- )
223
- return route_map
224
-
225
- # Default fallback
226
- return RouteMap(mcp_type=MCPType.TOOL)
227
-
228
-
229
- class OpenAPITool(Tool):
230
- """Tool implementation for OpenAPI endpoints."""
231
-
232
- def __init__(
233
- self,
234
- client: httpx.AsyncClient,
235
- route: openapi.HTTPRoute,
236
- name: str,
237
- description: str,
238
- parameters: dict[str, Any],
239
- output_schema: dict[str, Any] | None = None,
240
- tags: set[str] | None = None,
241
- timeout: float | None = None,
242
- annotations: ToolAnnotations | None = None,
243
- serializer: Callable[[Any], str] | None = None,
244
- ):
245
- super().__init__(
246
- name=name,
247
- description=description,
248
- parameters=parameters,
249
- output_schema=output_schema,
250
- tags=tags or set(),
251
- annotations=annotations,
252
- serializer=serializer,
253
- )
254
- self._client = client
255
- self._route = route
256
- self._timeout = timeout
257
-
258
- def __repr__(self) -> str:
259
- """Custom representation to prevent recursion errors when printing."""
260
- return f"OpenAPITool(name={self.name!r}, method={self._route.method}, path={self._route.path})"
261
-
262
- async def run(self, arguments: dict[str, Any]) -> ToolResult:
263
- """Execute the HTTP request based on the route configuration."""
264
-
265
- # Create mapping from suffixed parameter names back to original names and locations
266
- # This handles parameter collisions where suffixes were added during schema generation
267
- param_mapping = {} # suffixed_name -> (original_name, location)
268
-
269
- # First, check if we have request body properties to detect collisions
270
- body_props = set()
271
- if self._route.request_body and self._route.request_body.content_schema:
272
- content_type = next(iter(self._route.request_body.content_schema))
273
- body_schema = self._route.request_body.content_schema[content_type]
274
- body_props = set(body_schema.get("properties", {}).keys())
275
-
276
- # Build parameter mapping for potentially suffixed parameters
277
- for param in self._route.parameters:
278
- original_name = param.name
279
- suffixed_name = f"{param.name}__{param.location}"
280
-
281
- # If parameter name collides with body property, it would have been suffixed
282
- if param.name in body_props:
283
- param_mapping[suffixed_name] = (original_name, param.location)
284
- # Also map original name for backward compatibility when no collision
285
- param_mapping[original_name] = (original_name, param.location)
286
-
287
- # Prepare URL
288
- path = self._route.path
289
-
290
- # Replace path parameters with values from arguments
291
- # Look for both original and suffixed parameter names
292
- path_params = {}
293
- for p in self._route.parameters:
294
- if p.location == "path":
295
- # Try suffixed name first, then original name
296
- suffixed_name = f"{p.name}__{p.location}"
297
- if (
298
- suffixed_name in arguments
299
- and arguments.get(suffixed_name) is not None
300
- ):
301
- path_params[p.name] = arguments[suffixed_name]
302
- elif p.name in arguments and arguments.get(p.name) is not None:
303
- path_params[p.name] = arguments[p.name]
304
-
305
- # Ensure all path parameters are provided
306
- required_path_params = {
307
- p.name
308
- for p in self._route.parameters
309
- if p.location == "path" and p.required
310
- }
311
- missing_params = required_path_params - path_params.keys()
312
- if missing_params:
313
- raise ToolError(f"Missing required path parameters: {missing_params}")
314
-
315
- for param_name, param_value in path_params.items():
316
- # Handle array path parameters with style 'simple' (comma-separated)
317
- # In OpenAPI, 'simple' is the default style for path parameters
318
- param_info = next(
319
- (p for p in self._route.parameters if p.name == param_name), None
320
- )
321
-
322
- if param_info and isinstance(param_value, list):
323
- # Check if schema indicates an array type
324
- schema = param_info.schema_
325
- is_array = schema.get("type") == "array"
326
-
327
- if is_array:
328
- # Format array values as comma-separated string
329
- # This follows the OpenAPI 'simple' style (default for path)
330
- formatted_value = format_array_parameter(
331
- param_value, param_name, is_query_parameter=False
332
- )
333
- path = path.replace(f"{{{param_name}}}", str(formatted_value))
334
- continue
335
-
336
- # Default handling for non-array parameters or non-array schemas
337
- path = path.replace(f"{{{param_name}}}", str(param_value))
338
-
339
- # Prepare query parameters - filter out None and empty strings
340
- query_params = {}
341
- for p in self._route.parameters:
342
- if p.location == "query":
343
- # Try suffixed name first, then original name
344
- suffixed_name = f"{p.name}__{p.location}"
345
- param_value = None
346
-
347
- suffixed_value = arguments.get(suffixed_name)
348
- if (
349
- suffixed_name in arguments
350
- and suffixed_value is not None
351
- and suffixed_value != ""
352
- and not (
353
- isinstance(suffixed_value, list | dict)
354
- and len(suffixed_value) == 0
355
- )
356
- ):
357
- param_value = arguments[suffixed_name]
358
- else:
359
- name_value = arguments.get(p.name)
360
- if (
361
- p.name in arguments
362
- and name_value is not None
363
- and name_value != ""
364
- and not (
365
- isinstance(name_value, list | dict) and len(name_value) == 0
366
- )
367
- ):
368
- param_value = arguments[p.name]
369
-
370
- if param_value is not None:
371
- # Handle different parameter styles and types
372
- param_style = (
373
- p.style or "form"
374
- ) # Default style for query parameters is "form"
375
- param_explode = (
376
- p.explode if p.explode is not None else True
377
- ) # Default explode for query is True
378
-
379
- # Handle deepObject style for object parameters
380
- if (
381
- param_style == "deepObject"
382
- and isinstance(param_value, dict)
383
- and len(param_value) > 0
384
- ):
385
- if param_explode:
386
- # deepObject with explode=true: object properties become separate parameters
387
- # e.g., target[id]=123&target[type]=user
388
- deep_obj_params = format_deep_object_parameter(
389
- param_value, p.name
390
- )
391
- query_params.update(deep_obj_params)
392
- else:
393
- # deepObject with explode=false is not commonly used, fallback to JSON
394
- logger.warning(
395
- f"deepObject style with explode=false for parameter '{p.name}' is not standard. "
396
- f"Using JSON serialization fallback."
397
- )
398
- query_params[p.name] = json.dumps(param_value)
399
- # Handle array parameters with form style (default)
400
- elif (
401
- isinstance(param_value, list)
402
- and p.schema_.get("type") == "array"
403
- and len(param_value) > 0
404
- ):
405
- if param_explode:
406
- # When explode=True, we pass the array directly, which HTTPX will serialize
407
- # as multiple parameters with the same name
408
- query_params[p.name] = param_value
409
- else:
410
- # Format array as comma-separated string when explode=False
411
- formatted_value = format_array_parameter(
412
- param_value, p.name, is_query_parameter=True
413
- )
414
- query_params[p.name] = formatted_value
415
- else:
416
- # Non-array, non-deepObject parameters are passed as is
417
- query_params[p.name] = param_value
418
-
419
- # Prepare headers - fix typing by ensuring all values are strings
420
- headers = {}
421
-
422
- # Start with OpenAPI-defined header parameters
423
- openapi_headers = {}
424
- for p in self._route.parameters:
425
- if p.location == "header":
426
- # Try suffixed name first, then original name
427
- suffixed_name = f"{p.name}__{p.location}"
428
- param_value = None
429
-
430
- if (
431
- suffixed_name in arguments
432
- and arguments.get(suffixed_name) is not None
433
- ):
434
- param_value = arguments[suffixed_name]
435
- elif p.name in arguments and arguments.get(p.name) is not None:
436
- param_value = arguments[p.name]
437
-
438
- if param_value is not None:
439
- openapi_headers[p.name.lower()] = str(param_value)
440
- headers.update(openapi_headers)
441
-
442
- # Add headers from the current MCP client HTTP request (these take precedence)
443
- mcp_headers = get_http_headers()
444
- headers.update(mcp_headers)
445
-
446
- # Prepare request body
447
- json_data = None
448
- if self._route.request_body and self._route.request_body.content_schema:
449
- # Extract body parameters with collision-aware logic
450
- # Exclude all parameter names that belong to path/query/header locations
451
- params_to_exclude = set()
452
-
453
- for p in self._route.parameters:
454
- if (
455
- p.name in body_props
456
- ): # This parameter had a collision, so it was suffixed
457
- params_to_exclude.add(f"{p.name}__{p.location}")
458
- else: # No collision, parameter keeps original name but should still be excluded from body
459
- params_to_exclude.add(p.name)
460
-
461
- body_params = {
462
- k: v for k, v in arguments.items() if k not in params_to_exclude
463
- }
464
-
465
- if body_params:
466
- json_data = body_params
467
-
468
- # Execute the request
469
- try:
470
- response = await self._client.request(
471
- method=self._route.method,
472
- url=path,
473
- params=query_params,
474
- headers=headers,
475
- json=json_data,
476
- timeout=self._timeout,
477
- )
478
-
479
- # Raise for 4xx/5xx responses
480
- response.raise_for_status()
481
-
482
- # Try to parse as JSON first
483
- try:
484
- result = response.json()
485
-
486
- # Handle structured content based on output schema, if any
487
- structured_output = None
488
- if self.output_schema is not None:
489
- if self.output_schema.get("x-fastmcp-wrap-result"):
490
- # Schema says wrap - always wrap in result key
491
- structured_output = {"result": result}
492
- else:
493
- structured_output = result
494
- # If no output schema, use fallback logic for backward compatibility
495
- elif not isinstance(result, dict):
496
- structured_output = {"result": result}
497
- else:
498
- structured_output = result
499
-
500
- return ToolResult(structured_content=structured_output)
501
- except json.JSONDecodeError:
502
- return ToolResult(content=response.text)
503
-
504
- except httpx.HTTPStatusError as e:
505
- # Handle HTTP errors (4xx, 5xx)
506
- error_message = (
507
- f"HTTP error {e.response.status_code}: {e.response.reason_phrase}"
508
- )
509
- try:
510
- error_data = e.response.json()
511
- error_message += f" - {error_data}"
512
- except (json.JSONDecodeError, ValueError):
513
- if e.response.text:
514
- error_message += f" - {e.response.text}"
515
-
516
- raise ValueError(error_message) from e
517
-
518
- except httpx.RequestError as e:
519
- # Handle request errors (connection, timeout, etc.)
520
- raise ValueError(f"Request error: {e!s}") from e
521
-
522
-
523
- class OpenAPIResource(Resource):
524
- """Resource implementation for OpenAPI endpoints."""
525
-
526
- def __init__(
527
- self,
528
- client: httpx.AsyncClient,
529
- route: openapi.HTTPRoute,
530
- uri: str,
531
- name: str,
532
- description: str,
533
- mime_type: str = "application/json",
534
- tags: set[str] | None = None,
535
- timeout: float | None = None,
536
- ):
537
- if tags is None:
538
- tags = set()
539
- super().__init__(
540
- uri=AnyUrl(uri), # Convert string to AnyUrl
541
- name=name,
542
- description=description,
543
- mime_type=mime_type,
544
- tags=tags,
545
- )
546
- self._client = client
547
- self._route = route
548
- self._timeout = timeout
549
-
550
- def __repr__(self) -> str:
551
- """Custom representation to prevent recursion errors when printing."""
552
- return f"OpenAPIResource(name={self.name!r}, uri={self.uri!r}, path={self._route.path})"
553
-
554
- async def read(self) -> str | bytes:
555
- """Fetch the resource data by making an HTTP request."""
556
- try:
557
- # Extract path parameters from the URI if present
558
- path = self._route.path
559
- resource_uri = str(self.uri)
560
-
561
- # If this is a templated resource, extract path parameters from the URI
562
- if "{" in path and "}" in path:
563
- # Extract the resource ID from the URI (the last part after the last slash)
564
- parts = resource_uri.split("/")
565
-
566
- if len(parts) > 1:
567
- # Find all path parameters in the route path
568
- path_params = {}
569
-
570
- # Find the path parameter names from the route path
571
- param_matches = re.findall(r"\{([^}]+)\}", path)
572
- if param_matches:
573
- # Reverse sorting from creation order (traversal is backwards)
574
- param_matches.sort(reverse=True)
575
- # Number of sent parameters is number of parts -1 (assuming first part is resource identifier)
576
- expected_param_count = len(parts) - 1
577
- # Map parameters from the end of the URI to the parameters in the path
578
- # Last parameter in URI (parts[-1]) maps to last parameter in path, and so on
579
- for i, param_name in enumerate(param_matches):
580
- # Ensure we don't use resource identifier as parameter
581
- if i < expected_param_count:
582
- # Get values from the end of parts
583
- param_value = parts[-1 - i]
584
- path_params[param_name] = param_value
585
-
586
- # Replace path parameters with their values
587
- for param_name, param_value in path_params.items():
588
- path = path.replace(f"{{{param_name}}}", str(param_value))
589
-
590
- # Filter any query parameters - get query parameters and filter out None/empty values
591
- query_params = {}
592
- for param in self._route.parameters:
593
- if param.location == "query" and hasattr(self, f"_{param.name}"):
594
- value = getattr(self, f"_{param.name}")
595
- if value is not None and value != "":
596
- query_params[param.name] = value
597
-
598
- # Prepare headers from MCP client request if available
599
- headers = {}
600
- mcp_headers = get_http_headers()
601
- headers.update(mcp_headers)
602
-
603
- response = await self._client.request(
604
- method=self._route.method,
605
- url=path,
606
- params=query_params,
607
- headers=headers,
608
- timeout=self._timeout,
609
- )
610
-
611
- # Raise for 4xx/5xx responses
612
- response.raise_for_status()
613
-
614
- # Determine content type and return appropriate format
615
- content_type = response.headers.get("content-type", "").lower()
616
-
617
- if "application/json" in content_type:
618
- result = response.json()
619
- return json.dumps(result)
620
- elif any(ct in content_type for ct in ["text/", "application/xml"]):
621
- return response.text
622
- else:
623
- return response.content
624
-
625
- except httpx.HTTPStatusError as e:
626
- # Handle HTTP errors (4xx, 5xx)
627
- error_message = (
628
- f"HTTP error {e.response.status_code}: {e.response.reason_phrase}"
629
- )
630
- try:
631
- error_data = e.response.json()
632
- error_message += f" - {error_data}"
633
- except (json.JSONDecodeError, ValueError):
634
- if e.response.text:
635
- error_message += f" - {e.response.text}"
636
-
637
- raise ValueError(error_message) from e
638
-
639
- except httpx.RequestError as e:
640
- # Handle request errors (connection, timeout, etc.)
641
- raise ValueError(f"Request error: {e!s}") from e
642
-
643
-
644
- class OpenAPIResourceTemplate(ResourceTemplate):
645
- """Resource template implementation for OpenAPI endpoints."""
646
-
647
- def __init__(
648
- self,
649
- client: httpx.AsyncClient,
650
- route: openapi.HTTPRoute,
651
- uri_template: str,
652
- name: str,
653
- description: str,
654
- parameters: dict[str, Any],
655
- tags: set[str] | None = None,
656
- timeout: float | None = None,
657
- ):
658
- if tags is None:
659
- tags = set()
660
- super().__init__(
661
- uri_template=uri_template,
662
- name=name,
663
- description=description,
664
- parameters=parameters,
665
- tags=tags,
666
- )
667
- self._client = client
668
- self._route = route
669
- self._timeout = timeout
670
-
671
- def __repr__(self) -> str:
672
- """Custom representation to prevent recursion errors when printing."""
673
- return f"OpenAPIResourceTemplate(name={self.name!r}, uri_template={self.uri_template!r}, path={self._route.path})"
674
-
675
- async def create_resource(
676
- self,
677
- uri: str,
678
- params: dict[str, Any],
679
- context: Context | None = None,
680
- ) -> Resource:
681
- """Create a resource with the given parameters."""
682
- # Generate a URI for this resource instance
683
- uri_parts = []
684
- for key, value in params.items():
685
- uri_parts.append(f"{key}={value}")
686
-
687
- # Create and return a resource
688
- return OpenAPIResource(
689
- client=self._client,
690
- route=self._route,
691
- uri=uri,
692
- name=f"{self.name}-{'-'.join(uri_parts)}",
693
- description=self.description or f"Resource for {self._route.path}",
694
- mime_type="application/json",
695
- tags=set(self._route.tags or []),
696
- timeout=self._timeout,
697
- )
698
-
699
-
700
- class FastMCPOpenAPI(FastMCP):
701
- """
702
- FastMCP server implementation that creates components from an OpenAPI schema.
703
-
704
- This class parses an OpenAPI specification and creates appropriate FastMCP components
705
- (Tools, Resources, ResourceTemplates) based on route mappings.
706
-
707
- Example:
708
- ```python
709
- from fastmcp.server.openapi import FastMCPOpenAPI, RouteMap, MCPType
710
- import httpx
711
-
712
- # Define custom route mappings
713
- custom_mappings = [
714
- # Map all user-related endpoints to ResourceTemplate
715
- RouteMap(
716
- methods=["GET", "POST", "PATCH"],
717
- pattern=r".*/users/.*",
718
- mcp_type=MCPType.RESOURCE_TEMPLATE
719
- ),
720
- # Map all analytics endpoints to Tool
721
- RouteMap(
722
- methods=["GET"],
723
- pattern=r".*/analytics/.*",
724
- mcp_type=MCPType.TOOL
725
- ),
726
- ]
727
-
728
- # Create server with custom mappings and route mapper
729
- server = FastMCPOpenAPI(
730
- openapi_spec=spec,
731
- client=httpx.AsyncClient(),
732
- name="API Server",
733
- route_maps=custom_mappings,
734
- )
735
- ```
736
- """
737
-
738
- def __init__(
739
- self,
740
- openapi_spec: dict[str, Any],
741
- client: httpx.AsyncClient,
742
- name: str | None = None,
743
- route_maps: list[RouteMap] | None = None,
744
- route_map_fn: RouteMapFn | None = None,
745
- mcp_component_fn: ComponentFn | None = None,
746
- mcp_names: dict[str, str] | None = None,
747
- tags: set[str] | None = None,
748
- timeout: float | None = None,
749
- **settings: Any,
750
- ):
751
- """
752
- Initialize a FastMCP server from an OpenAPI schema.
753
-
754
- Args:
755
- openapi_spec: OpenAPI schema as a dictionary or file path
756
- client: httpx AsyncClient for making HTTP requests
757
- name: Optional name for the server
758
- route_maps: Optional list of RouteMap objects defining route mappings
759
- route_map_fn: Optional callable for advanced route type mapping.
760
- Receives (route, mcp_type) and returns MCPType or None.
761
- Called on every route, including excluded ones.
762
- mcp_component_fn: Optional callable for component customization.
763
- Receives (route, component) and can modify the component in-place.
764
- Called on every created component.
765
- mcp_names: Optional dictionary mapping operationId to desired component names.
766
- If an operationId is not in the dictionary, falls back to using the
767
- operationId up to the first double underscore. If no operationId exists,
768
- falls back to slugified summary or path-based naming.
769
- All names are truncated to 56 characters maximum.
770
- tags: Optional set of tags to add to all components. Components always receive any tags
771
- from the route.
772
- timeout: Optional timeout (in seconds) for all requests
773
- **settings: Additional settings for FastMCP
774
- """
775
- super().__init__(name=name or "OpenAPI FastMCP", **settings)
776
-
777
- self._client = client
778
- self._timeout = timeout
779
- self._mcp_component_fn = mcp_component_fn
780
-
781
- # Keep track of names to detect collisions
782
- self._used_names = {
783
- "tool": Counter(),
784
- "resource": Counter(),
785
- "resource_template": Counter(),
786
- "prompt": Counter(),
787
- }
788
-
789
- http_routes = openapi.parse_openapi_to_http_routes(openapi_spec)
790
-
791
- # Process routes
792
- num_excluded = 0
793
- route_maps = (route_maps or []) + DEFAULT_ROUTE_MAPPINGS
794
- for route in http_routes:
795
- # Determine route type based on mappings or default rules
796
- route_map = _determine_route_type(route, route_maps)
797
-
798
- # TODO: remove this once RouteType is removed and mcp_type is typed as MCPType without | None
799
- assert route_map.mcp_type is not None
800
- route_type = route_map.mcp_type
801
-
802
- # Call route_map_fn if provided
803
- if route_map_fn is not None:
804
- try:
805
- result = route_map_fn(route, route_type)
806
- if result is not None:
807
- route_type = result
808
- logger.debug(
809
- f"Route {route.method} {route.path} mapping customized by route_map_fn: "
810
- f"type={route_type.name}"
811
- )
812
- except Exception as e:
813
- logger.warning(
814
- f"Error in route_map_fn for {route.method} {route.path}: {e}. "
815
- f"Using default values."
816
- )
817
-
818
- # Generate a default name from the route
819
- component_name = self._generate_default_name(route, mcp_names)
820
-
821
- route_tags = set(route.tags) | route_map.mcp_tags | (tags or set())
822
-
823
- if route_type == MCPType.TOOL:
824
- self._create_openapi_tool(route, component_name, tags=route_tags)
825
- elif route_type == MCPType.RESOURCE:
826
- self._create_openapi_resource(route, component_name, tags=route_tags)
827
- elif route_type == MCPType.RESOURCE_TEMPLATE:
828
- self._create_openapi_template(route, component_name, tags=route_tags)
829
- elif route_type == MCPType.EXCLUDE:
830
- logger.info(f"Excluding route: {route.method} {route.path}")
831
- num_excluded += 1
832
-
833
- logger.info(
834
- f"Created FastMCP OpenAPI server with {len(http_routes) - num_excluded} routes"
835
- )
836
-
837
- def _generate_default_name(
838
- self, route: openapi.HTTPRoute, mcp_names_map: dict[str, str] | None = None
839
- ) -> str:
840
- """Generate a default name from the route using the configured strategy."""
841
- name = ""
842
- mcp_names_map = mcp_names_map or {}
843
-
844
- # First check if there's a custom mapping for this operationId
845
- if route.operation_id:
846
- if route.operation_id in mcp_names_map:
847
- name = mcp_names_map[route.operation_id]
848
- else:
849
- # If there's a double underscore in the operationId, use the first part
850
- name = route.operation_id.split("__")[0]
851
- else:
852
- name = route.summary or f"{route.method}_{route.path}"
853
-
854
- name = _slugify(name)
855
-
856
- # Truncate to 56 characters maximum
857
- if len(name) > 56:
858
- name = name[:56]
859
-
860
- return name
861
-
862
- def _get_unique_name(
863
- self,
864
- name: str,
865
- component_type: Literal["tool", "resource", "resource_template", "prompt"],
866
- ) -> str:
867
- """
868
- Ensure the name is unique within its component type by appending numbers if needed.
869
-
870
- Args:
871
- name: The proposed name
872
- component_type: The type of component ("tools", "resources", or "templates")
873
-
874
- Returns:
875
- str: A unique name for the component
876
- """
877
- # Check if the name is already used
878
- self._used_names[component_type][name] += 1
879
- if self._used_names[component_type][name] == 1:
880
- return name
881
-
882
- else:
883
- # Create the new name
884
- new_name = f"{name}_{self._used_names[component_type][name]}"
885
- logger.debug(
886
- f"Name collision detected: '{name}' already exists as a {component_type[:-1]}. "
887
- f"Using '{new_name}' instead."
888
- )
889
-
890
- return new_name
891
-
892
- def _create_openapi_tool(
893
- self,
894
- route: openapi.HTTPRoute,
895
- name: str,
896
- tags: set[str],
897
- ):
898
- """Creates and registers an OpenAPITool with enhanced description."""
899
- combined_schema = _combine_schemas(route)
900
-
901
- # Extract output schema from OpenAPI responses
902
- output_schema = extract_output_schema_from_responses(
903
- route.responses, route.schema_definitions, route.openapi_version
904
- )
905
-
906
- # Get a unique tool name
907
- tool_name = self._get_unique_name(name, "tool")
908
-
909
- base_description = (
910
- route.description
911
- or route.summary
912
- or f"Executes {route.method} {route.path}"
913
- )
914
-
915
- # Format enhanced description with parameters and request body
916
- enhanced_description = format_description_with_responses(
917
- base_description=base_description,
918
- responses=route.responses,
919
- parameters=route.parameters,
920
- request_body=route.request_body,
921
- )
922
-
923
- tool = OpenAPITool(
924
- client=self._client,
925
- route=route,
926
- name=tool_name,
927
- description=enhanced_description,
928
- parameters=combined_schema,
929
- output_schema=output_schema,
930
- tags=set(route.tags or []) | tags,
931
- timeout=self._timeout,
932
- )
933
-
934
- # Call component_fn if provided
935
- if self._mcp_component_fn is not None:
936
- try:
937
- self._mcp_component_fn(route, tool)
938
- logger.debug(f"Tool {tool_name} customized by component_fn")
939
- except Exception as e:
940
- logger.warning(
941
- f"Error in component_fn for tool {tool_name}: {e}. "
942
- f"Using component as-is."
943
- )
944
-
945
- # Use the potentially modified tool name as the registration key
946
- final_tool_name = tool.name
947
-
948
- # Register the tool by directly assigning to the tools dictionary
949
- self._tool_manager._tools[final_tool_name] = tool
950
- logger.debug(
951
- f"Registered TOOL: {final_tool_name} ({route.method} {route.path}) with tags: {route.tags}"
952
- )
953
-
954
- def _create_openapi_resource(
955
- self,
956
- route: openapi.HTTPRoute,
957
- name: str,
958
- tags: set[str],
959
- ):
960
- """Creates and registers an OpenAPIResource with enhanced description."""
961
- # Get a unique resource name
962
- resource_name = self._get_unique_name(name, "resource")
963
-
964
- resource_uri = f"resource://{resource_name}"
965
- base_description = (
966
- route.description or route.summary or f"Represents {route.path}"
967
- )
968
-
969
- # Format enhanced description with parameters and request body
970
- enhanced_description = format_description_with_responses(
971
- base_description=base_description,
972
- responses=route.responses,
973
- parameters=route.parameters,
974
- request_body=route.request_body,
975
- )
976
-
977
- resource = OpenAPIResource(
978
- client=self._client,
979
- route=route,
980
- uri=resource_uri,
981
- name=resource_name,
982
- description=enhanced_description,
983
- tags=set(route.tags or []) | tags,
984
- timeout=self._timeout,
985
- )
986
-
987
- # Call component_fn if provided
988
- if self._mcp_component_fn is not None:
989
- try:
990
- self._mcp_component_fn(route, resource)
991
- logger.debug(f"Resource {resource_uri} customized by component_fn")
992
- except Exception as e:
993
- logger.warning(
994
- f"Error in component_fn for resource {resource_uri}: {e}. "
995
- f"Using component as-is."
996
- )
997
-
998
- # Use the potentially modified resource URI as the registration key
999
- final_resource_uri = str(resource.uri)
1000
-
1001
- # Register the resource by directly assigning to the resources dictionary
1002
- self._resource_manager._resources[final_resource_uri] = resource
1003
- logger.debug(
1004
- f"Registered RESOURCE: {final_resource_uri} ({route.method} {route.path}) with tags: {route.tags}"
1005
- )
1006
-
1007
- def _create_openapi_template(
1008
- self,
1009
- route: openapi.HTTPRoute,
1010
- name: str,
1011
- tags: set[str],
1012
- ):
1013
- """Creates and registers an OpenAPIResourceTemplate with enhanced description."""
1014
- # Get a unique template name
1015
- template_name = self._get_unique_name(name, "resource_template")
1016
-
1017
- path_params = [p.name for p in route.parameters if p.location == "path"]
1018
- path_params.sort() # Sort for consistent URIs
1019
-
1020
- uri_template_str = f"resource://{template_name}"
1021
- if path_params:
1022
- uri_template_str += "/" + "/".join(f"{{{p}}}" for p in path_params)
1023
-
1024
- base_description = (
1025
- route.description or route.summary or f"Template for {route.path}"
1026
- )
1027
-
1028
- # Format enhanced description with parameters and request body
1029
- enhanced_description = format_description_with_responses(
1030
- base_description=base_description,
1031
- responses=route.responses,
1032
- parameters=route.parameters,
1033
- request_body=route.request_body,
1034
- )
1035
-
1036
- template_params_schema = {
1037
- "type": "object",
1038
- "properties": {
1039
- p.name: {
1040
- **(p.schema_.copy() if isinstance(p.schema_, dict) else {}),
1041
- **(
1042
- {"description": p.description}
1043
- if p.description
1044
- and not (
1045
- isinstance(p.schema_, dict) and "description" in p.schema_
1046
- )
1047
- else {}
1048
- ),
1049
- }
1050
- for p in route.parameters
1051
- if p.location == "path"
1052
- },
1053
- "required": [
1054
- p.name for p in route.parameters if p.location == "path" and p.required
1055
- ],
1056
- }
1057
-
1058
- template = OpenAPIResourceTemplate(
1059
- client=self._client,
1060
- route=route,
1061
- uri_template=uri_template_str,
1062
- name=template_name,
1063
- description=enhanced_description,
1064
- parameters=template_params_schema,
1065
- tags=set(route.tags or []) | tags,
1066
- timeout=self._timeout,
1067
- )
1068
-
1069
- # Call component_fn if provided
1070
- if self._mcp_component_fn is not None:
1071
- try:
1072
- self._mcp_component_fn(route, template)
1073
- logger.debug(f"Template {uri_template_str} customized by component_fn")
1074
- except Exception as e:
1075
- logger.warning(
1076
- f"Error in component_fn for template {uri_template_str}: {e}. "
1077
- f"Using component as-is."
1078
- )
1079
-
1080
- # Use the potentially modified template URI as the registration key
1081
- final_template_uri = template.uri_template
1082
-
1083
- # Register the template by directly assigning to the templates dictionary
1084
- self._resource_manager._templates[final_template_uri] = template
1085
- logger.debug(
1086
- f"Registered TEMPLATE: {final_template_uri} ({route.method} {route.path}) with tags: {route.tags}"
1087
- )