@asif2bd/umami-mcp 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.
Files changed (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +400 -0
  3. package/dist/client.d.ts +43 -0
  4. package/dist/client.js +163 -0
  5. package/dist/client.js.map +1 -0
  6. package/dist/config.d.ts +37 -0
  7. package/dist/config.js +121 -0
  8. package/dist/config.js.map +1 -0
  9. package/dist/envfile.d.ts +21 -0
  10. package/dist/envfile.js +72 -0
  11. package/dist/envfile.js.map +1 -0
  12. package/dist/http.d.ts +7 -0
  13. package/dist/http.js +133 -0
  14. package/dist/http.js.map +1 -0
  15. package/dist/index.d.ts +2 -0
  16. package/dist/index.js +72 -0
  17. package/dist/index.js.map +1 -0
  18. package/dist/oauth/consent.d.ts +13 -0
  19. package/dist/oauth/consent.js +99 -0
  20. package/dist/oauth/consent.js.map +1 -0
  21. package/dist/oauth/router.d.ts +27 -0
  22. package/dist/oauth/router.js +329 -0
  23. package/dist/oauth/router.js.map +1 -0
  24. package/dist/oauth/seal.d.ts +22 -0
  25. package/dist/oauth/seal.js +82 -0
  26. package/dist/oauth/seal.js.map +1 -0
  27. package/dist/oauth/store.d.ts +40 -0
  28. package/dist/oauth/store.js +48 -0
  29. package/dist/oauth/store.js.map +1 -0
  30. package/dist/redact.d.ts +14 -0
  31. package/dist/redact.js +54 -0
  32. package/dist/redact.js.map +1 -0
  33. package/dist/server.d.ts +12 -0
  34. package/dist/server.js +47 -0
  35. package/dist/server.js.map +1 -0
  36. package/dist/tools/admin.d.ts +1 -0
  37. package/dist/tools/admin.js +99 -0
  38. package/dist/tools/admin.js.map +1 -0
  39. package/dist/tools/analytics.d.ts +1 -0
  40. package/dist/tools/analytics.js +141 -0
  41. package/dist/tools/analytics.js.map +1 -0
  42. package/dist/tools/common.d.ts +46 -0
  43. package/dist/tools/common.js +86 -0
  44. package/dist/tools/common.js.map +1 -0
  45. package/dist/tools/index.d.ts +3 -0
  46. package/dist/tools/index.js +7 -0
  47. package/dist/tools/index.js.map +1 -0
  48. package/dist/tools/reports.d.ts +1 -0
  49. package/dist/tools/reports.js +122 -0
  50. package/dist/tools/reports.js.map +1 -0
  51. package/dist/tools/websites.d.ts +1 -0
  52. package/dist/tools/websites.js +194 -0
  53. package/dist/tools/websites.js.map +1 -0
  54. package/package.json +54 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 M Asif Rahman
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 ADDED
@@ -0,0 +1,400 @@
1
+ # Umami MCP Server
2
+
3
+ A [Model Context Protocol](https://modelcontextprotocol.io) server for [Umami Analytics](https://umami.is).
4
+ Ask Claude, Cursor or any MCP client about your traffic — and let it create and manage websites — while your
5
+ credentials stay on your own machine.
6
+
7
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
8
+ ![Node](https://img.shields.io/badge/node-%3E%3D20-brightgreen)
9
+ ![Umami](https://img.shields.io/badge/Umami-v3-blue)
10
+
11
+ ```
12
+ "Which pages drove the most visitors last month, and where did that traffic come from?"
13
+ "Build a funnel from /pricing to /signup to /welcome for the last 30 days."
14
+ "Add analytics for my new site blog.example.com and give me the tracking snippet."
15
+ ```
16
+
17
+ ## Why this exists
18
+
19
+ Umami has no official MCP server. Several community ones exist, and if you just want broad API
20
+ coverage you should look at [`0xtlt/umami-mcp`](https://github.com/0xtlt/umami-mcp) first — it
21
+ wraps more of the API than this does. Some of the older servers
22
+ ([`jakeyShakey`](https://github.com/jakeyShakey/umami_mcp_server),
23
+ [`mikusnuz`](https://github.com/mikusnuz/umami-mcp),
24
+ [`mittwald`](https://github.com/mittwald/umami-mcp),
25
+ [`Macawls`](https://github.com/Macawls/umami-mcp-server)) were written against the **v2** API and
26
+ break on a modern instance, because v3 renamed things without aliases:
27
+
28
+ | | Umami v2 | Umami v3 |
29
+ |---|---|---|
30
+ | Top pages | `/metrics?type=url` | `/metrics?type=path` |
31
+ | Hostnames | `/metrics?type=host` | `/metrics?type=hostname` |
32
+ | UTM data | `/metrics?type=utm_source` | `POST /api/reports/utm` |
33
+ | Funnels, retention, journeys, attribution, revenue | — | `POST /api/reports/*` |
34
+
35
+ This server exists for two things the others do not do:
36
+
37
+ **1. Complete, verified v3 report coverage.** All seven v3 report types — funnel, retention,
38
+ journey, goal, revenue, attribution and UTM — were exercised against a live **Umami 3.3.1**
39
+ instance. The report envelope is easy to get wrong: dates go in `parameters` as ISO-8601 strings,
40
+ not in `filters`, and not as the epoch milliseconds the rest of the API uses. Attribution takes
41
+ `first-click` / `last-click`, not the camelCase spellings you would guess.
42
+
43
+ **2. A capability model rather than a boolean.** See below.
44
+
45
+ ## Security model
46
+
47
+ An analytics MCP server holds a credential that can read every visitor session you have ever
48
+ recorded — and, if you let it, delete the lot. The design follows from that.
49
+
50
+ **Your credentials never leave your environment.** Configuration is read only from the process
51
+ environment. There is no telemetry, no phone-home, and no hosted relay. The only host this
52
+ server ever contacts is the `UMAMI_URL` you set. If you self-host it, nothing about your
53
+ analytics ever reaches a third party — including the author of this software.
54
+
55
+ > Be wary of any Umami MCP that offers a hosted endpoint you point at your instance.
56
+ > Self-hosted Umami has no API keys, so "convenient" hosting means mailing your **admin
57
+ > password** to someone else's server.
58
+
59
+ **Least privilege by default.** The server starts in `read` mode. Widening is a deliberate act:
60
+
61
+ | Mode | Adds |
62
+ |---|---|
63
+ | `read` *(default)* | Analytics, reports, listing websites |
64
+ | `write` | Create and update websites and teams |
65
+ | `admin` | User management |
66
+ | `+ UMAMI_MCP_ALLOW_DESTRUCTIVE=true` | Delete website, reset data, delete user |
67
+
68
+ Withheld tools are **not registered at all**, so they never appear in the model's tool list.
69
+ This is the part that differs from a `READONLY=true` flag: a tool that was never advertised
70
+ cannot be invoked by a prompt-injected instruction hidden in, say, a referrer string or a page
71
+ title inside your own analytics data. There is no runtime check to forget or bypass, because
72
+ there is no tool.
73
+
74
+ **Destructive actions need a typed confirmation checked against reality.** `umami_delete_website`
75
+ takes a `confirmDomain` argument, fetches the live record, and refuses unless they match. A model
76
+ that reaches for the wrong website UUID gets an error, not a wiped dataset.
77
+
78
+ **Credentials stay out of client config.** Rather than requiring your password inside
79
+ `~/.claude.json` or `mcp.json`, the server reads it from a file you control at
80
+ `~/.config/umami-mcp/env`, and warns if that file is readable by other users. See
81
+ [Credentials](#credentials).
82
+
83
+ **Secrets are scrubbed from output.** MCP output flows into a model and often into a chat
84
+ transcript, which cannot be un-said. Passwords, bearer tokens and JWTs are redacted from every
85
+ error and response before they leave the process.
86
+
87
+ **Refuses to leak credentials over the wire.** Plaintext HTTP to a remote host is rejected at
88
+ startup; it is permitted only for `localhost`, for local development.
89
+
90
+ ## Install
91
+
92
+ Three ways to run it. **Self-hosting is the default and the recommended one** — the hosted
93
+ instance exists so you can try it in two minutes without cloning anything.
94
+
95
+ | | Runs where | Credentials live | Best for |
96
+ |---|---|---|---|
97
+ | **Hosted** | asif.dev | Sealed in your token, never stored | Trying it out; Claude web and Cowork |
98
+ | **Source** | Your machine | A file only you can read | Daily use in Claude Code |
99
+ | **Docker** | Your server | Your `.env` | Teams, always-on |
100
+
101
+ If you self-host and want it in Claude web, run it with `UMAMI_MCP_OAUTH=true` behind your own
102
+ domain — then nothing of yours touches anyone else's infrastructure.
103
+
104
+ ### 1. Use the hosted instance (nothing to install)
105
+
106
+ Add a custom connector in Claude pointing at:
107
+
108
+ ```
109
+ https://umami-mcp.asif.dev/mcp
110
+ ```
111
+
112
+ You will be asked for your own Umami URL and login on a consent screen. See
113
+ [Claude web, Cowork, and Claude Code on web](#claude-web-cowork-and-claude-code-on-web)
114
+ for how the credentials are handled.
115
+
116
+ ### 2. From source
117
+
118
+ ```bash
119
+ git clone https://github.com/Asif2BD/umami-mcp.git
120
+ cd umami-mcp
121
+ npm install && npm run build
122
+ ```
123
+
124
+ Then set up [credentials](#credentials) and register it with your client:
125
+
126
+ ```bash
127
+ claude mcp add umami --scope user -- node "$PWD/dist/index.js"
128
+ ```
129
+
130
+ Requires Node 20 or newer.
131
+
132
+ ### 3. Docker
133
+
134
+ ```bash
135
+ git clone https://github.com/Asif2BD/umami-mcp.git
136
+ cd umami-mcp
137
+ cp .env.example .env # then edit .env
138
+ docker compose up -d
139
+ ```
140
+
141
+ > **npm:** not published yet. Once it is, `npx -y @asif2bd/umami-mcp` will replace the
142
+ > clone-and-build step above. Until then use source or Docker.
143
+
144
+ ## Credentials
145
+
146
+ Self-hosted Umami has no API keys, so the credential this server holds is a **real account
147
+ password**. MCP clients normally want that embedded in their config JSON — `~/.claude.json`,
148
+ `mcp.json` and friends — which are widely readable, get pasted into issues and screen-shares, and
149
+ are synced between machines by some clients.
150
+
151
+ So this server reads credentials from a file you control instead. Create it once:
152
+
153
+ ```bash
154
+ mkdir -p ~/.config/umami-mcp
155
+ cat > ~/.config/umami-mcp/env <<'EOF'
156
+ UMAMI_URL=https://analytics.example.com
157
+ UMAMI_USERNAME=mcp-bot
158
+ UMAMI_PASSWORD=your-password
159
+ UMAMI_MCP_MODE=read
160
+ EOF
161
+ chmod 600 ~/.config/umami-mcp/env
162
+ ```
163
+
164
+ The server loads it automatically. It warns on startup if the file is readable by other users.
165
+
166
+ Lookup order — the first file found wins, and **real environment variables always override the
167
+ file**, so you can still pass settings from the client config when you want to:
168
+
169
+ 1. `$UMAMI_MCP_ENV_FILE`, if set
170
+ 2. `~/.config/umami-mcp/env` (or `$XDG_CONFIG_HOME/umami-mcp/env`)
171
+ 3. `./.env` in the working directory
172
+
173
+ ## Connect your client
174
+
175
+ ### Claude Code
176
+
177
+ With the credentials file above, the registration carries no secrets at all:
178
+
179
+ ```bash
180
+ claude mcp add umami --scope user -- node ~/umami-mcp/dist/index.js
181
+ ```
182
+
183
+ Use the absolute path to your checkout. If your Node lives under nvm, give the full
184
+ interpreter path too, since MCP clients do not load your shell profile:
185
+
186
+ ```bash
187
+ claude mcp add umami --scope user -- ~/.nvm/versions/node/v22.22.0/bin/node ~/umami-mcp/dist/index.js
188
+ ```
189
+
190
+ ### Claude Desktop / Cursor / VS Code
191
+
192
+ ```json
193
+ {
194
+ "mcpServers": {
195
+ "umami": {
196
+ "command": "node",
197
+ "args": ["/absolute/path/to/umami-mcp/dist/index.js"]
198
+ }
199
+ }
200
+ }
201
+ ```
202
+
203
+ If you would rather keep everything in one place, environment variables still work and take
204
+ precedence over the file:
205
+
206
+ ```json
207
+ {
208
+ "mcpServers": {
209
+ "umami": {
210
+ "command": "node",
211
+ "args": ["/absolute/path/to/umami-mcp/dist/index.js"],
212
+ "env": {
213
+ "UMAMI_URL": "https://analytics.example.com",
214
+ "UMAMI_USERNAME": "mcp-bot",
215
+ "UMAMI_PASSWORD": "your-password"
216
+ }
217
+ }
218
+ }
219
+ }
220
+ ```
221
+
222
+ ### Check it works
223
+
224
+ Ask your client to run `umami_whoami`. It reports the instance, the account, and the permission
225
+ mode — the fastest way to confirm the connection and see how much the server is allowed to do:
226
+
227
+ ```json
228
+ {
229
+ "instance": "https://analytics.example.com",
230
+ "authenticatedAs": "mcp-bot",
231
+ "role": "admin",
232
+ "serverMode": "read",
233
+ "destructiveOperations": "disabled"
234
+ }
235
+ ```
236
+
237
+ Then try: *"List my Umami websites"*, or *"What were my top pages last week?"*
238
+
239
+ ## Claude web, Cowork, and Claude Code on web
240
+
241
+ Those clients cannot launch a local process, so they need a public HTTPS MCP server — and their
242
+ connector UI accepts **OAuth only**, with no field for a static bearer token or custom header.
243
+
244
+ Hosting the obvious way, with one set of Umami credentials baked in and no authentication, turns
245
+ the URL into an open proxy to that Umami. So this server does OAuth instead, and does it without
246
+ becoming a credential store.
247
+
248
+ ### Use the hosted instance
249
+
250
+ Add a custom connector in Claude with this URL:
251
+
252
+ ```
253
+ https://umami-mcp.asif.dev/mcp
254
+ ```
255
+
256
+ Claude registers itself, sends you to a consent screen, and asks for **your own** Umami URL,
257
+ username and password. Nothing is shared with other users of the host.
258
+
259
+ ### Host your own
260
+
261
+ ```bash
262
+ UMAMI_MCP_OAUTH=true
263
+ UMAMI_MCP_TRANSPORT=http
264
+ UMAMI_MCP_ISSUER=https://mcp.example.com # public HTTPS URL of this server
265
+ UMAMI_MCP_TOKEN_KEY=<32 random bytes> # keep stable; see below
266
+ UMAMI_MCP_TOKEN_TTL=2592000 # 30 days
267
+ ```
268
+
269
+ Generate the key once and keep it:
270
+
271
+ ```bash
272
+ node -e "console.log(require('crypto').randomBytes(32).toString('base64url'))"
273
+ ```
274
+
275
+ Set `UMAMI_URL` as well to pin every user to one instance instead of letting them choose.
276
+
277
+ ### How the credentials are handled
278
+
279
+ The consent screen verifies the credentials against the Umami instance the user named, then seals
280
+ them into the access token with AES-256-GCM. The server keeps **no session table and stores no
281
+ credentials**: each request decrypts the token, builds an MCP server scoped to that one user,
282
+ serves the call, and discards it.
283
+
284
+ The honest trade-off: whoever holds `UMAMI_MCP_TOKEN_KEY` can decrypt any token they capture.
285
+ Treat it as the most sensitive value in the deployment. Rotating it invalidates every issued
286
+ token, which is the intended blast-radius control.
287
+
288
+ Destructive tools are **never** exposed over OAuth, whatever permission the user picks. Their
289
+ typed-confirmation guard assumes a local operator who can see what they are about to delete, and
290
+ a remote caller cannot be shown that.
291
+
292
+ ## Running it as a plain HTTP service
293
+
294
+ Set `UMAMI_MCP_TRANSPORT=http` without `UMAMI_MCP_OAUTH` for a single-tenant endpoint at `/mcp`,
295
+ plus `/health`.
296
+
297
+ **In this mode the server has no authentication of its own.** Anyone who can reach the port can
298
+ use your Umami credentials. Keep it on loopback and tunnel to it:
299
+
300
+ ```bash
301
+ ssh -N -L 3334:127.0.0.1:3334 you@your-server
302
+ claude mcp add --transport http umami http://127.0.0.1:3334/mcp
303
+ ```
304
+
305
+ The server warns at startup when it is bound to anything other than loopback.
306
+
307
+ ## Tools
308
+
309
+ | Tool | Requires | Description |
310
+ |---|---|---|
311
+ | `umami_list_websites` | read | List the websites tracked by this Umami instance, with their UUIDs |
312
+ | `umami_get_website` | read | Fetch a single website by UUID, including its domain, owner and creation date. |
313
+ | `umami_create_website` | write | Register a new website for tracking and return its UUID, which is the value to put in the data-website-id attribute of the Umami tracking script. |
314
+ | `umami_update_website` | write | Change a website's name, domain or share slug |
315
+ | `umami_reset_website` | destructive | PERMANENTLY DELETE all collected analytics data for a website, keeping the website itself |
316
+ | `umami_delete_website` | destructive | PERMANENTLY DELETE a website and every event ever recorded for it |
317
+ | `umami_get_tracking_snippet` | read | Return the ready-to-paste HTML script tag that sends data to this Umami instance for a given website. |
318
+ | `umami_get_stats` | read | Headline totals for a website over a period: pageviews, visitors, visits, bounces and total time on site |
319
+ | `umami_get_pageviews` | read | Pageviews and sessions bucketed over time, for charting traffic |
320
+ | `umami_get_metrics` | read | Top values for one dimension, ranked by visitor count -- top pages, referrers, countries, browsers and so on |
321
+ | `umami_get_active_visitors` | read | Number of visitors active on the site in the last few minutes |
322
+ | `umami_get_realtime` | read | Live snapshot of current activity: recent events with country, URL, browser and device, plus rollups by country, URL and referrer |
323
+ | `umami_get_event_stats` | read | Totals for custom tracked events over a period: event count, unique event names, visitors and visits, with a comparison against the preceding period. |
324
+ | `umami_list_sessions` | read | Individual visitor sessions with browser, OS, device, country and region |
325
+ | `umami_get_session_activity` | read | The ordered sequence of pageviews and events for one visitor session -- their path through the site. |
326
+ | `umami_report_utm` | read | Breakdown of traffic by UTM parameters: source, medium, campaign, term and content |
327
+ | `umami_report_funnel` | read | Step-by-step conversion funnel |
328
+ | `umami_report_retention` | read | Cohort retention: of the visitors first seen on a given day, how many returned on each subsequent day. |
329
+ | `umami_report_journey` | read | Most common ordered paths visitors take through the site, as sequences of pages with a count for each. |
330
+ | `umami_report_goal` | read | Progress toward a single goal: how many visitors hit a given path or custom event. |
331
+ | `umami_report_revenue` | read | Revenue over time from events carrying a revenue property, broken down by country, region, referrer and channel |
332
+ | `umami_report_attribution` | read | Credits conversions to acquisition channels -- referrer, paid ads and UTM parameters -- under either a first-click or last-click model. |
333
+ | `umami_list_users` | admin | List Umami user accounts with their roles |
334
+ | `umami_create_user` | admin | Create a Umami user account |
335
+ | `umami_delete_user` | destructive | PERMANENTLY DELETE a user account and the websites they own |
336
+ | `umami_list_teams` | read | List teams and their members. |
337
+ | `umami_create_team` | write | Create a team so websites can be shared between users. |
338
+ | `umami_whoami` | read | Verify that this MCP server can reach the configured Umami instance and report which account it is authenticated as, plus the permission mode the server is running in |
339
+
340
+ ### Time ranges
341
+
342
+ Every analytics tool accepts a `period` shorthand — `24h`, `7d`, `30d`, `12m`, `today`,
343
+ `yesterday` — instead of epoch milliseconds. Models are reliably good at "last 30 days" and
344
+ unreliably good at timestamp arithmetic, and a miscalculated epoch returns data for the wrong
345
+ window *without erroring*. Explicit `startAt`/`endAt` in epoch milliseconds still work and take
346
+ precedence.
347
+
348
+ ## Configuration
349
+
350
+ See [.env.example](.env.example) for every option. The essentials:
351
+
352
+ | Variable | Default | Purpose |
353
+ |---|---|---|
354
+ | `UMAMI_URL` | *required* | Your Umami instance |
355
+ | `UMAMI_USERNAME` / `UMAMI_PASSWORD` | | Self-hosted login |
356
+ | `UMAMI_API_KEY` | | Umami Cloud alternative |
357
+ | `UMAMI_MCP_MODE` | `read` | `read` / `write` / `admin` |
358
+ | `UMAMI_MCP_ALLOW_DESTRUCTIVE` | `false` | Unlock delete and reset |
359
+ | `UMAMI_MCP_TRANSPORT` | `stdio` | `stdio` or `http` |
360
+ | `UMAMI_MCP_HOST` | `127.0.0.1` | HTTP bind address |
361
+ | `UMAMI_MCP_PORT` | `3334` | HTTP port |
362
+ | `UMAMI_MCP_ENV_FILE` | | Explicit path to a credentials file |
363
+
364
+ ## Recommended setup
365
+
366
+ Create a dedicated Umami account for the MCP server rather than reusing your admin login, and
367
+ give it only the websites it needs. Then, if the credential is ever exposed, the blast radius is
368
+ one bot account you can delete — not your administrator.
369
+
370
+ ## Compatibility
371
+
372
+ Verified against **Umami 3.3.1** (self-hosted, PostgreSQL). Umami Cloud works via `UMAMI_API_KEY`.
373
+ Umami v2 is not supported: the renamed metric types above mean v2 and v3 need different clients,
374
+ and this one targets v3.
375
+
376
+ ## Development
377
+
378
+ ```bash
379
+ npm install
380
+ npm run build
381
+ npm test # unit tests, no network required
382
+ ```
383
+
384
+ `test/e2e.mjs` and `test/write-e2e.mjs` drive the built server through a real MCP client against
385
+ a live instance. The write test creates a throwaway website on a `.invalid` domain and deletes it
386
+ again; point it at a non-production instance.
387
+
388
+ ## Contributing
389
+
390
+ Issues and pull requests welcome. Umami v3 exposes around 127 API routes and this server covers
391
+ the most useful ones — session replay, heatmaps, pixels, link tracking, boards and segments are
392
+ all still unmapped. If you add tools, keep the tier and `destructive` flags honest, because the
393
+ whole safety model rests on them.
394
+
395
+ If the Umami team would like to adopt, fork or upstream this, please open an issue — that is the
396
+ outcome this was built for.
397
+
398
+ ## License
399
+
400
+ MIT © M Asif Rahman
@@ -0,0 +1,43 @@
1
+ import type { Config } from './config.js';
2
+ /**
3
+ * A thin, dependency-free client for the Umami HTTP API.
4
+ *
5
+ * Self-hosted Umami has no API keys: you POST credentials to /api/auth/login
6
+ * and receive a bearer token. That token is held in memory only, never
7
+ * written to disk, and refreshed automatically when the server rejects it.
8
+ * Umami Cloud does issue API keys, which are sent as x-umami-api-key instead.
9
+ */
10
+ export declare class UmamiError extends Error {
11
+ readonly status?: number | undefined;
12
+ readonly path?: string | undefined;
13
+ constructor(message: string, status?: number | undefined, path?: string | undefined);
14
+ }
15
+ type Query = Record<string, string | number | boolean | undefined | null>;
16
+ export declare class UmamiClient {
17
+ private readonly config;
18
+ private token?;
19
+ private loginInFlight?;
20
+ constructor(config: Config);
21
+ private get usesApiKey();
22
+ /** Authenticate and cache the bearer token. Concurrent callers share one login. */
23
+ private login;
24
+ private authHeaders;
25
+ private raw;
26
+ private errorBody;
27
+ /** Perform an authenticated API call, retrying once if the token expired. */
28
+ request<T = unknown>(method: string, path: string, opts?: {
29
+ query?: Query;
30
+ body?: unknown;
31
+ }): Promise<T>;
32
+ get<T = unknown>(path: string, query?: Query): Promise<T>;
33
+ post<T = unknown>(path: string, body?: unknown, query?: Query): Promise<T>;
34
+ del<T = unknown>(path: string, query?: Query): Promise<T>;
35
+ /** Verify credentials and reachability. Returns the authenticated user. */
36
+ verify(): Promise<{
37
+ username?: string;
38
+ role?: string;
39
+ isAdmin?: boolean;
40
+ }>;
41
+ }
42
+ export declare function buildQuery(query?: Query): string;
43
+ export {};
package/dist/client.js ADDED
@@ -0,0 +1,163 @@
1
+ import { redact, redactUnknown } from './redact.js';
2
+ /**
3
+ * A thin, dependency-free client for the Umami HTTP API.
4
+ *
5
+ * Self-hosted Umami has no API keys: you POST credentials to /api/auth/login
6
+ * and receive a bearer token. That token is held in memory only, never
7
+ * written to disk, and refreshed automatically when the server rejects it.
8
+ * Umami Cloud does issue API keys, which are sent as x-umami-api-key instead.
9
+ */
10
+ export class UmamiError extends Error {
11
+ status;
12
+ path;
13
+ constructor(message, status, path) {
14
+ super(message);
15
+ this.status = status;
16
+ this.path = path;
17
+ this.name = 'UmamiError';
18
+ }
19
+ }
20
+ export class UmamiClient {
21
+ config;
22
+ token;
23
+ loginInFlight;
24
+ constructor(config) {
25
+ this.config = config;
26
+ }
27
+ get usesApiKey() {
28
+ return Boolean(this.config.apiKey);
29
+ }
30
+ /** Authenticate and cache the bearer token. Concurrent callers share one login. */
31
+ async login() {
32
+ if (this.loginInFlight)
33
+ return this.loginInFlight;
34
+ this.loginInFlight = (async () => {
35
+ const res = await this.raw('/api/auth/login', {
36
+ method: 'POST',
37
+ headers: { 'content-type': 'application/json' },
38
+ body: JSON.stringify({
39
+ username: this.config.username,
40
+ password: this.config.password,
41
+ }),
42
+ });
43
+ if (!res.ok) {
44
+ const detail = res.status === 401 ? 'check UMAMI_USERNAME and UMAMI_PASSWORD' : await this.errorBody(res);
45
+ throw new UmamiError(`Login failed (HTTP ${res.status}): ${detail}`, res.status, '/api/auth/login');
46
+ }
47
+ const body = (await res.json());
48
+ if (!body.token) {
49
+ throw new UmamiError('Login succeeded but returned no token', res.status, '/api/auth/login');
50
+ }
51
+ this.token = body.token;
52
+ return body.token;
53
+ })();
54
+ try {
55
+ return await this.loginInFlight;
56
+ }
57
+ finally {
58
+ this.loginInFlight = undefined;
59
+ }
60
+ }
61
+ async authHeaders() {
62
+ if (this.usesApiKey)
63
+ return { 'x-umami-api-key': this.config.apiKey };
64
+ const token = this.token ?? (await this.login());
65
+ return { authorization: `Bearer ${token}` };
66
+ }
67
+ async raw(path, init) {
68
+ const controller = new AbortController();
69
+ const timer = setTimeout(() => controller.abort(), this.config.timeoutMs);
70
+ try {
71
+ return await fetch(this.config.url + path, { ...init, signal: controller.signal });
72
+ }
73
+ catch (err) {
74
+ if (controller.signal.aborted) {
75
+ throw new UmamiError(`Request to ${path} timed out after ${this.config.timeoutMs}ms`, undefined, path);
76
+ }
77
+ throw new UmamiError(`Request to ${path} failed: ${redactUnknown(err)}`, undefined, path);
78
+ }
79
+ finally {
80
+ clearTimeout(timer);
81
+ }
82
+ }
83
+ async errorBody(res) {
84
+ let text;
85
+ try {
86
+ text = await res.text();
87
+ }
88
+ catch {
89
+ return res.statusText || 'no response body';
90
+ }
91
+ try {
92
+ const parsed = JSON.parse(text);
93
+ const msg = typeof parsed.error === 'string' ? parsed.error : parsed.error?.message;
94
+ if (msg)
95
+ return redact(msg);
96
+ }
97
+ catch {
98
+ /* not JSON; fall through */
99
+ }
100
+ return redact(text.slice(0, 400)) || res.statusText;
101
+ }
102
+ /** Perform an authenticated API call, retrying once if the token expired. */
103
+ async request(method, path, opts = {}) {
104
+ const qs = buildQuery(opts.query);
105
+ const fullPath = path + qs;
106
+ const attempt = async () => {
107
+ const headers = { ...(await this.authHeaders()), accept: 'application/json' };
108
+ const init = { method, headers };
109
+ if (opts.body !== undefined) {
110
+ headers['content-type'] = 'application/json';
111
+ init.body = JSON.stringify(opts.body);
112
+ }
113
+ return this.raw(fullPath, init);
114
+ };
115
+ let res = await attempt();
116
+ // A cached token can expire mid-session; re-login once and retry.
117
+ if (res.status === 401 && !this.usesApiKey) {
118
+ this.token = undefined;
119
+ res = await attempt();
120
+ }
121
+ if (!res.ok) {
122
+ throw new UmamiError(`Umami API ${method} ${path} failed (HTTP ${res.status}): ${await this.errorBody(res)}`, res.status, path);
123
+ }
124
+ if (res.status === 204)
125
+ return undefined;
126
+ const text = await res.text();
127
+ if (!text)
128
+ return undefined;
129
+ try {
130
+ return JSON.parse(text);
131
+ }
132
+ catch {
133
+ throw new UmamiError(`Umami API ${method} ${path} returned malformed JSON`, res.status, path);
134
+ }
135
+ }
136
+ get(path, query) {
137
+ return this.request('GET', path, { query });
138
+ }
139
+ post(path, body, query) {
140
+ return this.request('POST', path, { body, query });
141
+ }
142
+ del(path, query) {
143
+ return this.request('DELETE', path, { query });
144
+ }
145
+ /** Verify credentials and reachability. Returns the authenticated user. */
146
+ async verify() {
147
+ const me = await this.get('/api/me');
148
+ return me.user ?? {};
149
+ }
150
+ }
151
+ export function buildQuery(query) {
152
+ if (!query)
153
+ return '';
154
+ const params = new URLSearchParams();
155
+ for (const [k, v] of Object.entries(query)) {
156
+ if (v === undefined || v === null || v === '')
157
+ continue;
158
+ params.set(k, String(v));
159
+ }
160
+ const s = params.toString();
161
+ return s ? `?${s}` : '';
162
+ }
163
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAEpD;;;;;;;GAOG;AAEH,MAAM,OAAO,UAAW,SAAQ,KAAK;IAGxB;IACA;IAHX,YACE,OAAe,EACN,MAAe,EACf,IAAa;QAEtB,KAAK,CAAC,OAAO,CAAC,CAAC;QAHN,WAAM,GAAN,MAAM,CAAS;QACf,SAAI,GAAJ,IAAI,CAAS;QAGtB,IAAI,CAAC,IAAI,GAAG,YAAY,CAAC;IAC3B,CAAC;CACF;AAID,MAAM,OAAO,WAAW;IAIO;IAHrB,KAAK,CAAU;IACf,aAAa,CAAmB;IAExC,YAA6B,MAAc;QAAd,WAAM,GAAN,MAAM,CAAQ;IAAG,CAAC;IAE/C,IAAY,UAAU;QACpB,OAAO,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IACrC,CAAC;IAED,mFAAmF;IAC3E,KAAK,CAAC,KAAK;QACjB,IAAI,IAAI,CAAC,aAAa;YAAE,OAAO,IAAI,CAAC,aAAa,CAAC;QAElD,IAAI,CAAC,aAAa,GAAG,CAAC,KAAK,IAAI,EAAE;YAC/B,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,GAAG,CAAC,iBAAiB,EAAE;gBAC5C,MAAM,EAAE,MAAM;gBACd,OAAO,EAAE,EAAE,cAAc,EAAE,kBAAkB,EAAE;gBAC/C,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC;oBACnB,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,QAAQ;oBAC9B,QAAQ,EAAE,I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ACF;AAED,MAAM,UAAU,UAAU,CAAC,KAAa;IACtC,IAAI,CAAC,KAAK;QAAE,OAAO,EAAE,CAAC;IACtB,MAAM,MAAM,GAAG,IAAI,eAAe,EAAE,CAAC;IACrC,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QAC3C,IAAI,CAAC,KAAK,SAAS,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,EAAE;YAAE,SAAS;QACxD,MAAM,CAAC,GAAG,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;IAC3B,CAAC;IACD,MAAM,CAAC,GAAG,MAAM,CAAC,QAAQ,EAAE,CAAC;IAC5B,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;AAC1B,CAAC"}
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Configuration is read exclusively from the process environment.
3
+ *
4
+ * Nothing here is ever transmitted anywhere except to the single Umami
5
+ * instance named by UMAMI_URL. There is no telemetry, no phone-home, and no
6
+ * remote credential broker. If you self-host this server, your credentials
7
+ * stay on your machine.
8
+ */
9
+ export type Mode = 'read' | 'write' | 'admin';
10
+ export type Transport = 'stdio' | 'http';
11
+ export interface OAuthConfig {
12
+ enabled: boolean;
13
+ issuer: string;
14
+ tokenKey: string;
15
+ ttlSeconds: number;
16
+ /** When set, every user is pinned to this Umami rather than choosing one. */
17
+ fixedUrl?: string;
18
+ }
19
+ export interface Config {
20
+ url: string;
21
+ username?: string;
22
+ password?: string;
23
+ apiKey?: string;
24
+ teamId?: string;
25
+ mode: Mode;
26
+ allowDestructive: boolean;
27
+ transport: Transport;
28
+ host: string;
29
+ port: number;
30
+ timeoutMs: number;
31
+ oauth?: OAuthConfig;
32
+ }
33
+ export declare class ConfigError extends Error {
34
+ }
35
+ export declare function loadConfig(env?: NodeJS.ProcessEnv): Config;
36
+ /** Human-readable summary for startup logs. Never includes secrets. */
37
+ export declare function describeConfig(c: Config): string;