Skip to content
kubed-io[bot] edited this page Nov 27, 2026 · 7 revisions

Config

The one config every QuickMCP server has. It's composed from the sections that the server, its components and quick-mcp's own built-ins register, and it's loaded from defaults, one file, env vars and arguments. A config is a schema written as a class: its fields are the items, a field may nest another class, and the class may carry computed properties and methods of its own. The design is 2026-11-25-config-design.

Use cases

  • A server author writes a pydantic class for their settings, registers it, and gets loading, validation, provenance and a JSON Schema without writing a loader.
  • An operator sets any item the schema allows from the file, an env var or an argument, and sees in one boot line where each value came from, with secrets never shown.
  • A component (quick-mcp's telemetry, or a server's own) brings its own section. Its keys and env names are the same in every server that uses it.
  • A test builds a server from a dict or an instance, with no env and no argv read.

Neighbours

CFG-1. The components that register sections and receive them at start are components' (CMP). Injection and lifetimes are the container's (DI). Serving the server is the app's (APP). Telemetry's own keys are telemetry's (TEL). Delivery's are delivery's (DLV).

Sections

CFG-2. A section is a pydantic model registered under a top-level key with the config decorator, @config("telemetry"), and given to QuickMCP(sections=...). @config(), with no key, marks the root section, whose fields sit at the top level of the config. A key is an identifier that isn't a keyword, doesn't start with _ or model_ and isn't an attribute of a pydantic model; any other key is a ValueError. The decorator returns the class unchanged and a subclass doesn't inherit it. A key that isn't a str, @config without parentheses, a class that isn't a pydantic model, and a registered class without its own @config are each a TypeError.

CFG-3. The config is composed from every registered section, one key per section, the built-ins' first. A key registered by two classes, neither a subclass of the other, is a ValueError at registration naming the key and both classes. A section is extended by subclassing its class and registering the subclass for its key: the most derived class holds the key, in either order. A key that's also a root field or a root attribute is a ValueError.

pydantic drops a field's metadata when a subclass redefines it, so a field that redefines one a model base gave an env or arg (CFG-7) restates it. A field that drops one is a TypeError when the config is composed, naming the nearest base that has it: serving.host: redefines ServingSettings.host without its env='HOST' and arg='--host': restate Field(..., env='HOST', arg='--host') to keep them. Each keyword is checked on its own, against the nearest model base whose field of that name has it, and restating one under another name is allowed. This holds for every model a section reaches, the built-ins' included.

CFG-4. Every server has a config, mcp.config. With no section of the server's own, it holds only the built-ins' sections (CMP-4).

CFG-5. A section's field may be another pydantic model, nested to any depth. A section class keeps its own properties, methods and validators, and they run on the loaded instance. The config itself subclasses the root section, so the root's validators run on it as well.

CFG-6. An unknown key anywhere in the config is an error that stops the load, naming the key's dotted path and its source. Every model a section reaches must forbid unknown keys (extra="forbid", as Config, a public base, does). One that doesn't, or a dataclass or TypedDict among them, is refused at registration with a TypeError naming the class and the field's path.

Items and sources

CFG-7. Each field may declare, beside its type and default:

  • doc;
  • env, the env var's full name, prefix included;
  • arg, the flag's full name, -- included;
  • sensitive.

The spelling is Field(default, *, doc=None, env=None, arg=None, sensitive=False, ...), pydantic's Field with these four.

quick-mcp never derives an env name or a flag and never adds a prefix: a name is used exactly as written, case included. A field with no env has no env var, and one with no arg has no flag. env and arg may sit on any field reached through model fields, a model-typed one included.

A sensitive item is one whose type holds a pydantic secret type (SecretStr, SecretBytes, Secret[T] or a subclass) anywhere in its annotation, as SecretStr | None and list[SecretStr] do, but not inside another model's fields. It is sensitive marked or not, and it is read with get_secret_value(). sensitive=True on any other type is a TypeError.

Registration refuses, naming the field's path:

  • with a TypeError:
    • a flag that doesn't have the form --name: --, then a character other than -, with no = and no whitespace anywhere;
    • an env name holding = or a NUL character;
    • a name on a field of a model reached only through an annotation that holds the model other than alone or with None: a list, a dict, a tuple, a set, a union with other types or a Secret[...]. Such a field has no one path to set it at. A model that is also a model-typed field's type keeps its names;
    • env or arg on a field whose validation_alias isn't a str, such as an AliasChoices or an AliasPath: a named item takes a plain string alias or none;
    • env, arg or sensitive given by a Field inside the field's annotation rather than on the field;
  • with a ValueError:
    • one env name or flag declared by two fields, naming both, one model class at two paths included;
    • CONFIG_FILE or --config-file, which quick-mcp reads for the config file.

CFG-8. The sources, lowest priority to highest, are:

  1. the field's default;
  2. the config file;
  3. env vars;
  4. arguments.

Mappings merge at every depth, over the defaults, a model instance given as a default included, and so is one made by a default_factory that takes no argument, called once when a source sets part of its field. A factory that takes the validated data is never called for the merge. A list, a scalar or a secret replaces the lower value whole. Among env vars, or among arguments, a name on a nested field beats one on the model field that holds it. An env var or a flag is read only when a field declares it.

The arguments are the ones the server passes, QuickMCP(argv=sys.argv[1:]), and with none passed none are read. Env vars come from os.environ, or from the mapping passed as environ=.

A value from an env var or a flag is a string, validated as pydantic's lax mode does. A list, set, tuple, dict or model field takes JSON, an array or an object, and so does a union whose members all take the same. A field annotated with NoDecode, or typed Json[T], gets the raw string for its own validators.

CFG-9. The config file is one YAML file for the whole config, keyed as the composed config is. It's named by --config-file, or else by CONFIG_FILE, and a blank name names none. Its path is used as given, relative to the working directory. A server with no file named loads from the other sources alone. A named file that's missing, isn't a file, can't be read as UTF-8, isn't valid YAML or doesn't hold a mapping stops the load with an error naming the file. A file isn't valid YAML when the loader refuses it for any reason, a value its tag can't build included, or when a mapping in it holds itself through an anchor. The error never quotes the file. An empty file holds no values.

CFG-10. A blank value, null or a string that's empty once trimmed, counts as unset in an env var, a flag, or a file entry at any depth of mappings. An item of a list is left to the validators. A blank value never overrides a lower source, and is never decoded.

CFG-11. The config loads once: in QuickMCP(...), or before it in load_config(...) (CFG-18), and either way before any component registers (CMP-3) and before the server's own build code reads it: mcp.config holds it from construction on, and no section registers after construction. A loaded config doesn't change while the server runs: its top level is frozen and there's no reload. A section is frozen only if its class says so. The boot line (CFG-12) is built at load and logged once each time the server starts, before any component starts. The load itself logs nothing.

Provenance and errors

CFG-12. Each leaf item of the loaded config records the source that set it, as Source(kind, name). A leaf item is a field that doesn't hold one model, alone or with None, or that holds a model it already sits inside. The kinds are an open set:

  • default;
  • file, with its path;
  • env, with the variable's name;
  • arg, with the flag;
  • code, for values given in config=;
  • hook, for a section a hook supplies (CMP-6).

As a string, a source is its kind, then its name when it has one: default, env PORT.

A server reads the record as mcp.config_sources, a read-only mapping from each leaf item's dotted path to its Source, in item order. A load that succeeds builds one boot line, which the server logs at info on the kubed.mcp.config logger when it starts (CFG-11), listing each leaf item set by a source other than its default with its value as JSON and its source, or saying config: all defaults. A value with no JSON form shows as its type's name, "<SimpleNamespace>".

CFG-13. A sensitive item's value never appears in a log line, the provenance record or a dump of the config or of any section. The boot line shows it as ***, and so a leaf that holds a model with a secret field at any depth, such as list[Cred], since that model's own serializer may write the secret as anything. Every other value is masked at runtime before it is written: a secret anywhere in it shows as **********, and a model or a dataclass in it is written field by field, so no serializer of the server's runs and none can print a secret. No error text of quick-mcp's or pydantic's carries it, and an error on a sensitive item names the item and its source, and nothing below the item: no value, key or index. A server's own validator's message is kept as written (CFG-14), so a validator must not put the value in it.

CFG-14. A load error names the item's path, its source and what was expected: recording.hosts (env RECORDING_HOSTS): must be a JSON array.

  • The source is the highest one holding the path. An unknown key is attributed to the source that holds it.
  • One load reports every error it finds, those from arguments and env vars included, in one ValueError.
  • An unknown or abbreviated flag, a flag without its value, or a positional argument is one of those errors, and never ends the process. An unknown flag is named, and the value after it is never shown. A positional is counted, never quoted. A short or malformed flag is a positional, so -p 9000 counts as two, and so is every argument after a bare --. After a flag without its value, no argument and no file is read.
  • A value that isn't a mapping where a section or a model field belongs is an error from its own source, whatever a higher source sets below it: redis (file /etc/kb.yaml): must be a mapping, not a str. This holds for every source, code included.
  • An error with the config file is reported alone.
  • No text of quick-mcp's or pydantic's quotes a value. A server's own validator's message is kept as written, so it quotes none only if the validator doesn't.

Schema

CFG-15. config_schema(*sections, hooked=()) returns the composed config's one JSON Schema, covering every section given and the built-ins', with no QuickMCP. Each field's doc is its description, and its env and arg are named as written. A sensitive field is marked sensitive, and the schema never writes its default. It also leaves out a default that is a JSON object or sits on a field whose type reaches another schema (a model or an enum, alone or with None), and a sensitive field's examples. Every section and every model a section reaches has additionalProperties: false. Writing it imports no FastMCP (FAC-11), so a command that never serves can write it.

hooked names the built-ins a server supplies through hooks= (CMP-6), and composes as that server does: those sections stay in the schema, but their properties, at any depth, have no env or arg, and their names aren't checked against the others'. A model that a section not hooked reaches too keeps its names. A key that isn't a built-in's is a ValueError, hooked= takes a built-in's key, one of 'serving', 'telemetry', 'delivery'; got 'recording', and a bare str is a TypeError.

Injection and tests

CFG-16. A section is injectable by its class: Inject[Recording] gets the loaded section, and so does every class it replaced (CFG-3). The whole config is injectable as Config, and as the root section's class. None is built, entered or torn down.

CFG-17. A server can be built from a config given in code, QuickMCP(config=...). It's either a mapping keyed as the composed config, whose values may be section instances, or one or more section instances, each at the key its class holds, with a root instance's fields at the top level. It then reads no file, no env var and no argument. A class, or an object that isn't an instance of a registered section, is refused with a TypeError. Two instances for one key are a ValueError.

CFG-18. load_config(*, sections=(), components=(), argv=None, environ=None, config=None, hooks=None) loads a config with no QuickMCP. It composes and reads it exactly as QuickMCP(...) does given the same arguments (CFG-8, CFG-17, CMP-2, CMP-6), where QuickMCP's None for sections or components is load_config's () and load_config refuses None, and refuses what that refuses, with the same error. It returns a LoadedConfig: .config is the loaded config and .sources its record (CFG-12), both read-only, and it carries the components it was given. It logs nothing, and calling it imports no FastMCP (FAC-11).

QuickMCP(name, loaded=...) is built from it as it is: nothing is composed again and no file, env var or flag is read again. mcp.config is .config, mcp.config_sources is .sources, the components it carries register and start as components= do (CMP-3), and the boot line is logged as CFG-11 says. Passing sections, components, hooks, config, argv or environ with loaded is a TypeError naming each one given, an empty one included: loaded= is already loaded: pass sections= to load_config(), not with loaded=. A loaded that isn't a LoadedConfig is a TypeError. A LoadedConfig builds one server: a second QuickMCP(loaded=...) with it is a TypeError, and a call refused for its arguments doesn't count.

Setting the config

For an operator. This states no rule the rows above don't.

The file. One YAML file holds the whole config, keyed as the config is: the root section's items at the top, and each section's under its key, the built-ins' serving, telemetry and delivery included.

grid_url: https://grid.example.com
serving:
  port: 8080
recording:
  tags: [qa, nightly]

Name it with --config-file kb.yaml or CONFIG_FILE=kb.yaml. The flag wins, and a blank flag leaves CONFIG_FILE to name it. The path is used as given, relative to the working directory, and a file that is named but can't be used fails the load.

Env vars and flags. An item has an env var or a flag only when the server declares one, and the name is used exactly as declared. The server's config schema, config_schema(), lists them as each property's env and arg, and every server has the built-ins' (TRANSPORT, HOST, PORT, LOG_LEVEL, GRACEFUL_TIMEOUT, TELEMETRY_* and DELIVERY_*, in components). A flag's value follows it, --port 9000, or follows =, --port=9000. A value that starts with - is written with =, --port=-1 or --token=-s3cret: written apart, --token -s3cret reads as two flags, and the first has no value. A short or malformed flag is counted as a positional argument and never quoted, so -p 9000 is two, and so is every argument after a bare --. No item takes a positional.

Lists, dicts and models set from an env var or a flag are JSON: recording.hosts is set by --recording-hosts '["a", "b"]' or RECORDING_HOSTS='["a", "b"]', and a model field by an object, such as '{"dir": "/data", "keep": 3}'. A field the server marks to read its own text takes the format the server documents instead.

Blank means unset. An env var or a flag that's empty or only spaces, and a file entry that's empty or null, sets nothing: the value below it stays. PORT= doesn't clear a port.

Precedence, lowest to highest: the defaults, the file, env vars, flags. Mappings merge key by key at every depth, so the file can set one key of a section and an env var another. Anything else, a list included, replaces what's below it whole. When one env var sets a whole model field and another one of its fields, the field's wins, and the same goes for flags.

The boot line. When the server starts, it logs one INFO line on the kubed.mcp.config logger, before anything else it starts, naming each item set by a source other than its default, its value as JSON and where it came from. A secret shows as ***:

config: token=*** (env GRID_TOKEN), serving.port=9000 (arg --port)

With nothing set, it reads config: all defaults. A config that doesn't load raises one ValueError holding every error the load found, each naming the item's path and its source, or the config file's error alone. The server decides whether that stops it. quick-mcp's own texts never show a value.

Writing a server's config

For a server author. This states no rule the rows above don't.

The entry point passes the server's arguments. quick-mcp never reads sys.argv, so a server that passes none reads no flags.

import sys
from typing import Annotated

from pydantic import Secret, SecretStr, field_validator

from kubed.mcp import Config, Field, NoDecode, QuickMCP, config


@config()
class Settings(Config):
    grid_url: str = Field(
        "https://grid.example.com", doc="The grid's address.", env="GRID_URL"
    )
    token: SecretStr | None = Field(
        None, doc="The grid's token.", env="GRID_TOKEN", arg="--token"
    )
    pin: Secret[int] | None = Field(None, env="GRID_PIN")


@config("recording")
class Recording(Config):
    tags: Annotated[list[str], NoDecode] = Field([], env="RECORDING_TAGS")
    hosts: list[str] = Field([], env="RECORDING_HOSTS", arg="--recording-hosts")

    @field_validator("tags", mode="before")
    @classmethod
    def split(cls, value: object) -> object:
        return value.split(",") if isinstance(value, str) else value


mcp = QuickMCP("grid", sections=[Settings, Recording], argv=sys.argv[1:])

This module is a script, so its arguments are the server's. A module another program imports, such as pytest, fastmcp run or fastmcp inspect, builds its server without argv=, or builds it in its main() or under if __name__ == "__main__":, because that program's arguments aren't the server's. The boot line shows when the server starts, at INFO, the level run() sets on the root logger unless serving.log_level says otherwise (APP-9).

A server with a parser of its own passes what that parser leaves, such as the rest from parse_known_args(). --help, subcommands, and exiting on a config error are the server's: quick-mcp has no --help, and raises ValueError where argparse would exit.

Reading the config before the server. A server whose FastMCP options come from its config, such as its lifespan or a cache's lifetime, loads the config first with load_config(), which takes the config arguments QuickMCP takes, and builds the server from that load, so it loads once:

import sys

from kubed.mcp import QuickMCP, load_config

# Settings and Recording are the sections declared above.
loaded = load_config(sections=[Settings, Recording], argv=sys.argv[1:])
mcp = QuickMCP(
    "grid", loaded=loaded, instructions=f"Drives the grid at {loaded.config.grid_url}."
)

The config arguments then go to load_config() alone.

Tests pass environ=, a mapping that stands in for os.environ, or config=, which reads nothing. Every test that loads a config passes one of them, so a PORT set on a CI runner never reaches it: QuickMCP("grid", sections=[Settings], environ={"PORT": "9000"}). Passing argv= or environ= with config= is a TypeError.

NoDecode. Without it, RECORDING_TAGS would have to be a JSON array. With it, the field's mode="before" validator gets the raw text, qa,smoke, and splits it. The file's YAML list still reaches the same validator as a list, so it handles both.

Secrets. A field typed SecretStr, SecretBytes or Secret[T] is sensitive, with or without sensitive=True. pydantic masks it in repr, str and every dump, the boot line shows it as ***, and the server reads it with mcp.config.token.get_secret_value().

Where a value came from. mcp.config_sources maps each item's dotted path to its Source: mcp.config_sources["recording.tags"] is Source(kind="env", name="RECORDING_TAGS"), and its string is env RECORDING_TAGS.

Clone this wiki locally