Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

Revert 12 contributions merged without enough review (#6434)

nate nowack968eefe542a7
diff --git a/docs/apps/low-level.mdx b/docs/apps/low-level.mdx
index aab5a4608..4fc6a1c64 100644
--- a/docs/apps/low-level.mdx
+++ b/docs/apps/low-level.mdx
@@ -300,25 +300,7 @@ The tool generates a QR code as a base64 PNG. The resource loads the MCP Apps JS
## Checking client support
-FastMCP declares `io.modelcontextprotocol/ui` in `capabilities.extensions` when a registered component carries `_meta.ui`, a resource or resource template uses `ui://`, or a resource uses the MCP Apps MIME type. An untransformed server with no app components omits the declaration. Providers with transforms, proxies, and other dynamic providers retain it conservatively: they may introduce apps that cannot be inspected synchronously during capability negotiation.
-
-Capabilities are negotiated once, when a session initializes. An app tool or `ui://` resource added while a client is connected is not advertised to that client until it reconnects; new sessions see it immediately. If your server registers apps at runtime, register the extension explicitly so every session sees it from the start:
-
-```python
-from fastmcp import FastMCP
-from fastmcp.apps import UI_EXTENSION_ID
-from fastmcp.server.extensions import ServerExtension
-
-
-class AppsExtension(ServerExtension):
- identifier = UI_EXTENSION_ID
-
-
-mcp = FastMCP("Dynamic Apps")
-mcp.add_extension(AppsExtension())
-```
-
-Not all hosts support the Apps extension. A host that supports it declares the extension back, which is what you check at runtime using the tool's [context](/servers/context):
+Not all hosts support the Apps extension. You can check at runtime using the tool's [context](/servers/context):
```python
from fastmcp import Context
diff --git a/docs/docs.json b/docs/docs.json
index 7524658e5..250f70525 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -302,7 +302,6 @@
"integrations/google",
"integrations/huggingface",
"integrations/keycloak",
- "integrations/keystone",
"integrations/oci",
"integrations/permit",
"integrations/propelauth",
diff --git a/docs/integrations/keystone.mdx b/docs/integrations/keystone.mdx
deleted file mode 100644
index 5f076ed0d..000000000
--- a/docs/integrations/keystone.mdx
+++ /dev/null
@@ -1,141 +0,0 @@
----
-title: OpenStack Keystone 🀝 FastMCP
-sidebarTitle: Keystone
-description: Secure your FastMCP server with OpenStack Keystone tokens
-icon: shield-check
----
-
-import { VersionBadge } from "/snippets/version-badge.mdx"
-
-<VersionBadge version="4.2.0" />
-
-If your users already authenticate to an OpenStack cloud, your FastMCP server can accept the tokens they already have. `KeystoneTokenVerifier` validates each incoming token with Keystone, then exposes the caller's user, project, and roles to your tools.
-
-Keystone tokens are opaque and Keystone has no RFC 7662 introspection endpoint, so the [generic introspection verifier](/servers/auth/token-verification#token-introspection-protocol) won't work. This verifier uses Keystone's own equivalent, the Identity v3 [token validation API](https://docs.openstack.org/api-ref/identity/v3/#validate-and-show-information-for-token), through a [keystoneauth1](https://docs.openstack.org/keystoneauth/latest/) session.
-
-This is token verification only. FastMCP doesn't issue tokens or run a login flow, so clients must obtain a Keystone token themselves, and OAuth-based MCP clients can't sign in interactively.
-
-## Configuration
-
-### Prerequisites
-
-Install the `keystone` extra:
-
-```bash
-pip install "fastmcp[keystone]"
-```
-
-You also need:
-
-1. Your Keystone URL, such as `https://keystone.example.com:5000/v3`. The `/v3` suffix is optional.
-2. A service account that's allowed to validate other users' tokens. Keystone's default policy grants this to the `service` role, so a user with that role on your `service` project is the usual choice. A username and password must come with `project_name`, because an unscoped token has no service catalog and can't validate tokens.
-
-### FastMCP Configuration
-
-Authenticate the verifier with the service account, then pass it to your server:
-
-```python server.py
-import os
-
-from fastmcp import FastMCP
-from fastmcp.server.auth.providers.keystone import KeystoneTokenVerifier
-from fastmcp.server.dependencies import get_access_token
-
-auth = KeystoneTokenVerifier(
- auth_url=os.environ["KEYSTONE_AUTH_URL"],
- username="mcp-service",
- password=os.environ["KEYSTONE_SERVICE_PASSWORD"],
- project_name="service",
- allowed_project_ids=[os.environ["KEYSTONE_PROJECT_ID"]],
-)
-
-mcp = FastMCP("Keystone Example Server", auth=auth)
-
-
-def whoami() -> dict:
- """Show the authenticated Keystone identity."""
- token = get_access_token()
- return {
- "user_id": token.client_id,
- "project": token.claims["project_name"],
- "roles": token.scopes,
- }
-```
-
-To authenticate with an application credential instead of a password, replace `username`, `password`, and `project_name` with `application_credential_id` and `application_credential_secret`. Each verifier uses exactly one of these two credential types.
-
-<Warning>
-**Set `allowed_project_ids` on shared clouds.** Keystone authenticates every user in the cloud, so without this restriction any valid token is accepted, whichever project it belongs to. Role checks don't close this gap, because users commonly hold the `member` role in their own project. When the option is set, domain-scoped, system-scoped, and unscoped tokens are rejected too.
-</Warning>
-
-### Reaching Keystone
-
-The verifier finds the validation endpoint through the service catalog. It uses the `public` interface by default. Servers running inside the cloud may need `interface="internal"` and `region_name`. For a private certificate authority, set `verify` to the path of your CA bundle.
-
-## Testing
-
-Run your server, then get a token from the OpenStack CLI:
-
-```bash
-fastmcp run server.py --transport http --port 8000
-openstack token issue -f value -c id
-```
-
-Clients send the token as a standard bearer token, not in the `X-Auth-Token` header that OpenStack APIs use:
-
-```python client.py
-import asyncio
-import os
-
-from fastmcp import Client
-
-
-async def main():
- token = os.environ["OS_TOKEN"]
- async with Client("http://localhost:8000/mcp", auth=token) as client:
- print(await client.call_tool("whoami"))
-
-
-asyncio.run(main())
-```
-
-## Authorization
-
-Each token's Keystone role names become its FastMCP scopes, so you can use [`require_scopes`](/servers/authorization) to protect individual components. To require a role for the whole server, pass it to the verifier as `required_scopes`.
-
-```python
-from fastmcp.server.auth import require_scopes
-
-
[email protected](auth=require_scopes("admin"))
-def delete_everything() -> str:
- return "done"
-```
-
-Tools can read these values from `get_access_token().claims`:
-
-| Claim | Description |
-| ----- | ----------- |
-| `sub` | Keystone user ID, also available as `client_id` |
-| `username`, `user_domain_id`, `user_domain_name` | User name and domain |
-| `project_id`, `project_name`, `project_domain_id`, `project_domain_name` | Project, for project-scoped tokens |
-| `domain_id`, `domain_name` | Domain, for domain-scoped tokens |
-| `system_scoped` | Whether the token is system-scoped |
-| `roles` | Keystone role names |
-| `application_credential_id` | Application credential that produced the token, if any |
-| `audit_id` | Keystone audit ID |
-
-## Application Credential Access Rules
-
-Tokens from application credentials with [access rules](https://docs.openstack.org/keystone/latest/user/application_credentials.html#access-rules) are always rejected. Those rules list the OpenStack services and API paths a token may reach, and an MCP server isn't one of them. Application credentials without access rules work normally.
-
-## Caching
-
-Every request is validated with Keystone by default, so a revoked token stops working immediately. Busy servers can set `cache_ttl_seconds` to reduce that load, and a revoked token then keeps working until its cache entry expires. Only successful validations are cached, and entries never outlive the token.
-
-## Troubleshooting
-
-When Keystone can't validate a token, for example during an outage or because of bad service credentials, the verifier fails closed. Callers receive a `401` that looks the same as an invalid token, and the server logs a warning with the cause.
-
-If every token is rejected, look for these warnings. HTTP `401` means Keystone refused the service credentials, and HTTP `403` means the service account lacks permission to validate tokens.
diff --git a/docs/servers/authorization.mdx b/docs/servers/authorization.mdx
index 5e4b8ca99..5d598ff90 100644
--- a/docs/servers/authorization.mdx
+++ b/docs/servers/authorization.mdx
@@ -90,7 +90,6 @@ Keeping the claim path at the call site means any provider works, including ones
| Provider | Extractor |
| --- | --- |
| Keycloak | `lambda c: c["realm_access"]["roles"]` |
-| OpenStack Keystone | `lambda c: c["roles"]` |
| Microsoft Entra | `lambda c: c["roles"]` |
| AWS Cognito | `lambda c: c["cognito:groups"]` |
| Auth0 | `lambda c: c["permissions"]` |
diff --git a/docs/servers/pagination.mdx b/docs/servers/pagination.mdx
index 6a38833b4..0ea47dd22 100644
--- a/docs/servers/pagination.mdx
+++ b/docs/servers/pagination.mdx
@@ -39,8 +39,6 @@ When `list_page_size` is configured, the `tools/list`, `resources/list`, `resour
Cursors are opaque base64-encoded strings per the MCP specification. Clients should treat them as black boxes, passing them unchanged between requests. The cursor encodes the offset into the result set, but this is an implementation detail that may change.
-A malformed, non-empty cursor returns the MCP `-32602` (Invalid params) error, whether or not `list_page_size` is configured. Omitting the cursor still returns the complete list when pagination is disabled.
-
## Client Behavior
The FastMCP Client handles pagination transparently. Convenience methods like `list_tools()`, `list_resources()`, `list_resource_templates()`, and `list_prompts()` automatically fetch all pages and return the complete list. Existing code continues to work without modification.
diff --git a/fastmcp_slim/fastmcp/apps/config.py b/fastmcp_slim/fastmcp/apps/config.py
index eb51bc16e..4930c25d9 100644
--- a/fastmcp_slim/fastmcp/apps/config.py
+++ b/fastmcp_slim/fastmcp/apps/config.py
@@ -194,22 +194,6 @@ def app_config_to_meta_dict(app: AppConfig | dict[str, Any]) -> dict[str, Any]:
return app
-def component_serves_app(component: FastMCPComponent) -> bool:
- """Whether a component participates in the MCP Apps extension.
-
- A component does so by declaring ``meta["ui"]`` (``app=AppConfig(...)`` on a
- tool or resource) or by being the UI document itself: a ``ui://`` resource,
- or any resource the host would render as ``UI_MIME_TYPE``.
- """
- if component.meta and "ui" in component.meta:
- return True
- # `Resource.uri` is an AnyUrl, so compare on the string form.
- uri = getattr(component, "uri", None) or getattr(component, "uri_template", None)
- if uri is not None and str(uri).lower().startswith("ui://"):
- return True
- return getattr(component, "mime_type", None) == UI_MIME_TYPE
-
-
def is_model_visible(component: FastMCPComponent) -> bool:
"""Whether a component belongs on model-facing discovery and proxy surfaces.
diff --git a/fastmcp_slim/fastmcp/client/group.py b/fastmcp_slim/fastmcp/client/group.py
index f945d2297..123a3da7f 100644
--- a/fastmcp_slim/fastmcp/client/group.py
+++ b/fastmcp_slim/fastmcp/client/group.py
@@ -71,10 +71,6 @@ class ClientGroup:
self._tool_routes: dict[str, ToolRoute] = {}
self._catalog_loaded = False
self._route_lock = anyio.Lock()
- # Keep explicit refresh fetches and commits in the same order; this is
- # separate from _route_lock because lazy discovery calls list_tools()
- # while holding that lock.
- self._refresh_lock = anyio.Lock()
# Member closes handed off by exiting contexts; referenced until done.
self._closers: set[asyncio.Task[bool | None]] = set()
@@ -251,32 +247,30 @@ class ClientGroup:
cache hits when staleness within the server's hint is acceptable.
"""
self._require_connected()
- async with self._refresh_lock:
- self._require_connected()
- tools: list[mcp_types.Tool] = []
- routes: dict[str, ToolRoute] = {}
- clients = list(self._clients.items())
- tool_lists = await gather(
- client.list_tools(cache_mode=cache_mode) for _, client in clients
- )
+ tools: list[mcp_types.Tool] = []
+ routes: dict[str, ToolRoute] = {}
+ clients = list(self._clients.items())
+ tool_lists = await gather(
+ client.list_tools(cache_mode=cache_mode) for _, client in clients
+ )
+
+ for (server_name, client), server_tools in zip(
+ clients, tool_lists, strict=True
+ ):
+ for tool in server_tools:
+ public_name = f"{server_name}_{tool.name}"
+ if public_name in routes:
+ raise ValueError(f"Tool name collision: {public_name!r}")
+ routes[public_name] = ToolRoute(
+ server_name=server_name,
+ client=client,
+ upstream_name=tool.name,
+ )
+ tools.append(tool.model_copy(update={"name": public_name}))
- for (server_name, client), server_tools in zip(
- clients, tool_lists, strict=True
- ):
- for tool in server_tools:
- public_name = f"{server_name}_{tool.name}"
- if public_name in routes:
- raise ValueError(f"Tool name collision: {public_name!r}")
- routes[public_name] = ToolRoute(
- server_name=server_name,
- client=client,
- upstream_name=tool.name,
- )
- tools.append(tool.model_copy(update={"name": public_name}))
-
- self._tool_routes = routes
- self._catalog_loaded = True
- return tools
+ self._tool_routes = routes
+ self._catalog_loaded = True
+ return tools
async def list_skills(
self, *, cache_mode: CacheMode = "use"
diff --git a/fastmcp_slim/fastmcp/prompts/function_prompt.py b/fastmcp_slim/fastmcp/prompts/function_prompt.py
index d09596405..bac7362b1 100644
--- a/fastmcp_slim/fastmcp/prompts/function_prompt.py
+++ b/fastmcp_slim/fastmcp/prompts/function_prompt.py
@@ -42,51 +42,6 @@ F = TypeVar("F", bound=Callable[..., Any])
logger = get_logger(__name__)
-def _python_names_by_argument_name(fn: Callable[..., Any]) -> dict[str, str]:
- """Map advertised prompt-argument names to Python parameter names.
-
- Prompt arguments are advertised from the Pydantic call schema, so a
- parameter with an alias is listed under the alias. MCP callers send the
- advertised name, which must be translated back before the arguments are
- converted and filtered against the Python signature.
- """
- mapping: dict[str, str] = {}
- try:
- hints = get_type_hints(fn, include_extras=True)
- except Exception:
- hints = {}
- for param_name, param in inspect.signature(fn).parameters.items():
- annotation = hints.get(param_name, param.annotation)
- default = param.default
- try:
- if isinstance(default, FieldInfo):
- # A Field(...) default is part of the call schema too. Merge
- # it with Annotated metadata exactly as pydantic does, so the
- # alias pydantic advertises is the one we map.
- if annotation is inspect.Parameter.empty:
- field_info = default
- else:
- field_info = FieldInfo.from_annotated_attribute(annotation, default)
- elif annotation is not inspect.Parameter.empty:
- field_info = FieldInfo.from_annotation(annotation)
- else:
- continue
- except Exception as e:
- logger.debug(
- "Could not determine alias for prompt argument %s: %s", param_name, e
- )
- continue
-
- advertised_name = (
- field_info.validation_alias
- if isinstance(field_info.validation_alias, str)
- else field_info.alias
- )
- if advertised_name and advertised_name != param_name:
- mapping[advertised_name] = param_name
- return mapping
-
-
@runtime_checkable
class DecoratedPrompt(Protocol):
"""Protocol for functions decorated with @prompt."""
@@ -325,15 +280,11 @@ class FunctionPrompt(Prompt):
# Preserve the existing fallback for unresolved forward references.
type_hints = getattr(wrapper_fn, "__annotations__", {})
converted_kwargs = {}
- # Callers send advertised names; an advertised name may be a Pydantic
- # alias whose Python parameter is declared under a different name.
- aliases = _python_names_by_argument_name(self.fn)
for param_name, param_value in kwargs.items():
- python_name = aliases.get(param_name, param_name)
- param = sig.parameters.get(python_name)
- if param is not None:
- annotation = type_hints.get(python_name, param.annotation)
+ if param_name in sig.parameters:
+ param = sig.parameters[param_name]
+ annotation = type_hints.get(param_name, param.annotation)
if annotation == inspect.Parameter.empty or not isinstance(
param_value, str
@@ -405,12 +356,9 @@ class FunctionPrompt(Prompt):
# This is important for security: dependencies should not be overridable
# from external callers. self.fn is wrapped by without_injected_parameters,
# so we only accept arguments that are in the wrapped function's signature.
- # Advertised names may be Pydantic aliases; those are accepted too
- # and validated under the alias by the type adapter below.
sig = inspect.signature(self.fn)
valid_params = set(sig.parameters.keys())
- aliases = _python_names_by_argument_name(self.fn)
- kwargs = {k: v for k, v in kwargs.items() if k in valid_params or k in aliases}
+ kwargs = {k: v for k, v in kwargs.items() if k in valid_params}
# Use type adapter to validate arguments and handle Field() defaults
# This matches the behavior of tools in function_tool
diff --git a/fastmcp_slim/fastmcp/server/auth/providers/keystone.py b/fastmcp_slim/fastmcp/server/auth/providers/keystone.py
deleted file mode 100644
index 4cd4991cf..000000000
--- a/fastmcp_slim/fastmcp/server/auth/providers/keystone.py
+++ /dev/null
@@ -1,310 +0,0 @@
-"""OpenStack Keystone token verification for FastMCP.
-
-Keystone issues opaque Fernet tokens and has no RFC 7662 introspection
-endpoint. Its equivalent is the Identity v3 token validation API
-(`GET /v3/auth/tokens`), which this verifier calls through an authenticated
-keystoneauth1 session. The service account needs permission to validate other
-users' tokens, which Keystone's default policy grants to the `service` role.
-
-Example:
- ```python
- from fastmcp import FastMCP
- from fastmcp.server.auth.providers.keystone import KeystoneTokenVerifier
-
- verifier = KeystoneTokenVerifier(
- auth_url="https://keystone.example.com:5000/v3",
- username="mcp-service",
- password="service-password",
- project_name="service",
- allowed_project_ids=["f3a1c6b2d4e54c60a7c9e8b1d2f30456"],
- )
-
- mcp = FastMCP("My Protected Server", auth=verifier)
- ```
-"""
-
-from __future__ import annotations
-
-from datetime import UTC, datetime
-from typing import Any
-
-import anyio.to_thread
-from pydantic import AnyHttpUrl, SecretStr
-
-from fastmcp.server.auth import AccessToken, TokenVerifier
-from fastmcp.utilities.auth import parse_scopes
-from fastmcp.utilities.logging import get_logger
-from fastmcp.utilities.token_cache import TokenCache
-
-try:
- from keystoneauth1 import access, adapter, session
- from keystoneauth1.identity import v3
-except ImportError as e:
- raise ImportError(
- "KeystoneTokenVerifier requires the `keystone` extra. "
- "Install with: pip install 'fastmcp[keystone]'"
- ) from e
-
-logger = get_logger(__name__)
-
-
-def _secret_value(secret: str | SecretStr) -> str:
- return secret.get_secret_value() if isinstance(secret, SecretStr) else secret
-
-
-class KeystoneTokenVerifier(TokenVerifier):
- """Verify OpenStack Keystone tokens with the Identity v3 validation API.
-
- Clients send their Keystone token as a standard `Authorization: Bearer`
- header. The token's Keystone role names become its FastMCP scopes, so
- `required_scopes` and `require_scopes` operate on roles.
-
- Authenticate the verifier with either a service user (`username`,
- `password`, and `project_name`) or an application credential
- (`application_credential_id` and `application_credential_secret`).
-
- Keystone authenticates every user in a cloud, so a valid token alone only
- proves that its holder has an account there. On a shared cloud, set
- `allowed_project_ids` to limit access to specific projects.
-
- Tokens from application credentials with access rules are rejected. Those
- rules name the OpenStack service and API paths a token may reach, and an
- MCP server is not one of the services they can describe.
-
- Caching is disabled by default so that revoked tokens stop working
- immediately. Set `cache_ttl_seconds` to reduce load on Keystone.
- """
-
- def __init__(
- self,
- *,
- auth_url: str,
- username: str | None = None,
- password: str | SecretStr | None = None,
- user_domain_name: str = "Default",
- project_name: str | None = None,
- project_domain_name: str = "Default",
- application_credential_id: str | None = None,
- application_credential_secret: str | SecretStr | None = None,
- interface: str = "public",
- region_name: str | None = None,
- verify: bool | str = True,
- timeout_seconds: int = 10,
- required_scopes: list[str] | None = None,
- allowed_project_ids: list[str] | None = None,
- base_url: AnyHttpUrl | str | None = None,
- cache_ttl_seconds: int | None = None,
- max_cache_size: int | None = None,
- ):
- """Initialize the Keystone token verifier.
-
- Args:
- auth_url: Keystone URL, with or without the `/v3` suffix.
- username: Service user that validates tokens.
- password: Password for the service user.
- user_domain_name: Domain of the service user.
- project_name: Project to scope the service user's token to. Required
- with `username` and `password`.
- project_domain_name: Domain of `project_name`.
- application_credential_id: Application credential to authenticate
- with instead of a service user.
- application_credential_secret: Secret for the application credential.
- interface: Service catalog interface used to reach Keystone's
- validation endpoint: `public`, `internal`, or `admin`.
- region_name: Service catalog region of the identity endpoint.
- verify: Whether to verify TLS certificates, or a path to a CA bundle.
- timeout_seconds: Timeout for each request to Keystone.
- required_scopes: Keystone role names that every token must hold.
- allowed_project_ids: Project IDs a token must be scoped to. None
- accepts any token that Keystone considers valid. When set,
- domain-scoped, system-scoped, and unscoped tokens are rejected.
- base_url: Base URL for the TokenVerifier protocol.
- cache_ttl_seconds: How long to cache successful validations. None
- disables caching so that revocation takes effect immediately.
- max_cache_size: Maximum number of cached tokens. Default: 10000.
- """
- super().__init__(
- base_url=base_url,
- required_scopes=(
- parse_scopes(required_scopes) if required_scopes is not None else None
- ),
- )
-
- has_user = username is not None or password is not None
- has_app_cred = (
- application_credential_id is not None
- or application_credential_secret is not None
- )
- if has_user == has_app_cred:
- raise ValueError(
- "Provide either username and password or "
- "application_credential_id and application_credential_secret."
- )
-
- base_auth_url = auth_url.rstrip("/").removesuffix("/v3")
- identity_url = f"{base_auth_url}/v3"
-
- auth: v3.Auth
- if has_app_cred:
- if (
- application_credential_id is None
- or application_credential_secret is None
- ):
- raise ValueError(
- "application_credential_id and application_credential_secret "
- "must be provided together."
- )
- auth = v3.ApplicationCredential(
- auth_url=identity_url,
- application_credential_id=application_credential_id,
- application_credential_secret=_secret_value(
- application_credential_secret
- ),
- )
- else:
- if username is None or password is None:
- raise ValueError("username and password must be provided together.")
- # An unscoped token has no service catalog to find Keystone's
- # endpoint in and no roles to pass the token validation policy.
- if project_name is None:
- raise ValueError(
- "project_name is required with username and password, because "
- "an unscoped service token cannot validate tokens."
- )
- auth = v3.Password(
- auth_url=identity_url,
- username=username,
- password=_secret_value(password),
- user_domain_name=user_domain_name,
- project_name=project_name,
- project_domain_name=project_domain_name,
- )
-
- self._identity = adapter.Adapter(
- session.Session(auth=auth, verify=verify, timeout=timeout_seconds),
- service_type="identity",
- interface=interface,
- region_name=region_name,
- version="3.0",
- )
- self.allowed_project_ids = (
- None if allowed_project_ids is None else set(allowed_project_ids)
- )
- self._cache = TokenCache(
- ttl_seconds=cache_ttl_seconds,
- max_size=max_cache_size,
- )
-
- def _fetch_token_data(self, token: str) -> dict[str, Any] | None:
- """Ask Keystone to validate a token, returning its data if valid."""
- response = self._identity.get(
- "/auth/tokens?nocatalog",
- headers={"X-Subject-Token": token},
- raise_exc=False,
- log=False,
- )
- if response.status_code == 200:
- return response.json()
- if response.status_code == 404:
- logger.debug("Keystone does not recognize this token")
- return None
- # Anything else is about this verifier rather than the caller's token:
- # 401 and 403 mean Keystone refused the service credentials or their
- # permission to validate tokens. Without this warning, every caller
- # would simply see 401 and the cause would be invisible.
- logger.warning(
- "Keystone token validation failed: HTTP %d", response.status_code
- )
- return None
-
- async def verify_token(self, token: str) -> AccessToken | None:
- """Verify a token against Keystone's token validation API.
-
- Args:
- token: The Keystone token to validate.
-
- Returns:
- AccessToken if Keystone accepts the token and it satisfies this
- verifier's restrictions, otherwise None.
- """
- if not token or not token.strip():
- return None
-
- is_cached, cached_result = self._cache.get(token)
- if is_cached:
- return cached_result
-
- try:
- # keystoneauth1 is synchronous and may need to fetch a service
- # token, discover endpoints, and validate, all over blocking HTTP.
- data = await anyio.to_thread.run_sync(self._fetch_token_data, token)
- if data is None:
- return None
- result = self._build_access_token(token, data)
- except Exception as e:
- # Fail closed on outages, bad service credentials, and malformed
- # responses. Log above debug because operators need to see these.
- logger.warning("Keystone token verification error: %s", e)
- return None
-
- if result is not None:
- self._cache.set(token, result)
- return result
-
- def _build_access_token(
- self, token: str, data: dict[str, Any]
- ) -> AccessToken | None:
- """Apply this verifier's restrictions and build an AccessToken."""
- auth_ref = access.create(body=data, auth_token=token)
-
- expires = auth_ref.expires
- if expires is None or expires <= datetime.now(UTC):
- logger.debug("Keystone token has expired")
- return None
-
- application_credential = data["token"].get("application_credential") or {}
- if application_credential.get("access_rules") is not None:
- logger.debug("Rejecting Keystone token restricted by access rules")
- return None
-
- project_id = auth_ref.project_id
- if (
- self.allowed_project_ids is not None
- and project_id not in self.allowed_project_ids
- ):
- logger.debug("Keystone token is not scoped to an allowed project")
- return None
-
- roles = auth_ref.role_names or []
- if self.required_scopes and not set(self.required_scopes).issubset(roles):
- logger.debug("Keystone token is missing required roles")
- return None
-
- user_id = auth_ref.user_id
- if not user_id:
- logger.debug("Keystone token has no user ID")
- return None
-
- return AccessToken(
- token=token,
- client_id=user_id,
- scopes=roles,
- expires_at=int(expires.timestamp()),
- subject=user_id,
- claims={
- "sub": user_id,
- "username": auth_ref.username,
- "user_domain_id": auth_ref.user_domain_id,
- "user_domain_name": auth_ref.user_domain_name,
- "project_id": project_id,
- "project_name": auth_ref.project_name,
- "project_domain_id": auth_ref.project_domain_id,
- "project_domain_name": auth_ref.project_domain_name,
- "domain_id": auth_ref.domain_id,
- "domain_name": auth_ref.domain_name,
- "system_scoped": auth_ref.system_scoped,
- "roles": roles,
- "application_credential_id": application_credential.get("id"),
- "audit_id": auth_ref.audit_id,
- },
- )
diff --git a/fastmcp_slim/fastmcp/server/dependencies.py b/fastmcp_slim/fastmcp/server/dependencies.py
index 57fc0a2ea..151036f35 100644
--- a/fastmcp_slim/fastmcp/server/dependencies.py
+++ b/fastmcp_slim/fastmcp/server/dependencies.py
@@ -15,6 +15,7 @@ from collections.abc import AsyncGenerator, Awaitable, Callable, Generator, Mapp
from contextlib import AsyncExitStack, asynccontextmanager, contextmanager
from contextvars import ContextVar
from dataclasses import dataclass
+from functools import lru_cache
from types import TracebackType
from typing import TYPE_CHECKING, Any, Protocol, cast, get_type_hints, runtime_checkable
@@ -41,7 +42,6 @@ from uncalled_for.resolution import _Depends
from fastmcp.exceptions import FastMCPError
from fastmcp.server.auth import AccessToken
from fastmcp.server.http import _current_http_request
-from fastmcp.utilities._callable_cache import cache_on_callable
from fastmcp.utilities.async_utils import (
call_sync_fn_in_threadpool,
is_coroutine_function,
@@ -728,7 +728,7 @@ def get_access_token() -> AccessToken | None:
# --- Schema generation helper ---
-@cache_on_callable
+@lru_cache(maxsize=5000)
def without_injected_parameters(
fn: Callable[..., Any], *, run_in_thread: bool = True
) -> Callable[..., Any]:
diff --git a/fastmcp_slim/fastmcp/server/low_level.py b/fastmcp_slim/fastmcp/server/low_level.py
index e46de1884..f27f07463 100644
--- a/fastmcp_slim/fastmcp/server/low_level.py
+++ b/fastmcp_slim/fastmcp/server/low_level.py
@@ -555,9 +555,6 @@ class LowLevelServer(_Server[LifespanResultT]):
) -> mcp_types.ServerCapabilities:
"""Override to advertise registered extensions and the MCP Apps UI extension.
- The UI extension is advertised when the server may serve an app,
- including through transforms or dynamic providers (`FastMCP.may_serve_apps`).
-
``ServerCapabilities.extensions`` is a real declared field in v2, so we
update it directly. The
`FastMCP(experimental_capabilities=...)` merge also lives here rather
@@ -581,22 +578,19 @@ class LowLevelServer(_Server[LifespanResultT]):
# Advertise every registered extension's settings under
# capabilities.extensions[identifier]. The hand-rolled UI splice stays
# for now (MCP Apps migrates onto the extension API in a later phase);
- # the two coexist. It is advertised only when the server may serve an
- # app, including through transforms or dynamic providers.
- # The SDK's pre-2026 version
- # sieve strips capabilities.extensions on legacy eras, a known
+ # the two coexist. Advertisement is unconditional β€” the SDK's pre-2026
+ # version sieve strips capabilities.extensions on legacy eras, a known
# limitation (sdk-feedback #2).
existing_extensions = capabilities.extensions or {}
registered_extensions = {
extension.identifier: extension.settings()
for extension in self.fastmcp._extensions.values()
}
- app_extensions = {UI_EXTENSION_ID: {}} if self.fastmcp.may_serve_apps else {}
return capabilities.model_copy(
update={
"extensions": {
**existing_extensions,
- **app_extensions,
+ UI_EXTENSION_ID: {},
**registered_extensions,
},
}
diff --git a/fastmcp_slim/fastmcp/server/mixins/mcp_operations.py b/fastmcp_slim/fastmcp/server/mixins/mcp_operations.py
index ee6a10772..b74dec535 100644
--- a/fastmcp_slim/fastmcp/server/mixins/mcp_operations.py
+++ b/fastmcp_slim/fastmcp/server/mixins/mcp_operations.py
@@ -47,7 +47,7 @@ from fastmcp.utilities.async_utils import (
)
from fastmcp.utilities.json_schema import is_object_schema
from fastmcp.utilities.logging import get_logger
-from fastmcp.utilities.pagination import CursorState, paginate_sequence
+from fastmcp.utilities.pagination import paginate_sequence
from fastmcp.utilities.versions import VersionSpec, dedupe_with_versions
if TYPE_CHECKING:
@@ -65,13 +65,11 @@ def _apply_pagination(
) -> tuple[list[PaginateT], str | None]:
"""Apply pagination to items, raising MCPError for invalid cursors.
- If page_size is None, validates the cursor and returns all items without pagination.
+ If page_size is None, returns all items without pagination.
"""
+ if page_size is None:
+ return list(items), None
try:
- if page_size is None:
- if cursor:
- CursorState.decode(cursor)
- return list(items), None
return paginate_sequence(items, cursor, page_size)
except ValueError as e:
raise MCPError(code=INVALID_PARAMS, message=str(e)) from e
diff --git a/fastmcp_slim/fastmcp/server/providers/aggregate.py b/fastmcp_slim/fastmcp/server/providers/aggregate.py
index 88bd376fb..4df9100c7 100644
--- a/fastmcp_slim/fastmcp/server/providers/aggregate.py
+++ b/fastmcp_slim/fastmcp/server/providers/aggregate.py
@@ -261,13 +261,6 @@ class AggregateProvider(Provider):
def __repr__(self) -> str:
return f"AggregateProvider(providers={self.providers!r})"
- @property
- def may_serve_apps(self) -> bool:
- """Whether transforms or child providers may serve MCP App UI."""
- return bool(self._transforms) or any(
- provider.may_serve_apps for provider in self.providers
- )
-
# -------------------------------------------------------------------------
# Tools
# -------------------------------------------------------------------------
diff --git a/fastmcp_slim/fastmcp/server/providers/base.py b/fastmcp_slim/fastmcp/server/providers/base.py
index 5e69c7a5d..aff0471f7 100644
--- a/fastmcp_slim/fastmcp/server/providers/base.py
+++ b/fastmcp_slim/fastmcp/server/providers/base.py
@@ -118,23 +118,6 @@ class Provider:
def __repr__(self) -> str:
return f"{self.__class__.__name__}()"
- @property
- def may_serve_apps(self) -> bool:
- """Whether this provider may serve MCP App UI (``meta["ui"]`` or ``ui://``).
-
- Advertised capabilities are a promise the server has to keep, so a
- provider that cannot be enumerated synchronously answers ``True``: a
- proxy to a remote server, or a third-party provider, may well be holding
- an app, and hiding the extension from it would leave the host unable to
- render a UI that does exist. A spurious declaration is the lesser error.
-
- `LocalProvider` answers from its registry, and `AggregateProvider`
- combines its children. Providers with transforms also answer `True`:
- transforms can introduce app metadata or UI resources, and their async
- methods cannot be evaluated during synchronous capability negotiation.
- """
- return True
-
@property
def transforms(self) -> list[Transform]:
"""All transforms applied to components from this provider."""
diff --git a/fastmcp_slim/fastmcp/server/providers/fastmcp_provider.py b/fastmcp_slim/fastmcp/server/providers/fastmcp_provider.py
index bd4ac2131..158158db7 100644
--- a/fastmcp_slim/fastmcp/server/providers/fastmcp_provider.py
+++ b/fastmcp_slim/fastmcp/server/providers/fastmcp_provider.py
@@ -415,11 +415,6 @@ class FastMCPProvider(Provider):
super().__init__()
self.server = server
- @property
- def may_serve_apps(self) -> bool:
- """Whether transforms or the wrapped server may serve MCP App UI."""
- return bool(self._transforms) or self.server.may_serve_apps
-
def required_extensions(self) -> Sequence[ServerExtension]:
"""Expose the mounted server's bundled and auto-registerable extensions."""
return self.server.required_extensions()
diff --git a/fastmcp_slim/fastmcp/server/providers/local_provider/decorators/tools.py b/fastmcp_slim/fastmcp/server/providers/local_provider/decorators/tools.py
index 796a705c8..9779801b5 100644
--- a/fastmcp_slim/fastmcp/server/providers/local_provider/decorators/tools.py
+++ b/fastmcp_slim/fastmcp/server/providers/local_provider/decorators/tools.py
@@ -41,10 +41,6 @@ DuplicateBehavior = Literal["error", "warn", "replace", "ignore"]
PREFAB_RENDERER_URI = "ui://prefab/renderer.html"
-# Sentinel distinguishing "no metadata was stamped" from "stamped as None", so a
-# rejected registration can restore the function to exactly its prior state.
-_MISSING = object()
-
def _is_prefab_type(tp: Any) -> bool:
"""Check if *tp* is or contains a prefab type, recursing through unions and Annotated."""
@@ -323,22 +319,8 @@ class ToolDecoratorMixin:
run_in_thread=run_in_thread,
)
target = fn.__func__ if hasattr(fn, "__func__") else fn
- previous = getattr(target, "__fastmcp__", _MISSING)
target.__fastmcp__ = metadata # type: ignore[attr-defined] # ty:ignore[unresolved-attribute]
- try:
- self.add_tool(fn)
- except Exception:
- # Registration is what validates the function (a sync body with
- # task execution enabled raises there). The stamp above is only
- # meaningful for a tool that was actually registered, so a
- # rejected call must not leave metadata behind: the caller's
- # function is then free to register on another server, whose
- # own task settings apply instead of this one's.
- if previous is _MISSING:
- del target.__fastmcp__ # type: ignore[attr-defined] # ty:ignore[unresolved-attribute]
- else:
- target.__fastmcp__ = previous # type: ignore[attr-defined] # ty:ignore[unresolved-attribute]
- raise
+ self.add_tool(fn)
return fn
if inspect.isroutine(name_or_fn):
diff --git a/fastmcp_slim/fastmcp/server/providers/local_provider/local_provider.py b/fastmcp_slim/fastmcp/server/providers/local_provider/local_provider.py
index 207fe61af..ebb662571 100644
--- a/fastmcp_slim/fastmcp/server/providers/local_provider/local_provider.py
+++ b/fastmcp_slim/fastmcp/server/providers/local_provider/local_provider.py
@@ -340,24 +340,6 @@ class LocalProvider(
raise KeyError(f"Prompt {name!r} version {version!r} not found")
self._remove_component(key)
- # =========================================================================
- # Capability queries
- # =========================================================================
-
- @property
- def may_serve_apps(self) -> bool:
- """Whether transforms or registered components may serve MCP App UI.
-
- Without transforms, the local registry can be inspected synchronously.
- Transforms may introduce apps, so retain the conservative declaration
- without running their asynchronous methods.
- """
- from fastmcp.apps.config import component_serves_app
-
- return bool(self._transforms) or any(
- component_serves_app(c) for c in self._components.values()
- )
-
# =========================================================================
# Provider interface implementation
# =========================================================================
diff --git a/fastmcp_slim/fastmcp/server/providers/wrapped_provider.py b/fastmcp_slim/fastmcp/server/providers/wrapped_provider.py
index 55ba1b052..b76e2f2d3 100644
--- a/fastmcp_slim/fastmcp/server/providers/wrapped_provider.py
+++ b/fastmcp_slim/fastmcp/server/providers/wrapped_provider.py
@@ -62,11 +62,6 @@ class _WrappedProvider(Provider):
def __repr__(self) -> str:
return f"_WrappedProvider({self._inner!r}, transforms={self._transforms!r})"
- @property
- def may_serve_apps(self) -> bool:
- """Whether transforms or the wrapped provider may serve MCP App UI."""
- return bool(self._transforms) or self._inner.may_serve_apps
-
# -------------------------------------------------------------------------
# Delegate to inner provider's public methods (which apply inner's transforms)
# -------------------------------------------------------------------------
diff --git a/fastmcp_slim/fastmcp/server/server.py b/fastmcp_slim/fastmcp/server/server.py
index c37bf7e0a..6272be09d 100644
--- a/fastmcp_slim/fastmcp/server/server.py
+++ b/fastmcp_slim/fastmcp/server/server.py
@@ -153,31 +153,6 @@ def _validation_error_summary(error: PydanticValidationError) -> dict[str, Any]:
return {"error_count": error.error_count(), "error_types": sorted(error_types)}
-def _validation_error_message(tool_name: str, error: PydanticValidationError) -> str:
- """Client-facing summary: which argument failed and why, nothing else.
-
- `str(PydanticValidationError)` embeds the exact pydantic version URL, the
- internal adapter name (`call[<tool>]`), and every submitted value with its
- inferred type. None of that helps a caller fix the call, and the first two
- are version/internal-name disclosure, so the message is rebuilt from the
- error details without the URL, context or inputs.
- """
- details = error.errors(
- include_url=False, include_context=False, include_input=False
- )
- lines = [
- (
- f"Invalid arguments for tool {tool_name!r}:"
- f" {len(details)} validation error{'s' if len(details) != 1 else ''}"
- )
- ]
- for detail in details:
- location = ".".join(str(part) for part in detail.get("loc", ()))
- message = detail.get("msg", "Invalid value")
- lines.append(f"- {location}: {message}" if location else f"- {message}")
- return "\n".join(lines)
-
-
def _version_request_meta(
version: VersionSpec | None,
) -> mcp_types.RequestParamsMeta | None:
@@ -1635,16 +1610,8 @@ class FastMCP(
name,
_validation_error_summary(cause),
)
- # Re-raise a rebuilt message: the original carries the
- # pydantic version URL and the adapter name into the
- # tool result the caller reads. Chaining from the
- # pydantic cause keeps the type and cause that
- # middleware, CodeMode and parent servers rely on.
- raise ValidationError(
- _validation_error_message(name, cause),
- log_level=logging.WARNING,
- ) from cause
- logger.warning("Invalid arguments for tool %r", name)
+ else:
+ logger.warning("Invalid arguments for tool %r", name)
raise
except FastMCPError as e:
logger.log(
diff --git a/fastmcp_slim/fastmcp/server/sessions.py b/fastmcp_slim/fastmcp/server/sessions.py
index 17298b28d..82ef061a2 100644
--- a/fastmcp_slim/fastmcp/server/sessions.py
+++ b/fastmcp_slim/fastmcp/server/sessions.py
@@ -41,6 +41,7 @@ import inspect
import json
import time
from collections.abc import Callable, Sequence
+from functools import lru_cache
from types import TracebackType
from typing import (
TYPE_CHECKING,
@@ -60,7 +61,6 @@ from uncalled_for import Provider as DependencyProvider
from fastmcp.exceptions import FastMCPError
from fastmcp.server.dependencies import get_access_token, get_server, get_session
from fastmcp.server.providers.base import Provider
-from fastmcp.utilities._callable_cache import cache_on_callable
from fastmcp.utilities.logging import get_logger
if TYPE_CHECKING:
@@ -339,7 +339,7 @@ class _SessionIdMarker:
SessionId = Annotated[str, _SessionIdMarker()]
-@cache_on_callable
+@lru_cache(maxsize=5000)
def session_id_parameter_names(fn: Callable[..., object]) -> tuple[str, ...]:
"""Names of a function's parameters annotated with `SessionId`.
diff --git a/fastmcp_slim/fastmcp/tools/function_tool.py b/fastmcp_slim/fastmcp/tools/function_tool.py
index d388b47e9..85bbfcf75 100644
--- a/fastmcp_slim/fastmcp/tools/function_tool.py
+++ b/fastmcp_slim/fastmcp/tools/function_tool.py
@@ -7,6 +7,7 @@ import inspect
import logging
from collections.abc import Callable
from dataclasses import dataclass, field
+from functools import lru_cache
from types import MethodType
from typing import (
Annotated,
@@ -37,7 +38,6 @@ from fastmcp.tools.base import (
ToolResult,
)
from fastmcp.tools.function_parsing import ParsedFunction
-from fastmcp.utilities._callable_cache import cache_on_callable
from fastmcp.utilities.async_utils import (
call_sync_fn_in_threadpool,
is_coroutine_function,
@@ -81,7 +81,7 @@ def _materialize_sync_generator(result: Any) -> Any:
return result
-@cache_on_callable
+@lru_cache(maxsize=5000)
def _wrap_body_errors(
fn: Callable[..., Any], *, materialize_generators: bool = False
) -> Callable[..., Any]:
diff --git a/fastmcp_slim/fastmcp/utilities/_callable_cache.py b/fastmcp_slim/fastmcp/utilities/_callable_cache.py
deleted file mode 100644
index dfeb35dee..000000000
--- a/fastmcp_slim/fastmcp/utilities/_callable_cache.py
+++ /dev/null
@@ -1,82 +0,0 @@
-"""Memoize callable metadata without making the callable process-owned."""
-
-import inspect
-import weakref
-from collections.abc import Callable
-from dataclasses import dataclass, field
-from functools import wraps
-from threading import RLock
-from typing import Any, ParamSpec, TypeVar
-
-P = ParamSpec("P")
-R = TypeVar("R")
-_CACHE_ATTRIBUTE = "__fastmcp_callable_cache__"
-
-
-@dataclass
-class _CallableCache:
- owner: weakref.ReferenceType[Any] | None
- values: dict[tuple[Any, ...], Any] = field(default_factory=dict)
-
- def __reduce__(self) -> tuple[type, tuple[None]]:
- # Tasks can pickle user functions. Metadata is process-local and may
- # contain weakrefs or adapters; a restored callable builds it afresh.
- return type(self), (None,)
-
-
-def cache_on_callable(build: Callable[P, R]) -> Callable[P, R]:
- """Cache on the first argument, or its instance for a bound method.
-
- Wrapper and TypeAdapter values can refer back to their callable, so a weak
- key alone cannot prevent retention. Owning the values on the callable makes
- the whole cycle collectable. Callables without a writable namespace or weak
- reference support are evaluated uncached instead of retained globally.
- """
- first_parameter = next(iter(inspect.signature(build).parameters))
- lock = RLock()
-
- @wraps(build)
- def cached(*args: P.args, **kwargs: P.kwargs) -> R:
- try:
- target = args[0]
- except IndexError:
- if first_parameter not in kwargs:
- return build(*args, **kwargs)
- target = kwargs[first_parameter]
- if inspect.ismethod(target):
- method = target.__func__
- owner = target.__self__
- else:
- method = None
- owner = target
- options = tuple((k, v) for k, v in kwargs.items() if k != first_parameter)
- key = (build, method, args[1:], options)
- try:
- namespace = vars(owner)
- owner_ref = weakref.ref(owner)
- except TypeError:
- return build(*args, **kwargs)
-
- with lock:
- cache = namespace.get(_CACHE_ATTRIBUTE)
- # Function wrappers often copy __dict__. Never reuse the source
- # function's metadata on a distinct wrapper with a different schema.
- if (
- not isinstance(cache, _CallableCache)
- or cache.owner is None
- or cache.owner() is not owner
- ):
- cache = _CallableCache(owner_ref)
- try:
- namespace[_CACHE_ATTRIBUTE] = cache
- except TypeError:
- return build(*args, **kwargs)
- if key in cache.values:
- return cache.values[key]
-
- value = build(*args, **kwargs)
- with lock:
- cache.values[key] = value
- return value
-
- return cached
diff --git a/fastmcp_slim/fastmcp/utilities/json_schema.py b/fastmcp_slim/fastmcp/utilities/json_schema.py
index fcec042eb..3a4079e41 100644
--- a/fastmcp_slim/fastmcp/utilities/json_schema.py
+++ b/fastmcp_slim/fastmcp/utilities/json_schema.py
@@ -80,7 +80,7 @@ def _resolve_local_ref(
"""
hops = _hops if _hops is not None else [0]
fragment = ref[1:]
- parts = unquote(fragment).lstrip("/").split("/") if fragment else []
+ parts = unquote(fragment.lstrip("/")).split("/") if fragment else []
node: Any = schema
for part in parts:
while node is not schema and isinstance(node, dict) and "$ref" in node:
@@ -120,7 +120,7 @@ def ref_target_name(
called ``Alias One`` as ``Alias%20One``, and neither decoded name appears
in the raw text.
"""
- parts = unquote(ref[1:]).lstrip("/").split("/")
+ parts = unquote(ref[1:].lstrip("/")).split("/")
for root in roots:
depth = len(root)
if parts[:depth] == list(root) and len(parts) > depth and parts[depth]:
@@ -783,9 +783,8 @@ def _single_pass_optimize(
# still pins the referenced $def as "used".
if prune_defs:
ref = node.get("$ref")
- if isinstance(ref, str) and ref.startswith("#"):
- # Decode the pointer before matching it: escaped,
- # percent-encoded (including `%24defs` and `%2F`), and
+ if isinstance(ref, str) and ref.startswith("#/$defs/"):
+ # Decode the pointer: escaped, percent-encoded, and
# sub-pointer references resolve to a definition whose
# name is not the raw text of the segment.
referenced_def = ref_target_name(ref)
diff --git a/fastmcp_slim/fastmcp/utilities/json_schema_type.py b/fastmcp_slim/fastmcp/utilities/json_schema_type.py
index c8ff8f34c..3a5220cfc 100644
--- a/fastmcp_slim/fastmcp/utilities/json_schema_type.py
+++ b/fastmcp_slim/fastmcp/utilities/json_schema_type.py
@@ -10,7 +10,7 @@ for validation with Pydantic. It supports:
- String constraints (minLength, maxLength, pattern)
- Array constraints (minItems, maxItems, uniqueItems)
- Object properties with defaults
-- References and recursive schemas (including sibling constraints on scalar references)
+- References and recursive schemas
- Enums and constants
- Union types
@@ -579,7 +579,6 @@ def _create_string_type(schema: Mapping[str, Any]) -> type | Annotated[Any, ...]
return base
annotated: Any = Annotated[str, StringConstraints(**constraints)]
- unsupported_pattern: str | None = None
if "pattern" in constraints:
try:
@@ -595,7 +594,6 @@ def _create_string_type(schema: Mapping[str, Any]) -> type | Annotated[Any, ...]
stacklevel=2,
)
pattern_field = Field(json_schema_extra={"x-unsupported-pattern": pattern})
- unsupported_pattern = pattern
if constraints:
annotated = Annotated[
str, StringConstraints(**constraints), pattern_field
@@ -605,19 +603,7 @@ def _create_string_type(schema: Mapping[str, Any]) -> type | Annotated[Any, ...]
if base is str:
return annotated
- constrained = _constrain_raw_string(base, **constraints)
- if unsupported_pattern is None:
- return constrained
- # The dropped pattern stays visible for the shapes a `format` maps to a
- # non-str type too, as the module docstring's third point promises.
- return _with_pattern_marker(constrained, unsupported_pattern)
-
-
-@lru_cache(maxsize=1024)
-def _with_pattern_marker(constrained: Any, pattern: str) -> Any:
- return Annotated[
- constrained, Field(json_schema_extra={"x-unsupported-pattern": pattern})
- ]
+ return _constrain_raw_string(base, **constraints)
@lru_cache(maxsize=1024)
@@ -1122,65 +1108,7 @@ def _convert_schema(
resolved_refs[ref] = _schema_to_type(
_resolve_ref(ref, schemas), schemas, resolving_refs | {ref}
)
- ref_type = resolved_refs[ref]
- # Draft 4-7 treat a $ref object as a reference only. In newer drafts,
- # constraints next to a reference also apply to that use of the type.
- if (
- schemas.get("$schema", "")
- .rstrip("#")
- .endswith(("/draft-04/schema", "/draft-06/schema", "/draft-07/schema"))
- ):
- return ref_type
- siblings = {
- k: v
- for k, v in schema.items()
- if k
- in (
- "type",
- "format",
- "const",
- "enum",
- "minLength",
- "maxLength",
- "pattern",
- "minimum",
- "maximum",
- "exclusiveMinimum",
- "exclusiveMaximum",
- "multipleOf",
- )
- }
- if not siblings:
- return ref_type
- resolved = _resolve_ref(ref, schemas)
- seen = {ref}
- while isinstance(resolved, Mapping) and "$ref" in resolved:
- next_ref = resolved["$ref"]
- if next_ref in seen:
- return ref_type
- seen.add(next_ref)
- resolved = _resolve_ref(next_ref, schemas)
- if not isinstance(resolved, Mapping) or resolved.get("type") not in (
- "string",
- "integer",
- "number",
- "boolean",
- "null",
- ):
- return ref_type
- sibling_type = _schema_to_type(
- {"type": resolved["type"], **siblings}, schemas, resolving_refs
- )
- sibling_adapter = TypeAdapter(cast(Any, sibling_type))
-
- def validate_siblings(value: Any) -> Any:
- # Validate the original input, before formats turn strings into
- # dates/URLs. Keep both validators intact: merging their metadata
- # could replace a stricter constraint on the referenced type.
- sibling_adapter.validate_python(value)
- return value
-
- return cast(type, Annotated[ref_type, BeforeValidator(validate_siblings)])
+ return resolved_refs[ref]
if "const" in schema:
return _create_enum(f"Const_{len(_classes)}", [schema["const"]])
diff --git a/fastmcp_slim/fastmcp/utilities/types.py b/fastmcp_slim/fastmcp/utilities/types.py
index ce2718a71..56d77e59c 100644
--- a/fastmcp_slim/fastmcp/utilities/types.py
+++ b/fastmcp_slim/fastmcp/utilities/types.py
@@ -5,7 +5,7 @@ import inspect
import mimetypes
import os
from collections.abc import Callable
-from functools import lru_cache, partial
+from functools import lru_cache
from pathlib import Path
from types import EllipsisType, UnionType
from typing import (
@@ -17,7 +17,6 @@ from typing import (
get_args,
get_origin,
get_type_hints,
- overload,
)
from urllib.parse import quote
@@ -26,8 +25,6 @@ from mcp_types import Annotations, ContentBlock, ModelPreferences, SamplingMessa
from pydantic import AnyUrl, BaseModel, ConfigDict, Field, TypeAdapter, UrlConstraints
from typing_extensions import TypeVar
-from fastmcp.utilities._callable_cache import cache_on_callable
-
T = TypeVar("T", default=Any)
# TODO(sdkv2): the SDK's `mcp.types.AnyFunction` alias was removed with the
@@ -55,37 +52,14 @@ def get_function_type_hints(fn: Callable[..., Any]) -> dict[str, Any]:
return get_type_hints(fn, include_extras=True)
-@overload
-def get_cached_typeadapter(cls: type[T]) -> TypeAdapter[T]: ...
-
-
-@overload
-def get_cached_typeadapter(cls: Any) -> TypeAdapter[Any]: ...
-
-
-def get_cached_typeadapter(cls: Any) -> TypeAdapter[Any]:
+@lru_cache(maxsize=5000)
+def get_cached_typeadapter(cls: T) -> TypeAdapter[T]:
"""
TypeAdapters are heavy objects, and in an application context we'd typically
create them once in a global scope and reuse them as often as possible.
However, this isn't feasible for user-generated functions. Instead, we use a
cache to minimize the cost of creating them as much as possible.
"""
- if inspect.isfunction(cls) or inspect.ismethod(cls) or isinstance(cls, partial):
- return _get_callable_typeadapter(cls)
- return _get_type_typeadapter(cls)
-
-
-@cache_on_callable
-def _get_callable_typeadapter(cls: T) -> TypeAdapter[T]:
- return _create_typeadapter(cls)
-
-
-@lru_cache(maxsize=5000)
-def _get_type_typeadapter(cls: T) -> TypeAdapter[T]:
- return _create_typeadapter(cls)
-
-
-def _create_typeadapter(cls: T) -> TypeAdapter[T]:
# For functions, process annotations to handle forward references and convert
# Annotated[Type, "string"] to Annotated[Type, Field(description="string")]
if inspect.isfunction(cls) or inspect.ismethod(cls):
diff --git a/fastmcp_slim/pyproject.toml b/fastmcp_slim/pyproject.toml
index 973a44a3c..ff2d94c2d 100644
--- a/fastmcp_slim/pyproject.toml
+++ b/fastmcp_slim/pyproject.toml
@@ -78,7 +78,6 @@ client = [
]
code-mode = ["pydantic-monty>=1.1,<2"]
jev = ["typesafe-sdk>=0.5.7"]
-keystone = ["keystoneauth1>=5.0.0"]
gemini = ["certifi>=2026.10.19", "google-genai>=1.18.0", "jsonref>=1.1.0"]
mcp = [
"exceptiongroup>=1.2.2",
diff --git a/fastmcp_tasks/fastmcp_tasks/components.py b/fastmcp_tasks/fastmcp_tasks/components.py
index e1bbe4a49..6dad5a629 100644
--- a/fastmcp_tasks/fastmcp_tasks/components.py
+++ b/fastmcp_tasks/fastmcp_tasks/components.py
@@ -22,13 +22,10 @@ because core still declares them.
from __future__ import annotations
-import functools
import inspect
import logging
-from collections.abc import Awaitable, Callable
from typing import TYPE_CHECKING, Any
-import mcp_types
from pydantic import ValidationError as PydanticValidationError
from fastmcp.exceptions import ValidationError
@@ -37,7 +34,7 @@ from fastmcp.prompts.function_prompt import FunctionPrompt
from fastmcp.resources.base import Resource
from fastmcp.resources.function_resource import FunctionResource
from fastmcp.resources.template import FunctionResourceTemplate, ResourceTemplate
-from fastmcp.tools.base import InputRequiredToolResult, Tool, ToolResult
+from fastmcp.tools.base import Tool
from fastmcp.tools.function_tool import (
FunctionTool,
_resolve_param_hints,
@@ -46,69 +43,14 @@ from fastmcp.tools.function_tool import (
from fastmcp.tools.tool_transform import TransformedTool
from fastmcp.utilities.components import FastMCPComponent
from fastmcp.utilities.types import get_cached_typeadapter
-from fastmcp_tasks.input_loop import _error_result, reentrant_task_fn
+from fastmcp_tasks.input_loop import reentrant_task_fn
if TYPE_CHECKING:
+ from collections.abc import Callable
+
from docket import Docket
from docket.execution import Execution
-logger = logging.getLogger(__name__)
-
-TASK_RESULT_ENVELOPE_KEY = "__fastmcp_task_result__"
-
-
-def task_result_to_wire(tool: Tool, raw_value: Any) -> dict[str, Any]:
- """Convert a task's return value into an inlined `CallToolResult` dict.
-
- A raised tool error arrives as the `is_error` `ToolResult` the reentrant
- wrapper built, so it is used directly and `isError` round-trips. A normal
- return goes through the tool's own result coercion.
- """
- if isinstance(raw_value, ToolResult):
- mcp_result = raw_value.to_mcp_result()
- else:
- mcp_result = tool.convert_result(raw_value).to_mcp_result()
- if isinstance(mcp_result, mcp_types.CallToolResult):
- call_result = mcp_result
- elif isinstance(mcp_result, tuple):
- content, structured_content = mcp_result
- call_result = mcp_types.CallToolResult(
- content=content, structured_content=structured_content
- )
- else:
- call_result = mcp_types.CallToolResult(content=mcp_result)
- return call_result.model_dump(by_alias=True, mode="json", exclude_none=True)
-
-
-def _store_task_result_with_component(
- tool: Tool, fn: Callable[..., Awaitable[Any]]
-) -> Callable[..., Awaitable[Any]]:
- """Persist the protocol result so later polling does not need the live Tool.
-
- The conversion runs in the worker, under the same masking policy as a
- raised tool error: a return value that fails to serialize becomes a masked
- `is_error` result rather than a failed task carrying the exception text.
- """
-
- @functools.wraps(fn)
- async def wrapper(*args: Any, **kwargs: Any) -> Any:
- result = await fn(*args, **kwargs)
- if isinstance(result, mcp_types.InputRequiredResult | InputRequiredToolResult):
- # Preserve the existing defensive failure in tasks_get for a guard
- # result that escaped the end-and-reenter loop.
- return result
- try:
- wire = task_result_to_wire(tool, result)
- except Exception as exc:
- logger.exception(
- "background task tool %r result conversion failed", tool.name
- )
- wire = task_result_to_wire(tool, _error_result(tool.name, exc))
- return {TASK_RESULT_ENVELOPE_KEY: wire}
-
- wrapper.__signature__ = inspect.signature(fn) # ty: ignore[unresolved-attribute]
- return wrapper
-
def register_component_with_docket(component: FastMCPComponent, docket: Docket) -> None:
"""Register a component's callable with Docket for background execution.
@@ -125,20 +67,16 @@ def register_component_with_docket(component: FastMCPComponent, docket: Docket)
# InputRequiredResult drives the reentrant in-task input cycle. The
# wrapper is signature-preserving, so Docket's dependency injection is
# unchanged for a body that never asks for input.
- task_fn = reentrant_task_fn(component.fn, component.name)
docket.register(
- _store_task_result_with_component(component, task_fn),
- names=[component.key],
+ reentrant_task_fn(component.fn, component.name), names=[component.key]
)
elif isinstance(component, Tool):
# Custom Tool subclasses route through the same wrapper so a raised
# error becomes a masked, completed `is_error` result β€” matching the
# synchronous `tools/call` path β€” rather than a Docket `FAILED` task
# that leaks the raw exception text past the server's masking policy.
- task_fn = reentrant_task_fn(component.run, component.name)
docket.register(
- _store_task_result_with_component(component, task_fn),
- names=[component.key],
+ reentrant_task_fn(component.run, component.name), names=[component.key]
)
elif isinstance(component, FunctionResource):
docket.register(component.fn, names=[component.key])
diff --git a/fastmcp_tasks/fastmcp_tasks/handlers.py b/fastmcp_tasks/fastmcp_tasks/handlers.py
index eca6317a4..1029a4a43 100644
--- a/fastmcp_tasks/fastmcp_tasks/handlers.py
+++ b/fastmcp_tasks/fastmcp_tasks/handlers.py
@@ -29,10 +29,9 @@ from mcp.shared.exceptions import MCPError
from mcp_types import INVALID_PARAMS
from fastmcp.exceptions import NotFoundError
-from fastmcp.tools.base import InputRequiredToolResult, Tool
+from fastmcp.tools.base import InputRequiredToolResult, Tool, ToolResult
from fastmcp.utilities.tasks import DEFAULT_POLL_INTERVAL_MS
from fastmcp.utilities.versions import VersionSpec
-from fastmcp_tasks.components import TASK_RESULT_ENVELOPE_KEY, task_result_to_wire
from fastmcp_tasks.context import get_task_scope, refresh_snapshot_ttl
from fastmcp_tasks.creation import (
TASK_MAPPING_TTL_BUFFER_SECONDS,
@@ -229,7 +228,23 @@ def _inline_result(tool: Tool, raw_value: Any) -> dict[str, Any]:
"Guard-pattern tasks are supported for function tools."
),
)
- return task_result_to_wire(tool, raw_value)
+ # A raised tool error arrives as an is_error ToolResult the wrapper built
+ # (end-and-reenter G2); use it directly so isError round-trips. A normal
+ # return is converted through the tool's own result coercion.
+ if isinstance(raw_value, ToolResult):
+ mcp_result = raw_value.to_mcp_result()
+ else:
+ mcp_result = tool.convert_result(raw_value).to_mcp_result()
+ if isinstance(mcp_result, mcp_types.CallToolResult):
+ call_tool_result = mcp_result
+ elif isinstance(mcp_result, tuple):
+ content, structured_content = mcp_result
+ call_tool_result = mcp_types.CallToolResult(
+ content=content, structured_content=structured_content
+ )
+ else:
+ call_tool_result = mcp_types.CallToolResult(content=mcp_result)
+ return call_tool_result.model_dump(by_alias=True, mode="json", exclude_none=True)
async def tasks_get(server: FastMCP, task_id: str) -> GetTaskResult:
@@ -284,17 +299,8 @@ async def tasks_get(server: FastMCP, task_id: str) -> GetTaskResult:
if outstanding:
return build("input_required", input_requests=outstanding)
raw_value = await execution.get_result(timeout=timedelta(seconds=0))
- if isinstance(raw_value, dict) and TASK_RESULT_ENVELOPE_KEY in raw_value:
- # New executions persist the converted protocol result alongside
- # the Docket result. Polling therefore remains possible after a
- # dynamic provider removes the Tool that produced it.
- result = raw_value[TASK_RESULT_ENVELOPE_KEY]
- else:
- # Retain compatibility with tasks created before this envelope was
- # introduced; their Docket result still needs the live Tool schema.
- tool = await _resolve_tool(server, base_task_key)
- result = _inline_result(tool, raw_value)
- return build("completed", result=result)
+ tool = await _resolve_tool(server, base_task_key)
+ return build("completed", result=_inline_result(tool, raw_value))
if execution.state == ExecutionState.FAILED:
message = "Task failed"
diff --git a/pyproject.toml b/pyproject.toml
index 650d93511..b00f61469 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -58,7 +58,6 @@ apps = ["fastmcp-slim[apps]=={{ version }}"]
azure = ["fastmcp-slim[azure]=={{ version }}"]
code-mode = ["fastmcp-slim[code-mode]=={{ version }}"]
jev = ["fastmcp-slim[jev]=={{ version }}"]
-keystone = ["fastmcp-slim[keystone]=={{ version }}"]
gemini = ["fastmcp-slim[gemini]=={{ version }}"]
openai = ["fastmcp-slim[openai]=={{ version }}"]
tasks = ["fastmcp-tasks=={{ version }}"]
@@ -86,7 +85,7 @@ exclude-newer-package = { authlib = false, certifi = false, fastmcp = false, fas
[dependency-groups]
dev = [
"dirty-equals>=0.9.0",
- "fastmcp[anthropic,apps,azure,code-mode,gemini,jev,keystone,openai,tasks]",
+ "fastmcp[anthropic,apps,azure,code-mode,gemini,jev,openai,tasks]",
"fastapi>=0.115.12",
"fastmcp-remote",
"opentelemetry-sdk>=1.20.0",
diff --git a/tests/client/group/test_client_group.py b/tests/client/group/test_client_group.py
index 10c3b3d8b..b826e8c18 100644
--- a/tests/client/group/test_client_group.py
+++ b/tests/client/group/test_client_group.py
@@ -425,56 +425,6 @@ async def test_explicit_list_tools_refreshes_past_client_response_cache():
assert result.data == "added"
-async def test_overlapping_refreshes_do_not_commit_out_of_order():
- server = FastMCP("refresh-order")
-
- @server.tool
- def original() -> str:
- return "original"
-
- client = Client(FastMCPTransport(server))
- group = ClientGroup({"server": client})
- first_fetched = asyncio.Event()
- release_first = asyncio.Event()
- original_list_tools = client.list_tools
- calls = 0
-
- async def gated_list_tools(*, cache_mode="use"):
- nonlocal calls
- calls += 1
- tools = await original_list_tools(cache_mode=cache_mode)
- if calls == 1:
- first_fetched.set()
- await release_first.wait()
- return tools
-
- async with group:
- with patch.object(client, "list_tools", side_effect=gated_list_tools):
- first_refresh = asyncio.create_task(group.list_tools())
- await asyncio.wait_for(first_fetched.wait(), timeout=1)
-
- @server.tool
- def added() -> str:
- return "added"
-
- # Give the newer refresh a chance to commit before the older one.
- second_refresh = asyncio.create_task(group.list_tools())
- await asyncio.wait({second_refresh}, timeout=0.5)
- release_first.set()
-
- first_tools, second_tools = await asyncio.gather(
- first_refresh, second_refresh
- )
-
- assert [tool.name for tool in first_tools] == ["server_original"]
- assert {tool.name for tool in second_tools} == {
- "server_original",
- "server_added",
- }
- route = await group.resolve_tool("server_added")
- assert route.upstream_name == "added"
-
-
async def test_group_context_is_reentrant():
client = Client(make_server("server"))
group = ClientGroup({"server": client})
diff --git a/tests/prompts/test_dual_alias.py b/tests/prompts/test_dual_alias.py
deleted file mode 100644
index 59aee46e3..000000000
--- a/tests/prompts/test_dual_alias.py
+++ /dev/null
@@ -1,30 +0,0 @@
-from pydantic import Field
-
-from fastmcp.prompts import Prompt
-from fastmcp.prompts.base import Message
-
-
-async def test_validation_alias_takes_precedence_over_alias():
- def total(
- numbers: list[int] = Field(alias="Numbers", validation_alias="Input"),
- ) -> str:
- return f"sum={sum(numbers)}"
-
- prompt = Prompt.from_function(total)
- assert prompt.arguments is not None
- assert [arg.name for arg in prompt.arguments] == ["Input"]
- result = await prompt.render({"Input": "[1, 2, 3]"})
- assert result.messages == [Message("sum=6")]
-
-
-async def test_validation_alias_takes_precedence_with_default():
- def total(
- numbers: list[int] = Field(
- default=[7], alias="Numbers", validation_alias="Input"
- ),
- ) -> str:
- return f"sum={sum(numbers)}"
-
- prompt = Prompt.from_function(total)
- assert (await prompt.render({"Input": "[1, 2]"})).messages == [Message("sum=3")]
- assert (await prompt.render({})).messages == [Message("sum=7")]
diff --git a/tests/prompts/test_prompt.py b/tests/prompts/test_prompt.py
index 1c7c72889..f33a5dd5d 100644
--- a/tests/prompts/test_prompt.py
+++ b/tests/prompts/test_prompt.py
@@ -1052,100 +1052,3 @@ class TestPromptCallableAndConcurrency:
prompt.render(),
)
assert all(r.messages == [Message("done")] for r in results)
-
-
-class TestPromptArgumentAliases:
- """Pydantic aliases on prompt parameters must work like tool aliases."""
-
- async def test_alias_is_advertised_and_renderable(self):
- def greet(name: Annotated[int, Field(alias="Name")]) -> str:
- return f"Hello, {name}!"
-
- prompt = Prompt.from_function(greet)
-
- assert prompt.arguments is not None
- assert [arg.name for arg in prompt.arguments] == ["Name"]
- assert prompt.arguments[0].required is True
-
- result = await prompt.render({"Name": "5"})
- assert result.messages == [Message("Hello, 5!")]
-
- async def test_alias_on_field_default_is_advertised_and_renderable(self):
- def greet(name: str = Field(alias="Name")) -> str:
- return f"Hello, {name}!"
-
- prompt = Prompt.from_function(greet)
-
- assert prompt.arguments is not None
- assert [arg.name for arg in prompt.arguments] == ["Name"]
- assert prompt.arguments[0].required is True
-
- result = await prompt.render({"Name": "Ada"})
- assert result.messages == [Message("Hello, Ada!")]
-
- async def test_alias_on_field_default_with_default_value(self):
- def greet(name: int = Field(default=7, alias="Name")) -> str:
- return f"Hello, {name}!"
-
- prompt = Prompt.from_function(greet)
-
- assert prompt.arguments is not None
- assert [arg.name for arg in prompt.arguments] == ["Name"]
- assert prompt.arguments[0].required is False
-
- result = await prompt.render({"Name": "9"})
- assert result.messages == [Message("Hello, 9!")]
-
- default_result = await prompt.render({})
- assert default_result.messages == [Message("Hello, 7!")]
-
- async def test_validation_alias_on_field_default_is_advertised_and_renderable(self):
- def greet(name: int = Field(default=7, validation_alias="Name")) -> str:
- return f"Hello, {name}!"
-
- prompt = Prompt.from_function(greet)
-
- assert prompt.arguments is not None
- assert [arg.name for arg in prompt.arguments] == ["Name"]
-
- result = await prompt.render({"Name": "9"})
- assert result.messages == [Message("Hello, 9!")]
-
- async def test_aliased_non_string_argument_accepts_json_string(self):
- def total(numbers: Annotated[list[int], Field(alias="Numbers")]) -> str:
- return f"sum={sum(numbers)}"
-
- prompt = Prompt.from_function(total)
-
- result = await prompt.render({"Numbers": "[1, 2, 3]"})
- assert result.messages == [Message("sum=6")]
-
- async def test_alias_with_injected_parameter(self):
- from fastmcp.dependencies import Depends
-
- def greet(
- name: Annotated[int, Field(alias="Name")],
- dependency: str = Depends(lambda: "injected"),
- ) -> str:
- return f"Hello, {name}! {dependency}"
-
- prompt = Prompt.from_function(greet)
-
- assert prompt.arguments is not None
- assert [arg.name for arg in prompt.arguments] == ["Name"]
-
- # Injected parameters remain unaddressable from the outside.
- result = await prompt.render({"Name": "5", "dependency": "override"})
- assert result.messages == [Message("Hello, 5! injected")]
-
- async def test_ordinary_argument_names_unchanged(self):
- def greet(name: int, greeting: str = "Hello") -> str:
- return f"{greeting}, {name}!"
-
- prompt = Prompt.from_function(greet)
-
- assert prompt.arguments is not None
- assert [arg.name for arg in prompt.arguments] == ["name", "greeting"]
-
- result = await prompt.render({"name": "5"})
- assert result.messages == [Message("Hello, 5!")]
diff --git a/tests/server/auth/providers/test_keystone.py b/tests/server/auth/providers/test_keystone.py
deleted file mode 100644
index 6be3ae427..000000000
--- a/tests/server/auth/providers/test_keystone.py
+++ /dev/null
@@ -1,493 +0,0 @@
-"""Tests for KeystoneTokenVerifier against a local fake of the Identity v3 API."""
-
-from __future__ import annotations
-
-import json
-import logging
-import threading
-from collections.abc import Iterator
-from datetime import UTC, datetime, timedelta
-from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
-from typing import Any
-
-import httpx2
-import pytest
-
-pytest.importorskip("keystoneauth1")
-
-from pydantic import SecretStr
-
-from fastmcp import Client, FastMCP
-from fastmcp.client.auth.bearer import BearerAuth
-from fastmcp.client.transports import StreamableHttpTransport
-from fastmcp.server.auth.providers.keystone import KeystoneTokenVerifier
-from fastmcp.server.dependencies import get_access_token
-from fastmcp.utilities.tests import run_server_async
-
-SERVICE_TOKEN = "service-token"
-PROJECT_ID = "project-1"
-
-
-def _timestamp(delta: timedelta) -> str:
- moment = datetime.now(UTC) + delta
- return moment.strftime("%Y-%m-%dT%H:%M:%S.000000Z")
-
-
-def user_token_body(**overrides: Any) -> dict[str, Any]:
- token: dict[str, Any] = {
- "methods": ["password"],
- "audit_ids": ["audit-1"],
- "expires_at": _timestamp(timedelta(hours=1)),
- "issued_at": _timestamp(timedelta(minutes=-1)),
- "user": {
- "id": "user-1",
- "name": "alice",
- "domain": {"id": "default", "name": "Default"},
- },
- "project": {
- "id": PROJECT_ID,
- "name": "demo",
- "domain": {"id": "default", "name": "Default"},
- },
- "roles": [{"id": "r1", "name": "member"}, {"id": "r2", "name": "reader"}],
- }
- token.update(overrides)
- return {"token": {key: value for key, value in token.items() if value is not None}}
-
-
-class FakeKeystone:
- """The parts of Keystone that keystoneauth1 touches to validate a token."""
-
- def __init__(self) -> None:
- self.tokens: dict[str, dict[str, Any]] = {}
- self.auth_requests: list[dict[str, Any]] = []
- self.validation_requests: list[dict[str, str]] = []
- self.validation_paths: list[str] = []
- self.validation_status: int | None = None
- self.url = ""
-
-
-def _handler_for(keystone: FakeKeystone) -> type[BaseHTTPRequestHandler]:
- class Handler(BaseHTTPRequestHandler):
- def log_message(self, format: str, *args: Any) -> None:
- pass
-
- def _send(
- self,
- status: int,
- body: dict[str, Any],
- headers: dict[str, str] | None = None,
- ) -> None:
- payload = json.dumps(body).encode()
- self.send_response(status)
- self.send_header("Content-Type", "application/json")
- self.send_header("Content-Length", str(len(payload)))
- for name, value in (headers or {}).items():
- self.send_header(name, value)
- self.end_headers()
- self.wfile.write(payload)
-
- def do_POST(self) -> None:
- length = int(self.headers["Content-Length"])
- request = json.loads(self.rfile.read(length))
- keystone.auth_requests.append(request)
- auth = request["auth"]
- if (
- "scope" not in auth
- and "application_credential" not in (auth["identity"]["methods"])
- ):
- # Real Keystone gives unscoped tokens no project or catalog.
- body = user_token_body(project=None, roles=None)
- self._send(201, body, {"X-Subject-Token": SERVICE_TOKEN})
- return
- body = user_token_body(
- catalog=[
- {
- "type": "identity",
- "name": "keystone",
- "id": "identity",
- "endpoints": [
- {
- "id": "public",
- "interface": "public",
- "region": "RegionOne",
- "region_id": "RegionOne",
- "url": f"{keystone.url}/v3",
- }
- ],
- }
- ]
- )
- self._send(201, body, {"X-Subject-Token": SERVICE_TOKEN})
-
- def do_GET(self) -> None:
- if self.path.split("?")[0].rstrip("/") == "/v3":
- self._send(
- 200,
- {
- "version": {
- "id": "v3.14",
- "status": "stable",
- "links": [
- {"rel": "self", "href": f"{keystone.url}/v3/"},
- ],
- }
- },
- )
- return
-
- keystone.validation_requests.append(dict(self.headers))
- keystone.validation_paths.append(self.path)
- if keystone.validation_status is not None:
- self._send(keystone.validation_status, {"error": {}})
- elif self.headers.get("X-Auth-Token") != SERVICE_TOKEN:
- self._send(401, {"error": {}})
- elif (token := self.headers["X-Subject-Token"]) in keystone.tokens:
- self._send(200, keystone.tokens[token])
- else:
- self._send(404, {"error": {}})
-
- return Handler
-
-
-def keystone() -> Iterator[FakeKeystone]:
- fake = FakeKeystone()
- server = ThreadingHTTPServer(("127.0.0.1", 0), _handler_for(fake))
- fake.url = f"http://127.0.0.1:{server.server_port}"
- thread = threading.Thread(target=server.serve_forever, args=(0.01,), daemon=True)
- thread.start()
- yield fake
- server.shutdown()
- server.server_close()
- thread.join()
-
-
-def make_verifier(keystone: FakeKeystone, **kwargs: Any) -> KeystoneTokenVerifier:
- return KeystoneTokenVerifier(
- auth_url=f"{keystone.url}/v3",
- username="mcp-service",
- password="secret",
- project_name="service",
- **kwargs,
- )
-
-
-class TestConfiguration:
- def test_requires_credentials(self):
- with pytest.raises(ValueError, match="either username and password"):
- KeystoneTokenVerifier(auth_url="http://keystone/v3")
-
- def test_rejects_both_credential_types(self):
- with pytest.raises(ValueError, match="either username and password"):
- KeystoneTokenVerifier(
- auth_url="http://keystone/v3",
- username="user",
- password="secret",
- application_credential_id="id",
- application_credential_secret="secret",
- )
-
- def test_rejects_username_without_password(self):
- with pytest.raises(ValueError, match="provided together"):
- KeystoneTokenVerifier(auth_url="http://keystone/v3", username="user")
-
- def test_rejects_unscoped_service_user(self):
- with pytest.raises(ValueError, match="project_name is required"):
- KeystoneTokenVerifier(
- auth_url="http://keystone/v3",
- username="user",
- password="secret",
- )
-
- def test_rejects_application_credential_without_secret(self):
- with pytest.raises(ValueError, match="provided together"):
- KeystoneTokenVerifier(
- auth_url="http://keystone/v3",
- application_credential_id="id",
- )
-
-
-class TestVerifyToken:
- async def test_valid_token(self, keystone: FakeKeystone):
- keystone.tokens["user-token"] = user_token_body()
-
- result = await make_verifier(keystone).verify_token("user-token")
-
- assert result is not None
- assert result.token == "user-token"
- assert result.client_id == "user-1"
- assert result.subject == "user-1"
- assert result.scopes == ["member", "reader"]
- assert result.expires_at is not None
- assert result.claims["project_id"] == PROJECT_ID
- assert result.claims["project_name"] == "demo"
- assert result.claims["username"] == "alice"
- assert result.claims["roles"] == ["member", "reader"]
-
- async def test_validation_call_shape(self, keystone: FakeKeystone):
- keystone.tokens["user-token"] = user_token_body()
-
- await make_verifier(keystone).verify_token("user-token")
-
- assert keystone.validation_paths == ["/v3/auth/tokens?nocatalog"]
- headers = keystone.validation_requests[0]
- assert headers["X-Auth-Token"] == SERVICE_TOKEN
- assert headers["X-Subject-Token"] == "user-token"
-
- @pytest.mark.parametrize("suffix", ["", "/", "/v3/"])
- async def test_auth_url_forms(self, keystone: FakeKeystone, suffix: str):
- keystone.tokens["user-token"] = user_token_body()
- verifier = KeystoneTokenVerifier(
- auth_url=f"{keystone.url}{suffix}",
- username="mcp-service",
- password="secret",
- project_name="service",
- )
-
- assert await verifier.verify_token("user-token") is not None
-
- async def test_service_user_auth_request(self, keystone: FakeKeystone):
- keystone.tokens["user-token"] = user_token_body()
- verifier = KeystoneTokenVerifier(
- auth_url=keystone.url,
- username="mcp-service",
- password=SecretStr("secret"),
- user_domain_name="services",
- project_name="service",
- project_domain_name="ops",
- )
-
- await verifier.verify_token("user-token")
-
- auth = keystone.auth_requests[0]["auth"]
- assert auth["identity"]["password"]["user"] == {
- "name": "mcp-service",
- "password": "secret",
- "domain": {"name": "services"},
- }
- assert auth["scope"]["project"] == {
- "name": "service",
- "domain": {"name": "ops"},
- }
-
- async def test_application_credential_auth_request(self, keystone: FakeKeystone):
- keystone.tokens["user-token"] = user_token_body()
- verifier = KeystoneTokenVerifier(
- auth_url=keystone.url,
- application_credential_id="cred-id",
- application_credential_secret=SecretStr("cred-secret"),
- )
-
- assert await verifier.verify_token("user-token") is not None
-
- identity = keystone.auth_requests[0]["auth"]["identity"]
- assert identity["methods"] == ["application_credential"]
- assert identity["application_credential"] == {
- "id": "cred-id",
- "secret": "cred-secret",
- }
-
- async def test_service_token_reused_between_validations(
- self, keystone: FakeKeystone
- ):
- keystone.tokens["user-token"] = user_token_body()
- verifier = make_verifier(keystone)
-
- await verifier.verify_token("user-token")
- await verifier.verify_token("user-token")
-
- assert len(keystone.auth_requests) == 1
- assert len(keystone.validation_requests) == 2
-
-
-class TestRejection:
- async def test_unknown_token(self, keystone: FakeKeystone):
- assert await make_verifier(keystone).verify_token("unknown") is None
-
- @pytest.mark.parametrize("token", ["", " "])
- async def test_empty_token_never_reaches_keystone(
- self, keystone: FakeKeystone, token: str
- ):
- assert await make_verifier(keystone).verify_token(token) is None
- assert keystone.auth_requests == []
-
- async def test_expired_token(self, keystone: FakeKeystone):
- keystone.tokens["user-token"] = user_token_body(
- expires_at=_timestamp(timedelta(minutes=-1))
- )
-
- assert await make_verifier(keystone).verify_token("user-token") is None
-
- @pytest.mark.parametrize("status", [401, 403, 500, 503])
- async def test_keystone_refusal_fails_closed(
- self, keystone: FakeKeystone, status: int
- ):
- keystone.tokens["user-token"] = user_token_body()
- keystone.validation_status = status
-
- assert await make_verifier(keystone).verify_token("user-token") is None
-
- @pytest.mark.parametrize("status", [401, 403, 500])
- async def test_service_side_failures_are_logged_as_warnings(
- self,
- keystone: FakeKeystone,
- status: int,
- caplog: pytest.LogCaptureFixture,
- ):
- keystone.validation_status = status
-
- with caplog.at_level(logging.WARNING, logger="fastmcp"):
- await make_verifier(keystone).verify_token("user-token")
-
- assert f"HTTP {status}" in caplog.text
-
- async def test_unknown_token_is_not_logged_as_a_warning(
- self, keystone: FakeKeystone, caplog: pytest.LogCaptureFixture
- ):
- with caplog.at_level(logging.WARNING, logger="fastmcp"):
- await make_verifier(keystone).verify_token("unknown")
-
- assert "Keystone" not in caplog.text
-
- async def test_unreachable_keystone_fails_closed(self):
- verifier = KeystoneTokenVerifier(
- auth_url="http://127.0.0.1:1/v3",
- username="mcp-service",
- password="secret",
- project_name="service",
- timeout_seconds=1,
- )
-
- assert await verifier.verify_token("user-token") is None
-
- async def test_malformed_response_fails_closed(self, keystone: FakeKeystone):
- keystone.tokens["user-token"] = {"token": {"user": {"id": "user-1"}}}
-
- assert await make_verifier(keystone).verify_token("user-token") is None
-
- @pytest.mark.parametrize(
- "rules",
- [[], [{"service": "compute", "method": "GET", "path": "/v2.1/servers"}]],
- )
- async def test_access_rule_restricted_token(
- self, keystone: FakeKeystone, rules: list[dict[str, str]]
- ):
- keystone.tokens["user-token"] = user_token_body(
- application_credential={
- "id": "cred-1",
- "name": "restricted",
- "restricted": True,
- "access_rules": rules,
- }
- )
-
- assert await make_verifier(keystone).verify_token("user-token") is None
-
- async def test_unrestricted_application_credential_token(
- self, keystone: FakeKeystone
- ):
- keystone.tokens["user-token"] = user_token_body(
- application_credential={
- "id": "cred-1",
- "name": "plain",
- "restricted": True,
- }
- )
-
- result = await make_verifier(keystone).verify_token("user-token")
-
- assert result is not None
- assert result.claims["application_credential_id"] == "cred-1"
-
-
-class TestRestrictions:
- async def test_required_scopes_match_roles(self, keystone: FakeKeystone):
- keystone.tokens["user-token"] = user_token_body()
-
- allowed = make_verifier(keystone, required_scopes=["member"])
- denied = make_verifier(keystone, required_scopes=["admin"])
-
- assert await allowed.verify_token("user-token") is not None
- assert await denied.verify_token("user-token") is None
-
- async def test_allowed_project(self, keystone: FakeKeystone):
- keystone.tokens["user-token"] = user_token_body()
-
- allowed = make_verifier(keystone, allowed_project_ids=[PROJECT_ID])
- denied = make_verifier(keystone, allowed_project_ids=["another-project"])
-
- assert await allowed.verify_token("user-token") is not None
- assert await denied.verify_token("user-token") is None
-
- async def test_project_allowlist_rejects_unscoped_token(
- self, keystone: FakeKeystone
- ):
- keystone.tokens["user-token"] = user_token_body(project=None, roles=None)
-
- open_verifier = make_verifier(keystone)
- strict_verifier = make_verifier(keystone, allowed_project_ids=[PROJECT_ID])
-
- unscoped = await open_verifier.verify_token("user-token")
- assert unscoped is not None
- assert unscoped.scopes == []
- assert await strict_verifier.verify_token("user-token") is None
-
-
-class TestCaching:
- async def test_disabled_by_default_so_revocation_is_immediate(
- self, keystone: FakeKeystone
- ):
- keystone.tokens["user-token"] = user_token_body()
- verifier = make_verifier(keystone)
-
- assert await verifier.verify_token("user-token") is not None
-
- del keystone.tokens["user-token"]
-
- assert await verifier.verify_token("user-token") is None
-
- async def test_enabled_cache_skips_keystone(self, keystone: FakeKeystone):
- keystone.tokens["user-token"] = user_token_body()
- verifier = make_verifier(keystone, cache_ttl_seconds=60)
-
- first = await verifier.verify_token("user-token")
- second = await verifier.verify_token("user-token")
-
- assert first is not None and first == second
- assert len(keystone.validation_requests) == 1
-
- async def test_rejections_are_not_cached(self, keystone: FakeKeystone):
- verifier = make_verifier(keystone, cache_ttl_seconds=60)
-
- assert await verifier.verify_token("user-token") is None
-
- keystone.tokens["user-token"] = user_token_body()
-
- assert await verifier.verify_token("user-token") is not None
-
-
-class TestEndToEnd:
- async def test_bearer_token_over_http(self, keystone: FakeKeystone):
- keystone.tokens["user-token"] = user_token_body()
- mcp = FastMCP("keystone", auth=make_verifier(keystone))
-
- @mcp.tool
- def whoami() -> dict[str, Any]:
- token = get_access_token()
- assert token is not None
- return {"user": token.client_id, "project": token.claims["project_id"]}
-
- async with run_server_async(mcp, transport="http") as url:
- transport = StreamableHttpTransport(url, auth=BearerAuth("user-token"))
- async with Client(transport) as client:
- result = await client.call_tool("whoami")
- assert result.data == {"user": "user-1", "project": PROJECT_ID}
-
- async with httpx2.AsyncClient() as http:
- response = await http.post(
- url,
- headers={"Authorization": "Bearer bad"},
- json={"jsonrpc": "2.0", "id": 1, "method": "ping"},
- )
- assert response.status_code == 401
diff --git a/tests/server/providers/local_provider_tools/test_decorator.py b/tests/server/providers/local_provider_tools/test_decorator.py
index 5a5f1bd17..3bf490d4f 100644
--- a/tests/server/providers/local_provider_tools/test_decorator.py
+++ b/tests/server/providers/local_provider_tools/test_decorator.py
@@ -10,7 +10,6 @@ from typing_extensions import TypedDict
from fastmcp import FastMCP
from fastmcp.exceptions import NotFoundError
from fastmcp.tools.base import Tool
-from fastmcp.tools.function_tool import ToolMeta
def _normalize_anyof_order(schema):
@@ -340,66 +339,3 @@ class TestToolDecorator:
tool = next(t for t in tools if t.name == "multiply")
assert tool.meta == meta_data
-
-
-class TestDecoratorMetadataNotLeftBehind:
- """A rejected registration must not stamp the caller's function.
-
- ``decorate_and_register`` writes ``__fastmcp__`` metadata onto the function
- before ``add_tool`` validates it. Validation is where a sync body with
- ``task=True`` is rejected, so without a rollback the rejected call
- leaves ``task=True`` behind and the same function can no longer be
- registered anywhere β€” including on a server that has no tasks at all.
- """
-
- async def test_rejected_registration_removes_the_stamp(self):
- mcp = FastMCP("tasks_on")
-
- def sync_tool(x: int = 1) -> str:
- return f"ok{x}"
-
- with pytest.raises(ValueError, match="Background tasks require async"):
- mcp.tool(sync_tool, task=True)
-
- assert not hasattr(sync_tool, "__fastmcp__")
-
- async def test_function_is_registerable_on_another_server_after_rejection(self):
- mcp = FastMCP("tasks_on")
-
- def sync_tool(x: int = 1) -> str:
- return f"ok{x}"
-
- with pytest.raises(ValueError, match="Background tasks require async"):
- mcp.tool(sync_tool, task=True)
-
- other = FastMCP("no_tasks")
- added = other.add_tool(sync_tool)
-
- assert added.task_config.mode == "forbidden"
-
- async def test_successful_registration_keeps_the_stamp(self):
- mcp = FastMCP("tasks_on")
-
- async def async_tool(x: int = 1) -> str:
- return f"ok{x}"
-
- mcp.tool(async_tool, task=True)
-
- assert hasattr(async_tool, "__fastmcp__")
- tool = await mcp.get_tool("async_tool")
- assert tool is not None
- assert tool.task_config.mode == "optional"
-
- async def test_pre_existing_stamp_survives_a_rejection(self):
- mcp = FastMCP("tasks_on")
-
- def sync_tool(x: int = 1) -> str:
- return f"ok{x}"
-
- sentinel = ToolMeta(task=True, name="pre-existing")
- sync_tool.__fastmcp__ = sentinel # type: ignore[attr-defined] # ty:ignore[unresolved-attribute]
-
- with pytest.raises(ValueError, match="Background tasks require async"):
- mcp.tool(sync_tool, task=True)
-
- assert sync_tool.__fastmcp__ is sentinel # type: ignore[attr-defined] # ty:ignore[unresolved-attribute]
diff --git a/tests/server/providers/local_provider_tools/test_parameters.py b/tests/server/providers/local_provider_tools/test_parameters.py
index e8dbc2166..13e5e060e 100644
--- a/tests/server/providers/local_provider_tools/test_parameters.py
+++ b/tests/server/providers/local_provider_tools/test_parameters.py
@@ -187,7 +187,7 @@ class TestToolParameters:
def analyze(x: int = Field()) -> None:
pass
- with pytest.raises(ValidationError, match="x: Missing required argument"):
+ with pytest.raises(ValidationError, match="missing"):
await mcp.call_tool("analyze", {})
async def test_literal_type_validation_error(self):
diff --git a/tests/server/test_callable_cache_lifetime.py b/tests/server/test_callable_cache_lifetime.py
deleted file mode 100644
index 8592e6c49..000000000
--- a/tests/server/test_callable_cache_lifetime.py
+++ /dev/null
@@ -1,219 +0,0 @@
-"""Callable caches must not outlive the user functions they accelerate."""
-
-import gc
-import weakref
-from collections.abc import Callable
-from functools import partial, wraps
-
-import cloudpickle
-import pytest
-from uncalled_for import annotations, introspection
-
-from fastmcp import Client, FastMCP
-from fastmcp.server.context import Context
-from fastmcp.server.dependencies import without_injected_parameters
-from fastmcp.server.sessions import session_id_parameter_names
-from fastmcp.tools.function_tool import _wrap_body_errors
-from fastmcp.utilities.types import get_cached_typeadapter
-
-
-class Payload:
- def __init__(self) -> None:
- self.items = list(range(100))
-
-
-def external_introspection_caches(monkeypatch: pytest.MonkeyPatch) -> None:
- # uncalled-for #21 independently retains callables in its introspection
- # (signature, parameter) and annotations (metadata, annotation) caches.
- # Isolate them so these regressions can verify FastMCP's ownership without
- # changing the dependency's process-wide cache objects in production.
- monkeypatch.setattr(introspection, "_signature_cache", {})
- monkeypatch.setattr(introspection, "_parameter_cache", {})
- monkeypatch.setattr(annotations, "_metadata_cache", {})
- monkeypatch.setattr(annotations, "_annotation_cache", {})
-
-
-def release_external_introspection() -> None:
- introspection._signature_cache.clear()
- introspection._parameter_cache.clear()
- annotations._metadata_cache.clear()
- annotations._annotation_cache.clear()
-
-
[email protected]("external_introspection_caches")
- "build",
- [
- get_cached_typeadapter,
- without_injected_parameters,
- _wrap_body_errors,
- session_id_parameter_names,
- ],
- ids=["type-adapter", "dependencies", "body-errors", "session-id"],
-)
-def test_callable_cache_does_not_retain_a_dropped_closure(
- build: Callable[..., object],
-) -> None:
- def populate() -> tuple[weakref.ReferenceType, weakref.ReferenceType]:
- payload = Payload()
-
- def tool(query: str) -> int:
- return len(payload.items)
-
- build(tool)
- return weakref.ref(tool), weakref.ref(payload)
-
- tool_ref, payload_ref = populate()
- release_external_introspection()
- gc.collect()
-
- assert tool_ref() is None
- assert payload_ref() is None
-
-
[email protected]("external_introspection_caches")
-async def test_dropped_servers_leave_no_fastmcp_owned_tool_closures() -> None:
- async def build_and_call() -> tuple[weakref.ReferenceType, weakref.ReferenceType]:
- server = FastMCP("temporary")
- payload = Payload()
-
- def search(query: str) -> int:
- return len(payload.items)
-
- server.tool(search)
- async with Client(server) as client:
- result = await client.call_tool("search", {"query": "q"})
- assert result.data == 100
- return weakref.ref(search), weakref.ref(payload)
-
- refs = [await build_and_call() for _ in range(3)]
- release_external_introspection()
- gc.collect()
-
- assert all(tool() is None and payload() is None for tool, payload in refs)
-
-
[email protected]("external_introspection_caches")
-def test_live_callable_keeps_its_cached_adapter() -> None:
- def tool(value: int) -> int:
- return value + 1
-
- adapter = get_cached_typeadapter(tool)
- assert get_cached_typeadapter(tool) is adapter
- assert adapter.validate_python({"value": 2}) == 3
- gc.collect()
- assert get_cached_typeadapter(tool) is adapter
- assert get_cached_typeadapter(int) is get_cached_typeadapter(int)
-
-
-def test_wrapped_function_does_not_reuse_the_source_functions_cache() -> None:
- def source() -> int:
- return 1
-
- original = _wrap_body_errors(source)
-
- @wraps(source)
- def wrapped() -> int:
- return 2
-
- distinct = _wrap_body_errors(wrapped)
- assert distinct is not original
- assert original() == 1
- assert distinct() == 2
- assert _wrap_body_errors(wrapped) is distinct
-
-
[email protected]("external_introspection_caches")
-def test_dependency_wrapper_caches_each_thread_option_separately() -> None:
- def tool(value: int, ctx: Context) -> int:
- return value
-
- threaded = without_injected_parameters(tool, run_in_thread=True)
- inline = without_injected_parameters(tool, run_in_thread=False)
- assert threaded is not inline
- assert without_injected_parameters(tool, run_in_thread=True) is threaded
- assert without_injected_parameters(fn=tool, run_in_thread=False) is inline
-
-
[email protected]("external_introspection_caches")
-def test_bound_method_cache_is_owned_by_its_instance() -> None:
- class Receiver:
- def __init__(self, value: int) -> None:
- self.value = value
-
- def tool(self, offset: int) -> int:
- return self.value + offset
-
- live = Receiver(10)
- adapter = get_cached_typeadapter(live.tool)
- assert get_cached_typeadapter(live.tool) is adapter
-
- def populate() -> weakref.ReferenceType:
- dropped = Receiver(20)
- other = get_cached_typeadapter(dropped.tool)
- assert other is not adapter
- assert other.validate_python({"offset": 1}) == 21
- _wrap_body_errors(dropped.tool)
- without_injected_parameters(dropped.tool)
- session_id_parameter_names(dropped.tool)
- return weakref.ref(dropped)
-
- dropped_ref = populate()
- release_external_introspection()
- gc.collect()
- assert dropped_ref() is None
- assert get_cached_typeadapter(live.tool) is adapter
- assert adapter.validate_python({"offset": 1}) == 11
-
-
[email protected]("external_introspection_caches")
-def test_method_without_instance_namespace_is_not_retained() -> None:
- class Receiver:
- __slots__ = ("__weakref__",)
-
- def tool(self, offset: int) -> int:
- return offset
-
- def populate() -> weakref.ReferenceType:
- receiver = Receiver()
- adapter = get_cached_typeadapter(receiver.tool)
- assert adapter.validate_python({"offset": 2}) == 2
- _wrap_body_errors(receiver.tool)
- without_injected_parameters(receiver.tool)
- session_id_parameter_names(receiver.tool)
- return weakref.ref(receiver)
-
- receiver_ref = populate()
- release_external_introspection()
- gc.collect()
- assert receiver_ref() is None
-
-
-def test_partial_adapter_is_reused_without_retaining_its_bound_payload() -> None:
- def tool(payload: Payload, offset: int) -> int:
- return len(payload.items) + offset
-
- def populate() -> tuple[weakref.ReferenceType, weakref.ReferenceType]:
- payload = Payload()
- bound = partial(tool, payload)
- adapter = get_cached_typeadapter(bound)
- assert get_cached_typeadapter(bound) is adapter
- assert adapter.validate_python({"offset": 2}) == 102
- return weakref.ref(bound), weakref.ref(payload)
-
- bound_ref, payload_ref = populate()
- gc.collect()
- assert bound_ref() is None
- assert payload_ref() is None
-
-
-def test_callable_cache_is_not_serialized_with_a_task_function() -> None:
- def tool(value: int) -> int:
- return value + 1
-
- get_cached_typeadapter(tool)
- restored = cloudpickle.loads(cloudpickle.dumps(tool))
- assert restored(2) == 3
- assert get_cached_typeadapter(restored).validate_python({"value": 2}) == 3
- assert get_cached_typeadapter(restored) is not get_cached_typeadapter(tool)
diff --git a/tests/server/test_input_validation.py b/tests/server/test_input_validation.py
index 2035a1eb9..97d5baff1 100644
--- a/tests/server/test_input_validation.py
+++ b/tests/server/test_input_validation.py
@@ -25,7 +25,6 @@ from pydantic import (
StrictInt,
field_validator,
)
-from pydantic import ValidationError as PydanticValidationError
from pydantic_core import PydanticCustomError
from fastmcp import Client, FastMCP
@@ -534,65 +533,6 @@ class TestEdgeCases:
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "6"
- async def test_client_error_omits_pydantic_details(self):
- """The caller gets the failing arguments, not the library internals."""
- mcp = FastMCP("TestServer")
-
- @mcp.tool
- def echo(message: str) -> str:
- return message
-
- async with Client(mcp) as client:
- result = await client.call_tool(
- "echo", {"message": 123, "extra": "x"}, raise_on_error=False
- )
-
- assert result.is_error
- text = result.content[0].text
- assert text.startswith("Invalid arguments for tool 'echo'")
- assert "- message: Input should be a valid string" in text
- assert "- extra: Unexpected keyword argument" in text
- for leaked in (
- "errors.pydantic.dev",
- "call[",
- "input_value",
- "input_type",
- "2 validation errors for",
- ):
- assert leaked not in text, leaked
-
- async def test_call_tool_raises_validation_error_with_rebuilt_message(self):
- """Direct callers still get ValidationError, chained from pydantic."""
- mcp = FastMCP("TestServer")
-
- @mcp.tool
- def echo(message: str) -> str:
- return message
-
- with pytest.raises(ValidationError) as exc_info:
- await mcp.call_tool("echo", {"message": 123})
-
- assert not isinstance(exc_info.value, ToolError)
- assert isinstance(exc_info.value.__cause__, PydanticValidationError)
- assert str(exc_info.value).startswith("Invalid arguments for tool 'echo'")
- assert "errors.pydantic.dev" not in str(exc_info.value)
-
- async def test_mounted_tool_error_names_parent_tool(self):
- child = FastMCP("Child")
-
- @child.tool
- def echo(message: str) -> str:
- return message
-
- parent = FastMCP("Parent")
- parent.mount(child, namespace="child")
-
- with pytest.raises(ValidationError) as exc_info:
- await parent.call_tool("child_echo", {"message": 123})
-
- assert isinstance(exc_info.value.__cause__, PydanticValidationError)
- assert str(exc_info.value).startswith("Invalid arguments for tool 'child_echo'")
-
class TestExpectedToolFailureLogging:
@pytest.mark.parametrize("mask_error_details", [False, True])
@@ -728,15 +668,8 @@ class TestExpectedToolFailureLogging:
)
assert result.is_error
- # The client learns which argument failed and why, but the message no
- # longer carries pydantic's version URL, the internal adapter name, or
- # the submitted values.
- client_message = str(result.content)
- assert "Invalid arguments for tool 'submit'" in client_message
- assert "errors.pydantic.dev" not in client_message
- assert "input_value" not in client_message
- assert "input_type" not in client_message
- assert "call[" not in client_message
+ # The client still gets its detailed validation error.
+ assert "PRIVATE" in str(result.content)
records = [r for r in caplog.records if r.name == "fastmcp.server.server"]
assert len(records) == 1
assert "PRIVATE" not in records[0].getMessage()
diff --git a/tests/server/test_pagination.py b/tests/server/test_pagination.py
index a1389ffb8..f4645fc2c 100644
--- a/tests/server/test_pagination.py
+++ b/tests/server/test_pagination.py
@@ -2,8 +2,6 @@
from __future__ import annotations
-from collections.abc import Iterator
-from itertools import count, cycle, repeat
from unittest.mock import call, patch
import mcp_types
@@ -139,12 +137,9 @@ class TestMalformedCursorParams:
with pytest.raises(ValueError, match="Invalid cursor"):
paginate_sequence([0, 1, 2], self._cursor(offset), page_size=2)
- @pytest.mark.parametrize("page_size", [None, 1])
- async def test_list_tools_reports_invalid_params(
- self, page_size: int | None
- ) -> None:
+ async def test_list_tools_reports_invalid_params(self) -> None:
"""The caller maps the ValueError to INVALID_PARAMS, so the client sees that."""
- server = FastMCP(list_page_size=page_size)
+ server = FastMCP(list_page_size=1)
@server.tool(name="one")
def one() -> int:
@@ -332,21 +327,9 @@ class TestServerPagination:
assert len(result3.tools) == 5
assert result3.next_cursor is None
- @pytest.mark.parametrize("page_size", [None, 10])
- @pytest.mark.parametrize(
- "method",
- [
- "list_tools_mcp",
- "list_resources_mcp",
- "list_resource_templates_mcp",
- "list_prompts_mcp",
- ],
- )
- async def test_invalid_cursor_returns_error(
- self, page_size: int | None, method: str
- ) -> None:
+ async def test_invalid_cursor_returns_error(self) -> None:
"""Server should return MCP error for invalid cursor."""
- server = FastMCP(list_page_size=page_size)
+ server = FastMCP(list_page_size=10)
@server.tool
def my_tool() -> str:
@@ -354,11 +337,10 @@ class TestServerPagination:
async with Client(server) as client:
with pytest.raises(MCPError) as exc:
- await getattr(client, method)(cursor="invalid!")
+ await client.list_tools_mcp(cursor="invalid!")
assert exc.value.error.code == -32602
- @pytest.mark.parametrize("cursor", [None, "", CursorState(offset=1).encode()])
- async def test_no_pagination_when_disabled(self, cursor: str | None) -> None:
+ async def test_no_pagination_when_disabled(self) -> None:
"""Without list_page_size, all items returned at once."""
server = FastMCP() # No pagination
@@ -369,7 +351,7 @@ class TestServerPagination:
return "ok"
async with Client(server) as client:
- result = await client.list_tools_mcp(cursor=cursor)
+ result = await client.list_tools_mcp()
assert len(result.tools) == 25
assert result.next_cursor is None
@@ -413,192 +395,257 @@ class TestPageSizeValidation:
FastMCP(list_page_size=-1)
-class RepeatingPageServer(FastMCP):
- """Return the first page with a test-controlled opaque cursor scheme."""
-
- def __init__(self, cursors: Iterator[str]) -> None:
- super().__init__()
- self.cursors = cursors
- self.received_cursors: list[str | None] = []
-
- def _next_cursor(self, params: mcp_types.PaginatedRequestParams | None) -> str:
- self.received_cursors.append(params.cursor if params is not None else None)
- return next(self.cursors)
-
- async def _on_list_tools(
- self, ctx: ServerRequestContext, params: mcp_types.PaginatedRequestParams | None
- ) -> mcp_types.ListToolsResult:
- result = await super()._on_list_tools(ctx, None)
- result.next_cursor = self._next_cursor(params)
- return result
-
- async def _on_list_resources(
- self, ctx: ServerRequestContext, params: mcp_types.PaginatedRequestParams | None
- ) -> mcp_types.ListResourcesResult:
- result = await super()._on_list_resources(ctx, None)
- result.next_cursor = self._next_cursor(params)
- return result
-
- async def _on_list_resource_templates(
- self, ctx: ServerRequestContext, params: mcp_types.PaginatedRequestParams | None
- ) -> mcp_types.ListResourceTemplatesResult:
- result = await super()._on_list_resource_templates(ctx, None)
- result.next_cursor = self._next_cursor(params)
- return result
-
- async def _on_list_prompts(
- self, ctx: ServerRequestContext, params: mcp_types.PaginatedRequestParams | None
- ) -> mcp_types.ListPromptsResult:
- result = await super()._on_list_prompts(ctx, None)
- result.next_cursor = self._next_cursor(params)
- return result
-
-
class TestPaginationCycleDetection:
"""Tests that auto-pagination terminates when the server returns cycling cursors."""
@pytest.mark.parametrize("next_cursor", ["stuck", ""])
async def test_tools_constant_cursor_terminates(self, next_cursor: str) -> None:
"""list_tools should stop if the server always returns the same cursor."""
- server = RepeatingPageServer(repeat(next_cursor))
+ server = FastMCP()
@server.tool
def my_tool() -> str:
return "ok"
async with Client(server) as client:
- tools = await client.list_tools()
+ original = client.list_tools_mcp
+
+ async def returning_constant_cursor(
+ *,
+ cursor: str | None = None,
+ cache_mode: str = "use",
+ ) -> mcp_types.ListToolsResult:
+ result = await original(cursor=cursor)
+ result.next_cursor = next_cursor
+ return result
+
+ with patch.object(
+ client, "list_tools_mcp", side_effect=returning_constant_cursor
+ ):
+ tools = await client.list_tools()
# Should get tools from first page + one duplicate (the retry before
# detecting the cycle), then stop.
assert len(tools) == 2
assert all(t.name == "my_tool" for t in tools)
- assert server.received_cursors == [None, next_cursor]
@pytest.mark.parametrize("next_cursor", ["stuck", ""])
async def test_prompts_constant_cursor_terminates(self, next_cursor: str) -> None:
"""list_prompts should stop if the server always returns the same cursor."""
- server = RepeatingPageServer(repeat(next_cursor))
+ server = FastMCP()
@server.prompt
def my_prompt() -> str:
return "text"
async with Client(server) as client:
- prompts = await client.list_prompts()
+ original = client.list_prompts_mcp
+
+ async def returning_constant_cursor(
+ *,
+ cursor: str | None = None,
+ cache_mode: str = "use",
+ ) -> mcp_types.ListPromptsResult:
+ result = await original(cursor=cursor)
+ result.next_cursor = next_cursor
+ return result
+
+ with patch.object(
+ client, "list_prompts_mcp", side_effect=returning_constant_cursor
+ ):
+ prompts = await client.list_prompts()
- assert len(prompts) == 2
- assert all(p.name == "my_prompt" for p in prompts)
- assert server.received_cursors == [None, next_cursor]
+ assert len(prompts) == 2
+ assert all(p.name == "my_prompt" for p in prompts)
@pytest.mark.parametrize("next_cursor", ["stuck", ""])
async def test_resources_constant_cursor_terminates(self, next_cursor: str) -> None:
"""list_resources should stop if the server always returns the same cursor."""
- server = RepeatingPageServer(repeat(next_cursor))
+ server = FastMCP()
@server.resource("test://r")
def my_resource() -> str:
return "data"
async with Client(server) as client:
- resources = await client.list_resources()
+ original = client.list_resources_mcp
+
+ async def returning_constant_cursor(
+ *,
+ cursor: str | None = None,
+ cache_mode: str = "use",
+ ) -> mcp_types.ListResourcesResult:
+ result = await original(cursor=cursor)
+ result.next_cursor = next_cursor
+ return result
- assert len(resources) == 2
- assert all(r.name == "my_resource" for r in resources)
- assert server.received_cursors == [None, next_cursor]
+ with patch.object(
+ client, "list_resources_mcp", side_effect=returning_constant_cursor
+ ):
+ resources = await client.list_resources()
+
+ assert len(resources) == 2
+ assert all(r.name == "my_resource" for r in resources)
@pytest.mark.parametrize("next_cursor", ["stuck", ""])
async def test_resource_templates_constant_cursor_terminates(
self, next_cursor: str
) -> None:
"""list_resource_templates should stop if the server always returns the same cursor."""
- server = RepeatingPageServer(repeat(next_cursor))
+ server = FastMCP()
@server.resource("test://items/{item_id}")
def my_template(item_id: str) -> str:
return item_id
async with Client(server) as client:
- templates = await client.list_resource_templates()
+ original = client.list_resource_templates_mcp
+
+ async def returning_constant_cursor(
+ *,
+ cursor: str | None = None,
+ cache_mode: str = "use",
+ ) -> mcp_types.ListResourceTemplatesResult:
+ result = await original(cursor=cursor)
+ result.next_cursor = next_cursor
+ return result
- assert len(templates) == 2
- assert server.received_cursors == [None, next_cursor]
+ with patch.object(
+ client,
+ "list_resource_templates_mcp",
+ side_effect=returning_constant_cursor,
+ ):
+ templates = await client.list_resource_templates()
+
+ assert len(templates) == 2
async def test_cycling_cursors_terminates(self) -> None:
"""list_tools should stop if the server cycles through a set of cursors."""
- server = RepeatingPageServer(cycle(["A", "B", "C"]))
+ server = FastMCP()
@server.tool
def my_tool() -> str:
return "ok"
async with Client(server) as client:
- tools = await client.list_tools()
+ call_count = 0
+ original = client.list_tools_mcp
+
+ async def returning_cycling_cursor(
+ *,
+ cursor: str | None = None,
+ cache_mode: str = "use",
+ ) -> mcp_types.ListToolsResult:
+ nonlocal call_count
+ result = await original(cursor=cursor)
+ # Cycle through A -> B -> C -> A
+ cursors = ["A", "B", "C"]
+ result.next_cursor = cursors[call_count % 3]
+ call_count += 1
+ return result
+
+ with patch.object(
+ client, "list_tools_mcp", side_effect=returning_cycling_cursor
+ ):
+ tools = await client.list_tools()
- # A, B, C seen, then A is a duplicate β†’ 4 calls total
- assert server.received_cursors == [None, "A", "B", "C"]
- assert len(tools) == 4
+ # A, B, C seen, then A is a duplicate β†’ 4 calls total
+ assert call_count == 4
+ assert len(tools) == 4
async def test_tools_raises_on_auto_pagination_limit(self) -> None:
"""list_tools should raise RuntimeError after exceeding max_pages."""
- server = RepeatingPageServer(f"cursor-{i}" for i in count(1))
+ server = FastMCP()
@server.tool
def my_tool() -> str:
return "ok"
async with Client(server) as client:
- with pytest.raises(RuntimeError, match="auto-pagination limit"):
- await client.list_tools(max_pages=5)
+ original = client.list_tools_mcp
+ call_count = 0
- assert server.received_cursors == [
- None,
- "cursor-1",
- "cursor-2",
- "cursor-3",
- "cursor-4",
- ]
+ async def returning_unique_cursor(
+ *,
+ cursor: str | None = None,
+ cache_mode: str = "use",
+ ) -> mcp_types.ListToolsResult:
+ nonlocal call_count
+ result = await original(cursor=cursor)
+ call_count += 1
+ result.next_cursor = f"cursor-{call_count}"
+ return result
+
+ with (
+ patch.object(
+ client, "list_tools_mcp", side_effect=returning_unique_cursor
+ ),
+ pytest.raises(RuntimeError, match="auto-pagination limit"),
+ ):
+ await client.list_tools(max_pages=5)
async def test_resources_raises_on_auto_pagination_limit(self) -> None:
"""list_resources should raise RuntimeError after exceeding max_pages."""
- server = RepeatingPageServer(f"cursor-{i}" for i in count(1))
+ server = FastMCP()
@server.resource("test://r")
def my_resource() -> str:
return "data"
async with Client(server) as client:
- with pytest.raises(RuntimeError, match="auto-pagination limit"):
+ original = client.list_resources_mcp
+ call_count = 0
+
+ async def returning_unique_cursor(
+ *,
+ cursor: str | None = None,
+ cache_mode: str = "use",
+ ) -> mcp_types.ListResourcesResult:
+ nonlocal call_count
+ result = await original(cursor=cursor)
+ call_count += 1
+ result.next_cursor = f"cursor-{call_count}"
+ return result
+
+ with (
+ patch.object(
+ client, "list_resources_mcp", side_effect=returning_unique_cursor
+ ),
+ pytest.raises(RuntimeError, match="auto-pagination limit"),
+ ):
await client.list_resources(max_pages=5)
- assert server.received_cursors == [
- None,
- "cursor-1",
- "cursor-2",
- "cursor-3",
- "cursor-4",
- ]
-
async def test_prompts_raises_on_auto_pagination_limit(self) -> None:
"""list_prompts should raise RuntimeError after exceeding max_pages."""
- server = RepeatingPageServer(f"cursor-{i}" for i in count(1))
+ server = FastMCP()
@server.prompt
def my_prompt() -> str:
return "text"
async with Client(server) as client:
- with pytest.raises(RuntimeError, match="auto-pagination limit"):
+ original = client.list_prompts_mcp
+ call_count = 0
+
+ async def returning_unique_cursor(
+ *,
+ cursor: str | None = None,
+ cache_mode: str = "use",
+ ) -> mcp_types.ListPromptsResult:
+ nonlocal call_count
+ result = await original(cursor=cursor)
+ call_count += 1
+ result.next_cursor = f"cursor-{call_count}"
+ return result
+
+ with (
+ patch.object(
+ client, "list_prompts_mcp", side_effect=returning_unique_cursor
+ ),
+ pytest.raises(RuntimeError, match="auto-pagination limit"),
+ ):
await client.list_prompts(max_pages=5)
- assert server.received_cursors == [
- None,
- "cursor-1",
- "cursor-2",
- "cursor-3",
- "cursor-4",
- ]
-
async def test_normal_pagination_unaffected(self) -> None:
"""Cycle detection should not interfere with normal pagination."""
server = FastMCP(list_page_size=10)
diff --git a/tests/skills/test_extension.py b/tests/skills/test_extension.py
index a67bd41d8..bb85ae327 100644
--- a/tests/skills/test_extension.py
+++ b/tests/skills/test_extension.py
@@ -272,10 +272,9 @@ async def test_get_unknown_skill_returns_invalid_params() -> None:
assert exc_info.value.error.code == INVALID_PARAMS
[email protected]("page_size", [None, 1])
-async def test_list_rejects_invalid_cursor(page_size: int | None) -> None:
+async def test_list_rejects_invalid_cursor() -> None:
server = make_server(
- MemorySkillProvider(listed=[make_skill("review")]), page_size=page_size
+ MemorySkillProvider(listed=[make_skill("review")]), page_size=1
)
async with skills_client(server) as client:
diff --git a/tests/tasks/server/test_task_result_persistence.py b/tests/tasks/server/test_task_result_persistence.py
deleted file mode 100644
index 58382fbd6..000000000
--- a/tests/tasks/server/test_task_result_persistence.py
+++ /dev/null
@@ -1,61 +0,0 @@
-"""A completed task's result is converted in the worker and stored with it.
-
-`tasks/get` must keep returning the result after the producing tool is removed,
-and a return value that fails to serialize must respect the server's masking
-policy rather than surface its exception text.
-"""
-
-from pydantic import BaseModel, field_serializer
-
-from fastmcp import FastMCP
-from fastmcp_tasks import TasksExtension
-from tests.tasks.task_helpers import get_task, run_task, running_task_server
-
-
-async def test_completed_result_survives_tool_removal():
- mcp = FastMCP("removal-server")
- mcp.add_extension(TasksExtension())
-
- @mcp.tool(task=True)
- async def removable_tool() -> str:
- return "done"
-
- async with running_task_server(mcp):
- final = await run_task(mcp, "removable_tool", {})
- assert final.status == "completed"
-
- mcp.local_provider.remove_tool("removable_tool")
- after = await get_task(mcp, final.task_id)
-
- assert after.status == "completed"
- assert after.result is not None
- assert after.result["content"][0]["text"] == "done"
-
-
-class Unserializable(BaseModel):
- value: int
-
- @field_serializer("value")
- def _fail(self, value: int) -> int:
- raise ValueError("synthetic serialization failure")
-
-
-async def test_result_conversion_failure_is_masked():
- mcp = FastMCP("mask-server", mask_error_details=True)
- mcp.add_extension(TasksExtension())
-
- @mcp.tool(task=True)
- async def bad_result() -> Unserializable:
- return Unserializable(value=1)
-
- async with running_task_server(mcp):
- final = await run_task(mcp, "bad_result", {})
-
- assert final.status == "completed"
- assert final.error is None
- assert final.status_message is None
- assert final.result is not None
- assert final.result["isError"] is True
- text = final.result["content"][0]["text"]
- assert "synthetic serialization failure" not in text
- assert "Error calling tool 'bad_result'" in text
diff --git a/tests/test_apps.py b/tests/test_apps.py
index 8dc189683..375db8e91 100644
--- a/tests/test_apps.py
+++ b/tests/test_apps.py
@@ -6,7 +6,6 @@ extension negotiation, and the ``Context.client_supports_extension`` method.
from __future__ import annotations
-from collections.abc import Sequence
from types import SimpleNamespace
from typing import Any, cast
@@ -27,15 +26,8 @@ from fastmcp.apps import (
ResourcePermissions,
app_config_to_meta_dict,
)
-from fastmcp.prompts.base import Prompt
-from fastmcp.resources import Resource, ResourceTemplate
from fastmcp.server.context import Context
-from fastmcp.server.extensions import ServerExtension
from fastmcp.server.low_level import client_supports_extension
-from fastmcp.server.providers import AggregateProvider, FastMCPProvider, Provider
-from fastmcp.server.providers.local_provider import LocalProvider
-from fastmcp.server.transforms import ToolTransform, Transform
-from fastmcp.tools.tool_transform import ToolTransformConfig
# ---------------------------------------------------------------------------
# Model serialization
@@ -410,7 +402,7 @@ class TestExtensionAdvertisement:
async def test_capabilities_include_ui_extension(self):
server = FastMCP("test")
- @server.tool(app=AppConfig(resource_uri="ui://dashboard"))
+ @server.tool
def my_tool() -> str:
return "hello"
@@ -443,258 +435,6 @@ class TestExtensionAdvertisement:
# ---------------------------------------------------------------------------
-class TestAppCapabilityGating:
- """The UI extension is advertised only while the server can serve an app.
-
- Every FastMCP server used to declare it, so a host that reads the
- declaration could offer a UI affordance with no app behind it.
- """
-
- @staticmethod
- def _computed_extensions(server: FastMCP) -> dict[str, Any]:
- """Extensions the server computes, before the SDK's version sieve."""
- capabilities = server._mcp_server.get_capabilities()
- return dict(capabilities.extensions or {})
-
- def test_plain_server_does_not_advertise(self):
- server = FastMCP("test")
-
- @server.tool
- def my_tool() -> str:
- return "hello"
-
- assert UI_EXTENSION_ID not in self._computed_extensions(server)
-
- def test_app_tool_advertises(self):
- server = FastMCP("test")
-
- @server.tool(app=AppConfig(resource_uri="ui://dashboard"))
- def dashboard() -> str:
- return "data"
-
- assert UI_EXTENSION_ID in self._computed_extensions(server)
-
- def test_ui_resource_advertises(self):
- server = FastMCP("test")
-
- @server.resource("ui://my-app/view.html")
- def view() -> str:
- return "<html></html>"
-
- assert UI_EXTENSION_ID in self._computed_extensions(server)
-
- def test_ui_resource_template_advertises(self):
- server = FastMCP("test")
-
- @server.resource("ui://my-app/{name}.html")
- def view(name: str) -> str:
- return f"<html>{name}</html>"
-
- assert UI_EXTENSION_ID in self._computed_extensions(server)
-
- def test_ui_resource_with_other_mime_type_advertises(self):
- """The scheme marks the app, not the MIME type.
-
- An app ships more than its HTML entry point β€” a stylesheet served from
- ``ui://`` is explicitly ``text/css``, and the server still has an app.
- """
- server = FastMCP("test")
-
- @server.resource("ui://my-app/view.css", mime_type="text/css")
- def stylesheet() -> str:
- return "body {}"
-
- assert UI_EXTENSION_ID in self._computed_extensions(server)
-
- def test_mounted_app_advertises(self):
- parent = FastMCP("parent")
-
- @parent.tool
- def plain() -> str:
- return "x"
-
- child = FastMCP("child")
-
- @child.tool(app=AppConfig(resource_uri="ui://child/app"))
- def child_app() -> str:
- return "y"
-
- parent.mount(child)
-
- assert UI_EXTENSION_ID in self._computed_extensions(parent)
-
- def test_mounted_plain_child_does_not_advertise(self):
- parent = FastMCP("parent")
- child = FastMCP("child")
-
- @child.tool
- def plain() -> str:
- return "x"
-
- parent.mount(child)
-
- assert UI_EXTENSION_ID not in self._computed_extensions(parent)
-
- def test_unenumerable_provider_stays_conservative(self):
- """A provider whose components we can't enumerate keeps the promise.
-
- Suppressing the declaration for a proxy, or for a third-party provider,
- could hide an app that does exist β€” worse than a spurious promise.
- """
-
- class OpaqueProvider(Provider):
- pass
-
- server = FastMCP("test")
- server.add_provider(OpaqueProvider())
-
- assert UI_EXTENSION_ID in self._computed_extensions(server)
-
- def test_registered_extension_does_not_imply_apps(self):
- """An unrelated extension advertises itself without dragging UI along."""
-
- class Other(ServerExtension):
- identifier = "com.example/other"
-
- def settings(self) -> dict[str, Any]:
- return {"version": "1"}
-
- server = FastMCP("test")
- server.add_extension(Other())
-
- extensions = self._computed_extensions(server)
- assert extensions["com.example/other"] == {"version": "1"}
- assert UI_EXTENSION_ID not in extensions
-
- async def test_modern_client_sees_no_ui_extension_without_apps(self):
- """The reporter's observation, on the era that carries extensions."""
- server = FastMCP("test")
-
- @server.tool
- def my_tool() -> str:
- return "hello"
-
- async with Client(server, mode="auto") as client:
- extensions = client.server_capabilities.extensions or {}
- assert UI_EXTENSION_ID not in extensions
-
- @pytest.mark.parametrize(
- "scope", ["server", "local", "wrapped", "aggregate", "fastmcp"]
- )
- async def test_tool_transform_apps_advertised(self, scope: str):
- server = FastMCP("test")
- local = LocalProvider()
-
- @local.tool
- def plain() -> str:
- return "hello"
-
- transform = ToolTransform(
- {"plain": ToolTransformConfig(meta={"ui": {"resourceUri": "ui://app"}})}
- )
- if scope == "server":
- server.add_provider(local)
- server.add_transform(transform)
- else:
- provider: Provider = local
- if scope == "aggregate":
- provider = AggregateProvider([local])
- elif scope == "fastmcp":
- child = FastMCP("child")
- child.add_provider(local)
- provider = FastMCPProvider(child)
- if scope == "wrapped":
- provider = provider.wrap_transform(transform)
- else:
- provider.add_transform(transform)
- server.add_provider(provider)
-
- async with Client(server, mode="auto") as client:
- tools = await client.list_tools()
- assert len(tools) == 1
- assert tools[0].meta is not None
- assert tools[0].meta["ui"]["resourceUri"] == "ui://app"
- assert UI_EXTENSION_ID in (client.server_capabilities.extensions or {})
-
- async def test_custom_transform_non_tool_apps_advertised(self):
- class AddAppMetadata(Transform):
- async def list_resources(
- self, resources: Sequence[Resource]
- ) -> Sequence[Resource]:
- return [
- r.model_copy(update={"meta": {"ui": {"prefersBorder": True}}})
- for r in resources
- ]
-
- async def list_resource_templates(
- self, templates: Sequence[ResourceTemplate]
- ) -> Sequence[ResourceTemplate]:
- return [
- t.model_copy(update={"meta": {"ui": {"prefersBorder": True}}})
- for t in templates
- ]
-
- async def list_prompts(self, prompts: Sequence[Prompt]) -> Sequence[Prompt]:
- return [
- p.model_copy(update={"meta": {"ui": {"resourceUri": "ui://app"}}})
- for p in prompts
- ]
-
- server = FastMCP("test")
-
- @server.resource("data://plain")
- def plain_resource() -> str:
- return "hello"
-
- @server.resource("data://plain/{name}")
- def plain_template(name: str) -> str:
- return name
-
- @server.prompt
- def plain_prompt() -> str:
- return "hello"
-
- server.add_transform(AddAppMetadata())
- async with Client(server, mode="auto") as client:
- resources = await client.list_resources()
- templates = await client.list_resource_templates()
- prompts = await client.list_prompts()
- for components in (resources, templates, prompts):
- assert len(components) == 1
- assert components[0].meta is not None
- assert "ui" in components[0].meta
- assert UI_EXTENSION_ID in (client.server_capabilities.extensions or {})
-
- async def test_runtime_app_reaches_only_new_sessions(self):
- """Capabilities are fixed at initialize, so a runtime app waits for a reconnect."""
- server = FastMCP("test")
-
- def register_app() -> None:
- @server.tool(app=AppConfig(resource_uri="ui://late/app"))
- def late_app() -> str:
- return "late"
-
- async with Client(server, mode="auto") as client:
- register_app()
- assert "late_app" in {t.name for t in await client.list_tools()}
- assert UI_EXTENSION_ID not in (client.server_capabilities.extensions or {})
-
- async with Client(server, mode="auto") as client:
- assert UI_EXTENSION_ID in (client.server_capabilities.extensions or {})
-
- async def test_explicit_extension_advertises_without_apps(self):
- """Servers that add apps at runtime can keep the declaration up front."""
-
- class AppsExtension(ServerExtension):
- identifier = UI_EXTENSION_ID
-
- server = FastMCP("test")
- server.add_extension(AppsExtension())
-
- async with Client(server, mode="auto") as client:
- assert UI_EXTENSION_ID in (client.server_capabilities.extensions or {})
-
-
class TestContextClientSupportsExtension:
async def test_returns_false_when_no_session(self):
server = FastMCP("test")
diff --git a/tests/tools/tool_transform/test_args.py b/tests/tools/tool_transform/test_args.py
index a916797f4..047ac655d 100644
--- a/tests/tools/tool_transform/test_args.py
+++ b/tests/tools/tool_transform/test_args.py
@@ -579,7 +579,7 @@ class TestRenamedArgValidationErrors:
self, find_tool: Tool, arguments: dict[str, Any], location: str
):
error = await call_tool_error(find_tool, arguments)
- assert error.splitlines()[1].startswith(f"- {location}: ")
+ assert error.splitlines()[1] == location
async def test_error_uses_outermost_name_when_chained(self, find_tool: Tool):
lookup_tool = Tool.from_tool(
@@ -588,13 +588,12 @@ class TestRenamedArgValidationErrors:
transform_args={"max_results": ArgTransform(name="limit")},
)
error = await call_tool_error(lookup_tool, {"query": "x", "limit": 50})
- assert error.splitlines()[1].startswith("- limit: ")
+ assert error.splitlines()[1] == "limit"
async def test_error_unchanged_without_renames(self):
search_tool = Tool.from_function(search)
find_tool = Tool.from_tool(search_tool, name="find")
arguments = {"q": "x", "n": 50}
- find_error = await call_tool_error(find_tool, arguments)
- search_error = await call_tool_error(search_tool, arguments)
- # The header names the called tool; the error details are identical.
- assert find_error.splitlines()[1:] == search_error.splitlines()[1:]
+ assert await call_tool_error(find_tool, arguments) == await call_tool_error(
+ search_tool, arguments
+ )
diff --git a/tests/tools/tool_transform/test_schemas.py b/tests/tools/tool_transform/test_schemas.py
index 7373f8faa..09d70df78 100644
--- a/tests/tools/tool_transform/test_schemas.py
+++ b/tests/tools/tool_transform/test_schemas.py
@@ -3,7 +3,6 @@ from typing import Annotated, Any
import pytest
from dirty_equals import IsList
from inline_snapshot import snapshot
-from jsonschema import Draft202012Validator
from mcp_types import TextContent
from pydantic import BaseModel, Field, TypeAdapter
@@ -20,28 +19,6 @@ def get_property(tool: Tool, name: str) -> dict[str, Any]:
return tool.parameters["properties"][name]
-def test_renaming_tool_preserves_encoded_parameter_reference():
- def echo(value: str) -> str:
- return value
-
- schema = {
- "type": "object",
- "properties": {"value": {"$ref": "#/$defs/Display~1name"}},
- "required": ["value"],
- "$defs": {"Display/name": {"type": "string", "minLength": 1}},
- }
- parent = FunctionTool(name="echo", parameters=schema, fn=echo)
-
- transformed = Tool.from_tool(parent, name="renamed_echo")
- advertised_schema = transformed.to_mcp_tool().input_schema
-
- assert advertised_schema["$defs"] == schema["$defs"]
- validator = Draft202012Validator(advertised_schema)
- assert validator.is_valid({"value": "hello"})
- assert not validator.is_valid({"value": ""})
- assert parent.parameters == schema
-
-
@pytest.fixture
def add_tool() -> FunctionTool:
def add(
diff --git a/tests/utilities/json_schema_type/test_reference_constraints.py b/tests/utilities/json_schema_type/test_reference_constraints.py
deleted file mode 100644
index 05d066d04..000000000
--- a/tests/utilities/json_schema_type/test_reference_constraints.py
+++ /dev/null
@@ -1,123 +0,0 @@
-"""Constraints on uses of shared scalar definitions."""
-
-from copy import deepcopy
-from datetime import datetime
-
-import pytest
-from pydantic import TypeAdapter, ValidationError
-
-from fastmcp.utilities.json_schema_type import (
- json_schema_to_type,
- json_schema_to_type_adapter,
-)
-
-
[email protected]("cached", [False, True])
- ("definition", "siblings", "valid", "invalid"),
- [
- ({"type": "string"}, {"maxLength": 3}, "abc", "abcd"),
- ({"type": "string", "minLength": 3}, {"minLength": 1}, "abc", "ab"),
- ({"type": "string", "pattern": "^a"}, {"pattern": "z$"}, "az", "ab"),
- ({"type": "string", "pattern": "^a"}, {"pattern": "z$"}, "az", "bz"),
- ({"type": "integer", "minimum": 0}, {"maximum": 5}, 5, 6),
- ({"type": "integer", "minimum": 5}, {"minimum": 0}, 5, 4),
- ({"type": "number", "maximum": 5}, {"maximum": 10}, 5, 6),
- ({"type": "integer", "multipleOf": 2}, {"multipleOf": 3}, 6, 4),
- ({"type": "integer", "multipleOf": 2}, {"multipleOf": 3}, 6, 3),
- ({"type": "integer"}, {"enum": [2, 3]}, 2, 4),
- ({"type": "integer", "minimum": 5}, {"enum": [2, 6]}, 6, 2),
- ({"type": "integer"}, {"const": 2}, 2, 3),
- ({"type": "number"}, {"type": "integer"}, 2, 2.5),
- (
- {"type": "string", "format": "date-time"},
- {"maxLength": 20},
- "2026-10-26T00:00:00Z",
- "2026-10-26T00:00:00.000000+00:00",
- ),
- ],
-)
-def test_scalar_reference_constraints(definition, siblings, valid, invalid, cached):
- schema = {"$defs": {"Value": definition}, "$ref": "#/$defs/Value", **siblings}
- original = deepcopy(schema)
- adapter = (
- json_schema_to_type_adapter(schema)
- if cached
- else TypeAdapter(json_schema_to_type(schema))
- )
- result = adapter.validate_python(valid)
- if definition.get("format") == "date-time":
- assert isinstance(result, datetime)
- else:
- assert result == valid
- with pytest.raises(ValidationError):
- adapter.validate_python(invalid)
- assert schema == original
-
-
[email protected]("model", [False, True])
-def test_reference_constraints_do_not_change_other_uses(model):
- schema = {
- "type": "object",
- "properties": {
- "short": {"$ref": "#/$defs/Text", "maxLength": 2},
- "long": {"$ref": "#/$defs/Text", "minLength": 3},
- "plain": {"$ref": "#/$defs/Text"},
- },
- "required": ["short", "long", "plain"],
- "$defs": {"Text": {"type": "string", "minLength": 1}},
- }
- if model:
- schema["additionalProperties"] = True
- adapter = TypeAdapter(json_schema_to_type(schema))
- valid = {"short": "ab", "long": "abcd", "plain": "anything"}
- result = adapter.validate_python(valid)
- assert result.short == "ab"
- assert result.long == "abcd"
- assert result.plain == "anything"
- for changed in ({"short": "abc"}, {"long": "ab"}, {"plain": ""}):
- with pytest.raises(ValidationError):
- adapter.validate_python({**valid, **changed})
-
-
-def test_constraints_on_transitive_scalar_reference():
- schema = {
- "$defs": {
- "Text": {"type": "string", "minLength": 2},
- "Alias": {"$ref": "#/$defs/Text"},
- },
- "$ref": "#/$defs/Alias",
- "maxLength": 3,
- }
- adapter = TypeAdapter(json_schema_to_type(schema))
- assert adapter.validate_python("abc") == "abc"
- for value in ("a", "abcd"):
- with pytest.raises(ValidationError):
- adapter.validate_python(value)
-
-
-def test_reference_annotations_do_not_wrap_plain_type():
- schema = {
- "$defs": {"Text": {"type": "string"}},
- "$ref": "#/$defs/Text",
- "description": "A shared string",
- }
- assert json_schema_to_type(schema) is str
-
-
- "draft",
- [
- "http://json-schema.org/draft-04/schema#",
- "http://json-schema.org/draft-06/schema#",
- "http://json-schema.org/draft-07/schema#",
- ],
-)
-def test_legacy_reference_siblings_remain_ignored(draft):
- schema = {
- "$schema": draft,
- "definitions": {"Text": {"type": "string"}},
- "$ref": "#/definitions/Text",
- "maxLength": 1,
- }
- assert TypeAdapter(json_schema_to_type(schema)).validate_python("long") == "long"
diff --git a/tests/utilities/test_json_schema_references.py b/tests/utilities/test_json_schema_references.py
deleted file mode 100644
index d483099e9..000000000
--- a/tests/utilities/test_json_schema_references.py
+++ /dev/null
@@ -1,67 +0,0 @@
-import pytest
-
-from fastmcp.utilities.json_schema import compress_schema
-
-
-class TestDefinitionReferences:
- @pytest.mark.parametrize(
- ("definition_name", "ref"),
- [
- ("Name", "#/$defs/Name"),
- ("Name/part", "#/$defs/Name~1part"),
- ("Name~part", "#/$defs/Name~0part"),
- ("Name~1part", "#/$defs/Name~01part"),
- ("Name part", "#/$defs/Name%20part"),
- ("Name%2Fpart", "#/$defs/Name%252Fpart"),
- ("Name", "#/%24defs/Name"),
- ("Name", "#%2F$defs%2FName"),
- ],
- )
- def test_keeps_encoded_definition_references(self, definition_name: str, ref: str):
- schema = {
- "type": "object",
- "properties": {"value": {"$ref": "#/$defs/Alias"}},
- "$defs": {
- "Alias": {"$ref": ref},
- definition_name: {"type": "string"},
- "Unused": {"type": "number"},
- },
- }
-
- result = compress_schema(schema)
-
- assert result["$defs"] == {
- "Alias": {"$ref": ref},
- definition_name: {"type": "string"},
- }
- assert result["properties"] == schema["properties"]
-
- @pytest.mark.parametrize(
- "ref",
- [
- "#/$defs/Envelope/properties/name",
- "#/$defs/Envelope%2Fproperties%2Fname",
- ],
- )
- def test_keeps_owner_of_nested_definition_reference(self, ref: str):
- envelope = {
- "type": "object",
- "properties": {"name": {"$ref": "#/$defs/Leaf"}},
- }
- schema = {
- "type": "object",
- "properties": {"value": {"$ref": ref}},
- "$defs": {
- "Envelope": envelope,
- "Leaf": {"type": "string"},
- "name": {"type": "number"},
- },
- }
-
- result = compress_schema(schema)
-
- assert result["$defs"] == {
- "Envelope": envelope,
- "Leaf": {"type": "string"},
- }
- assert result["properties"] == schema["properties"]
diff --git a/tests/utilities/test_json_schema_type_unsupported_pattern.py b/tests/utilities/test_json_schema_type_unsupported_pattern.py
deleted file mode 100644
index 494555e8c..000000000
--- a/tests/utilities/test_json_schema_type_unsupported_pattern.py
+++ /dev/null
@@ -1,93 +0,0 @@
-"""`x-unsupported-pattern` marks a dropped pattern for every string shape.
-
-The module docstring promises that a pattern Pydantic cannot compile is
-preserved in the type metadata as `x-unsupported-pattern`. That held for a plain
-string; a string whose `format` maps to another Python type took a different
-return path and lost the marker.
-"""
-
-from __future__ import annotations
-
-import warnings
-from typing import Any
-
-import pytest
-from pydantic import TypeAdapter, ValidationError
-
-from fastmcp.utilities.json_schema_type import json_schema_to_type
-
-UNSUPPORTED = "(?!x)"
-
-
-def _type(schema: dict[str, Any]) -> Any:
- with warnings.catch_warnings():
- warnings.simplefilter("ignore")
- return json_schema_to_type(schema)
-
-
-def _json_schema(schema: dict[str, Any]) -> dict[str, Any]:
- return TypeAdapter(_type(schema)).json_schema()
-
-
-def test_pattern_marker_without_a_format() -> None:
- assert (
- _json_schema({"type": "string", "pattern": UNSUPPORTED})[
- "x-unsupported-pattern"
- ]
- == UNSUPPORTED
- )
-
-
-def test_pattern_marker_with_a_string_format() -> None:
- assert (
- _json_schema({"type": "string", "format": "uuid", "pattern": UNSUPPORTED})[
- "x-unsupported-pattern"
- ]
- == UNSUPPORTED
- )
-
-
-def test_pattern_marker_with_a_non_string_format() -> None:
- assert (
- _json_schema({"type": "string", "format": "date-time", "pattern": UNSUPPORTED})[
- "x-unsupported-pattern"
- ]
- == UNSUPPORTED
- )
-
-
-def test_supported_pattern_leaves_no_marker() -> None:
- schema = _json_schema(
- {"type": "string", "format": "uuid", "pattern": "^[0-9a-f-]+$"}
- )
-
- assert "x-unsupported-pattern" not in schema
-
-
-def test_dropping_the_pattern_keeps_the_other_constraints() -> None:
- schema = {
- "type": "string",
- "format": "uuid",
- "minLength": 40,
- "pattern": UNSUPPORTED,
- }
-
- with pytest.raises(ValidationError):
- TypeAdapter(_type(schema)).validate_python(
- "2f1a4e6c-0f4d-4b7a-9c2e-8d1b3a5c7e9f"
- )
-
-
-def test_format_with_unsupported_pattern_keeps_type_identity() -> None:
- """Repeated conversions return the same type.
-
- `_constrain_raw_string` is cached so a schema seen on every call maps to one
- type; wrapping its result in an uncached `Annotated[..., Field(...)]` broke
- that identity for the `format` route.
- """
- schema = {"type": "string", "format": "uuid", "pattern": "(?!x)"}
-
- first = json_schema_to_type(schema)
- second = json_schema_to_type(schema)
-
- assert first is second
diff --git a/uv.lock b/uv.lock
index 8a2bb4fb0..5cab794ae 100644
--- a/uv.lock
+++ b/uv.lock
@@ -822,9 +822,6 @@ gemini = [
jev = [
{ name = "fastmcp-slim", extra = ["jev"] },
]
-keystone = [
- { name = "fastmcp-slim", extra = ["keystone"] },
-]
openai = [
{ name = "fastmcp-slim", extra = ["openai"] },
]
@@ -836,7 +833,7 @@ tasks = [
dev = [
{ name = "dirty-equals" },
{ name = "fastapi" },
- { name = "fastmcp", extra = ["anthropic", "apps", "azure", "code-mode", "gemini", "jev", "keystone", "openai", "tasks"] },
+ { name = "fastmcp", extra = ["anthropic", "apps", "azure", "code-mode", "gemini", "jev", "openai", "tasks"] },
{ name = "fastmcp-remote" },
{ name = "inline-snapshot", extra = ["dirty-equals"] },
{ name = "ipython" },
@@ -871,17 +868,16 @@ requires-dist = [
{ name = "fastmcp-slim", extras = ["code-mode"], marker = "extra == 'code-mode'", editable = "fastmcp_slim" },
{ name = "fastmcp-slim", extras = ["gemini"], marker = "extra == 'gemini'", editable = "fastmcp_slim" },
{ name = "fastmcp-slim", extras = ["jev"], marker = "extra == 'jev'", editable = "fastmcp_slim" },
- { name = "fastmcp-slim", extras = ["keystone"], marker = "extra == 'keystone'", editable = "fastmcp_slim" },
{ name = "fastmcp-slim", extras = ["openai"], marker = "extra == 'openai'", editable = "fastmcp_slim" },
{ name = "fastmcp-tasks", marker = "extra == 'tasks'", editable = "fastmcp_tasks" },
]
-provides-extras = ["anthropic", "apps", "azure", "code-mode", "gemini", "jev", "keystone", "openai", "tasks"]
+provides-extras = ["anthropic", "apps", "azure", "code-mode", "gemini", "jev", "openai", "tasks"]
[package.metadata.requires-dev]
dev = [
{ name = "dirty-equals", specifier = ">=0.9.0" },
{ name = "fastapi", specifier = ">=0.115.12" },
- { name = "fastmcp", extras = ["anthropic", "apps", "azure", "code-mode", "gemini", "jev", "keystone", "openai", "tasks"], editable = "." },
+ { name = "fastmcp", extras = ["anthropic", "apps", "azure", "code-mode", "gemini", "jev", "openai", "tasks"], editable = "." },
{ name = "fastmcp-remote", editable = "fastmcp_remote" },
{ name = "inline-snapshot", extras = ["dirty-equals"], specifier = ">=0.27.2" },
{ name = "ipython", specifier = ">=8.12.3" },
@@ -964,9 +960,6 @@ gemini = [
jev = [
{ name = "typesafe-sdk" },
]
-keystone = [
- { name = "keystoneauth1" },
-]
mcp = [
{ name = "exceptiongroup" },
{ name = "httpx2" },
@@ -1032,7 +1025,6 @@ requires-dist = [
{ name = "jsonref", marker = "extra == 'server'", specifier = ">=1.1.0" },
{ name = "jsonschema", marker = "extra == 'server'", specifier = ">=4.20.0" },
{ name = "jsonschema-path", marker = "extra == 'server'", specifier = ">=0.3.4" },
- { name = "keystoneauth1", marker = "extra == 'keystone'", specifier = ">=5.0.0" },
{ name = "mcp", marker = "extra == 'client'", specifier = ">=2.3.0,<3.0.0" },
{ name = "mcp", marker = "extra == 'mcp'", specifier = ">=2.3.0,<3.0.0" },
{ name = "mcp", marker = "extra == 'server'", specifier = ">=2.3.0,<3.0.0" },
@@ -1066,7 +1058,7 @@ requires-dist = [
{ name = "watchfiles", marker = "extra == 'server'", specifier = ">=1.0.0" },
{ name = "websockets", marker = "extra == 'server'", specifier = ">=15.0.1" },
]
-provides-extras = ["anthropic", "apps", "azure", "client", "code-mode", "gemini", "jev", "keystone", "mcp", "openai", "server"]
+provides-extras = ["anthropic", "apps", "azure", "client", "code-mode", "gemini", "jev", "mcp", "openai", "server"]
[[package]]
name = "fastmcp-tasks"
@@ -1357,15 +1349,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/d9/33/1f075bf72b0b747cb3288d011319aaf64083cf2efef8354174e3ed4540e2/ipython_pygments_lexers-1.1.1-py3-none-any.whl", hash = "sha256:a9462224a505ade19a605f71f8fa63c2048833ce50abc86768a0d81d876dc81c", size = 8074, upload-time = "2025-01-17T11:24:33.271Z" },
]
-[[package]]
-name = "iso8601"
-version = "2.1.0"
-source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/b9/f3/ef59cee614d5e0accf6fd0cbba025b93b272e626ca89fb70a3e9187c5d15/iso8601-2.1.0.tar.gz", hash = "sha256:6b1d3829ee8921c4301998c909f7829fa9ed3cbdac0d3b16af2d743aed1ba8df", size = 6522, upload-time = "2023-10-03T00:25:39.317Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/6c/0c/f37b6a241f0759b7653ffa7213889d89ad49a2b76eb2ddf3b57b2738c347/iso8601-2.1.0-py3-none-any.whl", hash = "sha256:aac4145c4dcb66ad8b648a02830f5e2ff6c24af20f4f482689be402db2429242", size = 7545, upload-time = "2023-10-03T00:25:32.304Z" },
-]
-
[[package]]
name = "jedi"
version = "0.20.0"
@@ -1527,22 +1510,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/41/45/1a4ed80516f02155c51f51e8cedb3c1902296743db0bbc66608a0db2814f/jsonschema_specifications-2025.9.1-py3-none-any.whl", hash = "sha256:98802fee3a11ee76ecaca44429fda8a41bff98b00a0f2838151b113f210cc6fe", size = 18437, upload-time = "2025-09-08T01:34:57.871Z" },
]
-[[package]]
-name = "keystoneauth1"
-version = "5.18.1"
-source = { registry = "https://pypi.org/simple" }
-dependencies = [
- { name = "iso8601" },
- { name = "os-service-types" },
- { name = "requests" },
- { name = "stevedore" },
- { name = "typing-extensions" },
-]
-sdist = { url = "https://files.pythonhosted.org/packages/04/af/268e14554c6bd4a2614872fb2b8431e466ce01415a9783b260ce7fb7ae5c/keystoneauth1-5.18.1.tar.gz", hash = "sha256:8970f9d103f335c39151366d70c001d1bb99b00d73845f03d47825e8dc35ff78", size = 319181, upload-time = "2026-10-12T09:04:48.166Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/78/24/38ccf4476c81435c834d4791804099f305b91087fad171ac17d18fc84ca9/keystoneauth1-5.18.1-py3-none-any.whl", hash = "sha256:2440f1f29e4aaaaf771893e8da7c098ca27548210dc13e964b53fd2aaaedd6b0", size = 367402, upload-time = "2026-10-12T09:04:46.753Z" },
-]
-
[[package]]
name = "loq"
version = "0.1.0"
@@ -1837,19 +1804,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" },
]
-[[package]]
-name = "os-service-types"
-version = "1.9.0"
-source = { registry = "https://pypi.org/simple" }
-dependencies = [
- { name = "pbr" },
- { name = "typing-extensions" },
-]
-sdist = { url = "https://files.pythonhosted.org/packages/86/ae/fe7ac23155ae0b4b9779e06e9c5bb4070f2315dc4ca886a88fa3230d344b/os_service_types-1.9.0.tar.gz", hash = "sha256:1f2e5fb71d1f6f4ff31d8992674f2368465bc2f25cd94018015c3ddbfc5c617f", size = 28087, upload-time = "2026-08-04T13:07:43.171Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/e3/79/f8ae99ae9bb54cd63e7ab89251b2a4ff4ff07f02847403948b6a6f50f816/os_service_types-1.9.0-py3-none-any.whl", hash = "sha256:f268545c896434177bf55c43f7d5129e65210d5d456df3f00a1c9832a71c3a4b", size = 25282, upload-time = "2026-08-04T13:07:42.258Z" },
-]
-
[[package]]
name = "packaging"
version = "26.2"
@@ -1886,18 +1840,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/f1/d9/7fb5aa316bc299258e68c73ba3bddbc499654a07f151cba08f6153988714/pathspec-1.1.1-py3-none-any.whl", hash = "sha256:a00ce642f577bf7f473932318056212bc4f8bfdf53128c78bbd5af0b9b20b189", size = 57328, upload-time = "2026-04-27T01:46:07.06Z" },
]
-[[package]]
-name = "pbr"
-version = "7.1.3"
-source = { registry = "https://pypi.org/simple" }
-dependencies = [
- { name = "setuptools" },
-]
-sdist = { url = "https://files.pythonhosted.org/packages/6b/8d/ce438c28c7958e33184e8ac851ea2225b47a41e5e9e708fa3bddba631135/pbr-7.1.3.tar.gz", hash = "sha256:9a4a85b84e906337708009af0b5f5cdabeeb72d4dc213c9e97974da54fd9acc5", size = 140100, upload-time = "2026-10-07T10:38:15.526Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/bb/a2/79a926b7ab54b247c3419bfa00cfbeb78ad495d21c6d787c978c6261623d/pbr-7.1.3-py2.py3-none-any.whl", hash = "sha256:6583e878a1d97cb135fdc509811f31b9235905cde8d4dacd3dbadf9efc45d745", size = 136717, upload-time = "2026-10-07T10:38:14.069Z" },
-]
-
[[package]]
name = "pdbpp"
version = "0.12.1"
@@ -3015,15 +2957,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/57/c9/e69b1ff4c8b69093ef08b8919ab767af0569666865b39c30a8795d88d3c6/ruff-0.15.22-py3-none-win_arm64.whl", hash = "sha256:e1168075b72158510839f250027659cdd78476f40507dd517892304c41318661", size = 11298172, upload-time = "2026-07-16T15:14:10.51Z" },
]
-[[package]]
-name = "setuptools"
-version = "84.2.1"
-source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/70/b3/c19426f783614d625699a4b247faf628ea9ab1db228674491767b417f9e1/setuptools-84.2.1.tar.gz", hash = "sha256:3ff8b3b5492a0aa66960f4419365a86b84e013070d4313e4d4a6894f5d64d6bc", size = 1230289, upload-time = "2026-10-20T19:01:37.742Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/ef/55/6dc6d6bb953bdfc52519a0059592c52b6e3b8ad51cf8256dffceb55b0610/setuptools-84.2.1-py3-none-any.whl", hash = "sha256:ca140b45d5325a9478f880e351484f62fef15f336462e449ca0c03c873d589c2", size = 876263, upload-time = "2026-10-20T19:01:35.678Z" },
-]
-
[[package]]
name = "shellingham"
version = "1.5.4"
@@ -3082,15 +3015,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/ec/bb/2799cc2ede3ed41131f8975621e7213dfc7ef4acbbaadfa440f32500c370/starlette-1.3.1-py3-none-any.whl", hash = "sha256:c7372aae11c3c3f26a42df7bd626cec2f47d03483d261d369516a615a53714c6", size = 73632, upload-time = "2026-06-12T09:23:10.017Z" },
]
-[[package]]
-name = "stevedore"
-version = "5.9.1"
-source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/db/a1/3b8ed9c1fc3aa6eebb57732d924ddaa0500ecc3b638d0454816320994383/stevedore-5.9.1.tar.gz", hash = "sha256:e97a2667923efda926e8713fde6a73616df68210a3cbc6f02b48967b676fd8bf", size = 518111, upload-time = "2026-08-20T15:25:14.754Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/c5/97/bba6e7ec2f5498b9dcb7b1b6400086b80ae5a8ebaff4b25e8c8add75f439/stevedore-5.9.1-py3-none-any.whl", hash = "sha256:5c8ff3a9f336cc1a06ac0f597bc79d11a2f950bfd32e290ca56b5a301fafafbf", size = 54931, upload-time = "2026-08-20T15:25:13.602Z" },
-]
-
[[package]]
name = "tenacity"
version = "9.1.4"