@kometolabs/mcp-analytics 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/LICENSE +202 -0
- package/NOTICE +2 -0
- package/OTLP.md +81 -0
- package/README.md +194 -2
- package/dist/analytics.d.ts +172 -0
- package/dist/analytics.d.ts.map +1 -0
- package/dist/analytics.js +799 -0
- package/dist/analytics.js.map +1 -0
- package/dist/cli.d.ts +10 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +72 -0
- package/dist/cli.js.map +1 -0
- package/dist/clients.d.ts +5 -0
- package/dist/clients.d.ts.map +1 -0
- package/dist/clients.js +29 -0
- package/dist/clients.js.map +1 -0
- package/dist/doctor.d.ts +27 -0
- package/dist/doctor.d.ts.map +1 -0
- package/dist/doctor.js +108 -0
- package/dist/doctor.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -0
- package/dist/mcp.d.ts +87 -0
- package/dist/mcp.d.ts.map +1 -0
- package/dist/mcp.js +291 -0
- package/dist/mcp.js.map +1 -0
- package/dist/otlp-protocol.d.ts +10 -0
- package/dist/otlp-protocol.d.ts.map +1 -0
- package/dist/otlp-protocol.js +485 -0
- package/dist/otlp-protocol.js.map +1 -0
- package/dist/otlp.d.ts +24 -0
- package/dist/otlp.d.ts.map +1 -0
- package/dist/otlp.js +174 -0
- package/dist/otlp.js.map +1 -0
- package/package.json +59 -3
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
package/OTLP.md
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
# MCP analytics OTLP event profile v1
|
|
2
|
+
|
|
3
|
+
This profile maps the SDK's fixed analytics schema to standard OTLP LogRecords.
|
|
4
|
+
It supports OTLP/HTTP logs at `/v1/logs`; traces, metrics, arbitrary logs, and
|
|
5
|
+
OTLP/gRPC are outside this receiver's scope. Schema version 1 is independent of
|
|
6
|
+
the npm package version. Unknown schema versions are rejected as a whole batch.
|
|
7
|
+
|
|
8
|
+
## Record envelope
|
|
9
|
+
|
|
10
|
+
`eventName` is one of `mcp_analytics.tool_call`, `mcp_analytics.authorization`, or
|
|
11
|
+
`mcp_analytics.value_completed`. `timeUnixNano` carries the observation timestamp
|
|
12
|
+
as a positive uint64 number of nanoseconds since Unix epoch; JSON uses a decimal
|
|
13
|
+
string. The SDK records tool calls at their start time, after execution settles.
|
|
14
|
+
Canonical storage has millisecond resolution. A LogRecord body must be absent or
|
|
15
|
+
empty. `droppedAttributesCount` must be absent or zero.
|
|
16
|
+
|
|
17
|
+
No trace or span is needed. The exporter does not depend on a global OTel
|
|
18
|
+
provider or tracing sampler. `eventId` is generated once per observation and
|
|
19
|
+
survives retries and Collector forwarding. `(projectId, eventId)` is the storage
|
|
20
|
+
deduplication key; a new MCP invocation is a new observation.
|
|
21
|
+
|
|
22
|
+
## Allowed record attributes
|
|
23
|
+
|
|
24
|
+
| OTLP attribute | Value type | Canonical SDK field / requirement |
|
|
25
|
+
|---|---|---|
|
|
26
|
+
| `mcp_analytics.schema.version` | int | `schemaVersion`, required, exactly 1 |
|
|
27
|
+
| `mcp_analytics.event.id` | string | `eventId`, required UUID |
|
|
28
|
+
| `mcp_analytics.project.id` | string | `projectId`, required, authorized by receiver write key |
|
|
29
|
+
| `mcp_analytics.server.id` | string | `serverId`, required configured alias |
|
|
30
|
+
| `mcp_analytics.environment` | string | `environment`, required configured alias |
|
|
31
|
+
| `gen_ai.tool.name` | string | `toolName`, required for tool calls |
|
|
32
|
+
| `mcp_analytics.outcome` | string | `outcome`: `ok`, `tool_error`, `exception`, `input_required`; tool calls only |
|
|
33
|
+
| `mcp_analytics.duration_ms` | double or int | `durationMs`, finite nonnegative number; tool calls only |
|
|
34
|
+
| `mcp_analytics.user.hash` | string | `subjectHash`, optional 64-character lowercase SHA-256 HMAC |
|
|
35
|
+
| `mcp_analytics.identity.key_version` | string | `identityKeyVersion`, required when subject hash is present |
|
|
36
|
+
| `mcp_analytics.subject.type` | string | `subjectType`: `user`, `account`, `service`; required when subject hash is present |
|
|
37
|
+
| `mcp_analytics.client.application` | string | `clientApplication`, configured alias or `unknown` |
|
|
38
|
+
| `mcp_analytics.source` | string | `sourceTag`, optional configured alias |
|
|
39
|
+
| `mcp_analytics.operation.hash` | string | `operationHash`, optional 64-character lowercase SHA-256 HMAC |
|
|
40
|
+
|
|
41
|
+
Except for the standard `gen_ai.tool.name`, these are custom versioned analytics
|
|
42
|
+
attributes. MCP semantic conventions are still Development; this profile does
|
|
43
|
+
not claim arbitrary MCP spans can supply identity, authorization, or activation.
|
|
44
|
+
Aliases use 1–64 ASCII letters, digits, underscores, dots, or hyphens, starting
|
|
45
|
+
with a letter, digit, or underscore. Configure public aliases locally; do not
|
|
46
|
+
put dynamic user input into tool or dimension names. All three subject fields
|
|
47
|
+
must be present together or absent together. Raw identity and HMAC secrets stay
|
|
48
|
+
inside the application. Authorization and value-completion events have no
|
|
49
|
+
duration or outcome; `toolName` is optional for those milestones.
|
|
50
|
+
|
|
51
|
+
Unknown or repeated record attributes are rejected. Resource/scope attributes,
|
|
52
|
+
trace context, severity, and unknown envelope fields are ignored by ingestion
|
|
53
|
+
and never become canonical analytics data. The SDK exports only this profile
|
|
54
|
+
and its instrumentation scope name; it does not capture arbitrary baggage,
|
|
55
|
+
resource metadata, arguments, responses, errors, credentials, or content.
|
|
56
|
+
|
|
57
|
+
## HTTP and delivery
|
|
58
|
+
|
|
59
|
+
The SDK sends `application/json` with `Authorization: Bearer <write key>` and
|
|
60
|
+
`Accept: application/json`. The receiver accepts JSON and `application/x-protobuf`,
|
|
61
|
+
each optionally gzip-compressed. Responses match the request encoding. Successful
|
|
62
|
+
committed batches receive HTTP 200 with `{}` for JSON or an empty Protobuf message.
|
|
63
|
+
The receiver validates every event and the authorized project before writing;
|
|
64
|
+
it uses whole-batch acceptance, rather than partial success.
|
|
65
|
+
|
|
66
|
+
Receiver defaults are 1 MiB for both compressed and decompressed bodies, 1000
|
|
67
|
+
events per request, 16 concurrent requests, and 4 outstanding writes. The profile
|
|
68
|
+
codecs themselves cap records at 1000. SDK defaults batch 100 records within a
|
|
69
|
+
1000-event/1 MiB queue. A write timeout may still commit later; retries must reuse
|
|
70
|
+
event IDs. Queues are in memory and process termination can lose unflushed data.
|
|
71
|
+
|
|
72
|
+
Collectors must preserve event names, attributes, timestamps, and IDs. Use a
|
|
73
|
+
dedicated logs pipeline without sampling or payload enrichment. The supplied
|
|
74
|
+
Collector configuration uses Protobuf/gzip and disables asynchronous sending
|
|
75
|
+
queues so the downstream result reaches the SDK. A Collector with a queue or
|
|
76
|
+
batch processor can acknowledge before the receiver commits; document that
|
|
77
|
+
different delivery boundary if you choose it.
|
|
78
|
+
|
|
79
|
+
References: [OTLP](https://opentelemetry.io/docs/specs/otlp/),
|
|
80
|
+
[LogRecord model](https://opentelemetry.io/docs/specs/otel/logs/data-model/),
|
|
81
|
+
[MCP conventions](https://github.com/open-telemetry/semantic-conventions-genai/blob/main/docs/gen-ai/mcp.md).
|
package/README.md
CHANGED
|
@@ -1,3 +1,195 @@
|
|
|
1
|
-
#
|
|
1
|
+
# MCP Analytics SDK
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
By [Kometo Labs](https://kometo.co). Part of [MCP Analytics](https://github.com/kometolabs/mcp-analytics#readme).
|
|
4
|
+
|
|
5
|
+
A small Node.js/TypeScript SDK for metadata-only MCP analytics. It has no runtime dependencies and sends OTLP/HTTP logs to your self-hosted analytics receiver. One connection string configures it; the application needs no database driver or database credentials. It does not proxy MCP traffic, change tool schemas, or collect arguments, results, prompts, raw identities, credentials, or error messages.
|
|
6
|
+
|
|
7
|
+
## MCP servers
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { observe } from '@kometolabs/mcp-analytics';
|
|
11
|
+
|
|
12
|
+
const server = observe(new McpServer({ name: 'notes', version: '1.0.0' }));
|
|
13
|
+
server.registerTool('add_note', config, handler); // existing code, unchanged
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
MCP_ANALYTICS_URL=https://<write-key>@analytics.example.com/<project-id>
|
|
18
|
+
MCP_ANALYTICS_IDENTITY_SECRET=<at least 32 bytes> # optional: enables user metrics
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
`observe(server, options?)` works with the MCP TypeScript SDK v2 (`@modelcontextprotocol/server`) and v1 (`@modelcontextprotocol/sdk`). It patches `registerTool` (and v1's `tool()`) on that server instance only, never the class, and returns the same server. It adds nothing to tool schemas and registers no tools. Call it before registering tools; tools registered earlier are not recorded, and a one-time stderr line says so. Renames and callback replacements through the returned tool handle's `update()` are followed.
|
|
22
|
+
|
|
23
|
+
Each registered tool name is written once and added to the tool allowlist; it is a static code name, not client input. A name outside the alias rule is still observed and recorded as `__unknown_tool__`. The client label comes from the request's `io.modelcontextprotocol/clientInfo` metadata (MCP 2026-07-28), or from the initialize handshake on older connections. It is self-reported and passes through the client allowlist.
|
|
24
|
+
|
|
25
|
+
**Users.** `user: (ctx) => ...` returns a plain user ID (namespaced by the project) or a full `Subject`, sync or async. Use verified claims only, never a token:
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
observe(server, { user: (ctx) => ctx.http?.authInfo?.extra?.sub }); // SDK v2
|
|
29
|
+
observe(server, { user: (extra) => extra.authInfo?.extra?.sub }); // SDK v1
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
When an identity secret is configured and `user` is not given, the verified `authInfo.extra.sub` is used automatically, namespaced by `authInfo.extra.iss` when present. `authInfo` exists only after the MCP SDK verified a bearer token. `user: false` turns this off. Without a secret, no user is recorded and nothing warns.
|
|
33
|
+
|
|
34
|
+
**Other options.** `context: (ctx) => ({ sourceTag, ... })` supplies or overrides other safe fields. Any `createAnalytics` option (below) can be passed too. `analytics: createAnalytics(...)` records through your own instance instead of the shared one.
|
|
35
|
+
|
|
36
|
+
**Never throws.** Missing or invalid configuration disables analytics: the server is returned unpatched and one stderr line names the field, never its value, for example `MCP analytics disabled: MCP_ANALYTICS_URL is not set`. Each distinct line is printed once per process. `strict: true` or `MCP_ANALYTICS_STRICT=1` (for CI) throws instead.
|
|
37
|
+
|
|
38
|
+
**Per-request servers.** `observe()` reuses one process-wide instance for the same configuration, so servers created per request (for example by `createMcpHandler`) share one queue and keep batching. Pass function options, such as `onDiagnostic`, as the same function every time.
|
|
39
|
+
|
|
40
|
+
**Shutdown.** With a single server, closing it flushes queued events. Per-request servers rely on the one-second flush. When the event loop drains (for example when a stdio client closes stdin), every instance `observe()` created is closed, bounded by `flushTimeoutMs`. No signal handlers are installed: in a server that exits on a signal, call `await closeAnalytics()` before exiting.
|
|
41
|
+
|
|
42
|
+
**See it working.** `npx @kometolabs/mcp-analytics doctor` checks the configuration, the identity secret, the receiver's health, the write key, and the project, using an empty batch that writes no data (`--env-file FILE`, `--url URL`, `--json`; exit code 1 on a failed check). Its codes are explained in the repository's [troubleshooting guide](../../docs/troubleshooting.md). `MCP_ANALYTICS_DEBUG=1` (or `debug: true`) prints one stderr line per recorded event and delivery result, never values:
|
|
43
|
+
|
|
44
|
+
```text
|
|
45
|
+
mcp-analytics: tool_call add_note ok 3.2 ms client=claude user=4be1a8c09d2f
|
|
46
|
+
mcp-analytics: sent 1 event
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
A complete small stdio server is in the repository's [`examples/minimal-server`](../../examples/minimal-server/README.md).
|
|
50
|
+
|
|
51
|
+
## Other execution boundaries
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
import { createAnalytics } from '@kometolabs/mcp-analytics';
|
|
55
|
+
|
|
56
|
+
// Reads MCP_ANALYTICS_URL and the other MCP_ANALYTICS_* variables; explicit
|
|
57
|
+
// options win. Unlike observe(), createAnalytics throws on invalid configuration.
|
|
58
|
+
const analytics = createAnalytics({
|
|
59
|
+
serverId: 'demo-server',
|
|
60
|
+
tools: ['search', 'create_report'],
|
|
61
|
+
sources: ['directory'],
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
// Add this at an existing tool dispatcher or execution boundary.
|
|
65
|
+
const result = await analytics.observeTool('search', () => handleSearch(input), {
|
|
66
|
+
subject: { issuer: 'my-auth-provider', tenant: 'workspace', id: authenticatedUser.id },
|
|
67
|
+
clientApplication: 'claude-ai', // a reported name; recorded as `claude`
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
// Optional application milestones use the same identity mapping.
|
|
71
|
+
analytics.recordMilestone('authorization', {
|
|
72
|
+
subject: { issuer: 'my-auth-provider', tenant: 'workspace', id: authenticatedUser.id },
|
|
73
|
+
clientApplication: 'claude',
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
// After in-flight application work settles, flush during graceful shutdown.
|
|
77
|
+
await analytics.close({ timeoutMs: 5000 });
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
The example references the host application's `handleSearch`, `input`, and `authenticatedUser`; the SDK does not supply or inspect those application objects. Pass only the displayed safe context, not the request or authentication token.
|
|
81
|
+
|
|
82
|
+
`subject` may also be a plain user ID string, hashed in the project's namespace as `{ issuer: <project>, id, type: 'user' }`. Context can also be a function, sync or async: `observeTool('search', handler, async () => ({ subject: await lookUpSubject() }))`. It is resolved while the handler runs, and the tool result never waits for it. Synchronous fields are copied when the call starts. A resolver that throws, rejects, or returns invalid data drops only that event (`invalid_context`); one that never settles produces no event. `occurredAt` is always the call start.
|
|
83
|
+
|
|
84
|
+
## Configuration
|
|
85
|
+
|
|
86
|
+
One connection string configures delivery: `MCP_ANALYTICS_URL=https://<write-key>@<host>[:port][/base-path]/<project-id>` (or the `url` option). The SDK derives the OTLP endpoint (`<origin><base-path>/v1/logs`), the write key, and the project from it, and removes the credentials before any request: the key travels only in the `Authorization` header. A key containing `/` must be percent-encoded (`%2F`). The receiver still checks both the key and the project.
|
|
87
|
+
|
|
88
|
+
| Setting | Source, first match wins | Default |
|
|
89
|
+
|---|---|---|
|
|
90
|
+
| endpoint, write key, project | `endpoint` / `writeKey` / `projectId` option, connection string, `MCP_ANALYTICS_ENDPOINT` / `_WRITE_KEY` / `_PROJECT_ID` | required |
|
|
91
|
+
| `serverId` | option, `MCP_ANALYTICS_SERVER_ID` | `default` (set it when a project has several servers) |
|
|
92
|
+
| `environment` | option, `MCP_ANALYTICS_ENVIRONMENT`, `NODE_ENV` | `production` |
|
|
93
|
+
| `identitySecret` | option, `MCP_ANALYTICS_IDENTITY_SECRET` | none: no user metrics |
|
|
94
|
+
| `clients` | option | the built-in families below |
|
|
95
|
+
| `debug` | option, `MCP_ANALYTICS_DEBUG` | off |
|
|
96
|
+
|
|
97
|
+
An empty variable counts as unset. The `env` option replaces `process.env` for these lookups, mainly in tests. With a custom `sink`, the connection string, endpoint, and write-key variables are ignored.
|
|
98
|
+
|
|
99
|
+
`endpoint` may be the receiver's base URL; `/v1/logs` is appended unless the path already ends with it. `createOtlpSink` applies the same rule.
|
|
100
|
+
|
|
101
|
+
Invalid configuration makes `createAnalytics` throw `Invalid analytics configuration: <field> <rule>` (or `Invalid OTLP configuration: ...`) naming only the first failing field and rule, never its value. List entries are named by index (`clients[1] ...`). When a value came from an environment variable, the message names the variable. `observe()` prints the same text instead of throwing.
|
|
102
|
+
|
|
103
|
+
`identitySecret` and `tools` are optional. Without a secret, events omit subject and operation hashes, so they count in usage totals but not in user metrics; `identity_unavailable` is reported only when a subject or operation ID was supplied. Without `tools`, every tool name is recorded as `__unknown_tool__` with an `unknown_tool` diagnostic, unless `observe()` or `allowTools` adds it.
|
|
104
|
+
|
|
105
|
+
**Clients.** By default the SDK records these families (exported as `DEFAULT_CLIENTS`) and maps the names their applications report, ignoring case:
|
|
106
|
+
|
|
107
|
+
| Label | Also matches |
|
|
108
|
+
|---|---|
|
|
109
|
+
| `claude` | `claude-ai` (Claude Desktop), `Anthropic/ClaudeAI`, `Claude Desktop`, `claude.ai` |
|
|
110
|
+
| `claude-code` | `Claude Code` |
|
|
111
|
+
| `chatgpt` | `openai-mcp` |
|
|
112
|
+
| `cursor` | `cursor-vscode` |
|
|
113
|
+
| `vscode` | `Visual Studio Code`, `Visual Studio Code - Insiders`, `github-copilot-developer` |
|
|
114
|
+
| `windsurf` | `windsurf-client` |
|
|
115
|
+
| `codex` | `codex-mcp-client` |
|
|
116
|
+
| `gemini` | `gemini-cli`, `gemini-cli-mcp-client` |
|
|
117
|
+
| `zed`, `cline`, `goose` | their own names |
|
|
118
|
+
|
|
119
|
+
The reported names come from observed traffic collected by the community MCP client registry. They are self-reported and unverified, and clients can change them. Everything else is recorded as `unknown` with an `unknown_client` diagnostic, so arbitrary names never enter telemetry. An explicit `clients` list replaces the defaults but keeps the reported names of any built-in family it lists; `clientAliases` maps further names (keys matched ignoring case) to configured clients and may override a built-in name. An alias that names an unconfigured client, or conflicts with another explicit entry, is a configuration error. Labels longer than 256 characters become `unknown`. An explicit `unknown` raises no diagnostic. `MCP_ANALYTICS_DEBUG=1` shows the label each call received.
|
|
120
|
+
|
|
121
|
+
`observeTool` preserves the handler's returned value or thrown value. It records `isError: true` as a tool error, and `resultType: 'input_required'` as an intermediate outcome. It sees the chosen execution boundary only; it cannot infer client timeouts, full conversations, OAuth grants, or business completion from a successful tool call.
|
|
122
|
+
|
|
123
|
+
`recordMilestone('value_completed', context, { toolName: 'create_report' })` can record an explicit application completion when a tool merely starts asynchronous work. `operationId` in context is optional and HMAC-hashed locally for correlation.
|
|
124
|
+
|
|
125
|
+
## Identity and collection contract
|
|
126
|
+
|
|
127
|
+
Use a persistent, customer-held identity secret of at least 32 UTF-8 bytes. The SDK computes HMAC-SHA-256 over a canonical tuple containing project, subject type, issuer, tenant, and subject ID. It exports only `subjectHash`, `subjectType`, and `identityKeyVersion` (default `v1`). Different projects, identity secrets, or subject namespaces yield different hashes. Rotation breaks identity continuity; keep historical key versions available for local deletion-hash calculations.
|
|
128
|
+
|
|
129
|
+
`hashSubject(secret, projectId, subject)` is exported for deletion tools and synthetic fixtures. Hashes are pseudonymous, not anonymous. Do not use credential/token hashes as identities.
|
|
130
|
+
|
|
131
|
+
Project, server, environment, key-version, tool, client, and source aliases must be 1-64 ASCII letters, digits, underscores, dots, or hyphens. Configure only public, non-sensitive aliases. Unknown tool names become `__unknown_tool__`; unknown client names become `unknown`; unrecognized source tags are omitted. This prevents arbitrary incoming names from entering telemetry.
|
|
132
|
+
|
|
133
|
+
`validateEvent(unknown)` validates and copies the fixed schema, rejects unknown properties/accessors and incomplete identity fields, and returns an immutable event. Errors contain no submitted values. Persistence adapters should validate independently before writing.
|
|
134
|
+
|
|
135
|
+
## Delivery and shutdown
|
|
136
|
+
|
|
137
|
+
The default queue holds at most 1,000 events or 1 MiB, batching at most 100 records. A one-second unreferenced timer flushes in the background. Tool calls do not wait for sink I/O. Set `flushIntervalMs: 0` for explicit-only delivery. Each flush sends the events queued up to its latest call; events arriving during a write wait for the next flush, so continuous load produces full batches rather than a stream of tiny requests.
|
|
138
|
+
|
|
139
|
+
Network errors and HTTP 429/502/503/504 are retried with bounded exponential delays, honoring `Retry-After`, up to three retries and a 30-second queue lifetime by default. Retries reuse the same immutable event IDs. Other HTTP errors, redirects, invalid acknowledgments, and partial rejection are permanent delivery failures. A partially accepted batch is never retransmitted; `dropped` counts the entire unconfirmed batch because OTLP does not identify which individual events were rejected. Response bodies and error messages never enter diagnostics. Write keys are never forwarded on redirects. Only one actual sink write may be outstanding, including after a timeout; a hung sink cannot create an unlimited sequence of overlapping requests.
|
|
140
|
+
|
|
141
|
+
The SDK exports JSON OTLP/HTTP logs and expects a JSON OTLP acknowledgment. The receiver also accepts Protobuf/gzip from an existing Collector. Events are independent of trace sampling. See the shipped [OTLP event profile](OTLP.md) for names, types, limits, and compatibility boundaries. Use HTTPS outside a trusted local deployment.
|
|
142
|
+
|
|
143
|
+
`flush({ timeoutMs })` waits within its deadline and resolves even if records remain pending. Inspect `getStats()` for `queued`, `queuedBytes`, `sent`, `dropped`, `retries`, `sinkErrors`, `unknownTools`, and `unknownClients`. `close({ timeoutMs })` stops accepting telemetry, stops the timer, attempts a flush, and discards any records still queued when that attempt ends. It is idempotent.
|
|
144
|
+
|
|
145
|
+
`sinkErrors` counts rejected delivery attempts and delivery waits that reach
|
|
146
|
+
the attempt's own `sinkTimeoutMs`, once per attempt. Reaching a shorter caller-supplied flush
|
|
147
|
+
deadline leaves the write pending and does not count as a delivery error.
|
|
148
|
+
Repeated flushes retain the original attempt's sink deadline and never start
|
|
149
|
+
an overlapping write.
|
|
150
|
+
|
|
151
|
+
## Diagnostics
|
|
152
|
+
|
|
153
|
+
`onDiagnostic: ({ code, events, status? }) => { ... }` receives delivery and configuration signals asynchronously, outside the tool path. Errors it throws are ignored. Diagnostics contain only a code, an event count, and an HTTP status where one was received: never submitted values, identities, tool names, or response bodies.
|
|
154
|
+
|
|
155
|
+
| Code | Meaning |
|
|
156
|
+
|---|---|
|
|
157
|
+
| `authentication_failed` | HTTP 401: check the write key. |
|
|
158
|
+
| `project_rejected` | HTTP 403: the receiver is configured for another project. |
|
|
159
|
+
| `delivery_rejected` | Another permanent rejection (other HTTP errors, redirects, invalid or partial acknowledgments); the batch was discarded. |
|
|
160
|
+
| `delivery_failed` | Retries or the queue lifetime were exhausted. |
|
|
161
|
+
| `queue_full` | The bounded queue had no room. |
|
|
162
|
+
| `unknown_tool` | A tool name outside the allowlist was recorded as `__unknown_tool__`. |
|
|
163
|
+
| `unknown_client` | A client label outside `clients` was recorded as `unknown`. |
|
|
164
|
+
| `invalid_context` | A context resolver failed or returned invalid data; the event was dropped. |
|
|
165
|
+
| `identity_unavailable` | No identity secret; subject and operation hashes were omitted. |
|
|
166
|
+
| `closed` | Telemetry after `close`, or events still queued when `close` ended. |
|
|
167
|
+
|
|
168
|
+
Without `onDiagnostic`, the SDK emits one `process.emitWarning` per instance for each configuration-class code (`authentication_failed`, `project_rejected`, `delivery_rejected`, `unknown_tool`, `invalid_context`, `identity_unavailable`), with warning codes such as `MCP_ANALYTICS_AUTHENTICATION_FAILED`. Transient failures do not warn. Pass `onDiagnostic: () => {}` to silence the warnings.
|
|
169
|
+
|
|
170
|
+
## Options
|
|
171
|
+
|
|
172
|
+
Defaults and tunable options:
|
|
173
|
+
|
|
174
|
+
| Option | Default |
|
|
175
|
+
|---|---:|
|
|
176
|
+
| `maxQueueEvents` | 1,000 |
|
|
177
|
+
| `maxQueueBytes` | 1,048,576 |
|
|
178
|
+
| `batchSize` | 100 |
|
|
179
|
+
| `flushIntervalMs` | 1,000 |
|
|
180
|
+
| `maxRetries` | 3 |
|
|
181
|
+
| `retryDelayMs` | 100 |
|
|
182
|
+
| `maxRetryAgeMs` | 30,000 |
|
|
183
|
+
| `sinkTimeoutMs` | 2,000 |
|
|
184
|
+
| `requestTimeoutMs` | `sinkTimeoutMs` |
|
|
185
|
+
| `flushTimeoutMs` | 5,000 |
|
|
186
|
+
|
|
187
|
+
Delivery is best effort before sink acknowledgment. Process termination can lose buffered records. A timed-out sink may still finish and commit; `dropped` measures client-side discard decisions, not proven missing database rows. Stable event IDs and idempotent storage handle ambiguous delivery. This SDK is not a billing meter or a durable queue.
|
|
188
|
+
|
|
189
|
+
Call `close` after the application's in-flight tools finish. Node serverless runtimes require an explicit supported lifecycle/flush integration; they are outside this release's long-lived Node profile.
|
|
190
|
+
|
|
191
|
+
## Advanced direct sinks
|
|
192
|
+
|
|
193
|
+
Tests and existing storage integrations can supply `sink: async (events) => { ... }` instead of `endpoint` and `writeKey`. These configurations are mutually exclusive. Persist the whole validated batch atomically, resolve only after commit, and deduplicate on `(projectId, eventId)`. A custom sink rejection uses the bounded retry policy; it must not log original application data or credentials.
|
|
194
|
+
|
|
195
|
+
`createOtlpSink({ endpoint, writeKey, timeoutMs?, fetch? })` exposes validated OTLP delivery as an explicit sink. The `/otlp` subpath exports the profile codecs for server-side ingestion and interoperability checks; applications normally need only `observe` or `createAnalytics`.
|