Repository navigation
2026 11 26 telemetry reports itself
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 intoissue-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 parent's rulings aren't to be reopened:
- TEL-19 is the probe, with the row reworded;
enable_loggingand 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).
-
The factory is
_TraceTextinkubed/mcp/_otel.py:-
install()keepslogging.getLogRecordFactory()as the previous factory and sets its own. The bound method is stored once, so "still ours" is anischeck. - 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, alogging.LogRecordsubclass at module level.
- the text
- Otherwise the record is returned untouched.
-
_TracedRecord.getMessage()issuper().getMessage()with_kubed_traceappended, unless that text already contains it. So aQueueHandler, which bakes the formatted line intomsg, never shows the ids twice, a traceback after them included (settled here; built as "contains", since "ends with" showed them twice forlog.exception). -
msg,args, every handler and every formatter are untouched, so a handler added later is covered too. TEL-15'sotelTraceIDandotelSpanIDstay. - 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 owngetMessage(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. -
_makenever raises: a failure returns the record as the previous factory made it.
-
-
Where it goes.
_trace_text() -> _TraceText | Noneinstalls 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.startcalls it in two places:-
someone else's SDK: after the
_instrument_loggingblock, whatever that block returned; -
our own SDK: after a successful
initialize(), when the returned_Otelis built.
The failed-
initialize()path installs nothing._Otelgainstext: _TraceText | None = None. -
someone else's SDK: after the
-
Stop.
_Otel.stopremoves the text first, beforeLoggingInstrumentor().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 whilelogging.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. -
Docs (Task 4):
- the TEL-18 row;
- a formatter that reads
record.msgraw doesn't show the ids; - the OTLP log body carries them too when
OTEL_LOGS_EXPORTERexports; - an operator's Loki derived field is
trace_id=(\w+).
-
Constants in
kubed/mcp/telemetry.py:-
_UPLOAD_INTERVAL = 10(seconds), now passed explicitly aspyroscope.configure(..., upload_interval=_UPLOAD_INTERVAL); -
_PROBE_TIMEOUT = 5.0(seconds), under the interval.
-
-
_Probe(address: str, *, interval: float = _UPLOAD_INTERVAL, timeout: float = _PROBE_TIMEOUT):-
check() -> Noneruns one probe and logs a change. It never raises. -
start() -> Nonestarts a daemonthreading.Threadnamedpyroscope-probe, never tied to the event loop. Its loop ischeck(), thenself._stopping.wait(interval), until stopped, so the first probe runs at start. -
stop() -> Nonesets the event and joins for at mosttimeout. It never raises.
-
-
The request, built by
_ready(address: str) -> tuple[str, str | None], which returns the URL and theAuthorizationheader:-
Scheme: an address without
://getshttp://(settled here). -
Userinfo: split as TEL-20's
_wheresplits 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, sohttps://u:p@host:4040/base/?t=xprobeshttps://host:4040/base/ready. -
Auth: userinfo
user:password, each parturllib.parse.unquoted, is sent asBasic 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._NoRedirectfollows no redirect, so the credentials never reach another host, and a 3xx counts as reachable (settled here). -
urllib.requestis imported inside_Probe, so importingkubed.mcpdoesn't load it.
-
Scheme: an address without
-
Classification,
_outcome(address: str, timeout: float) -> str | None, whereNoneis reachable. The kinds are exact copy (settled here):What happened Kind ConnectionRefusedErrorconnection refusedsocket.gaierrorDNSssl.SSLError, a certificate error includedTLSTimeoutError/socket.timeouttimeoutany other OSErrororhttp.client.HTTPExceptionconnection errorValueError(a URL that won't parse)invalid addressHTTP 401 or 403 auth (HTTP 401),auth (HTTP 403)HTTP 5xx server error (HTTP 503), with the codeany other status, 2xx, 3xx and 404 included reachable any other Exceptionits type's __name__A
URLErroris classified by itsreasonwhen that's an exception.HTTPErroris checked beforeURLError. -
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.
- the first failure of a run: one warning,
-
Lifetime.
_start_probe(address: str) -> _Probe | Nonebuilds and starts one, never raises, and is the tests' seam.-
_start_signalscalls it right after_start_profilesreturns pyroscope._start_profileskeeps 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 owntry. - Profiles off, or profiles that didn't start, start no probe.
-
-
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 intests/conftest.py,no_probe, replaceskubed.mcp.telemetry._start_probewithlambda address: None. It does this unless the test carries the new markerprobe, registered inpyproject.toml. Tests that build a_Probedirectly don't need the marker.
-
kubed/mcp/_metrics.py(new) imports FastMCP,UsageMiddlewareand_TakeThePrefixat module level.telemetry._call_metricsimports it lazily, only whenotelis on. It holds:-
_TEMPLATE = "mcp.resource.template"; -
_MATCHED: ContextVar[_Matched | None], where_Matchedholdslabel: str | None = None.
-
-
_CallMetrics(UsageMiddleware), built as_CallMetrics(user_id="omit")._call_metricsreturns it in place of the bareUsageMiddleware.-
__init__wrapsself._duration(FastMCP 4.2.6's histogram) in_Labelled. If the private names it relies on (_duration, and_recordon 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_Matchedin_MATCHED. It returnsawait self._record(context, call_next, method="resources/read", name_attribute=_TEMPLATE, name=""), and resets the var in afinally. So the attributes are UsageMiddleware's own: the transport, protocol and server name,error.typeandrpc.status_code. -
_Labelled.record(amount, attributes=None, *args, **kwargs)acts only when_TEMPLATEis inattributes. On a copy, it sets_TEMPLATEto 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) -> Noneinserts_ReadObserver(server)intoserver.middlewareright after the_TakeThePrefixinstance, or appends it when there's none. It never raises.
-
-
_ReadObserver(server), placed inside_PinScopeand_TakeThePrefix, sees the plain URI under the request's pin. When_MATCHEDholds no_Matched, it just callscall_next. Otherwise:-
on success: the label is the
uri_templateof the template the URI matches, else the URI as the observer saw it; -
when
call_nextraises anException: the label is that template'suri_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 fromcontext.message's_metaas FastMCP's resources/read handler reads it, andNonewhen 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 thenget_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.mdfile, the plugin layer's_get_resourcere-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.
-
on success: the label is the
-
Registration.
_TelemetryComponent.registerinserts the metrics at index 0, as today, then callsmetrics.observe(mcp.server). Off, it imports nothing: neither_metricsnor FastMCP's usage module.tests/otel_child.py'sHEAVYgains"kubed.mcp._metrics".
-
from __future__ import annotationsat the top of every module.kubed/gets no__init__.py. -
telemetry.py,_builtins.pyandcomponents.pystay FastMCP-free at module level, with the relative importstests/test_facade.pyallows today._metrics.pyand_otel.pyare imported only whenotelis on. Importingkubed.mcpstill loads no FastMCP, andtelemetry.pyimportsurllib.requestonly 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
profilessecret, 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=orconfig=; - 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_PROXYandno_proxywithmonkeypatch.
-
Checks, as CI runs them (
lint.yml, andtest.ymlafterpip install -e .[test,tasks]):ruff check .,ruff format --check .andpytest. -
The wiki. Edits are left in the
docs/checkout. The job commits them on the wiki branchissue-59, cut from the commitissue-47pins (15572d9), and 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. -
.github/isn't touched.
-
A server that logs through a
QueueHandler. The handler bakesgetMessage()intomsg, and the listener formats it again. The ids must show once (Task 1,test_a_queue_handler_shows_the_ids_once). -
A bare root logger.
logging.lastResortprints%(message)s, so its line gains the ids, on theinitialize()path too. The child tests that matched the bareinsideline must match the new form (Task 1,test_otel_leaves_a_bare_root_logger_bare,test_the_real_configuration_exports_a_named_tagged_span). -
A Pyroscope address that redirects, such as a hosted endpoint sending
/readyto 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). -
A Pyroscope address with a path and a trailing slash.
http://u:p@127.0.0.1:<port>/base/?t=xmust probe/base/ready, with no query (Task 2,test_the_probe_sends_basic_auth_and_shows_none_of_it). -
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).
Files:
- Modify:
kubed/mcp/_otel.py: new_TracedRecord,_TraceTextand_trace_text;_Otel(text=);_Otel.stopremoves the text first;startinstalls 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,_Otelandstartonissue-47. -
Produces:
-
class _TracedRecord(logging.LogRecord); -
class _TraceTextwithinstall(self) -> Noneandremove(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)keepsself.format(record)for each record. -
as_jsonis alogging.Formattersubclass whoseformatreturnsjson.dumps({"level": r.levelname, "message": r.getMessage()}). - Each test adds its handlers to root and removes them in a
finally, astest_log_records_carry_the_trace_and_root_keeps_its_handlersdoes. 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}"becomesre.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()becomesany(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
ImportErrorfor_TraceText, or on the missing suffix; -
the two child tests fail on the old line;
-
test_otel_off_installs_no_factorypasses 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"Files:
- Modify:
kubed/mcp/telemetry.py:_UPLOAD_INTERVAL,_PROBE_TIMEOUT,_ready,_outcome,_NoRedirect,_Probeand_start_probe;upload_interval=in_start_profiles;_Signals(probe=);_start_signalsstarts it. - Modify:
tests/conftest.py: the autouseno_probefixture. - 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_signalsand_start_profilesonissue-47. -
Produces:
-
_UPLOAD_INTERVAL: int = 10and_PROBE_TIMEOUT: float = 5.0; -
_ready(address: str) -> tuple[str, str | None]; -
_outcome(address: str, timeout: float) -> str | None; -
class _Probewithcheck(),start()andstop(); -
_start_probe(address: str) -> _Probe | None; -
_Signals(profiles, otel=None, probe=None).
-
-
Step 1: Write the failing tests
Fixtures in the section:
-
stub: ahttp.server.ThreadingHTTPServer(("127.0.0.1", 0), ...)withdaemon_threads = True, served on a daemon thread and shut down after the test. Its handler answersGETwith the server'sstatusattribute (default 200), plusLocation: /elsewhereon a 3xx, and sleeps the server'sdelayfirst (default 0). It appends(path, Authorization header or None)to the server'sseenand logs nothing. It yields an object withport,status,delayandseen. -
refused: a port bound on 127.0.0.1, then closed. -
no_proxies:monkeypatch.delenvof 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"Files:
- Create:
kubed/mcp/_metrics.py:_TEMPLATE,_Matched,_MATCHED,_Labelled,_CallMetricsand_ReadObserver. - Modify:
kubed/mcp/telemetry.py:_call_metricsbuilds_CallMetrics(user_id="omit"). - Modify:
kubed/mcp/_builtins.py:_TelemetryComponent.registercallsmetrics.observe(mcp.server). - Modify:
tests/otel_child.py:HEAVYgains"kubed.mcp._metrics". - Test:
tests/test_telemetry.py, a new section# -- resource reads (TEL-21), andtest_call_metrics_are_outermost_with_otel_on.
Interfaces:
-
Consumes:
_call_metrics,_TelemetryComponent.register,_TakeThePrefix, andUsageMiddleware's_record(self, context, call_next, *, method, name_attribute, name)and_duration(4.2.6). -
Produces:
-
_call_metrics(settings: TelemetrySettings | None) -> _CallMetrics | None, typedMiddleware | NoneunderTYPE_CHECKINGas 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"Files:
-
Modify:
docs/superpowers/specs/telemetry.md(the wiki). -
Modify:
CHANGELOG.md,[Unreleased]→### Addedonly. -
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
otelon, a log line the server writes inside a span ends withtrace_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'sgetMessage()returns. Itsmsgandargs, and every handler and formatter, are left as they are, so a formatter that printsrecord.msgraw 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. WhenOTEL_LOGS_EXPORTERexports, 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
profilesaddress every 10 seconds, the interval it pushes on. It sendsGET <address>/readywith 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."
- 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
-
TEL-21: "Call metrics (TEL-16) also record
resources/readonmcp.server.operation.duration, labelledmcp.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://andagents://reads are labelled too. - A read that matches nothing carries no label, only the error attributes the other methods get."
- The label comes from the template lookup alone. A read whose URI matches a template is labelled
by that template's
-
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.msgcaveat.
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"These pages describe what is on main; the spec says what is built and what is only proposed.
kubed-mcp · MIT