Skip to content

components

kubed-io[bot] edited this page Nov 27, 2026 · 6 revisions

Components

The parts of a server that join its lifecycle. A component contributes a config section, registers its objects in the container, and starts and stops with the server. quick-mcp's own features (serving, telemetry, delivery) are components, and a server adds its own the same way. The container provides everything common, and a server adds itself by implementing the interface that gets injected. The design is 2026-11-25-config-design.

Use cases

  • A server gets serving, telemetry and delivery without wiring them. Each is in its config whether the server uses it or not, and switching one off is a config value.
  • A server adds a component of its own, such as a backend client. The component gets its own section and its own place in startup and shutdown.
  • A server that already holds its own run settings hands them to a built-in in code, so the built-in's env vars and file keys aren't read.

Neighbours

CMP-1. The config sections a component registers are config's (CFG). The container's recipes and lifetimes are the container's (DI). The lifespan components start and stop in is the app's (APP-5).

The interface

CMP-2. A component is an instance of kubed.mcp.Component, which has four members, each optional and doing nothing until overridden:

  • section, a class attribute: a section class carrying its own @config(key) (CFG-2), or None for no section;
  • register(mcp, section), which may add tools, middleware, routes, container recipes or mcp.auth (APP-2);
  • async start(section);
  • async stop().

A server passes its components as QuickMCP(components=[...]), or as load_config(components=[...]) for QuickMCP(loaded=...) (CFG-18). A component's section is composed into the config as sections= are, so a section without its own @config is CFG-2's TypeError and two components naming one key follow CFG-3. The section each method is given is the loaded instance of the class that won the key, a server's subclass included, and None when the component names none. Anything in components that isn't a Component instance, a Component subclass itself included, is a TypeError.

CMP-3. The components join the server's life in this order:

  • each register runs once, at the end of QuickMCP(...), after the config loads (CFG-11), the built-ins' first and then the server's in the order given;
  • at each lifespan entry, after the config's boot line is logged (CFG-11), each start runs in the same order, before the server's own lifespan (APP-5);
  • when that entry exits, after the server's own lifespan, the started components stop in reverse;
  • every stop runs: one that raises an Exception is logged at error on kubed.mcp.components by the component's class and the error's type, never its text, and isn't raised: BackendComponent did not stop cleanly: RuntimeError. Anything else, a cancellation, is raised once every stop has run;
  • a start that raises stops the components already started, in reverse, and fails the boot with its error. The one that raised isn't stopped, and the server's own lifespan doesn't run;
  • the container closes last (DI-10), also when a start fails.

A component's start decides from its section whether it does anything. Entries may overlap: two lifespan entries racing at start-up each run every start before either runs a stop. So a start may run again before the earlier entry's stop, and a component keeps no single-slot state it can't share.

Built-ins

CMP-4. Every server has three built-ins, registered and started before any component of the server's, each with its section in the config and the schema (their fields are in The built-ins' settings):

  • serving at the key serving, ServingSettings: transport, host, port, log level and the graceful timeout, which run() reads (APP-7);
  • telemetry at the key telemetry, TelemetrySettings: TEL's settings and signals (TEL-2);
  • delivery at the key delivery, DeliverySettings: the config's defaults that DLV's resolver reads (DLV-4).

A built-in that's switched off is still registered, and its section is still in the config and the schema. A server changes a built-in by subclassing its class under the same key (CFG-3). The built-ins' keys are taken: a server's own section at serving, telemetry or delivery that doesn't subclass the built-in's class is CFG-3's ValueError, the section 'serving' is claimed by both ServingSettings and Mine; one must subclass the other. Their env names and flags are taken too: a server's own item that declares one, such as PORT, is CFG-7's ValueError naming both items, unless that built-in is hooked (CMP-6). The error says so: The env var 'PORT' is declared by both port and serving.port; to keep your own, hook the built-in: hooks={'serving': ...}. A clash between two of the server's own items has no such hint.

CMP-5. QuickMCP never finds a section by attribute name on a server's object. Every section it reads, it reads through registration (CFG-3).

The escape hatch

CMP-6. A server supplies a built-in's section from its own config with QuickMCP(hooks={"serving": fn}). The keys of hooks are built-ins' keys, serving, telemetry or delivery: any other is a ValueError, and a hooks that isn't a mapping, or a value that isn't callable, is a TypeError.

  • A hooked section's file entries, env vars, flags and config= values aren't read. Its env vars are ignored, its flags are unknown flags (CFG-14), and its entries in the file and in config= are dropped. So it loads at its defaults, and a hooked section's every field needs a default.
  • Once the config validates, each hook is called with it, in the order serving, telemetry, delivery. It returns an instance of the class holding the key, the server's subclass when one replaces the built-in, and anything else is a TypeError. A hook that raises propagates as it is.
  • The instance is validated as its class. A field it doesn't hold, or a value its class refuses, is a load error naming (hook), serving.port (hook): Field required, reported with the others in one ValueError (CFG-14). The whole config is then validated again with each hooked section in place, so the root's validators see it.
  • Its items record hook (CFG-12).
  • A hooked section's env names and flags are out of the clash check (CFG-7), so a server's own PORT doesn't clash with a hooked serving.
  • A hooked section's class is still checked when the config is composed (the subclass rule, CFG-3), so a subclass that drops a field's env or arg is refused whether it's hooked or not.

config_schema(hooked=["serving"]) composes the same way (CFG-15). Without a hook, the built-in's registered section is used.

The built-ins' settings

Each field's env var and flag are used exactly as written (CFG-7).

serving, ServingSettings:

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
graceful_timeout float, >= 0 15 GRACEFUL_TIMEOUT --graceful-timeout

The transports are the ones FastMCP's run takes. The level is read case-insensitively, a subclass's restated log_level included, so LOG_LEVEL=info loads as INFO. The graceful timeout is the seconds in-flight HTTP requests get to finish when the server stops (APP-15): a stop by signal ends listen streams at once; a programmatic stop waits up to graceful_timeout for them. stdio doesn't read it. A subclass that changes a default restates Field(default, env=..., arg=...) on each field it changes, as host: str = Field("0.0.0.0", env="HOST", arg="--host"). pydantic drops a field's metadata when a subclass redefines it, so a bare host: str = "0.0.0.0" is refused when the config is composed (CFG-3): serving.host: redefines ServingSettings.host without its env='HOST' and arg='--host': restate Field(..., env='HOST', arg='--host') to keep them.

telemetry, TelemetrySettings:

Field Type Default env arg
profiles SecretStr | None None TELEMETRY_PROFILES --telemetry-profiles
profile_cpu bool True TELEMETRY_PROFILE_CPU --telemetry-profile-cpu
profile_memory bool True TELEMETRY_PROFILE_MEMORY --telemetry-profile-memory
otel bool False TELEMETRY_OTEL --telemetry-otel
tags dict[str, str] {} TELEMETRY_TAGS, a JSON object --telemetry-tags

delivery, DeliverySettings:

Field Type Default env arg
resources str | None None DELIVERY_RESOURCES --delivery-resources
listed str | None, a comma string None DELIVERY_LISTED --delivery-listed
via str | None None DELIVERY_VIA --delivery-via
max str | int | None, a whole number or all None DELIVERY_MAX --delivery-max

Writing a component

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

import logging
import sys

import httpx
from pydantic import BaseModel

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

log = logging.getLogger(__name__)


@config("backend")
class Backend(Config):
    url: str = Field(
        "https://backend.example.com", doc="The backend's address.", env="BACKEND_URL"
    )


class BackendComponent(Component):
    section = Backend

    def register(self, mcp: QuickMCP, section: BaseModel | None) -> None:
        assert isinstance(section, Backend)
        url = section.url
        mcp.singleton(httpx.AsyncClient, lambda: httpx.AsyncClient(base_url=url))

    async def start(self, section: BaseModel | None) -> None:
        assert isinstance(section, Backend)
        log.info("backend: %s", section.url)


mcp = QuickMCP("grid", components=[BackendComponent()], argv=sys.argv[1:])

A tool takes client: Inject[httpx.AsyncClient], and the operator sets BACKEND_URL. The container owns the client: it builds and enters it on first use (DI-4), closes it when serving ends and builds it again on first use after (DI-10), so the component needs no stop. register runs once, at construction, and start at each lifespan entry, so a start does only what is safe to repeat.

Clone this wiki locally