Skip to content

2026 11 26 components

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

Components: an interface that contributes config and joins the lifecycle; serving, telemetry and delivery become built-ins: plan

History. Written 2026-11-26 for Dr K. It is the plan of record for #49 (Epic 5, #47), built in #58 on issue-49, which merges into issue-47. It builds components CMP-2 to CMP-6 and telemetry TEL-20 on top of the config core and the config sources. It rewrites APP-2, APP-3, APP-5, APP-7 to APP-9, APP-11, TEL-2, TEL-3, DLV-4, CFG-11, CFG-12, CFG-14, CFG-15 and FAC-11. It fixes a merge bug and closes the sources plan's two carry-overs. TEL-18, TEL-19 and TEL-21 aren't here: they stay (proposed) for a sibling sub-issue. The epic's design is the why, and this plan doesn't replace it. Built in #58.

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: every server gets serving, telemetry and delivery as registered components, each with its own config section, env vars and flags. A server adds components of its own that get a section, a place in the container and a start and stop around serving. It can supply a built-in's section from its own config through a hook, and set mcp.auth after construction.

Architecture: the three sections live in a new FastMCP-free kubed/mcp/_builtins.py, which _config._compose reaches through a lazy _builtin_sections(). A public, FastMCP-free kubed/mcp/components.py holds Component and the start and stop loops. QuickMCP loads the config with the built-ins' and the components' sections. It calls each component's register at the end of __init__, and runs their starts and stops inside the lifespan it gives FastMCP. Hooks run inside _load, so config_schema and the provenance record see what a server sees.

Tech Stack: Python 3.11–3.14, FastMCP 4.2 (>=4.2,<5), pydantic 2.12, PyYAML, pytest, ruff.

Spec: the issue's spec, in #49's notes, confirmed by the parent #47 at 08:15 UTC on 2026-11-26 and approved by Dr K. The design below is that spec, settled against the code on issue-47. There's no separate spec file: this plan is the record, and Task 6 writes the rows.

The design this settles

The parent's rulings aren't to be reopened:

  • the TEL split;
  • log_level applied in run();
  • the built-ins' names and defaults;
  • the hooks as spelled;
  • the breaking changes;
  • additions (a) to (d).

Where the spec left a detail open, the choice made here is marked (settled here).

  1. Component is public, in kubed/mcp/components.py, and exported from kubed.mcp. It imports no FastMCP: QuickMCP is imported under TYPE_CHECKING only. Every method is a no-op by default:

    • section: ClassVar[type[BaseModel] | None] = None: a class carrying @config(key);
    • def register(self, mcp: QuickMCP, section: BaseModel | None) -> None;
    • async def start(self, section: BaseModel | None) -> None;
    • async def stop(self) -> None.

    The section passed is the loaded instance of the class that won the key, a server's subclass included. It's None when the component names no section.

  2. Registration.

    • The signature is QuickMCP(name, *, sections=(), components=(), hooks=None, config=None, argv=None, environ=None, header_prefix=None, **fastmcp_options).
    • components takes Component instances. Anything else, a Component subclass itself included, is the TypeError "components= takes Component instances, got " (settled here).
    • The sources go to _load as [component sections, sections]. _compose puts the built-ins first, so the order is built-ins, then component sections, then sections.
    • A component's section without its own @config is #48's TypeError ("has no @config of its own"). Two components naming one key follow #48's subclass rule.
    • register runs at the end of __init__, after the load, the scopes and _Describe. It runs for the built-ins (serving, telemetry, delivery), then for the server's components, in order.
  3. Lifecycle. The lifespan QuickMCP gives FastMCP does this, on every entry:

    1. marks serving as started (item 7);
    2. logs the config boot line (item 8);
    3. starts each component in order;
    4. runs the server's own lifespan;
    5. stops the started components in reverse;
    6. runs container.aclose() last.
    • Every stop runs, even when an earlier one raised. A stop that raises an Exception is logged at error on kubed.mcp.components, as "%s did not stop cleanly: %s" with the component's class __qualname__ and the exception's type __name__. It's never raised and never shows its text (settled here).
    • A start that raises stops the ones already started, in reverse, then runs container.aclose() and propagates the error, so the boot fails (settled here: the container closes as APP-5 says).
    • Telemetry's start never raises (TEL-6).
  4. The built-in sections live in kubed/mcp/_builtins.py, which imports no FastMCP. Each is a Config (extra="forbid") and is named exactly so. _builtins.BUILTINS is (ServingSettings, TelemetrySettings, DeliverySettings).

    • ServingSettings at serving, exported from kubed.mcp:

      Field Type Default env arg
      transport Literal["stdio", "http", "sse", "streamable-http"] "stdio" TRANSPORT --transport
      host str "127.0.0.1" HOST --host
      port int 8000 PORT --port
      log_level Literal["CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG"] "INFO" LOG_LEVEL --log-level

      The transports are FastMCP's, as its FastMCP.run annotates transport. A test keeps them equal (settled here). A server changes the defaults by subclassing under serving, and restates Field(default, env=..., arg=...) on each field it changes. pydantic drops a parent field's metadata when a subclass redefines the field, so a bare host: str = "0.0.0.0" would have no HOST. Composition refuses it (Dr K, 09:23 UTC): _check_item_keywords compares each field with the same field on the class's model bases, and one that drops a base's env or arg is a TypeError, naming the nearest base that has them: ": redefines

      . without its env='HOST': restate Field(..., env='HOST') to keep it", or, with both dropped, "... without its env='HOST' and arg='--host': restate Field(..., env='HOST', arg='--host') to keep them". Restating either under another name is allowed. It holds for every section, not only the built-ins. The components page says so.
    • TelemetrySettings at telemetry stays in kubed/mcp/telemetry.py. It becomes a Config with @config("telemetry"), and its fields use kubed.mcp's Field(doc=..., env=..., arg=...):

      • profiles: SecretStr | None, env TELEMETRY_PROFILES, --telemetry-profiles;
      • profile_cpu: bool = True, env TELEMETRY_PROFILE_CPU, --telemetry-profile-cpu;
      • profile_memory: bool = True, env TELEMETRY_PROFILE_MEMORY, --telemetry-profile-memory;
      • otel: bool = False, env TELEMETRY_OTEL, --telemetry-otel;
      • tags: dict[str, str], env TELEMETRY_TAGS (JSON), --telemetry-tags.

      _start_profiles passes profiles.get_secret_value() to pyroscope.

    • DeliverySettings at delivery, exported from kubed.mcp: resources, listed and via, each str | None = None, with env DELIVERY_RESOURCES, DELIVERY_LISTED and DELIVERY_VIA and flags --delivery-resources, --delivery-listed and --delivery-via. listed is a comma string. They're lax strings, so DLV-4's warn-and-ignore, at construction, is unchanged. The Delivery Protocol stays as DeliveryDefault's partial type.

    • The cycle: _config.py holds no module-level relative import (FAC-11's test). Its _BUILTINS constant becomes _builtin_sections() -> tuple[type[BaseModel], ...], which imports _builtins.BUILTINS inside the function. _compose calls it, so config_schema() shows the three with no QuickMCP (settled here: a lazy import, not a registry).

  5. The built-in components are private, in _builtins.py, made per server by _builtin_components(name) -> tuple[Component, Component, Component]:

    • _ServingComponent (section = ServingSettings) does nothing else. run(**http_options):

      • reads the loaded ServingSettings;
      • marks serving as started;
      • sets the root logger's level from log_level. It calls logging.basicConfig() first only when the root logger has no handler, and does nothing to logging at construction;
      • runs quiet_fastmcp_logging(), then FastMCP, as APP-10 says.

      run(serving=...) and the public Serving Protocol are removed. run() takes no positional argument.

    • _TelemetryComponent(name) (section = TelemetrySettings):

      • register inserts _call_metrics(section) at index 0 when it isn't None;
      • start is _start_signals(name, section), then the TEL-20 line (item 9);
      • stop is signals.stop() when a start began some, and it forgets them.

      Off still imports nothing. The public Telemetry Protocol is removed, and Inject[TelemetrySettings] replaces it. _otel.py and the telemetry functions are typed on TelemetrySettings.

    • _DeliveryComponent (section = DeliverySettings) does nothing else. __init__ still builds _Resolver(header_prefix, <the loaded DeliverySettings>) where it does today, because _ResolveScope's place in the middleware list is fixed by index before any register runs. Only the resolver's config input changes (settled here).

    • No attribute reads:

      • the getattr(self._config, ...) reads go, and so does run()'s hasattr fallback;
      • _call_metrics' getattr(settings, "otel", False) goes too;
      • tests/config_server.py (Duck) is deleted, and the telemetry and delivery tests move onto the real sections.
  6. Hooks (CMP-6).

    • The type is hooks: Mapping[str, Callable[[Config], BaseModel]] | None.

    • Its keys are built-in keys: serving, telemetry and delivery.

      • Any other key is the ValueError "hooks= takes a built-in's key, one of 'serving', 'telemetry', 'delivery'; got <key!r>".
      • A non-mapping is the TypeError "hooks= takes a mapping of built-in keys to callables".
      • A non-callable value is the TypeError "hooks[<key!r>] must be callable".
    • One read of the sources. The hooked keys are left out of every layer:

      • their items' env vars aren't read;
      • their flags aren't added to the parser, so --port for a hooked serving is an unknown-flag error;
      • the file's and config='s entries under those keys are dropped, silently (settled here: config= too).

      So the hooked sections take their defaults.

    • The hooks run in built-in order, each given the config that load validated. Each must return an instance of the class holding the key (a subclass is allowed). Otherwise it's the TypeError "hooks[<key!r>] returned a , not an instance of ", raised at once. A hook that raises propagates unchanged.

    • Each result is validated as its own class, from its field values (_merge(result, {})). Its errors are load errors serving.port (hook): <text>, reported together in the one ValueError. The model is then validated again, with each validated section in place (settled here). So the root's validators see the hooked values, and a root validator runs twice, as config= instances already make it.

    • Provenance: every leaf under a hooked key records Source("hook"). A _Layer("hook", ...) with one contribution ((key,), None) per hooked key goes on top, so _source gives it.

    • Names: the hooked keys' env names and flags stay out of _check_names, so a server's own PORT doesn't clash with a hooked serving. _compose(sources, *, hooked=frozenset()) carries the set.

    • The schema: config_schema(*sections, hooked=()) composes as a server with those hooks does. Its keys are checked as hooks='s are. The hooked sections stay in the schema (CMP-4) without their env and arg, which aren't read, and their names aren't checked (settled here: without it, mcp-kb's config_schema(Root) would refuse its own PORT).

    • CFG-12 lists hook.

  7. QuickMCP.auth is a public property, since FastMCP 4.2 reads server.auth only in http_app():

    • reading it gives self.server.auth;
    • setting it assigns self.server.auth, from a server's build code or a component's register;
    • once serving has started, setting it is the RuntimeError "auth is fixed once serving starts: set mcp.auth before run()". Serving starts when run() is called or the lifespan is entered, and stays started (settled here: never cleared);
    • auth= in fastmcp_options still works at construction;
    • there's no public compose: code takes its section (design goal 7).
  8. The start lines.

    • _Loaded gains boot_line: str, which is #50's line, built after the hooks, at every load.
    • _load no longer logs it. The lifespan logs it, once per entry, on kubed.mcp.config at info, before any component starts.
    • TEL-20's line comes from the telemetry component's start. Telemetry is a built-in, so it starts before a server's components. The order is: the boot line, TEL-20's line, then the server's components' lines (settled here: the spec's test list put TEL-20's line last, which the start order can't give).
    • #50's boot-line tests assert .boot_line and no longer read logs at load. test_the_boot_line_is_not_built_when_info_is_off is deleted, because the line is always built.
  9. TEL-20 is one info line on kubed.mcp.telemetry:

    • telemetry: profiles → pyroscope.example:4040; otel → traces otlp, metrics otlp, logs none;
    • one part alone when only one signal started;
    • telemetry: off when this start began none (_start_signals returned None).

    The arrow is U+2192.

    • Where profiles go: the host, from urllib.parse.urlsplit of the secret's value, as hostname, in brackets when it holds a : (IPv6), plus :port when there is one. It never includes userinfo, path or query.
      • An address without :// is read as //<address>, so user:pw@pyroscope:4040 shows pyroscope:4040 (settled here).
      • An address with no host, or a port that won't parse, shows an address with no host, or the host alone. It never raises.
    • Where OTel goes: each exporter from OTEL_TRACES_EXPORTER, OTEL_METRICS_EXPORTER and OTEL_LOGS_EXPORTER as os.environ holds it after _set_defaults, stripped. An unset or empty one shows otlp, or none for logs.
  10. The _merge bug. A layer holding a non-mapping at a model-typed path is now a collected error.

    • "Model-typed" means a non-leaf item's loc, and it is checked in every layer, code included.
    • The value isn't a BaseModel instance, and it's checked whatever a higher layer sets.
    • The error is <path> (<source>): must be a mapping, not a <type(value).__name__>, with the source as _source(item.loc, [layer]) gives it.
    • The value is then dropped from that layer, so pydantic doesn't report the path a second time.
    • Items are walked depth-first, so a parent's error removes what its children would see.
    • These errors come after the decode errors and before the validation errors.
    • So redis: broken in the file plus REDIS_HOST=x gives redis (file <path>): must be a mapping, not a str.
  11. #50's carry-overs.

    • _boot_line masks the loaded value at runtime with _masked(value), before _json. Every SecretStr, SecretBytes and Secret instance becomes "**********", wherever it sits:
      • a BaseModel and a pydantic or stdlib dataclass become a dict of its fields by attribute name, so their own serializers never run;
      • a mapping's values, and a list's, tuple's or set's items are masked in turn;
      • a RecursionError names the value by its type.
    • tests/test_header_prefix.py:32 is reformatted by ruff format.

Global Constraints

  • from __future__ import annotations at the top of every module. kubed/ gets no __init__.py.

  • FastMCP-free modules. kubed/mcp/_config.py, telemetry.py, components.py and _builtins.py import only pydantic, the standard library and, for _config.py, PyYAML, at module level.

    • Their relative imports at module level are:
      • telemetry → _config;
      • _builtins → _config, components and telemetry;
      • _config and components: none.
    • components imports QuickMCP under TYPE_CHECKING, and _config imports _builtins inside _builtin_sections().
    • Importing kubed.mcp still loads no FastMCP.
  • Public names:

    • added:
      • Component, ServingSettings and DeliverySettings in kubed.mcp, eager;
      • QuickMCP's components= and hooks=;
      • mcp.auth;
      • config_schema(..., hooked=);
    • removed: Serving, Telemetry and run(serving=);
    • retyped: TelemetrySettings.profiles, now a SecretStr.

    No other public name changes.

  • TEL-6 and CFG-13. No log line or error shows a credential, a secret's value or an exception's text. Start and stop failures are logged by type name only.

  • Tests:

    • no network;
    • section classes at module level unless a test needs its own;
    • every new test that builds a server or loads a config passes environ= or config=;
    • existing servers built without either stay safe through the conftest guard, which covers the built-ins' names once they exist;
    • a test that sets the root logger's level or handlers puts them back.
  • Checks, as CI runs them (lint.yml, test.yml after pip install -e .[test,tasks]):

    • ruff check .;
    • ruff format --check .;
    • pytest.
  • The wiki. Its edits are left in the docs/ checkout. The job commits them on the wiki branch issue-49 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/ isn't touched.

Review Focus

  1. A subclass that changes serving's default. class Pod(ServingSettings): host: str = "0.0.0.0" would drop HOST, because pydantic replaces the field, so composition refuses it. The tests pin both: a subclass restating Field("0.0.0.0", env="HOST", arg="--host") defaults to 0.0.0.0 and still reads HOST, and a bare one is the TypeError (Task 2, test_a_serving_subclass_changes_the_defaults_and_keeps_the_names and test_a_subclass_field_that_drops_its_names_is_refused).
  2. A file that still holds a hooked section. serving: {port: 1} in the file with hooks={"serving": fn} must load, take the hook's port, and record hook, never file (Task 4, test_a_hooked_sections_file_entries_are_not_read).
  3. A start that fails after telemetry started. A server component whose start raises must stop telemetry's signals and the components before it, in reverse, close the container and fail the boot (Task 3, test_a_raising_start_stops_those_started_and_fails_the_boot).
  4. A server that configured logging itself. run() must set only the root level and add no second handler. With no handler at all, basicConfig runs once (Task 2, test_run_sets_the_root_level_and_adds_a_handler_only_when_there_is_none).
  5. A Pyroscope address with credentials and no scheme. user:pw@pyroscope:4040 and https://user:pw@host:4040/x?token=t must show only pyroscope:4040 and host:4040 (Task 5, test_the_start_line_never_shows_a_credential).

Task 1: The config fixes: a scalar where a section belongs, and the boot line masked at runtime

Files:

  • Modify: kubed/mcp/_config.py:
    • _load gains the shape check;
    • _boot_line's value goes through a new _masked;
    • new _check_shapes.
  • Modify: tests/test_header_prefix.py: reformat only.
  • Test: tests/test_config_sources.py, sections # -- shapes and # -- boot line.

Interfaces:

  • Consumes: _Item, _Layer, _source, _json, _boot_line on issue-47.

  • Produces:

    • _check_shapes(items: Sequence[_Item], layers: Sequence[_Layer]) -> tuple[list[_Layer], list[str]]: the layers without their bad values, and the error lines;
    • _masked(value: object) -> object.
  • Step 1: Write the failing tests

Fixtures, at module level:

  • @config("redis") class Redis(Config) with host: str = Field("", env="REDIS_HOST");
  • Deeper(Config) with x: int = 0, and Inner(Config) with deep: Deeper = Deeper();
  • @config("outer") class Outer(Config) with inner: Inner = Field(Inner(), env="OUTER").

For the masking, reuse the file's Loose (thing: Any) and Login (a revealing field_serializer).

# -- shapes

def test_a_scalar_where_a_section_belongs_is_its_layers_error(tmp_path) -> None:
    f = tmp_path / "c.yaml"
    f.write_text("redis: broken\n")
    with pytest.raises(ValueError) as caught:
        load(Redis, environ={"CONFIG_FILE": str(f), "REDIS_HOST": "x"})
    message = str(caught.value)
    assert f"  redis (file {f}): must be a mapping, not a str" in message
    assert message.count("  redis") == 1


def test_a_scalar_section_alone_is_reported_once() -> None:
    with pytest.raises(ValueError) as caught:
        _load([[Redis]], {"redis": 5})
    assert str(caught.value) == "the config did not load:\n  redis (code): must be a mapping, not a int"


def test_a_scalar_for_a_model_inside_json_names_the_env_var() -> None:
    with pytest.raises(ValueError) as caught:
        load(Outer, environ={"OUTER": '{"deep": 5}'})
    assert "  outer.inner.deep (env OUTER): must be a mapping, not a int" in str(caught.value)
    assert str(caught.value).count("outer.inner.deep") == 1


# -- boot line

def test_the_boot_line_masks_a_revealing_serializer_held_by_any(caplog) -> None:
    with caplog.at_level(logging.INFO, logger="kubed.mcp.config"):
        _load([[Loose]], {"loose": {"thing": Login(name="a", token="S3CRET")}})
    assert "S3CRET" not in caplog.text
    assert [r.getMessage() for r in caplog.records if r.name == "kubed.mcp.config"] == [
        'config: loose.thing={"name":"a","token":"**********"} (code)'
    ]

The boot line is still logged at load here. Task 3 moves this test to .boot_line with the file's other boot-line tests.

  • Step 2: Run the tests to verify they fail

Run: pytest tests/test_config_sources.py -v -k "shape or scalar or revealing" Expected:

  • the file case loads without error, so it fails on DID NOT RAISE;

  • the code case fails on pydantic's text;

  • the boot line case fails on S3CRET in the line.

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

  • Add _check_shapes as design item 10 says. _load runs it over every layer after the env and arg layers are built, before the merge, and adds its lines after the decode errors.

  • Add _masked as item 11 says. _boot_line calls _json(_masked(node)). Its docstring says the value is masked before it's written, so no serializer of the server's can print a secret.

  • Run ruff format tests/test_header_prefix.py.

  • Step 4: Run the tests to verify they pass

Run: pytest tests/test_config_sources.py tests/test_config.py -v Expected: PASS, #50's boot-line and error tests included.

  • Step 5: Checks and commit

Run: ruff check . && ruff format --check . && pytest Expected: all pass, ruff format --check included, with the reformat.

git add kubed/mcp/_config.py tests/test_config_sources.py tests/test_header_prefix.py
git commit -m "fix(config): a scalar where a section belongs is its source's error; the boot line masks secrets at runtime"

Task 2: The built-in sections, read by class; run() from serving

Files:

  • Create: kubed/mcp/_builtins.py: ServingSettings, DeliverySettings, BUILTINS.
  • Modify: kubed/mcp/_config.py: _BUILTINS becomes _builtin_sections(), and _compose calls it; _check_item_keywords refuses a subclass field that drops its base's names.
  • Modify: kubed/mcp/telemetry.py:
    • Telemetry is removed;
    • TelemetrySettings becomes @config("telemetry"), a Config, with the env names and profiles: SecretStr | None;
    • _start_signals, _start_profiles, _start_otel and _call_metrics are typed on it, and _call_metrics loses its getattr.
  • Modify: kubed/mcp/_otel.py: start(name, settings: TelemetrySettings, profiles).
  • Modify: kubed/mcp/delivery.py: _Resolver.__init__(self, header_prefix=None, delivery: DeliverySettings | None = None), _config_level(entry, delivery: DeliverySettings | None), and the Delivery docstring ("a partial set of defaults, as delivery_default answers").
  • Modify: kubed/mcp/app.py:
    • Serving and run(serving=) are removed;
    • __init__ reads loaded.provided[TelemetrySettings] and loaded.provided[DeliverySettings] in place of the two getattrs, and keeps loaded.provided as self._provided;
    • run(**http_options) reads self._provided[ServingSettings] and applies log_level.
  • Modify: kubed/mcp/__init__.py:
    • drop Serving and Telemetry;
    • add DeliverySettings and ServingSettings, imported eagerly from ._builtins;
    • the docstring's eager list.
  • Delete: tests/config_server.py.
  • Modify tests:
    • tests/conftest.py: a no_builtins fixture, not autouse;
    • tests/test_config.py;
    • tests/test_config_sources.py: its module pytestmark gains pytest.mark.usefixtures("no_builtins"), and its # -- a server's sources section moves to tests/test_components.py, onto the built-in serving;
    • tests/test_app.py, tests/test_telemetry.py, tests/test_delivery_inputs.py, tests/test_via.py, tests/test_listed.py and tests/test_facade.py.
  • Test: tests/test_components.py (new, pytestmark = pytest.mark.unit), sections # -- built-ins, # -- serving and # -- no attribute reads.

Interfaces:

  • Consumes: Config, Field, config and _load from _config.py.

  • Produces:

    • kubed.mcp._builtins.ServingSettings, .DeliverySettings and .BUILTINS: tuple[type[BaseModel], ...];
    • kubed.mcp._config._builtin_sections() -> tuple[type[BaseModel], ...];
    • QuickMCP.run(self, **http_options: Any) -> None;
    • QuickMCP._provided: dict[type, object];
    • the fixture no_builtins, which monkeypatches kubed.mcp._config._builtin_sections to lambda: ().
  • Step 1: Write the failing tests

In tests/test_components.py:

@config("serving")
class Pod(ServingSettings):
    transport: Literal["stdio", "http", "sse", "streamable-http"] = Field("http", env="TRANSPORT", arg="--transport")
    host: str = Field("0.0.0.0", env="HOST", arg="--host")


@pytest.fixture
def ran(monkeypatch) -> list[dict]:
    calls: list[dict] = []
    monkeypatch.setattr("fastmcp.FastMCP.run", lambda self, **kwargs: calls.append(kwargs))
    return calls


@pytest.fixture
def root_logging(monkeypatch):
    """The root logger's level and handlers, put back after the test."""
    root = logging.getLogger()
    monkeypatch.setattr(root, "level", root.level)
    monkeypatch.setattr(root, "handlers", list(root.handlers))
    return root


# -- built-ins

def test_every_server_has_the_three_built_ins_with_their_defaults() -> None:
    mcp = QuickMCP("t", environ={})
    assert set(type(mcp.config).model_fields) == {"serving", "telemetry", "delivery"}
    s = mcp.config.serving
    assert (s.transport, s.host, s.port, s.log_level) == ("stdio", "127.0.0.1", 8000, "INFO")
    assert mcp.config.telemetry == TelemetrySettings() and mcp.config.delivery == DeliverySettings()
    assert set(config_schema()["properties"]) == {"serving", "telemetry", "delivery"}


@pytest.mark.parametrize("path, env, arg", [
    ("serving.transport", "TRANSPORT", "--transport"), ("serving.host", "HOST", "--host"),
    ("serving.port", "PORT", "--port"), ("serving.log_level", "LOG_LEVEL", "--log-level"),
    ("telemetry.profiles", "TELEMETRY_PROFILES", "--telemetry-profiles"),
    ("telemetry.profile_cpu", "TELEMETRY_PROFILE_CPU", "--telemetry-profile-cpu"),
    ("telemetry.profile_memory", "TELEMETRY_PROFILE_MEMORY", "--telemetry-profile-memory"),
    ("telemetry.otel", "TELEMETRY_OTEL", "--telemetry-otel"),
    ("telemetry.tags", "TELEMETRY_TAGS", "--telemetry-tags"),
    ("delivery.resources", "DELIVERY_RESOURCES", "--delivery-resources"),
    ("delivery.listed", "DELIVERY_LISTED", "--delivery-listed"),
    ("delivery.via", "DELIVERY_VIA", "--delivery-via"),
])
def test_each_built_in_item_has_its_names(path, env, arg) -> None:
    item = {i.path: i for i in _compose([]).items}[path]
    assert (item.env, item.arg) == (env, arg)


def test_off_is_a_value_and_the_env_turns_it_on() -> None:
    mcp = QuickMCP("t", environ={"TELEMETRY_OTEL": "true", "TELEMETRY_TAGS": '{"team": "a"}',
                                 "TELEMETRY_PROFILES": "http://p:4040"})
    t = mcp.config.telemetry
    assert t.otel is True and t.tags == {"team": "a"} and t.profiles.get_secret_value() == "http://p:4040"
    assert mcp.config_sources["telemetry.profiles"] == Source("env", "TELEMETRY_PROFILES")
    assert "http://p:4040" not in repr(mcp.config)


def test_the_transports_are_fastmcps() -> None:
    hint = typing.get_type_hints(FastMCP.run)["transport"]
    theirs = {a for m in typing.get_args(hint) or (hint,) for a in typing.get_args(m) or (m,) if a is not type(None)}
    assert set(typing.get_args(ServingSettings.model_fields["transport"].annotation)) == theirs


def test_a_serving_subclass_changes_the_defaults_and_keeps_the_names() -> None:
    mcp = QuickMCP("t", sections=[Pod], environ={})
    assert (mcp.config.serving.transport, mcp.config.serving.host) == ("http", "0.0.0.0")
    assert QuickMCP("t", sections=[Pod], environ={"HOST": "10.0.0.1"}).config.serving.host == "10.0.0.1"


def test_a_subclass_field_that_drops_its_names_is_refused() -> None:
    @config("serving")
    class Bare(ServingSettings):
        host: str = "0.0.0.0"

    with pytest.raises(TypeError) as caught:
        _compose([[Bare]])
    assert str(caught.value) == (
        "serving.host: redefines ServingSettings.host without its env='HOST' and arg='--host': "
        "restate Field(..., env='HOST', arg='--host') to keep them"
    )


@config("telemetry")
class Traced(TelemetrySettings):
    sampler: str = "always"


def test_a_servers_telemetry_subclass_replaces_the_built_in() -> None:
    mcp = QuickMCP("t", sections=[Traced], config={"telemetry": {"sampler": "never"}})
    assert type(mcp.config.telemetry) is Traced and mcp._provided[TelemetrySettings] is mcp.config.telemetry


# -- serving (moved here from test_config_sources.py's "a server's sources", onto the real serving)

def test_run_reads_host_and_port_from_environ(ran) -> None:
    QuickMCP("t", environ={"TRANSPORT": "http", "HOST": "0.0.0.0", "PORT": "9001"}).run(path="/mcp")
    assert ran == [{"transport": "http", "host": "0.0.0.0", "port": 9001, "show_banner": False, "path": "/mcp"}]


def test_run_on_stdio_passes_nothing_else(ran) -> None:
    QuickMCP("t", environ={}).run(path="/mcp")
    assert ran == [{"transport": "stdio", "show_banner": False}]


def test_run_takes_no_serving(ran) -> None:
    with pytest.raises(TypeError):
        QuickMCP("t", environ={}).run(argparse.Namespace(transport="http", host="h", port=1))
    assert ran == [] and not hasattr(kubed.mcp.app, "Serving") and "Serving" not in kubed.mcp.__all__


def test_run_sets_the_root_level_and_adds_a_handler_only_when_there_is_none(ran, root_logging, monkeypatch) -> None:
    called: list[dict] = []
    monkeypatch.setattr(logging, "basicConfig", lambda **kw: called.append(kw))
    QuickMCP("t", environ={"LOG_LEVEL": "DEBUG"}).run()
    assert root_logging.level == logging.DEBUG and called == []  # pytest's handlers are on root
    root_logging.handlers = []
    QuickMCP("t", environ={"LOG_LEVEL": "WARNING"}).run()
    assert root_logging.level == logging.WARNING and len(called) == 1


def test_construction_sets_no_level(root_logging) -> None:
    before = root_logging.level
    QuickMCP("t", environ={"LOG_LEVEL": "DEBUG"})
    assert root_logging.level == before


# -- no attribute reads

def test_no_section_is_found_by_attribute_name() -> None:
    """CMP-5: no getattr or hasattr on the config outside the module that loads it."""
    for path in Path(kubed.mcp.__file__).parent.glob("*.py"):
        if path.name == "_config.py":
            continue
        for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))):
            if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in ("getattr", "hasattr"):
                assert "config" not in ast.unparse(node.args[0]).lower(), f"{path.name}:{node.lineno}"

Also move the sources plan's # -- a server's sources tests (test_a_server_reads_only_the_flags_and_env_it_is_given, test_environ_none_reads_the_process_env, test_config_with_argv_or_environ_is_a_type_error_through_the_server, test_a_bad_flag_stops_construction_without_exiting and test_config_sources_is_read_only) into # -- serving. They drop sections=[Serve], and port / PORT / --port become serving.port read through the built-in. Their assertions are otherwise unchanged.

  • Step 2: Run the tests to verify they fail

Run: pytest tests/test_components.py -v Expected: collection fails with ImportError: cannot import name 'ServingSettings' from 'kubed.mcp'.

  • Step 3: Implement

  • _builtins.py, the telemetry.py changes and _builtin_sections(), as design items 4 and 5 say.

  • _check_item_keywords refuses a field that drops a model base's env or arg, as design item 4 says. Give each field a one-sentence doc. TelemetrySettings' docstring drops "a server's config can embed", and says the section is registered in every server, and that a server's subclass under telemetry replaces it.

  • app.py:

    • the two section reads by class;
    • self._provided;
    • run() as design item 5 says, with the docstring saying where its settings come from and that it sets the root level;
    • no Serving and no hasattr.
  • delivery.py: the types, imported from ._builtins.

  • __init__.py: the exports.

  • Step 4: Move the tests onto the real sections

  • tests/conftest.py: add no_builtins. Its docstring says it's for tests of composition that name their own PORT or telemetry key. no_config_from_the_runner's docstring now names the built-ins' env vars, which _compose([]).items covers.

  • tests/test_config_sources.py:

    • the module's pytestmark uses no_builtins. Its fixtures Serve (PORT, --port) and Tel (key telemetry) would clash with the built-ins;
    • the server tests moved out in Step 1.
  • tests/test_config.py:

    • the tests that assert a composition's exact keys use @pytest.mark.usefixtures("no_builtins"): lines 245, 304–306, 338, 580–582 and 837 on issue-47;
    • the two monkeypatch.setattr(kubed.mcp._config, "_BUILTINS", (Base,)) become monkeypatch.setattr(kubed.mcp._config, "_builtin_sections", lambda: (Base,));
    • test_a_server_with_no_sections_has_an_empty_config becomes test_a_server_with_no_sections_has_only_the_built_ins, asserting the three keys;
    • test_the_composed_class_is_not_a_key uses Root in place of Duck.
  • tests/test_app.py:

    • Settings and the Duck import go;
    • test_the_root_section_is_injectable uses Inject[ServingSettings] with config={"serving": {"port": 9000}};
    • test_run_reads_serving, test_run_reads_an_argparse_namespace, test_run_falls_back_to_the_config_and_passes_http_options and test_run_needs_a_serving are deleted, since tests/test_components.py covers them;
    • test_run_hands_fastmcps_logging_to_the_server and test_serving_over_http_leaves_fastmcps_logging_with_the_server build their server with config={"serving": {...}}, the latter with "log_level": "DEBUG", and take a root_logging fixture of their own (copy the one above).
  • tests/test_telemetry.py:

    • served() is QuickMCP(name, config={"telemetry": telemetry}, **options);
    • a test that handed an argparse.Namespace or None as the section is either rewritten on TelemetrySettings, keeping every assertion that a secret never shows, or deleted where it only tested a duck (test_otel_off_adds_no_call_metrics keeps TelemetrySettings() alone);
    • config.telemetry.profiles == ADDRESS becomes .get_secret_value() == ADDRESS;
    • _with_teardown keeps its signature in this task.
  • tests/test_delivery_inputs.py, tests/test_via.py and tests/test_listed.py:

    • each config() helper returns DeliverySettings(...), a list for listed joined with ",";
    • each server builder passes config={} when it's given no delivery, else config={"delivery": delivery}, with no sections=.
  • tests/test_facade.py:

    • OWN["kubed.mcp"] drops Serving and Telemetry, and gains DeliverySettings and ServingSettings (Component comes in Task 3);
    • test_importing_kubed_mcp_imports_no_fastmcp expects loaded == ["kubed.mcp._builtins", "kubed.mcp._config", "kubed.mcp.telemetry"];
    • the config-modules test is parametrized as (module, extra tops, allowed relative):
      • ("kubed.mcp.telemetry", set(), {"_config"});
      • ("kubed.mcp._config", {"yaml"}, set());
      • ("kubed.mcp._builtins", set(), {"_config", "telemetry"});
    • it asserts set(relative) <= allowed.
  • Step 5: Confirm no reader of the old shapes is left

Run: grep -rnE "Duck|config_server|run\(serving|getattr\(self\._config|hasattr\(settings" kubed tests Expected: no match. The public names Serving and Telemetry are covered by tests/test_facade.py's OWN and by test_run_takes_no_serving.

  • Step 6: Run the tests to verify they pass

Run: pip install -e .[test,tasks] && pytest -v Expected: PASS, the whole suite, tests/test_facade.py's fresh interpreters included.

  • Step 7: Checks and commit

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

git add kubed tests
git commit -m "feat!: serving, telemetry and delivery are built-in sections; run() reads serving and applies log_level"

Task 3: Component, components=, the lifecycle, the start lines and mcp.auth

Files:

  • Create: kubed/mcp/components.py: Component, _start_all and _stop_all.
  • Modify: kubed/mcp/_builtins.py: _ServingComponent, _TelemetryComponent, _DeliveryComponent and _builtin_components.
  • Modify: kubed/mcp/_config.py: _Loaded.boot_line. _load builds it and no longer logs.
  • Modify: kubed/mcp/app.py:
    • QuickMCP.__init__(..., components=());
    • _with_teardown's new signature;
    • the auth property;
    • run() marks serving as started;
    • telemetry's metrics and start move into its component.
  • Modify: kubed/mcp/__init__.py: Component, eager.
  • Modify tests:
    • tests/test_config_sources.py: every boot-line test reads .boot_line, and test_the_boot_line_is_not_built_when_info_is_off is deleted;
    • tests/test_telemetry.py: the _with_teardown call;
    • tests/test_facade.py: OWN gains Component, loaded gains "kubed.mcp.components", and the config-modules test gains ("kubed.mcp.components", set(), set()) and lets _builtins import components.
  • Test: tests/test_components.py, sections # -- a server's component, # -- order and # -- auth.

Interfaces:

  • Consumes: Task 2's sections and _provided.

  • Produces:

    • class Component as design item 1 says;
    • async def _start_all(parts: Sequence[tuple[Component, BaseModel | None]]) -> list[Component]. It returns those started. On a raise it stops them and re-raises;
    • async def _stop_all(started: Sequence[Component]) -> None, in reverse, logging as design item 3 says;
    • _builtin_components(name: str) -> tuple[Component, Component, Component];
    • _with_teardown(container: Container, lifespan, *, parts: Sequence[tuple[Component, BaseModel | None]], boot_line: str, on_enter: Callable[[], None]);
    • QuickMCP.auth: AuthProvider | None, a read-write property;
    • _Loaded.boot_line: str.
  • Step 1: Write the failing tests

LOG = logging.getLogger("tests.components")
EVENTS: list[str] = []


@config("backend")
class Backend(Config):
    url: str = "mem://"


class Recorder(Component):
    section = Backend

    def __init__(self, tag: str, *, fail_start: bool = False, fail_stop: bool = False) -> None:
        self.tag, self.fail_start, self.fail_stop = tag, fail_start, fail_stop

    def register(self, mcp, section) -> None:
        EVENTS.append(f"register {self.tag} {section.url}")

    async def start(self, section) -> None:
        LOG.info("start %s", self.tag)
        EVENTS.append(f"start {self.tag} {section.url}")
        if self.fail_start:
            raise RuntimeError("https://user:s3cret@x")

    async def stop(self) -> None:
        EVENTS.append(f"stop {self.tag}")
        if self.fail_stop:
            raise RuntimeError("https://user:s3cret@x")


# -- a server's component

async def test_a_component_gets_its_section_and_starts_and_stops_in_order() -> None:
    EVENTS.clear()
    mcp = QuickMCP("t", components=[Recorder("a"), Recorder("b")], config={"backend": {"url": "redis://r"}})
    assert EVENTS == ["register a redis://r", "register b redis://r"]
    async with Client(mcp.server):
        assert EVENTS[2:] == ["start a redis://r", "start b redis://r"]
    assert EVENTS[4:] == ["stop b", "stop a"]


async def test_a_raising_stop_is_logged_by_type_and_the_others_still_stop(caplog) -> None:
    EVENTS.clear()
    mcp = QuickMCP("t", components=[Recorder("a"), Recorder("b", fail_stop=True)], environ={})
    async with Client(mcp.server):
        pass
    assert EVENTS[-2:] == ["stop b", "stop a"]
    (record,) = [r for r in caplog.records if r.name == "kubed.mcp.components"]
    assert (record.levelno, record.getMessage()) == (logging.ERROR, "Recorder did not stop cleanly: RuntimeError")
    assert "s3cret" not in caplog.text


async def test_a_raising_start_stops_those_started_and_fails_the_boot(monkeypatch) -> None:
    EVENTS.clear()
    closed: list[bool] = []

    async def aclose(self) -> None:
        closed.append(True)

    monkeypatch.setattr(Container, "aclose", aclose)
    monkeypatch.setattr(kubed.mcp.telemetry, "_running", None)
    fake = types.ModuleType("pyroscope")
    fake.configure = lambda **kw: EVENTS.append("profiles started")
    fake.shutdown = lambda: EVENTS.append("profiles stopped")
    monkeypatch.setitem(sys.modules, "pyroscope", fake)
    mcp = QuickMCP(
        "t",
        components=[Recorder("a"), Recorder("b", fail_start=True), Recorder("c")],
        config={"telemetry": {"profiles": "http://p:4040"}},
    )
    with pytest.raises(BaseException) as caught:
        async with Client(mcp.server):
            pass
    assert _holds(caught.value, RuntimeError)
    assert [e for e in EVENTS if not e.startswith("register")] == [
        "profiles started", "start a mem://", "start b mem://", "stop a", "profiles stopped",
    ]
    assert closed == [True]


def test_components_takes_component_instances() -> None:
    for bad in (Recorder, object()):
        with pytest.raises(TypeError, match=r"components= takes Component instances"):
            QuickMCP("t", components=[bad], environ={})


def test_a_components_section_needs_its_own_config_mark() -> None:
    class Bare(Component):
        section = Unmarked  # a Config subclass with no @config
    with pytest.raises(TypeError, match=r"no @config of its own"):
        QuickMCP("t", components=[Bare()], environ={})


def test_a_component_with_no_section_gets_none() -> None:
    seen: list[object] = []
    class Plain(Component):
        def register(self, mcp, section) -> None:
            seen.append(section)
    QuickMCP("t", components=[Plain()], environ={})
    assert seen == [None]


# -- order

async def test_the_boot_line_is_logged_at_each_start_before_the_components(caplog) -> None:
    with caplog.at_level(logging.INFO):
        mcp = QuickMCP("t", components=[Recorder("a")], environ={"PORT": "9000"})
        assert not [r for r in caplog.records if r.name == "kubed.mcp.config"]  # nothing at construction
        for _ in range(2):
            async with Client(mcp.server):
                pass
    names = ("kubed.mcp.config", "tests.components")
    lines = [r.getMessage() for r in caplog.records if r.name in names]
    assert lines == ["config: serving.port=9000 (env PORT)", "start a"] * 2


# -- auth

class Refuse(TokenVerifier):
    async def verify_token(self, token: str):
        return None


def test_auth_set_after_construction_is_enforced() -> None:
    mcp = QuickMCP("t", environ={})
    assert mcp.auth is None
    mcp.auth = Refuse()
    assert mcp.server.auth is mcp.auth
    client = TestClient(mcp.server.http_app())
    answer = client.post("/mcp", json={"jsonrpc": "2.0", "id": 1, "method": "ping"},
                         headers={"accept": "application/json, text/event-stream"})
    assert answer.status_code == 401


def test_a_component_can_set_auth_in_register() -> None:
    class Door(Component):
        def register(self, mcp, section) -> None:
            mcp.auth = Refuse()
    assert isinstance(QuickMCP("t", components=[Door()], environ={}).auth, Refuse)


def test_auth_is_fixed_once_run_is_called(ran) -> None:
    mcp = QuickMCP("t", environ={})
    mcp.run()
    with pytest.raises(RuntimeError, match=r"auth is fixed once serving starts"):
        mcp.auth = Refuse()


async def test_auth_is_fixed_inside_the_lifespan() -> None:
    mcp = QuickMCP("t", environ={})
    async with Client(mcp.server):
        with pytest.raises(RuntimeError, match=r"auth is fixed once serving starts"):
            mcp.auth = Refuse()

Notes on the test file:

  • _holds(error, kind) is a helper in the file. It says whether error, its __cause__ or __context__, or a member of an exception group's .exceptions, at any depth, is a kind, because FastMCP may wrap a lifespan's error.
  • Unmarked is a module-level Config subclass with no @config.
  • TokenVerifier comes from kubed.mcp.auth, and TestClient from starlette.testclient. Refuse may need the constructor arguments FastMCP 4.2's TokenVerifier takes: give it what its signature asks.
  • In tests/test_facade.py, test_importing_kubed_mcp_imports_no_fastmcp's cases gain "from kubed.mcp import Component, DeliverySettings, ServingSettings".

In tests/test_config_sources.py, each boot-line test becomes an assertion on the load's .boot_line. For example, test_the_boot_line_lists_only_what_is_not_default asserts the two loads' boot_lines, and that no kubed.mcp.config record was logged.

  • Step 2: Run the tests to verify they fail

Run: pytest tests/test_components.py tests/test_config_sources.py -v Expected:

  • collection fails with ImportError: cannot import name 'Component';

  • the boot-line tests fail on AttributeError: '_Loaded' object has no attribute 'boot_line'.

  • Step 3: Implement

  • components.py, as design items 1 and 3 say. The module docstring says what a component is, and that it imports no FastMCP.

  • The three built-in components and _builtin_components, as item 5 says. The telemetry component keeps its _Signals and logs no TEL-20 line yet: Task 5 adds it.

  • _Loaded.boot_line. _load builds it unconditionally and stops logging.

  • app.py:

    • __init__ validates components, builds _builtin_components(name), and passes the component sections to _load;
    • it builds parts from loaded.provided, and gives _with_teardown the parts, the boot line and on_enter=self._serving_starts;
    • it calls each part's register last;
    • _with_teardown runs design item 3's steps, using _start_all and _stop_all, and logs the boot line on logging.getLogger("kubed.mcp.config");
    • auth is as item 7 says, and run() marks serving as started before it reads serving.
  • tests/test_telemetry.py's direct _with_teardown test uses parts=[(_TelemetryComponent("t"), TelemetrySettings(profiles=ADDRESS))], boot_line="config: all defaults" and on_enter=lambda: None. Its assertion about the lifespan's own error is unchanged.

  • Step 4: Run the tests to verify they pass

Run: pytest -v Expected: PASS, the whole suite. The telemetry tests that rely on signals starting before the server's lifespan and stopping after it are unchanged.

  • Step 5: Checks and commit

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

git add kubed tests
git commit -m "feat: components that register, start and stop around serving; the boot line at start; mcp.auth until serving starts"

Task 4: Hooks, and config_schema(hooked=)

Files:

  • Modify: kubed/mcp/_config.py:
    • _compose(sources, *, hooked=frozenset()), and _items and _check_names skip the hooked keys' names;
    • _load(..., hooks=None);
    • config_schema(*sections, hooked=());
    • _Schema leaves out env and arg on the hooked sections' properties;
    • new _check_hooks.
  • Modify: kubed/mcp/app.py: QuickMCP.__init__(..., hooks=None) passes it to _load.
  • Test: tests/test_components.py, section # -- hooks.

Interfaces:

  • Consumes: Task 2's built-ins and _builtin_sections(), and Task 3's _Loaded.boot_line.

  • Produces:

    • _load(sources, values, *, argv=None, environ=None, hooks: Mapping[str, Callable[[Config], BaseModel]] | None = None) -> _Loaded;
    • _compose(sources, *, hooked: frozenset[str] = frozenset()) -> _Composition;
    • _check_hooks(keys: Iterable[object], what: str) -> frozenset[str], which raises design item 6's ValueError with what as "hooks=" or "hooked=";
    • config_schema(*sections: type[BaseModel], hooked: Iterable[str] = ()) -> dict[str, Any].
  • Step 1: Write the failing tests

@config()
class Kb(Config):
    port: int = Field(9100, env="PORT", arg="--port")
    bind: str = "0.0.0.0"


def from_root(config) -> ServingSettings:
    return ServingSettings(transport="http", host=config.bind, port=config.port)


def test_a_hook_builds_serving_from_the_servers_own_fields() -> None:
    mcp = QuickMCP("kb", sections=[Kb], hooks={"serving": from_root}, environ={"PORT": "9200"})
    s = mcp.config.serving
    assert (s.transport, s.host, s.port) == ("http", "0.0.0.0", 9200)
    assert mcp.config.port == 9200 and mcp.config_sources["port"] == Source("env", "PORT")
    assert {mcp.config_sources[f"serving.{n}"] for n in ("transport", "host", "port", "log_level")} == {Source("hook")}


def test_a_hooked_built_ins_env_and_flags_are_not_read() -> None:
    seen: list[object] = []

    def keep(config):
        seen.append(config.serving)
        return ServingSettings()

    mcp = QuickMCP("t", hooks={"serving": keep}, environ={"HOST": "10.0.0.1", "PORT": "1"})
    assert seen[0].host == "127.0.0.1" and mcp.config.serving.port == 8000
    with pytest.raises(ValueError, match=r"  the arguments \(arg --port\): no item takes this flag"):
        QuickMCP("t", hooks={"serving": keep}, argv=["--port", "1"], environ={})


def test_a_hooked_sections_file_entries_are_not_read(tmp_path) -> None:
    f = tmp_path / "c.yaml"
    f.write_text("serving:\n  port: 1\n")
    mcp = QuickMCP("t", hooks={"serving": lambda c: ServingSettings(port=2)}, environ={"CONFIG_FILE": str(f)})
    assert mcp.config.serving.port == 2 and mcp.config_sources["serving.port"] == Source("hook")


def test_a_servers_port_and_a_hooked_serving_do_not_clash() -> None:
    with pytest.raises(ValueError, match=r"'PORT' is declared by both serving\.port and port"):
        QuickMCP("kb", sections=[Kb], environ={})
    QuickMCP("kb", sections=[Kb], hooks={"serving": from_root}, environ={})
    schema = config_schema(Kb, hooked=["serving"])
    serving = schema["$defs"]["ServingSettings"]["properties"]["port"]
    assert "env" not in serving and "arg" not in serving and schema["properties"]["port"]["env"] == "PORT"
    with pytest.raises(ValueError, match=r"PORT"):
        config_schema(Kb)


def test_a_hook_returning_the_wrong_type_is_a_type_error() -> None:
    with pytest.raises(TypeError, match=r"hooks\['serving'\] returned a dict, not an instance of ServingSettings"):
        QuickMCP("t", hooks={"serving": lambda c: {"port": 1}}, environ={})


def test_a_hook_may_return_the_servers_subclass_and_must_when_one_holds_the_key() -> None:
    mcp = QuickMCP("t", sections=[Pod], hooks={"serving": lambda c: Pod(port=3)}, environ={})
    assert type(mcp.config.serving) is Pod and mcp.config.serving.port == 3
    with pytest.raises(TypeError, match=r"not an instance of Pod"):
        QuickMCP("t", sections=[Pod], hooks={"serving": lambda c: ServingSettings()}, environ={})


def test_a_hooks_result_is_validated_and_its_errors_name_the_hook() -> None:
    bad = ServingSettings.model_construct(port="not a port")
    with pytest.raises(ValueError, match=r"  serving\.port \(hook\): Input should be a valid integer"):
        QuickMCP("t", hooks={"serving": lambda c: bad}, environ={})


@pytest.mark.parametrize("hooks, error, match", [
    ({"recording": from_root}, ValueError, r"hooks= takes a built-in's key, one of 'serving', 'telemetry', 'delivery'; got 'recording'"),
    ({"serving": 1}, TypeError, r"hooks\['serving'\] must be callable"),
    ([("serving", from_root)], TypeError, r"hooks= takes a mapping"),
])
def test_a_bad_hooks_argument_is_refused(hooks, error, match) -> None:
    with pytest.raises(error, match=match):
        QuickMCP("t", hooks=hooks, environ={})


def test_every_built_in_takes_a_hook() -> None:
    mcp = QuickMCP("t", environ={}, hooks={
        "telemetry": lambda c: TelemetrySettings(otel=False, tags={"a": "b"}),
        "delivery": lambda c: DeliverySettings(via="local"),
    })
    assert mcp.config.telemetry.tags == {"a": "b"} and mcp.config.delivery.via == "local"
    assert mcp.config_sources["delivery.via"] == Source("hook")


def test_the_boot_line_shows_hooked_items_as_hook() -> None:
    loaded = _load([[]], None, environ={}, hooks={"serving": lambda c: ServingSettings(port=1)})
    assert "serving.port=1 (hook)" in loaded.boot_line
  • Step 2: Run the tests to verify they fail

Run: pytest tests/test_components.py -v -k hook Expected: FAIL with TypeError: QuickMCP.__init__() got an unexpected keyword argument 'hooks'.

  • Step 3: Implement

As design item 6 says:

  • _check_hooks;
  • _compose(hooked=) and _check_names skipping;
  • in _load:
    • the hooked items are left out of _read_env and _read_argv, with one filtered item list used by both, so the flag indexes line up;
    • the hooked keys are dropped from the file's and the code layer's data;
    • the hooks run after the first validation, then the result is validated, the model validated again, and the hook layer put on top;
    • boot_line is built last;
  • config_schema(hooked=), and _Schema, which is given the hooked sections' classes, for example through a subclass made per call;
  • QuickMCP's hooks= passthrough. Its docstring states the hook's contract.

_load's and config_schema's docstrings state the hooked keys' rules and the TypeErrors and ValueErrors.

  • Step 4: Run the tests to verify they pass

Run: pytest tests/test_components.py tests/test_config_sources.py 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 tests
git commit -m "feat(config): hooks supply a built-in's section from the server's own config"

Task 5: TEL-20, the telemetry start line

Files:

  • Modify: kubed/mcp/telemetry.py: new _start_line and _where.
  • Modify: kubed/mcp/_builtins.py: _TelemetryComponent.start logs the line.
  • Test: tests/test_telemetry.py, section # -- the start line, and the order test in tests/test_components.py.

Interfaces:

  • Consumes: Task 3's _TelemetryComponent, and _Signals' _profiles and _otel.

  • Produces:

    • _start_line(signals: _Signals | None, settings: TelemetrySettings) -> str;
    • _where(address: str) -> str: the host, as design item 9 says. It never raises.
  • Step 1: Write the failing tests

def start_lines(caplog) -> list[str]:
    return [r.getMessage() for r in caplog.records if r.name == "kubed.mcp.telemetry" and r.getMessage().startswith("telemetry: ")]


async def test_the_start_line_says_off_with_nothing_on(caplog) -> None:
    with caplog.at_level(logging.INFO, logger="kubed.mcp.telemetry"):
        async with Client(served("off", TelemetrySettings()).server):
            pass
    assert start_lines(caplog) == ["telemetry: off"]


async def test_the_start_line_names_profiles_and_the_host(pyroscope, caplog) -> None:
    with caplog.at_level(logging.INFO, logger="kubed.mcp.telemetry"):
        async with Client(served("p", TelemetrySettings(profiles=ADDRESS)).server):
            pass
    assert start_lines(caplog) == ["telemetry: profiles → pyroscope.example.com:4040"]


async def test_the_start_line_names_otels_exporters(traced, pyroscope, monkeypatch, caplog) -> None:
    monkeypatch.setenv("OTEL_TRACES_EXPORTER", " console ")
    with caplog.at_level(logging.INFO, logger="kubed.mcp.telemetry"):
        async with Client(served("o", TelemetrySettings(profiles=ADDRESS, otel=True)).server):
            pass
    assert start_lines(caplog) == [
        "telemetry: profiles → pyroscope.example.com:4040; otel → traces console, metrics otlp, logs none"
    ]


@pytest.mark.parametrize("address, shown", [
    ("https://user:s3cret@pyroscope.example:4040/push?token=s3cret", "pyroscope.example:4040"),
    ("user:s3cret@pyroscope:4040", "pyroscope:4040"),
    ("http://[::1]:4040", "[::1]:4040"),
    ("http://host:notaport", "host"),
    ("http://", "an address with no host"),
])
def test_the_start_line_never_shows_a_credential(address, shown) -> None:
    assert telemetry._where(address) == shown and "s3cret" not in shown


async def test_profiles_that_fail_to_start_are_not_named(monkeypatch, caplog) -> None:
    monkeypatch.setitem(sys.modules, "pyroscope", None)  # not installed
    with caplog.at_level(logging.INFO, logger="kubed.mcp.telemetry"):
        async with Client(served("missing", TelemetrySettings(profiles=ADDRESS)).server):
            pass
    assert start_lines(caplog) == ["telemetry: off"]

In tests/test_components.py, test_the_boot_line_is_logged_at_each_start_before_the_components becomes test_the_start_lines_are_the_boot_line_then_telemetry_then_the_components. Its names gain "kubed.mcp.telemetry", and it expects ["config: serving.port=9000 (env PORT)", "telemetry: off", "start a"] * 2.

  • Step 2: Run the tests to verify they fail

Run: pytest tests/test_telemetry.py -v -k start_line Expected: FAIL: no telemetry: line, and no _where.

  • Step 3: Implement

_where and _start_line in telemetry.py, as design item 9 says, use urllib.parse.urlsplit and read only os.environ. The component's start logs log.info("%s", _start_line(signals, section)) after _start_signals. Both docstrings say the line never shows a credential.

  • Step 4: Run the tests to verify they pass

Run: pytest tests/test_telemetry.py tests/test_components.py -v Expected: PASS, the order test included.

  • Step 5: Checks and commit

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

git add kubed/mcp/telemetry.py kubed/mcp/_builtins.py tests/test_telemetry.py tests/test_components.py
git commit -m "feat(telemetry): one start line naming the signals that started and where they go"

Task 6: The rows, the pages, the README and the changelog

Files:

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

Interfaces:

  • Consumes: Tasks 1 to 5, built and green. Check every row below against the code as built before writing it, and where a detail differs, correct the row, not the code.

  • Produces: nothing that code reads.

  • Step 1: Components. CMP-2 to CMP-6 lose (proposed), and each states what's built:

    • CMP-2: Component, with section, register(mcp, section), start(section) and stop(), all optional. A server passes QuickMCP(components=[...]), and the section is the loaded instance of the class that won the key.
    • CMP-3: the order of design item 3:
      • register at the end of construction;
      • starts in order with the built-ins first, at each lifespan entry, after the boot line;
      • stops in reverse;
      • a stop's error is logged by type and the next stop runs;
      • a start's error stops those started and fails the boot;
      • the container closes last.
    • CMP-4: the three keys, as now.
    • CMP-5: as now.
    • CMP-6: hooks={"serving": fn}, built-in keys only. The hooked section's file entries, env vars, flags and config= values aren't read. The hook returns an instance of the class holding the key, which is validated, and its items record hook. Its names are out of the clash check. config_schema(hooked=) composes the same way.

    Then add ## The built-ins' settings: one table per built-in with its key, fields, types, defaults, env names and flags (design item 4). Below the serving table, note that a subclass restates Field(default, env=..., arg=...) on each field whose default it changes. Then add ## Writing a component: a ten-line example of a component with a section that registers a client in register and closes it in stop. It states no rule the rows don't.

  • Step 2: App.

    • APP-2: the signature of design item 2. Add: "mcp.auth is the server's auth provider. It may be set after construction, by the server or a component's register, until serving starts. Setting it after that is a RuntimeError."
    • APP-3 gains: "components are the server's components (CMP-2), and hooks supply built-ins' sections (CMP-6)."
    • APP-5: the lifespan order of design item 3.
    • APP-7: "run() reads the serving section (CMP-4): transport, host, port and log_level."
    • APP-8: "mcp.run(**http_options) takes no serving settings of its own."
    • APP-9: it also sets the root logger's level from log_level. It calls logging.basicConfig() first when the root logger has no handler, and nothing is set at construction.
    • APP-11: "run() never passes a log level to FastMCP: given one, FastMCP's run puts its own handlers back on the fastmcp logger, undoing APP-9."
  • Step 3: Config.

    • CFG-11: the boot line is built at load and logged once each time the server starts, before any component starts.
    • CFG-12: the kinds list hook (CMP-6) as an item. The boot-line sentence says the line is logged at start (CFG-11).
    • CFG-14 gains: "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."
    • CFG-15 gains hooked=.
    • In the config page's operator section, the boot line's example says it appears at start.
  • Step 4: Telemetry, delivery and the facade.

    • TEL-2:
      • the built-in telemetry section (CMP-4), TelemetrySettings, is registered in every server, and QuickMCP reads no attribute;
      • the table gains env and flag columns, and profiles is SecretStr | None;
      • a server's subclass under telemetry replaces it;
      • code reads it as Inject[TelemetrySettings].
    • TEL-3 drops "How the section maps to environment variables and flags is the server's own config loading", which the names now settle.
    • TEL-20 loses (proposed) and gains the line's example and the telemetry: off case.
    • TEL-18, TEL-19 and TEL-21 keep (proposed).
    • DLV-4: the built-in delivery section (DeliverySettings, CMP-4) gives each input's default: resources, listed (a comma string) and via, from DELIVERY_* or the --delivery-* flags. The rest stays: a value its input doesn't take is dropped with one warning when QuickMCP is built, naming config delivery.<attribute>. Delivery is the partial type delivery_default answers with.
    • FAC-11: the eager names are Component, Config, DeliverySettings, Field, NoDecode, ServingSettings, Source, TelemetrySettings, config and config_schema. The last sentence names kubed.mcp.components and the built-ins' module beside telemetry and the config module.
  • Step 5: The history headers.

    • The design's History gains: "CMP-2 to CMP-6 and TEL-20 are built, in the components plan. TEL-18, TEL-19 and TEL-21 are left for their own round."
    • In this file's History, "Not built yet." becomes "Built in #58."
  • Step 6: The README. The example drops Settings and the Config and config imports. Its server line is mcp = QuickMCP("grid", argv=sys.argv[1:]), and mcp.run() gains the comment # TRANSPORT, HOST, PORT and LOG_LEVEL, or --transport, --host, --port and --log-level. Nothing else changes.

  • Step 7: The changelog, under [Unreleased]. The lines already there stay. ### Added gains:

- **Components:** subclass `Component` and pass `QuickMCP(components=[...])` to give part of a server its own config section, its objects in the container, and a start and stop around serving.
- Every server's config has the built-in `serving`, `telemetry` and `delivery` sections, set by `TRANSPORT`, `HOST`, `PORT`, `LOG_LEVEL`, `TELEMETRY_*` and `DELIVERY_*` or their `--` flags.
- `QuickMCP(hooks={"serving": fn})` builds a built-in's section from the server's own config, in place of its env vars, flags and file keys.
- Set `mcp.auth` after construction, until the server starts serving.
- At start, telemetry logs one line naming the signals that started and where they go, or `telemetry: off`.

### Changed gains:

- **BREAKING:** `run()` takes no serving settings and `Serving` is gone: set `serving` in the config (`TRANSPORT`, `--port`, a `serving:` file key) or through `hooks={"serving": ...}`; `run()` applies `serving.log_level` to the root logger.
- **BREAKING:** `Telemetry` is gone: a server reads telemetry's settings with `Inject[TelemetrySettings]`.
- **BREAKING:** `TelemetrySettings.profiles` is a `SecretStr`: read it with `get_secret_value()`.
- **BREAKING:** the config's boot line is logged when the server starts, not when `QuickMCP(...)` is built.
  • Step 8: Checks and commit

Leave the wiki edits in docs/. The job commits them on the wiki branch issue-49 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: CMP-2 to 6 and TEL-20 built; the app, config, telemetry, delivery and facade rows; README and changelog"

Clone this wiki locally