Skip to content

2026 11 26 telemetry reports itself

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

Telemetry reports itself: trace ids in log lines, an unreachable Pyroscope logged, resource reads in the call metrics: plan

History. Written 2026-11-26 for Dr K. It is the plan of record for #59 (Epic 5, #47), built in #60 on issue-59, which merges into issue-47. It builds telemetry TEL-18, TEL-19 and TEL-21 on top of the components' _TelemetryComponent, and rewords TEL-19 and touches TEL-16. Its merge is 0.4.0-rc.3. The epic's design is the why, and this plan doesn't replace it.

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: with otel on, a log line written inside a span shows its trace and span ids in its own text, and the call metrics record resources/read labelled by template. With profiles on, a Pyroscope that can't be reached is logged once, and so is its recovery.

Architecture: TEL-18 is a chained LogRecord factory in _otel.py, installed by the OpenTelemetry start and removed first by its stop. TEL-19 is a daemon thread in telemetry.py, started and stopped with the profiles signal. TEL-21 is a new module, _metrics.py, imported only when otel is on. It holds a UsageMiddleware subclass that adds on_read_resource, and an inner observer placed right after _TakeThePrefix. The observer hands the matched template out through a ContextVar holder.

Tech Stack: Python 3.11–3.14, FastMCP 4.2 (>=4.2,<5, researched on 4.2.6), OpenTelemetry SDK and opentelemetry-instrumentation-logging, pyroscope-io 1.4, stdlib urllib, pytest, ruff.

Spec: the issue's spec in #59's notes, ruled by the parent #47 at 12:10 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 4 writes the rows.

The design this settles

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

  • TEL-19 is the probe, with the row reworded; enable_logging and a relay are rejected;
  • TEL-21's attribute is mcp.resource.template;
  • TEL-18's text form is trace_id=<32 hex> span_id=<16 hex>.

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

TEL-18: the ids in the line's text

  1. The factory is _TraceText in kubed/mcp/_otel.py:

    • install() keeps logging.getLogRecordFactory() as the previous factory and sets its own. The bound method is stored once, so "still ours" is an is check.
    • Each record comes from the previous factory. When trace.get_current_span().get_span_context() is valid, the factory gives the record two things:
      • the text trace_id={trace_id:032x} span_id={span_id:016x}, as the record attribute _kubed_trace;
      • the class _TracedRecord, a logging.LogRecord subclass at module level.
    • Otherwise the record is returned untouched.
    • _TracedRecord.getMessage() is super().getMessage() with _kubed_trace appended, unless that text already contains it. So a QueueHandler, which bakes the formatted line into msg, never shows the ids twice, a traceback after them included (settled here; built as "contains", since "ends with" showed them twice for log.exception).
    • msg, args, every handler and every formatter are untouched, so a handler added later is covered too. TEL-15's otelTraceID and otelSpanID stay.
    • The class is swapped only for a record whose class is exactly logging.LogRecord. Another class's record is left as it is, because swapping it would drop its own getMessage (settled here). The ids are read when the record is made, so a line formatted later, on another thread, keeps the span it was written in.
    • _make never raises: a failure returns the record as the previous factory made it.
  2. Where it goes. _trace_text() -> _TraceText | None installs one and never raises. A failure is logged at error as "OpenTelemetry did not put the trace in log lines: %s", with the type's name. start calls it in two places:

    • someone else's SDK: after the _instrument_logging block, whatever that block returned;
    • our own SDK: after a successful initialize(), when the returned _Otel is built.

    The failed-initialize() path installs nothing. _Otel gains text: _TraceText | None = None.

  3. Stop. _Otel.stop removes the text first, before LoggingInstrumentor().uninstrument() (settled here). The instrumentor's uninstrument sets back the factory it found. That factory sits under ours, so removing ours afterwards would bring back the instrumentor's own factory. remove() puts the previous factory back only while logging.getLogRecordFactory() is still ours. Otherwise it becomes a pass-through for good. It never raises, and it's logged as _Otel.stop's other steps are.

  4. Docs (Task 4):

    • the TEL-18 row;
    • a formatter that reads record.msg raw doesn't show the ids;
    • the OTLP log body carries them too when OTEL_LOGS_EXPORTER exports;
    • an operator's Loki derived field is trace_id=(\w+).

TEL-19: Pyroscope unreachable, checked on the push interval

  1. Constants in kubed/mcp/telemetry.py:

    • _UPLOAD_INTERVAL = 10 (seconds), now passed explicitly as pyroscope.configure(..., upload_interval=_UPLOAD_INTERVAL);
    • _PROBE_TIMEOUT = 5.0 (seconds), under the interval.
  2. _Probe(address: str, *, interval: float = _UPLOAD_INTERVAL, timeout: float = _PROBE_TIMEOUT):

    • check() -> None runs one probe and logs a change. It never raises.
    • start() -> None starts a daemon threading.Thread named pyroscope-probe, never tied to the event loop. Its loop is check(), then self._stopping.wait(interval), until stopped, so the first probe runs at start.
    • stop() -> None sets the event and joins for at most timeout. It never raises.
  3. The request, built by _ready(address: str) -> tuple[str, str | None], which returns the URL and the Authorization header:

    • Scheme: an address without :// gets http:// (settled here).
    • Userinfo: split as TEL-20's _where splits it, at the last @ unless an @ follows a ? or #.
    • URL: the host and port, then the path with trailing slashes stripped, then /ready. The query and fragment are dropped, so https://u:p@host:4040/base/?t=x probes https://host:4040/base/ready.
    • Auth: userinfo user:password, each part urllib.parse.unquoted, is sent as Basic base64(user:password), as the agent sends it. With no userinfo there's no header.
    • The address is read with get_secret_value() only, in _start_signals.
    • The opener: urllib.request.build_opener(_NoRedirect). It honours the environment's proxies, as the agent's HTTP client does. _NoRedirect follows no redirect, so the credentials never reach another host, and a 3xx counts as reachable (settled here).
    • urllib.request is imported inside _Probe, so importing kubed.mcp doesn't load it.
  4. Classification, _outcome(address: str, timeout: float) -> str | None, where None is reachable. The kinds are exact copy (settled here):

    What happened Kind
    ConnectionRefusedError connection refused
    socket.gaierror DNS
    ssl.SSLError, a certificate error included TLS
    TimeoutError / socket.timeout timeout
    any other OSError or http.client.HTTPException connection error
    ValueError (a URL that won't parse) invalid address
    HTTP 401 or 403 auth (HTTP 401), auth (HTTP 403)
    HTTP 5xx server error (HTTP 503), with the code
    any other status, 2xx, 3xx and 404 included reachable
    any other Exception its type's __name__

    A URLError is classified by its reason when that's an exception. HTTPError is checked before URLError.

  5. The lines go on kubed.mcp.telemetry, with <host> from _where(address):

    • the first failure of a run: one warning, profiles: pyroscope at <host> unreachable: <kind>;
    • nothing more while it stays unreachable, whatever the kind;
    • the first success after that: one info line, profiles: pyroscope at <host> reachable again;
    • a success with no failure before it: nothing.

    No line shows an exception's text, a credential, the path or the query.

  6. Lifetime. _start_probe(address: str) -> _Probe | None builds and starts one, never raises, and is the tests' seam.

    • _start_signals calls it right after _start_profiles returns pyroscope. _start_profiles keeps returning the module (settled here).
    • _Signals(profiles, otel=None, probe=None) keeps it. _Signals.stop() stops the probe first, then OpenTelemetry, then profiles, each in its own try.
    • Profiles off, or profiles that didn't start, start no probe.
  7. The tests' guard. Every test that starts profiles with the fake pyroscope would otherwise probe a real host, such as pyroscope.example.com. So an autouse fixture in tests/conftest.py, no_probe, replaces kubed.mcp.telemetry._start_probe with lambda address: None. It does this unless the test carries the new marker probe, registered in pyproject.toml. Tests that build a _Probe directly don't need the marker.

TEL-21: resource reads in the call metrics

  1. kubed/mcp/_metrics.py (new) imports FastMCP, UsageMiddleware and _TakeThePrefix at module level. telemetry._call_metrics imports it lazily, only when otel is on. It holds:

    • _TEMPLATE = "mcp.resource.template";
    • _MATCHED: ContextVar[_Matched | None], where _Matched holds label: str | None = None.
  2. _CallMetrics(UsageMiddleware), built as _CallMetrics(user_id="omit"). _call_metrics returns it in place of the bare UsageMiddleware.

    • __init__ wraps self._duration (FastMCP 4.2.6's histogram) in _Labelled. If the private names it relies on (_duration, and _record on the class) aren't there, it logs one warning, "Resource reads are not in the call metrics: FastMCP's UsageMiddleware has changed", and reads pass straight through. Tools and prompts are then still recorded (settled here).
    • on_read_resource(context, call_next) sets a fresh _Matched in _MATCHED. It returns await self._record(context, call_next, method="resources/read", name_attribute=_TEMPLATE, name=""), and resets the var in a finally. So the attributes are UsageMiddleware's own: the transport, protocol and server name, error.type and rpc.status_code.
    • _Labelled.record(amount, attributes=None, *args, **kwargs) acts only when _TEMPLATE is in attributes. On a copy, it sets _TEMPLATE to the holder's label, or deletes it when there's no label, then forwards. UsageMiddleware pops the name on a routing error, so such a read never carries a label.
    • observe(server: FastMCP) -> None inserts _ReadObserver(server) into server.middleware right after the _TakeThePrefix instance, or appends it when there's none. It never raises.
  3. _ReadObserver(server), placed inside _PinScope and _TakeThePrefix, sees the plain URI under the request's pin. When _MATCHED holds no _Matched, it just calls call_next. Otherwise:

    • on success: the label is the uri_template of the template the URI matches, else the URI as the observer saw it;
    • when call_next raises an Exception: the label is that template's uri_template, else none, and it re-raises. A cancellation is passed through unlabelled.
    • the lookup is await server.get_resource_template(uri, version=...) only. The version is the request's, read from context.message's _meta as FastMCP's resources/read handler reads it, and None when it carries none. A lookup that raises gives no template.

    Why template-only (approved by Dr K with the plan): the spec offered get_resource(uri) and then get_resource_template(uri). A successful read that matches no template has already found a static resource, so a second static lookup decides nothing. That lookup isn't free either: for a skill's .md file, the plugin layer's _get_resource re-reads the file for its heading. Skipping it gives the same labels, with one exception: a static resource whose URI also matches a template is labelled by that template, and that series is still bounded. The TEL-21 row says so.

    FastMCP's span key was rejected too. A sampled-out span is non-recording and carries no attributes.

  4. Registration. _TelemetryComponent.register inserts the metrics at index 0, as today, then calls metrics.observe(mcp.server). Off, it imports nothing: neither _metrics nor FastMCP's usage module. tests/otel_child.py's HEAVY gains "kubed.mcp._metrics".

Global Constraints

  • from __future__ import annotations at the top of every module. kubed/ gets no __init__.py.
  • telemetry.py, _builtins.py and components.py stay FastMCP-free at module level, with the relative imports tests/test_facade.py allows today. _metrics.py and _otel.py are imported only when otel is on. Importing kubed.mcp still loads no FastMCP, and telemetry.py imports urllib.request only inside the probe.
  • No public name changes. rc.3 is a message to the servers, not an API change.
  • TEL-6 and CFG-13. Start, stop, the probe, the factory and the observer never raise into a server or a request. A failure is logged by its type's name, never its text. No line shows the profiles secret, its userinfo, path or query.
  • TEL-20's start line and the config's boot line stay as #49 left them.
  • Tests:
    • no network beyond localhost;
    • every test that builds a server passes environ= or config=;
    • a test that sets a log record factory, a root handler or a proxy variable puts it back;
    • the probe tests clear http_proxy, https_proxy, HTTP_PROXY, HTTPS_PROXY and no_proxy with monkeypatch.
  • Checks, as CI runs them (lint.yml, and test.yml after pip install -e .[test,tasks]): ruff check ., ruff format --check . and pytest.
  • The wiki. Edits are left in the docs/ checkout. The job commits them on the wiki branch issue-59, cut from the commit issue-47 pins (15572d9), and moves the pointer here. No git runs inside docs/, and the wiki's master is never pushed. Spec text is in the present tense, with no issue numbers.
  • .github/ isn't touched.

Review Focus

  1. A server that logs through a QueueHandler. The handler bakes getMessage() into msg, and the listener formats it again. The ids must show once (Task 1, test_a_queue_handler_shows_the_ids_once).
  2. A bare root logger. logging.lastResort prints %(message)s, so its line gains the ids, on the initialize() path too. The child tests that matched the bare inside line must match the new form (Task 1, test_otel_leaves_a_bare_root_logger_bare, test_the_real_configuration_exports_a_named_tagged_span).
  3. A Pyroscope address that redirects, such as a hosted endpoint sending /ready to a login page. The probe must not follow, so the basic auth never reaches the other host, and it counts the address as reachable (Task 2, test_a_redirect_is_reachable_and_not_followed).
  4. A Pyroscope address with a path and a trailing slash. http://u:p@127.0.0.1:<port>/base/?t=x must probe /base/ready, with no query (Task 2, test_the_probe_sends_basic_auth_and_shows_none_of_it).
  5. Reads that overlap. Two reads of two templates at once must each be labelled by their own template (Task 3, test_overlapping_reads_keep_their_own_templates).

Task 1: TEL-18, the trace ids in the line's text

Files:

  • Modify: kubed/mcp/_otel.py: new _TracedRecord, _TraceText and _trace_text; _Otel(text=); _Otel.stop removes the text first; start installs it in both paths.
  • Modify: tests/test_telemetry.py: a new section, # -- trace ids in the line (TEL-18), and the two child tests' assertions.

Interfaces:

  • Consumes: _instrument_logging, _Otel and start on issue-47.

  • Produces:

    • class _TracedRecord(logging.LogRecord);
    • class _TraceText with install(self) -> None and remove(self) -> None;
    • _trace_text() -> _TraceText | None;
    • _Otel(*, owned, logging_instrumented, link=None, text: _TraceText | None = None).
  • Step 1: Write the failing tests

Helpers in the section:

  • Lines(logging.Handler) keeps self.format(record) for each record.
  • as_json is a logging.Formatter subclass whose format returns json.dumps({"level": r.levelname, "message": r.getMessage()}).
  • Each test adds its handlers to root and removes them in a finally, as test_log_records_carry_the_trace_and_root_keeps_its_handlers does. A test that sets a factory puts the one it found back.
async def test_a_line_inside_a_span_ends_with_its_ids(traced, spans) -> None:
    text, data, keep = Lines(), Lines(), Keep()
    text.setFormatter(logging.Formatter("%(levelname)s %(message)s"))
    data.setFormatter(as_json())
    mcp = served("ids", TelemetrySettings(otel=True))

    @mcp.tool
    def log() -> str:
        logging.getLogger("tests.tool").warning("value %s", 5)
        return "logged"

    root = logging.getLogger()
    for handler in (text, data, keep):
        root.addHandler(handler)
    try:
        async with Client(mcp.server) as client:
            await client.call_tool("log", {})
            logging.getLogger("tests.tool").warning("outside")
    finally:
        for handler in (text, data, keep):
            root.removeHandler(handler)
        if LoggingInstrumentor().is_instrumented_by_opentelemetry:
            LoggingInstrumentor().uninstrument()
    (record,) = [r for r in keep.records if r.msg == "value %s"]
    ids = f" trace_id={record.otelTraceID} span_id={record.otelSpanID}"
    assert re.fullmatch(r" trace_id=[0-9a-f]{32} span_id=[0-9a-f]{16}", ids)
    (call,) = [s for s in spans.get_finished_spans() if s.name == "tools/call log"]
    assert record.otelTraceID == format(call.context.trace_id, "032x")
    assert f"WARNING value 5{ids}" in text.lines and "WARNING outside" in text.lines
    assert {"level": "WARNING", "message": f"value 5{ids}"} in [json.loads(x) for x in data.lines]
    assert {"level": "WARNING", "message": "outside"} in [json.loads(x) for x in data.lines]
    assert (record.msg, record.args) == ("value %s", (5,))


async def test_a_queue_handler_shows_the_ids_once(traced, spans) -> None:
    queued: queue.SimpleQueue = queue.SimpleQueue()
    handler = logging.handlers.QueueHandler(queued)
    mcp = served("queued", TelemetrySettings(otel=True))

    @mcp.tool
    def log() -> str:
        logging.getLogger("tests.tool").warning("queued %s", 1)
        return "logged"

    # handler on root, removed in finally, as above
    async with Client(mcp.server) as client:
        await client.call_tool("log", {})
    records = [r for r in iter_queue(queued) if r.getMessage().startswith("queued 1")]
    formatted = logging.Formatter("%(message)s").format(records[0])  # as a QueueListener's handler does
    assert formatted.count(" trace_id=") == 1
    assert re.fullmatch(r"queued 1 trace_id=[0-9a-f]{32} span_id=[0-9a-f]{16}", formatted)


def test_remove_puts_the_previous_factory_back(traced) -> None:
    before = logging.getLogRecordFactory()
    text = _TraceText()
    text.install()
    assert logging.getLogRecordFactory() is not before
    text.remove()
    assert logging.getLogRecordFactory() is before


def test_remove_after_another_factory_leaves_it_and_goes_quiet(traced) -> None:
    provider, _ = traced
    before = logging.getLogRecordFactory()
    text = _TraceText()
    text.install()
    ours = logging.getLogRecordFactory()
    other = lambda *a, **kw: ours(*a, **kw)  # noqa: E731
    logging.setLogRecordFactory(other)
    try:
        text.remove()
        assert logging.getLogRecordFactory() is other
        with provider.get_tracer("t").start_as_current_span("quiet"):
            record = logging.getLogger("tests").makeRecord("tests", logging.INFO, "f", 1, "m", (), None)
        assert record.getMessage() == "m"
    finally:
        logging.setLogRecordFactory(before)


async def test_otel_off_installs_no_factory(traced) -> None:
    provider, _ = traced
    before = logging.getLogRecordFactory()
    seen: list[object] = []
    mcp = served("no-ids", TelemetrySettings())

    @mcp.tool
    def look() -> str:
        seen.append(logging.getLogRecordFactory())
        with provider.get_tracer("t").start_as_current_span("own"):
            made = logging.getLogRecordFactory()("tests", logging.INFO, "f", 1, "m", (), None)
            seen.append(made.getMessage())
        return "ok"

    async with Client(mcp.server) as client:
        await client.call_tool("look", {})
    assert seen == [before, "m"]

iter_queue(q) drains a SimpleQueue with get_nowait() until it's empty. The existing test_log_records_carry_the_trace_and_root_keeps_its_handlers already asserts logging.getLogRecordFactory() is factory after the stop. It pins the end state, not design item 3's order: with remove()'s "still ours" check, either order ends on the factory the start found.

The child tests, which run the initialize() path:

  • test_the_real_configuration_exports_a_named_tagged_span: f"inside trace={trace_id}" becomes re.search(rf"^inside trace_id={trace_id} span_id=[0-9a-f]{{16}} trace={trace_id}$", out.stderr, re.M).

  • test_otel_leaves_a_bare_root_logger_bare: "inside" in out.stderr.splitlines() becomes any(re.fullmatch(r"inside trace_id=[0-9a-f]{32} span_id=[0-9a-f]{16}", line) for line in out.stderr.splitlines()).

  • Step 2: Run the tests to verify they fail

Run: pytest tests/test_telemetry.py -v -k "ids or factory or queue or bare or real_configuration" Expected:

  • the new tests fail on ImportError for _TraceText, or on the missing suffix;

  • the two child tests fail on the old line;

  • test_otel_off_installs_no_factory passes already.

  • Step 3: Implement design items 1 to 3 in kubed/mcp/_otel.py

The module docstring gains one sentence: inside a span, a record's message ends with its trace and span ids. _TraceText's docstring says why the stop removes it before the instrumentor.

  • Step 4: Run the tests to verify they pass

Run: pytest tests/test_telemetry.py -v Expected: PASS, the child tests and every TEL-15 test included.

  • Step 5: Checks and commit

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

git add kubed/mcp/_otel.py tests/test_telemetry.py
git commit -m "feat(telemetry): a log line inside a span ends with its trace_id and span_id"

Task 2: TEL-19, the Pyroscope probe

Files:

  • Modify: kubed/mcp/telemetry.py: _UPLOAD_INTERVAL, _PROBE_TIMEOUT, _ready, _outcome, _NoRedirect, _Probe and _start_probe; upload_interval= in _start_profiles; _Signals(probe=); _start_signals starts it.
  • Modify: tests/conftest.py: the autouse no_probe fixture.
  • Modify: pyproject.toml: the marker "probe: let the test start the real Pyroscope probe".
  • Test: tests/test_telemetry.py, section # -- the probe (TEL-19).

Interfaces:

  • Consumes: _where, _Signals, _start_signals and _start_profiles on issue-47.

  • Produces:

    • _UPLOAD_INTERVAL: int = 10 and _PROBE_TIMEOUT: float = 5.0;
    • _ready(address: str) -> tuple[str, str | None];
    • _outcome(address: str, timeout: float) -> str | None;
    • class _Probe with check(), start() and stop();
    • _start_probe(address: str) -> _Probe | None;
    • _Signals(profiles, otel=None, probe=None).
  • Step 1: Write the failing tests

Fixtures in the section:

  • stub: a http.server.ThreadingHTTPServer(("127.0.0.1", 0), ...) with daemon_threads = True, served on a daemon thread and shut down after the test. Its handler answers GET with the server's status attribute (default 200), plus Location: /elsewhere on a 3xx, and sleeps the server's delay first (default 0). It appends (path, Authorization header or None) to the server's seen and logs nothing. It yields an object with port, status, delay and seen.
  • refused: a port bound on 127.0.0.1, then closed.
  • no_proxies: monkeypatch.delenv of the five proxy variables.
def probe_lines(caplog) -> list[tuple[int, str]]:
    return [(r.levelno, r.getMessage()) for r in caplog.records
            if r.name == "kubed.mcp.telemetry" and "pyroscope at" in r.getMessage()]


def test_a_pyroscope_down_at_boot_is_one_warning_in_the_first_interval(refused, no_proxies, caplog) -> None:
    probe = _Probe(f"http://127.0.0.1:{refused}", interval=0.05, timeout=1)
    probe.start()
    try:
        deadline = time.monotonic() + 2
        while not probe_lines(caplog) and time.monotonic() < deadline:
            time.sleep(0.01)
        time.sleep(0.2)  # several more intervals
    finally:
        probe.stop()
    assert probe_lines(caplog) == [
        (logging.WARNING, f"profiles: pyroscope at 127.0.0.1:{refused} unreachable: connection refused")
    ]


def test_down_then_up_is_one_warning_then_one_info(stub, no_proxies, caplog) -> None:
    probe = _Probe(f"http://127.0.0.1:{stub.port}", timeout=1)
    stub.status = 503
    probe.check(); probe.check()
    stub.status = 200
    probe.check(); probe.check()
    host = f"127.0.0.1:{stub.port}"
    assert probe_lines(caplog) == [
        (logging.WARNING, f"profiles: pyroscope at {host} unreachable: server error (HTTP 503)"),
        (logging.INFO, f"profiles: pyroscope at {host} reachable again"),
    ]


@pytest.mark.parametrize("status", [401, 403])
def test_a_refused_login_is_an_auth_warning(stub, no_proxies, caplog, status) -> None:
    stub.status = status
    _Probe(f"http://127.0.0.1:{stub.port}", timeout=1).check()
    assert probe_lines(caplog)[0][1].endswith(f"unreachable: auth (HTTP {status})")


def test_a_404_is_reachable(stub, no_proxies, caplog) -> None:
    stub.status = 404
    _Probe(f"http://127.0.0.1:{stub.port}", timeout=1).check()
    assert probe_lines(caplog) == []


def test_a_redirect_is_reachable_and_not_followed(stub, no_proxies, caplog) -> None:
    stub.status = 302
    _Probe(f"http://u:s3cret@127.0.0.1:{stub.port}", timeout=1).check()
    assert probe_lines(caplog) == [] and [p for p, _ in stub.seen] == ["/ready"]


def test_a_timeout_is_its_own_kind(stub, no_proxies, caplog) -> None:
    stub.delay = 1
    _Probe(f"http://127.0.0.1:{stub.port}", timeout=0.2).check()
    assert probe_lines(caplog)[0][1].endswith("unreachable: timeout")


def test_the_probe_sends_basic_auth_and_shows_none_of_it(stub, no_proxies, caplog) -> None:
    stub.status = 401
    _Probe(f"http://us%40er:s3cret@127.0.0.1:{stub.port}/base/?token=t0ken", timeout=1).check()
    assert stub.seen == [("/base/ready", "Basic " + base64.b64encode(b"us@er:s3cret").decode())]
    for secret in ("s3cret", "us@er", "us%40er", "t0ken", "base"):
        assert_safe(caplog.records, secret)
    assert probe_lines(caplog) == [
        (logging.WARNING, f"profiles: pyroscope at 127.0.0.1:{stub.port} unreachable: auth (HTTP 401)")
    ]


def test_a_probe_that_fails_oddly_never_raises(monkeypatch, caplog) -> None:
    def boom(*a, **kw):
        raise RuntimeError("https://u:s3cret@x")
    monkeypatch.setattr(urllib.request.OpenerDirector, "open", boom)
    _Probe("http://127.0.0.1:1", timeout=1).check()
    assert probe_lines(caplog)[0][1].endswith("unreachable: RuntimeError")
    assert_safe(caplog.records, "s3cret")


def test_stop_ends_the_thread_within_the_timeout(stub, no_proxies) -> None:
    probe = _Probe(f"http://127.0.0.1:{stub.port}", interval=60, timeout=1)
    probe.start()
    started = time.monotonic()
    probe.stop()
    assert time.monotonic() - started < 1.5
    assert "pyroscope-probe" not in [t.name for t in threading.enumerate()]


@pytest.mark.probe
def test_profiles_start_the_probe_on_the_push_interval_and_stop_ends_it(pyroscope, stub, no_proxies) -> None:
    signals = _start_signals("t", TelemetrySettings(profiles=f"http://127.0.0.1:{stub.port}"))
    (thread,) = [t for t in threading.enumerate() if t.name == "pyroscope-probe"]
    assert thread.daemon and pyroscope[0]["upload_interval"] == 10
    signals.stop()
    assert not thread.is_alive()


@pytest.mark.probe
def test_profiles_off_start_no_probe() -> None:
    assert _start_signals("t", TelemetrySettings()) is None
    assert "pyroscope-probe" not in [t.name for t in threading.enumerate()]

test_profiles_off_start_no_probe also runs _start_signals("t", TelemetrySettings(profiles=ADDRESS)) with pyroscope missing (monkeypatch.setitem(sys.modules, "pyroscope", None)), and asserts no thread either. test_every_keyword_passed_is_one_configure_takes already checks upload_interval against the real configure.

  • Step 2: Run the tests to verify they fail

Run: pytest tests/test_telemetry.py -v -k "probe or pyroscope_down or down_then_up or refused_login or 404 or redirect or timeout or basic_auth" Expected: collection fails with ImportError: cannot import name '_Probe'.

  • Step 3: Implement design items 5 to 11

_Probe's docstring says it checks reachability, not the push itself, and why: pyroscope-io 1.4 gives Python no status for a push. no_probe's docstring says why it's autouse: the fake pyroscope's addresses are real hostnames.

  • Step 4: Run the tests to verify they pass

Run: pytest tests/test_telemetry.py tests/test_components.py -v Expected: PASS, the profile tests from #49 unchanged.

  • Step 5: Checks and commit

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

git add kubed/mcp/telemetry.py tests/conftest.py tests/test_telemetry.py pyproject.toml
git commit -m "feat(telemetry): an unreachable Pyroscope is logged once, checked on the push interval, and so is its recovery"

Task 3: TEL-21, resource reads in the call metrics

Files:

  • Create: kubed/mcp/_metrics.py: _TEMPLATE, _Matched, _MATCHED, _Labelled, _CallMetrics and _ReadObserver.
  • Modify: kubed/mcp/telemetry.py: _call_metrics builds _CallMetrics(user_id="omit").
  • Modify: kubed/mcp/_builtins.py: _TelemetryComponent.register calls metrics.observe(mcp.server).
  • Modify: tests/otel_child.py: HEAVY gains "kubed.mcp._metrics".
  • Test: tests/test_telemetry.py, a new section # -- resource reads (TEL-21), and test_call_metrics_are_outermost_with_otel_on.

Interfaces:

  • Consumes: _call_metrics, _TelemetryComponent.register, _TakeThePrefix, and UsageMiddleware's _record(self, context, call_next, *, method, name_attribute, name) and _duration (4.2.6).

  • Produces:

    • _call_metrics(settings: TelemetrySettings | None) -> _CallMetrics | None, typed Middleware | None under TYPE_CHECKING as today;
    • _CallMetrics.observe(self, server: FastMCP) -> None;
    • _ReadObserver(server: FastMCP).
  • Step 1: Write the failing tests

All of these use metered and duration_points. reads(points) is a small helper giving [(p.attributes.get("mcp.resource.template"), p.count) for p in points if p.attributes["mcp.method.name"] == "resources/read"].

def resourced(name: str) -> QuickMCP:
    mcp = QuickMCP(name, config={"telemetry": TelemetrySettings(otel=True)})

    @mcp.resource("data://items/{id}")
    def item(id: str) -> str:
        return id

    @mcp.resource("data://about")
    def about() -> str:
        return "about"

    return mcp


async def test_reads_of_one_template_are_one_series(metered) -> None:
    async with Client(resourced("templated").server) as client:
        await client.read_resource("data://items/1")
        await client.read_resource("data://items/2")
    assert reads(duration_points(metered, "templated")) == [("data://items/{id}", 2)]


async def test_a_static_read_is_labelled_by_its_uri(metered) -> None:
    async with Client(resourced("static").server) as client:
        await client.read_resource("data://about")
    assert reads(duration_points(metered, "static")) == [("data://about", 1)]


async def test_a_read_that_matches_nothing_has_only_the_error_label(metered) -> None:
    async with Client(resourced("missing").server) as client:
        with pytest.raises(Exception):
            await client.read_resource("data://nope")
    (point,) = [p for p in duration_points(metered, "missing") if p.attributes["mcp.method.name"] == "resources/read"]
    assert "mcp.resource.template" not in point.attributes
    assert {"error.type", "rpc.status_code"} & set(point.attributes)


async def test_a_plugin_skill_read_under_a_prefix_is_labelled_without_it(metered, tmp_path) -> None:
    mcp = QuickMCP("kit-reads", header_prefix="Kb", config={"telemetry": TelemetrySettings(otel=True)})
    mcp.add_plugin(write(tmp_path / "kit", KIT_TREE), namespace="lib")
    async with over_http(mcp, headers={"Kb-Resource-Prefix": "kb+"}) as client:
        await client.read_resource("kb+skill://lib/guide/references/a.md")
        await client.read_resource("kb+skill://lib/guide/references/a.md")
    assert reads(duration_points(metered, "kit-reads")) == [("skill://lib/guide/references/a.md", 2)]


async def test_overlapping_reads_keep_their_own_templates(metered) -> None:
    mcp = resourced("overlap")

    @mcp.resource("data://slow/{id}")
    async def slow(id: str) -> str:
        await asyncio.sleep(0.05)
        return id

    async with Client(mcp.server) as client:
        await asyncio.gather(client.read_resource("data://slow/1"), client.read_resource("data://items/1"))
    assert sorted(reads(duration_points(metered, "overlap"))) == [("data://items/{id}", 1), ("data://slow/{id}", 1)]


async def test_tools_and_prompts_are_recorded_as_before(metered) -> None:
    mcp = resourced("mixed")
    mcp.tool(lambda: "pong", name="ping")
    mcp.prompt(lambda: "hello", name="greet")
    async with Client(mcp.server) as client:
        await client.call_tool("ping", {})
        await client.get_prompt("greet")
        await client.read_resource("data://about")
    kinds = sorted(p.attributes["mcp.method.name"] for p in duration_points(metered, "mixed"))
    assert kinds == ["prompts/get", "resources/read", "tools/call"]
    tool = next(p for p in duration_points(metered, "mixed") if p.attributes["mcp.method.name"] == "tools/call")
    assert "mcp.resource.template" not in tool.attributes


def test_usage_middleware_still_has_what_the_reads_use() -> None:
    from fastmcp.server.middleware.usage import UsageMiddleware

    from kubed.mcp._metrics import _CallMetrics, _Labelled

    assert callable(getattr(UsageMiddleware, "_record", None))
    assert isinstance(_CallMetrics(user_id="omit")._duration, _Labelled)

write and KIT_TREE come from tests/plugin_server.py and tests/gateway_server.py, and over_http from tests/gateway_server.py. In the plugin test, if Step 4 shows that FastMCP's catalogue provider answers the file through a template, the label is that template's uri_template. Pin that value and say so in the pull request. Either way it never starts with kb+.

test_call_metrics_are_outermost_with_otel_on changes:

  • kinds[:2] == [_CallMetrics, _CallScope];
  • kinds.count(_CallMetrics) == 1;
  • kinds[kinds.index(_TakeThePrefix) + 1] is _ReadObserver.

test_otel_off_adds_no_call_metrics also asserts _ReadObserver isn't in the list, by name, without importing _metrics.

  • Step 2: Run the tests to verify they fail

Run: pytest tests/test_telemetry.py -v -k "read or series or static or usage_middleware or outermost" Expected: collection fails with ModuleNotFoundError: No module named 'kubed.mcp._metrics'.

  • Step 3: Implement design items 12 to 15

_metrics.py's module docstring says why the label crosses two middlewares: the metrics are outermost (TEL-16), and only the observer sees the plain URI under the pin. It also says why the lookup is template-only (item 14).

  • Step 4: Run the tests to verify they pass

Run: pytest tests/test_telemetry.py tests/test_gateway.py tests/test_facade.py -v Expected: PASS, test_otel_off_imports_no_sdk's child (with kubed.mcp._metrics in HEAVY) and the facade's import tests included.

  • Step 5: Checks and commit

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

git add kubed/mcp/_metrics.py kubed/mcp/telemetry.py kubed/mcp/_builtins.py tests/test_telemetry.py tests/otel_child.py
git commit -m "feat(telemetry): call metrics record resources/read, labelled by mcp.resource.template"

Task 4: The rows, the telemetry page and the CHANGELOG

Files:

  • Modify: docs/superpowers/specs/telemetry.md (the wiki).

  • Modify: CHANGELOG.md, [Unreleased] → ### Added only.

  • Step 1: The rows lose (proposed) and read:

  • TEL-16's second sentence: "Every tool call, prompt render and resource read (TEL-21) is then recorded on mcp.server.operation.duration …", and the rest is unchanged.

  • TEL-18: "With otel on, a log line the server writes inside a span ends with trace_id=<32 hex> span_id=<16 hex>, OpenTelemetry's own names, whatever format the server's handlers use. So a backend that reads only the line, such as Loki reading stdout, joins it to its trace. The ids are added to what the record's getMessage() returns. Its msg and args, and every handler and formatter, are left as they are, so a formatter that prints record.msg raw doesn't show them. A line formatted later, on another thread, shows the span it was written in, and shows the ids once. Outside a span, a line is unchanged. TEL-15's record fields stay. When OTEL_LOGS_EXPORTER exports, the record's body carries the ids too. The stop puts back the record factory it found, unless something replaced it since, which then stays."

  • TEL-19: "Pyroscope unreachable, checked on the push interval. With profiles on, the server checks the profiles address every 10 seconds, the interval it pushes on. It sends GET <address>/ready with the address's basic auth, and follows no redirect. The check is reachability, not the push itself: pyroscope-io gives Python no status for a push.

    • A connection refused, a DNS, TLS or timeout failure, a 401 or 403, or a 5xx makes the address unreachable. Any other answer, a 404 included, is reachable, since some hosted endpoints serve no /ready.
    • The first failure logs one warning on kubed.mcp.telemetry, profiles: pyroscope at <host> unreachable: <kind>, and nothing more until the address is reachable again. Then it logs one info line, profiles: pyroscope at <host> reachable again.
    • <host> is shown as TEL-20 shows it. No line shows a credential, the path, the query or an error's text.
    • The first check runs at start, so a server whose Pyroscope is down at boot says so within the first interval, not only at exit. The check runs on a thread of its own, and starts and stops with profiles."
  • TEL-21: "Call metrics (TEL-16) also record resources/read on mcp.server.operation.duration, labelled mcp.resource.template.

    • The label comes from the template lookup alone. A read whose URI matches a template is labelled by that template's uri_template, a static resource included when its URI also matches a template. A successful read that matches no template is labelled by its static URI.
    • The URI is the one the server's providers saw: never with a gateway prefix (GW-4), and never a templated URI's values, so the series stay bounded. The plugin layer's skill://, prompts:// and agents:// reads are labelled too.
    • A read that matches nothing carries no label, only the error attributes the other methods get."
  • Step 2: The telemetry page's logs

Add a short paragraph under TEL-18, or in the page's use cases, for operators:

  • the text form;
  • a Loki derived field trace_id=(\w+) that links the line to its trace;
  • the record.msg caveat.

The use case "A log line written during a traced call carries that call's trace id" gains "in its text".

  • Step 3: The CHANGELOG, three lines appended to [Unreleased]'s ### Added:
- With `otel` on, a log line written inside a span ends with `trace_id=… span_id=…`, so Loki can link it to its trace.
- An unreachable Pyroscope is logged once, checked on the push interval, and so is its recovery.
- Call metrics include `resources/read`, labelled by `mcp.resource.template`.
  • Step 4: Checks

Run: ruff check . && ruff format --check . && pytest Expected: all pass. The wiki and the CHANGELOG are left for the job to commit, as Global Constraints says.

git add CHANGELOG.md
git commit -m "docs: TEL-18, TEL-19 and TEL-21 are built; the changelog for rc.3"

Clone this wiki locally