Repository navigation
2026 11 26 components
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 intoissue-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 parent's rulings aren't to be reopened:
- the TEL split;
-
log_levelapplied inrun(); - 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).
-
Componentis public, inkubed/mcp/components.py, and exported fromkubed.mcp. It imports no FastMCP:QuickMCPis imported underTYPE_CHECKINGonly. 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
sectionpassed is the loaded instance of the class that won the key, a server's subclass included. It'sNonewhen the component names no section. -
-
Registration.
- The signature is
QuickMCP(name, *, sections=(), components=(), hooks=None, config=None, argv=None, environ=None, header_prefix=None, **fastmcp_options). -
componentstakesComponentinstances. Anything else, aComponentsubclass itself included, is theTypeError"components= takes Component instances, got " (settled here). - The sources go to
_loadas[component sections, sections]._composeputs the built-ins first, so the order is built-ins, then component sections, then sections. - A component's
sectionwithout its own@configis #48'sTypeError("has no @config of its own"). Two components naming one key follow #48's subclass rule. -
registerruns 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.
- The signature is
-
Lifecycle. The lifespan
QuickMCPgives FastMCP does this, on every entry:- marks serving as started (item 7);
- logs the config boot line (item 8);
- starts each component in order;
- runs the server's own
lifespan; - stops the started components in reverse;
- runs
container.aclose()last.
- Every stop runs, even when an earlier one raised. A stop that raises an
Exceptionis logged at error onkubed.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).
-
The built-in sections live in
kubed/mcp/_builtins.py, which imports no FastMCP. Each is aConfig(extra="forbid") and is named exactly so._builtins.BUILTINSis(ServingSettings, TelemetrySettings, DeliverySettings).-
ServingSettingsatserving, exported fromkubed.mcp:Field Type Default env arg transportLiteral["stdio", "http", "sse", "streamable-http"]"stdio"TRANSPORT--transporthoststr"127.0.0.1"HOST--hostportint8000PORT--portlog_levelLiteral["CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG"]"INFO"LOG_LEVEL--log-levelThe transports are FastMCP's, as its
. 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.FastMCP.runannotatestransport. A test keeps them equal (settled here). A server changes the defaults by subclassing underserving, and restatesField(default, env=..., arg=...)on each field it changes. pydantic drops a parent field's metadata when a subclass redefines the field, so a barehost: str = "0.0.0.0"would have noHOST. Composition refuses it (Dr K, 09:23 UTC):_check_item_keywordscompares each field with the same field on the class's model bases, and one that drops a base'senvorargis aTypeError, naming the nearest base that has them: ": redefines -
TelemetrySettingsattelemetrystays inkubed/mcp/telemetry.py. It becomes aConfigwith@config("telemetry"), and its fields usekubed.mcp'sField(doc=..., env=..., arg=...):-
profiles: SecretStr | None, envTELEMETRY_PROFILES,--telemetry-profiles; -
profile_cpu: bool = True, envTELEMETRY_PROFILE_CPU,--telemetry-profile-cpu; -
profile_memory: bool = True, envTELEMETRY_PROFILE_MEMORY,--telemetry-profile-memory; -
otel: bool = False, envTELEMETRY_OTEL,--telemetry-otel; -
tags: dict[str, str], envTELEMETRY_TAGS(JSON),--telemetry-tags.
_start_profilespassesprofiles.get_secret_value()to pyroscope. -
-
DeliverySettingsatdelivery, exported fromkubed.mcp:resources,listedandvia, eachstr | None = None, with envDELIVERY_RESOURCES,DELIVERY_LISTEDandDELIVERY_VIAand flags--delivery-resources,--delivery-listedand--delivery-via.listedis a comma string. They're lax strings, so DLV-4's warn-and-ignore, at construction, is unchanged. TheDeliveryProtocol stays asDeliveryDefault's partial type. -
The cycle:
_config.pyholds no module-level relative import (FAC-11's test). Its_BUILTINSconstant becomes_builtin_sections() -> tuple[type[BaseModel], ...], which imports_builtins.BUILTINSinside the function._composecalls it, soconfig_schema()shows the three with noQuickMCP(settled here: a lazy import, not a registry).
-
-
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 callslogging.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 publicServingProtocol are removed.run()takes no positional argument. - reads the loaded
-
_TelemetryComponent(name)(section = TelemetrySettings):-
registerinserts_call_metrics(section)at index 0 when it isn'tNone; -
startis_start_signals(name, section), then the TEL-20 line (item 9); -
stopissignals.stop()when a start began some, and it forgets them.
Off still imports nothing. The public
TelemetryProtocol is removed, andInject[TelemetrySettings]replaces it._otel.pyand the telemetry functions are typed onTelemetrySettings. -
-
_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 anyregisterruns. Only the resolver's config input changes (settled here). -
No attribute reads:
- the
getattr(self._config, ...)reads go, and so doesrun()'shasattrfallback; -
_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.
- the
-
-
Hooks (CMP-6).
-
The type is
hooks: Mapping[str, Callable[[Config], BaseModel]] | None. -
Its keys are built-in keys:
serving,telemetryanddelivery.- 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".
- Any other key is the
-
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
--portfor 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 errorsserving.port (hook): <text>, reported together in the oneValueError. 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, asconfig=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_sourcegives it. -
Names: the hooked keys' env names and flags stay out of
_check_names, so a server's ownPORTdoesn'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 ashooks='s are. The hooked sections stay in the schema (CMP-4) without theirenvandarg, which aren't read, and their names aren't checked (settled here: without it, mcp-kb'sconfig_schema(Root)would refuse its ownPORT). -
CFG-12 lists
hook.
-
-
QuickMCP.authis a public property, since FastMCP 4.2 readsserver.authonly inhttp_app():- reading it gives
self.server.auth; - setting it assigns
self.server.auth, from a server's build code or a component'sregister; - once serving has started, setting it is the
RuntimeError"auth is fixed once serving starts: set mcp.auth before run()". Serving starts whenrun()is called or the lifespan is entered, and stays started (settled here: never cleared); -
auth=infastmcp_optionsstill works at construction; - there's no public compose: code takes its section (design goal 7).
- reading it gives
-
The start lines.
-
_Loadedgainsboot_line: str, which is #50's line, built after the hooks, at every load. -
_loadno longer logs it. The lifespan logs it, once per entry, onkubed.mcp.configat 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_lineand no longer read logs at load.test_the_boot_line_is_not_built_when_info_is_offis deleted, because the line is always built.
-
-
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: offwhen this start began none (_start_signalsreturnedNone).
The arrow is U+2192.
-
Where profiles go: the host, from
urllib.parse.urlsplitof the secret's value, ashostname, in brackets when it holds a:(IPv6), plus:portwhen there is one. It never includes userinfo, path or query.- An address without
://is read as//<address>, souser:pw@pyroscope:4040showspyroscope: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.
- An address without
-
Where OTel goes: each exporter from
OTEL_TRACES_EXPORTER,OTEL_METRICS_EXPORTERandOTEL_LOGS_EXPORTERasos.environholds it after_set_defaults, stripped. An unset or empty one showsotlp, ornonefor logs.
-
-
The
_mergebug. 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,codeincluded. - The value isn't a
BaseModelinstance, 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: brokenin the file plusREDIS_HOST=xgivesredis (file <path>): must be a mapping, not a str.
- "Model-typed" means a non-leaf item's
-
#50's carry-overs.
-
_boot_linemasks the loaded value at runtime with_masked(value), before_json. EverySecretStr,SecretBytesandSecretinstance becomes"**********", wherever it sits:- a
BaseModeland 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
RecursionErrornames the value by its type.
- a
-
tests/test_header_prefix.py:32is reformatted byruff format.
-
-
from __future__ import annotationsat the top of every module.kubed/gets no__init__.py. -
FastMCP-free modules.
kubed/mcp/_config.py,telemetry.py,components.pyand_builtins.pyimport only pydantic, the standard library and, for_config.py, PyYAML, at module level.- Their relative imports at module level are:
-
telemetry→_config; -
_builtins→_config,componentsandtelemetry; -
_configandcomponents: none.
-
-
componentsimportsQuickMCPunderTYPE_CHECKING, and_configimports_builtinsinside_builtin_sections(). - Importing
kubed.mcpstill loads no FastMCP.
- Their relative imports at module level are:
-
Public names:
- added:
-
Component,ServingSettingsandDeliverySettingsinkubed.mcp, eager; -
QuickMCP'scomponents=andhooks=; -
mcp.auth; -
config_schema(..., hooked=);
-
- removed:
Serving,Telemetryandrun(serving=); - retyped:
TelemetrySettings.profiles, now aSecretStr.
No other public name changes.
- added:
-
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=orconfig=; - 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.ymlafterpip 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 branchissue-49and moves the pointer here. No git runs insidedocs/, and the wiki'smasteris never pushed. Spec text is in the present tense, with no issue numbers and no names but Dr K's. -
.github/isn't touched.
-
A subclass that changes serving's default.
class Pod(ServingSettings): host: str = "0.0.0.0"would dropHOST, because pydantic replaces the field, so composition refuses it. The tests pin both: a subclass restatingField("0.0.0.0", env="HOST", arg="--host")defaults to0.0.0.0and still readsHOST, and a bare one is theTypeError(Task 2,test_a_serving_subclass_changes_the_defaults_and_keeps_the_namesandtest_a_subclass_field_that_drops_its_names_is_refused). -
A file that still holds a hooked section.
serving: {port: 1}in the file withhooks={"serving": fn}must load, take the hook's port, and recordhook, neverfile(Task 4,test_a_hooked_sections_file_entries_are_not_read). -
A start that fails after telemetry started. A server component whose
startraises 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). -
A server that configured logging itself.
run()must set only the root level and add no second handler. With no handler at all,basicConfigruns once (Task 2,test_run_sets_the_root_level_and_adds_a_handler_only_when_there_is_none). -
A Pyroscope address with credentials and no scheme.
user:pw@pyroscope:4040andhttps://user:pw@host:4040/x?token=tmust show onlypyroscope:4040andhost:4040(Task 5,test_the_start_line_never_shows_a_credential).
Files:
- Modify:
kubed/mcp/_config.py:-
_loadgains 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# -- shapesand# -- boot line.
Interfaces:
-
Consumes:
_Item,_Layer,_source,_json,_boot_lineonissue-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)withhost: str = Field("", env="REDIS_HOST"); -
Deeper(Config)withx: int = 0, andInner(Config)withdeep: Deeper = Deeper(); -
@config("outer") class Outer(Config)withinner: 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
S3CRETin the line. -
Step 3: Implement in
kubed/mcp/_config.py -
Add
_check_shapesas design item 10 says._loadruns it over every layer after the env and arg layers are built, before the merge, and adds its lines after the decode errors. -
Add
_maskedas item 11 says._boot_linecalls_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"Files:
- Create:
kubed/mcp/_builtins.py:ServingSettings,DeliverySettings,BUILTINS. - Modify:
kubed/mcp/_config.py:_BUILTINSbecomes_builtin_sections(), and_composecalls it;_check_item_keywordsrefuses a subclass field that drops its base's names. - Modify:
kubed/mcp/telemetry.py:-
Telemetryis removed; -
TelemetrySettingsbecomes@config("telemetry"), aConfig, with the env names andprofiles: SecretStr | None; -
_start_signals,_start_profiles,_start_oteland_call_metricsare typed on it, and_call_metricsloses itsgetattr.
-
- 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 theDeliverydocstring ("a partial set of defaults, asdelivery_defaultanswers"). - Modify:
kubed/mcp/app.py:-
Servingandrun(serving=)are removed; -
__init__readsloaded.provided[TelemetrySettings]andloaded.provided[DeliverySettings]in place of the twogetattrs, and keepsloaded.providedasself._provided; -
run(**http_options)readsself._provided[ServingSettings]and applieslog_level.
-
- Modify:
kubed/mcp/__init__.py:- drop
ServingandTelemetry; - add
DeliverySettingsandServingSettings, imported eagerly from._builtins; - the docstring's eager list.
- drop
- Delete:
tests/config_server.py. - Modify tests:
-
tests/conftest.py: ano_builtinsfixture, not autouse; -
tests/test_config.py; -
tests/test_config_sources.py: its modulepytestmarkgainspytest.mark.usefixtures("no_builtins"), and its# -- a server's sourcessection moves totests/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.pyandtests/test_facade.py.
-
- Test:
tests/test_components.py(new,pytestmark = pytest.mark.unit), sections# -- built-ins,# -- servingand# -- no attribute reads.
Interfaces:
-
Consumes:
Config,Field,configand_loadfrom_config.py. -
Produces:
-
kubed.mcp._builtins.ServingSettings,.DeliverySettingsand.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 monkeypatcheskubed.mcp._config._builtin_sectionstolambda: ().
-
-
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, thetelemetry.pychanges and_builtin_sections(), as design items 4 and 5 say. -
_check_item_keywordsrefuses a field that drops a model base'senvorarg, as design item 4 says. Give each field a one-sentencedoc.TelemetrySettings' docstring drops "a server's config can embed", and says the section is registered in every server, and that a server's subclass undertelemetryreplaces 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
Servingand nohasattr.
-
delivery.py: the types, imported from._builtins. -
__init__.py: the exports. -
Step 4: Move the tests onto the real sections
-
tests/conftest.py: addno_builtins. Its docstring says it's for tests of composition that name their ownPORTortelemetrykey.no_config_from_the_runner's docstring now names the built-ins' env vars, which_compose([]).itemscovers. -
tests/test_config_sources.py:- the module's
pytestmarkusesno_builtins. Its fixturesServe(PORT,--port) andTel(keytelemetry) would clash with the built-ins; - the server tests moved out in Step 1.
- the module's
-
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 onissue-47; - the two
monkeypatch.setattr(kubed.mcp._config, "_BUILTINS", (Base,))becomemonkeypatch.setattr(kubed.mcp._config, "_builtin_sections", lambda: (Base,)); -
test_a_server_with_no_sections_has_an_empty_configbecomestest_a_server_with_no_sections_has_only_the_built_ins, asserting the three keys; -
test_the_composed_class_is_not_a_keyusesRootin place ofDuck.
- the tests that assert a composition's exact keys use
-
tests/test_app.py:-
Settingsand theDuckimport go; -
test_the_root_section_is_injectableusesInject[ServingSettings]withconfig={"serving": {"port": 9000}}; -
test_run_reads_serving,test_run_reads_an_argparse_namespace,test_run_falls_back_to_the_config_and_passes_http_optionsandtest_run_needs_a_servingare deleted, sincetests/test_components.pycovers them; -
test_run_hands_fastmcps_logging_to_the_serverandtest_serving_over_http_leaves_fastmcps_logging_with_the_serverbuild their server withconfig={"serving": {...}}, the latter with"log_level": "DEBUG", and take aroot_loggingfixture of their own (copy the one above).
-
-
tests/test_telemetry.py:-
served()isQuickMCP(name, config={"telemetry": telemetry}, **options); - a test that handed an
argparse.NamespaceorNoneas the section is either rewritten onTelemetrySettings, keeping every assertion that a secret never shows, or deleted where it only tested a duck (test_otel_off_adds_no_call_metricskeepsTelemetrySettings()alone); -
config.telemetry.profiles == ADDRESSbecomes.get_secret_value() == ADDRESS; -
_with_teardownkeeps its signature in this task.
-
-
tests/test_delivery_inputs.py,tests/test_via.pyandtests/test_listed.py:- each
config()helper returnsDeliverySettings(...), a list forlistedjoined with","; - each server builder passes
config={}when it's given no delivery, elseconfig={"delivery": delivery}, with nosections=.
- each
-
tests/test_facade.py:-
OWN["kubed.mcp"]dropsServingandTelemetry, and gainsDeliverySettingsandServingSettings(Componentcomes in Task 3); -
test_importing_kubed_mcp_imports_no_fastmcpexpectsloaded == ["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"Files:
- Create:
kubed/mcp/components.py:Component,_start_alland_stop_all. - Modify:
kubed/mcp/_builtins.py:_ServingComponent,_TelemetryComponent,_DeliveryComponentand_builtin_components. - Modify:
kubed/mcp/_config.py:_Loaded.boot_line._loadbuilds it and no longer logs. - Modify:
kubed/mcp/app.py:-
QuickMCP.__init__(..., components=()); -
_with_teardown's new signature; - the
authproperty; -
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, andtest_the_boot_line_is_not_built_when_info_is_offis deleted; -
tests/test_telemetry.py: the_with_teardowncall; -
tests/test_facade.py:OWNgainsComponent,loadedgains"kubed.mcp.components", and the config-modules test gains("kubed.mcp.components", set(), set())and lets_builtinsimportcomponents.
-
- Test:
tests/test_components.py, sections# -- a server's component,# -- orderand# -- auth.
Interfaces:
-
Consumes: Task 2's sections and
_provided. -
Produces:
-
class Componentas 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 whethererror, its__cause__or__context__, or a member of an exception group's.exceptions, at any depth, is akind, because FastMCP may wrap a lifespan's error. -
Unmarkedis a module-levelConfigsubclass with no@config. -
TokenVerifiercomes fromkubed.mcp.auth, andTestClientfromstarlette.testclient.Refusemay need the constructor arguments FastMCP 4.2'sTokenVerifiertakes: 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_Signalsand logs no TEL-20 line yet: Task 5 adds it. -
_Loaded.boot_line._loadbuilds it unconditionally and stops logging. -
app.py:-
__init__validatescomponents, builds_builtin_components(name), and passes the component sections to_load; - it builds
partsfromloaded.provided, and gives_with_teardownthe parts, the boot line andon_enter=self._serving_starts; - it calls each part's
registerlast; -
_with_teardownruns design item 3's steps, using_start_alland_stop_all, and logs the boot line onlogging.getLogger("kubed.mcp.config"); -
authis as item 7 says, andrun()marks serving as started before it reads serving.
-
-
tests/test_telemetry.py's direct_with_teardowntest usesparts=[(_TelemetryComponent("t"), TelemetrySettings(profiles=ADDRESS))],boot_line="config: all defaults"andon_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"Files:
- Modify:
kubed/mcp/_config.py:-
_compose(sources, *, hooked=frozenset()), and_itemsand_check_namesskip the hooked keys' names; -
_load(..., hooks=None); -
config_schema(*sections, hooked=()); -
_Schemaleaves outenvandargon 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'sValueErrorwithwhatas"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_namesskipping; - in
_load:- the hooked items are left out of
_read_envand_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
hooklayer put on top; -
boot_lineis built last;
- the hooked items are left out of
-
config_schema(hooked=), and_Schema, which is given the hooked sections' classes, for example through a subclass made per call; -
QuickMCP'shooks=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"Files:
- Modify:
kubed/mcp/telemetry.py: new_start_lineand_where. - Modify:
kubed/mcp/_builtins.py:_TelemetryComponent.startlogs the line. - Test:
tests/test_telemetry.py, section# -- the start line, and the order test intests/test_components.py.
Interfaces:
-
Consumes: Task 3's
_TelemetryComponent, and_Signals'_profilesand_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"Files:
- Modify (wiki, branch
issue-49):-
docs/superpowers/specs/components.md,app.md,config.md,telemetry.md,delivery.mdandfacade.md; -
docs/superpowers/plans/2026-11-25-config-design.md's History, and this file's History.
-
- Modify:
README.md,CHANGELOG.md([Unreleased]), then thedocspointer.
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, withsection,register(mcp, section),start(section)andstop(), all optional. A server passesQuickMCP(components=[...]), and the section is the loaded instance of the class that won the key. -
CMP-3: the order of design item 3:
-
registerat 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 andconfig=values aren't read. The hook returns an instance of the class holding the key, which is validated, and its items recordhook. 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 restatesField(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 inregisterand closes it instop. It states no rule the rows don't. -
CMP-2:
-
Step 2: App.
-
APP-2: the signature of design item 2. Add: "
mcp.authis the server's auth provider. It may be set after construction, by the server or a component'sregister, until serving starts. Setting it after that is aRuntimeError." -
APP-3 gains: "
componentsare the server's components (CMP-2), andhookssupply built-ins' sections (CMP-6)." - APP-5: the lifespan order of design item 3.
-
APP-7: "
run()reads theservingsection (CMP-4):transport,host,portandlog_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 callslogging.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 thefastmcplogger, undoing APP-9."
-
APP-2: the signature of design item 2. Add: "
-
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
telemetrysection (CMP-4),TelemetrySettings, is registered in every server, andQuickMCPreads no attribute; - the table gains env and flag columns, and
profilesisSecretStr | None; - a server's subclass under
telemetryreplaces it; - code reads it as
Inject[TelemetrySettings].
- the built-in
- 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: offcase. - TEL-18, TEL-19 and TEL-21 keep (proposed).
-
DLV-4: the built-in
deliverysection (DeliverySettings, CMP-4) gives each input's default:resources,listed(a comma string) andvia, fromDELIVERY_*or the--delivery-*flags. The rest stays: a value its input doesn't take is dropped with one warning whenQuickMCPis built, namingconfig delivery.<attribute>.Deliveryis the partial typedelivery_defaultanswers with. -
FAC-11: the eager names are
Component,Config,DeliverySettings,Field,NoDecode,ServingSettings,Source,TelemetrySettings,configandconfig_schema. The last sentence nameskubed.mcp.componentsand the built-ins' module beside telemetry and the config module.
-
TEL-2:
-
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
Settingsand theConfigandconfigimports. Its server line ismcp = QuickMCP("grid", argv=sys.argv[1:]), andmcp.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.### Addedgains:
- **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"These pages describe what is on main; the spec says what is built and what is only proposed.
kubed-mcp · MIT