Repository navigation
metrics: expose Prometheus exposition at /metrics - #124
Conversation
Wires a Prometheus registry into the router so the org's Prometheus / Victoria Metrics clusters can scrape this service directly, rather than inferring its state from a status page. Uses the `prometheus` crate pinned to the version dfinity/ic already depends on, since these series land in the same estate and two exposition dialects there would be nobody's win. What it reports: request counters and a latency histogram, taken from the facts the request-logging middleware already computed and previously only wrote to a log; the live and active session gauges that /version publishes, read at scrape time because they are derived state; build version and commit as labels on a build_info gauge, so any series can be attributed to an exact commit; process start time under the conventional name, so a redeploy is a step change rather than something to infer; and CPU, resident memory and file descriptors from the crate's process collector, compiled only on Linux since it reads /proc. Label cardinality is the whole design problem, not a detail. Every series is a row Prometheus holds in memory, so a label whose value an outsider picks is a memory-exhaustion primitive — and this service is internet-facing and continuously scanned, with a request log full of paths nobody here wrote. The route label is therefore never the requested path; it is axum's MatchedPath, the route template, which is bounded by the route table by construction and stays correct as routes are added. Unmatched requests have no template and collapse into one shared bucket. A test asserts that property rather than trusting the comment: 500 distinct unmatched paths produce exactly one series. Verified against a running server too, where 25 probe paths stayed one series while real routes kept their templates. Not published to the public internet. The app binds 0.0.0.0:8000, so a scraper reaches /metrics on the host's private address over the VPN — the same path the deploy already uses — and nothing needs exposing to make that work. Caddy returns 404 for the path rather than 403, so it is not advertised as existing. Metrics are not secret, but they are a free operational read (request volumes and error rates per route, session counts, process memory) and a public scrape target is also an amplification lever, since each request makes the process gather and encode its whole registry. The endpoint measures itself as well: a scrape that quietly got slow is how a target starts being dropped for timing out, and the resulting gap looks like an outage that never happened. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01R8ZshwKmjD5fZ4Hs9dS6zh
There was a problem hiding this comment.
🟡 Changes recommended
Arbitrary HTTP methods can still create unbounded metric series, and the cardinality test does not exercise actual requests.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
This review doesn't count toward merge requirements. Sign up for the private preview to control whether Copilot approvals count.
Pull request overview
Adds Prometheus observability for HTTP traffic, sessions, build details, and process health.
Changes:
- Adds a Prometheus registry and
/metricsendpoint. - Records request latency/counts and session gauges.
- Blocks public
/metricsaccess through Caddy.
File summaries
| File | Description |
|---|---|
src/metrics.rs |
Defines collectors, exposition, and tests. |
src/main.rs |
Adds metrics routing and request instrumentation. |
deploy/native/Caddyfile |
Returns 404 for public metrics requests. |
Cargo.toml |
Adds the Prometheus dependency. |
Cargo.lock |
Locks Prometheus and transitive dependencies. |
Review details
- Files reviewed: 4/5 changed files
- Comments generated: 2
- Review effort level: Balanced
We're testing this review assessment. Please use 👍 or 👎 to tell us if it's correct.
Two review findings, both correct, and the first is a clean bypass of the guard this change was built around. The route label was bounded while the method label beside it was not. HTTP permits arbitrary extension method tokens and the public listener forwards them, so a request line reading WIBBLE / HTTP/1.1 minted its own series. Measured before fixing: twelve nonsense methods against a single path produced thirteen counter series and 182 histogram bucket lines, because a histogram multiplies every label set by its bucket count. The same twelve now produce one series and the buckets drop to 65. Methods are allow-listed to the standard nine and the helper returns &'static str, so the bound holds by type rather than by care. Worth naming the pattern rather than just the bug: I bounded the label I had been thinking about and left the one immediately next to it wide open, having written a module doc that presented cardinality as the central design problem. The doc now says the rule applies to every request-influenced label, and notes why status is the one that does not need it — the server chooses it, from a small closed set. The cardinality test was also vacuous, which is the more uncomfortable of the two. It built 500 distinct paths, discarded them, and called the recorder 500 times with a constant. That asserts a pure function is deterministic. It says nothing about the middleware deriving a bounded label from a hostile one, and would have passed unchanged if the middleware started using the raw URI — precisely the regression it existed to prevent. Both cardinality tests now drive real requests through an axum router with the real middleware installed. Confirmed by mutation: making the middleware use the raw path fails the path test and nothing else, and making the method label a pass-through fails the two method tests and nothing else. The old test survived the first of those mutations, which is the whole argument for the rewrite. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01R8ZshwKmjD5fZ4Hs9dS6zh
There was a problem hiding this comment.
🟡 Changes recommended
Concurrent scrapes can expose an inconsistent session gauge pair that violates the documented invariant.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
This review doesn't count toward merge requirements. Sign up for the private preview to control whether Copilot approvals count.
Review details
Suppressed comments (1)
src/metrics.rs:214
liveandactiveare separate collectors and are updated independently while Axum can run another/metricsscrape concurrently. When counts decrease, a concurrentregistry.gather()can observe the newlivevalue and the oldactivevalue, exportingactive > livedespite the metric's stated invariant. Serialize each session-pair update with gathering (or publish both values from one synchronized collector/snapshot).
self.live_sessions.with_label_values(&[instance]).set(live);
self.active_sessions
.with_label_values(&[instance])
.set(active);
- Files reviewed: 4/5 changed files
- Comments generated: 0 new
- Review effort level: Balanced
We're testing this review assessment. Please use 👍 or 👎 to tell us if it's correct.
Addresses consumer feedback that none of this was reachable: `mod metrics;` lived in main.rs, so the module was private to the bin target and an embedder depending on the crate got nothing. It is `pub mod metrics` in lib.rs now. Split log_request into write_request_metrics and write_request_logs, both exported. They are separated because their constraints genuinely differ rather than for tidiness: metrics must bound every label, while a log line can afford the full request path and is more useful carrying it. Splitting also lets an embedder take either one alone. The log moves from info to debug — it fires on every request including the noise floor of an internet-facing service, so at info it drowns the handful of lines an operator actually wants. Metrics::new now registers into a Registry the caller supplies and keeps none of its own. A host embedding this crate already has a registry and already exposes it; series published into a private one would simply never be seen. Exposition follows the registry, so render() is gone and the binary gathers its own; the scrape-duration signal survives as observe_scrape, recorded by whoever renders. Registering the process collector also stops being the library's business. `process_*` is un-namespaced and describes the whole OS process, which belongs to the embedding application rather than to this crate, and would collide with a host that already has one. It is now an explicit register_process_collector the standalone binary calls, since the binary is the application. The metric prefix is factored into a macro rather than repeated. A macro over a const plus format! keeps the names &'static str and keeps them greppable in full, so searching an alert rule's imcp2_http_requests_total still finds the line that defines it. Fixed rather than caller-configurable on purpose: a metric name identifies the software emitting it, and one dashboard working across every deployment depends on that. Verified from outside the crate, not only by unit tests: a scratch consumer crate registers imcp2's collectors into its own registry alongside its own metric, does its own exposition, and asserts no process_* leaked in. Also confirmed the log line is absent at default level and present under RUST_LOG=imcp2=debug, and that the binary still serves /metrics with the process collector it registers itself. Two library-safety properties the review raised are now pinned by tests rather than assumed: a second Metrics::new against one registry returns AlreadyReg instead of panicking, and Metrics::new registers no process_* series. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01R8ZshwKmjD5fZ4Hs9dS6zh
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 5 out of 6 changed files in this pull request and generated no new comments.
Suppressed comments (3)
src/metrics.rs:221
- This gauge is named
imcp2_process_start_time_secondsbecausemetric!always adds the prefix, so it is not the conventionalprocess_start_time_secondsclaimed here. The binary also immediately registersProcessCollector::for_self(), which already exports the conventional series using the OS process start; this extra gauge instead records a later point after application initialization. Remove the duplicate custom gauge/constructor parameter and use the process collector's series, or rename and document it as an application-ready timestamp.
let start_time = IntGauge::new(
metric!("process_start_time_seconds"),
"Unix epoch seconds at which this process started, i.e. when the deployment \
last restarted. Every deploy restarts the service.",
)?;
registry.register(Box::new(start_time.clone()))?;
start_time.set(started_at as i64);
src/metrics.rs:245
observe_requestis public for embedders, but it writesmethoddirectly as a label. Only the provided middleware callsmethod_label, so a host using this recording API with a request method can reintroduce the unbounded attacker-controlled cardinality that this module promises to prevent. Normalize the method inside this method; the middleware's existing normalization is harmless if retained.
pub fn observe_request(&self, route: &str, method: &str, status: u16, elapsed_secs: f64) {
src/metrics.rs:351
- This changes the existing request log from
infotodebug. Bothdeploy/native/imcp2.serviceand the Docker image default toRUST_LOG=info, so deployed request lines—including the full paths that metrics intentionally discard—will disappear, contrary to the PR's claim that the existing log remains. Preserve theinfolevel, or update the runtime filters to enableimcp2::metrics=debugand document the behavior change.
tracing::debug!(%method, %path, status, elapsed_ms, "http request");
… deployed request log Three findings from review of the library move, all real. observe_request was public and took route and method as raw &str, writing both straight in as labels. Only the middleware normalised them, so the bound this module exists to enforce lived one direct call away from being bypassed — and an embedder reaching for the obvious-looking recording API would have bypassed it without noticing. That hole did not exist before the move, because nothing outside the binary could call it; making the module public created it. It is pub(crate) now, with the middleware as the supported entry point, and it normalises the method itself so the invariant holds at the recording site rather than depending on every caller. Reducing the surface now is also cheap in a way it will not be later: taking a public function away after release is a break. The process-start gauge claimed a conventional name it does not have. The prefix macro makes it imcp2_process_start_time_seconds, while the process collector the binary registers exports the actual conventional process_start_time_seconds — and the two measure different moments, observed three seconds apart on a real run: the collector reports OS process start, this reports when the server finished initialising and began serving, which is when a redeploy becomes visible to clients. Both are worth having and an embedder gets only ours, since the library does not register the collector. The comment now says that instead of the opposite. Moving the request log to debug would have silently deleted it in production. Both imcp2.service and the Dockerfile pin RUST_LOG=info, so the line that records what external clients actually probe would simply have stopped appearing on deployed hosts — the full paths the metrics deliberately discard, gone from the one place that keeps them. Both now set info,imcp2::metrics=debug: quiet by default for embedders and local runs, which is what moving it to debug was for, while the deployed hosts keep the record. Verified both filters against a running server: 0 lines under plain info, present with the target enabled. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01R8ZshwKmjD5fZ4Hs9dS6zh
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 7 out of 8 changed files in this pull request and generated no new comments.
Suppressed comments (3)
src/metrics.rs:226
- This metric is named and documented as a process start time, but the bundled binary passes a timestamp captured only after agent/server construction and session-reaper startup (
src/main.rs:233-273); the surrounding comment here instead calls it the time serving began, which is also later than that timestamp. Consumers computing process uptime will therefore get a value with the wrong semantics. Either capture the actual process/service start at the beginning ofmain, or rename and document the metric to match the event being recorded.
let start_time = IntGauge::new(
metric!("process_start_time_seconds"),
"Unix epoch seconds at which this process started, i.e. when the deployment \
last restarted. Every deploy restarts the service.",
)?;
src/metrics.rs:151
- Registration is not atomic across this constructor. If an embedder's registry already contains a later name such as
imcp2_live_sessions, this call first registers the request collectors and then returnsAlreadyReg, leaving inaccessible collectors behind in the caller-owned registry and preventing a clean retry or fallback. Roll back every collector registered by this invocation when any subsequent registration fails (and add a test where the collision occurs after the first collector).
registry.register(Box::new(requests.clone()))?;
src/main.rs:413
- The scrape timer starts only after both
session_gauges()calls, even though each call scans the full session map and is part of producing the scrape. If those scans become the source of scrape latency or timeouts,imcp2_metrics_scrape_duration_secondswill stay low and miss exactly the degradation it is intended to expose. Start the timer at the beginning of the handler, before refreshing the gauges.
let started = std::time::Instant::now();
… are pulled The session gauges were pushed from the binary's /metrics handler, which is nobody else's exposition path. A host embedding this crate refreshes metrics on its own schedule, so those gauges would have sat at whatever value they last held — or never appeared at all. The pull point has to be something the caller can invoke. `Metrics::track(&McpServer)` registers a server, `Metrics::refresh().await` recomputes and publishes the derived gauges for everything tracked. Call it from an exposition path immediately before gathering, which makes the value exact as of that scrape, or from a timer if the pipeline refreshes on its own cadence. This crate deliberately does not choose; it only stops being the binary's private arrangement. `refresh` takes no arguments, which requires the handle to know its sources, so `Metrics` holds the tracked servers behind a shared `Arc<Mutex<_>>`. Clones share that set, since the handle is realistically cloned into middleware state and into an exposition path separately and tracking through either must be visible to both. The lock is never held across an await — the handles are cloned out first — and a poisoned lock warns rather than propagating a panic out of an instrumentation call. `set_sessions` becomes pub(crate) and takes `&'static str`, for the same reason `observe_request` did: a public `&str` setter is a caller-supplied label string, and the bound only holds if there is no way around it. `track` reads the name from IiInstance, where it is already `&'static str`, so the label is bounded by type. One deliberate behaviour change: `track` publishes zeroes on registration, so a served instance reads 0 from startup rather than being absent until the first refresh — but an instance that is *not* served is no longer forced to a flat zero. It is simply not tracked and has no series, which reads as "no such instance here" rather than "exists, currently idle". The previous flat zero for an unserved beta asserted something false. Also merges current main, which carries #128 — the registry renamed the `motoko` skill, and the live-network test asserting it only passes with that fix. That failure was branch staleness, not a regression here. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01R8ZshwKmjD5fZ4Hs9dS6zh
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 7 out of 8 changed files in this pull request and generated 1 comment.
Suppressed comments (3)
src/main.rs:423
- Concurrent scrapes are not serialized across
refreshandgather. One handler can gather while another independently updateslive_sessionsandactive_sessions, exposing a mixed snapshot (includingactive > live), and an older refresh can overwrite a newer snapshot after its await. Serialize the complete refresh-and-gather operation, and document or enforce the same requirement for embedders.
metrics.refresh().await;
let started = std::time::Instant::now();
let encoded = {
src/metrics.rs:168
Metrics::newmutates the caller's registry incrementally. If this or any later registration collides (for example, the host already ownsimcp2_build_info), the constructor returns an error after leaving all earlier collectors registered, so the embedder receives no handle but is left with a partial metric set. Roll back collectors registered by this invocation on failure, or register the set atomically.
registry.register(Box::new(duration.clone()))?;
src/metrics.rs:678
- This test bypasses
trackby calling the private setter directly, so it still passes iftrackstops retaining the server or publishing the initial zeroes. Exercise the public API with a minimalMcpServerfixture and assert the exposition afterm.track(&server); the existing router tests already demonstrate how to construct such a fixture.
// A real McpServer needs an Agent and network config, so assert the
// narrower property directly: registration is what creates the series.
m.set_sessions("prod", 0, 0);
…ites Four review findings on the metrics work, all real. **/metrics was public on a deployment path we ship.** The Caddyfile claimed the exposition "is NOT published to the public internet", and on the native host that is true — Caddy answers /metrics itself with a 404 and a scraper reaches the app on its own port over the VPN. But the bundled Dockerfile is a documented, supported deployment (README: Render, Fly, Cloud Run, Koyeb) with no proxy in it, so the platform routes the public hostname straight at the process and every registered route is on the internet. So the route is now gated on $MCP_SERVE_METRICS, defaulting to OFF: the exposure takes a deliberate opt-in on a host that has something to hide it, instead of requiring every other operator to notice and remove it. imcp2.service sets it; the Dockerfile does not. deploy.sh now also asserts on every deploy that the public origin does NOT answer /metrics with 200 — the Caddy block is a config edit away at all times, and that assertion is what makes it load-bearing rather than decorative. **Metrics::new was not atomic.** A collision partway through left the earlier collectors registered while returning Err, so the caller held no handle but its registry kept a partial set of our descriptors — and the retry, after the caller fixed the real collision, failed with AlreadyReg on the *first* collector, reporting a cause with nothing to do with the problem. Every collector is now built before anything is registered, and the group registers as a unit that unwinds on the first failure. **Two gauges cannot be written atomically, so order them.** A scrape landing between the live and active writes could see active > live, which the help text promises never happens and an alert dividing the two would report as a ratio above 1. Write active first when live is falling, live first when it is rising; both intermediate states then satisfy the invariant. refresh() is serialized against itself for the same reason, and for a worse one: two overlapping refreshes can commit in the order they *finish* rather than the order they read, leaving a whole scrape interval of numbers that were never true. **The track test asserted nothing about track.** It called the private setter, so it kept passing if track stopped retaining the server or stopped zero-filling. McpServer::new is pure construction, so it now uses a real server — the excuse that a fixture needs network config was simply wrong; tests/routers.rs builds one. Mutation-tested: flipping the write order, dropping the rollback, removing the zero-fill, dropping the retain, defaulting the gate on, and dropping the scrape timing each fail exactly one test. The first draft of the refresh test survived its mutation and was rewritten to poison the gauges first. 192 tests pass. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01R8ZshwKmjD5fZ4Hs9dS6zh
|
All four findings were real. Fixed in 6d65b30; one is resolved differently than suggested, noted below.
Partial registration. Fixed by building every collector before registering any, then registering the group as a unit that unwinds on the first failure. The user-visible symptom was worse than a stranded metric set: after the caller fixed the real collision, the retry failed with Refresh/gather. Resolved differently. Serializing the complete refresh-and-gather is not available to an embedder — it owns the registry and gathers wherever it already does, so any lock I hold here cannot cover its
The Mutation-tested rather than assumed: flipping the write order, dropping the rollback, removing the zero-fill, dropping the tracked-server retain, defaulting the gate on, and dropping the scrape timing each fail exactly one test. Worth recording that the first draft of the new refresh test survived its mutation — a fresh server publishes zeroes and Generated by Claude Code |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 10 out of 11 changed files in this pull request and generated no new comments.
Suppressed comments (2)
src/metrics.rs:572
- Each refresh overwrites the map entry keyed only by
IiInstance.name. Since the public API allows embedders to track distinctMcpServers with the same name, the last server silently replaces the earlier server’s counts and the exported session gauges under-report. Reject duplicate names when tracking, or define and implement aggregation/deduplication for servers sharing a label.
for server in &servers {
let g = server.session_gauges().await;
self.set_sessions(server.instance().name, g.live as i64, g.active as i64);
src/metrics.rs:415
- This metric has conflicting semantics: its name and HELP text say “process start,” while the preceding contract says it represents when initialization finished, and the bundled binary actually captures the value after constructing servers and spawning reapers but before binding the listener. Consumers cannot reliably interpret the series. Use a server/readiness-specific name and capture it at the corresponding event, or capture the real process-start time and keep the current name/HELP text.
metric!("process_start_time_seconds"),
"Unix epoch seconds at which this process started, i.e. when the deployment \
last restarted. Every deploy restarts the service.",
…ocess start Two findings, both real. **Servers sharing an instance name silently under-reported.** `refresh` wrote each tracked server's counts keyed on `IiInstance.name`, so an embedder serving one Internet Identity instance at two mounts — two `McpServer`s both named `prod` — got the last one's sessions published as the whole instance's. An under-report with no symptom, which is the worst shape a metric bug can take. The counts are now summed per instance, which is what the label already claims: it names an II instance, not a mount. Aggregation is a free function over an iterator, deliberately. Going through `refresh` cannot distinguish summing from overwriting in a test, because every count reachable without authenticated sessions is zero and 0 + 0 = 0 either way. Mutating it back to assignment fails the new test; a second test drives two real servers through `track`/`refresh` and pins that one instance still yields one series. **imcp2_process_start_time_seconds did not mean process start.** Raised three times across rounds and each time I answered the name rather than the value. The name and help text said process start, my comment claimed it deliberately meant "began serving" instead, and the value was captured mid-`main` — after the agent, the servers and their reapers, before binding the listener — so it was neither, and disagreed with the process collector's conventional series by a couple of seconds for a reason no consumer could discover. A metric whose name says one thing and whose value means another is worse than not having it. The reading moved to the first statement of `main`; the name and help text were already right, so they stay. `/version`'s `started_at` becomes correspondingly accurate (the status dashboard only displays it, so nothing changes there). The gauge keeps its overlap with the process collector on purpose: an embedder gets only this one, since the library does not register that collector and it is Linux-only regardless. 194 tests pass; clippy clean on both changed files. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01R8ZshwKmjD5fZ4Hs9dS6zh
|
Both findings were real. Fixed in 2c992b6. Servers sharing an instance name silently under-reported. I took the summing option rather than rejecting duplicates: refusing them would either change The aggregation is a free function over an iterator on purpose. Driving it through
Fixed by moving the reading to the first statement of 194 tests pass; clippy clean on both changed files. Generated by Claude Code |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 10 out of 11 changed files in this pull request and generated no new comments.
Suppressed comments (2)
src/metrics.rs:231
- Prometheus adds an
instancetarget label to every scrape. With the defaulthonor_labels: false, this exported label is renamed toexported_instanceand replaced by the target address, so queries expectinginstance="prod"/"beta"will not work after ingestion. Use a domain-specific label such asii_instanceconsistently on both session descriptors and emitted metrics.
vec!["instance".to_string()],
src/metrics.rs:558
- Tracking a second server with the same instance name unconditionally resets the aggregate gauge for the already-tracked server to zero. This contradicts the documented summing behavior and makes existing sessions disappear until the next refresh. Initialize the entry only when this is the first server for that instance.
self.set_sessions(name, 0, 0);
…stance
Two findings, both real.
**The `instance` label collides with Prometheus's own.** Prometheus attaches `job`
and `instance` target labels to every sample it scrapes, and with the default
`honor_labels: false` a scraped label of the same name is not merged — it is
renamed to `exported_instance` while `instance` becomes the target address. So
`imcp2_live_sessions{instance="prod"}` arrives in the database as
`exported_instance="prod"`, and every alert or dashboard query written against
`instance="prod"` matches nothing. Silently: the series exists, the query is
valid, the panel is just empty. Renamed to `ii_instance`, which cannot collide and
says what it means — it is an Internet Identity instance, not a scrape target.
Factored into one constant so the descriptors, the emitted label pairs and the
assertions cannot drift apart.
**track() reset an instance that already had sessions.** Fallout from summing the
counts in the previous commit: the zero-fill wrote unconditionally, so tracking a
second server for an instance with live sessions zeroed the whole instance's total
until the next refresh. The fix for under-reporting would have introduced a
different wrong number, and the same "sessions vanish for a scrape interval" shape
at that. `track` now seeds the series only when it is absent, via a `seed_sessions`
that exists to be distinct from `set_sessions` for exactly this reason.
Both mutation-checked: seeding unconditionally fails the new test, and reverting
the label to `instance` fails three.
196 tests pass; clippy clean on both changed files.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01R8ZshwKmjD5fZ4Hs9dS6zh
|
Both real. Fixed in 359f947. The Renamed to
Both mutation-checked: seeding unconditionally fails the new test, and reverting the label to 196 tests pass; clippy clean on both changed files. Generated by Claude Code |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 10 out of 11 changed files in this pull request and generated no new comments.
Suppressed comments (1)
deploy/native/deploy.sh:189
- This verifies
/metricsonly through SSH on the host's loopback interface, so it does not verify the network path the scraper actually needs. A deployment will pass even if the private-interface security group or firewall blocks TCP 8000—the open question in the PR description. Probehttp://<private-host>:8000/metricsdirectly from the VPN/self-hosted runner (and document/allow the scraper's ingress range) before declaring the deployment successful.
if $SSH "curl -fsS --max-time 5 http://127.0.0.1:8000/metrics | grep -q imcp2_build_info"; then
…h is verified The loopback check proved the app serves the exposition, but the comment above it talked about the scraper reaching it over the VPN — which that check says nothing about. A green deploy could therefore be read as "monitoring works" while the private interface drops TCP 8000. Fixed the claim, and added the part of the path that is actually checkable from here: the host reaching itself on its private address, which proves the app bound 0.0.0.0 rather than loopback and that no host-local firewall eats the port. The address is derived on the host and never printed — this repository is public, so its Actions logs are too, and echoing a private address into them is the exact disclosure the repository was scrubbed to remove. curl's stderr is dropped for the same reason, since its errors would carry the URL. A warning rather than fatal: users are served through Caddy over loopback either way, so this affects scraping alone, and the remedy is a security-group or firewall change that failing a deploy does not bring closer. The remaining hop — the scraper's network actually reaching that address — is not verifiable from this script at all, since the deploy runs on a GitHub-hosted runner that is not on the VPN. Saying so in the file rather than leaving a check that looks more complete than it is; it stays the open question on the pull request. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01R8ZshwKmjD5fZ4Hs9dS6zh
|
Right about the gap, and I've fixed the part that is fixable from here — c37d1e0. Being precise about which part, because the suggested remedy is not available to this script. What was wrong: the check probed loopback while the comment above it talked about the scraper reaching the endpoint over the VPN. Those are different claims, and a green deploy could therefore be read as "monitoring works" while the private interface drops TCP 8000. The comment now states what the check does and does not prove. What I added: the host reaching itself on its private address. That is a real subset of the path — it proves the app bound One detail worth flagging since it constrains the shape of the check: the address is never printed. This repository is public, so its Actions logs are public too, and echoing a host's private address into them is precisely the disclosure the repository was scrubbed to remove (the reason What I cannot do: probe 178 lib tests + 18 others pass; no Rust changes in this commit. Generated by Claude Code |
The public /metrics exposure check called curl with no --max-time, so an origin
that accepts the connection and then never finishes the response hangs it forever.
That is not just slow: the check never reaches its own retry loop or its own
failure, so a security assertion silently becomes a deadlock — after the service
has already been restarted. `|| true` does not help, since it handles a non-zero
exit rather than the absence of one. health.yml's webhook curl already carried
--max-time for exactly this reason; this was the inconsistency.
Timed out now, which yields `000`, which is not 404, so it retries and then fails —
the honest verdict for an origin that would not answer.
Fixed the same defect in the other three places along this path rather than only
the reported one:
* the two informational external checks in deploy.sh (a hang wedges the deploy
whether or not anyone reads the output);
* deploy-native.yml's "Verify deployed version" step, the other blocking
verification in this deploy. --max-time bounds each attempt there — curl
applies it per transfer, so the existing --retry keeps its own budget — and
--retry alone does not cover a stall, since it retries failures rather than a
transfer that never ends.
Left alone deliberately: the Caddy binary download in the provisioning path. A
blanket --max-time there would kill a legitimately slow but progressing transfer;
a stall guard for it wants --speed-limit/--speed-time, which is a change to
first-run provisioning rather than to verification, and belongs in its own commit.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01R8ZshwKmjD5fZ4Hs9dS6zh
Owner-directed simplification. Review iteration had ratcheted this module into
machinery out of proportion to what it publishes: a custom collector with
hand-built wire types so a scrape could never observe active > live, a
transactional registration with rollback, per-instance summing with a
seed-vs-set distinction, three mutexes, and essay-length comments throughout.
Each piece defended a real but marginal property; together they were the wrong
trade for observability code, which should be boring.
What changed:
* The served servers are a constructor argument (`Metrics::new(.., &[&server])`)
instead of a mutable `track()` API. The tracked set is immutable, so the
tracked-set lock, the zero-fill-under-lock dance, and the track-races-refresh
subtlety all disappear.
* The session gauges are two plain IntGaugeVecs again. The help text now says
what is true — active is sampled independently of live, so a scrape may
briefly observe it above — instead of promising an invariant that took a
custom collector, a pair mutex, a refresh mutex and a concurrency test to
uphold. The failure it allowed was a one-sample dashboard blip.
* Registration is sequential with a doc line ("not transactional; on error use
a fresh registry") instead of an unwinding Registration type.
* Duplicate instance names overwrite (documented) instead of summing.
* Comments cut to the necessary reasoning everywhere the PR touched: module
docs, main.rs, Caddyfile, imcp2.service, deploy.sh, both READMEs.
What deliberately stays, because it is load-bearing: the route/method label
bounds and their end-to-end flood tests (a label an outsider picks is a
memory-exhaustion primitive), the ii_instance label (Prometheus renames a
colliding `instance` to `exported_instance`), the MCP_SERVE_METRICS gate with
its off default, the deploy assertions (exact-404 publicly, serving privately,
--max-time on every external curl), refresh() as the embedder's pull point, and
the caller-owned registry.
Net -919 lines; src/metrics.rs 1352 -> 552. 187 tests pass; clippy clean.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01R8ZshwKmjD5fZ4Hs9dS6zh
|
272f074 deliberately simplifies this branch — net −919 lines, Relaxed, now documented behaviour instead of enforced invariant:
Kept, because it is load-bearing: the route/method cardinality bounds and their end-to-end flood tests, the 187 tests pass; clippy clean. The PR description has been rewritten to match. Generated by Claude Code |
Re-verify every claim and file:line reference against the rebased tree and absorb what main already did or changed: - The five vestigial deps (ed25519-dalek, p256, ic-signature-verification, ic-representation-independent-hash, schemars 0.8) were already removed on main (#100) — reframe that stripping work as done. - Account for the new hosted-only surfaces the local split must gate: prometheus + src/metrics.rs (/metrics, #124) and McpConfig's state_dir/require_resource (#144/#127); note the local binary needs no state directory at all. pocket-ic (e2e-only, #76) never enters any closure. - Rewrite §10: production II now serves at /mcp by default (#92), CI probes it (#113), and the PocketIC e2e harness verifies the full connect contract — the remaining unknowns are the local binary's http://127.0.0.1 mixed-content and CORS behavior, and the harness is the plan for testing the local flow. - Prod-instance env overrides are II_URL_PROD/II_CANISTER_ID_PROD (#92); registration chains are also verified client-side against the agent's root key (new_with_root_key); registration_pubkey_b64 is now fallible; AuthStore's dropped fields now include mcp_path and require_resource, and the dropped OAuth side grew RFC 8707/9207 and the bounded DCR store. - Note the crates.io publishing dimension (v0.2.0, tag-guarded trusted publishing, docs/ excluded from the .crate) and re-stamp every stale file:line reference (auth.rs shifted ~500-650 lines; the 13 call-site list and all evidence-index anchors updated). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01AqNkpMQiQHzYxC2djTfvBK
…148) * Add scoping doc for a local-deployment MCP instance Analyze the current beta/prod composition and scope a secondary server instance that bridges the MCP tools to a local dfx replica instead of mainnet. Documents the mainnet assumptions that would break locally (root-key fetch, hard-coded IC_URL, the discovery SSRF/https guard, target_origin canonicalization, and the CMC/ledger management path), a proposed local run-profile design, the security guardrails, a phased work breakdown, and open decisions. Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_01AqNkpMQiQHzYxC2djTfvBK * Rescope: minimal stdio local binary, no OAuth, prod II Rewrite the scoping doc for the intended model: a separate, minimal run-it-yourself binary that speaks MCP over stdio and talks to mainnet IC + production Internet Identity — not a local dfx replica. It drops the entire OAuth 2.1 authorization-server layer (the local client is co-located, so the stdio process boundary replaces bearer-token auth) while keeping Internet Identity: login runs as a built-in browser handshake and per-app account delegations work as today. Adds a verified dependency-stripping analysis (four unreferenced crates plus a vestigial schemars drop; rmcp swaps to the stdio transport and drops auth), the auth.rs OAuth-drop/II-connect-keep partition, the tool/session singleton seam, a 3-crate workspace layout, the security model, and the production-II verification risks. Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_01AqNkpMQiQHzYxC2djTfvBK * Keep the crate named imcp2 in the layout The shared library crate stays imcp2 (its existing embeddable identity) and the hosted binary stays named imcp2, so the Dockerfile, systemd unit, and deploy scripts that build/run an imcp2 binary are unchanged. The hosted server + OAuth layer move behind a default-on `hosted` feature (optional axum/tower-http); the new minimal stdio binary is a separate imcp2-local crate depending on imcp2 with default-features off, so it never compiles the OAuth/HTTP deps. Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_01AqNkpMQiQHzYxC2djTfvBK * Add "Working with AI tool clients" section Cover how imcp2-local integrates with Claude (Desktop/Code + the cloud surfaces), Codex, Cursor, Perplexity, and Antigravity, verified against each client's current MCP docs. Key findings: a stdio server is reachable only by clients that spawn a local subprocess (Claude Desktop/Code, Codex CLI/IDE/desktop, Cursor, Antigravity, and the Perplexity macOS app via its PerplexityXPC helper); cloud/remote-only surfaces (claude.ai web/mobile, Perplexity web/Windows, Codex Cloud) can't reach localhost and need the hosted imcp2 server — the reason the OAuth layer stays in imcp2. Host-driven OAuth never applies to stdio, and stderr is invisible in chat on every client, so the II login URL is surfaced in-band via an authenticate tool (lazy, non-blocking) plus a best-effort browser auto-open. Adds a capability matrix, per-client registration snippets, the login invariants, and the Perplexity remote OAuth/discovery caveats; updates the login section and open decisions to match. Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_01AqNkpMQiQHzYxC2djTfvBK * Update the scoping doc for the 63-commit rebase onto v0.2.0 Re-verify every claim and file:line reference against the rebased tree and absorb what main already did or changed: - The five vestigial deps (ed25519-dalek, p256, ic-signature-verification, ic-representation-independent-hash, schemars 0.8) were already removed on main (#100) — reframe that stripping work as done. - Account for the new hosted-only surfaces the local split must gate: prometheus + src/metrics.rs (/metrics, #124) and McpConfig's state_dir/require_resource (#144/#127); note the local binary needs no state directory at all. pocket-ic (e2e-only, #76) never enters any closure. - Rewrite §10: production II now serves at /mcp by default (#92), CI probes it (#113), and the PocketIC e2e harness verifies the full connect contract — the remaining unknowns are the local binary's http://127.0.0.1 mixed-content and CORS behavior, and the harness is the plan for testing the local flow. - Prod-instance env overrides are II_URL_PROD/II_CANISTER_ID_PROD (#92); registration chains are also verified client-side against the agent's root key (new_with_root_key); registration_pubkey_b64 is now fallible; AuthStore's dropped fields now include mcp_path and require_resource, and the dropped OAuth side grew RFC 8707/9207 and the bounded DCR store. - Note the crates.io publishing dimension (v0.2.0, tag-guarded trusted publishing, docs/ excluded from the .crate) and re-stamp every stale file:line reference (auth.rs shifted ~500-650 lines; the 13 call-site list and all evidence-index anchors updated). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01AqNkpMQiQHzYxC2djTfvBK * Restructure the design doc to the standard feature-doc shape Reorganize into Summary -> Problem -> Non-goals -> Approach -> Design components -> Implementation Stages (with the verification plan and open decisions under the stages, and the code-evidence index as an appendix). Content is unchanged apart from the connective text: the same components, client matrix, security model, and file:line evidence, now in the house design-doc structure. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01AqNkpMQiQHzYxC2djTfvBK * Add a concise high-level companion to the local-deployment design docs/local-deployment.md is the short, stakeholder-facing overview (same Summary -> Problem -> Non-goals -> Approach -> Design components -> Implementation Stages shape, one altitude up: no file:line evidence or dependency minutiae); the full doc keeps the detail and both docs cross-link. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01AqNkpMQiQHzYxC2djTfvBK * Refer to ICP CLI-spawned local replicas, not dfx Local replicas are spawned by the ICP CLI now; drop the dfx naming from both design docs' non-goals. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01AqNkpMQiQHzYxC2djTfvBK * Make the local-replica mode a test configuration, not a non-goal Talking to an ICP CLI-spawned local replica is a nice-to-have rather than something we rule out: a test build enables it with an explicit IC-endpoint override plus a loopback-guarded fetch_root_key, and the integration tests run imcp2-local in exactly that configuration (against an ICP CLI-spawned replica or PocketIC carrying a deployed II canister). Chains are already verified against the injected agent's root key, so the flow works on a test network. The shipped binary still targets mainnet + production II only. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01AqNkpMQiQHzYxC2djTfvBK * State the no-listening-socket claim precisely "The server has no listening socket" overclaimed: it is true of the MCP tool surface (stdio), but the login handshake necessarily binds a transient loopback listener — II navigates the browser to the callback and fetches the #4091 well-known from the callback's origin, both of which require a real HTTP origin (a custom URI scheme has no origin and II offers no device-grant alternative; this is the RFC 8252 loopback redirect). Scope the trust-boundary claim to the tool surface, note that reaching the login listener confers nothing (static pages; /redeem is state-correlated and only accepts a chain targeting the in-process X), and add the rationale to the login component. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01AqNkpMQiQHzYxC2djTfvBK * Recommend an imcp2-core crate over the hosted feature flag Make the shared components a new imcp2-core library that both binaries build on: imcp2 (unchanged name, lib + hosted binary, OAuth AS, routers, metrics, e2e harness) and imcp2-local depend on it, and imcp2 re-exports core's public items so existing embedders keep compiling. The default-on `hosted` cargo feature is demoted to a rejected alternative: features unify additively, so any crate enabling imcp2/hosted would switch the OAuth/axum closure on for the whole build graph, leaving the minimal-closure claim invocation-dependent; it also needs cfg gates scattered through the code, where the crate boundary states the component split structurally — with the core split the session seam needs no #[cfg] at all (AuthedSession lives in core and the Bearer arm reads http::request::Parts). Cost accepted: imcp2-core becomes a second published crate (family-internal, 0.x, published before imcp2). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01AqNkpMQiQHzYxC2djTfvBK * Make the session-handling component self-contained in the overview The overview's "session seam" bullet leaned on the full doc's jargon (seam, bearer-token lookup, singleton). State the motivation instead: every tool call acts as the user's II session, the hosted server resolves it per request from the OAuth bearer token, the single-user local server reads the one in-memory session from login, and the tool implementations are identical in both. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01AqNkpMQiQHzYxC2djTfvBK * Make the design docs self-contained State the final design plainly instead of narrating how it evolved: drop the rejected-alternative paragraphs and every contrast with superseded drafts ("not a cargo feature", "originally proposed", "since this design's first draft", "the original concern is resolved"), recast the dependency profile per crate as final state, and remove the settled layout item from the open decisions. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01AqNkpMQiQHzYxC2djTfvBK * Drop the local-replica bullet from Non-goals The local-replica test configuration is covered where it belongs (the II wiring component and the verification plan), and the mainnet + production II targeting is already stated in the Approach, so the non-goal bullet added nothing but a hedge. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01AqNkpMQiQHzYxC2djTfvBK * Resolve the login-flow choices like the ICP CLI; add end-user setup UX The login listener is axum and the browser opens via open::that, matching the ICP CLI's web-identity flow (icp identity link web: an axum Router on 127.0.0.1:0 with graceful shutdown; open = "5"), so the two tools behave the same way. Session persistence stays in-memory. With all three choices settled, the open-decisions sections are gone. Add component 9, end-user setup (UX): per-client steps with no JSON or config editing — the double-click .mcpb bundle for Claude Desktop, an Add-to-Cursor install link, one pasted command for Claude Code and Codex, connector UIs for Perplexity (macOS) and Antigravity, an `imcp2-local setup` command that detects installed clients and writes their configs, and the signing/notarization packaging that makes double-click installs work. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01AqNkpMQiQHzYxC2djTfvBK * Add the upgrade story to the end-user setup UX Client registrations point at a stable install path, so an upgrade is an in-place binary swap picked up on the next server start — nothing to re-register and no state to migrate (sessions are in-memory). Distribution and updates follow the ICP CLI: cargo-dist installers with the axoupdater updater shipped alongside, and channel detection that surfaces the right upgrade command (axoupdater receipt / Homebrew / npm). The Claude Desktop bundle upgrades on its own channel by installing the new .mcpb version. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01AqNkpMQiQHzYxC2djTfvBK * Add signing and provenance to the end-user setup component Two layers for two verifiers. OS execution gates: macOS Developer ID + notarization (Gatekeeper is the verifier for browser-downloaded files — including binaries spawned as MCP subprocesses — and accepts only Apple-issued signatures; a bare signed+notarized binary passes, no installer artifact needed) and Windows Authenticode via Azure Trusted Signing or an EV cert. Supply-chain provenance: keyless GitHub artifact attestations on every artifact, verifiable with gh attestation verify. The .mcpb's substance is the signed binary inside (the format specifies no bundle-level signing), with directory listing as the trusted distribution path. Notes which channels bypass the gates (installer script, Homebrew, npm), where the steps hook into the cargo-dist pipeline, and what DFINITY must acquire with lead time. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01AqNkpMQiQHzYxC2djTfvBK * Promote signing and provenance to its own design component Give the signing content top-level visibility as component 10 instead of a block inside the end-user setup component, and mirror it in the overview's component list. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01AqNkpMQiQHzYxC2djTfvBK * Commit to PocketIC as the integration-test dependency Integration tests run imcp2-local's local-replica test configuration against PocketIC carrying a deployed II canister (the pocket-ic dev dependency, reusing the e2e harness's real-II setup). The endpoint override still lets a developer point a test build at any other local replica, but the test plan names one vehicle. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01AqNkpMQiQHzYxC2djTfvBK * Reconcile the dependency and AuthStore claims with the axum decision The login-listener decision (axum, matching the ICP CLI) left three stale claims behind: imcp2-local does depend on axum for its three transient login routes, so say so in the crate-layout bullet, the net dependency list, and the overview, scoping the absence claim to tower-http/prometheus/OAuth and the hosted MCP transport. Also state the AuthStore reality under the crate split: it stays intact in imcp2 (the retained OAuth routes need all of its state), the extracted primitives carry none of it, and the local binary replaces it with a minimal pending-connect state rather than a slimmed copy. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01AqNkpMQiQHzYxC2djTfvBK * docs: address second review round on the local-deployment design - Component 6: rmcp's #[tool_router] is type-level per impl block, so construction mode alone cannot hide tools. Specify that the local-only authenticate/auth_status tools live in their own router that only the local binary composes, with a hosted-side tools/list exclusion test. - Component 7: the Singleton session source holds a shared, replaceable slot rather than a fixed String — the II contract requires a fresh session key after Unauthorized, so re-login must be a same-process step with no client restart. - Sessions wording (both docs): replace the misleading "re-login per run" with the actual lifetime — sign in again after a restart, on grant expiry, or on revocation; note the one-hour grant requested today and the user's consent-time choice of effective TTL. - Verification: PocketIC exercises the protocol, not browser policy, so add a real-browser compatibility gate (automated Chromium/Firefox login run plus a manual Safari/enterprise-policy pass) to Stage 2's login exit criterion. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01AqNkpMQiQHzYxC2djTfvBK * docs: address third review round on the local-deployment design - Component 6: the login tools cannot be an impl block in imcp2-core — they drive the loopback listener and browser opener, which live in imcp2-local, and core cannot call back into its dependent crate. They now live on a small wrapper handler in imcp2-local that merges tools/list and dispatches tools/call to its own router before forwarding to the inner IcTools handler (RequestContext<RoleServer> is handler-independent). Hosted stays login-free by construction, with the tools/list test kept as a regression guard. - Component 1: the crate split is not visibility-neutral — workspace packages share no crate-private access, so the composition API (IcTools/IcTools::new with SessionSource, the Identities registration/redeem entry points, the iiconnect builders) graduates from pub(crate) to core's deliberate public API, re-exported by imcp2; dropped the "kept verbatim" phrasing. - Component 4/5: dropping the redeem's redirect tail breaks the callback page's only success arm (it treats a JSON redirect as success, error otherwise). Specify the second success arm: the local redeem answers {"done": true} and the shared page renders "Signed in — you can close this tab" in place; hosted keeps answering redirect. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01AqNkpMQiQHzYxC2djTfvBK * docs: address fourth review round on the local-deployment design - Dependency isolation: distinguish direct dependencies and linked code from unavoidable transitives. prometheus and the OAuth modules are structurally absent from imcp2-local's graph (it never depends on imcp2), but tower-http still appears deep in the graph as an rmcp/reqwest internal — the guarantee is that the hosted CORS layer is not a dependency, not that the crate name vanishes. Scope the Stage 1 exit criterion the same way. - Versioning: an "internal" 0.x label on imcp2-core cannot exempt items imcp2 re-exports — those are imcp2 public API and breaking them is a breaking change for imcp2 embedders under imcp2's own semver. State that the label relaxes stability only for core-only surface, with the re-export set curated to the pre-split imcp2 API. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01AqNkpMQiQHzYxC2djTfvBK --------- Co-authored-by: Claude <[email protected]>
Summary
Prometheus instrumentation for this crate, usable from the library and not only from the bundled binary, plus a gated
GET /metricsexposition in that binary. Pinned toprometheus = "0.14"(processfeature) — the versiondfinity/icpins, so these series land in the same estate.Complements the status dashboard and #113's off-host probe: those answer "is it up" from outside; this answers "what is it doing" from inside.
Shape
Metrics::newregisters into aRegistryyou supply; exposition stays your job (norender).refresh()recomputes their session gauges whenever the caller decides (exposition path or timer).write_request_metrics(bounded labels) andwrite_request_logs(full path,debuglevel; deployed runtime filters updated so the line survives on hosts).register_process_collectoris separate: un-namespacedprocess_*belongs to the application, so binaries call it and embedders generally don't.Security decisions
/metricsis gated on$MCP_SERVE_METRICS, default off. The bundledDockerfile(a documented PaaS path) has no proxy in front, so a default-on endpoint would be public there. The native host opts in and Caddy answers/metricspublicly with a 404;deploy.shasserts both halves on every deploy (exactly 404 on the public origin, serving on the private one), with--max-timeon every external curl so a stalled origin fails rather than hangs.routeis axum'sMatchedPath(the template, never the requested path; unmatched → oneotherseries),methodis allow-listed to the standard nine. Tested end to end by flooding a real router with distinct paths and extension methods and asserting one series (the method test also pins the histogram bucket count, where a bug does ~14× the damage).ii_instance, notinstance— Prometheus renames a colliding exposedinstancetoexported_instance, so the obvious queries would silently match nothing.Deliberately simple
An earlier revision of this branch enforced stronger runtime invariants (a snapshot collector so a scrape could never observe
active > live, transactional registration with rollback, per-instance summing, serialized refresh). That machinery was out of proportion for observability code and has been removed in favour of documented behaviour:active_sessionsis sampled independently oflive_sessions(the help text says so), registration is not transactional (on error, use a fresh registry), duplicate instance names overwrite. The gauges' failure mode is a one-sample blip, which is what gauges are.Testing
cargo test— 187 pass; clippy clean on the changed files.imcp2's in one caller-owned registry; noprocess_*leakage).MatchedPathandmethod_label-as-pass-through each fail exactly the flood test that claims them; theMCP_SERVE_METRICSgate defaulting on fails its test.Known limitation
nest_service("/mcp", …)means axum omitsMatchedPathbelow the mount, so all MCP tools and OAuth endpoints currently shareroute="other"with scanner noise. InstrumentingMcpServeritself is the fix — deliberately a follow-up.Open question for the reviewer
Does the scraper have a network path to the host's private address on
:8000? Not answerable from this repo: the deploy runs on a GitHub-hosted runner that is not on the VPN, so it verifies the app serves the endpoint (and that the host can reach it off loopback) but not the scraper's ingress. If the answer is no, a blackbox probe of the public/status/api/statusneeds no path at all — and the endpoint stays useful for embedders and local debugging regardless.Generated by Claude Code