@kometolabs/mcp-analytics-receiver 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/Dockerfile ADDED
@@ -0,0 +1,47 @@
1
+ # Build context: the repository root.
2
+ # docker build -f packages/receiver/Dockerfile -t mcp-analytics-receiver .
3
+ # Targets: `receiver` (default; the published image) and `demo` (the synthetic
4
+ # demo's seed and MCP server, used by the repository's Compose demo profile).
5
+
6
+ # Node, pinned by digest so a re-pushed tag cannot change what gets built.
7
+ # Bump the tag and digest together (docker buildx imagetools inspect <tag>).
8
+ ARG NODE_IMAGE=node:26.13.1-alpine3.24@sha256:6bd9ab43c0ec0190ca7b2d193906cb8b7edf6e7f4afa43ddeccd6452710bffb5
9
+
10
+ FROM ${NODE_IMAGE} AS build
11
+ WORKDIR /src
12
+ # pnpm's official Alpine build, pinned by digest (the Node image ships no
13
+ # corepack). Keep the tag equal to packageManager in package.json.
14
+ COPY --from=ghcr.io/pnpm/pnpm:12.23.0-alpine@sha256:f0acb1f42d79e8221951554858d4474f3a48f4e287f612ad8bfd4ed874b4ab12 /opt/pnpm /opt/pnpm
15
+ RUN ln -s /opt/pnpm/pnpm /usr/local/bin/pnpm
16
+ COPY package.json pnpm-lock.yaml pnpm-workspace.yaml tsconfig.base.json ./
17
+ COPY packages ./packages
18
+ COPY examples ./examples
19
+ COPY sql ./sql
20
+ COPY grafana ./grafana
21
+ RUN pnpm install --frozen-lockfile --ignore-scripts
22
+ RUN pnpm -r build
23
+ # The receiver's published files and its production dependencies at the
24
+ # versions pnpm-lock.yaml pins, with the SDK copied in as a regular package.
25
+ RUN pnpm --filter @kometolabs/mcp-analytics-receiver deploy --prod --ignore-scripts /deploy \
26
+ && chmod +x /deploy/dist/cli.js /deploy/dist/admin.js
27
+
28
+ # The synthetic demo runs from the workspace build.
29
+ FROM build AS demo
30
+ ENV NODE_ENV=production DEMO_HOST=0.0.0.0
31
+ USER node
32
+ EXPOSE 4318
33
+ CMD ["node", "examples/demo/dist/cli.js", "serve"]
34
+
35
+ # The receiver as the npm package ships it, with exactly the dependency
36
+ # versions the workspace was tested with; nothing is resolved at image build
37
+ # time. Both bins are on PATH: mcp-analytics-receiver (the default command)
38
+ # and mcp-analytics-admin.
39
+ FROM ${NODE_IMAGE} AS receiver
40
+ WORKDIR /app
41
+ COPY --from=build /deploy /app
42
+ RUN ln -s /app/dist/cli.js /usr/local/bin/mcp-analytics-receiver \
43
+ && ln -s /app/dist/admin.js /usr/local/bin/mcp-analytics-admin
44
+ ENV NODE_ENV=production MCP_ANALYTICS_HOST=0.0.0.0 MCP_ANALYTICS_PORT=4318 PATH=/app/node_modules/.bin:$PATH
45
+ USER node
46
+ EXPOSE 4318
47
+ CMD ["mcp-analytics-receiver"]
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,2 @@
1
+ MCP Analytics
2
+ Copyright 2026 Kometo Labs & Konstantin Komelin
package/README.md CHANGED
@@ -1,3 +1,345 @@
1
- # Temporary Holding Version
1
+ # MCP Analytics backend
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ By [Kometo Labs](https://kometo.co). Part of [MCP Analytics](https://github.com/kometolabs/mcp-analytics#readme).
4
+
5
+ The self-hosted side of [`@kometolabs/mcp-analytics`](../sdk/README.md): an
6
+ OTLP/HTTP receiver, PostgreSQL storage and schema, the `mcp-analytics-admin`
7
+ CLI, and a deployment generator. Applications only need the SDK and one
8
+ connection string; database credentials stay here.
9
+
10
+ ## Install a backend
11
+
12
+ ```sh
13
+ npx @kometolabs/mcp-analytics-receiver init my-analytics
14
+ cd my-analytics && docker compose up -d
15
+ ```
16
+
17
+ `init` writes three things into the directory and prints the two settings the
18
+ MCP server needs (`MCP_ANALYTICS_URL` and `MCP_ANALYTICS_IDENTITY_SECRET`) and
19
+ the Grafana login:
20
+
21
+ - `compose.yaml`: PostgreSQL 18, a one-shot `migrate` service
22
+ (`mcp-analytics-admin migrate`: schema, roles, and the writer and reader
23
+ passwords), the receiver, Grafana with the provisioned analytics page, and a
24
+ one-shot `grafana-setup` that creates the Viewer account. The receiver and
25
+ Grafana wait for `migrate`.
26
+ - `grafana/`: the datasource and dashboard provisioning and the Viewer setup script.
27
+ - `.env` (mode 600): the receiver image, the project, a fresh write key and
28
+ identity secret, random passwords for PostgreSQL (owner, writer, reader) and
29
+ Grafana (admin, viewer), and the host bindings.
30
+
31
+ Options: `--project P` (default: the directory name), `--public-url URL` (where
32
+ applications reach the receiver, used in the printed connection string; default
33
+ `http://localhost:4319`), `--image IMAGE` (default:
34
+ `ghcr.io/kometolabs/mcp-analytics-receiver:<this version>`).
35
+
36
+ Both commands are safe to rerun. `init` never overwrites `.env`, so the
37
+ database passwords stay valid, and leaves `compose.yaml` and `grafana/` alone
38
+ unless `--force` is given (use it after upgrading the package to refresh the
39
+ templates). `docker compose up -d` reruns the idempotent migration.
40
+
41
+ Every port is published on `127.0.0.1` by default. Before applications on other
42
+ hosts can send events, put an HTTPS reverse proxy in front of the receiver (and
43
+ Grafana), or set `MCP_ANALYTICS_BIND` / `GRAFANA_BIND` in `.env`, and set
44
+ `MCP_ANALYTICS_PUBLIC_URL` to the public address. The value action, which the
45
+ page shows as "Not configured" until it is set, is a later step:
46
+
47
+ ```sh
48
+ docker compose run --rm migrate mcp-analytics-admin configure \
49
+ --project my-analytics --server default --environment production --value-tool create_report
50
+ ```
51
+
52
+ ### Container image
53
+
54
+ `ghcr.io/kometolabs/mcp-analytics-receiver` installs the packed SDK and receiver
55
+ with their production dependencies. Both bins are on `PATH`; the default command
56
+ is `mcp-analytics-receiver`, and `mcp-analytics-admin` runs the owner tasks.
57
+ Build it locally from the repository root with
58
+ `docker build -f packages/receiver/Dockerfile -t mcp-analytics-receiver .` and
59
+ pass `--image mcp-analytics-receiver` to `init`. The same Dockerfile has a
60
+ `demo` target for the repository's synthetic demo.
61
+
62
+ ## In-process handler
63
+
64
+ The public handler is also usable in-process:
65
+
66
+ ```ts
67
+ import { createOtlpHandler } from '@kometolabs/mcp-analytics-receiver';
68
+
69
+ const handler = createOtlpHandler({
70
+ projectId: 'my-product',
71
+ writeKey: process.env.MCP_ANALYTICS_WRITE_KEY!,
72
+ sink: internalStorageSink,
73
+ });
74
+ const response = await handler(request);
75
+ ```
76
+
77
+ `internalStorageSink` resolves only after the batch commits. The supplied CLI
78
+ creates this sink with the PostgreSQL adapter. The handler validates the whole
79
+ batch and its authorized project before calling it. PostgreSQL's
80
+ `(project_id, event_id)` uniqueness makes ambiguous retries idempotent.
81
+
82
+ An optional `onResult({ status, events })` callback runs after every non-health
83
+ request, including 404/405 and busy responses. It receives only the HTTP status
84
+ and the event count; errors it throws are ignored.
85
+
86
+ ## HTTP interface
87
+
88
+ - `POST /v1/logs`: `Authorization: Bearer <write key>`, with `application/json`
89
+ or `application/x-protobuf`. Both encodings accept `Content-Encoding: gzip`.
90
+ A successful committed batch returns HTTP 200 and the matching empty OTLP
91
+ response. This service returns whole-batch success or failure, not partial
92
+ acceptance.
93
+ - `GET /health`: a bounded database health check in the CLI. It does not expose
94
+ connection details or require the write key.
95
+
96
+ The receiver implements MCP Analytics' documented analytics profile, rather than
97
+ arbitrary application logs or trace/metric ingestion. It discards resource/scope
98
+ metadata and validates decoded events with the SDK's canonical schema. Unknown
99
+ record attributes and payload bodies are rejected. It never logs request bodies,
100
+ keys, or raw storage errors.
101
+
102
+ Defaults limit compressed and decompressed bodies to 1 MiB, events to 1000 per
103
+ request, simultaneous requests to 16, and simultaneous sink writes to 4. Body
104
+ reads have a 10-second deadline and writes a 5-second deadline. A timed-out write
105
+ continues to hold its slot until the underlying operation settles, so repeating
106
+ requests cannot accumulate unlimited hung writes. A late write can still commit;
107
+ clients retry with the same event IDs. Errors return sanitized OTLP statuses;
108
+ storage failures and overload return 503 with `Retry-After: 1`.
109
+
110
+ ## Receiver configuration
111
+
112
+ The package installs two commands: `mcp-analytics-receiver` (this service, plus
113
+ `init`) and `mcp-analytics-admin` (owner tasks, below). In this repository,
114
+ build the workspace and run `node packages/receiver/dist/cli.js`. Configure the
115
+ receiver with:
116
+
117
+ - `MCP_ANALYTICS_WRITE_KEY`: required visible ASCII token of at least 16 characters.
118
+ Use an alphanumeric/base64url token, as `init` generates: it travels in the
119
+ user part of the SDK's connection string.
120
+ - `MCP_ANALYTICS_PROJECT_ID`: required authorized project (1-64 letters, digits,
121
+ underscores, dots, or hyphens). Compose supplies `demo` for the synthetic demo.
122
+ - `MCP_ANALYTICS_DATABASE_URL`: optional PostgreSQL URL. `DATABASE_URL` is a fallback;
123
+ otherwise standard `PGHOST`, `PGPORT`, `PGDATABASE`, `PGUSER`, and `PGPASSWORD`
124
+ configure the pool. Compose uses separate variables so special characters in
125
+ passwords do not need URI encoding.
126
+ - `MCP_ANALYTICS_HOST`: default `127.0.0.1`; the supplied Docker image uses `0.0.0.0`
127
+ inside its container.
128
+ - `MCP_ANALYTICS_PORT`: default 4318. Compose exposes localhost 4319 to avoid the demo
129
+ MCP server's existing 4318 port.
130
+
131
+ Startup fails with a message naming each missing or invalid variable
132
+ (`MCP_ANALYTICS_PROJECT_ID`, `MCP_ANALYTICS_WRITE_KEY`, `MCP_ANALYTICS_PORT`, `MCP_ANALYTICS_HOST`,
133
+ the database URL, or `PGPORT`); values are never echoed.
134
+
135
+ The CLI logs the first rejected request of each HTTP status at once, then a
136
+ per-minute summary of later rejections, and a final summary on shutdown. Each
137
+ line has the status, a count, and a short hint (for example 401 "check the write
138
+ key", 403 "check MCP_ANALYTICS_PROJECT_ID and the sender projectId"). Request bodies,
139
+ keys, and event values are never logged.
140
+
141
+ The receiver uses a restricted writer role and assumes the owner has applied
142
+ the schema and grants with `mcp-analytics-admin migrate`. It never migrates with
143
+ writer credentials. Both Compose files run `migrate` as a one-shot service
144
+ before the receiver starts.
145
+
146
+ In this repository, `docker compose up -d receiver` builds and starts it (with
147
+ PostgreSQL and the migration). To run the CLI on the host alongside the MCP
148
+ demo, use `MCP_ANALYTICS_PORT=4319 pnpm receiver:serve`; the copied `.env`
149
+ supplies its database and write-key configuration. Both modes use the
150
+ restricted `mcp_writer` role.
151
+
152
+ An existing OpenTelemetry Collector can forward the analytics event stream to
153
+ `/v1/logs` with the matching write key and project. Both JSON and Protobuf are
154
+ supported, including the Collector's usual Protobuf/gzip output. Preserve event
155
+ attributes and event names. Never sample away user/milestone history needed by
156
+ the adoption queries.
157
+
158
+ The supplied [Collector setup](../../otel/README.md) and optional Compose profile
159
+ provide a pinned forwarding configuration. The complete event-name/attribute
160
+ mapping is documented in the SDK's [OTLP profile](../sdk/OTLP.md).
161
+
162
+ ## PostgreSQL storage
163
+
164
+ The `./postgres` subpath, with `./schema.sql` and `./roles.sql`, is the storage layer the receiver uses.
165
+
166
+ `createPostgresSink` provides server-side persistence for the OTLP receiver and
167
+ advanced direct integrations. It accepts an operator-owned query function and
168
+ does not open a connection or keep credentials. Ordinary applications use the
169
+ SDK's connection string instead.
170
+
171
+ ```ts
172
+ import { createPostgresSink } from '@kometolabs/mcp-analytics-receiver/postgres';
173
+
174
+ const sink = createPostgresSink((text, values) => pool.query(text, values));
175
+ // Pass sink to createAnalytics from @kometolabs/mcp-analytics.
176
+ ```
177
+
178
+ Apply the schema and roles as the database owner, most simply with
179
+ `mcp-analytics-admin migrate` (or `migrateSchema` below). A batch uses one parameterized
180
+ INSERT and resolves after its transaction commits when the supplied connection is
181
+ in autocommit mode. If the application supplies a connection already inside a
182
+ transaction, it owns that transaction's commit and must not treat the sink's
183
+ resolution as a durable commit. Prefer a pool-level autocommit query callback.
184
+
185
+ Packed installations include the same SQL assets under the public
186
+ `@kometolabs/mcp-analytics-receiver/schema.sql` and
187
+ `@kometolabs/mcp-analytics-receiver/roles.sql` exports. Operators can locate and read
188
+ them without knowing the package's directory layout:
189
+
190
+ ```ts
191
+ import { readFile } from 'node:fs/promises';
192
+ const schema = await readFile(new URL(import.meta.resolve('@kometolabs/mcp-analytics-receiver/schema.sql')), 'utf8');
193
+ await operatorPool.query(schema);
194
+ ```
195
+
196
+ `pnpm test:packages` verifies the packed dependency metadata, clean TypeScript
197
+ and runtime imports, byte-for-byte inclusion of these SQL files, and the
198
+ `LICENSE` and `NOTICE` files.
199
+
200
+ `(project_id, event_id)` uniqueness makes repeated delivery idempotent. Tool
201
+ requests retried by an MCP client remain separate observations with separate IDs.
202
+ All events are validated before the statement executes, so a malformed event
203
+ rejects the entire batch without a partial insert. Driver errors are replaced
204
+ with generic messages to avoid accidentally forwarding sensitive parameters.
205
+
206
+ A cohort starts at the subject's earliest retained authorization or tool call,
207
+ which also freezes its client/source; an authorization wins only on an equal
208
+ timestamp, so a later grant never re-dates a cohort. Cohorts are separated by
209
+ project, server, environment, identity key version, and subject type.
210
+ Tool-call entries within `existing_user_days` (default 14, 0-365) of the start
211
+ of retained identified history in that scope are labelled `existing`: users
212
+ already active at installation, after a retention purge, or after key rotation.
213
+ They are excluded from adoption metrics. Keep `existing_user_days + 7` below
214
+ the raw-event retention period, or no first-observed cohort can mature.
215
+
216
+ There is no default value action. Each project/server/environment needs a
217
+ `project_settings` row with `value_tool` (successful calls of that tool) or
218
+ `value_mode = 'application'` (explicit `value_completed` events); create it with
219
+ `mcp-analytics-admin configure` or `configureDataset`. Without a row, value
220
+ metrics are unavailable rather than zero. The definition is immutable within a
221
+ dataset: both refuse to change it, and only `existing_user_days` can be updated.
222
+ Create a new server/environment key for a changed definition.
223
+ Seven-day activation and week-two retention are half-open windows.
224
+
225
+ Reports call `mcp_analytics.subject_cohorts_at(cutoff, projects, servers,
226
+ environments, started_from)` with their exclusive range end (capped at now),
227
+ the selected datasets as text arrays, and the range start. Entry and milestones
228
+ use only events before the cutoff, so later events cannot rewrite an earlier
229
+ report. Dataset filters never change how a cohort is classified;
230
+ `started_from` limits which cohorts get activation and return lookups, while
231
+ earlier entries still define the start of history. Every argument is required:
232
+ a NULL returns no rows. The one-argument `subject_cohorts_at(cutoff)` and the
233
+ `subject_cohorts` view (current time) return every dataset. Grafana separately
234
+ excludes incomplete activation and retention observation windows.
235
+
236
+ `sql/002-roles.sql` creates two NOLOGIN roles and grants only the needed
237
+ permissions. `mcp-analytics-admin migrate` enables login when given passwords. The reader can query the
238
+ approved views (`grafana_events`, `grafana_settings`, `subject_cohorts`) and
239
+ execute both cohort functions, cannot query base tables, and cannot write. The
240
+ functions return only the approved cohort columns, have a fixed search path, and
241
+ revoke default PUBLIC execution. The writer can
242
+ insert events and read only conflict-key columns. It cannot alter settings or
243
+ delete events. Neither role should own the schema or be a superuser.
244
+
245
+ Reapply both SQL files when upgrading an existing installation. The schema file
246
+ converges an earlier alpha schema without deleting events: it removes the old
247
+ value-action default, adds `existing_user_days`, and recreates changed cohort
248
+ functions; the roles file restores the reader grants. The schema file records
249
+ its version (currently 2; the first, unversioned alpha counts as 1) in the
250
+ one-row `mcp_analytics.schema_info` table, which neither role can read, and
251
+ refuses to run over a newer schema. `mcp-analytics-admin migrate` and the demo's
252
+ `pnpm demo:migrate` apply both files in one transaction. Independent dashboard-value checks and the
253
+ hand-calculated fixture ledger are described in the repository's
254
+ `docs/dashboard-reconciliation.md`.
255
+
256
+ Operators use `purgeEventsBefore(query, cutoff)` for retention and
257
+ `deleteSubjectEvents(query, { projectId, subjectHash, identityKeyVersion? })` for
258
+ deletion. Both need an owner/operator connection and resolve to the number of
259
+ deleted events when the driver reports it (`rowCount` in `pg`).
260
+ `mcp-analytics-admin` wraps them as `retention` and `forget-subject`. Stop new collection and drain
261
+ or discard outstanding SDK batches before deleting a subject, otherwise a late
262
+ retry can reinsert an old event. Views contain no stored rollups and reflect
263
+ deletion immediately. Backup expiry and restoring deletion records remain
264
+ operator responsibilities.
265
+
266
+ ### Owner operations
267
+
268
+ These take a query function on one owner session (`client.query`, not a pool),
269
+ because `migrateSchema` runs a transaction.
270
+
271
+ ```ts
272
+ import { configureDataset, migrateSchema, readSchemaVersion } from '@kometolabs/mcp-analytics-receiver/postgres';
273
+
274
+ const query = (text, values) => client.query(text, values);
275
+ await migrateSchema(query); // { from: 1, to: 2 }; null for a new database
276
+ await migrateSchema(query, { writer: writerPassword, reader: readerPassword }); // also enables login
277
+ await configureDataset(query, { projectId: 'my-product', serverId: 'docs-mcp',
278
+ environment: 'production', mode: 'tool', valueTool: 'create_report' });
279
+ await readSchemaVersion(query); // 2
280
+ ```
281
+
282
+ `configureDataset` resolves to `created`, `unchanged`, or `updated` (only the
283
+ existing-user window changed) and throws `DefinitionChangeError` for a different
284
+ value definition. `SCHEMA_VERSION` is the version the packaged schema file
285
+ installs.
286
+
287
+ ## Admin CLI
288
+
289
+ `mcp-analytics-admin` connects as the database owner with `MCP_ANALYTICS_ADMIN_DATABASE_URL`
290
+ or the standard `PG*` variables, on one session. It prints neither credentials
291
+ nor event data; database errors become a generic message. Help and argument
292
+ errors need no database. Exit codes: 0 success, 1 failure, 2 usage error.
293
+
294
+ ```sh
295
+ mcp-analytics-admin migrate
296
+ mcp-analytics-admin configure --project my-product --server docs-mcp --environment production \
297
+ --value-tool create_report # or --application; [--existing-user-days 14]
298
+ mcp-analytics-admin retention --days 30
299
+ mcp-analytics-admin forget-subject --project my-product --subject-hash <64 hex> >> deletions.jsonl
300
+ mcp-analytics-admin reapply-deletions deletions.jsonl # after restoring a backup
301
+ ```
302
+
303
+ - `migrate` applies the packaged schema and roles in one transaction, reports
304
+ the schema version (for example `version 2 (was 1)`), and refuses a newer
305
+ schema. Roles are created NOLOGIN. With `MCP_ANALYTICS_WRITER_PASSWORD` or
306
+ `MCP_ANALYTICS_READER_PASSWORD` set, it also enables login for `mcp_writer` or
307
+ `mcp_reader` with that password, in the same transaction; PostgreSQL quotes
308
+ the value server-side and it is never printed. Rerunning with a new value
309
+ rotates the password.
310
+ - `configure` creates a dataset's value definition. A definition cannot change;
311
+ rerunning with the same one is harmless, and only `--existing-user-days` (0-365,
312
+ default 14) can be updated. It warns when that window plus the 7-day activation
313
+ window reaches `--retention-days` (default 30), because no first-observed cohort
314
+ could then complete activation before its events are purged.
315
+ - `retention` deletes events older than `--days` (default 30). It is not
316
+ scheduled; run it from your own scheduler.
317
+ - `forget-subject` deletes one user's events in a project, optionally only for
318
+ `--key-version`. With `--issuer I --id ID [--tenant T] [--type user|account|service]`
319
+ instead of `--subject-hash`, it hashes the identity with
320
+ `MCP_ANALYTICS_IDENTITY_SECRET`, exactly as the SDK does. It writes one JSON
321
+ deletion record to stdout, containing only the project, the hash, the key
322
+ version, and the time, and its summary to stderr. Keep the records with your
323
+ backups.
324
+ - `reapply-deletions` replays saved records after a restore. It checks every line
325
+ before deleting anything.
326
+
327
+ Stop collection and let outstanding SDK batches settle before deleting a
328
+ subject, or a late retry can reinsert an event. The same commands are available
329
+ in-process as `runAdmin(argv, { query })` from `@kometolabs/mcp-analytics-receiver/admin`;
330
+ `pnpm demo:migrate` and `pnpm demo:retention` use it. In a deployment made by
331
+ `init`, run them in the image: `docker compose run --rm migrate mcp-analytics-admin <command>`.
332
+
333
+ ## Verification
334
+
335
+ `pnpm test:packages` packs this package, installs it offline in a clean project
336
+ with its dependencies, and runs both commands, including `init`. `pnpm test:init`
337
+ builds the image, runs `init` and `docker compose up` in a temporary directory,
338
+ sends events with the printed connection string, reads them back through
339
+ Grafana as the Viewer, and checks that rerunning both commands keeps `.env` and
340
+ the data. `pnpm test:demo` runs `docker compose --profile demo up -d` without a
341
+ `.env`. `pnpm test:deployment` builds and
342
+ starts a separate Compose project with random localhost ports and disposable
343
+ volumes. It exercises the real Collector, PostgreSQL, service restarts, SDK
344
+ shutdown, every admin command (including deletion reapplication on a restored
345
+ backup), and Grafana provisioning, then removes its own resources.
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env node
2
+ import { type OwnerQuery } from './postgres.js';
3
+ export declare const ADMIN_USAGE = "Usage: mcp-analytics-admin <command> [options]\n\nConnects as the analytics database owner using MCP_ANALYTICS_ADMIN_DATABASE_URL or the\nstandard PG* variables. Credentials and event data are never printed.\n\nCommands:\n migrate\n Apply the schema and roles in one transaction (safe to rerun). With\n MCP_ANALYTICS_WRITER_PASSWORD or MCP_ANALYTICS_READER_PASSWORD set, also\n enable login for mcp_writer (receiver) or mcp_reader (Grafana) with that\n password; rerunning with a new value rotates it.\n configure --project P --server S --environment E (--value-tool T | --application)\n [--existing-user-days N] [--retention-days N]\n Create a dataset's value definition. A definition cannot change later;\n only the existing-user window (default 14 days) can.\n retention [--days N]\n Delete events older than N days (default 30).\n forget-subject --project P (--subject-hash H | --issuer I [--tenant T] --id ID [--type T])\n [--key-version V]\n Delete one user's events. The --issuer form hashes the identity with\n MCP_ANALYTICS_IDENTITY_SECRET. Prints a JSON deletion record on stdout: keep\n it to reapply the deletion after restoring a backup.\n reapply-deletions FILE\n Reapply saved deletion records (one JSON object per line).\n";
4
+ /** Shown to the operator as is; never contains configuration values. */
5
+ export declare class AdminUsageError extends Error {
6
+ constructor(message: string);
7
+ }
8
+ export interface AdminIo {
9
+ query: OwnerQuery;
10
+ env?: NodeJS.ProcessEnv;
11
+ stdout?: (line: string) => void;
12
+ stderr?: (line: string) => void;
13
+ readFile?: (path: string) => Promise<string>;
14
+ now?: () => Date;
15
+ }
16
+ /** Runs one admin command and resolves to the process exit code. */
17
+ export declare function runAdmin(argv: readonly string[], io: AdminIo): Promise<number>;