Metadata-Version: 2.5
Name: fastmcp-seaworthy
Version: 0.3.0
Summary: Production building blocks for FastMCP servers: serve one server under several public hostnames, each a full OAuth identity, and keep the OAuth proxy's state across restarts and secret rotations.
Project-URL: Homepage, https://github.com/stephaneberle9/fastmcp-seaworthy
Project-URL: Issues, https://github.com/stephaneberle9/fastmcp-seaworthy/issues
Author-email: Stephan Eberle <stephaneberle9@gmail.com>
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: deployment,dynamodb,fastmcp,mcp,oauth,postgresql
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
Requires-Python: >=3.10
Requires-Dist: cryptography>=45.0.0
Requires-Dist: fastmcp<5,>=4.0.8
Requires-Dist: mcp>=2.0.0
Requires-Dist: py-key-value-aio>=0.4.4
Requires-Dist: pydantic>=2.12.0
Requires-Dist: starlette>=0.27
Requires-Dist: uvicorn>=0.35
Provides-Extra: dynamodb
Requires-Dist: py-key-value-aio[dynamodb]>=0.4.4; extra == 'dynamodb'
Provides-Extra: postgres
Requires-Dist: asyncpg>=0.30.0; extra == 'postgres'
Requires-Dist: py-key-value-aio[postgresql]>=0.4.4; extra == 'postgres'
Description-Content-Type: text/markdown

# fastmcp-seaworthy <!-- omit in toc -->

Production building blocks for [FastMCP](https://gofastmcp.com) servers: serve
one server under several public hostnames, each a full OAuth identity, keep
the OAuth proxy's state across restarts and rotations of the upstream client
secret, and limit which MCP clients may connect.

A FastMCP server that runs fine on a laptop can still fail in production: it
answers OAuth discovery under one hostname only, and with an `OAuthProxy`-based
auth provider (`OIDCProxy`, `AWSCognitoProvider`, `GoogleProvider`,
`AzureProvider`, ...) every container restart signs every user out. This
library closes both gaps with the same settings and the same code in every
server that uses it.

> [!NOTE]
> An independent project, not affiliated with PrefectHQ, the maintainers of
> FastMCP.

- [What Is This For](#what-is-this-for)
- [Installation](#installation)
- [Usage](#usage)
  - [Serving several hostnames](#serving-several-hostnames)
  - [Surviving restarts](#surviving-restarts)
  - [Limiting which clients connect](#limiting-which-clients-connect)
  - [All together](#all-together)
- [Configuration](#configuration)
  - [Environment variables](#environment-variables)
  - [DynamoDB table](#dynamodb-table)
  - [PostgreSQL table](#postgresql-table)
- [API Reference](#api-reference)
  - [`serve_http`](#serve_http)
  - [`build_host_router`](#build_host_router)
  - [`OAuthStateSettings`](#oauthstatesettings)
  - [`build_client_storage`](#build_client_storage)
  - [`ClientStorage`](#clientstorage)
  - [`ClientAllowlist`](#clientallowlist)
  - [`HostRouter`](#hostrouter)
  - [Helpers](#helpers)
- [Contributing](#contributing)
- [License](#license)

## What Is This For

Typical use cases:

- Reaching one MCP server under an alias domain, for clients whose networks
  block the primary TLD.
- Running an MCP server with an `OAuthProxy`-based provider on Kubernetes,
  where the container filesystem — and with it FastMCP's default OAuth state
  store — does not survive a restart.
- Rotating the upstream IdP's client secret without invalidating every issued
  token and every client registration.
- Running several replicas of one MCP server that share their OAuth state.
- Accepting only MCP clients whose vendors the operator has vetted, because
  the client sends the tool results to its vendor's LLM.

## Installation

```bash
pip install fastmcp-seaworthy
# or, with uv:
uv add fastmcp-seaworthy
```

The DynamoDB store backend needs the `dynamodb` extra, the PostgreSQL one the
`postgres` extra:

```bash
pip install 'fastmcp-seaworthy[dynamodb]'
pip install 'fastmcp-seaworthy[postgres]'
# or, with uv:
uv add 'fastmcp-seaworthy[dynamodb]'
uv add 'fastmcp-seaworthy[postgres]'
```

Requires Python 3.10+ and FastMCP 4.

## Usage

### Serving several hostnames

A FastMCP auth provider is built around one `base_url`, which it advertises
everywhere: in the protected-resource and authorization-server metadata, as the
`redirect_uri` sent to the IdP, and in the tokens it mints. FastMCP never
derives it from the request, so a provider can answer as one hostname only.
Adding a second host at the ingress fixes TLS and routing, but the server keeps
sending clients to the first hostname — the one the alias exists to avoid.

`serve_http` builds one app per base URL, each with its own provider, over one
shared FastMCP server, and routes requests between them on the `Host` header:

```python
import asyncio
import os

from fastmcp import FastMCP
from fastmcp.server.auth.providers.aws import AWSCognitoProvider
from fastmcp_seaworthy import serve_http, split_base_urls

# No auth= here: it is supplied per hostname below.
mcp = FastMCP(name="my-server")


def auth_for(base_url: str) -> AWSCognitoProvider:
    return AWSCognitoProvider(
        user_pool_id=os.environ["COGNITO_USER_POOL_ID"],
        aws_region=os.environ["COGNITO_AWS_REGION"],
        client_id=os.environ["COGNITO_CLIENT_ID"],
        client_secret=os.environ["COGNITO_CLIENT_SECRET"],
        base_url=base_url,
    )


asyncio.run(
    serve_http(
        mcp,
        # e.g. "https://mcp.example.io,https://mcp.example.com"
        split_base_urls(os.environ["BASE_URLS"]),
        auth_for,
        host="0.0.0.0",
        port=8080,
    )
)
```

The first base URL is **canonical**: it answers requests with no or an unknown
`Host` header, such as container health probes addressing the pod IP. Register
`{base_url}/auth/callback` as an allowed redirect URI with your IdP for every
entry. With a single base URL, the same code serves one identity.

### Surviving restarts

An `OAuthProxy` keeps state — the clients registered through DCR, the upstream
IdP's tokens, and the mapping from the tokens it issued to them — and signs its
tokens with a signing key. By default FastMCP keeps the state in an encrypted
file store under `${FASTMCP_HOME}` and derives the signing key from the upstream
client secret. A container restart then loses all state, and a secret rotation
strands it.

`OAuthStateSettings` reads a stable signing key and an external store from the
environment, `build_client_storage` builds that store, encrypted the way FastMCP
encrypts its own, and `provider_kwargs` hands both to the provider:

```python
from fastmcp_seaworthy import OAuthStateSettings, build_client_storage

settings = OAuthStateSettings.from_env()
storage = build_client_storage(settings)  # None for FastMCP's default file store

provider = AWSCognitoProvider(
    ...,
    **settings.provider_kwargs(storage),
)
```

`STORE_BACKEND` selects where the state lives:

| `STORE_BACKEND` | State lives in | Survives | Extra |
| --- | --- | --- | --- |
| `file` (default) | FastMCP's own encrypted file store under `${FASTMCP_HOME}` | restarts on a VM disk or a mounted volume; not a container filesystem | none |
| `dynamodb` | a DynamoDB table, shared by every replica (see [DynamoDB table](#dynamodb-table)) | any restart | `dynamodb` |
| `postgres` | a PostgreSQL table, shared by every replica (see [PostgreSQL table](#postgresql-table)) | any restart | `postgres` |

Open the store before serving, so a missing table or missing permissions fail
the rollout rather than the first sign-in, and close it afterwards —
`serve_http` does both when given the store. Build it once per process: every
hostname's provider shares the one store, and with it the one DynamoDB client
or PostgreSQL connection pool.

### Limiting which clients connect

Registration tells an OAuth server which client software is asking, never
which user. Where tool results may only reach service providers the operator
has vetted — under professional-secrecy rules or data-processing agreements,
say — the vendor of the MCP client is one of them, since the client sends the
tool results to its LLM. Behind an `OAuthProxy` the upstream IdP cannot make
that call: every token it issues names the proxy's own upstream application,
never the MCP client. The proxy is the authorization server the client talks
to, so the check belongs there.

A client identifies itself to the proxy in one of three ways:

1. **With a Client ID Metadata Document (CIMD).** The `client_id` is an HTTPS
   URL under a domain its publisher controls — Claude's is
   `https://claude.ai/oauth/mcp-oauth-client-metadata` — and the document at
   that URL lists the client's redirect URIs.
2. **With Dynamic Client Registration (DCR).** The client registers at
   `/register` and gets a random `client_id`.
3. **With the `client_id` of the upstream application's static client**,
   entered by hand: the "own OAuth client" option of Claude's custom connector
   dialog, or Claude Code's `--client-id`. FastMCP accepts it without
   registration. The rest of this section calls it the upstream `client_id`.

#### Client allowlist

The client allowlist is the mechanism that decides which clients get in. It
checks the `client_id` a client presents, whichever of the three ways it got
it, and refuses every `client_id` not on the list. Which settings limit the
clients of each way:

| Way | Client | Settings that limit it | Result |
| --- | --- | --- | --- |
| 1 | [CIMD client](#cimd-clients) | `ALLOWED_CLIENT_IDS`, with an exact or a prefix entry | Only the listed clients and publishers get in |
| 2 | [DCR client](#dcr-clients) | None | Cannot be limited; setting `ALLOWED_CLIENT_IDS` turns DCR off and refuses every DCR client |
| 3 | [Upstream `client_id`](#the-upstream-client_id) | `ALLOWED_CLIENT_IDS`, with an exact entry, and `ALLOWED_UPSTREAM_CLIENT_REDIRECT_URIS` | Gets in only when listed, and only with a listed redirect URI |

The three subsections that follow explain each row.

`ClientAllowlist` reads the allowed clients from `ALLOWED_CLIENT_IDS`, and
`apply` enforces them on any `OAuthProxy` subclass:

```python
from fastmcp_seaworthy import ClientAllowlist

allowlist = ClientAllowlist.from_env()  # e.g. ALLOWED_CLIENT_IDS=https://claude.ai/

provider = allowlist.apply(AWSCognitoProvider(...))
```

Unset, `apply` returns the provider untouched, so the call can stay in place
in every deployment. Each entry matches a `client_id` in one of two ways:

- **Exactly**, for any entry: a CIMD URL, or the upstream `client_id`.
- **As a prefix**, for an `https://` URL ending in `/`: `https://claude.ai/`
  allows every client published under that host, `https://example.com/clients/`
  every client under that path. The trailing `/` is what keeps
  `https://claude.ai/` from matching `https://claude.ai.attacker.example/`,
  which is why there are no wildcards. A `client_id` with a `.` or `..` path
  segment never matches a prefix.

Matching is case-sensitive, on the `client_id` as the client sends it.
Malformed entries — a `*`, an `http://` URL, an `https://` URL without a path
or with a query, fragment, credentials or dot segment — fail at startup.

A `client_id` that matches no entry is refused with an OAuth error and a
warning in the log, before anything else happens. The token endpoint looks
clients up the same way, so removing an entry stops that client from
refreshing its tokens, not only from signing in again. Access tokens already
issued stay valid until they expire.

`allowlist.describe()` returns one line naming the clients accepted, for the
startup log.

#### CIMD clients

This applies to way 1, which `ALLOWED_CLIENT_IDS` limits, with an exact or a
prefix entry. A CIMD `client_id` is a URL attributable to its publisher, so it
can be allowed by publisher with a prefix entry, and it is the way the
allowlist is designed around. A CIMD URL not on the list is never fetched,
which also removes the proxy's outbound requests for everything not on the
list.

A CIMD client may only redirect to the `redirect_uris` its own document lists,
which FastMCP enforces. That is what makes the `client_id` worth trusting:
Claude's document lists only `https://claude.ai/api/mcp/auth_callback`, so an
authorization code issued to that `client_id` can only reach Claude. Claude
Code publishes its own document,
`https://claude.ai/oauth/claude-code-client-metadata`, which lists the
loopback callbacks `http://localhost/callback` and `http://127.0.0.1/callback`,
on any port. `ALLOWED_CLIENT_IDS=https://claude.ai/` therefore admits both.
A loopback callback stays on the user's own machine, so any program running
there can present Claude Code's `client_id`: allowing a loopback client keeps
out other vendors' hosted clients, not software the user runs locally.

#### DCR clients

This applies to way 2, which no setting limits: the allowlist and DCR cannot
be used together. Setting `ALLOWED_CLIENT_IDS` turns DCR off, so where clients
must keep registering through DCR, leave `ALLOWED_CLIENT_IDS` unset.

The reason is that a `client_id` from DCR is random and anonymous, so there is
nothing to list. With the allowlist set, the `/register` route and the
`registration_endpoint` in the authorization-server metadata disappear, so a
client does not attempt a registration that could only fail, and nobody can
write registrations into the store. Clients registered through DCR before the
allowlist was set are refused. Clients that support CIMD switch to it, since
the metadata advertises `client_id_metadata_document_supported`.

#### The upstream `client_id`

This applies to way 3, which takes two settings: `ALLOWED_CLIENT_IDS`, with an
exact entry for the upstream `client_id`, and
`ALLOWED_UPSTREAM_CLIENT_REDIRECT_URIS`, which has no effect on CIMD or DCR
clients.

For the upstream `client_id`, FastMCP builds a client on the fly. That client
has no document and accepts any redirect URI, so on its own the `client_id`
would let in whoever knows it, and the authorization code would go wherever
they asked. Listing the upstream `client_id` therefore requires
`ALLOWED_UPSTREAM_CLIENT_REDIRECT_URIS`, the redirect URIs the clients sending
it may use, in the pattern syntax of FastMCP's `allowed_client_redirect_uris`.
For Claude's connector dialog, that is Claude's callback; for Claude Code, the
loopback addresses:

```bash
ALLOWED_CLIENT_IDS="https://claude.ai/ my-upstream-client-id"
ALLOWED_UPSTREAM_CLIENT_REDIRECT_URIS="https://claude.ai/api/mcp/auth_callback http://localhost:* http://127.0.0.1:*"
```

`apply` refuses to start without it. Unlike `allowed_client_redirect_uris`,
which FastMCP applies to every client, this list applies to the upstream
`client_id` only, so CIMD clients keep the redirect URIs their documents list.
When the provider also sets `allowed_client_redirect_uris`, a redirect URI has
to pass both.

The client FastMCP builds for the upstream `client_id` is a public client: it
has no secret and authenticates with PKCE alone. Way 3 therefore works only
with clients that send just a `client_id` and use PKCE, never with
confidential clients that also send a `client_secret`. Leave the secret field
empty, and never hand the upstream application's secret to a client. This
limit comes from FastMCP, not from `fastmcp-seaworthy`, which neither adds nor
removes it.

### All together

Build the store and the allowlist once and use them for every hostname: the
hostnames are separate OAuth identities of one deployment, not separate
deployments. Applying the allowlist in `auth_for` makes every hostname's
provider enforce it.

```python
import logging

from fastmcp_seaworthy import (
    ClientAllowlist,
    OAuthStateSettings,
    build_client_storage,
    serve_http,
    split_base_urls,
)


async def main() -> None:
    settings = OAuthStateSettings.from_env()
    storage = build_client_storage(settings)
    allowlist = ClientAllowlist.from_env()
    logging.info(settings.describe())
    logging.info(allowlist.describe())

    def auth_for(base_url: str) -> AWSCognitoProvider:
        return allowlist.apply(
            AWSCognitoProvider(
                ...,
                base_url=base_url,
                **settings.provider_kwargs(storage),
            )
        )

    await serve_http(
        mcp,
        split_base_urls(os.environ["BASE_URLS"]),
        auth_for,
        client_storage=storage,
        host="0.0.0.0",
        port=8080,
    )


asyncio.run(main())
```

## Configuration

### Environment variables

Read by `OAuthStateSettings.from_env()`, except `ALLOWED_CLIENT_IDS`, which
`ClientAllowlist.from_env()` reads. Empty values count as unset.

| Variable | Description |
| --- | --- |
| `JWT_SIGNING_KEY` | Secret the server signs its tokens with and derives the store's encryption key from. At least 32 characters, e.g. from `secrets.token_urlsafe(32)`; a shorter one is an error. Keep it in a secret store and stable across deployments. Unset, FastMCP derives both from the upstream client secret. Required with any `STORE_BACKEND` other than `file`. |
| `STORE_BACKEND` | `file` (default) for FastMCP's own encrypted file store, `dynamodb` or `postgres`. An unknown value is an error, not a fallback to `file`. |
| `STORE_DYNAMODB_TABLE` | DynamoDB table name. Required for `STORE_BACKEND=dynamodb`. |
| `STORE_DYNAMODB_REGION` | AWS region of the table. Optional; unset, the AWS SDK's usual chain decides. |
| `STORE_DYNAMODB_AUTO_CREATE` | `true` to create a missing table at startup. Default `false`, so a missing table fails the rollout and the server needs no `dynamodb:CreateTable`. |
| `STORE_POSTGRES_URL` | PostgreSQL connection URL, `postgresql://user:password@db.example.com:5432/appdb`; `postgres://` works too, and libpq query parameters such as `?sslmode=require` are passed on to asyncpg. Required for `STORE_BACKEND=postgres`. Percent-encode `@`, `/`, `?` and `#` in the user name and password (`%40`, `%2F`, `%3F`, `%23`); an unencoded one is an error. Never logged (see [PostgreSQL table](#postgresql-table)). |
| `STORE_POSTGRES_TABLE` | Table name, optionally schema-qualified as `schema.table` (see [PostgreSQL table](#postgresql-table)). Optional; default `fastmcp_oauth_state`, in the schema the connection's `search_path` resolves it to. Each part: lowercase letters, digits and underscores, not starting with a digit, at most 63 characters; anything else is an error at startup. |
| `STORE_POSTGRES_AUTO_CREATE` | `true` to create a missing table at startup. Default `false`, so a missing table fails the rollout and the server's role needs no `CREATE` on the schema. |
| `ALLOWED_CLIENT_IDS` | The OAuth clients the server accepts, separated by commas or whitespace: exact `client_id`s, or `https://` URLs ending in `/` that allow every `client_id` under them (see [Limiting which clients connect](#limiting-which-clients-connect)). Unset, every client is accepted and DCR stays open. Set, DCR is off. |
| `ALLOWED_UPSTREAM_CLIENT_REDIRECT_URIS` | The redirect URIs a client sending the `client_id` of the upstream application's static client may use, separated by commas or whitespace, in the pattern syntax of FastMCP's `allowed_client_redirect_uris` (e.g. `http://localhost:*`). Required when `ALLOWED_CLIENT_IDS` allows the upstream `client_id`, and applied to that client only (see [The upstream `client_id`](#the-upstream-client_id)). |

The values written to an external store are Fernet-encrypted with a key derived
from `JWT_SIGNING_KEY` exactly as FastMCP derives its file store's key, so the
store never holds an upstream token in plaintext. An entry written under a
different key reads as missing: clients re-register and users sign in again,
instead of every request failing. So does an entry that is not encrypted at
all: everything the server writes is, so such an entry was written by someone
with write access to the store but not the key, and is logged as a warning.

Only the values are encrypted. Each entry's collection, key and expiry are
stored as they are: client IDs, token IDs and, while they are valid,
authorization codes. None of them can be redeemed without the encrypted value
(an authorization code also needs the client's PKCE verifier), but they show
who signs in when. Treat the table's backups and exports accordingly, and
scope write access to the table to the server alone.

The check for unencrypted entries covers the external stores this library
builds. With `STORE_BACKEND=file`, FastMCP builds its own store, which still
trusts an unencrypted file. That is harmless while only the server's own
process can write to its directory, but on a volume shared with anything
else, whoever can write files there can plant state.

`JWT_SIGNING_KEY` is worth setting with the default file store too: it
decouples the stored state from the upstream client secret.

### DynamoDB table

Credentials and region come from the AWS SDK's usual chain (IRSA or EKS Pod
Identity, instance profile, `AWS_*` environment variables);
`AWS_ENDPOINT_URL_DYNAMODB` points it at DynamoDB Local for testing. Create the
table with your infrastructure code:

| Property | Value |
| --- | --- |
| Partition key | `collection` (String) |
| Sort key | `key` (String) |
| Time to live | enabled on the attribute `ttl` |
| Billing mode | any; on-demand fits the access pattern |

The server needs `dynamodb:DescribeTable`, `dynamodb:DescribeTimeToLive`,
`dynamodb:GetItem`, `dynamodb:PutItem` and `dynamodb:DeleteItem` on the table.
`STORE_DYNAMODB_AUTO_CREATE=true` additionally needs `dynamodb:CreateTable` and
`dynamodb:UpdateTimeToLive`; so does a table without TTL enabled.

### PostgreSQL table

The store is py-key-value-aio's `PostgreSQLStore`, on one asyncpg connection
pool per process. Create the table with your migrations, or let
`STORE_POSTGRES_AUTO_CREATE=true` create it:

```sql
CREATE TABLE fastmcp_oauth_state (
    collection TEXT NOT NULL,
    key TEXT NOT NULL,
    value JSONB NOT NULL,
    ttl DOUBLE PRECISION,
    created_at TIMESTAMPTZ,
    expires_at TIMESTAMPTZ,
    PRIMARY KEY (collection, key)
);
CREATE INDEX idx_fastmcp_oauth_state_expires_at
    ON fastmcp_oauth_state (expires_at) WHERE expires_at IS NOT NULL;
```

The server's role needs `SELECT`, `INSERT`, `UPDATE` and `DELETE` on the
table; `STORE_POSTGRES_AUTO_CREATE=true` additionally needs `CREATE` on the
schema.

An unqualified `STORE_POSTGRES_TABLE` resolves through the connection's
`search_path`, which by default is the role's own schema, then `public`. To
keep the table in a schema of its own — for example where the database is
the application's and its migrations own `public` — qualify it:
`STORE_POSTGRES_TABLE=oauth.fastmcp_oauth_state`. The server then sets the
pool's `search_path` to that schema alone, so the table, its index and every
query live there. The schema must exist (`CREATE SCHEMA oauth;`, with
`USAGE` granted to the server's role); auto-create creates the table, not the
schema.

At startup the server checks that the table resolves where its queries will
look for it. `PostgreSQLStore`'s own check finds a table of that name in any
schema; on its own, a same-named table elsewhere would let the server start
and fail at the first sign-in. With auto-create off a table missing from the
resolved schema fails startup, and with auto-create on a table the store
skipped because of a namesake elsewhere does too.

The connection URL usually carries the database password, so it never
appears in the startup log line, in `ClientStorage.description`, in the
settings' `repr()` or in a startup error: they name the table, the database,
and the host and port only. An error from the database driver that would
quote the URL or the password is re-raised with both replaced by `***`.

**Expired rows are not deleted.** `PostgreSQLStore` records each entry's
expiry and ignores expired entries on read, but nothing removes them, so the
table keeps every expired authorization code and token record. Unlike
DynamoDB, PostgreSQL has no time to live of its own. Prune it periodically,
e.g. from a cron job or `pg_cron`; the partial index on `expires_at` keeps
the statement cheap:

```sql
DELETE FROM fastmcp_oauth_state WHERE expires_at < now();
-- or, with a qualified STORE_POSTGRES_TABLE:
DELETE FROM oauth.fastmcp_oauth_state WHERE expires_at < now();
```

Entries without an expiry, such as DCR client registrations, are kept.

## API Reference

### `serve_http`

`async serve_http(server, base_urls, auth_for, /, *, client_storage=None, show_banner=True, host=None, port=None, log_level=None, path=None, uvicorn_config=None, json_response=None, stateless_http=None, stateless=None, middleware=None, host_origin_protection=None, allowed_hosts=None, allowed_origins=None, session_idle_timeout=None)`
— serves `server` under every base URL until uvicorn stops. Mirrors
`FastMCP.run_http_async`: unset keywords fall back to FastMCP's settings, so
`FASTMCP_*` environment variables keep working.

| Parameter | Type | Description |
| --- | --- | --- |
| `server` | `FastMCP` | The server backing every identity; construct it without `auth=` |
| `base_urls` | `Sequence[str]` | Public base URLs, canonical first |
| `auth_for` | `Callable[[str], AuthProvider \| None]` | Builds the provider for one base URL |
| `client_storage` | `ClientStorage \| None` | Opened before any provider is built, closed once uvicorn stops |

The remaining keywords are those of `FastMCP.run_http_async`. With
`host_origin_protection` enabled, `allowed_hosts` must list every public
hostname, since one list applies to every identity's app.

### `build_host_router`

`build_host_router(server, base_urls, auth_for, /, *, path=None, json_response=None, stateless_http=None, middleware=None, host_origin_protection=None, allowed_hosts=None, allowed_origins=None, session_idle_timeout=None)`
— builds the `HostRouter` that `serve_http` serves, for callers that run the ASGI
app themselves. Those callers hold `server._lifespan_manager()` open around it
if the server lifespan must outlive the router, as `serve_http` does.

### `OAuthStateSettings`

`OAuthStateSettings(jwt_signing_key=None, store_backend="file", store_dynamodb_table=None, store_dynamodb_region=None, store_dynamodb_auto_create=False, store_postgres_url=None, store_postgres_table=None, store_postgres_auto_create=False)`
— the signing key and the store an `OAuthProxy` keeps its state in. Frozen
dataclass; construction raises `ValueError` for a signing key shorter than
`MIN_JWT_SIGNING_KEY_LENGTH` (32), a combination the server could not keep
readable, a PostgreSQL URL asyncpg would misread or an invalid PostgreSQL
table name. The two secrets, `jwt_signing_key` and `store_postgres_url`, are
left out of `repr()`, and no error message quotes either.
`store_postgres_table` takes `"table"` or `"schema.table"`; `None` means
`DEFAULT_POSTGRES_TABLE` (`"fastmcp_oauth_state"`).

| Method | Description |
| --- | --- |
| `from_env(environ=None)` | Class method; reads the [environment variables](#environment-variables) from `environ`, default `os.environ` |
| `describe()` | Returns one line naming the store and signing key in effect, for the startup log; never the key itself, and of a PostgreSQL URL only the host, port and database |
| `provider_kwargs(client_storage)` | Returns the `jwt_signing_key` and `client_storage` keyword arguments for an `OAuthProxy` subclass, each only when set; not for a `RemoteAuthProvider` such as `KeycloakAuthProvider` |

### `build_client_storage`

`build_client_storage(settings)` — returns the encrypted `ClientStorage` the
settings select, or `None` for FastMCP's default file store. Imports no backend
dependency for `file`; raises `RuntimeError` when the backend's extra is
missing.

### `ClientStorage`

Returned by `build_client_storage`.

| Member | Type | Description |
| --- | --- | --- |
| `store` | `AsyncKeyValue` | The encrypted store handed to providers as `client_storage` |
| `backend` | `BaseContextManagerStore` | The unencrypted backend, kept for its lifecycle |
| `description` | `str` | Names the backend's location in startup errors |
| `await open()` | `None` | Connects; raises `ValueError` naming the backend when it cannot be used |
| `await close()` | `None` | Closes the backend |

### `ClientAllowlist`

`ClientAllowlist(client_ids=(), upstream_client_redirect_uris=())` — the OAuth
clients an `OAuthProxy` accepts, or every client when empty, and the redirect
URIs allowed for the upstream `client_id`. Frozen dataclass; construction
raises `ValueError`, naming the entry's position but not the entry, for a
malformed entry, and for redirect URIs without any client ID.

| Member | Description |
| --- | --- |
| `from_env(environ=None)` | Class method; reads `ALLOWED_CLIENT_IDS` and `ALLOWED_UPSTREAM_CLIENT_REDIRECT_URIS` from `environ`, default `os.environ` |
| `enabled` | Property; whether any entry is set |
| `allows(client_id)` | Returns whether `client_id` matches an entry; always `True` when empty |
| `describe()` | Returns one line naming the clients accepted, for the startup log |
| `apply(provider)` | Returns `provider` with the allowlist enforced and DCR turned off; untouched when empty. Call it before the provider's routes are built. Raises `TypeError` for a provider that is not an `OAuthProxy` and `ValueError` when an allowlist is already applied or the upstream `client_id` is allowed without `upstream_client_redirect_uris` |

### `HostRouter`

`HostRouter(apps, canonical_base_url)` — an ASGI app dispatching to per-hostname
child apps keyed by base URL, and running every child's lifespan under its own.
Rejects an empty mapping, two base URLs sharing a hostname, and a canonical base
URL that is not among them.

### Helpers

| Function | Description |
| --- | --- |
| `split_base_urls(raw)` | Splits a comma-separated list of base URLs, drops blank entries and checks them with `check_distinct_hosts` |
| `check_distinct_hosts(base_urls)` | Raises `ValueError` for an entry without a hostname or two entries sharing one |
| `host_of(base_url)` | Returns the lower-cased, port-less hostname of a base URL |
| `storage_encryption_key(jwt_signing_key)` | Derives the store's Fernet key from a signing key, as FastMCP does |

## Contributing

See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup and guidelines.

## License

Apache-2.0 — see [LICENSE](LICENSE).
