mcp-owner-auth 0.1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,108 @@
1
+ Metadata-Version: 2.4
2
+ Name: mcp-owner-auth
3
+ Version: 0.1.1
4
+ Summary: Single-user OAuth 2.1 (password + TOTP) for self-hosted MCP servers used from claude.ai
5
+ Keywords: mcp,model-context-protocol,oauth,totp,claude
6
+ Author: Emil Madsen
7
+ License-Expression: Apache-2.0
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3.13
11
+ Classifier: Topic :: Security
12
+ Classifier: Typing :: Typed
13
+ Requires-Dist: argon2-cffi>=25.1.0
14
+ Requires-Dist: mcp>=2.3.0
15
+ Requires-Dist: pyotp>=2.12.0
16
+ Requires-Dist: qrcode>=8.2
17
+ Requires-Dist: uvicorn>=0.30
18
+ Requires-Python: >=3.13
19
+ Project-URL: Homepage, https://github.com/EmilbMadsen/mcp-owner-auth
20
+ Description-Content-Type: text/markdown
21
+
22
+ # mcp-owner-auth
23
+
24
+ Single-user OAuth 2.1 for self-hosted [MCP](https://modelcontextprotocol.io) servers that you use
25
+ from claude.ai and the Claude mobile app.
26
+
27
+ It turns an `MCPServer` (MCP Python SDK v2) into a Streamable HTTP app where the server is both
28
+ authorization server and resource server, for **exactly one owner and one client**:
29
+
30
+ - One static OAuth client (for claude.ai: *Add custom connector → Use your own OAuth client*).
31
+ No dynamic client registration, no client ID metadata documents.
32
+ - Login with username + password (argon2id) + TOTP, CSRF protection, no JavaScript, rate limit
33
+ (5 failures per IP per 15 min) and a lockout after 20 failures in 24 h.
34
+ - PKCE S256 only, exact `redirect_uri` allowlist, RFC 8707 `resource` binding, RFC 9207 `iss`.
35
+ - Opaque tokens stored only as SHA-256 hashes: access tokens 1 h, refresh tokens 30 days, rotated
36
+ on every use, reuse of a used refresh token revokes the whole family.
37
+ - `auth revoke-all` takes effect on the next request, without a restart.
38
+ - Host-header allowlist, body limit, timeout, optional IP allowlist on `/mcp` and `/token`,
39
+ JSON-lines audit log of tool calls (no results, no secrets), strict security headers.
40
+ - Fallback `static_bearer` mode for clients that can send a fixed `Authorization` header.
41
+
42
+ It is meant for personal, self-hosted servers. It is not a general-purpose identity provider.
43
+ See [SECURITY.md](SECURITY.md) for the threat model and design.
44
+
45
+ ## Use
46
+
47
+ ```python
48
+ from pathlib import Path
49
+ from mcp_owner_auth import OwnerAuthConfig, serve
50
+ from mcp_owner_auth import cli as auth_cli
51
+
52
+ config = OwnerAuthConfig.from_env(
53
+ "MY_MCP", # reads MY_MCP_PUBLIC_URL, MY_MCP_AUTH_MODE, ...
54
+ state_dir=Path("/data"),
55
+ app_name="My Data",
56
+ command="my-mcp",
57
+ scope="mydata:read",
58
+ consent="read-only access to your data",
59
+ )
60
+ serve(server, config, host="0.0.0.0", port=8000) # server: your MCPServer
61
+ ```
62
+
63
+ Add the CLI to your own argparse:
64
+
65
+ ```python
66
+ auth_cli.add_parser(subcommands)
67
+ ...
68
+ if args.command == "auth":
69
+ sys.exit(
70
+ auth_cli.run(
71
+ args.action,
72
+ auth_db=state / "auth.db",
73
+ app_name="My Data",
74
+ command="my-mcp",
75
+ force=args.force,
76
+ redirect_uris=args.redirect_uri,
77
+ )
78
+ )
79
+ ```
80
+
81
+ Then `my-mcp auth init` (username, password, TOTP QR code, prints the client ID and secret once),
82
+ `auth status`, `auth rotate-client`, `auth revoke-all`, `auth unlock`.
83
+
84
+ ### Environment
85
+
86
+ | Variable | Meaning |
87
+ |---|---|
88
+ | `<PREFIX>_PUBLIC_URL` | public base URL, e.g. `https://mcp.example.com` (https; http only for localhost) |
89
+ | `<PREFIX>_AUTH_MODE` | `oauth` (default) or `static_bearer` |
90
+ | `<PREFIX>_STATIC_BEARER_FILE` | file with the static token (at least 32 characters) |
91
+ | `<PREFIX>_ALLOWED_CIDRS` | optional comma-separated allowlist for `/mcp` and `/token` |
92
+ | `<PREFIX>_CLIENT_IP_HEADER` | e.g. `CF-Connecting-IP`; only when the app is reachable solely through that proxy |
93
+
94
+ ### Routes
95
+
96
+ `/mcp`, `/.well-known/oauth-protected-resource/mcp`, `/.well-known/oauth-authorization-server`,
97
+ `/authorize`, `/token`, `/login`, `/consent`, `/healthz`.
98
+
99
+ ## License
100
+
101
+ Apache-2.0
102
+
103
+ ## Releasing
104
+
105
+ Releases go to PyPI from GitHub Actions with trusted publishing (no API token anywhere). Bump
106
+ `version` in `pyproject.toml`, commit, then push a matching tag (`git tag v0.1.1 && git push
107
+ origin v0.1.1`). One-time setup on pypi.org: a trusted publisher for project `mcp-owner-auth`,
108
+ owner `EmilbMadsen`, repository `mcp-owner-auth`, workflow `release.yml`, environment `pypi`.
@@ -0,0 +1,87 @@
1
+ # mcp-owner-auth
2
+
3
+ Single-user OAuth 2.1 for self-hosted [MCP](https://modelcontextprotocol.io) servers that you use
4
+ from claude.ai and the Claude mobile app.
5
+
6
+ It turns an `MCPServer` (MCP Python SDK v2) into a Streamable HTTP app where the server is both
7
+ authorization server and resource server, for **exactly one owner and one client**:
8
+
9
+ - One static OAuth client (for claude.ai: *Add custom connector → Use your own OAuth client*).
10
+ No dynamic client registration, no client ID metadata documents.
11
+ - Login with username + password (argon2id) + TOTP, CSRF protection, no JavaScript, rate limit
12
+ (5 failures per IP per 15 min) and a lockout after 20 failures in 24 h.
13
+ - PKCE S256 only, exact `redirect_uri` allowlist, RFC 8707 `resource` binding, RFC 9207 `iss`.
14
+ - Opaque tokens stored only as SHA-256 hashes: access tokens 1 h, refresh tokens 30 days, rotated
15
+ on every use, reuse of a used refresh token revokes the whole family.
16
+ - `auth revoke-all` takes effect on the next request, without a restart.
17
+ - Host-header allowlist, body limit, timeout, optional IP allowlist on `/mcp` and `/token`,
18
+ JSON-lines audit log of tool calls (no results, no secrets), strict security headers.
19
+ - Fallback `static_bearer` mode for clients that can send a fixed `Authorization` header.
20
+
21
+ It is meant for personal, self-hosted servers. It is not a general-purpose identity provider.
22
+ See [SECURITY.md](SECURITY.md) for the threat model and design.
23
+
24
+ ## Use
25
+
26
+ ```python
27
+ from pathlib import Path
28
+ from mcp_owner_auth import OwnerAuthConfig, serve
29
+ from mcp_owner_auth import cli as auth_cli
30
+
31
+ config = OwnerAuthConfig.from_env(
32
+ "MY_MCP", # reads MY_MCP_PUBLIC_URL, MY_MCP_AUTH_MODE, ...
33
+ state_dir=Path("/data"),
34
+ app_name="My Data",
35
+ command="my-mcp",
36
+ scope="mydata:read",
37
+ consent="read-only access to your data",
38
+ )
39
+ serve(server, config, host="0.0.0.0", port=8000) # server: your MCPServer
40
+ ```
41
+
42
+ Add the CLI to your own argparse:
43
+
44
+ ```python
45
+ auth_cli.add_parser(subcommands)
46
+ ...
47
+ if args.command == "auth":
48
+ sys.exit(
49
+ auth_cli.run(
50
+ args.action,
51
+ auth_db=state / "auth.db",
52
+ app_name="My Data",
53
+ command="my-mcp",
54
+ force=args.force,
55
+ redirect_uris=args.redirect_uri,
56
+ )
57
+ )
58
+ ```
59
+
60
+ Then `my-mcp auth init` (username, password, TOTP QR code, prints the client ID and secret once),
61
+ `auth status`, `auth rotate-client`, `auth revoke-all`, `auth unlock`.
62
+
63
+ ### Environment
64
+
65
+ | Variable | Meaning |
66
+ |---|---|
67
+ | `<PREFIX>_PUBLIC_URL` | public base URL, e.g. `https://mcp.example.com` (https; http only for localhost) |
68
+ | `<PREFIX>_AUTH_MODE` | `oauth` (default) or `static_bearer` |
69
+ | `<PREFIX>_STATIC_BEARER_FILE` | file with the static token (at least 32 characters) |
70
+ | `<PREFIX>_ALLOWED_CIDRS` | optional comma-separated allowlist for `/mcp` and `/token` |
71
+ | `<PREFIX>_CLIENT_IP_HEADER` | e.g. `CF-Connecting-IP`; only when the app is reachable solely through that proxy |
72
+
73
+ ### Routes
74
+
75
+ `/mcp`, `/.well-known/oauth-protected-resource/mcp`, `/.well-known/oauth-authorization-server`,
76
+ `/authorize`, `/token`, `/login`, `/consent`, `/healthz`.
77
+
78
+ ## License
79
+
80
+ Apache-2.0
81
+
82
+ ## Releasing
83
+
84
+ Releases go to PyPI from GitHub Actions with trusted publishing (no API token anywhere). Bump
85
+ `version` in `pyproject.toml`, commit, then push a matching tag (`git tag v0.1.1 && git push
86
+ origin v0.1.1`). One-time setup on pypi.org: a trusted publisher for project `mcp-owner-auth`,
87
+ owner `EmilbMadsen`, repository `mcp-owner-auth`, workflow `release.yml`, environment `pypi`.
@@ -0,0 +1,80 @@
1
+ [project]
2
+ name = "mcp-owner-auth"
3
+ version = "0.1.1"
4
+ description = "Single-user OAuth 2.1 (password + TOTP) for self-hosted MCP servers used from claude.ai"
5
+ readme = "README.md"
6
+ license = "Apache-2.0"
7
+ requires-python = ">=3.13"
8
+ keywords = [
9
+ "mcp",
10
+ "model-context-protocol",
11
+ "oauth",
12
+ "totp",
13
+ "claude",
14
+ ]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.13",
19
+ "Topic :: Security",
20
+ "Typing :: Typed",
21
+ ]
22
+ dependencies = [
23
+ "argon2-cffi>=25.1.0",
24
+ "mcp>=2.3.0",
25
+ "pyotp>=2.12.0",
26
+ "qrcode>=8.2",
27
+ "uvicorn>=0.30",
28
+ ]
29
+
30
+ [[project.authors]]
31
+ name = "Emil Madsen"
32
+
33
+ [project.urls]
34
+ Homepage = "https://github.com/EmilbMadsen/mcp-owner-auth"
35
+
36
+ [build-system]
37
+ requires = ["uv_build>=0.9.2,<0.10.0"]
38
+ build-backend = "uv_build"
39
+
40
+ [dependency-groups]
41
+ dev = [
42
+ "httpx>=0.28",
43
+ "mypy>=2.4.1",
44
+ "pytest>=9.2.0",
45
+ "pytest-asyncio>=1.5.0",
46
+ "ruff>=0.17.5",
47
+ ]
48
+
49
+ [tool.ruff]
50
+ line-length = 100
51
+ target-version = "py313"
52
+
53
+ [tool.ruff.lint]
54
+ select = [
55
+ "E",
56
+ "F",
57
+ "W",
58
+ "I",
59
+ "B",
60
+ "UP",
61
+ "SIM",
62
+ "RUF",
63
+ ]
64
+
65
+ [tool.mypy]
66
+ python_version = "3.13"
67
+ strict = true
68
+ files = [
69
+ "src",
70
+ "tests",
71
+ ]
72
+
73
+ [[tool.mypy.overrides]]
74
+ module = ["qrcode.*"]
75
+ ignore_missing_imports = true
76
+
77
+ [tool.pytest.ini_options]
78
+ testpaths = ["tests"]
79
+ asyncio_mode = "auto"
80
+ asyncio_default_fixture_loop_scope = "function"
@@ -0,0 +1,60 @@
1
+ [project]
2
+ name = "mcp-owner-auth"
3
+ version = "0.1.1"
4
+ description = "Single-user OAuth 2.1 (password + TOTP) for self-hosted MCP servers used from claude.ai"
5
+ readme = "README.md"
6
+ license = "Apache-2.0"
7
+ authors = [{ name = "Emil Madsen" }]
8
+ requires-python = ">=3.13"
9
+ keywords = ["mcp", "model-context-protocol", "oauth", "totp", "claude"]
10
+ classifiers = [
11
+ "Development Status :: 3 - Alpha",
12
+ "Programming Language :: Python :: 3",
13
+ "Programming Language :: Python :: 3.13",
14
+ "Topic :: Security",
15
+ "Typing :: Typed",
16
+ ]
17
+ dependencies = [
18
+ "argon2-cffi>=25.1.0",
19
+ "mcp>=2.3.0",
20
+ "pyotp>=2.12.0",
21
+ "qrcode>=8.2",
22
+ "uvicorn>=0.30",
23
+ ]
24
+
25
+ [project.urls]
26
+ Homepage = "https://github.com/EmilbMadsen/mcp-owner-auth"
27
+
28
+ [build-system]
29
+ requires = ["uv_build>=0.9.2,<0.10.0"]
30
+ build-backend = "uv_build"
31
+
32
+ [dependency-groups]
33
+ dev = [
34
+ "httpx>=0.28",
35
+ "mypy>=2.4.1",
36
+ "pytest>=9.2.0",
37
+ "pytest-asyncio>=1.5.0",
38
+ "ruff>=0.17.5",
39
+ ]
40
+
41
+ [tool.ruff]
42
+ line-length = 100
43
+ target-version = "py313"
44
+
45
+ [tool.ruff.lint]
46
+ select = ["E", "F", "W", "I", "B", "UP", "SIM", "RUF"]
47
+
48
+ [tool.mypy]
49
+ python_version = "3.13"
50
+ strict = true
51
+ files = ["src", "tests"]
52
+
53
+ [[tool.mypy.overrides]]
54
+ module = ["qrcode.*"]
55
+ ignore_missing_imports = true
56
+
57
+ [tool.pytest.ini_options]
58
+ testpaths = ["tests"]
59
+ asyncio_mode = "auto"
60
+ asyncio_default_fixture_loop_scope = "function"
@@ -0,0 +1,10 @@
1
+ """Single-user OAuth 2.1 for self-hosted MCP servers.
2
+
3
+ One owner, one static client (e.g. claude.ai), password + TOTP login, short-lived opaque tokens
4
+ with rotation and reuse detection, and an emergency ``auth revoke-all``. See the README.
5
+ """
6
+
7
+ from .app import build_app, serve
8
+ from .config import ConfigError, OwnerAuthConfig
9
+
10
+ __all__ = ["ConfigError", "OwnerAuthConfig", "build_app", "serve"]
@@ -0,0 +1,278 @@
1
+ """The remote (Streamable HTTP) application: MCP endpoint, OAuth routes and security layers.
2
+
3
+ Routes:
4
+
5
+ - ``/mcp``: the MCP endpoint (bearer token required)
6
+ - ``/.well-known/oauth-protected-resource/mcp``: RFC 9728 metadata
7
+ - ``/.well-known/oauth-authorization-server``: RFC 8414 metadata
8
+ - ``/authorize``, ``/token``: OAuth 2.1 with PKCE (S256) for the one static client
9
+ - ``/login``, ``/consent``: password + TOTP sign-in and consent
10
+ - ``/healthz``: liveness for the container (returns ``ok``, nothing else)
11
+
12
+ Layers around everything: Host-header allowlist, request body limit, request timeout, optional IP
13
+ allowlist on ``/mcp`` and ``/token``, and a JSON-lines audit log of tool calls.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import ipaddress
19
+ import json
20
+ import logging
21
+ import os
22
+ import time
23
+ from collections.abc import Awaitable, Callable
24
+ from pathlib import Path
25
+ from typing import Any
26
+
27
+ import anyio
28
+ from mcp.server.auth.handlers.authorize import AuthorizationHandler
29
+ from mcp.server.auth.handlers.metadata import MetadataHandler
30
+ from mcp.server.auth.handlers.token import TokenHandler
31
+ from mcp.server.auth.routes import build_metadata
32
+ from mcp.server.auth.settings import AuthSettings, ClientRegistrationOptions, RevocationOptions
33
+ from mcp.server.mcpserver import MCPServer
34
+ from mcp.server.transport_security import TransportSecuritySettings
35
+ from starlette.requests import Request
36
+ from starlette.responses import PlainTextResponse, Response
37
+ from starlette.routing import Route
38
+ from starlette.types import ASGIApp, Message, Receive, Scope, Send
39
+
40
+ from .config import ConfigError, OwnerAuthConfig
41
+ from .provider import (
42
+ OwnerOAuthProvider,
43
+ StaticBearerVerifier,
44
+ StaticClientAuthenticator,
45
+ StoreTokenVerifier,
46
+ )
47
+ from .store import AuthStore
48
+ from .web import client_ip, login_routes
49
+
50
+ _LOGGER = logging.getLogger(__name__)
51
+
52
+ MAX_BODY_BYTES = 256 * 1024
53
+ REQUEST_TIMEOUT_SECONDS = 120.0
54
+ IP_RESTRICTED_PATHS = ("/mcp", "/token")
55
+
56
+
57
+ # -- ASGI layers ------------------------------------------------------------------------------
58
+
59
+
60
+ async def _plain(send: Send, status: int, text: str) -> None:
61
+ await send(
62
+ {
63
+ "type": "http.response.start",
64
+ "status": status,
65
+ "headers": [(b"content-type", b"text/plain; charset=utf-8")],
66
+ }
67
+ )
68
+ await send({"type": "http.response.body", "body": text.encode()})
69
+
70
+
71
+ class GuardMiddleware:
72
+ """Host allowlist, body size limit, timeout and optional IP allowlist for every request."""
73
+
74
+ def __init__(self, app: ASGIApp, config: OwnerAuthConfig) -> None:
75
+ self.app = app
76
+ self.config = config
77
+
78
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
79
+ if scope["type"] != "http":
80
+ await self.app(scope, receive, send)
81
+ return
82
+ request = Request(scope)
83
+ host = request.headers.get("host", "")
84
+ path = scope.get("path", "")
85
+ if host != self.config.host and path != "/healthz": # container health check
86
+ await _plain(send, 421, "Misdirected request")
87
+ return
88
+ if self.config.allowed_cidrs and path.startswith(IP_RESTRICTED_PATHS):
89
+ try:
90
+ ip = ipaddress.ip_address(client_ip(request, self.config.client_ip_header))
91
+ allowed = any(ip in network for network in self.config.allowed_cidrs)
92
+ except ValueError:
93
+ allowed = False
94
+ if not allowed:
95
+ await _plain(send, 403, "Forbidden")
96
+ return
97
+ length = request.headers.get("content-length")
98
+ if length is not None and (not length.isdigit() or int(length) > MAX_BODY_BYTES):
99
+ await _plain(send, 413, "Request body too large")
100
+ return
101
+
102
+ received = 0
103
+ started = False
104
+
105
+ async def limited_receive() -> Message:
106
+ nonlocal received
107
+ message = await receive()
108
+ if message["type"] == "http.request":
109
+ received += len(message.get("body", b""))
110
+ if received > MAX_BODY_BYTES:
111
+ raise _BodyTooLarge
112
+ return message
113
+
114
+ async def tracking_send(message: Message) -> None:
115
+ nonlocal started
116
+ if message["type"] == "http.response.start":
117
+ started = True
118
+ await send(message)
119
+
120
+ try:
121
+ with anyio.fail_after(REQUEST_TIMEOUT_SECONDS):
122
+ await self.app(scope, limited_receive, tracking_send)
123
+ except _BodyTooLarge:
124
+ if not started:
125
+ await _plain(send, 413, "Request body too large")
126
+ except TimeoutError:
127
+ _LOGGER.warning("request timed out: %s", path)
128
+ if not started:
129
+ await _plain(send, 504, "Timeout")
130
+
131
+
132
+ class _BodyTooLarge(Exception):
133
+ pass
134
+
135
+
136
+ class AuditMiddleware:
137
+ """MCP middleware writing one JSON line per tool call: time, tool, arguments, status,
138
+ duration. Tool arguments here are dates, IDs, limits and flags; results are never logged."""
139
+
140
+ def __init__(self, path: Path) -> None:
141
+ self.path = path
142
+
143
+ async def __call__(self, ctx: Any, call_next: Callable[[Any], Awaitable[Any]]) -> Any:
144
+ if getattr(ctx, "method", None) != "tools/call":
145
+ return await call_next(ctx)
146
+ params = ctx.params or {}
147
+ started = time.monotonic()
148
+ status = "ok"
149
+ try:
150
+ result = await call_next(ctx)
151
+ if getattr(result, "is_error", False) or (
152
+ isinstance(result, dict) and result.get("isError")
153
+ ):
154
+ status = "tool_error"
155
+ return result
156
+ except BaseException:
157
+ status = "error"
158
+ raise
159
+ finally:
160
+ self._write(
161
+ {
162
+ "time": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
163
+ "tool": str(params.get("name", "")),
164
+ "arguments": _safe_arguments(params.get("arguments")),
165
+ "status": status,
166
+ "ms": round((time.monotonic() - started) * 1000),
167
+ }
168
+ )
169
+
170
+ def _write(self, entry: dict[str, Any]) -> None:
171
+ try:
172
+ descriptor = os.open(self.path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
173
+ with os.fdopen(descriptor, "a", encoding="utf-8") as handle:
174
+ handle.write(json.dumps(entry) + "\n")
175
+ except OSError:
176
+ _LOGGER.warning("could not write the audit log")
177
+
178
+
179
+ def _safe_arguments(arguments: Any) -> dict[str, Any]:
180
+ if not isinstance(arguments, dict):
181
+ return {}
182
+ safe: dict[str, Any] = {}
183
+ for key, value in arguments.items():
184
+ if isinstance(value, bool | int | float) or (isinstance(value, str) and len(value) <= 40):
185
+ safe[str(key)] = value
186
+ else:
187
+ safe[str(key)] = "<omitted>"
188
+ return safe
189
+
190
+
191
+ # -- application ------------------------------------------------------------------------------
192
+
193
+
194
+ def build_app(server: MCPServer[Any], config: OwnerAuthConfig) -> ASGIApp:
195
+ """The complete ASGI app for ``server``: MCP endpoint, OAuth routes and all layers."""
196
+ # model_validate keeps the issuer exactly as configured (no trailing slash): RFC 8414 and
197
+ # RFC 9207 compare issuers as plain strings.
198
+ auth_settings = AuthSettings.model_validate(
199
+ {
200
+ "issuer_url": config.public_url,
201
+ "resource_server_url": config.resource,
202
+ "required_scopes": [config.scope],
203
+ "validate_token_resource": True,
204
+ "client_registration_options": ClientRegistrationOptions(enabled=False),
205
+ "revocation_options": RevocationOptions(enabled=False),
206
+ }
207
+ )
208
+
209
+ async def healthz(_: Request) -> Response:
210
+ return PlainTextResponse("ok")
211
+
212
+ routes: list[Route] = [Route("/healthz", healthz, methods=["GET"])]
213
+ if config.auth_mode == "static_bearer":
214
+ assert config.static_bearer_file is not None
215
+ secret = config.static_bearer_file.read_text(encoding="utf-8").strip()
216
+ verifier: Any = StaticBearerVerifier(secret, config.resource, config.scope)
217
+ else:
218
+ store = AuthStore(config.auth_db)
219
+ if not store.initialized():
220
+ raise ConfigError(f"OAuth is not set up. Run `{config.command} auth init` first.")
221
+ provider = OwnerOAuthProvider(
222
+ store, public_url=config.public_url, resource=config.resource, scope=config.scope
223
+ )
224
+ verifier = StoreTokenVerifier(provider)
225
+ metadata = build_metadata(
226
+ auth_settings.issuer_url,
227
+ None,
228
+ ClientRegistrationOptions(enabled=False),
229
+ RevocationOptions(enabled=False),
230
+ )
231
+ token_handler = TokenHandler(provider, StaticClientAuthenticator(provider)) # type: ignore[arg-type]
232
+ routes += [
233
+ Route("/.well-known/oauth-authorization-server", MetadataHandler(metadata).handle),
234
+ Route(
235
+ "/authorize",
236
+ AuthorizationHandler(provider).handle, # type: ignore[arg-type]
237
+ methods=["GET", "POST"],
238
+ ),
239
+ Route("/token", token_handler.handle, methods=["POST"]),
240
+ *login_routes(store, provider, config),
241
+ ]
242
+
243
+ server.middleware[:] = [m for m in server.middleware if not isinstance(m, AuditMiddleware)]
244
+ server.middleware.append(AuditMiddleware(config.audit_log))
245
+ app = server._lowlevel_server.streamable_http_app(
246
+ streamable_http_path="/mcp",
247
+ json_response=True,
248
+ stateless_http=True,
249
+ max_request_body_size=MAX_BODY_BYTES,
250
+ transport_security=TransportSecuritySettings(
251
+ enable_dns_rebinding_protection=True,
252
+ allowed_hosts=[config.host],
253
+ allowed_origins=[config.public_url, "https://claude.ai"],
254
+ ),
255
+ auth=auth_settings,
256
+ token_verifier=verifier,
257
+ custom_starlette_routes=routes,
258
+ )
259
+ return GuardMiddleware(app, config)
260
+
261
+
262
+ def serve(server: MCPServer[Any], config: OwnerAuthConfig, host: str, port: int) -> None:
263
+ """Run ``server`` over Streamable HTTP with uvicorn (blocking)."""
264
+ import uvicorn
265
+
266
+ app = build_app(server, config)
267
+ logging.getLogger(__name__).info("serving %s (auth: %s)", config.resource, config.auth_mode)
268
+ uvicorn.run(
269
+ app,
270
+ host=host,
271
+ port=port,
272
+ proxy_headers=False,
273
+ server_header=False,
274
+ date_header=False,
275
+ timeout_keep_alive=5,
276
+ limit_concurrency=64,
277
+ log_level="warning",
278
+ )