Skip to content

2026 11 24 telemetry profiles

kubed-io[bot] edited this page Nov 24, 2026 · 1 revision

Telemetry, piece 1: profiles to Pyroscope — Implementation Plan

History. Plan of record for #13, built in #25. What it builds is in the living spec: telemetry (TEL-1 to TEL-10), facade (FAC-1, FAC-2) and package (PKG-22, pyroscope-io only). The design and its rulings are 2026-11-24-telemetry-design. Overtaken: nothing yet.

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

Goal: A QuickMCP server whose config has a telemetry section with profiles set pushes CPU and memory profiles to Pyroscope for the life of its lifespan. A server without one starts, serves and imports exactly as today.

Architecture: A new module, kubed/mcp/telemetry.py, holds the Telemetry protocol, the TelemetrySettings model and the start/stop logic. QuickMCP.__init__ reads getattr(config, "telemetry", None) and hands it to _with_teardown, which starts the signals on entry, before the server's own lifespan, and stops them in its finally, before container.aclose(). A module-level slot makes the first start in a process the owner. pyroscope is imported only on the path that starts profiles.

Tech Stack: Python 3.11 to 3.14, FastMCP 4, pydantic 2 (through FastMCP, as prompts.py, agents.py and skills.py already use it), pyroscope-io>=1.2,<2, pytest with asyncio_mode = "auto".

Spec: telemetry TEL-1 to TEL-10, approved by Dr K on #13. There was no draft spec on the branch; this plan argues from the living spec and the design above, and the calls in "Settled here" below.

Settled here

The design left these to the builder. Dr K agreed the first four on #13; the rest are mine, from the code and the SDK.

  1. Start and stop sit in _with_teardown, not run(): entry starts, before the server's lifespan; the finally stops, before container.aclose(). That is TEL-5's order against APP-5, and it holds on stdio, HTTP and an in-memory Client alike.
  2. The owner is a start, not a server. _start_signals returns a handle only to the call that started something; any later call while it runs gets None and stops nothing. Stopping clears the slot, so a server restarted after its owner stopped starts its profiles again.
  3. TelemetrySettings and Telemetry are both exported from kubed.mcp, by symmetry with Serving. TelemetrySettings is a pydantic BaseModel, not BaseSettings (TEL-3).
  4. CI installs the extra, and the tests use a fake pyroscope in sys.modules, plus one check of every keyword we pass against the real configure().
  5. The floor is pyroscope-io>=1.2. grafana/pyroscope-python's release 1.2.0 (2026-07-24) is the one with "memory profiler based on dd-trace-py" (grafana/pyroscope-python#83) and "allow memory-only profiling". 1.4.0 is current. configure() is a plain Python def and takes application_name, server_address, tags, mem_enabled and cpu_enabled by keyword, so inspect.signature works on it.
  6. pydantic is not declared. PKG-9 lists the runtime dependencies exactly, and three modules already import pydantic through FastMCP.
  7. An empty string is unset. profiles="", and an empty POD_NAMESPACE, POD_NAME or OTEL_SERVICE_NAME, count as not set: an environment-mapped config yields "" for a variable that is defined but blank.
  8. Log lines never carry the address. It may hold credentials (https://user:token@…).

Global Constraints

  • Every new module starts with from __future__ import annotations; every public name is annotated.
  • kubed/ gets no __init__.py.
  • pyroscope is never imported at module level, anywhere in kubed/.
  • Each broad except Exception carries # noqa: BLE001 and a reason.
  • Logger: logging.getLogger(__name__), so kubed.mcp.telemetry, as plugins.py and skills.py do.
  • No per-call labels: no tag_wrapper, no add_thread_tag (TEL-10). oncpu and every other configure() argument stay at the SDK's defaults (TEL-8).
  • Test hostnames are *.example.com. No homelab hostname anywhere.
  • otel is a field and nothing reads it: OpenTelemetry is piece 2 (#14).
  • PKG-22 keeps (proposed): #14 and #15 add their packages and the last of them drops the tag.
  • Wiki changes are commits in docs/ on the wiki branch issue-13, pushed, then the docs pointer committed here. Never the wiki's master.
  • Checks, every task: ruff check ., ruff format --check ., pytest, after pip install -e '.[test,tasks,telemetry]'.

Review Focus

  1. profiles="" (an env var defined but blank): profiles stay off and nothing is imported. Test in Task 2.
  2. Two clients on one server at once (FastMCP may enter the lifespan per client): configure once, shutdown once by the end, never a second profiler. Test in Task 2.
  3. A restart after the owner stopped: the next lifespan starts profiles again, with its own settings. Test in Task 2.
  4. An address with credentials that fails to start: the error is logged and the address is not in the record's message. Test in Task 2.
  5. POD_NAMESPACE set but empty: no namespace="" label. Test in Task 3.

Task 1: The telemetry extra and the settings

Files:

  • Create: kubed/mcp/telemetry.py
  • Modify: kubed/mcp/__init__.py (import and __all__)
  • Modify: pyproject.toml ([project.optional-dependencies])
  • Modify: .github/workflows/test.yml:72 (the Install step)
  • Modify: tests/test_facade.py:88 (OWN["kubed.mcp"])
  • Modify (wiki): docs/superpowers/specs/facade.md FAC-1 and FAC-2
  • Test: tests/test_telemetry.py

Interfaces:

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

    • class Telemetry(Protocol) with read-only properties profiles -> str | None, profile_cpu -> bool, profile_memory -> bool, otel -> bool, tags -> dict[str, str], written as Serving is in app.py.
    • class TelemetrySettings(BaseModel): profiles: str | None = None, profile_cpu: bool = True, profile_memory: bool = True, otel: bool = False, tags: dict[str, str] = Field(default_factory=dict).
    • Both re-exported from kubed.mcp.
  • Step 1: Write the failing tests in a new tests/test_telemetry.py

def test_settings_default_to_every_signal_off() -> None:
    settings = TelemetrySettings()
    assert settings.profiles is None
    assert settings.profile_cpu is True
    assert settings.profile_memory is True
    assert settings.otel is False
    assert settings.tags == {}


def test_settings_embed_as_a_configs_telemetry_section() -> None:
    class Config(BaseModel):
        telemetry: TelemetrySettings = TelemetrySettings()

    config = Config.model_validate(
        {"telemetry": {"profiles": "http://pyroscope.example.com:4040", "tags": {"team": "a"}}}
    )
    assert config.telemetry.profiles == "http://pyroscope.example.com:4040"
    assert config.telemetry.tags == {"team": "a"}
    assert Config().telemetry.tags is not Config().telemetry.tags

And in tests/test_facade.py: OWN["kubed.mcp"] = {"Inject", "QuickMCP", "Serving", "Telemetry", "TelemetrySettings", "lookup"}.

  • Step 2: Run them to see them fail

Run: pytest tests/test_telemetry.py tests/test_facade.py -v Expected: FAIL, ImportError: cannot import name 'TelemetrySettings' and the __all__ mismatch.

  • Step 3: Implement Telemetry and TelemetrySettings in kubed/mcp/telemetry.py

Module docstring: why the module exists (what a server reports about itself, off until its config says, nothing imported until a signal is on). Docstrings on both classes for an integrator: what each field switches. Import Telemetry and TelemetrySettings in kubed/mcp/__init__.py from .telemetry and add both to __all__ in sorted order.

  • Step 4: Add the extra and install it in CI

pyproject.toml, after tasks:

# Telemetry (the telemetry area of the spec), installed by servers' images only.
# pyroscope-io's floor is the first release with memory profiling (mem_enabled), 1.2.0.
telemetry = [
  "pyroscope-io>=1.2,<2",
]

.github/workflows/test.yml, the Install step: run: pip install .[test,tasks,telemetry].

As built: the code agent can't write workflow files, so the test extra pulls in kubed-mcp[telemetry] and the workflow's pip install .[test,tasks] installs pyroscope-io as it is.

  • Step 5: Edit FAC-1 and FAC-2 in the wiki

FAC-1 gains: "Telemetry and TelemetrySettings are the telemetry area's." FAC-2's kubed.mcp row gains Telemetry, TelemetrySettings after Serving.

  • Step 6: Run the checks

Run: pip install -e '.[test,tasks,telemetry]' && ruff check . && ruff format --check . && pytest Expected: all pass; the two new tests and both facade tests PASS.

  • Step 7: Commit

In docs/ on wiki branch issue-13: git add superpowers/specs/facade.md && git commit -m "facade: export Telemetry and TelemetrySettings (#25)", push. Then here:

git add kubed/mcp/telemetry.py kubed/mcp/__init__.py pyproject.toml .github/workflows/test.yml tests/test_telemetry.py tests/test_facade.py docs
git commit -m "Add the telemetry extra, Telemetry and TelemetrySettings"

Task 2: Profiles start and stop with the server

TEL-2, TEL-4, TEL-5, TEL-6, and TEL-8's "both off starts nothing".

Files:

  • Modify: kubed/mcp/telemetry.py
  • Modify: kubed/mcp/app.py:64-81 (_with_teardown) and :105-107 (QuickMCP.__init__)
  • Test: tests/test_telemetry.py

Interfaces:

  • Consumes: Telemetry, TelemetrySettings (Task 1).

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

    • _running: _Signals | None = None, the process's slot.
    • class _Signals with stop(self) -> None: calls pyroscope.shutdown() on the module it holds, logs and swallows anything it raises (log.exception("Profiles did not stop cleanly")), and clears _running in a finally. It never raises.
    • _start_signals(name: str, settings: Telemetry | None) -> _Signals | None: None when _running is set, when settings is None, or when nothing started. Otherwise it sets _running and returns it. It never raises.
    • _start_profiles(name: str, settings: Telemetry) -> ModuleType | None: the pyroscope module it configured, or None. Off (not settings.profiles, or both switches off): returns before any import. ModuleNotFoundError on import pyroscope: one log.warning("Profiles are on, but pyroscope-io is not installed: install kubed-mcp[telemetry]"). Anything else, from the import or configure: log.exception("Profiles did not start; serving without them"). This task calls pyroscope.configure(application_name=name, server_address=settings.profiles, cpu_enabled=settings.profile_cpu, mem_enabled=settings.profile_memory, tags=dict(settings.tags)); Task 3 replaces the name and the tags.
    • _with_teardown(container, lifespan, *, name: str, telemetry: Telemetry | None); QuickMCP passes name=name, telemetry=getattr(config, "telemetry", None).
  • Step 1: Write the test fixtures

In tests/test_telemetry.py: a module EVENTS: list[str]; an autouse fixture that clears it, monkeypatch.setattr(kubed.mcp.telemetry, "_running", None) and monkeypatch.delenv of OTEL_SERVICE_NAME, POD_NAMESPACE and POD_NAME (raising=False); a pyroscope fixture that puts a types.ModuleType("pyroscope") in sys.modules with monkeypatch.setitem, whose configure(**kwargs) appends kwargs to a list it returns and "profiles started" to EVENTS, and whose shutdown() appends "profiles stopped"; a dataclass Config with transport, host, port (defaults "http", "0.0.0.0", 8000) and telemetry: object = None; and served(name, telemetry, **options) -> QuickMCP that builds QuickMCP(name, config=Config(telemetry=telemetry), **options) with a Monitor singleton whose context manager appends "monitor stopped" on exit, and one tool, ping(monitor: Inject[Monitor]) -> str, returning "pong". The monitor is built only when ping is called, so a test that asserts "monitor stopped" calls ping. Use ADDRESS = "http://pyroscope.example.com:4040".

  • Step 2: Write the failing tests
async def test_profiles_start_before_the_lifespan_and_stop_before_the_container(pyroscope) -> None:
    @asynccontextmanager
    async def lifespan(server):
        EVENTS.append("lifespan up")
        yield {}
        EVENTS.append("lifespan down")

    mcp = served("profiled", TelemetrySettings(profiles=ADDRESS), lifespan=lifespan)
    async with Client(mcp.server) as client:
        assert (await client.call_tool("ping", {})).data == "pong"
    assert pyroscope == [
        {"application_name": "profiled", "server_address": ADDRESS,
         "cpu_enabled": True, "mem_enabled": True, "tags": {}}
    ]
    assert EVENTS[:2] == ["profiles started", "lifespan up"]
    assert EVENTS[-3:] == ["lifespan down", "profiles stopped", "monitor stopped"]


async def test_profiles_stop_when_the_lifespan_fails(pyroscope) -> None:
    # Through _with_teardown directly, so the error is the lifespan's own.
    @asynccontextmanager
    async def lifespan(server):
        EVENTS.append("lifespan up")
        raise RuntimeError("boom")
        yield

    run = _with_teardown(Container(), lifespan, name="t", telemetry=TelemetrySettings(profiles=ADDRESS))
    with pytest.raises(RuntimeError, match="boom"):
        async with run(FastMCP("t")):
            pass
    assert EVENTS == ["profiles started", "lifespan up", "profiles stopped"]


@pytest.mark.parametrize("telemetry", [None, TelemetrySettings(), TelemetrySettings(profiles=""),
    TelemetrySettings(profiles=ADDRESS, profile_cpu=False, profile_memory=False)])
async def test_profiles_off_import_nothing(monkeypatch, telemetry) -> None:
    monkeypatch.delitem(sys.modules, "pyroscope", raising=False)
    async with Client(served("off", telemetry).server) as client:
        await client.call_tool("ping", {})
    assert "pyroscope" not in sys.modules


async def test_a_config_without_telemetry_imports_nothing(monkeypatch) -> None:
    # A Serving with no telemetry attribute at all, as both servers' configs are today.
    monkeypatch.delitem(sys.modules, "pyroscope", raising=False)
    mcp = QuickMCP("plain", config=argparse.Namespace(transport="http", host="0.0.0.0", port=8000))
    async with Client(mcp.server):
        pass
    assert "pyroscope" not in sys.modules


def test_importing_kubed_mcp_imports_no_pyroscope() -> None:
    out = subprocess.run(
        [sys.executable, "-I", "-c", "import sys, kubed.mcp; print('pyroscope' in sys.modules)"],
        capture_output=True, text=True, check=True,
    )
    assert out.stdout.strip() == "False"


async def test_a_missing_package_is_one_warning_and_the_server_serves(monkeypatch, caplog) -> None:
    monkeypatch.setitem(sys.modules, "pyroscope", None)
    async with Client(served("missing", TelemetrySettings(profiles=ADDRESS)).server) as client:
        assert (await client.call_tool("ping", {})).data == "pong"
    warnings = [r for r in caplog.records if r.name == "kubed.mcp.telemetry"]
    assert [r.levelno for r in warnings] == [logging.WARNING]
    assert "kubed-mcp[telemetry]" in warnings[0].getMessage()


async def test_a_profiler_that_fails_to_start_is_logged_and_the_server_serves(pyroscope, monkeypatch, caplog) -> None:
    secret = "https://user:s3cret@pyroscope.example.com"

    def refuse(**kwargs):
        raise RuntimeError("agent refused")

    monkeypatch.setattr(sys.modules["pyroscope"], "configure", refuse)
    async with Client(served("failing", TelemetrySettings(profiles=secret)).server) as client:
        assert (await client.call_tool("ping", {})).data == "pong"
    errors = [r for r in caplog.records if r.name == "kubed.mcp.telemetry"]
    assert [r.levelno for r in errors] == [logging.ERROR]
    assert "s3cret" not in errors[0].getMessage()
    assert "profiles stopped" not in EVENTS


async def test_a_profiler_that_fails_to_stop_still_closes_the_container(pyroscope, monkeypatch, caplog) -> None:
    def refuse() -> None:
        raise RuntimeError("agent stuck")

    monkeypatch.setattr(sys.modules["pyroscope"], "shutdown", refuse)
    async with Client(served("stuck", TelemetrySettings(profiles=ADDRESS)).server) as client:
        await client.call_tool("ping", {})
    assert EVENTS[-1] == "monitor stopped"
    assert [r.levelno for r in caplog.records if r.name == "kubed.mcp.telemetry"] == [logging.ERROR]


async def test_the_first_server_owns_the_profiles(pyroscope) -> None:
    first = served("first", TelemetrySettings(profiles="http://a.example.com"))
    second = served("second", TelemetrySettings(profiles="http://b.example.com"))
    async with Client(first.server):
        async with Client(second.server):
            pass
        assert EVENTS.count("profiles stopped") == 0
    assert [c["server_address"] for c in pyroscope] == ["http://a.example.com"]
    assert EVENTS.count("profiles stopped") == 1


async def test_two_clients_on_one_server_start_one_profiler(pyroscope) -> None:
    mcp = served("shared", TelemetrySettings(profiles=ADDRESS))
    async with Client(mcp.server), Client(mcp.server):
        pass
    assert len(pyroscope) == 1
    assert EVENTS.count("profiles stopped") == 1


async def test_profiles_start_again_once_the_owner_has_stopped(pyroscope) -> None:
    async with Client(served("first", TelemetrySettings(profiles="http://a.example.com")).server):
        pass
    async with Client(served("second", TelemetrySettings(profiles="http://b.example.com")).server):
        pass
    assert [c["server_address"] for c in pyroscope] == ["http://a.example.com", "http://b.example.com"]


async def test_a_servers_own_section_satisfies_telemetry(pyroscope) -> None:
    section = argparse.Namespace(profiles=ADDRESS, profile_cpu=True, profile_memory=False, otel=False, tags={})
    async with Client(served("own", section).server):
        pass
    assert pyroscope[0]["mem_enabled"] is False
  • Step 3: Run them to see them fail

Run: pytest tests/test_telemetry.py -v Expected: FAIL; _with_teardown() got an unexpected keyword argument 'name', and no configure call.

  • Step 4: Implement _start_signals, _start_profiles and _Signals in kubed/mcp/telemetry.py, and wire _with_teardown

In _with_teardown's run, signals = _start_signals(name, telemetry) comes first, before the try; the finally calls signals.stop() when it is not None, then await container.aclose(). _start_signals wraps its whole body in one except Exception (# noqa: BLE001: TEL-6, telemetry never stops a server), so a server's own section that lacks an attribute is a logged error, not a failed start. pyroscope.shutdown() is synchronous and is called directly: it runs once, at shutdown.

  • Step 5: Run the tests

Run: pytest tests/test_telemetry.py tests/test_app.py -v Expected: PASS, and every existing test_app.py lifespan test unchanged.

  • Step 6: Run the checks

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

  • Step 7: Commit
git add kubed/mcp/telemetry.py kubed/mcp/app.py tests/test_telemetry.py
git commit -m "Start profiles before a server's lifespan and stop them after it"

Task 3: What profiles are named and labelled

TEL-7, TEL-8's switches, TEL-9, TEL-10; then the spec loses its tags and the changelog gains its line.

Files:

  • Modify: kubed/mcp/telemetry.py (_start_profiles)
  • Modify: CHANGELOG.md ([Unreleased] → ### Added)
  • Modify (wiki): docs/superpowers/specs/telemetry.md, docs/superpowers/plans/2026-11-24-telemetry-design.md (History)
  • Test: tests/test_telemetry.py

Interfaces:

  • Consumes: _start_profiles, the pyroscope fixture and served() (Task 2).

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

    • _service_name(name: str) -> str: os.environ.get("OTEL_SERVICE_NAME") or name.
    • _profile_tags(tags: Mapping[str, str]) -> dict[str, str]: namespace from POD_NAMESPACE and pod from POD_NAME, each only when non-empty, then updated by tags.
    • _start_profiles passes application_name=_service_name(name) and tags=_profile_tags(settings.tags). No other keyword is added.
  • Step 1: Write the failing tests

async def test_otel_service_name_names_the_profiles(pyroscope, monkeypatch) -> None:
    monkeypatch.setenv("OTEL_SERVICE_NAME", "selenium-flow")
    async with Client(served("built-name", TelemetrySettings(profiles=ADDRESS)).server):
        pass
    assert pyroscope[0]["application_name"] == "selenium-flow"


async def test_profiles_carry_the_pod_and_tags_win(pyroscope, monkeypatch) -> None:
    monkeypatch.setenv("POD_NAMESPACE", "tools")
    monkeypatch.setenv("POD_NAME", "sf-0")
    settings = TelemetrySettings(profiles=ADDRESS, tags={"pod": "pinned", "team": "a"})
    async with Client(served("labelled", settings).server):
        pass
    assert pyroscope[0]["tags"] == {"namespace": "tools", "pod": "pinned", "team": "a"}


async def test_an_empty_pod_variable_adds_no_label(pyroscope, monkeypatch) -> None:
    monkeypatch.setenv("POD_NAMESPACE", "")
    monkeypatch.setenv("POD_NAME", "sf-0")
    async with Client(served("blank", TelemetrySettings(profiles=ADDRESS)).server):
        pass
    assert pyroscope[0]["tags"] == {"pod": "sf-0"}


@pytest.mark.parametrize(("cpu", "memory"), [(True, False), (False, True)])
async def test_cpu_and_memory_switch_independently(pyroscope, cpu, memory) -> None:
    settings = TelemetrySettings(profiles=ADDRESS, profile_cpu=cpu, profile_memory=memory)
    async with Client(served("switched", settings).server):
        pass
    assert (pyroscope[0]["cpu_enabled"], pyroscope[0]["mem_enabled"]) == (cpu, memory)


async def test_every_keyword_passed_is_one_configure_takes(request) -> None:
    # A real import: CI installs the extra, so there it must not skip.
    real = importlib.import_module("pyroscope") if os.environ.get("CI") else pytest.importorskip("pyroscope")
    configure = inspect.signature(real.configure)
    calls = request.getfixturevalue("pyroscope")  # the fake goes in only after the real import
    settings = TelemetrySettings(profiles=ADDRESS, tags={"team": "a"})
    async with Client(served("checked", settings).server):
        pass
    assert set(calls[0]) <= set(configure.parameters)
    assert set(calls[0]) == {"application_name", "server_address", "cpu_enabled", "mem_enabled", "tags"}
  • Step 2: Run them to see them fail

Run: pytest tests/test_telemetry.py -v -k "service_name or pod or switch or keyword" Expected: FAIL on the service name and the tags; the switch and keyword tests already PASS.

  • Step 3: Implement _service_name and _profile_tags, and use them in _start_profiles

  • Step 4: Check the floor

Run: pip install 'pyroscope-io==1.2.0' && pytest tests/test_telemetry.py -k keyword -v && pip install -e '.[test,tasks,telemetry]' Expected: PASS on 1.2.0, then 1.4.x reinstalled. If 1.2.0 lacks a keyword, raise the floor in pyproject.toml and its comment to the first release that passes, and say so in the PR.

  • Step 5: The spec and the changelog

  • telemetry.md: TEL-1 to TEL-10 lose (proposed). TEL-11 to TEL-17 keep it.

  • 2026-11-24-telemetry-design.md History: "TEL-1 to TEL-10 shipped in #25; TEL-11 to TEL-17 and PKG-22 are still proposed."

  • package.md: PKG-22 unchanged.

  • CHANGELOG.md, [Unreleased] → ### Added, after the existing lines: - **\kubed-mcp[telemetry]` and `TelemetrySettings`:** set `telemetry.profiles` to push CPU and memory profiles to Pyroscope.`

  • Step 6: Run the checks

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

  • Step 7: Commit

In docs/ on wiki branch issue-13: commit both wiki files ("telemetry: TEL-1 to TEL-10 built (#25)"), push. Then here:

git add kubed/mcp/telemetry.py tests/test_telemetry.py CHANGELOG.md docs
git commit -m "Name profiles after the service and label them with the pod"

Clone this wiki locally