Skip to content

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

Support rotating Redis credentials for tasks (#5970)

nate nowack435948521d40
diff --git a/.github/actions/run-pytest/action.yml b/.github/actions/run-pytest/action.yml
index c82e9c0bd..346c9d745 100644
--- a/.github/actions/run-pytest/action.yml
+++ b/.github/actions/run-pytest/action.yml
@@ -10,6 +10,15 @@ inputs:
runs:
using: "composite"
steps:
+ - name: Install Redis for credential rotation integration tests
+ if: inputs.test-type == 'integration' && runner.os == 'Linux'
+ shell: bash
+ run: |
+ if ! command -v redis-server >/dev/null; then
+ sudo apt-get update
+ sudo apt-get install -y redis-server
+ fi
+
- name: Run pytest
shell: bash
run: |
diff --git a/.github/workflows/run-downstream-smoke.yml b/.github/workflows/run-downstream-smoke.yml
index 74cffc2f9..3c4f8c395 100644
--- a/.github/workflows/run-downstream-smoke.yml
+++ b/.github/workflows/run-downstream-smoke.yml
@@ -155,7 +155,7 @@ jobs:
run: |
echo "UV_RUN=uv run --all-extras --no-extra mcp-tasks --all-packages \
--exclude-newer-package certifi=false \
- --exclude-newer-package pydocket=2026-10-03T00:00:00Z \
+ --exclude-newer-package pydocket=2026-10-06T00:00:00Z \
--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/tasks.mdx b/docs/servers/tasks.mdx
index 3bb9d579a..87ceb0d8a 100644
--- a/docs/servers/tasks.mdx
+++ b/docs/servers/tasks.mdx
@@ -196,6 +196,45 @@ mcp.add_extension(TasksExtension(url="redis://localhost:6379/0"))
- **Fast**: Single-digit millisecond task pickup latency
- **Scalable**: Add workers to distribute load across processes or machines
+### Rotating Redis Credentials
+
+For backends with expiring credentials, pass a redis-py `CredentialProvider` to `TasksExtension`. Use a URL without a username or password. Docket passes the provider to its Redis connections so a reconnect can obtain fresh credentials.
+
+This example reads credentials from a file on each new connection. Your deployment can replace the file when the password or token changes:
+
+```python
+from pathlib import Path
+
+from redis.credentials import CredentialProvider
+
+from fastmcp import FastMCP
+from fastmcp_tasks import TasksExtension
+
+
+class FileCredentials(CredentialProvider):
+ def get_credentials(self) -> tuple[str, str]:
+ password = Path("/run/secrets/redis-password").read_text().strip()
+ return "tasks-user", password
+
+
+mcp = FastMCP("MyServer")
+mcp.add_extension(
+ TasksExtension(
+ url="rediss://redis.example.com:6379/0",
+ credential_provider=FileCredentials(),
+ )
+)
+
+
+async def double(value: int) -> int:
+ return value * 2
+```
+
+You can also supply a provider that implements `get_credentials_async()`, or a provider from your cloud authentication library. FastMCP does not generate or refresh cloud tokens itself. Docket manages connection authentication, including refresh notifications from streaming providers; see [Docket credential providers](https://docket.lol/en/latest/production/#credential-providers) for details about long-lived connections and provider ownership.
+
+Configure the provider in your server module. [Additional workers](#workers) load that same module and use its registered extension, so no separate worker flag is needed. Provider objects are runtime configuration, not `FASTMCP_DOCKET_*` environment settings. The default `memory://` backend ignores them.
+
### Credentials at Rest
A background task runs long after the request that submitted it has ended, but it still needs to know who asked for the work. FastMCP captures that identity at submission time in a **task context snapshot**: the caller's access token and every inbound HTTP header, including `Authorization`. The worker restores the snapshot before the tool body runs, so `get_access_token()` and `get_http_headers()` return the submitting caller.
diff --git a/fastmcp_tasks/fastmcp_tasks/extension.py b/fastmcp_tasks/fastmcp_tasks/extension.py
index 331125a7b..7083b6b2a 100644
--- a/fastmcp_tasks/fastmcp_tasks/extension.py
+++ b/fastmcp_tasks/fastmcp_tasks/extension.py
@@ -66,6 +66,7 @@ from fastmcp_tasks.settings import DocketSettings
if TYPE_CHECKING:
import mcp_types
+ from redis.credentials import CredentialProvider
from fastmcp.server.context import Context
from fastmcp.server.extensions import ToolCallContinuation, ToolCallOutcome
@@ -83,6 +84,10 @@ class TasksExtension(ServerExtension):
Construct with backend/worker configuration; anything omitted falls back to
the ``FASTMCP_DOCKET_*`` environment defaults (unchanged from FastMCP 3), so
``TasksExtension()`` works out of the box on an env-configured deployment.
+
+ Pass a redis-py `credential_provider` for rotating backend credentials,
+ with no credentials in the URL. The provider is runtime configuration,
+ not an environment setting; Docket manages its connections and refreshes.
"""
identifier = TASKS_EXTENSION_ID
@@ -90,6 +95,7 @@ class TasksExtension(ServerExtension):
def __init__(
self,
*,
+ credential_provider: CredentialProvider | None = None,
url: str | None = None,
name: str | None = None,
worker_name: str | None = None,
@@ -98,6 +104,7 @@ class TasksExtension(ServerExtension):
reconnection_delay: timedelta | None = None,
minimum_check_interval: timedelta | None = None,
) -> None:
+ self._credential_provider = credential_provider
overrides: dict[str, Any] = {
"url": url,
"name": name,
@@ -303,7 +310,11 @@ class TasksExtension(ServerExtension):
_install_worker_hooks()
try:
- async with docket_lifespan(self.server, self._settings):
+ async with docket_lifespan(
+ self.server,
+ self._settings,
+ credential_provider=self._credential_provider,
+ ):
yield
finally:
_release_worker_hooks()
diff --git a/fastmcp_tasks/fastmcp_tasks/lifespan.py b/fastmcp_tasks/fastmcp_tasks/lifespan.py
index a8738bd81..6de0fb4a8 100644
--- a/fastmcp_tasks/fastmcp_tasks/lifespan.py
+++ b/fastmcp_tasks/fastmcp_tasks/lifespan.py
@@ -19,6 +19,8 @@ from typing import TYPE_CHECKING, Any
from fastmcp.utilities.logging import get_logger
if TYPE_CHECKING:
+ from redis.credentials import CredentialProvider
+
from fastmcp.server.server import FastMCP
from fastmcp_tasks.settings import DocketSettings
@@ -27,7 +29,10 @@ logger = get_logger(__name__)
@asynccontextmanager
async def docket_lifespan(
- server: FastMCP, settings: DocketSettings
+ server: FastMCP,
+ settings: DocketSettings,
+ *,
+ credential_provider: CredentialProvider | None = None,
) -> AsyncIterator[None]:
"""Manage the Docket instance and Worker for background task execution.
@@ -66,7 +71,9 @@ async def docket_lifespan(
yield
return
- async with Docket(name=settings.name, url=settings.url) as docket:
+ async with Docket(
+ name=settings.name, url=settings.url, credential_provider=credential_provider
+ ) as docket:
server._docket = docket
for component in task_components:
register_component_with_docket(component, docket)
diff --git a/fastmcp_tasks/pyproject.toml b/fastmcp_tasks/pyproject.toml
index e19fef930..ad5918147 100644
--- a/fastmcp_tasks/pyproject.toml
+++ b/fastmcp_tasks/pyproject.toml
@@ -71,5 +71,6 @@ dependencies = [
# it starts. Earlier versions treated that cancellation as a shutdown
# request, so the worker stopped reading tasks and every later task stayed
# in `working` forever.
- "pydocket>=0.26.0",
+ # pydocket 0.26.1 supports Redis credential providers and token rotation.
+ "pydocket>=0.26.1",
]
diff --git a/tests/integration_tests/test_task_credentials.py b/tests/integration_tests/test_task_credentials.py
new file mode 100644
index 000000000..807fdfd36
--- /dev/null
+++ b/tests/integration_tests/test_task_credentials.py
@@ -0,0 +1,233 @@
+import asyncio
+import shutil
+import sys
+from collections.abc import AsyncIterator
+from datetime import timedelta
+from pathlib import Path
+
+import pytest
+from docket import Docket
+from redis.asyncio import Redis
+from redis.credentials import CredentialProvider
+from redis.exceptions import AuthenticationError, ConnectionError
+
+from fastmcp import Client, FastMCP
+from fastmcp_tasks import TasksExtension
+
+pytestmark = [pytest.mark.integration, pytest.mark.timeout(30)]
+
+
+class FileCredentials(CredentialProvider):
+ def __init__(self, path: Path):
+ self.path = path
+
+ def get_credentials(self) -> tuple[str, str]:
+ return "tasks", self.path.read_text()
+
+
+class AsyncFileCredentials(FileCredentials):
+ def get_credentials(self) -> tuple[str, str]:
+ raise AssertionError("Async credentials must be awaited")
+
+ async def get_credentials_async(self) -> tuple[str, str]:
+ return "tasks", self.path.read_text()
+
+
+async def redis_backend(free_port: int, tmp_path: Path) -> AsyncIterator[Redis]:
+ executable = shutil.which("redis-server")
+ if executable is None:
+ pytest.skip("redis-server is required for credential rotation tests")
+ with (tmp_path / "redis.log").open("w") as log:
+ process = await asyncio.create_subprocess_exec(
+ executable,
+ "--bind",
+ "127.0.0.1",
+ "--port",
+ str(free_port),
+ "--save",
+ "",
+ "--appendonly",
+ "no",
+ "--dir",
+ str(tmp_path),
+ stdout=log,
+ stderr=log,
+ )
+ async with Redis(host="127.0.0.1", port=free_port) as admin:
+ try:
+ for _ in range(100):
+ try:
+ await admin.ping()
+ break
+ except ConnectionError:
+ if process.returncode is not None:
+ pytest.fail((tmp_path / "redis.log").read_text())
+ await asyncio.sleep(0.02)
+ else:
+ pytest.fail("Redis did not start")
+ yield admin
+ finally:
+ if process.returncode is None:
+ process.terminate()
+ await asyncio.wait_for(process.wait(), 5)
+
+
+async def rotate(admin: Redis, path: Path, password: str) -> None:
+ path.write_text(password)
+ await admin.execute_command(
+ "ACL",
+ "SETUSER",
+ "tasks",
+ "on",
+ "resetpass",
+ f">{password}",
+ "~*",
+ "&*",
+ "+@all",
+ )
+ await admin.execute_command("CLIENT", "KILL", "USER", "tasks")
+
+
+def task_server(url: str, provider: CredentialProvider | None) -> FastMCP:
+ server = FastMCP("rotating-credentials")
+ server.add_extension(
+ TasksExtension(
+ url=url,
+ credential_provider=provider,
+ reconnection_delay=timedelta(milliseconds=10),
+ )
+ )
+
+ @server.tool(task=True)
+ async def double(value: int) -> int:
+ return value * 2
+
+ return server
+
+
[email protected]("provider_type", [FileCredentials, AsyncFileCredentials])
+async def test_tasks_reconnect_with_rotated_credentials(
+ redis_backend: Redis,
+ free_port: int,
+ tmp_path: Path,
+ provider_type: type[FileCredentials],
+) -> None:
+ password = tmp_path / "password"
+ await rotate(redis_backend, password, "first")
+ url = f"redis://127.0.0.1:{free_port}/0"
+ server = task_server(url, provider_type(password))
+ async with Client(server) as client:
+ result = await client.call_tool("double", {"value": 21})
+ assert result.data == 42
+ assert type(result.data) is int
+ await rotate(redis_backend, password, "second")
+ result = await client.call_tool("double", {"value": 22})
+ assert result.data == 44
+ assert type(result.data) is int
+
+
+async def test_static_credentials_do_not_refresh(
+ redis_backend: Redis,
+ free_port: int,
+ tmp_path: Path,
+) -> None:
+ password = tmp_path / "password"
+ await rotate(redis_backend, password, "first")
+ server = task_server(f"redis://tasks:[email protected]:{free_port}/0", None)
+ async with Client(server) as client:
+ assert (await client.call_tool("double", {"value": 21})).data == 42
+ await rotate(redis_backend, password, "second")
+ assert server.docket is not None
+ async with server.docket.redis() as redis:
+ with pytest.raises(AuthenticationError):
+ await redis.get("after-rotation")
+
+
+async def test_invalid_provider_credentials_are_rejected(
+ redis_backend: Redis,
+ free_port: int,
+ tmp_path: Path,
+) -> None:
+ password = tmp_path / "password"
+ await rotate(redis_backend, password, "first")
+ password.write_text("wrong")
+ server = task_server(f"redis://127.0.0.1:{free_port}/0", FileCredentials(password))
+ async with server._lifespan_manager():
+ assert server.docket is not None
+ async with server.docket.redis() as redis:
+ with pytest.raises(AuthenticationError):
+ await redis.get("invalid-credentials")
+
+
+async def test_worker_cli_uses_the_servers_provider(
+ redis_backend: Redis,
+ free_port: int,
+ tmp_path: Path,
+) -> None:
+ password = tmp_path / "password"
+ await rotate(redis_backend, password, "first")
+ url = f"redis://127.0.0.1:{free_port}/0"
+ result_path = tmp_path / "result"
+ server_path = tmp_path / "server.py"
+ server_path.write_text(f"""from pathlib import Path
+from datetime import timedelta
+from redis.credentials import CredentialProvider
+from fastmcp import FastMCP
+from fastmcp_tasks import TasksExtension
+
+class Credentials(CredentialProvider):
+ async def get_credentials_async(self):
+ return "tasks", Path({str(password)!r}).read_text()
+
+mcp = FastMCP("worker-credentials")
+mcp.add_extension(TasksExtension(
+ url={url!r}, name="worker-credentials", credential_provider=Credentials(),
+ reconnection_delay=timedelta(milliseconds=10),
+))
+
+async def record(value: int) -> int:
+ Path({str(result_path)!r}).write_text(str(value))
+ return value
+""")
+ with (tmp_path / "worker.log").open("w") as log:
+ process = await asyncio.create_subprocess_exec(
+ sys.executable,
+ "-m",
+ "fastmcp_tasks.worker_cli",
+ "worker",
+ str(server_path),
+ stdout=log,
+ stderr=log,
+ )
+ try:
+ async with Docket(
+ name="worker-credentials",
+ url=url,
+ credential_provider=FileCredentials(password),
+ ) as docket:
+
+ async def record(value: int) -> int:
+ return value
+
+ docket.register(record, names=["tool:record@"])
+ for value in (41, 42):
+ if value == 42:
+ await rotate(redis_backend, password, "second")
+ await docket.add("tool:record@")(value=value)
+ for _ in range(400):
+ if result_path.exists() and result_path.read_text() == str(
+ value
+ ):
+ break
+ if process.returncode is not None:
+ pytest.fail((tmp_path / "worker.log").read_text())
+ await asyncio.sleep(0.02)
+ else:
+ pytest.fail((tmp_path / "worker.log").read_text())
+ finally:
+ if process.returncode is None:
+ process.terminate()
+ await asyncio.wait_for(process.wait(), 5)
diff --git a/tests/server/test_server_docket.py b/tests/server/test_server_docket.py
index 7bd83d1e7..923e11069 100644
--- a/tests/server/test_server_docket.py
+++ b/tests/server/test_server_docket.py
@@ -3,9 +3,11 @@
import asyncio
from contextlib import asynccontextmanager
+import pytest
from docket import Docket
from docket.worker import Worker
from fastmcp_tasks.dependencies import CurrentDocket, CurrentWorker
+from redis.credentials import CredentialProvider
from fastmcp import FastMCP
from fastmcp.client import Client
@@ -169,3 +171,40 @@ async def test_user_lifespan_still_works_with_docket():
assert lifespan_entered
result = await client.call_tool("check_both", {})
assert HUZZAH in str(result)
+
+
+async def test_memory_backend_does_not_request_credentials():
+ class UnusedCredentials(CredentialProvider):
+ def get_credentials(self) -> tuple[str, str]:
+ raise AssertionError("The memory backend must not authenticate")
+
+ mcp = FastMCP("memory-credentials")
+ mcp.add_extension(TasksExtension(credential_provider=UnusedCredentials()))
+
+ @mcp.tool(task=True)
+ async def double(value: int) -> int:
+ return value * 2
+
+ async with Client(mcp) as client:
+ result = await client.call_tool("double", {"value": 21})
+
+ assert result.data == 42
+ assert type(result.data) is int
+
+
+async def test_provider_and_url_credentials_are_rejected():
+ mcp = FastMCP("conflicting-credentials")
+ mcp.add_extension(
+ TasksExtension(
+ url="redis://user:password@localhost:6379/0",
+ credential_provider=CredentialProvider(),
+ )
+ )
+
+ @mcp.tool(task=True)
+ async def double(value: int) -> int:
+ return value * 2
+
+ with pytest.raises(ValueError, match="not both"):
+ async with mcp._lifespan_manager():
+ pytest.fail("Conflicting credentials must not start the task backend")
diff --git a/uv.lock b/uv.lock
index b0f5ce413..65c6fe207 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1162,7 +1162,7 @@ dependencies = [
requires-dist = [
{ name = "cryptography", specifier = ">=43.0.0" },
{ name = "fastmcp-slim", extras = ["server"], editable = "fastmcp_slim" },
- { name = "pydocket", specifier = ">=0.26.0" },
+ { name = "pydocket", specifier = ">=0.26.1" },
]
[[package]]
@@ -2583,7 +2583,7 @@ wheels = [
[[package]]
name = "pydocket"
-version = "0.26.0"
+version = "0.26.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "burner-redis" },
@@ -2602,9 +2602,9 @@ dependencies = [
{ name = "tzdata", marker = "sys_platform == 'win32'" },
{ name = "uncalled-for" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/35/aa/a1b9b324ed010db7f9a2bc3a2f2aa03e43e8d8f404fd5305c13cb8418314/pydocket-0.26.0.tar.gz", hash = "sha256:a168adbc5ed280ed5c557bb97e7162b8ac883baca395b205dfb14494cbf85231", size = 482629, upload-time = "2026-10-02T14:26:51.811Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/77/36/97b4b18fe41a6814cdb58cd8b40b41df1618b3f9104043dd3fb3e7cc2317/pydocket-0.26.1.tar.gz", hash = "sha256:1032d3a3c1442a648761b1a23590bb8baee35f5b381002c1149b117decf20cec", size = 320084, upload-time = "2026-10-05T17:39:37.534Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/90/81/8b90fcb6ab7d8abb86ed81c26efb9d70494b9be3a9dcf7b78ee77fa1db46/pydocket-0.26.0-py3-none-any.whl", hash = "sha256:63051711f56912dde81f794ddac6430cfe187e9b7f241f967fdfb78d00737734", size = 142764, upload-time = "2026-10-02T14:26:50.101Z" },
+ { url = "https://files.pythonhosted.org/packages/f2/3b/97dc5b1011a4768414a8549fac4085530cb5c48c4f29b921aedae12210e2/pydocket-0.26.1-py3-none-any.whl", hash = "sha256:250d1ab13c1f9baf338902d3e05ca1b1bb69247e7332033b6eff6eb41c820c4b", size = 152056, upload-time = "2026-10-05T17:39:36.184Z" },
]
[[package]]