π The fast, Pythonic way to build MCP servers and clients.
Support Annotated dependencies (#6378)
nate nowack7f3192e56bf9
diff --git a/.github/workflows/run-downstream-smoke.yml b/.github/workflows/run-downstream-smoke.ymlindex 4122e71b9..d14912078 100644--- a/.github/workflows/run-downstream-smoke.yml+++ b/.github/workflows/run-downstream-smoke.yml@@ -181,6 +181,7 @@ jobs:--exclude-newer-package authlib=false \--exclude-newer-package certifi=false \--exclude-newer-package pydocket=2026-10-06T00:00:00Z \+ --exclude-newer-package uncalled-for=false \--with fastmcp@file://$(ls $GITHUB_WORKSPACE/dist/fastmcp-4*.whl) \--with fastmcp-slim@file://$(ls $GITHUB_WORKSPACE/dist/fastmcp_slim-*.whl) \--with fastmcp-tasks@file://$(ls $GITHUB_WORKSPACE/dist/fastmcp_tasks-*.whl)" >> "$GITHUB_ENV"diff --git a/docs/servers/dependency-injection.mdx b/docs/servers/dependency-injection.mdxindex 784d5f0fd..e3f83f0d1 100644--- a/docs/servers/dependency-injection.mdx+++ b/docs/servers/dependency-injection.mdx@@ -352,6 +352,33 @@ async def fetch_data(return f"User {user_id} fetching '{query}' from {config['api_url']}"```+### Annotated Dependencies++A dependency can also go in the parameter's annotation instead of its default. The parameter keeps its declared type, so a type checker sees `config` as a `dict` rather than a `Depends` object, and a direct call that forgets it fails with a `TypeError` instead of running with the marker. An alias carries the type and the dependency together, so every tool that needs the config reads the same declaration.++```python+from typing import Annotated++from fastmcp import FastMCP+from fastmcp.dependencies import Depends++mcp = FastMCP("Annotated Deps Demo")+++def get_config() -> dict:+ return {"api_url": "https://api.example.com", "timeout": 30}+++Config = Annotated[dict, Depends(get_config)]+++async def fetch_data(query: str, config: Config) -> str:+ return f"Fetching '{query}' from {config['api_url']}"+```++As with a default, the parameter stays out of the tool's schema. Use one form per parameter: combining an annotated dependency with a `Depends()` default raises `TypeError`.+### CachingDependencies are cached per-request. If multiple parameters use the same dependency, or if nested dependencies share a common dependency, it's resolved once and the same instance is reused.diff --git a/fastmcp_slim/fastmcp/server/dependencies.py b/fastmcp_slim/fastmcp/server/dependencies.pyindex 0f4980cfd..e32686714 100644--- a/fastmcp_slim/fastmcp/server/dependencies.py+++ b/fastmcp_slim/fastmcp/server/dependencies.py@@ -33,6 +33,7 @@ from starlette.requests import Requestfrom uncalled_for import (CycleError,Dependency,+ Provider,frame_scope,get_dependency_parameters,)@@ -372,6 +373,13 @@ def transform_context_annotations(fn: Callable[..., Any]) -> Callable[..., Any]:except Exception:type_hints = getattr(fn, "__annotations__", {})+ # A parameter that already names its dependency, as a default or as+ # `Annotated` provider metadata, keeps it.+ try:+ declared = set(get_dependency_parameters(fn))+ except TypeError:+ declared = set()+# First pass: identify which params need transformationparams_to_transform: set[str] = set()optional_context_params: set[str] = set()@@ -379,7 +387,7 @@ def transform_context_annotations(fn: Callable[..., Any]) -> Callable[..., Any]:optional_session_params: set[str] = set()for name, param in sig.parameters.items():annotation = type_hints.get(name, param.annotation)- if isinstance(param.default, Dependency):+ if name in declared or isinstance(param.default, Dependency):continueif is_class_member_of_type(annotation, Context):params_to_transform.add(name)@@ -940,7 +948,7 @@ async def resolve_dependencies(# so that get_dependency_parameters can detect them.-class _CurrentContext(Dependency["Context"]):+class _CurrentContext(Provider["Context"]):"""Async context manager for Context dependency.Returns the active context from _current_context (normal MCP request).@@ -988,7 +996,7 @@ class _CurrentContext(Dependency["Context"]):await ctx.__aexit__(exc_type, exc_value, traceback)-class _OptionalCurrentContext(Dependency["Context | None"]):+class _OptionalCurrentContext(Provider["Context | None"]):"""Context dependency that returns None instead of raising when no contextis active. Used for ``ctx: Context = None`` parameter patterns.@@ -1048,7 +1056,7 @@ def OptionalCurrentContext() -> Context | None:return cast("Context | None", _OptionalCurrentContext())-class _CurrentFastMCP(Dependency["FastMCP"]):+class _CurrentFastMCP(Provider["FastMCP"]):"""Async context manager for FastMCP server dependency."""async def __aenter__(self) -> FastMCP:@@ -1088,7 +1096,7 @@ def CurrentFastMCP() -> FastMCP:return cast(FastMCP, _CurrentFastMCP())-class _CurrentRequest(Dependency[Request]):+class _CurrentRequest(Provider[Request]):"""Async context manager for HTTP Request dependency."""async def __aenter__(self) -> Request:@@ -1129,7 +1137,7 @@ def CurrentRequest() -> Request:return cast(Request, _CurrentRequest())-class _CurrentHeaders(Dependency[dict[str, str]]):+class _CurrentHeaders(Provider[dict[str, str]]):"""Async context manager for HTTP Headers dependency."""async def __aenter__(self) -> dict[str, str]:@@ -1266,7 +1274,7 @@ class InMemoryProgress:self._message = message-class Progress(Dependency["Progress"]):+class Progress(Provider["Progress"]):"""Progress dependency that works in both server and worker contexts.In a Docket worker, delegates to the execution's Redis-backed progress@@ -1343,7 +1351,7 @@ class Progress(Dependency["Progress"]):# --- Access Token dependency ----class _CurrentAccessToken(Dependency[AccessToken]):+class _CurrentAccessToken(Provider[AccessToken]):"""Async context manager for AccessToken dependency."""async def __aenter__(self) -> AccessToken:@@ -1393,7 +1401,7 @@ def CurrentAccessToken() -> AccessToken:# --- Token Claim dependency ----class _TokenClaim(Dependency[str]):+class _TokenClaim(Provider[str]):"""Dependency that extracts a specific claim from the access token."""def __init__(self, claim_name: str):diff --git a/fastmcp_slim/fastmcp/server/sessions.py b/fastmcp_slim/fastmcp/server/sessions.pyindex a68a462f8..82ef061a2 100644--- a/fastmcp_slim/fastmcp/server/sessions.py+++ b/fastmcp_slim/fastmcp/server/sessions.py@@ -56,7 +56,7 @@ from typing import (from uuid import uuid4from mcp.server.auth.provider import principal_components-from uncalled_for import Dependency+from uncalled_for import Provider as DependencyProviderfrom fastmcp.exceptions import FastMCPErrorfrom fastmcp.server.dependencies import get_access_token, get_server, get_session@@ -401,7 +401,7 @@ def _current_user_session() -> UserSession | None:)-class _CurrentSession(Dependency["Session"]):+class _CurrentSession(DependencyProvider["Session"]):"""Dependency that injects a per-user `Session` keyed by the request principal.Mirrors `_CurrentContext`: a `session: UserSession` parameter is rewritten to@@ -425,7 +425,7 @@ class _CurrentSession(Dependency["Session"]):return None-class _OptionalCurrentSession(Dependency["Session | None"]):+class _OptionalCurrentSession(DependencyProvider["Session | None"]):"""Dependency for an *optional* per-user session (`session: UserSession | None`).Mirrors `_OptionalCurrentContext`: when the request carries no authenticateddiff --git a/fastmcp_slim/pyproject.toml b/fastmcp_slim/pyproject.tomlindex fcbb69b4e..ff2d94c2d 100644--- a/fastmcp_slim/pyproject.toml+++ b/fastmcp_slim/pyproject.toml@@ -109,7 +109,7 @@ server = ["pyperclip>=1.9.0","python-multipart>=0.0.26","pyyaml>=6.0,<7.0",- "uncalled-for>=0.4.0",+ "uncalled-for>=0.6.0","uvicorn>=0.35","watchfiles>=1.0.0","websockets>=15.0.1",diff --git a/fastmcp_tasks/fastmcp_tasks/dependencies.py b/fastmcp_tasks/fastmcp_tasks/dependencies.pyindex 0598fe6af..0129a2bb7 100644--- a/fastmcp_tasks/fastmcp_tasks/dependencies.py+++ b/fastmcp_tasks/fastmcp_tasks/dependencies.py@@ -18,7 +18,7 @@ from contextvars import ContextVarfrom types import TracebackTypefrom typing import TYPE_CHECKING, cast-from uncalled_for import Dependency+from uncalled_for import Providerfrom fastmcp.server.dependencies import (_MIN_DOCKET_VERSION,@@ -72,7 +72,7 @@ def require_docket(feature: str) -> None:raise ImportError(f"{detail} (Triggered by {feature})")-class _CurrentDocket(Dependency["Docket"]):+class _CurrentDocket(Provider["Docket"]):"""Async context manager for Docket dependency."""async def __aenter__(self) -> Docket:@@ -129,7 +129,7 @@ def CurrentDocket() -> Docket:return cast("Docket", _CurrentDocket())-class _CurrentWorker(Dependency["Worker"]):+class _CurrentWorker(Provider["Worker"]):"""Async context manager for Worker dependency."""async def __aenter__(self) -> Worker:diff --git a/tests/server/test_annotated_dependencies.py b/tests/server/test_annotated_dependencies.pynew file mode 100644index 000000000..e739e772f--- /dev/null+++ b/tests/server/test_annotated_dependencies.py@@ -0,0 +1,98 @@+"""Dependencies declared in `Annotated` metadata resolve like `Depends()` defaults."""++from typing import Annotated++import pytest++from fastmcp import FastMCP+from fastmcp.client import Client+from fastmcp.dependencies import CurrentContext, CurrentFastMCP, Depends+from fastmcp.server.context import Context+++def get_config() -> dict[str, str]:+ return {"api_url": "https://api.example.com"}+++Config = Annotated[dict[str, str], Depends(get_config)]+++async def test_tool_resolves_annotated_dependency_outside_its_schema():+ mcp = FastMCP()++ @mcp.tool+ async def fetch(query: str, config: Annotated[dict, Depends(get_config)]) -> str:+ return f"{query} from {config['api_url']}"++ async with Client(mcp) as client:+ (tool,) = await client.list_tools()+ result = await client.call_tool("fetch", {"query": "users"})++ assert list(tool.input_schema["properties"]) == ["query"]+ assert result.data == "users from https://api.example.com"+++async def test_type_alias_carries_the_dependency():+ mcp = FastMCP()++ @mcp.tool+ async def fetch(config: Config) -> str:+ return config["api_url"]++ async with Client(mcp) as client:+ (tool,) = await client.list_tools()+ result = await client.call_tool("fetch", {})++ assert tool.input_schema.get("properties", {}) == {}+ assert result.data == "https://api.example.com"+++async def test_prompt_and_template_resolve_annotated_dependencies():+ mcp = FastMCP()++ @mcp.prompt+ def describe(topic: str, config: Config) -> str:+ return f"{topic} at {config['api_url']}"++ @mcp.resource("config://{key}")+ def read_config(key: str, config: Config) -> str:+ return config[key]++ async with Client(mcp) as client:+ (prompt,) = await client.list_prompts()+ rendered = await client.get_prompt("describe", {"topic": "search"})+ contents = await client.read_resource("config://api_url")++ assert [argument.name for argument in prompt.arguments or []] == ["topic"]+ assert rendered.messages[0].content.text == "search at https://api.example.com"+ assert contents[0].text == "https://api.example.com"+++def test_annotated_dependency_with_a_depends_default_is_rejected():+ mcp = FastMCP()++ with pytest.raises(TypeError):++ @mcp.tool+ async def fetch(+ config: Annotated[dict, Depends(get_config)] = Depends(get_config),+ ) -> str:+ return config["api_url"]+++async def test_builtin_dependencies_provide_values_as_annotations():+ mcp = FastMCP("annotated-builtins")++ @mcp.tool+ async def whoami(+ ctx: Annotated[Context, CurrentContext()],+ server: Annotated[FastMCP, CurrentFastMCP()],+ ) -> str:+ return f"{ctx.fastmcp.name}/{server.name}"++ async with Client(mcp) as client:+ (tool,) = await client.list_tools()+ result = await client.call_tool("whoami", {})++ assert tool.input_schema.get("properties", {}) == {}+ assert result.data == "annotated-builtins/annotated-builtins"diff --git a/uv.lock b/uv.lockindex 69cf5e295..5cab794ae 100644--- a/uv.lock+++ b/uv.lock@@ -1053,7 +1053,7 @@ requires-dist = [{ name = "starlette", marker = "extra == 'server'", specifier = ">=1.0.1" },{ name = "typesafe-sdk", marker = "extra == 'jev'", specifier = ">=0.5.7" },{ name = "typing-extensions", specifier = ">=4.0.0" },- { name = "uncalled-for", marker = "extra == 'server'", specifier = ">=0.4.0" },+ { name = "uncalled-for", marker = "extra == 'server'", specifier = ">=0.6.0" },{ name = "uvicorn", marker = "extra == 'server'", specifier = ">=0.35" },{ name = "watchfiles", marker = "extra == 'server'", specifier = ">=1.0.0" },{ name = "websockets", marker = "extra == 'server'", specifier = ">=15.0.1" },@@ -3195,11 +3195,11 @@ wheels = [[[package]]name = "uncalled-for"-version = "0.4.0"+version = "0.6.0"source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/6b/5a/92ce0b3ea5481915f55da994c2c2c5f7a3c09949afde196ee89f8ab961aa/uncalled_for-0.4.0.tar.gz", hash = "sha256:335b95bd2422332ec210d518f314a16e4c640921c39fc8bf2ad095bd3538f4af", size = 56979, upload-time = "2026-08-10T14:51:46.247Z" }+sdist = { url = "https://files.pythonhosted.org/packages/58/49/423c660a9b548ebe875562c4f47d3dcbc5807377e19eced0596b05894ca9/uncalled_for-0.6.0.tar.gz", hash = "sha256:5872701bf3b4eb0698930f87126d339d56a904c53f052eb0eadad64439fa9b11", size = 68911, upload-time = "2026-11-05T23:47:08.578Z" }wheels = [- { url = "https://files.pythonhosted.org/packages/a2/40/97cec87c077eb3291fc7905e6633e08b7ca593c57d30238444bcb6bb3d53/uncalled_for-0.4.0-py3-none-any.whl", hash = "sha256:16c4bb3337532e4bd5569adc192285976f3ad5305402256d34c67a12b5c968bd", size = 15502, upload-time = "2026-08-10T14:51:45.068Z" },+ { url = "https://files.pythonhosted.org/packages/a6/a7/d819bc9c5ea3d0ccbedc9999e36efebe9dbae61b024f494afc423483909a/uncalled_for-0.6.0-py3-none-any.whl", hash = "sha256:5c6932836965b0e6b0a80f9962388922f3bb235431d8f5d3fedc2ad07b581189", size = 16734, upload-time = "2026-11-05T23:47:07.177Z" },][[package]]