π The fast, Pythonic way to build MCP servers and clients.
feat: persist encrypted CLI OAuth tokens (#5405)
Andrei Vincea4c7f8c6832c
diff --git a/docs/cli/overview.mdx b/docs/cli/overview.mdxindex 675514ecc..53f39f2ec 100644--- a/docs/cli/overview.mdx+++ b/docs/cli/overview.mdx@@ -118,6 +118,14 @@ JSON mode does not open a browser or ask a question.When targeting an HTTP URL, the CLI enables OAuth authentication by default. If the server requires it, you'll be guided through the flow (typically opening a browser). If it doesn't, the setup is a silent no-op.+OAuth tokens are kept in memory by default and discarded when the command exits. To reuse authentication across `fastmcp list` and `fastmcp call`, generate a Fernet key once and save it as `FASTMCP_OAUTH_ENCRYPTION_KEY` in your environment or `.env` file:++```bash+python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"+```++With that setting, the CLI encrypts tokens and client registration details on disk under `FASTMCP_HOME`. Keep the key secret and reuse the same value across invocations. Changing it starts a separate cache and requires signing in again. This applies to HTTP and SSE URLs and discovered servers that connect directly over HTTP or SSE; MCPConfig files retain their per-server authentication configuration. The Python SDK's storage defaults are unchanged.+To skip authentication entirely β useful for local development servers β pass `--auth none`:```bashdiff --git a/docs/more/settings.mdx b/docs/more/settings.mdxindex ac9182054..0c6a53fb5 100644--- a/docs/more/settings.mdx+++ b/docs/more/settings.mdx@@ -72,6 +72,7 @@ These control how the server listens when running with an HTTP transport.|---|---|---|---|| `FASTMCP_SHOW_SERVER_BANNER` | `bool` | `true` | Show the server banner on startup. Also controllable via `--no-banner` or `server.run(show_banner=False)`. || `FASTMCP_CHECK_FOR_UPDATES` | `Literal["stable", "prerelease", "off"]` | `stable` | Update checking on CLI startup. `stable` checks stable releases only, `prerelease` includes pre-releases, `off` disables checking. |+| `FASTMCP_OAUTH_ENCRYPTION_KEY` | `str \| None` | None | Fernet key for [encrypted CLI OAuth storage](/cli/overview#mcp-server-authentication). An unset or empty value uses memory only. |## Telemetrydiff --git a/fastmcp_slim/fastmcp/cli/client.py b/fastmcp_slim/fastmcp/cli/client.pyindex cf9946de7..33c1facb9 100644--- a/fastmcp_slim/fastmcp/cli/client.py+++ b/fastmcp_slim/fastmcp/cli/client.py@@ -1,18 +1,29 @@"""Client-side CLI commands for querying and invoking MCP servers."""import difflib+import hashlibimport jsonimport shleximport sys+import warningsfrom pathlib import Pathfrom typing import Annotated, Any, Literalimport cycloptsimport mcp_types+from cryptography.fernet import Fernet+from key_value.aio.stores.filetree import (+ FileTreeStore,+ FileTreeV1CollectionSanitizationStrategy,+ FileTreeV1KeySanitizationStrategy,+)+from key_value.aio.wrappers.encryption import FernetEncryptionWrapperfrom rich.console import Consolefrom rich.markup import escape as escape_rich_markup+from fastmcp import settingsfrom fastmcp.cli.discovery import DiscoveredServer, discover_servers, resolve_name+from fastmcp.client.auth.oauth import OAuthfrom fastmcp.client.client import CallToolResult, Clientfrom fastmcp.client.elicitation import ElicitResultfrom fastmcp.client.transports.base import ClientTransport@@ -24,6 +35,8 @@ from fastmcp.utilities.logging import get_loggerlogger = get_logger("cli.client")console = Console()+_MEMORY_TOKEN_WARNING = r"Using in-memory token storage\b"+# ---------------------------------------------------------------------------# Server spec resolution@@ -106,7 +119,14 @@ def resolve_server_spec(# 3. Name-based resolution (bare name or source:name)try:- return resolve_name(spec)+ with warnings.catch_warnings():+ warnings.filterwarnings(+ "ignore",+ message=_MEMORY_TOKEN_WARNING,+ category=UserWarning,+ module=r"fastmcp\.client\.",+ )+ return resolve_name(spec)except ValueError as exc:console.print(f"[bold red]Error:[/bold red] {exc}")sys.exit(1)@@ -240,7 +260,7 @@ def _build_client(means "explicitly disabled"."""if auth == "none":- effective_auth: str | None = None+ effective_auth: str | OAuth | None = Noneelif auth is not None:effective_auth = authelif _is_http_target(resolved):@@ -248,12 +268,48 @@ def _build_client(else:effective_auth = None- return Client(- resolved,- timeout=timeout,- auth=effective_auth,- elicitation_handler=_terminal_elicitation_handler,- )+ if effective_auth == "oauth" and _is_http_target(resolved):+ token_storage = None+ encryption_key = settings.oauth_encryption_key+ if encryption_key and encryption_key.get_secret_value():+ key = encryption_key.get_secret_value().encode()+ try:+ fernet = Fernet(key)+ except ValueError:+ raise ValueError(+ "FASTMCP_OAUTH_ENCRYPTION_KEY must be a valid Fernet key."+ ) from None+ key_fingerprint = hashlib.sha256(key).hexdigest()[:12]+ storage_dir = settings.home / "cli-oauth" / key_fingerprint+ storage_dir.mkdir(parents=True, exist_ok=True)+ token_storage = FernetEncryptionWrapper(+ key_value=FileTreeStore(+ data_directory=storage_dir,+ key_sanitization_strategy=FileTreeV1KeySanitizationStrategy(+ storage_dir+ ),+ collection_sanitization_strategy=FileTreeV1CollectionSanitizationStrategy(+ storage_dir+ ),+ ),+ fernet=fernet,+ raise_on_decryption_error=False,+ )+ effective_auth = OAuth(token_storage=token_storage)++ with warnings.catch_warnings():+ warnings.filterwarnings(+ "ignore",+ message=_MEMORY_TOKEN_WARNING,+ category=UserWarning,+ module=r"fastmcp\.client\.",+ )+ return Client(+ resolved,+ timeout=timeout,+ auth=effective_auth,+ elicitation_handler=_terminal_elicitation_handler,+ )# ---------------------------------------------------------------------------@@ -703,9 +759,8 @@ async def list_command("""resolved = resolve_server_spec(server_spec, command=command, transport=transport)- client = _build_client(resolved, timeout=timeout, auth=auth)-try:+ client = _build_client(resolved, timeout=timeout, auth=auth)async with client:tools = await client.list_tools()@@ -876,9 +931,8 @@ async def call_command(sys.exit(1)resolved = resolve_server_spec(server_spec, command=command, transport=transport)- client = _build_client(resolved, timeout=timeout, auth=auth)-try:+ client = _build_client(resolved, timeout=timeout, auth=auth)async with client:if prompt:await _handle_prompt(client, target, arguments, input_json, json_output)diff --git a/fastmcp_slim/fastmcp/settings.py b/fastmcp_slim/fastmcp/settings.pyindex d442d7218..8b62d6d70 100644--- a/fastmcp_slim/fastmcp/settings.py+++ b/fastmcp_slim/fastmcp/settings.py@@ -6,7 +6,7 @@ from pathlib import Pathfrom typing import Annotated, Any, Literalfrom platformdirs import user_data_dir-from pydantic import Field, field_validator+from pydantic import Field, SecretStr, field_validatorfrom pydantic_settings import (BaseSettings,SettingsConfigDict,@@ -71,6 +71,8 @@ class Settings(BaseSettings):home: Path = Path(user_data_dir("fastmcp", appauthor=False))+ oauth_encryption_key: SecretStr | None = None+test_mode: bool = Falselog_enabled: bool = Truediff --git a/tests/cli/test_client_commands.py b/tests/cli/test_client_commands.pyindex d2083d1db..7849a1ef2 100644--- a/tests/cli/test_client_commands.py+++ b/tests/cli/test_client_commands.py@@ -1,12 +1,15 @@"""Tests for fastmcp list and fastmcp call CLI commands."""import json+import warningsfrom pathlib import Pathfrom typing import Anyfrom unittest.mock import patchimport mcp_typesimport pytest+from cryptography.fernet import Fernet+from mcp.shared.auth import OAuthClientInformationFull, OAuthTokenfrom fastmcp import FastMCPfrom fastmcp.cli import client as client_module@@ -24,8 +27,13 @@ from fastmcp.cli.client import (parse_tool_arguments,resolve_server_spec,)+from fastmcp.client.auth.oauth import OAuthfrom fastmcp.client.client import CallToolResult+from fastmcp.client.transports.sse import SSETransportfrom fastmcp.client.transports.stdio import StdioTransport+from fastmcp.mcp_config import RemoteMCPServer+from fastmcp.settings import Settings+from fastmcp.utilities.tests import temporary_settings# ---------------------------------------------------------------------------# coerce_value@@ -367,6 +375,132 @@ class TestIsHttpTarget:class TestBuildClient:+ @pytest.mark.parametrize("transport,auth", [("http", None), ("sse", "oauth")])+ async def test_encrypted_oauth_reused_by_fresh_client(+ self,+ transport: str,+ auth: str | None,+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ ) -> None:+ monkeypatch.setenv(+ "FASTMCP_OAUTH_ENCRYPTION_KEY", Fernet.generate_key().decode()+ )+ url = (+ "https://example.com/mcp"+ if transport == "http"+ else "https://example.com/sse"+ )+ resolved = url if transport == "http" else SSETransport(url)+ tokens = OAuthToken(+ access_token="synthetic-access-token",+ refresh_token="synthetic-refresh-token",+ token_type="Bearer",+ expires_in=300,+ )+ registration = OAuthClientInformationFull(+ client_id="test-client",+ client_secret="synthetic-registration-secret",+ redirect_uris=["http://localhost/callback"],+ )++ with temporary_settings(**Settings(home=tmp_path, _env_file=None).model_dump()):+ with warnings.catch_warnings(record=True) as emitted:+ warnings.simplefilter("always")+ first = _build_client(resolved, auth=auth).transport.auth+ assert isinstance(first, OAuth)+ await first.token_storage_adapter.set_tokens(tokens)+ await first.token_storage_adapter.set_client_info(registration)+ second = _build_client(resolved, auth=auth).transport.auth+ assert isinstance(second, OAuth)++ assert await second.token_storage_adapter.get_tokens() == tokens+ assert await second.token_storage_adapter.get_client_info() == registration+ assert await second.token_storage_adapter.get_token_expiry() == (+ await first.token_storage_adapter.get_token_expiry()+ )+ other = _build_client("https://example.com/other").transport.auth+ assert isinstance(other, OAuth)+ assert await other.token_storage_adapter.get_tokens() is None++ assert not emitted+ files = [path for path in tmp_path.rglob("*") if path.is_file()]+ assert files+ for path in files:+ contents = path.read_bytes()+ for secret in (+ tokens.access_token,+ tokens.refresh_token,+ registration.client_secret,+ ):+ assert secret is not None+ assert secret.encode() not in contents++ @pytest.mark.parametrize("key", [None, ""])+ async def test_unconfigured_oauth_is_quiet_and_ephemeral(+ self,+ key: str | None,+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ ) -> None:+ if key is None:+ monkeypatch.delenv("FASTMCP_OAUTH_ENCRYPTION_KEY", raising=False)+ else:+ monkeypatch.setenv("FASTMCP_OAUTH_ENCRYPTION_KEY", key)++ with temporary_settings(**Settings(home=tmp_path, _env_file=None).model_dump()):+ with warnings.catch_warnings(record=True) as emitted:+ warnings.simplefilter("always")+ first = _build_client("https://example.com/mcp").transport.auth+ second = _build_client("https://example.com/mcp").transport.auth+ assert not emitted+ assert isinstance(first, OAuth) and isinstance(second, OAuth)+ await first.token_storage_adapter.set_tokens(+ OAuthToken(access_token="ephemeral-token", token_type="Bearer")+ )+ assert await second.token_storage_adapter.get_tokens() is None+ assert not list(tmp_path.iterdir())+ with pytest.warns(UserWarning, match="Using in-memory token storage"):+ OAuth("https://example.com/mcp")++ async def test_changed_key_does_not_reuse_encrypted_tokens(+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+ ) -> None:+ original_key = Fernet.generate_key().decode()+ monkeypatch.setenv("FASTMCP_OAUTH_ENCRYPTION_KEY", original_key)+ with temporary_settings(**Settings(home=tmp_path, _env_file=None).model_dump()):+ first = _build_client("https://example.com/mcp").transport.auth+ assert isinstance(first, OAuth)+ await first.token_storage_adapter.set_tokens(+ OAuthToken(access_token="original-key-token", token_type="Bearer")+ )++ monkeypatch.setenv(+ "FASTMCP_OAUTH_ENCRYPTION_KEY", Fernet.generate_key().decode()+ )+ with temporary_settings(**Settings(home=tmp_path, _env_file=None).model_dump()):+ changed = _build_client("https://example.com/mcp").transport.auth+ assert isinstance(changed, OAuth)+ assert await changed.token_storage_adapter.get_tokens() is None+ await changed.token_storage_adapter.set_tokens(+ OAuthToken(access_token="changed-key-token", token_type="Bearer")+ )++ monkeypatch.setenv("FASTMCP_OAUTH_ENCRYPTION_KEY", original_key)+ with temporary_settings(**Settings(home=tmp_path, _env_file=None).model_dump()):+ restored = _build_client("https://example.com/mcp").transport.auth+ assert isinstance(restored, OAuth)+ tokens = await restored.token_storage_adapter.get_tokens()+ assert tokens is not None and tokens.access_token == "original-key-token"++ @pytest.mark.parametrize("auth", ["none", "synthetic-bearer-token"])+ def test_unused_invalid_key_does_not_break_explicit_auth(+ self, auth: str, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+ ) -> None:+ monkeypatch.setenv("FASTMCP_OAUTH_ENCRYPTION_KEY", "invalid-key")+ with temporary_settings(**Settings(home=tmp_path, _env_file=None).model_dump()):+ _build_client("https://example.com/mcp", auth=auth)+def test_http_target_gets_oauth_by_default(self):client = _build_client("http://localhost:8000/mcp")# OAuth is applied during Client init via _set_auth@@ -390,6 +524,48 @@ class TestBuildClient:assert client.transport is not None[email protected]("command", ["list", "call"])+async def test_invalid_oauth_key_is_a_cli_error(+ command: str,+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ capsys: pytest.CaptureFixture[str],+) -> None:+ monkeypatch.setenv("FASTMCP_OAUTH_ENCRYPTION_KEY", "invalid-key")+ with temporary_settings(**Settings(home=tmp_path, _env_file=None).model_dump()):+ with pytest.raises(SystemExit) as exc_info:+ if command == "list":+ await list_command("https://example.com/mcp")+ else:+ await call_command("https://example.com/mcp", "greet")+ assert exc_info.value.code == 1+ output = capsys.readouterr()+ assert "FASTMCP_OAUTH_ENCRYPTION_KEY" in output.out+ assert "Fernet" in output.out+ assert "invalid-key" not in output.out + output.err+ assert "Traceback" not in output.out + output.err+++def test_named_oauth_server_is_quiet(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ server = client_module.DiscoveredServer(+ name="weather",+ source="project",+ config=RemoteMCPServer(url="https://example.com/mcp", auth="oauth"),+ config_path=tmp_path / "mcp.json",+ )+ monkeypatch.setattr(+ "fastmcp.cli.discovery.discover_servers", lambda start_dir: [server]+ )+ monkeypatch.delenv("FASTMCP_OAUTH_ENCRYPTION_KEY", raising=False)+ with temporary_settings(**Settings(home=tmp_path, _env_file=None).model_dump()):+ with warnings.catch_warnings(record=True) as emitted:+ warnings.simplefilter("always")+ _build_client(resolve_server_spec("weather"))+ assert not emitted++# ---------------------------------------------------------------------------# Integration tests β invoke actual CLI commands via monkeypatched _build_client# ---------------------------------------------------------------------------