Skip to content

2026 11 26 config core

kubed-io[bot] edited this page Nov 26, 2026 · 3 revisions

Config core: sections registered by key, one composed config and schema, injected by section: plan

History. Written 2026-11-26 for Dr K. It is the plan of record for #48 (Epic 5, #47), built in #51. It builds config CFG-2 to CFG-6, CFG-11 and CFG-15 to CFG-17. It defines CFG-7's spelling, which stays (proposed) until #50 makes env and arg load. It rewrites APP-2, APP-3 and APP-8, replaces DI-12 and extends FAC-11. The epic's design is the why; this plan doesn't replace it. Built in #51.

For agentic workers: REQUIRED SUB-SKILL: Use skill://superpowers/subagent-driven-development/SKILL.md (recommended) or skill://superpowers/executing-plans/SKILL.md to implement this plan task-by-task. Steps use checkbox (- [ ]) syntax for tracking.

Goal: a server declares its config as pydantic sections (@config("key"), plus a root section with @config()) and registers them with QuickMCP(sections=...). quick-mcp composes one frozen config from them, loads it at construction from defaults or from values given in code (config=), exposes it as mcp.config, and injects each section by its class. config_schema() writes the whole config's JSON Schema without importing FastMCP.

Architecture: a new FastMCP-free module, kubed/mcp/_config.py, holds the decorator, the Config base, the Field spelling, the built-ins list (empty until #49), the composition and the one loading function. QuickMCP.__init__ calls that function first, puts each section and the whole config in its container with Container.provide, and keeps reading telemetry, delivery and run()'s Serving from the loaded config by attribute until #49 (CMP-5).

Tech Stack: Python 3.11–3.14, pydantic 2, FastMCP 4.2, pytest, ruff.

Spec: the wiki's config rows, (proposed) until Task 5. The spec they build was confirmed by the parent, #47, on 2026-11-26 and approved by Dr K. It is in #48's notes, and the design below is that spec, settled against the code. There is no separate spec file: this plan is the record, and Task 5 writes the rows' text.

The design this settles

The parent's rulings are not to reopen:

  • the registration call;
  • env and arg as literal strings;
  • loading at construction;
  • a strict, frozen top level;
  • Inject[Parent] getting the subclass;
  • no backwards compatibility;
  • a minor release.
  1. The module is kubed/mcp/_config.py.
    • It is private, and its public names are re-exported eagerly by kubed.mcp.
    • It isn't config.py: importing a submodule of that name would overwrite the exported config decorator on kubed.mcp.
    • At module level it imports pydantic and the standard library only. In particular, it doesn't import pydantic_core: an "argument not given" default is a private sentinel of its own.
    • pydantic>=2,<3 becomes a direct dependency.
  2. config(key: str | None = None) returns a decorator. The decorator stamps the key on the class and returns the class unchanged, and there's no global registry.
    • The stamp is a private attribute read from the class's own vars(), so a subclass doesn't inherit it. A subclass registered for a key carries its own @config(key).
    • A key must be a str (a TypeError otherwise). A bare @config, given the class as its key, is a TypeError that says to write @config().
    • A key must be an identifier that isn't a Python keyword, doesn't start with _ or model_, and isn't an attribute of BaseModel (json, copy, schema, ...). Any other key is a ValueError.
    • A decorated class that isn't a BaseModel subclass is a TypeError.
  3. Config is a public BaseModel with model_config = ConfigDict(extra="forbid"), and nothing else. A section may subclass it, or any BaseModel that forbids unknown keys.
  4. Field(default=<unset>, *, doc=None, env=None, arg=None, sensitive=False, **kwargs) is pydantic's Field with the item metadata (CFG-7). It returns pydantic.Field(...):
    • default is passed on only when given, so an omitted default is required, as with pydantic.
    • doc becomes description.
    • env, arg and sensitive=True go into json_schema_extra as {"env": ..., "arg": ..., "sensitive": True}. Only the keys given are written: sensitive appears only when true.
    • env and arg are taken literally. Nothing derives, prefixes or defaults them. Each, when given, must be a non-empty str, or it's a TypeError.
    • description or json_schema_extra in kwargs is a TypeError that names doc= or the item keywords. Every other keyword goes to pydantic unchanged.
    • #50 reads the items back from FieldInfo.json_schema_extra.
  5. Registration happens at construction, through _compose(sources), and nothing registers after it.
    • sources is an ordered sequence of iterables of classes, and _BUILTINS always comes first. QuickMCP passes [sections]. #49 passes [components' sections, sections] on the same path.
    • Each class registers under its stamp's key, and the root section's key is None.
    • When a key is already held:
      • a subclass of the holder replaces it;
      • a superclass of the holder is recorded as replaced, and the holder stays;
      • the same class again is a no-op.
    • So the most derived class wins in either order. Each class that lost its key is kept in replaced[key], for injection.
    • Unrelated classes under one key are a ValueError. It names the key (or "the root section") and both classes' qualnames.
    • These are TypeErrors:
      • a class with no stamp of its own, which says to add @config(...);
      • a source that is itself a class (sections=Root), which says to write sections=(Root,);
      • an instance among the classes, which says that values go in config=.
  6. Composition.
    • The composed model is pydantic.create_model("Config", __base__=bases, **fields). bases is (Root, _Top) with a root section and (_Top,) without one.
    • _Top is a private Config subclass with frozen=True. Listed last, it keeps the top level frozen even if the root says otherwise.
    • Each keyed section is a field named by its key. A section whose fields all have defaults gets default_factory=<its class>, and any other section is required. The section isn't built to find this out.
    • The composed model subclasses the root, so the root's properties, methods and validators work on the loaded config (CFG-5).
    • Two key checks run here, each a ValueError naming the key and both owners:
      • a key that is also a field of the root;
      • a key that is an attribute of the root class (a property, a method).
    • Sections aren't frozen by quick-mcp. Each stays as its class says, so a section validator that assigns still works.
    • A root mode="after" validator can't assign, because the top is frozen. The config docstring says so.
  7. Strictness (CFG-6), checked at registration.
    • The check walks every root and section class, then every model reachable from their field annotations. That reach includes models inside Optional, unions, list, dict, tuple and Annotated, through typing.get_args, keeping only the arguments that are classes or parameterized generics.
    • A visited set stops self-referencing models.
    • A model whose model_config.get("extra") isn't "forbid" is a TypeError. A nested stdlib or pydantic dataclass, or a TypedDict, is also a TypeError: pydantic doesn't refuse their unknown keys.
    • The error names the class's qualname and the path. The path is the dotted field names from the top of the composed config: root fields at the top, sections under their key, and the root itself is "the root section". A model in a list or dict is named by the field that holds it.
  8. Values: _load(sources, values) -> _Loaded, the one loading function. #50 adds the file, env vars and argv inside it, for when values is None. _Loaded is a NamedTuple of config: Config and provided: dict[type, object]. values is taken in this order:
    • None: defaults only.
    • A BaseModel instance: one section instance. It's taken before the iterable case, because a model iterates as (name, value) pairs.
    • A Mapping: validated against the composed model. Nested values may be section instances.
    • A str or bytes: a TypeError.
    • Another iterable: each item must be a BaseModel instance.
      • A class among them is a TypeError that says classes go in sections=.
      • An instance goes to the key whose winning class it's an instance of. A root instance's fields spread at the top level, as {name: getattr(instance, name)} for each field of its class.
      • An instance of a class that lost its key (a parent of the winner) is a TypeError that names the winner.
      • An instance of an unregistered class is a TypeError, and so is an object that isn't a model (a dataclass or argparse.Namespace, as both servers pass today). Both say config= takes a mapping or section instances, and classes go in sections=.
      • Two instances for one key are a ValueError.
    • Anything else is the same TypeError.
    • Instances are kept as given: pydantic doesn't revalidate them, so Inject[Section] gets the object passed.
    • Given values are never read from a file, an env var or argv (CFG-17).
  9. Load errors.
    • pydantic.ValidationError is caught and raised again as a ValueError, from None. The message's first line is the config did not load:, then one line per error: <path> (<source>): <msg>.
    • <path> joins pydantic's loc: strings with ., and integers as [i] (items[0].name).
    • <source> is code when values was given and holds the path's first segment (a root instance's spread fields count), and default otherwise. #50 adds file, env and arg.
    • The message is built from loc and msg only, never pydantic's input, and the original isn't chained: a value never reaches the error (the ground CFG-13 builds on).
  10. Injection (CFG-16).
    • _Loaded.provided maps each winning section class, and each class it replaced, to the loaded section. It maps Config, the winning root class and each root class it replaced to the whole loaded config.
    • QuickMCP gives each pair to Container.provide. So Inject[TelemetrySettings] gets a server's subclass section, and Inject[Config] and Inject[Root] get the whole config.
    • DI-12's type(config) key goes.
  11. Load time (CFG-11).
    • QuickMCP.__init__ calls _load([sections], config) as its first statement, so a bad config stops construction before FastMCP is built.
    • mcp.config is a read-only property, the loaded instance. There's no reload, and no registration after construction.
  12. Schema (CFG-15): config_schema(*sections: type[BaseModel]) -> dict[str, Any].
    • It composes [sections] after _BUILTINS, with every registration rule and error above, and returns the composed model's model_json_schema(), post-processed.
    • The post-processing walks every dict in the result, $defs included, and removes two kinds of default:
      • the default of any dict carrying "sensitive": True;
      • every default whose value is a JSON object, because a model instance written as a default may carry a sensitive item.
    • It needs no QuickMCP and imports no FastMCP.
    • doc appears as description, and env and arg as written. extra="forbid" appears as additionalProperties: false. The command that writes the schema is each server's own.
  13. Until #49.
    • QuickMCP reads getattr(self.config, "telemetry", None) and getattr(self.config, "delivery", None).
    • run() falls back to self.config when it has transport, host and port. With no serving and a config lacking any of the three, it raises the TypeError "run() needs a Serving: pass one, or register a root section with transport, host and port".
    • Serving, TelemetrySettings (unstamped) and Delivery are unchanged, and _BUILTINS is ().

Global Constraints

  • from __future__ import annotations at the top of every module. kubed/ gets no __init__.py.
  • The new public names are Config, Field, config and config_schema in kubed.mcp, and QuickMCP's sections= and mcp.config. config= changes meaning, which is the BREAKING: line. No other public name changes.
  • kubed/mcp/_config.py imports only pydantic and the standard library at module level. kubed.mcp imports it eagerly, beside kubed.mcp.telemetry.
  • Every error names what's wrong in quick-mcp's words: the key, the classes' qualnames, the path and the source. No error message or log line holds a config value.
  • Test section classes are defined at module level in the test files, so pydantic resolves their annotations under from __future__ import annotations.
  • tests/ reach no network and read no env var or argv for config. A child process runs sys.executable -I, so the package is installed editable: pip install -e .[test,tasks].
  • Checks, as CI and this repository's rules run them: ruff check . (lint.yml), pytest (test.yml) and ruff format --check ..
  • Wiki edits are left in the docs/ checkout. The job commits them on the wiki branch issue-48 and moves the pointer here. No git runs inside docs/, and the wiki's master is never pushed. Spec text is in the present tense, with no issue numbers and no names but Dr K's.
  • .github/ is not touched.

Review Focus

  1. Today's call shape. Both servers pass config= a dataclass, an argparse.Namespace or a model instance of a class they never registered. Each must be a TypeError that names sections=, never an AttributeError deep inside the load. A class in config=, or an instance in sections=, gets the same treatment (Task 2, test_an_old_style_config_is_a_type_error_naming_sections).

  2. One instance, not in a list. config=Root(name="x") is one section instance. A BaseModel iterates as (name, value) pairs, so without the early check it would fail confusingly (Task 2, test_a_single_instance_is_one_section).

  3. A key that shadows an attribute. Two cases must be a ValueError at registration, never a silent shadow:

    • a key like "json" or "copy", which shadows BaseModel's attributes;
    • a key equal to a root property or method.

    (Task 1, test_a_key_that_shadows_an_attribute_is_refused.)

  4. A value in a load error. pydantic's own error text carries input_value. A secret given in code for a field with the wrong type must not appear in the ValueError or in a chained cause (Task 2, test_a_load_error_never_holds_a_value).

  5. A secret default inside a model default. A root field defaulting to a model instance whose sensitive field has a default must not print that default in the schema (Task 3, test_a_sensitive_default_is_never_written, nested case).


Task 1: Sections, Config, Field, registration, composition and strictness

Files:

  • Create: kubed/mcp/_config.py
  • Modify: pyproject.toml, dependencies: add "pydantic>=2,<3", with the comment "The config's sections and its schema are pydantic models."
  • Test: tests/test_config.py (new, pytestmark = pytest.mark.unit), with sections # -- sections and # -- composing

Interfaces:

  • Produces, in kubed/mcp/_config.py:

    • config(key: str | None = None) -> Callable[[type[M]], type[M]], where M is bound to BaseModel;
    • class Config(BaseModel);
    • Field(default: Any = <unset>, *, doc: str | None = None, env: str | None = None, arg: str | None = None, sensitive: bool = False, **kwargs: Any) -> Any;
    • _BUILTINS: tuple[type[BaseModel], ...] = ();
    • _compose(sources: Iterable[Iterable[type[BaseModel]]]) -> _Composition, where _Composition is a NamedTuple of model: type[Config], held: dict[str | None, type[BaseModel]] and replaced: dict[str | None, tuple[type[BaseModel], ...]];
    • _compose reads _BUILTINS at call time, so a test can monkeypatch it.
  • Consumes: nothing.

  • Step 1: Write the failing tests

Module-level fixtures for the whole file:

  • Root: @config(), a Config with name: str = "flow" and a property shout -> self.name.upper().
  • Recording: @config("recording"), a Config with inbox: str | None = Field(None, doc="Where recordings go", env="RECORDING_INBOX", arg="--recording-inbox") and a property enabled -> self.inbox is not None.
  • Deep, Middle and Nest:
    • Deep(Config): level: int = 3 and a property twice.
    • Middle(Config): deep: Deep = Field(default_factory=Deep).
    • Nest: @config("nest"), a Config with label: str = "", middle: Middle = Field(default_factory=Middle), a field_validator("label") that strips, and a model_validator(mode="after") that assigns label = "unnamed" when it's empty.
  • Base, Sub, Other:
    • Base: @config("base"), a Config with a: int = 1.
    • Sub: @config("base"), a subclass of Base with b: int = 2.
    • Other: @config("base"), an unrelated Config.
  • Node(Config): children: list[Node] = [], self-referencing.
def test_config_stamps_the_key_and_returns_the_class() -> None:
    class Fresh(Config):
        pass

    assert config("fresh")(Fresh) is Fresh
    assert _compose([[Fresh]]).held == {"fresh": Fresh}
    # a subclass with no @config of its own doesn't inherit its parent's key
    with pytest.raises(TypeError, match=r"Unstamped has no @config"):
        _compose([[Unstamped]])  # class Unstamped(Recording): pass


@pytest.mark.parametrize("key", ["", "1st", "_private", "model_x", "class", "json", "copy"])
def test_a_bad_key_is_a_value_error(key) -> None:
    with pytest.raises(ValueError, match=repr(key)):
        config(key)


def test_config_refuses_a_class_that_is_not_a_model_and_a_bare_decorator() -> None:
    with pytest.raises(TypeError, match="BaseModel"):
        config("x")(type("Plain", (), {}))
    with pytest.raises(TypeError, match=r"@config\(\)"):
        config(Recording)  # @config with no parentheses


def test_field_writes_doc_env_arg_and_sensitive() -> None:
    info = Field("x", doc="A doc", env="A_ENV", arg="--a", sensitive=True)
    assert info.description == "A doc"
    assert info.json_schema_extra == {"env": "A_ENV", "arg": "--a", "sensitive": True}
    bare = Field(doc="d")
    assert bare.json_schema_extra is None  # no item given, nothing written
    assert bare.is_required()  # no default given: required, as pydantic's Field
    with pytest.raises(TypeError, match="doc="):
        Field("x", description="d")
    with pytest.raises(TypeError):
        Field("x", env="")


def test_a_root_and_keyed_sections_compose() -> None:
    composed = _compose([[Root, Recording]])
    assert set(composed.model.model_fields) == {"name", "recording"}
    assert issubclass(composed.model, Root) and issubclass(composed.model, Config)
    assert composed.held == {None: Root, "recording": Recording}


def test_an_unrelated_class_under_a_taken_key_names_both() -> None:
    with pytest.raises(ValueError, match=r"'base'.*Base.*Other|'base'.*Other.*Base"):
        _compose([[Base, Other]])


@pytest.mark.parametrize("order", [[Base, Sub], [Sub, Base]])
def test_a_subclass_replaces_its_parent_in_either_order(order) -> None:
    composed = _compose([order])
    assert composed.held["base"] is Sub
    assert composed.replaced["base"] == (Base,)


def test_a_servers_subclass_replaces_a_built_in(monkeypatch) -> None:
    monkeypatch.setattr(kubed.mcp._config, "_BUILTINS", (Base,))
    assert _compose([[Sub]]).held["base"] is Sub


def test_a_root_field_named_like_a_key_is_refused() -> None:
    # @config() class Clashing(Config): recording: str = ""
    with pytest.raises(ValueError, match=r"'recording'.*Clashing.*Recording"):
        _compose([[Clashing, Recording]])


def test_a_key_that_shadows_an_attribute_is_refused() -> None:
    # @config() class Shouting(Config): with a property `loud`; @config("loud") class Loud(Config)
    with pytest.raises(ValueError, match=r"'loud'"):
        _compose([[Shouting, Loud]])


def test_a_class_or_an_instance_where_sources_belong_is_a_type_error() -> None:
    with pytest.raises(TypeError, match=r"sections=\(Root,\)"):
        _compose([Root])
    with pytest.raises(TypeError, match="config="):
        _compose([[Root()]])


def test_a_nested_model_that_allows_unknown_keys_is_refused() -> None:
    # class Loose(BaseModel): x: int = 0   (no forbid)
    # @config("recording2") class Holding(Config): inner: Loose | None = None
    with pytest.raises(TypeError, match=r"Loose at recording2\.inner"):
        _compose([[Holding]])
    # the same for list[Loose] and dict[str, Loose] fields, and for a section that is Loose itself


def test_a_nested_dataclass_or_typed_dict_is_refused() -> None:
    with pytest.raises(TypeError, match=r"Point at"):
        _compose([[HoldsPoint]])  # Point is a @dataclasses.dataclass


def test_a_self_referencing_model_registers() -> None:
    _compose([[HoldsNode]])  # @config("tree") class HoldsNode(Config): root: Node = Node()

kubed.mcp._config is imported as import kubed.mcp._config, and _compose, config, Config and Field come from it.

  • Step 2: Run the tests to verify they fail

Run: pytest tests/test_config.py -v Expected: collection fails with ModuleNotFoundError: kubed.mcp._config.

  • Step 3: Implement kubed/mcp/_config.py

Write config, Config, Field, _BUILTINS, _Composition and _compose, with the private _Top and the strictness walk, as design items 1 to 7 say. The module docstring says why the module exists: one config per server, composed from registered sections, loadable and describable without FastMCP. The config docstring tells an integrator:

  • how to mark the root and a keyed section;
  • that a subclass needs its own @config;
  • that a root mode="after" validator can't assign.

Add the dependency to pyproject.toml.

  • Step 4: Run the tests to verify they pass

Run: pip install -e .[test,tasks] && pytest tests/test_config.py -v Expected: PASS.

  • Step 5: Checks and commit

Run: ruff check . && ruff format --check . && pytest Expected: all pass (nothing else uses the module yet).

git add kubed/mcp/_config.py pyproject.toml tests/test_config.py
git commit -m "feat(config): sections by key, composed into one strict config"

Task 2: Loading: defaults and values given in code

Files:

  • Modify: kubed/mcp/_config.py
  • Test: tests/test_config.py, section # -- loading

Interfaces:

  • Consumes: Task 1's _compose, Config, config and Field.

  • Produces: _load(sources: Iterable[Iterable[type[BaseModel]]], values: Mapping[str, Any] | BaseModel | Iterable[BaseModel] | None) -> _Loaded. _Loaded is a NamedTuple of config: Config and provided: dict[type, object]. Task 4 calls it as _load([sections], config), and #50 extends it.

  • Step 1: Write the failing tests

Required is a module-level fixture: @config("required"), a Config with token: str and no default. Secretive is @config("secretive"), a Config with token: str = Field("dflt", sensitive=True).

def test_no_sections_load_an_empty_config() -> None:
    loaded = _load([[]], None)
    assert type(loaded.config).model_fields == {}
    assert isinstance(loaded.config, Config)
    assert loaded.provided == {Config: loaded.config}


def test_defaults_load_and_properties_and_validators_run() -> None:
    loaded = _load([[Root, Recording, Nest]], None)
    assert loaded.config.name == "flow" and loaded.config.shout == "FLOW"
    assert loaded.config.recording.enabled is False
    assert loaded.config.nest.label == "unnamed"  # a section's assigning validator still works


def test_three_levels_load_from_a_dict() -> None:
    loaded = _load([[Nest]], {"nest": {"label": " x ", "middle": {"deep": {"level": 4}}}})
    assert loaded.config.nest.label == "x"
    assert loaded.config.nest.middle.deep.twice == 8


def test_a_dict_may_hold_section_instances() -> None:
    recording = Recording(inbox="/in")
    loaded = _load([[Root, Recording]], {"name": "kb", "recording": recording})
    assert loaded.config.recording is recording and loaded.config.name == "kb"


def test_section_instances_go_to_their_keys_and_a_root_spreads() -> None:
    recording = Recording(inbox="/in")
    loaded = _load([[Root, Recording]], [Root(name="kb"), recording])
    assert loaded.config.name == "kb" and loaded.config.recording is recording


def test_a_single_instance_is_one_section() -> None:
    assert _load([[Root]], Root(name="kb")).config.name == "kb"


def test_the_provided_values_cover_every_class() -> None:
    loaded = _load([[Root, Base, Sub]], None)
    assert loaded.provided[Sub] is loaded.provided[Base] is loaded.config.base
    assert loaded.provided[Config] is loaded.provided[Root] is loaded.config


@pytest.mark.parametrize(
    "values, path",
    [
        ({"nope": 1}, "nope (code)"),
        ({"recording": {"nope": 1}}, "recording.nope (code)"),
        ({"nest": {"middle": {"deep": {"nope": 1}}}}, "nest.middle.deep.nope (code)"),
    ],
)
def test_an_unknown_key_names_its_path_and_source(values, path) -> None:
    with pytest.raises(ValueError, match=r"^the config did not load:") as caught:
        _load([[Root, Recording, Nest]], values)
    assert f"  {path}: Extra inputs are not permitted" in str(caught.value)


def test_a_missing_required_section_is_from_default() -> None:
    with pytest.raises(ValueError, match=r"required \(default\): Field required"):
        _load([[Required]], None)


def test_a_load_error_never_holds_a_value() -> None:
    with pytest.raises(ValueError) as caught:
        _load([[Secretive]], {"secretive": {"token": ["s3cret"]}})
    assert "s3cret" not in str(caught.value)
    assert caught.value.__cause__ is None and caught.value.__suppress_context__


@pytest.mark.parametrize(
    "values, match",
    [
        (Settings(), "sections="),                        # a dataclass, as test_app's
        (argparse.Namespace(port=1), "sections="),
        (Unregistered(), "sections="),                    # a Config subclass never registered
        ([Recording], "sections="),                       # a class among values
        ("recording", "mapping or section instances"),
        (42, "mapping or section instances"),
    ],
)
def test_an_old_style_config_is_a_type_error_naming_sections(values, match) -> None:
    with pytest.raises(TypeError, match=match):
        _load([[Root, Recording]], values)


def test_an_instance_of_a_replaced_class_names_the_winner() -> None:
    with pytest.raises(TypeError, match="Sub"):
        _load([[Base, Sub]], [Base()])


def test_two_instances_for_one_key_are_refused() -> None:
    with pytest.raises(ValueError, match="'recording'"):
        _load([[Recording]], [Recording(), Recording()])

Settings here is a small module-level dataclass in tests/test_config.py with port: int = 8000.

  • Step 2: Run the tests to verify they fail

Run: pytest tests/test_config.py -v Expected: collection fails with ImportError: cannot import name '_load'.

  • Step 3: Implement _load in kubed/mcp/_config.py

Follow design items 8 to 10: the order in which values is taken, the error message format and the source rule, and provided.

  • Step 4: Run the tests to verify they pass

Run: pytest tests/test_config.py -v Expected: PASS.

  • Step 5: Checks and commit

Run: ruff check . && ruff format --check . && pytest Expected: all pass.

git add kubed/mcp/_config.py tests/test_config.py
git commit -m "feat(config): load from defaults or values given in code, with errors by path and source"

Task 3: config_schema and the exports (CFG-15, FAC-11)

Files:

  • Modify: kubed/mcp/_config.py, kubed/mcp/__init__.py
  • Test: tests/test_config.py (section # -- schema) and tests/test_facade.py

Interfaces:

  • Consumes: Task 1's _compose.

  • Produces:

    • config_schema(*sections: type[BaseModel]) -> dict[str, Any].
    • kubed.mcp exports Config, Field, config and config_schema eagerly, with from ._config import Config, Field, config, config_schema.
  • Step 1: Write the failing tests

In tests/test_config.py, Holder is a module-level fixture: @config(), a Config with inner: Secretive = Secretive().

def test_one_schema_covers_every_section() -> None:
    schema = config_schema(Root, Recording)
    assert schema["title"] == "Config"
    assert set(schema["properties"]) == {"name", "recording"}
    inbox = schema["$defs"]["Recording"]["properties"]["inbox"]
    assert inbox["description"] == "Where recordings go"
    assert inbox["env"] == "RECORDING_INBOX" and inbox["arg"] == "--recording-inbox"
    assert "sensitive" not in inbox


def test_every_object_forbids_unknown_keys() -> None:
    schema = config_schema(Root, Recording, Nest)
    assert schema["additionalProperties"] is False
    assert all(d["additionalProperties"] is False for d in schema["$defs"].values())


@pytest.mark.parametrize("sections", [(Secretive,), (Holder,)])
def test_a_sensitive_default_is_never_written(sections) -> None:
    schema = config_schema(*sections)
    assert "dflt" not in json.dumps(schema)
    assert schema["$defs"]["Secretive"]["properties"]["token"]["sensitive"] is True


def test_the_schema_includes_the_built_ins(monkeypatch) -> None:
    monkeypatch.setattr(kubed.mcp._config, "_BUILTINS", (Base,))
    assert "base" in config_schema()["properties"]

In tests/test_facade.py:

  • OWN["kubed.mcp"] gains "Config", "Field", "config" and "config_schema".
  • test_importing_kubed_mcp_imports_no_fastmcp expects {"loaded": ["kubed.mcp._config", "kubed.mcp.telemetry"], "missing_from_dir": []}.
  • It gains two cases:
        "from kubed.mcp import Config, Field, config, config_schema",
        "from kubed.mcp import Config, Field, config, config_schema\n"
        "@config('recording')\n"
        "class Recording(Config):\n"
        "    inbox: str | None = Field(None, doc='Where', env='RECORDING_INBOX')\n"
        "assert config_schema(Recording)['properties']['recording']",
  • test_telemetry_imports_only_pydantic_and_the_standard_library becomes test_the_config_modules_import_only_pydantic_and_the_standard_library, parametrized over "kubed.mcp.telemetry" and "kubed.mcp._config", with the same assertions.

  • Step 2: Run the tests to verify they fail

Run: pytest tests/test_config.py tests/test_facade.py -v Expected: tests/test_config.py fails to collect with ImportError: cannot import name 'config_schema'. The facade tests FAIL on __all__ and on loaded.

  • Step 3: Implement config_schema and the exports

Implement config_schema as design item 12 says. In kubed/mcp/__init__.py:

  • the eager import;
  • the four names in __all__, in the order ruff's RUF022 accepts;
  • the docstring's second paragraph names the six eager names, and says a config module can declare its sections and write their schema without loading FastMCP.

_LAZY is unchanged.

  • Step 4: Run the tests to verify they pass

Run: pip install -e .[test,tasks] && pytest tests/test_config.py tests/test_facade.py tests/test_package.py -v Expected: PASS.

  • Step 5: Checks and commit

Run: ruff check . && ruff format --check . && pytest Expected: all pass.

git add kubed/mcp/_config.py kubed/mcp/__init__.py tests/test_config.py tests/test_facade.py
git commit -m "feat(config): one JSON Schema for the composed config, written without FastMCP"

Task 4: QuickMCP(sections=..., config=...), mcp.config and injection by section

Files:

  • Modify: kubed/mcp/app.py: QuickMCP.__init__ (lines 155–213), a new config property, run() (lines 486–507) and the class docstring.
  • Create: tests/config_server.py, holding Duck, a module-level @config() Config. It has transport: str = "http", host: str = "0.0.0.0", port: int = 8000, telemetry: Any = None and delivery: Any = None. Its docstring says it holds whatever a test gives telemetry and delivery, which QuickMCP reads by attribute until the built-ins are components.
    • Duck is a stand-in, and #49 deletes it. When the built-ins become components, the telemetry and delivery tests move onto the real sections, and no test-only root that accepts anything stays behind. The pull request's body says so.
  • Test: tests/test_config.py, section # -- a server's config.
  • Rewrite every test that passes config=:
    • tests/test_app.py:493-502 and :606-609;
    • tests/test_telemetry.py: the Config dataclass at :104-109, served() at :123, :284-286, :1680 and :1701;
    • tests/test_delivery_inputs.py:33-35, tests/test_via.py:37-39 and tests/test_listed.py:22;
    • tests/otel_child.py:59-63 and :132-138.

Interfaces:

  • Consumes: Task 2's _load and _Loaded, and Task 1's Config.

  • Produces:

    • QuickMCP.__init__(self, name: str, *, sections: Iterable[type[BaseModel]] = (), config: Mapping[str, Any] | BaseModel | Iterable[BaseModel] | None = None, header_prefix: str | None = None, **fastmcp_options: Any);
    • QuickMCP.config -> Config, a read-only property.
  • Step 1: Write the failing tests

def test_the_config_is_there_right_after_construction_and_frozen() -> None:
    mcp = QuickMCP("t", sections=[Root, Recording], config={"name": "kb"})
    assert mcp.config.name == "kb"
    with pytest.raises(pydantic.ValidationError):
        mcp.config.name = "other"
    with pytest.raises(AttributeError):
        mcp.config = None  # no setter


def test_a_server_with_no_sections_has_an_empty_config() -> None:
    assert type(QuickMCP("t").config).model_fields == {}


def test_a_bad_config_stops_construction() -> None:
    with pytest.raises(ValueError, match=r"recording\.nope \(code\)"):
        QuickMCP("t", sections=[Recording], config={"recording": {"nope": 1}})


async def test_sections_and_the_config_are_injected_by_class() -> None:
    mcp = QuickMCP("t", sections=[Root, Base, Sub])

    @mcp.tool
    def seen(sub: Inject[Sub], base: Inject[Base], whole: Inject[Config], root: Inject[Root]) -> dict:
        return {"sub": sub is base, "whole": whole is root is mcp.config, "b": base.b}

    async with Client(mcp.server) as client:
        assert (await client.call_tool("seen", {})).data == {"sub": True, "whole": True, "b": 2}


def test_the_composed_class_is_not_a_key() -> None:
    # DI-12's type(config) key is gone: Duck and Config resolve, the composed class doesn't.
    mcp = QuickMCP("t", sections=[Duck])
    assert mcp._container.knows(Duck) and mcp._container.knows(Config)
    assert not mcp._container.knows(type(mcp.config))

In tests/test_app.py:

  • test_the_config_is_injectable_as_its_own_type becomes test_the_root_section_is_injectable. It uses QuickMCP("configured", sections=[Duck], config={"port": 9000}) and a tool port(settings: Inject[Duck]) -> int, and still expects 9000.
  • test_run_falls_back_to_the_config_and_passes_http_options builds QuickMCP("configured", sections=[Duck]).
  • test_run_needs_a_serving is unchanged: it must still pass.

The other rewrites:

  • In tests/test_telemetry.py, the Config dataclass goes, and served() and the two direct builds use sections=[Duck], config={"telemetry": telemetry}. Grep the file for Config( so none is missed.

  • test_a_config_without_telemetry_imports_nothing builds QuickMCP("plain"), and its comment becomes "A server with no telemetry section."

  • The three delivery helpers use sections=[Duck], config={"delivery": delivery}.

  • tests/otel_child.py is run with -I, so it can't import config_server. It defines its own module-level @config() class Child(Config), with Duck's three serving fields and telemetry: TelemetrySettings | None = None. It builds QuickMCP(name, sections=[Child], config={"telemetry": telemetry}).

  • Step 2: Run the tests to verify they fail

Run: pytest tests/test_config.py tests/test_app.py -v Expected: the new and rewritten tests FAIL with TypeError: ... unexpected keyword argument 'sections'.

  • Step 3: Implement in kubed/mcp/app.py

As design items 10, 11 and 13 say:

  • _load([sections], config) is the first statement;
  • Container.provide runs for each pair in provided;
  • getattr(self._config, ...) for telemetry and delivery;
  • values[type(config)] is removed;
  • the config property;
  • run()'s fallback and its new TypeError message.

The class docstring says what sections= and config= take, and that mcp.config is the loaded config.

  • Step 4: Run the tests to verify they pass

Run: pip install -e .[test,tasks] && pytest -v Expected: PASS, the whole suite: the telemetry child-process tests, the delivery, via and listed tests, and test_run_needs_a_serving.

  • Step 5: Check that no old shape is left

Run: grep -rn "type(config)\|config=SimpleNamespace\|config=argparse\|config=Config(\|config=Settings(" kubed tests Expected: no match.

  • Step 6: Checks and commit

Run: ruff check . && ruff format --check . && pytest Expected: all pass.

git add kubed/mcp/app.py tests
git commit -m "feat(app)!: QuickMCP(sections=..., config=...) loads one config at construction and injects it by section"

Task 5: The spec, the history, the README and the changelog

Files:

  • Modify (wiki, branch issue-48): docs/superpowers/specs/config.md, app.md, container.md and facade.md; docs/superpowers/plans/2026-11-25-config-design.md and this file's History.
  • Modify: README.md, CHANGELOG.md ([Unreleased]), then the docs pointer.

Interfaces:

  • Consumes: Tasks 1–4, built and green. Every row below must be true of the code as built: check each against it before writing, and correct the row, not the code, if a detail differs.

  • Produces: nothing code reads.

  • Step 1: The config rows. In config.md, CFG-2 to CFG-6, CFG-11 and CFG-15 to CFG-17 lose (proposed) and are replaced, to read:

**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. The decorator returns the class unchanged and a subclass doesn't inherit it. A class that
isn't a pydantic model is refused with a `TypeError`, and so is a registered class without its own
`@config`.

**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`.

**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), and with none at all it is an empty `Config`.

**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 run on it too.

**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.
**CFG-11.** The config loads once, in `QuickMCP(...)`, before any component starts (CMP-3) and
before the server's own build code reads it: `mcp.config` holds it from construction on, and
nothing 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.
**CFG-15.** `config_schema(*sections)` 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. Every object has `additionalProperties: false`. Writing it imports
no FastMCP (FAC-11), so a command that never serves can write it.
**CFG-16.** A section is injectable by its class: `Inject[TelemetryConfig]` 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`.

CFG-7 keeps (proposed) and gains, after its list: "The spelling is Field(default, *, doc=None, env=None, arg=None, sensitive=False, ...), pydantic's Field with these four."

  • Step 2: The app, container and facade rows

    • APP-2: QuickMCP(name, *, sections=(), config=None, header_prefix=None, **fastmcp_options), and the rest as it is.
    • APP-3: "sections registers the server's config sections (CFG-2, CFG-3), and config, when given, is the config's values in code (CFG-17). mcp.config is the loaded config, read-only, from construction on (CFG-11)."
    • APP-8: "mcp.run(serving=None, **http_options) reads its Serving from serving, or from mcp.config when serving is None and the config has all three attributes. Otherwise it refuses with a TypeError before anything runs."
    • APP-7 isn't touched.
    • DI-12: "The loaded config's sections, and the config itself, resolve as their classes (config, CFG-16). Like an override, none is built, entered or torn down."
    • FAC-11: its first sentence excepts Config, Field, Telemetry, TelemetrySettings, config and config_schema. The second says that importing those, or writing config_schema(...), imports no FastMCP or MCP SDK module, so a server's config layer can declare its sections and write their schema without loading FastMCP. The last says kubed.mcp.telemetry and the config module import only pydantic and the standard library at module level.
  • Step 3: The history headers

    • In 2026-11-25-config-design.md, the History gains: "CFG-2 to CFG-6, CFG-11 and CFG-15 to CFG-17 are built, in the config core plan." It also gains: "Overtaken: the sketch's QuickMCP(..., config=[SeleniumFlow, Recording]) is sections=[...], and config= carries values in code (CFG-17). quick-mcp's Field takes doc, env, arg and sensitive, and a flag is never derived."
    • In this file's History, "Not built yet." becomes "Built in #51."
  • Step 4: The README. In the example, mcp = QuickMCP("grid", config=settings) becomes mcp = QuickMCP("grid", sections=[Settings]). Settings is a @config() root section with the serving fields, and the example explains nothing more.

  • Step 5: The changelog, under [Unreleased]

### Added

- **Config sections:** declare pydantic sections with `@config("key")`, register them with `QuickMCP(sections=...)`, inject each with `Inject[Section]`, and write the whole config's JSON Schema with `config_schema()`.

### Changed

- **BREAKING:** `QuickMCP(config=...)` now takes the config's values, a mapping or section instances, and the config's classes go in `sections=`. The loaded config is `mcp.config`, injectable as `Config` or by section, and no longer as `type(config)`.
  • Step 6: Checks and commit

Leave the wiki edits in docs/. The job commits them on the wiki branch issue-48 and moves the pointer.

Run: ruff check . && ruff format --check . && pytest Expected: all pass.

git add README.md CHANGELOG.md docs
git commit -m "docs: the config rows, APP-2/3/8, DI-12, FAC-11, the README and the changelog"

Clone this wiki locally