@armature-tech/mcp-analytics 0.6.13 → 0.6.14

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.
Files changed (2) hide show
  1. package/README.md +188 -90
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -1,147 +1,245 @@
1
- # @armature-tech/mcp-analytics
1
+ # Armature MCP Analytics for TypeScript
2
2
 
3
- [Armature](https://armature.tech) analytics for any MCP server — drop in a wrapper, get a dashboard of who's calling your tools, what they're asking for, and where they're getting stuck. On Armature you can see:
3
+ Understand which MCP tools agents use, what users are trying to accomplish, and where calls fail—without building an observability pipeline.
4
4
 
5
- - Who your users are and which tools they actually use
6
- - What agents are *trying* to accomplish (user intent, agent thinking, frustration captured per call)
7
- - Where tools fail, time out, or get retried
8
- - Cross-server activity for the same user, even across vendors
5
+ [![npm version](https://img.shields.io/npm/v/%40armature-tech%2Fmcp-analytics?label=npm)](https://www.npmjs.com/package/@armature-tech/mcp-analytics)
6
+ [![CI](https://github.com/armature-tech/mcp-analytics/actions/workflows/ci.yml/badge.svg)](https://github.com/armature-tech/mcp-analytics/actions/workflows/ci.yml)
7
+ [![Apache 2.0](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE)
9
8
 
10
- All this without rolling your own logging pipeline, schema, or auth.
9
+ [Dashboard](https://app.armature.tech) · [Python SDK](https://github.com/armature-tech/mcp-analytics-python) · [Go SDK](https://github.com/armature-tech/mcp-analytics-go) · [Agent install](SKILL.md)
11
10
 
12
- ## Getting Started
11
+ ## Install in 30 seconds
13
12
 
14
- **Cloud:** sign in at [app.armature.tech](https://app.armature.tech), create a server, copy the API key.
13
+ ### 1. Install
15
14
 
16
- **Install the SDK** in your MCP server repo:
15
+ ~~~bash
16
+ npm install @armature-tech/mcp-analytics @modelcontextprotocol/sdk@^1.29.0 zod
17
+ ~~~
17
18
 
18
- ```sh
19
- npm install @armature-tech/mcp-analytics @modelcontextprotocol/sdk zod
20
- ```
19
+ MCP SDK 1.29 or newer is required when your tools use Zod 4 raw-shape
20
+ schemas. MCP SDK 1.20 accepts the package but silently drops fields from those
21
+ schemas, including Armature's telemetry field.
21
22
 
22
- **Wrap your server** (the most common shape — an existing `McpServer` factory):
23
+ ### 2. Add your ingest key
23
24
 
24
- ```ts
25
+ Create a server in the [Armature dashboard](https://app.armature.tech), copy its ingest key, and add it to your environment:
26
+
27
+ ~~~bash
28
+ export ANALYTICS_INGEST_API_KEY="..."
29
+ ~~~
30
+
31
+ ### 3. Instrument your MCP server
32
+
33
+ Wrap the factory that creates your existing **McpServer**:
34
+
35
+ ~~~ts
25
36
  import { createMcpAnalyticsServer } from "@armature-tech/mcp-analytics";
26
- import { createMyMcpServer } from "./my-mcp-server.js";
37
+ import { createMyMcpServer } from "./server.js";
27
38
 
28
- const server = createMcpAnalyticsServer(() => createMyMcpServer(), {
29
- armature: {
30
- endpointUrl: "https://app.armature.tech/api/mcp-analytics/ingest",
31
- apiKey: process.env.ANALYTICS_INGEST_API_KEY,
39
+ const server = createMcpAnalyticsServer(createMyMcpServer);
40
+ ~~~
41
+
42
+ > **That’s it. Make one tool call, open Armature, and the session is already there.**
43
+
44
+ ## Built for MCP—not page views
45
+
46
+ | Understand demand | Find what breaks | Improve with context |
47
+ | --- | --- | --- |
48
+ | See which tools and use cases people actually need. | Surface failures, retries, latency, and dead ends. | Connect every call to user intent and agent reasoning. |
49
+
50
+ No custom event schema. No logging pipeline. No changes to your tool handlers.
51
+
52
+ ## What you see in Armature
53
+
54
+ - Complete MCP sessions and client attribution
55
+ - The user intent behind each session
56
+ - Every tool called by the agent
57
+ - Input and output previews, latency, and outcome
58
+ - Failures, timeouts, and repeated retries
59
+ - Cross-server activity for the same actor
60
+
61
+ ## How it works
62
+
63
+ Armature instruments the boundary around every tool call:
64
+
65
+ 1. The SDK adds an optional **telemetry** block to the tool’s input schema.
66
+ 2. The agent can attach user intent, reasoning, and frustration to the call.
67
+ 3. The SDK removes telemetry before your handler receives the arguments.
68
+ 4. Timing, outcome, and truncated previews are sent to your dashboard.
69
+
70
+ ~~~json
71
+ {
72
+ "telemetry": {
73
+ "user_turn": 1,
74
+ "user_intent": "Check whether the customer's last payment succeeded",
75
+ "agent_thinking": "The payment lookup tool provides the requested status",
76
+ "user_frustration": "low"
77
+ }
78
+ }
79
+ ~~~
80
+
81
+ All telemetry fields are optional. The earlier **intent**, **context**, and **frustration_level** names remain accepted for clients with cached schemas.
82
+
83
+ > **Privacy:** Armature is observability, not authentication. Keep your existing MCP authentication and authorization in place. Do not put secrets in tool arguments or telemetry fields.
84
+
85
+ ## Choose the integration that matches your server
86
+
87
+ | Server shape | Integration |
88
+ | --- | --- |
89
+ | Existing **McpServer** factory | **createMcpAnalyticsServer(factory, config)** |
90
+ | Existing server and tool registry | **instrumentMcpServerTools(...)** |
91
+ | Custom registry or JSON-RPC dispatcher | **createAnalyticsRecorder(...)** |
92
+ | Mastra tool map | **wrapMastraTools(...)** |
93
+ | Stateless HTTP or serverless | **resolveStatelessHttpSession(...)** |
94
+
95
+ ### Existing server and tool registry
96
+
97
+ Use **instrumentMcpServerTools** when you own an existing server instance and a registry of tool definitions:
98
+
99
+ ~~~ts
100
+ instrumentMcpServerTools({
101
+ server,
102
+ tools,
103
+ config: {
104
+ armature: {
105
+ delivery: "await",
106
+ },
32
107
  },
108
+ mapTool,
33
109
  });
34
- ```
110
+ ~~~
35
111
 
36
- That's it. Every tool registered inside your factory is now instrumented. Open the dashboard and the first tool call shows up.
112
+ This path registers tools directly and works with package layouts where wrapping the server factory is not a fit.
37
113
 
38
- > Don't want to wire it up yourself? Ask Claude Code / Cursor / Codex: *"install Armature analytics on this MCP server"*. From your MCP server repo, run `npx --yes skills add armature-tech/mcp-analytics` first so the agent picks up our [integration playbook](SKILL.md) — it detects which of the four shapes your repo uses and edits the right files.
114
+ ### Custom dispatcher
39
115
 
40
- ## Why mcp-analytics
116
+ Use the recorder when you manage **tools/list** and **tools/call** yourself:
41
117
 
42
- **1) Generic analytics don't understand MCP.**
118
+ ~~~ts
119
+ import { createAnalyticsRecorder } from "@armature-tech/mcp-analytics";
43
120
 
44
- An MCP tool call has structure that page-view analytics throws away: the tool name, the args the agent constructed, whether the call succeeded, what the agent was *trying to do*. You want those as first-class fields, not buried in custom dimensions.
121
+ const analytics = createAnalyticsRecorder({
122
+ armature: {
123
+ delivery: "await",
124
+ },
125
+ });
45
126
 
46
- **2) Instrumenting by hand is the same boilerplate every time.**
127
+ analytics.tool(toolDefinition, toolHandler);
47
128
 
48
- Decorate input schemas, strip telemetry fields before the handler runs, time the call, batch, retry, dedupe sessions, propagate auth. Every MCP server reinvents it. This package is that boilerplate, packaged once.
129
+ // tools/list
130
+ const tools = analytics.toolDefinitions();
49
131
 
50
- **3) The agent should be able to tell you what it's doing.**
132
+ // tools/call
133
+ const result = await analytics.dispatch(name, args, context);
134
+ ~~~
51
135
 
52
- We add a `telemetry` object to each tool's input schema with `user_turn`, `user_intent`, `agent_thinking`, and `user_frustration`. Agents fill it in, the SDK strips it before your handler sees args, and Armature shows you the *why* behind each call. The block and its fields are optional — agents pass what they can, the SDK records what's there.
136
+ ### Mastra
53
137
 
54
- ## How it works
138
+ ~~~ts
139
+ import { wrapMastraTools } from "@armature-tech/mcp-analytics/mastra";
140
+
141
+ const instrumentedTools = wrapMastraTools(tools, {
142
+ armature: {
143
+ delivery: "await",
144
+ },
145
+ });
146
+ ~~~
55
147
 
56
- Three things happen on every tool call:
148
+ ### Stateless HTTP and serverless
57
149
 
58
- 1. **The agent sees a `telemetry` block** added to your tool's input schema — `user_turn`, `user_intent`, `agent_thinking`, `user_frustration`. (Pre-V1 spellings — `intent`, `context`, `frustration_level` — are still accepted from clients holding a cached schema.) The block is optional; the SDK never rejects a call for omitting it.
59
- 2. **Your handler sees its original args.** The SDK strips `telemetry` before invoking it.
60
- 3. **An authenticated batch is POSTed to Armature** with timing, status, input/output previews, and whatever the agent put in `telemetry`. The first call on a new `sessionId` is preceded by a `session_init` event.
150
+ Initialization and tool calls can land on different instances in stateless deployments. **resolveStatelessHttpSession** preserves the MCP client and session identity without a session store:
151
+
152
+ ~~~ts
153
+ import { resolveStatelessHttpSession } from "@armature-tech/mcp-analytics";
61
154
 
62
- ## Other integration shapes
155
+ const session = resolveStatelessHttpSession({
156
+ body: requestBody,
157
+ headers: requestHeaders,
158
+ });
63
159
 
64
- `createMcpAnalyticsServer` covers most repos. If yours doesn't fit, there are three other entry points — the [agent skill](SKILL.md) picks the right one automatically:
160
+ const transport = new StreamableHTTPServerTransport({
161
+ sessionIdGenerator: session.sessionIdGenerator,
162
+ enableJsonResponse: true,
163
+ });
65
164
 
66
- - **Concrete-server registry helper** — `instrumentMcpServerTools({ server, tools, config, mapTool })`. Use when you already own both the `McpServer` instance and your tool registry; the helper calls `server.registerTool(...)` directly (no prototype patching), so it survives pnpm virtual-peer layouts where `createMcpAnalyticsServer`'s patch can miss the customer's SDK module copy.
67
- - **Registry-style** — `createAnalyticsRecorder()` + `analytics.tool(...)` + `analytics.createMcpServer(...)`. Use when you're building a server from scratch and want the recorder to own tool registration.
68
- - **Dispatcher-style** — same recorder, but you call `analytics.toolDefinitions()` from your `tools/list` handler and `analytics.dispatch(name, args, ctx)` from `tools/call`. For servers that hand-roll the JSON-RPC layer.
69
- - **Mastra** — `wrapMastraTools(tools, config)` from `@armature-tech/mcp-analytics/mastra`. Drop the wrapped map into `new MCPServer({ tools })`.
165
+ await analytics.dispatch(name, args, {
166
+ ...context,
167
+ ...session.dispatchContext,
168
+ });
169
+ ~~~
70
170
 
71
- Code examples for all three live in [`SKILL.md`](SKILL.md).
171
+ Use **delivery: "await"** in serverless and short-lived processes.
72
172
 
73
- ## Serverless / stateless HTTP (Vercel, Lambda, Cloud Run)
173
+ Client attribution is best-effort observability, not a security boundary. Continue to gate access with real authentication.
74
174
 
75
- Stateless deployments have no memory between invocations: `initialize` — the only
76
- request carrying the client's name/version — lands on one instance, tool calls land
77
- on others, and clients only echo an `Mcp-Session-Id` header if the server issued one.
78
- Untreated, the dashboard shows one anonymous session per call and client "unknown".
175
+ ## Let your coding agent install it
79
176
 
80
- `resolveStatelessHttpSession` fixes both with no session store: the session id minted
81
- at `initialize` encodes the client identity (`mcp_<name>_v_<version>_<uuid>`), the
82
- client echoes it on every request, and each invocation parses it back out:
177
+ From your MCP server repository:
83
178
 
84
- ```ts
85
- import { resolveStatelessHttpSession } from "@armature-tech/mcp-analytics";
179
+ ~~~bash
180
+ npx --yes skills add armature-tech/mcp-analytics
181
+ ~~~
86
182
 
87
- export default async (req, res) => {
88
- const session = resolveStatelessHttpSession({ body: req.body, headers: req.headers });
89
- const transport = new StreamableHTTPServerTransport({
90
- sessionIdGenerator: session.sessionIdGenerator, // defined only at initialize
91
- enableJsonResponse: true,
92
- });
93
- // dispatcher shape:
94
- await analytics.dispatch(name, args, { ctx, ...session.dispatchContext });
95
- // ... connect server, transport.handleRequest(req, res, req.body)
96
- };
97
- ```
183
+ Then ask Claude Code, Cursor, or Codex:
98
184
 
99
- The recorder also parses identity-bearing session ids on its own as a last-resort
100
- fallback, so client attribution works even when only the transport side is wired.
101
- Use `delivery: "await"` in serverless (see Delivery mode below).
185
+ > Install Armature MCP Analytics using the repository’s SKILL.md. Detect the server shape, instrument it, and verify that a tool-call event is emitted.
102
186
 
103
- Attribution is best-effort telemetry, not a security boundary: the echoed id
104
- carries no signature, so a malicious caller can claim any client name. Gate
105
- access with real auth and treat client/session attribution as observability.
187
+ The full integration playbook is in [SKILL.md](SKILL.md).
106
188
 
107
189
  ## Configuration
108
190
 
109
- ```ts
191
+ Most servers only need **ANALYTICS_INGEST_API_KEY**. Operational controls are available when you need them:
192
+
193
+ ~~~ts
110
194
  type McpAnalyticsConfig = {
111
195
  armature?: {
112
- endpointUrl?: string; // default reads ANALYTICS_INGEST_URL
113
- apiKey?: string; // default reads ANALYTICS_INGEST_API_KEY
196
+ endpointUrl?: string;
197
+ apiKey?: string;
114
198
  actorId?: string | ((input) => string | Promise<string>);
115
- enabled?: boolean; // default true
116
- delivery?: "background" | "await"; // default "background"
117
- timeoutMs?: number; // default 500
118
- emit?: (batch) => void | Promise<void>; // override the network emitter
199
+ enabled?: boolean;
200
+ delivery?: "background" | "await";
201
+ timeoutMs?: number;
202
+ emit?: (batch) => void | Promise<void>;
119
203
  onError?: (error, batch) => void;
120
204
  };
121
205
  };
122
- ```
206
+ ~~~
207
+
208
+ | Option | Default | Purpose |
209
+ | --- | --- | --- |
210
+ | **endpointUrl** | Armature cloud | Override the ingestion endpoint |
211
+ | **apiKey** | **ANALYTICS_INGEST_API_KEY** | Authenticate events and identify the MCP server |
212
+ | **actorId** | Derived from request auth | Supply a stable user or tenant seed |
213
+ | **enabled** | **true** | Enable or disable instrumentation |
214
+ | **delivery** | **"background"** | Use **"await"** for serverless or short-lived processes |
215
+ | **timeoutMs** | **500** | Set the delivery timeout |
216
+ | **emit** | Network emitter | Replace delivery for tests or custom pipelines |
217
+ | **onError** | None | Observe delivery failures |
218
+
219
+ ### Delivery
123
220
 
124
- The shape of the `telemetry` block on each tool's input schema is Armature-owned and not customer-configurable. Customers only set operational config (delivery, actor id, transport).
221
+ - **"background"** returns tool results immediately and posts events on the next turn of the event loop. Call **await recorder.flush()** during shutdown.
222
+ - **"await"** waits for the delivery attempt before returning. Use it for serverless functions and short-lived processes.
125
223
 
126
- **Delivery mode.** `"background"` (default, best for long-lived processes) returns the tool result immediately and posts the batch on `setImmediate` — call `await analytics.flush()` at shutdown. `"await"` (recommended for serverless) resolves only after the batch has been posted; no flush needed.
224
+ If the API key is missing, delivery quietly no-ops for local development.
127
225
 
128
- **Actor id.** A SHA-256 of an actor seed. By default the seed comes from the request's auth token / client id / authorization header. Pass a static `armature.actorId` seed for a stable source, or a function to derive the seed from `{ ctx, extra, headers, authInfo, toolName, telemetry }`. Armature scopes the actor id to your server via the API key, so the same seed under two different servers stays linked to the same person (cross-surface analytics).
226
+ ### Actor identification
129
227
 
130
- **Missing API key.** The SDK silently skips delivery — useful for local development.
228
+ By default, the SDK derives an actor seed from request authentication information. You may provide a string or function through **actorId**.
131
229
 
132
- **Auth.** Each batch is POSTed with `Authorization: Bearer <apiKey>`. Server identity is resolved from the API key — no separate header.
230
+ The seed is hashed before transmission. Armature scopes the resulting actor identifier to your server.
133
231
 
134
232
  ## Environment variables
135
233
 
136
234
  | Variable | Purpose |
137
235
  | --- | --- |
138
- | `ANALYTICS_INGEST_URL` | Ingest endpoint (defaults to `https://app.armature.tech/api/mcp-analytics/ingest`; override for a local mock or staging) |
139
- | `ANALYTICS_INGEST_API_KEY` | Your Armature API key — identifies the MCP server and signs each batch |
236
+ | **ANALYTICS_INGEST_API_KEY** | Armature ingest key |
237
+ | **ANALYTICS_INGEST_URL** | Optional ingestion endpoint override |
238
+
239
+ ## Support
240
+
241
+ [Open an issue](https://github.com/armature-tech/mcp-analytics/issues) · [Email us](mailto:hey@armature.tech) · [Changelog](CHANGELOG.md)
140
242
 
141
- ## More
243
+ ## License
142
244
 
143
- - **Custom integrations** — `withMcpAnalytics`, `createAnalyticsRecorder`, `decorateInputSchemaWithTelemetry`, and other lower-level primitives are exported for cases the four shapes don't cover. See [`docs/`](docs/) and the source.
144
- - **Recording `session_init` explicitly** — `recordToolCall` already emits one on the first call per `sessionId`. Call `analytics.recordSessionInit({ sessionId, ctx })` from your `initialize` handler if you want it at handshake time.
145
- - **Flushing on the `McpServer` path** — use `withMcpAnalytics(config, createServer)` instead of `createMcpAnalyticsServer`; it returns `{ result, recorder }` so you can `await recorder.flush()`.
146
- - **AI agents integrating this** — read [`SKILL.md`](SKILL.md) (also shipped in the npm tarball).
147
- - **Support** — `hey@armature.tech` or open an issue.
245
+ Licensed under the [Apache License 2.0](LICENSE).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@armature-tech/mcp-analytics",
3
- "version": "0.6.13",
3
+ "version": "0.6.14",
4
4
  "type": "module",
5
5
  "description": "MCP analytics wrapper SDK that instruments MCP tool declarations with telemetry.",
6
6
  "license": "Apache-2.0",