Skip to content
1 change: 1 addition & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
# CLAUDE.md

Guidance for Claude Code / AI agents working in this repo. **This file is loaded into every session — keep it lean.** It is orientation + behavior only; detailed reference lives in `docs/`.
Expand Down Expand Up @@ -146,6 +146,7 @@
- **Windows installer**: [docs/github-actions-windows-wix-research.md](docs/github-actions-windows-wix-research.md). **Prerelease** (`next` branch + `v*-rc.*` tags, opt-in, off stable channels): [docs/prerelease-builds.md](docs/prerelease-builds.md).

## Recent Changes
- 126-day-two-activation (PR-A): Go 1.26, backend + docs — telemetry schema 17, instrumentation only (no onboarding, UI or API change). Install anchor: `storage.EnsureInstallAnchor` (own bucket `install_anchor`, written once in `runtime.New` after the Spec 080 shutdown marker and Spec 123 OAuth boot sweep, before any other startup write, only when `config.db` held no record other than `meta/schema_version` at open, `BoltDB.WasEmptyAtOpen`; never from onboarding writes; recorded with telemetry off; read once per process for both `day_two` and `window_age`). `upstream_outcomes {succeeded, unusable, succeeded_non_starter, coverage, window_age}` (`internal/telemetry/upstream_outcomes.go`): one outcome per LOGICAL call that dispatched (dispatch counts requests), begun right after `noteUpstreamDispatched` and deferred (`upstreamOutcome` in `internal/server/mcp_upstream_telemetry.go`) on the wrapper, direct routing and `code_execution` sub-calls, guarded by an AST test; part of the drained window (retries byte-identical); `coverage` from the persisted `outcome_window_undelivered` marker (`outcome_window.go`: set by the first outcome after start or a Drain, cleared after a 2xx only if nothing was counted since that drain, both under the outcome window's own mutex, never `deliveryMu`), `window_age` = install age when the window opened (start or Drain), `install_origin: fresh` personal only. `day_two {install_origin, install_age, success_scope_ever}` personal only (`day_two.go`: UTC calendar-date buckets; `success_scope.go` forward-only ordinal in the activation bucket). `runtime.StarterClassifier` (default false, `SetStarterClassifier` for PR-B) + `Runtime.RecordUpstreamOutcome`. `ScanForPII` closed-object rule `day_two_field_invalid`. Docs: `docs/features/telemetry.md` "Schema v17". **No new dependencies.**
- 125-skills-over-mcp (PR-3): Go 1.26, backend + CLI + docs — approved skills reach agents through three read-only built-ins, registered only while `enable_skills` is on (`MCPProxyServer.RefreshSkillsAvailability`: default registry, call-tool, code-execution and direct surfaces; never `/mcp/s/<server>`, never from `code_execution`): `retrieve_skills(query, limit)`, `load_skill(id, offset, limit, version)`, `read_skill_file(id, path, offset, limit, version)` (`internal/server/mcp_skills.go`). Everything comes from the approved copy through `Runtime.AvailableSkill` / `AvailableSkillFile` / `SearchAvailableSkills` (`internal/runtime/skills_agent.go`); one refusal `skill not found: <id>` for every unavailable reason; reach = `resolveActiveProfileWithSource` → `serverInScope`, tool policy not applied. Search: memory-only Bleve in `internal/skills/index`, one index per reach, every match re-checked against its record. Paging: parts of ≤60,000 bytes with `Version:` in the header. Output policy (`mcp_skills_output.go`): block/redact/strip on the whole file before paging, also on names, descriptions and file names; skills build a detector when a policy is switched on after start. Activity type `skill_access` (administrator-only, like `skill_quarantine_change`). Scoped REST: `GET /api/v1/servers/{id}/skills{,/content}` answer an agent token with available skills from the approved copy through the same policy. Records of skills a listing did not name are bounded (200 per server). Docs: `docs/features/skills.md` "Skills for agents". **No new dependencies.**
- 125-skills-over-mcp (PR-2): Go 1.26, backend + CLI + docs — the skills approval gate, still administrator-only and offered to no agent. `decideSkill` (`internal/runtime/skills_quarantine.go`) is the whole status rule: `manual` holds new and changed skills, `scan` approves a new skill only on a clean and complete scan and always holds a changed one, `auto` / `quarantine_enabled:false` approve; a hash equal to the approved one restores approved; `Blocked` survives everything. Scan (`skills_scan.go`): every text file in ≤48 KiB chunks through `ScanToolMetadataVerdict`, after the reads and outside the upstream timeout, 45 s per refresh with follow-up refreshes, 1 MiB and 2 min per skill (`size_cap` / `time_limit` are kept, `coverage` is retried), result bound to the content hash. Review-bound decisions (`skills_approval.go`): `ApproveSkillsReviewedAt` (expected hash per skill + incarnation, whole request refused with nothing written) and `SetSkillsBlockedAt`, records-only writes (`storage.UpdateSkillApprovals`). REST `POST /api/v1/servers/{id}/skills/approve|block|unblock` (409 `review_out_of_date` / `server_replaced`, 422 `skill_unusable`), CLI `mcpproxy skills approve|block|unblock`, `skills show --diff`. Activity type `skill_quarantine_change` is administrator-only on every activity read door and on SSE (`storage.IsAdminOnlyActivityType`). Docs: `docs/features/skills.md` "Reviewing skills". **No new dependencies.**
- 125-skills-over-mcp (PR-1): Go 1.26, backend + docs — opt-in Skills over MCP (`enable_skills`, per-server `expose_skills`), visible to administrators only and offered to no agent yet. New leaf `internal/skills` (wire types, `skill://` URI rules, digest + frontmatter verification, `sk1-` content hash); upstream reads through raw `skills/list` / `skills/get` + `ReadResource` with a per-request response limit (`internal/transport/response_limit.go`); bbolt buckets `skill_approvals` + `skill_files` are in the purge set; runtime catalog (`internal/runtime/skills_catalog.go`: single-flight refresh, budgets, capture-ordered apply); admin-only REST `GET /api/v1/servers/{id}/skills{,/content}` and `POST …/skills/refresh` (scoped tokens get 403 before any runtime call; `skills.changed` SSE is dropped for scoped callers); CLI `mcpproxy skills list|show|refresh`. Docs: `docs/features/skills.md`. **No new dependencies.**
Expand Down
55 changes: 54 additions & 1 deletion docs/features/telemetry.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ MCPProxy collects anonymous usage statistics to help improve the product. This p

## What is collected

MCPProxy sends a **daily heartbeat** containing only aggregate, non-identifying information. The current schema is **version 16** (`schema_version: 16` in the JSON payload); the schema is forward-compatible so older consumers simply ignore fields they don't recognize.
MCPProxy sends a **daily heartbeat** containing only aggregate, non-identifying information. The current schema is **version 17** (`schema_version: 17` in the JSON payload); the schema is forward-compatible so older consumers simply ignore fields they don't recognize. A field counts only on heartbeats whose `schema_version` introduced it: before that version it is **not measured**, never zero or false (see [Coverage](#coverage-a-field-counts-only-from-its-schema-version)).

| Field | Example | Purpose |
|-------|---------|---------|
Expand Down Expand Up @@ -47,6 +47,8 @@ MCPProxy sends a **daily heartbeat** containing only aggregate, non-identifying
| `feature_flags.idp_provider` | `none` | The configured identity-provider **family** for server-edition SSO (schema v13) — fixed enum `google` / `github` / `microsoft` / `oidc` / `none`. The kind only: never the issuer URL, tenant, client id or display name. `none` when the block is disabled or unset |
| `member_count_bucket` | `1-10` | Number of server-edition user accounts, bucketed (schema v13) — fixed enum `0` / `1-10` / `11-100` / `101-1000` / `1000+`. `0` on the personal edition (no counter is installed); omitted only when the counter fails. A count only, never an identity. (Named `member_…`, not `user_…`: the anonymity scanner blocks the home-dir basename as a substring of the whole payload, and `user` is the username of every `USER user` container image) |
| `env_markers.is_container` | `true` | Unchanged in v13; read together with the fields above to see how server-edition installs are deployed |
| `upstream_outcomes` | `{"succeeded":"1-10","unusable":"0","succeeded_non_starter":"1-10","coverage":"full","window_age":"d0_6"}` | Completed upstream calls in this counter window, by outcome (schema v17). Bucket labels, a coverage flag and the install age when the window opened — never a name or a timestamp. Both editions; `window_age` only on a fresh personal install. See [Schema v17](#schema-v17--dispatch-vs-completion-and-install-cohorts-spec-126) |
| `day_two` | `{"install_origin":"fresh","install_age":"d7_13","success_scope_ever":"non_starter"}` | Install origin, install age bucket and lifetime success scope (schema v17). Closed enums only; personal edition only. See [Schema v17](#schema-v17--dispatch-vs-completion-and-install-cohorts-spec-126) |
| `preflight` | `{"filter_diag_emitted_24h":3,"availability_block_24h":2,"availability_block_reasons_24h":{"server_quarantined":2},"discovery_omission_24h":5}` | Preflight baseline counters (issue #969) — counts only, reason map keyed by a fixed enum. Omitted entirely when nothing was counted. See below |

The `server_protocol_counts` map uses a **fixed enum of keys** (`stdio`, `http`, `sse`, `streamable_http`, `auto`) — server names and URLs are never included. Unknown or misconfigured protocol values are bucketed into `auto`.
Expand Down Expand Up @@ -265,6 +267,57 @@ Five reset-on-accept counters count the refresh lifecycle (the daily check of th

**What is deliberately absent.** The bundle's age, `generated_at`, the last-checked and last-activated times, the next-check time, the fetch URL and host, refusal reasons and digests are never transmitted. The freshness view ("how old is the bundle in the fleet") is computed on the receiver by joining `bundle_sequence` against the release timeline, not reported by the client. The anonymity scanner rejects any `tpa_scanner` key outside the whitelist, and the five counters above must be non-negative integers (strings, negatives and floats block the heartbeat). With telemetry disabled (`MCPPROXY_TELEMETRY=false`, `DO_NOT_TRACK`, the CLI or config opt-out) none of these keys, and no `tpa_scanner` object, is sent.

## Schema v17 — dispatch vs completion, and install cohorts (Spec 126)

Schema v17 is instrumentation only: it adds two objects and changes nothing else. They exist so that new installs can be followed from their first week to their second, and so that "an upstream was called" and "an upstream call worked" are never inferred from each other.

### Dispatch vs completion

Two instruments now sit side by side, and they count different things:

| Instrument | Since | Counts | Unit |
|-----------|-------|--------|------|
| `upstream_tool_call_count_bucket` | v14 | **Dispatches**: requests the core client handed to the transport | Requests. A request repeated after an upstream session was re-initialized counts twice |
| `upstream_outcomes` | v17 | **Completions**: logical calls that dispatched at least one request, by outcome | Logical calls. The same session-recovery repeat is one call and one outcome |

A logical call is one `call_tool_*` call, one direct-routing call, or one `code_execution` sub-call. A call refused before dispatch (validation, quarantine, a profile or policy, a disconnected server, the concurrency limiter, a moved connection generation) records neither a dispatch nor an outcome. An operator replaying a stored call from the REST API or Web UI records neither.

### `upstream_outcomes` (both editions)

A reset-on-accept counter window, like `upstream_tool_call_count_bucket`: it is part of the window keyed by `heartbeat_id`, frozen until an accepted (2xx) heartbeat, and a retry of an undelivered window re-sends it byte-identical. Calls made while a send is being retried go to the next window.

| Field | Values | Meaning |
|-------|--------|---------|
| `upstream_outcomes.succeeded` | `0` / `1-10` / `11-100` / `101-1000` / `1000+` | Logical calls with a **usable** result: no error, no `isError: true` answer, and not withheld by an output policy (output sanitisation or output-schema validation). The same predicate as `activation.first_real_tool_call_ever` |
| `upstream_outcomes.unusable` | same buckets | Logical calls that dispatched but ended without a usable result: a transport or upstream error, `isError: true`, or a result an output policy withheld |
| `upstream_outcomes.succeeded_non_starter` | same buckets | The subset of `succeeded` that is not on the starter server. No starter exists yet, so it equals `succeeded`; the field is sent anyway so the instrument stays the same when one ships |
| `upstream_outcomes.coverage` | `full` / `partial` | `full` when the counts cover the whole time since the previous accepted heartbeat. `partial` for the first window of a process whose predecessor left recorded outcomes undelivered, and once for the first schema-17 start of an install whose `install_origin` is `existing`. A local marker tracks this: the first outcome after process start, or after each window is detached for sending, sets it; an accepted heartbeat (the shutdown flush included) clears it only when no outcome was recorded after that heartbeat's window was detached (a send detaches its window when it starts, so calls made while it is in flight are still unsent when it is accepted). A fresh install, and a plain restart after a delivered window, are `full` |
| `upstream_outcomes.window_age` | `d0_6` / `d7_13` / `d14_plus` | The install age (as `day_two.install_age` below) at the moment the window **opened**: process start, or the moment the previous window was detached for sending. Present only when `day_two.install_origin` is `fresh`; never next to `existing`, and always absent on the server edition. The install anchor is read once per process, so `day_two` and `window_age` always agree. Frozen with the window, so a retry carries the age it opened at |

### `day_two` (personal edition only)

State, read fresh at every heartbeat build; it is not part of the counter window. Omitted on the server edition.

| Field | Values | Meaning |
|-------|--------|---------|
| `day_two.install_origin` | `fresh` / `existing` | `fresh` when the local data store holds an **install anchor**: a UTC time written once, right after the data store opens at startup, only when `config.db` held no prior data when it was opened (no file, an empty file, or no record in any bucket other than the schema version every open writes). An install upgraded from a build without the anchor has none and reports `existing`; it is never counted as a new install. The anchor is recorded whatever the telemetry setting and is never sent — only the buckets derived from it are |
| `day_two.install_age` | `d0_6` / `d7_13` / `d14_plus` | The difference in **UTC calendar dates** between the anchor's date and the date the heartbeat is built (constant within one UTC date). A negative difference (clock skew) counts as `d0_6`. Present only when `install_origin` is `fresh` |
| `day_two.success_scope_ever` | `none` / `starter_only` / `non_starter` | Whether this install ever got a usable upstream result, and where. Persisted locally, recorded whatever the telemetry setting, and moves forward only (`none` → `starter_only` → `non_starter`). On an `existing` install it covers the time since the upgrade |

`days_since_install` (v7) is unchanged, but it is not a cohort key: it is stamped on the first telemetry-enabled heartbeat, so it cannot tell an upgrade or a late opt-in from a new install. Use `install_origin` and `install_age` for cohorts.

**Privacy.** Both objects carry closed enums and bucket labels only: no server or tool name, path, timestamp, free text or new identifier. The anonymity scanner treats them as closed objects and blocks the heartbeat on an unknown key, an out-of-enum value, a non-string value, a nested object, a `window_age` next to `install_origin: existing`, or an `install_age` that does not match the origin; the violation never echoes the offending key or value. With telemetry disabled nothing is sent; the anchor and `success_scope_ever` are still recorded locally.

### Coverage: a field counts only from its schema version

A field is measured only on heartbeats with `schema_version >=` the version that introduced it. When a heartbeat is older, the field is **not measured** — do not read its absence as `false`, `0` or `none`. For the day-two questions that means:

- no `install_origin` / `install_age` below v17 (fall back to the first heartbeat date, and say so);
- no completion counts below v17 (only dispatch-based activity, v14 and later, can be measured, and it is reported under that name);
- `coverage: partial` windows are reported as their own gap, not silently merged.

Later onboarding fields (the starter, second-client and summary fields) each ship with the release that produces them, at the next free schema version, and follow the same rule.

## Preflight baseline counters (issue #969)

The `preflight` sub-object measures two things the proxy currently does silently:
Expand Down
21 changes: 21 additions & 0 deletions internal/runtime/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,13 @@ type Runtime struct {
refreshManager *oauth.RefreshManager // Proactive OAuth token refresh
updateChecker *updatecheck.Checker // Background version checking
telemetryService *telemetry.Service // Anonymous usage telemetry (Spec 036)
// starterClassifier decides starter-ness of a (server, incarnation) for the
// schema-17 completion counters (Spec 126 FR-037). nil: the default, which
// answers false. See upstream_outcome.go.
starterClassifier atomic.Pointer[starterClassifierHolder]
// successScopeReached caches the success_scope_ever ordinal this process
// has persisted, so RecordUpstreamOutcome skips the store once reached.
successScopeReached atomic.Uint32

// bundleRefresher is the TPA bundle refresh scheduler (Spec 087 / Spec 101
// US3 B19), registered by the server and started in
Expand Down Expand Up @@ -541,6 +548,16 @@ func New(cfg *config.Config, cfgPath string, logger *zap.Logger) (*Runtime, erro
zap.String("key_id", oauthTokenKey.ID()), zap.Int("sealed_plaintext_rows", sealed))
}

// Spec 126 FR-033: record the install anchor right after the shutdown
// marker (Spec 080 FR-010 keeps that the first DB operation) and the
// Spec 123 OAuth boot sweep, and before every other startup write, before
// telemetry is wired (SetTelemetry reads the anchor once, for day_two and
// window_age) and before the HTTP server and MCP initialisation. Emptiness
// was decided when the store opened, so those earlier writes cannot change
// it; an early write only shrinks the window in which a crash would leave
// a new store without an anchor. Whatever the telemetry opt-out setting.
ensureInstallAnchor(storageManager, logger)

// Close any stale sessions from previous runs
if err := storageManager.CloseAllActiveSessions(); err != nil {
logger.Warn("Failed to close stale sessions on startup", zap.Error(err))
Expand Down Expand Up @@ -4287,6 +4304,10 @@ func (r *Runtime) SetTelemetry(version, edition string) {
if err := funnelStore.RecordActivity(db, time.Now().UTC()); err != nil {
r.logger.Debug("Failed to record funnel activity at startup", zap.Error(err))
}

// Spec 126 (schema 17): install anchor provider for day_two and
// window_age, and the first counter window's coverage.
r.wireDayTwoTelemetry()
}
}

Expand Down
Loading
Loading