@trimstats/mcp 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 +21 -0
- package/README.md +83 -2
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +39 -0
- package/dist/http-backend.d.ts +11 -0
- package/dist/http-backend.js +179 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/protocol.d.ts +52 -0
- package/dist/protocol.js +169 -0
- package/dist/stdio.d.ts +13 -0
- package/dist/stdio.js +84 -0
- package/dist/tools.d.ts +129 -0
- package/dist/tools.js +825 -0
- package/package.json +56 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 TrimStats
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,84 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @trimstats/mcp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Official zero-dependency [Model Context Protocol (MCP)](https://modelcontextprotocol.io) server for [TrimStats](https://www.trimstats.com) web analytics.
|
|
4
|
+
|
|
5
|
+
Connect Claude Desktop, Claude Code, Cursor, Codex, or any MCP client to query your TrimStats traffic, live visitors, custom event properties, attributed revenue, anomaly insights, UI friction, funnels, retention cohorts, AI crawlers, and AI referrals.
|
|
6
|
+
|
|
7
|
+
## Prerequisites
|
|
8
|
+
|
|
9
|
+
Create a read-only API key (`ts_live_...`) under **Workspace -> API keys** in TrimStats. You can scope the key to all sites in your workspace or lock it to a single site.
|
|
10
|
+
|
|
11
|
+
## Option 1: Local stdio (`npx -y @trimstats/mcp`)
|
|
12
|
+
|
|
13
|
+
### Claude Code
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
claude mcp add trimstats --env TRIMSTATS_API_KEY=ts_live_your_api_key -- npx -y @trimstats/mcp
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
### Codex CLI
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
codex mcp add trimstats --env TRIMSTATS_API_KEY=ts_live_your_api_key -- npx -y @trimstats/mcp
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
### Claude Desktop / Cursor (`mcpServers`)
|
|
26
|
+
|
|
27
|
+
```json
|
|
28
|
+
{
|
|
29
|
+
"mcpServers": {
|
|
30
|
+
"trimstats": {
|
|
31
|
+
"command": "npx",
|
|
32
|
+
"args": ["-y", "@trimstats/mcp"],
|
|
33
|
+
"env": {
|
|
34
|
+
"TRIMSTATS_API_KEY": "ts_live_your_api_key"
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Option 2: Remote Streamable HTTP (no local Node install)
|
|
42
|
+
|
|
43
|
+
Point any Streamable HTTP MCP client directly at `https://collect.trimstats.com/mcp` with your `Authorization: Bearer` API key:
|
|
44
|
+
|
|
45
|
+
```json
|
|
46
|
+
{
|
|
47
|
+
"mcpServers": {
|
|
48
|
+
"trimstats": {
|
|
49
|
+
"type": "http",
|
|
50
|
+
"url": "https://collect.trimstats.com/mcp",
|
|
51
|
+
"headers": {
|
|
52
|
+
"Authorization": "Bearer ts_live_your_api_key"
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Test with MCP Inspector
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
TRIMSTATS_API_KEY=ts_live_your_api_key npx @modelcontextprotocol/inspector npx -y @trimstats/mcp
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Available Tools (12 read-only tools)
|
|
66
|
+
|
|
67
|
+
| Tool | Purpose |
|
|
68
|
+
| --- | --- |
|
|
69
|
+
| `list_sites` | List websites accessible to the API key (call first to obtain `siteId`) |
|
|
70
|
+
| `get_site_overview` | KPIs, period comparison, daily timeseries, breakdowns, custom events, goals |
|
|
71
|
+
| `get_live_visitors` | Unique visitors active within the last 5 minutes |
|
|
72
|
+
| `get_event_properties` | Property keys and top values for a custom event |
|
|
73
|
+
| `get_revenue_report` | Attributed revenue (USD cents), orders, AOV, channel/UTM/landing page breakdowns |
|
|
74
|
+
| `get_anomaly_insights` | Rolling 7-day anomalies with optional daily trends, drivers, and 30-day history |
|
|
75
|
+
| `get_ui_friction` | Rage clicks, dead clicks, 90% scroll reach, top friction pages & CSS selectors |
|
|
76
|
+
| `list_funnels` | Saved funnel definitions for a site |
|
|
77
|
+
| `evaluate_funnel` | Step-by-step `windowFunnel()` evaluation by saved `funnelId` or ad-hoc `steps` |
|
|
78
|
+
| `get_retention_cohorts` | Weekly visitor retention matrix (2 to 12 weeks) |
|
|
79
|
+
| `get_ai_crawlers` | AI bot fetches by category (`ai_answers`, `indexing`, `training`), crawler, and page |
|
|
80
|
+
| `get_ai_referrals` | Human AI assistant referrals, revenue, goals, and `#:~:text=` cited passages |
|
|
81
|
+
|
|
82
|
+
## License
|
|
83
|
+
|
|
84
|
+
MIT
|
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createTrimStatsHttpBackend } from './http-backend.js';
|
|
3
|
+
import { MCP_SERVER_INFO } from './protocol.js';
|
|
4
|
+
import { runStdioServer } from './stdio.js';
|
|
5
|
+
const args = process.argv.slice(2);
|
|
6
|
+
if (args.includes('--version') || args.includes('-v')) {
|
|
7
|
+
process.stdout.write(`${MCP_SERVER_INFO.version}\n`);
|
|
8
|
+
process.exit(0);
|
|
9
|
+
}
|
|
10
|
+
if (args.includes('--help') || args.includes('-h')) {
|
|
11
|
+
process.stderr.write([
|
|
12
|
+
`${MCP_SERVER_INFO.name} v${MCP_SERVER_INFO.version}`,
|
|
13
|
+
'Official read-only MCP server for TrimStats web analytics.',
|
|
14
|
+
'',
|
|
15
|
+
'Environment variables:',
|
|
16
|
+
' TRIMSTATS_API_KEY Required. Read-only API key (ts_live_...) from Workspace -> API keys.',
|
|
17
|
+
' TRIMSTATS_API_URL Optional. Defaults to https://collect.trimstats.com',
|
|
18
|
+
'',
|
|
19
|
+
'Example:',
|
|
20
|
+
' TRIMSTATS_API_KEY=ts_live_... npx -y @trimstats/mcp',
|
|
21
|
+
'',
|
|
22
|
+
].join('\n'));
|
|
23
|
+
process.exit(0);
|
|
24
|
+
}
|
|
25
|
+
let backend;
|
|
26
|
+
try {
|
|
27
|
+
backend = createTrimStatsHttpBackend({
|
|
28
|
+
apiKey: process.env.TRIMSTATS_API_KEY ?? '',
|
|
29
|
+
apiBaseUrl: process.env.TRIMSTATS_API_URL,
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
catch (err) {
|
|
33
|
+
const msg = err instanceof Error ? err.message : 'Invalid configuration.';
|
|
34
|
+
process.stderr.write(`[trimstats-mcp] ${msg}\n`);
|
|
35
|
+
process.exit(1);
|
|
36
|
+
}
|
|
37
|
+
process.on('SIGINT', () => process.exit(0));
|
|
38
|
+
process.on('SIGTERM', () => process.exit(0));
|
|
39
|
+
await runStdioServer({ backend });
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type TrimStatsMcpBackend } from './protocol.js';
|
|
2
|
+
export declare const DEFAULT_TRIMSTATS_API_URL = "https://collect.trimstats.com";
|
|
3
|
+
export declare function validateApiKeyFormat(rawKey: string | undefined): string;
|
|
4
|
+
export declare function validateApiBaseUrl(rawUrl: string | undefined): string;
|
|
5
|
+
export interface HttpBackendOptions {
|
|
6
|
+
apiKey: string;
|
|
7
|
+
apiBaseUrl?: string;
|
|
8
|
+
timeoutMs?: number;
|
|
9
|
+
fetchFn?: typeof fetch;
|
|
10
|
+
}
|
|
11
|
+
export declare function createTrimStatsHttpBackend(options: HttpBackendOptions): TrimStatsMcpBackend;
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { McpToolError } from './protocol.js';
|
|
2
|
+
export const DEFAULT_TRIMSTATS_API_URL = 'https://collect.trimstats.com';
|
|
3
|
+
const API_KEY_RE = /^ts_live_[A-Za-z0-9_-]{32,64}$/;
|
|
4
|
+
const DEFAULT_TIMEOUT_MS = 20_000;
|
|
5
|
+
const MAX_RESPONSE_BYTES = 2 * 1024 * 1024; // 2 MB cap
|
|
6
|
+
export function validateApiKeyFormat(rawKey) {
|
|
7
|
+
const key = rawKey?.trim() ?? '';
|
|
8
|
+
if (!API_KEY_RE.test(key)) {
|
|
9
|
+
throw new Error('Invalid or missing TRIMSTATS_API_KEY. Create a read-only ts_live_ key in TrimStats Workspace -> API keys.');
|
|
10
|
+
}
|
|
11
|
+
return key;
|
|
12
|
+
}
|
|
13
|
+
export function validateApiBaseUrl(rawUrl) {
|
|
14
|
+
const trimmed = (rawUrl?.trim() || DEFAULT_TRIMSTATS_API_URL).replace(/\/+$/, '');
|
|
15
|
+
let parsed;
|
|
16
|
+
try {
|
|
17
|
+
parsed = new URL(trimmed);
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
throw new Error('Invalid TRIMSTATS_API_URL: must be a valid URL.');
|
|
21
|
+
}
|
|
22
|
+
if (parsed.username || parsed.password) {
|
|
23
|
+
throw new Error('TRIMSTATS_API_URL must not include embedded credentials.');
|
|
24
|
+
}
|
|
25
|
+
const host = parsed.hostname.toLowerCase();
|
|
26
|
+
const isLoopback = host === '127.0.0.1' || host === 'localhost' || host === '::1' || host === '[::1]';
|
|
27
|
+
if (parsed.protocol !== 'https:' && !(parsed.protocol === 'http:' && isLoopback)) {
|
|
28
|
+
throw new Error('TRIMSTATS_API_URL must use HTTPS (HTTP is allowed only for localhost).');
|
|
29
|
+
}
|
|
30
|
+
return `${parsed.origin}${parsed.pathname.replace(/\/+$/, '')}`;
|
|
31
|
+
}
|
|
32
|
+
function buildQuery(params) {
|
|
33
|
+
const sp = new URLSearchParams();
|
|
34
|
+
for (const [k, v] of Object.entries(params)) {
|
|
35
|
+
if (v !== undefined) {
|
|
36
|
+
sp.set(k, String(v));
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
const qs = sp.toString();
|
|
40
|
+
return qs ? `?${qs}` : '';
|
|
41
|
+
}
|
|
42
|
+
export function createTrimStatsHttpBackend(options) {
|
|
43
|
+
const apiKey = validateApiKeyFormat(options.apiKey);
|
|
44
|
+
const baseUrl = validateApiBaseUrl(options.apiBaseUrl);
|
|
45
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
46
|
+
const fetchImpl = options.fetchFn ?? fetch;
|
|
47
|
+
async function requestJson(path, init) {
|
|
48
|
+
const headers = {
|
|
49
|
+
authorization: `Bearer ${apiKey}`,
|
|
50
|
+
accept: 'application/json',
|
|
51
|
+
'user-agent': 'trimstats-mcp/0.1.0',
|
|
52
|
+
};
|
|
53
|
+
if (init?.body !== undefined) {
|
|
54
|
+
headers['content-type'] = 'application/json';
|
|
55
|
+
}
|
|
56
|
+
let res;
|
|
57
|
+
try {
|
|
58
|
+
res = await fetchImpl(`${baseUrl}${path}`, {
|
|
59
|
+
method: init?.method ?? 'GET',
|
|
60
|
+
headers,
|
|
61
|
+
body: init?.body !== undefined ? JSON.stringify(init.body) : undefined,
|
|
62
|
+
redirect: 'error', // Never forward Bearer token across HTTP redirects.
|
|
63
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
catch (err) {
|
|
67
|
+
const isTimeout = err instanceof Error && err.name === 'TimeoutError';
|
|
68
|
+
throw new McpToolError(isTimeout
|
|
69
|
+
? 'TrimStats API request timed out.'
|
|
70
|
+
: 'Could not reach the TrimStats API endpoint.');
|
|
71
|
+
}
|
|
72
|
+
const rawText = await readBoundedText(res, MAX_RESPONSE_BYTES);
|
|
73
|
+
let parsed = null;
|
|
74
|
+
if (rawText) {
|
|
75
|
+
try {
|
|
76
|
+
parsed = JSON.parse(rawText);
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
parsed = null;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
if (!res.ok) {
|
|
83
|
+
const apiErr = parsed && typeof parsed === 'object' && typeof parsed.error === 'string'
|
|
84
|
+
? parsed.error
|
|
85
|
+
: `HTTP ${res.status}`;
|
|
86
|
+
if (res.status === 429) {
|
|
87
|
+
const retryAfter = res.headers.get('retry-after');
|
|
88
|
+
throw new McpToolError(retryAfter
|
|
89
|
+
? `TrimStats API rate limit reached. Retry after ${retryAfter}s.`
|
|
90
|
+
: 'TrimStats API rate limit reached. Try again shortly.');
|
|
91
|
+
}
|
|
92
|
+
throw new McpToolError(`TrimStats API error (${res.status}): ${apiErr}`);
|
|
93
|
+
}
|
|
94
|
+
if (parsed === null) {
|
|
95
|
+
throw new McpToolError('TrimStats API returned an invalid JSON response.');
|
|
96
|
+
}
|
|
97
|
+
return parsed;
|
|
98
|
+
}
|
|
99
|
+
return {
|
|
100
|
+
listSites: () => requestJson('/v1/sites'),
|
|
101
|
+
getSiteOverview: (input) => {
|
|
102
|
+
const { siteId, ...rest } = input;
|
|
103
|
+
return requestJson(`/v1/sites/${encodeURIComponent(siteId)}/overview${buildQuery(rest)}`);
|
|
104
|
+
},
|
|
105
|
+
getLiveVisitors: (siteId) => requestJson(`/v1/sites/${encodeURIComponent(siteId)}/live`),
|
|
106
|
+
getEventProperties: (input) => {
|
|
107
|
+
const { siteId, ...rest } = input;
|
|
108
|
+
return requestJson(`/v1/sites/${encodeURIComponent(siteId)}/events/properties${buildQuery(rest)}`);
|
|
109
|
+
},
|
|
110
|
+
getRevenueReport: (input) => {
|
|
111
|
+
const { siteId, ...rest } = input;
|
|
112
|
+
return requestJson(`/v1/sites/${encodeURIComponent(siteId)}/revenue${buildQuery(rest)}`);
|
|
113
|
+
},
|
|
114
|
+
getAnomalyInsights: (input) => {
|
|
115
|
+
const { siteId, includeDetails } = input;
|
|
116
|
+
return requestJson(`/v1/sites/${encodeURIComponent(siteId)}/insights${buildQuery({ includeDetails })}`);
|
|
117
|
+
},
|
|
118
|
+
getUiFriction: (input) => {
|
|
119
|
+
const { siteId, from, to } = input;
|
|
120
|
+
return requestJson(`/v1/sites/${encodeURIComponent(siteId)}/friction${buildQuery({ from, to })}`);
|
|
121
|
+
},
|
|
122
|
+
listFunnels: (siteId) => requestJson(`/v1/sites/${encodeURIComponent(siteId)}/funnels`),
|
|
123
|
+
evaluateFunnel: (input) => {
|
|
124
|
+
const { siteId, funnelId, steps, from, to, windowSeconds } = input;
|
|
125
|
+
if (funnelId) {
|
|
126
|
+
return requestJson(`/v1/sites/${encodeURIComponent(siteId)}/funnels/${encodeURIComponent(funnelId)}${buildQuery({ from, to, windowSeconds })}`);
|
|
127
|
+
}
|
|
128
|
+
const now = new Date();
|
|
129
|
+
const defaultTo = now.toISOString().slice(0, 10);
|
|
130
|
+
const start = new Date(now);
|
|
131
|
+
start.setUTCDate(start.getUTCDate() - 29);
|
|
132
|
+
const defaultFrom = start.toISOString().slice(0, 10);
|
|
133
|
+
return requestJson(`/v1/sites/${encodeURIComponent(siteId)}/funnels/evaluate`, {
|
|
134
|
+
method: 'POST',
|
|
135
|
+
body: {
|
|
136
|
+
from: from ?? defaultFrom,
|
|
137
|
+
to: to ?? defaultTo,
|
|
138
|
+
...(windowSeconds !== undefined ? { windowSeconds } : {}),
|
|
139
|
+
steps,
|
|
140
|
+
},
|
|
141
|
+
});
|
|
142
|
+
},
|
|
143
|
+
getRetentionCohorts: (input) => {
|
|
144
|
+
const { siteId, weeks } = input;
|
|
145
|
+
return requestJson(`/v1/sites/${encodeURIComponent(siteId)}/cohorts${buildQuery({ weeks })}`);
|
|
146
|
+
},
|
|
147
|
+
getAiCrawlers: (input) => {
|
|
148
|
+
const { siteId, ...rest } = input;
|
|
149
|
+
return requestJson(`/v1/sites/${encodeURIComponent(siteId)}/ai-crawlers${buildQuery(rest)}`);
|
|
150
|
+
},
|
|
151
|
+
getAiReferrals: (input) => {
|
|
152
|
+
const { siteId, ...rest } = input;
|
|
153
|
+
return requestJson(`/v1/sites/${encodeURIComponent(siteId)}/ai-referrals${buildQuery(rest)}`);
|
|
154
|
+
},
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
async function readBoundedText(res, maxBytes) {
|
|
158
|
+
if (!res.body)
|
|
159
|
+
return '';
|
|
160
|
+
const reader = res.body.getReader();
|
|
161
|
+
const decoder = new TextDecoder();
|
|
162
|
+
let totalBytes = 0;
|
|
163
|
+
let text = '';
|
|
164
|
+
while (true) {
|
|
165
|
+
const { done, value } = await reader.read();
|
|
166
|
+
if (done)
|
|
167
|
+
break;
|
|
168
|
+
if (value) {
|
|
169
|
+
totalBytes += value.byteLength;
|
|
170
|
+
if (totalBytes > maxBytes) {
|
|
171
|
+
await reader.cancel().catch(() => { });
|
|
172
|
+
throw new McpToolError('TrimStats API response exceeded maximum size limit.');
|
|
173
|
+
}
|
|
174
|
+
text += decoder.decode(value, { stream: true });
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
text += decoder.decode();
|
|
178
|
+
return text;
|
|
179
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { type AiCrawlersToolInput, type AiReferralsToolInput, type CohortsToolInput, type EvaluateFunnelToolInput, type EventPropertiesToolInput, type FrictionToolInput, type InsightsToolInput, type OverviewToolInput, type RevenueToolInput } from './tools.js';
|
|
2
|
+
export declare const MCP_PROTOCOL_VERSION = "2025-03-26";
|
|
3
|
+
export declare const MCP_SUPPORTED_VERSIONS: readonly ['2025-03-26', '2024-11-05'];
|
|
4
|
+
export declare const MCP_SERVER_INFO: {
|
|
5
|
+
readonly name: 'trimstats-mcp';
|
|
6
|
+
readonly version: '0.1.0';
|
|
7
|
+
};
|
|
8
|
+
export declare const MCP_SERVER_INSTRUCTIONS = "Read-only TrimStats web analytics MCP server. Call list_sites first to discover accessible siteId UUIDs, then call site-scoped tools for traffic overview, live visitors, custom event properties, attributed revenue (USD cents), anomaly insights, UI friction, funnels, retention cohorts, AI crawlers, and AI referrals.";
|
|
9
|
+
export type JsonRpcId = string | number | null;
|
|
10
|
+
export interface JsonRpcSuccess {
|
|
11
|
+
jsonrpc: '2.0';
|
|
12
|
+
id: JsonRpcId;
|
|
13
|
+
result: unknown;
|
|
14
|
+
}
|
|
15
|
+
export interface JsonRpcError {
|
|
16
|
+
jsonrpc: '2.0';
|
|
17
|
+
id: JsonRpcId;
|
|
18
|
+
error: {
|
|
19
|
+
code: number;
|
|
20
|
+
message: string;
|
|
21
|
+
data?: unknown;
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
export type JsonRpcResponse = JsonRpcSuccess | JsonRpcError;
|
|
25
|
+
export type McpDispatchOutcome = {
|
|
26
|
+
kind: 'notification';
|
|
27
|
+
} | {
|
|
28
|
+
kind: 'response';
|
|
29
|
+
response: JsonRpcResponse;
|
|
30
|
+
};
|
|
31
|
+
export interface TrimStatsMcpBackend {
|
|
32
|
+
listSites(): Promise<unknown>;
|
|
33
|
+
getSiteOverview(input: OverviewToolInput): Promise<unknown>;
|
|
34
|
+
getLiveVisitors(siteId: string): Promise<unknown>;
|
|
35
|
+
getEventProperties(input: EventPropertiesToolInput): Promise<unknown>;
|
|
36
|
+
getRevenueReport(input: RevenueToolInput): Promise<unknown>;
|
|
37
|
+
getAnomalyInsights(input: InsightsToolInput): Promise<unknown>;
|
|
38
|
+
getUiFriction(input: FrictionToolInput): Promise<unknown>;
|
|
39
|
+
listFunnels(siteId: string): Promise<unknown>;
|
|
40
|
+
evaluateFunnel(input: EvaluateFunnelToolInput): Promise<unknown>;
|
|
41
|
+
getRetentionCohorts(input: CohortsToolInput): Promise<unknown>;
|
|
42
|
+
getAiCrawlers(input: AiCrawlersToolInput): Promise<unknown>;
|
|
43
|
+
getAiReferrals(input: AiReferralsToolInput): Promise<unknown>;
|
|
44
|
+
}
|
|
45
|
+
export declare class McpToolError extends Error {
|
|
46
|
+
constructor(message: string);
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Handles a single parsed MCP JSON-RPC 2.0 request or notification.
|
|
50
|
+
* Rejects batch arrays (removed in current MCP spec and prevents rate-limit amplification).
|
|
51
|
+
*/
|
|
52
|
+
export declare function handleMcpJsonRpcPayload(payload: unknown, backend: TrimStatsMcpBackend): Promise<McpDispatchOutcome>;
|
package/dist/protocol.js
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import { TRIMSTATS_MCP_TOOLS, validateToolCall, } from './tools.js';
|
|
2
|
+
export const MCP_PROTOCOL_VERSION = '2025-03-26';
|
|
3
|
+
export const MCP_SUPPORTED_VERSIONS = ['2025-03-26', '2024-11-05'];
|
|
4
|
+
export const MCP_SERVER_INFO = {
|
|
5
|
+
name: 'trimstats-mcp',
|
|
6
|
+
version: '0.1.0',
|
|
7
|
+
};
|
|
8
|
+
export const MCP_SERVER_INSTRUCTIONS = 'Read-only TrimStats web analytics MCP server. Call list_sites first to discover accessible siteId UUIDs, then call site-scoped tools for traffic overview, live visitors, custom event properties, attributed revenue (USD cents), anomaly insights, UI friction, funnels, retention cohorts, AI crawlers, and AI referrals.';
|
|
9
|
+
const JSONRPC_INVALID_REQUEST = -32600;
|
|
10
|
+
const JSONRPC_METHOD_NOT_FOUND = -32601;
|
|
11
|
+
const JSONRPC_INVALID_PARAMS = -32602;
|
|
12
|
+
function isPlainObject(val) {
|
|
13
|
+
return typeof val === 'object' && val !== null && !Array.isArray(val);
|
|
14
|
+
}
|
|
15
|
+
function isValidRpcId(val) {
|
|
16
|
+
return val === null || typeof val === 'string' || (typeof val === 'number' && Number.isFinite(val));
|
|
17
|
+
}
|
|
18
|
+
function errorResponse(id, code, message) {
|
|
19
|
+
return { jsonrpc: '2.0', id, error: { code, message } };
|
|
20
|
+
}
|
|
21
|
+
function successResponse(id, result) {
|
|
22
|
+
return { jsonrpc: '2.0', id, result };
|
|
23
|
+
}
|
|
24
|
+
function negotiateProtocolVersion(requested) {
|
|
25
|
+
if (typeof requested === 'string') {
|
|
26
|
+
if (MCP_SUPPORTED_VERSIONS.includes(requested)) {
|
|
27
|
+
return requested;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return MCP_PROTOCOL_VERSION;
|
|
31
|
+
}
|
|
32
|
+
async function executeValidatedTool(call, backend) {
|
|
33
|
+
switch (call.name) {
|
|
34
|
+
case 'list_sites':
|
|
35
|
+
return backend.listSites();
|
|
36
|
+
case 'get_site_overview':
|
|
37
|
+
return backend.getSiteOverview(call.args);
|
|
38
|
+
case 'get_live_visitors':
|
|
39
|
+
return backend.getLiveVisitors(call.args.siteId);
|
|
40
|
+
case 'get_event_properties':
|
|
41
|
+
return backend.getEventProperties(call.args);
|
|
42
|
+
case 'get_revenue_report':
|
|
43
|
+
return backend.getRevenueReport(call.args);
|
|
44
|
+
case 'get_anomaly_insights':
|
|
45
|
+
return backend.getAnomalyInsights(call.args);
|
|
46
|
+
case 'get_ui_friction':
|
|
47
|
+
return backend.getUiFriction(call.args);
|
|
48
|
+
case 'list_funnels':
|
|
49
|
+
return backend.listFunnels(call.args.siteId);
|
|
50
|
+
case 'evaluate_funnel':
|
|
51
|
+
return backend.evaluateFunnel(call.args);
|
|
52
|
+
case 'get_retention_cohorts':
|
|
53
|
+
return backend.getRetentionCohorts(call.args);
|
|
54
|
+
case 'get_ai_crawlers':
|
|
55
|
+
return backend.getAiCrawlers(call.args);
|
|
56
|
+
case 'get_ai_referrals':
|
|
57
|
+
return backend.getAiReferrals(call.args);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
export class McpToolError extends Error {
|
|
61
|
+
constructor(message) {
|
|
62
|
+
super(message);
|
|
63
|
+
this.name = 'McpToolError';
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Handles a single parsed MCP JSON-RPC 2.0 request or notification.
|
|
68
|
+
* Rejects batch arrays (removed in current MCP spec and prevents rate-limit amplification).
|
|
69
|
+
*/
|
|
70
|
+
export async function handleMcpJsonRpcPayload(payload, backend) {
|
|
71
|
+
if (!isPlainObject(payload)) {
|
|
72
|
+
return {
|
|
73
|
+
kind: 'response',
|
|
74
|
+
response: errorResponse(null, JSONRPC_INVALID_REQUEST, 'JSON-RPC request must be a single object.'),
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
const hasId = Object.prototype.hasOwnProperty.call(payload, 'id');
|
|
78
|
+
const rawId = payload.id;
|
|
79
|
+
const id = hasId && isValidRpcId(rawId) ? rawId : null;
|
|
80
|
+
if (payload.jsonrpc !== '2.0' || typeof payload.method !== 'string' || payload.method.length === 0) {
|
|
81
|
+
return {
|
|
82
|
+
kind: 'response',
|
|
83
|
+
response: errorResponse(id, JSONRPC_INVALID_REQUEST, 'Invalid JSON-RPC 2.0 envelope.'),
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
if (hasId && !isValidRpcId(rawId)) {
|
|
87
|
+
return {
|
|
88
|
+
kind: 'response',
|
|
89
|
+
response: errorResponse(null, JSONRPC_INVALID_REQUEST, 'Invalid JSON-RPC id.'),
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
const method = payload.method;
|
|
93
|
+
const params = payload.params;
|
|
94
|
+
// Notifications carry no `id` and expect no JSON-RPC response body.
|
|
95
|
+
if (!hasId) {
|
|
96
|
+
return { kind: 'notification' };
|
|
97
|
+
}
|
|
98
|
+
switch (method) {
|
|
99
|
+
case 'initialize': {
|
|
100
|
+
const requestedVersion = isPlainObject(params) ? params.protocolVersion : undefined;
|
|
101
|
+
return {
|
|
102
|
+
kind: 'response',
|
|
103
|
+
response: successResponse(id, {
|
|
104
|
+
protocolVersion: negotiateProtocolVersion(requestedVersion),
|
|
105
|
+
capabilities: {
|
|
106
|
+
tools: { listChanged: false },
|
|
107
|
+
},
|
|
108
|
+
serverInfo: MCP_SERVER_INFO,
|
|
109
|
+
instructions: MCP_SERVER_INSTRUCTIONS,
|
|
110
|
+
}),
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
case 'ping':
|
|
114
|
+
return {
|
|
115
|
+
kind: 'response',
|
|
116
|
+
response: successResponse(id, {}),
|
|
117
|
+
};
|
|
118
|
+
case 'tools/list':
|
|
119
|
+
return {
|
|
120
|
+
kind: 'response',
|
|
121
|
+
response: successResponse(id, {
|
|
122
|
+
tools: TRIMSTATS_MCP_TOOLS,
|
|
123
|
+
}),
|
|
124
|
+
};
|
|
125
|
+
case 'tools/call': {
|
|
126
|
+
if (!isPlainObject(params)) {
|
|
127
|
+
return {
|
|
128
|
+
kind: 'response',
|
|
129
|
+
response: errorResponse(id, JSONRPC_INVALID_PARAMS, 'tools/call params must be an object.'),
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
const validated = validateToolCall(params.name, params.arguments);
|
|
133
|
+
if (!validated.ok) {
|
|
134
|
+
return {
|
|
135
|
+
kind: 'response',
|
|
136
|
+
response: errorResponse(id, JSONRPC_INVALID_PARAMS, validated.error),
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
try {
|
|
140
|
+
const data = await executeValidatedTool(validated.call, backend);
|
|
141
|
+
return {
|
|
142
|
+
kind: 'response',
|
|
143
|
+
response: successResponse(id, {
|
|
144
|
+
content: [{ type: 'text', text: JSON.stringify(data, null, 2) }],
|
|
145
|
+
structuredContent: isPlainObject(data) ? data : { data },
|
|
146
|
+
isError: false,
|
|
147
|
+
}),
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
catch (err) {
|
|
151
|
+
const message = err instanceof McpToolError
|
|
152
|
+
? err.message
|
|
153
|
+
: 'TrimStats analytics request failed.';
|
|
154
|
+
return {
|
|
155
|
+
kind: 'response',
|
|
156
|
+
response: successResponse(id, {
|
|
157
|
+
content: [{ type: 'text', text: message }],
|
|
158
|
+
isError: true,
|
|
159
|
+
}),
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
default:
|
|
164
|
+
return {
|
|
165
|
+
kind: 'response',
|
|
166
|
+
response: errorResponse(id, JSONRPC_METHOD_NOT_FOUND, `Method not found: ${method}`),
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
}
|
package/dist/stdio.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { Readable, Writable } from 'node:stream';
|
|
2
|
+
import { type TrimStatsMcpBackend } from './protocol.js';
|
|
3
|
+
export interface StdioServerOptions {
|
|
4
|
+
backend: TrimStatsMcpBackend;
|
|
5
|
+
stdin?: Readable;
|
|
6
|
+
stdout?: Writable;
|
|
7
|
+
stderr?: Writable;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Runs a line-delimited JSON-RPC 2.0 MCP server over stdio.
|
|
11
|
+
* Writes strictly valid JSON-RPC frames to stdout; diagnostics go only to stderr.
|
|
12
|
+
*/
|
|
13
|
+
export declare function runStdioServer(options: StdioServerOptions): Promise<void>;
|
package/dist/stdio.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { handleMcpJsonRpcPayload } from './protocol.js';
|
|
2
|
+
const MAX_LINE_BYTES = 1024 * 1024; // 1 MB per JSON-RPC message line
|
|
3
|
+
/**
|
|
4
|
+
* Runs a line-delimited JSON-RPC 2.0 MCP server over stdio.
|
|
5
|
+
* Writes strictly valid JSON-RPC frames to stdout; diagnostics go only to stderr.
|
|
6
|
+
*/
|
|
7
|
+
export function runStdioServer(options) {
|
|
8
|
+
const stdin = options.stdin ?? process.stdin;
|
|
9
|
+
const stdout = options.stdout ?? process.stdout;
|
|
10
|
+
const stderr = options.stderr ?? process.stderr;
|
|
11
|
+
return new Promise((resolve) => {
|
|
12
|
+
let buffer = '';
|
|
13
|
+
let chain = Promise.resolve();
|
|
14
|
+
const writeLine = (payload) => {
|
|
15
|
+
stdout.write(`${JSON.stringify(payload)}\n`);
|
|
16
|
+
};
|
|
17
|
+
const processLine = async (rawLine) => {
|
|
18
|
+
const trimmed = rawLine.trim();
|
|
19
|
+
if (!trimmed)
|
|
20
|
+
return;
|
|
21
|
+
if (Buffer.byteLength(trimmed, 'utf8') > MAX_LINE_BYTES) {
|
|
22
|
+
writeLine({
|
|
23
|
+
jsonrpc: '2.0',
|
|
24
|
+
id: null,
|
|
25
|
+
error: { code: -32600, message: 'Message exceeds maximum size limit.' },
|
|
26
|
+
});
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
let parsed;
|
|
30
|
+
try {
|
|
31
|
+
parsed = JSON.parse(trimmed);
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
writeLine({
|
|
35
|
+
jsonrpc: '2.0',
|
|
36
|
+
id: null,
|
|
37
|
+
error: { code: -32700, message: 'Parse error: invalid JSON.' },
|
|
38
|
+
});
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
try {
|
|
42
|
+
const outcome = await handleMcpJsonRpcPayload(parsed, options.backend);
|
|
43
|
+
if (outcome.kind === 'response') {
|
|
44
|
+
writeLine(outcome.response);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
catch (err) {
|
|
48
|
+
const msg = err instanceof Error ? err.message : 'Internal server error';
|
|
49
|
+
stderr.write(`[trimstats-mcp] unexpected error: ${msg}\n`);
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
stdin.setEncoding('utf8');
|
|
53
|
+
stdin.on('data', (chunk) => {
|
|
54
|
+
buffer += chunk;
|
|
55
|
+
if (Buffer.byteLength(buffer, 'utf8') > MAX_LINE_BYTES * 2) {
|
|
56
|
+
buffer = '';
|
|
57
|
+
writeLine({
|
|
58
|
+
jsonrpc: '2.0',
|
|
59
|
+
id: null,
|
|
60
|
+
error: { code: -32600, message: 'Input buffer exceeded limit.' },
|
|
61
|
+
});
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
let newlineIdx = buffer.indexOf('\n');
|
|
65
|
+
while (newlineIdx !== -1) {
|
|
66
|
+
const line = buffer.slice(0, newlineIdx);
|
|
67
|
+
buffer = buffer.slice(newlineIdx + 1);
|
|
68
|
+
chain = chain.then(() => processLine(line));
|
|
69
|
+
newlineIdx = buffer.indexOf('\n');
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
stdin.on('end', () => {
|
|
73
|
+
if (buffer.trim()) {
|
|
74
|
+
const remainder = buffer;
|
|
75
|
+
buffer = '';
|
|
76
|
+
chain = chain.then(() => processLine(remainder));
|
|
77
|
+
}
|
|
78
|
+
void chain.then(() => resolve());
|
|
79
|
+
});
|
|
80
|
+
stdin.on('error', () => {
|
|
81
|
+
void chain.then(() => resolve());
|
|
82
|
+
});
|
|
83
|
+
});
|
|
84
|
+
}
|