@kaminari-ad/mcp 0.5.2 → 0.6.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/CHANGELOG.md CHANGED
@@ -7,6 +7,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.6.0] - 2026-06-30
11
+
12
+ ### Changed
13
+
14
+ - **HTTP transport is now stateless** (`StreamableHTTPServerTransport` with
15
+ `sessionIdGenerator: undefined`). The server no longer issues an
16
+ `Mcp-Session-Id`; it builds a fresh, single-use MCP server + transport per
17
+ request and authenticates each request independently by its own Bearer. This
18
+ lets `mcp.kaminari.ad` run multiple replicas behind a round-robin load
19
+ balancer with no sticky sessions and no shared session store — fixing the
20
+ mid-session failures that appeared after the Traefik edge cutover. It aligns
21
+ with the MCP stateless direction (SEP-2575 / SEP-2567) and improves
22
+ ChatGPT-connector compatibility (the connector opens a new session per tool
23
+ call, which a stateful server handles poorly).
24
+
25
+ ### Removed
26
+
27
+ - In-memory session store, the session-id <-> bearer binding, and the
28
+ `KAMINARI_AD_SESSION_TTL_SEC` env var — all obsolete in stateless mode. The
29
+ only remaining mutable store is the per-bearer rate limiter.
30
+
10
31
  ## [0.5.2] - 2026-06-20
11
32
 
12
33
  ### Security
package/README.md CHANGED
@@ -198,7 +198,7 @@ We follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html) for the two
198
198
 
199
199
  ## Privacy
200
200
 
201
- - **Data collected by the MCP server itself:** none beyond the `Authorization` header it forwards. In HTTP mode, only ephemeral per-request scoped state (session id Bearer hash, leaky-bucket rate limit by Bearer hash) is held in memory.
201
+ - **Data collected by the MCP server itself:** none beyond the `Authorization` header it forwards. The HTTP transport is stateless — no sessions are persisted; each request is authenticated independently by its own Bearer. The only in-memory state is the leaky-bucket rate limiter keyed by `sha256(bearer)`.
202
202
  - **Data forwarded to Kaminari Ad:** every tool call is a thin pass-through to `/api/v1` over HTTPS. The Kaminari Ad privacy policy applies: [https://kaminari.ad/legal/privacy](https://kaminari.ad/legal/privacy).
203
203
  - **Logs:** structured pino output, JSON in HTTP mode. The full Bearer token is redacted; only `bearer_hash = sha256(token).slice(0,8)` makes it into a log line, alongside `request_id`, `tool_name`, `api_status`, `elapsed_ms`. Tool inputs (which may contain customer scan IDs / URLs) are NOT logged.
204
204
  - **Telemetry:** none. The OSS build ships a `NoopErrorReporter`. We do not bundle Sentry, OpenTelemetry exporters, or PostHog.
package/dist/bin.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { NAME, VERSION, err, ok } from './chunk-SQVFFWOB.js';
2
+ import { NAME, VERSION, err, ok } from './chunk-CEKRYHCR.js';
3
3
  import process from 'process';
4
4
  import { z } from 'zod';
5
5
 
@@ -69,7 +69,6 @@ var RawSchema = z.object({
69
69
  KAMINARI_AD_LOG_LEVEL: LogLevelSchema.default("info"),
70
70
  KAMINARI_AD_LOG_FORMAT: LogFormatSchema.optional(),
71
71
  KAMINARI_AD_HTTP_PORT: z.coerce.number().int().min(0).max(65535).default(8080),
72
- KAMINARI_AD_SESSION_TTL_SEC: z.coerce.number().int().min(60).max(86400).default(1800),
73
72
  KAMINARI_AD_RATE_LIMIT_RPM: z.coerce.number().int().min(1).max(1e4).default(120),
74
73
  KAMINARI_AD_API_KEY: z.string().min(8).optional(),
75
74
  // OAuth discovery (RFC 9728 protected-resource + RFC 8414 AS
@@ -98,7 +97,6 @@ function loadConfig(env) {
98
97
  logLevel: raw.KAMINARI_AD_LOG_LEVEL,
99
98
  logFormat,
100
99
  httpPort: raw.KAMINARI_AD_HTTP_PORT,
101
- sessionTtlSec: raw.KAMINARI_AD_SESSION_TTL_SEC,
102
100
  rateLimitRpm: raw.KAMINARI_AD_RATE_LIMIT_RPM,
103
101
  stdioApiKey: raw.KAMINARI_AD_API_KEY,
104
102
  oauthProtectedResource: raw.KAMINARI_AD_OAUTH_PROTECTED_RESOURCE,
@@ -162,10 +160,10 @@ async function main() {
162
160
  }
163
161
  const config = configResult.value;
164
162
  if (config.transport === "stdio") {
165
- const { bootstrapStdio } = await import('./stdio-bootstrap-JBLNH46R.js');
163
+ const { bootstrapStdio } = await import('./stdio-bootstrap-4UHUIN7N.js');
166
164
  return bootstrapStdio(config);
167
165
  }
168
- const { bootstrapHttp } = await import('./http-bootstrap-X2Y2VGBO.js');
166
+ const { bootstrapHttp } = await import('./http-bootstrap-DAPC3LFX.js');
169
167
  return bootstrapHttp(config);
170
168
  }
171
169
  main().then(
package/dist/bin.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/shared/check-node-version.ts","../src/shared/oauth-scope-catalogue.ts","../src/shared/config.ts","../src/bin.ts"],"names":[],"mappings":";;;;;;AAoBO,IAAM,mBAAA,GAAsB,EAAA;AAC5B,IAAM,mBAAA,GAAsB,EAAA;AAU5B,SAAS,iBAAiB,WAAA,EAAgD;AAC/E,EAAA,MAAM,KAAA,GAAQ,WAAA,CAAY,KAAA,CAAM,GAAG,CAAA;AACnC,EAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,KAAA,CAAM,CAAC,CAAC,CAAA;AAC7B,EAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,KAAA,CAAM,CAAC,CAAC,CAAA;AAC7B,EAAA,IACE,MAAA,CAAO,KAAA,CAAM,KAAK,CAAA,IAClB,MAAA,CAAO,KAAA,CAAM,KAAK,CAAA,IAClB,KAAA,GAAQ,mBAAA,IACP,KAAA,KAAU,mBAAA,IAAuB,QAAQ,mBAAA,EAC1C;AACA,IAAA,MAAM,QAAA,GAAW,KAAK,MAAA,CAAO,mBAAmB,CAAC,CAAA,CAAA,EAAI,MAAA,CAAO,mBAAmB,CAAC,CAAA,EAAA,CAAA;AAChF,IAAA,OAAO,GAAA;AAAA,MACL;AAAA,QACE,CAAA,EAAG,IAAI,CAAA,kBAAA,EAAqB,QAAQ,eAAe,WAAW,CAAA,EAAA,CAAA;AAAA,QAC9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* can be unit-tested without `process.exit` side effects.\n *\n * Why this exists: `undici@8.x` removed feature probes in v8.0.3 and\n * imports `markAsUncloneable` from `node:worker_threads`\n * unconditionally — that symbol only exists on Node 22.19+. Older\n * Node versions crash at import time with the cryptic message\n * `webidl.util.markAsUncloneable is not a function`. We surface a\n * clean upgrade message instead, BEFORE any dynamic import pulls\n * undici.\n *\n * Keep {@link REQUIRED_NODE_MAJOR} / {@link REQUIRED_NODE_MINOR} in\n * sync with `engines.node` in `package.json` (currently\n * `>=22.19.0`).\n */\n\nimport { err, ok, type Result } from \"./result.js\";\nimport { NAME } from \"./version.js\";\n\nexport const REQUIRED_NODE_MAJOR = 22;\nexport const REQUIRED_NODE_MINOR = 19;\n\n/**\n * Check whether `nodeVersion` (e.g. `\"22.19.0\"`, the value of\n * `process.versions.node`) satisfies the package's runtime floor.\n *\n * Returns `Ok(undefined)` on pass, `Err(message)` with a multi-line\n * upgrade message on fail. The message is plain text ready to be\n * written to stderr verbatim.\n */\nexport function checkNodeVersion(nodeVersion: string): Result<undefined, string> {\n const parts = nodeVersion.split(\".\");\n const major = Number(parts[0]);\n const minor = Number(parts[1]);\n if (\n Number.isNaN(major) ||\n Number.isNaN(minor) ||\n major < REQUIRED_NODE_MAJOR ||\n (major === REQUIRED_NODE_MAJOR && minor < REQUIRED_NODE_MINOR)\n ) {\n const required = `>=${String(REQUIRED_NODE_MAJOR)}.${String(REQUIRED_NODE_MINOR)}.0`;\n return err(\n [\n `${NAME} requires Node.js ${required} (you have v${nodeVersion}).`,\n \"\",\n \"The underlying undici 8.x HTTP client uses markAsUncloneable\",\n \"from node:worker_threads, available only on Node 22.19+.\",\n \"Older Node crashes at import time with the cryptic message\",\n \"`webidl.util.markAsUncloneable is not a function`.\",\n \"\",\n \"Please upgrade Node and re-run: https://nodejs.org/en/download\",\n ].join(\"\\n\")\n );\n }\n return ok(undefined);\n}\n","/**\n * Canonical catalogue of OAuth 2.0 scopes the Kaminari Ad MCP server\n * advertises in its protected-resource metadata (RFC 9728) and\n * `WWW-Authenticate: Bearer scope=\"...\"` challenge.\n *\n * The catalogue is intentionally static and lives in `shared/` because\n * (a) it has no runtime behaviour — it is data — and (b) it is read by\n * both the `protected-resource-metadata-handler` and the\n * `www-authenticate` builder. If a new scope is added on the\n * Authorization Server side, mirror it here in the same release so the\n * Resource Server (this process) advertises it.\n *\n * `offline_access` is part of the catalogue per RFC 6749 §6 because\n * the Authorization Server issues refresh tokens only when the client\n * requests this scope. Anthropic's Claude clients append it\n * automatically when the server advertises it in\n * `scopes_supported`/the `WWW-Authenticate` `scope=` parameter.\n */\n\n/**\n * Default scope catalogue, frozen at build time.\n *\n * MUST stay byte-identical to the Authorization Server's advertised\n * catalogue (`app.oauth_authorization.domain.entities.scope.advertised_scopes()`\n * — i.e. `sorted(KNOWN_SCOPES)`). The order is lexicographic, which\n * happens to yield the desired semantics for free: `:read` sorts before\n * `:write` within a resource, and `offline_access` sorts after every\n * `mcp:` scope.\n *\n * Read scopes grant the resource's view permission; write scopes grant\n * read + the resource's mutating permissions. billing/invoicing/account\n * are read-only over OAuth by design (money-spend / privilege-escalation\n * tools stay API-key only). When the AS catalogue changes, mirror it\n * here in the same release — `tests/unit/shared/oauth-scope-catalogue.test.ts`\n * pins the exact list so drift fails CI.\n */\nexport const DEFAULT_OAUTH_SCOPES: readonly string[] = Object.freeze([\n \"mcp:account:read\",\n \"mcp:alert_notifications:read\",\n \"mcp:alert_notifications:write\",\n \"mcp:alerts:read\",\n \"mcp:alerts:write\",\n \"mcp:billing:read\",\n \"mcp:campaigns:read\",\n \"mcp:campaigns:write\",\n \"mcp:custom_rules:read\",\n \"mcp:custom_rules:write\",\n \"mcp:invoicing:read\",\n \"mcp:policies:read\",\n \"mcp:policies:write\",\n \"mcp:scans:read\",\n \"mcp:scans:write\",\n \"mcp:tags:read\",\n \"mcp:tags:write\",\n \"mcp:taxonomies:read\",\n \"mcp:taxonomies:write\",\n \"mcp:webhooks:read\",\n \"mcp:webhooks:write\",\n \"offline_access\",\n]);\n","/**\n * Runtime configuration for `@kaminari-ad/mcp`.\n *\n * The single source of truth for all env-var reads. `process.env.X`\n * outside this file is a code-review blocker — every config value flows\n * through the zod-parsed {@link Config} object.\n */\n\nimport { z } from \"zod\";\n\nimport { DEFAULT_OAUTH_SCOPES } from \"./oauth-scope-catalogue.js\";\nimport { err, ok, type Result } from \"./result.js\";\n\n/**\n * MCP transport. `stdio` is for local install (one process per user);\n * `http` is for the hosted multi-tenant endpoint.\n */\nexport const TransportSchema = z.enum([\"stdio\", \"http\"]);\nexport type Transport = z.infer<typeof TransportSchema>;\n\n/**\n * pino log level.\n */\nexport const LogLevelSchema = z.enum([\"trace\", \"debug\", \"info\", \"warn\", \"error\", \"fatal\"]);\nexport type LogLevel = z.infer<typeof LogLevelSchema>;\n\n/**\n * pino log output format.\n *\n * - `pretty` — colorised single-line ANSI output for terminals. Default\n * in stdio mode (operator reads stderr in their shell).\n * - `json` — newline-delimited JSON, one record per line. Default in\n * HTTP mode (Docker/k8s log aggregators expect JSON). MCP hosts that\n * capture stderr from the stdio process (Cursor, Claude Desktop)\n * parse much better with `json` — flip this when the operator is a\n * machine, not a human.\n */\nexport const LogFormatSchema = z.enum([\"pretty\", \"json\"]);\nexport type LogFormat = z.infer<typeof LogFormatSchema>;\n\n/**\n * Parsed configuration. All fields are `readonly` — mutation post-load\n * is a bug.\n */\nexport interface Config {\n readonly transport: Transport;\n readonly apiBaseUrl: string;\n readonly logLevel: LogLevel;\n readonly logFormat: LogFormat;\n readonly httpPort: number;\n readonly sessionTtlSec: number;\n readonly rateLimitRpm: number;\n /**\n * Set only in stdio mode. In HTTP mode the bootstrap MUST assert\n * this is `undefined` (see CONTRIBUTING.md \"Tenant isolation\" §5).\n */\n readonly stdioApiKey: string | undefined;\n /**\n * Canonical MCP endpoint URL advertised as the `resource` field of\n * the RFC 9728 protected-resource metadata document. Anthropic's\n * Claude clients require this to match the URL the user enters in\n * Claude exactly (including the path component).\n */\n readonly oauthProtectedResource: string;\n /**\n * Absolute URL where this server serves the protected-resource\n * metadata JSON. Advertised back to clients via\n * `WWW-Authenticate: Bearer resource_metadata=\"…\"` on 401.\n */\n readonly oauthProtectedResourceMetadataUrl: string;\n /**\n * Issuer URL of the Authorization Server that mints access tokens\n * accepted by this Resource Server. Advertised as the first (and\n * only) entry of the metadata's `authorization_servers` array.\n */\n readonly oauthAuthorizationServerUrl: string;\n /**\n * Scopes the Resource Server advertises in both the metadata's\n * `scopes_supported` field and the 401 `WWW-Authenticate scope=…`\n * parameter. Defaults to {@link DEFAULT_OAUTH_SCOPES}; operators\n * may override via `KAMINARI_AD_OAUTH_SCOPES` (space-separated).\n */\n readonly oauthScopes: readonly string[];\n}\n\n/**\n * Every env var carries the `KAMINARI_AD_` namespace prefix.\n *\n * Why: this process inherits the host's full environment (Cursor /\n * Claude Desktop / Docker compose / k8s pod), where `API_BASE_URL` /\n * `LOG_LEVEL` / `HTTP_PORT` are common generic names. Without a\n * namespace, another tool in the same shell trivially poisons our\n * config — e.g. `LOG_LEVEL=debug` set for some app library suddenly\n * makes the MCP server log every secret-redacted-but-still-noisy\n * request to stderr, and the user has no idea why. With the prefix\n * the boundary is explicit and `env | grep KAMINARI_AD_` enumerates\n * exactly what we read.\n */\nconst RawSchema = z.object({\n KAMINARI_AD_TRANSPORT: TransportSchema.default(\"stdio\"),\n // `app.kaminari.ad` is the API host; `kaminari.ad` (no subdomain)\n // is the marketing landing page and does NOT serve /api/v1/*.\n // Setting this wrong (e.g. the root domain) makes every tool call\n // fail with HTTP 404 — the symptom that surfaced this default bug\n // in v0.2.0.\n KAMINARI_AD_API_URL: z.string().url().default(\"https://app.kaminari.ad\"),\n KAMINARI_AD_LOG_LEVEL: LogLevelSchema.default(\"info\"),\n KAMINARI_AD_LOG_FORMAT: LogFormatSchema.optional(),\n KAMINARI_AD_HTTP_PORT: z.coerce.number().int().min(0).max(65535).default(8080),\n KAMINARI_AD_SESSION_TTL_SEC: z.coerce.number().int().min(60).max(86_400).default(1800),\n KAMINARI_AD_RATE_LIMIT_RPM: z.coerce.number().int().min(1).max(10_000).default(120),\n KAMINARI_AD_API_KEY: z.string().min(8).optional(),\n // OAuth discovery (RFC 9728 protected-resource + RFC 8414 AS\n // metadata). All three URLs default to the production deployment;\n // local/staging operators override per-environment.\n KAMINARI_AD_OAUTH_PROTECTED_RESOURCE: z.string().url().default(\"https://mcp.kaminari.ad/mcp\"),\n KAMINARI_AD_OAUTH_PROTECTED_RESOURCE_METADATA_URL: z\n .string()\n .url()\n .default(\"https://mcp.kaminari.ad/.well-known/oauth-protected-resource\"),\n KAMINARI_AD_OAUTH_AUTHORIZATION_SERVER_URL: z.string().url().default(\"https://app.kaminari.ad\"),\n // Space-separated scope list. We split on /\\s+/ post-parse and drop\n // empty tokens so accidental double-spaces don't corrupt the array.\n KAMINARI_AD_OAUTH_SCOPES: z.string().optional(),\n});\n\n/**\n * Parse and validate environment variables into a {@link Config}.\n *\n * Returns `Err<ConfigError>` on validation failure. Caller (typically\n * `bin.ts`) prints the error and exits non-zero.\n *\n * `KAMINARI_AD_LOG_FORMAT` defaults are transport-dependent: `pretty`\n * for stdio (terminal-facing) and `json` for http (aggregator-facing).\n * If the user sets the env var explicitly, that wins.\n */\nexport function loadConfig(env: NodeJS.ProcessEnv): Result<Config, ConfigError> {\n const parsed = RawSchema.safeParse(env);\n if (!parsed.success) {\n return err({ kind: \"invalid\", issues: parsed.error.flatten().fieldErrors });\n }\n const raw = parsed.data;\n const transport = raw.KAMINARI_AD_TRANSPORT;\n const logFormat = raw.KAMINARI_AD_LOG_FORMAT ?? (transport === \"stdio\" ? \"pretty\" : \"json\");\n const oauthScopesRaw = raw.KAMINARI_AD_OAUTH_SCOPES;\n const oauthScopes: readonly string[] =\n oauthScopesRaw === undefined\n ? DEFAULT_OAUTH_SCOPES\n : Object.freeze(oauthScopesRaw.split(/\\s+/).filter((s) => s.length > 0));\n return ok({\n transport,\n apiBaseUrl: raw.KAMINARI_AD_API_URL,\n logLevel: raw.KAMINARI_AD_LOG_LEVEL,\n logFormat,\n httpPort: raw.KAMINARI_AD_HTTP_PORT,\n sessionTtlSec: raw.KAMINARI_AD_SESSION_TTL_SEC,\n rateLimitRpm: raw.KAMINARI_AD_RATE_LIMIT_RPM,\n stdioApiKey: raw.KAMINARI_AD_API_KEY,\n oauthProtectedResource: raw.KAMINARI_AD_OAUTH_PROTECTED_RESOURCE,\n oauthProtectedResourceMetadataUrl: raw.KAMINARI_AD_OAUTH_PROTECTED_RESOURCE_METADATA_URL,\n oauthAuthorizationServerUrl: raw.KAMINARI_AD_OAUTH_AUTHORIZATION_SERVER_URL,\n oauthScopes,\n });\n}\n\n/**\n * Errors from {@link loadConfig}.\n */\nexport interface ConfigError {\n readonly kind: \"invalid\";\n readonly issues: Readonly<Record<string, readonly string[] | undefined>>;\n}\n","/**\n * CLI entrypoint for `@kaminari-ad/mcp`.\n *\n * Dispatches to a transport-specific composition root (stdio or HTTP)\n * based on the `--transport` flag (or `TRANSPORT` env var, with stdio\n * as the default).\n *\n * Wire-up is intentionally minimal — every dependency is constructed\n * inside the chosen bootstrap, never here. This file just parses argv\n * and config, then hands off.\n *\n * Imports policy: the STATIC imports below MUST stay free of any\n * runtime dependency that requires Node >= 22.19 (undici, MCP SDK,\n * pino). Otherwise the Node-version preflight in `main()` runs too\n * late — those modules crash at import time on older Node. The\n * transport bootstraps pull undici / MCP SDK / pino via dynamic\n * `await import()` so the preflight gets to fire first.\n */\n\nimport process from \"node:process\";\n\nimport { checkNodeVersion } from \"./shared/check-node-version.js\";\nimport { loadConfig, type Transport } from \"./shared/config.js\";\nimport { NAME, VERSION } from \"./shared/version.js\";\n\nfunction parseTransportFlag(argv: readonly string[]): Transport | undefined {\n for (const arg of argv) {\n if (arg === \"--transport=stdio\" || arg === \"--transport=http\") {\n return arg === \"--transport=stdio\" ? \"stdio\" : \"http\";\n }\n if (arg.startsWith(\"--transport=\")) {\n const value = arg.slice(\"--transport=\".length);\n if (value === \"stdio\" || value === \"http\") return value;\n }\n }\n return undefined;\n}\n\nasync function main(): Promise<number> {\n const argv = process.argv.slice(2);\n\n // Informational flags handled BEFORE the Node preflight so users on\n // any Node can confirm the binary resolves and discover the help\n // text — the only paths that touch zero runtime deps.\n if (argv.includes(\"--version\") || argv.includes(\"-v\")) {\n process.stdout.write(`${NAME} ${VERSION}\\n`);\n return 0;\n }\n if (argv.includes(\"--help\") || argv.includes(\"-h\")) {\n process.stdout.write(\n [\n `${NAME} ${VERSION}`,\n ``,\n `Usage:`,\n ` kaminari-ad-mcp [--transport=stdio|http]`,\n ``,\n `Transports:`,\n ` stdio (default) Local install — auth via KAMINARI_AD_API_KEY env var.`,\n ` http Hosted multi-tenant server — auth via incoming Authorization header.`,\n ``,\n `Configuration is documented in .env.example.`,\n ``,\n ].join(\"\\n\")\n );\n return 0;\n }\n\n // Preflight: bail with a clean upgrade message BEFORE any dynamic\n // import pulls undici / MCP SDK / pino — all three require\n // Node 22.19+ and crash at import time on older Node. Without this\n // gate users see undici's cryptic\n // `webidl.util.markAsUncloneable is not a function` instead.\n const check = checkNodeVersion(process.versions.node);\n if (check.isErr()) {\n process.stderr.write(`${check.error}\\n`);\n return 2;\n }\n\n const cliTransport = parseTransportFlag(argv);\n const env: NodeJS.ProcessEnv = cliTransport\n ? { ...process.env, KAMINARI_AD_TRANSPORT: cliTransport }\n : process.env;\n\n const configResult = loadConfig(env);\n if (configResult.isErr()) {\n process.stderr.write(`Invalid configuration: ${JSON.stringify(configResult.error.issues)}\\n`);\n return 2;\n }\n const config = configResult.value;\n\n if (config.transport === \"stdio\") {\n const { bootstrapStdio } = await import(\"./presentation/stdio/stdio-bootstrap.js\");\n return bootstrapStdio(config);\n }\n const { bootstrapHttp } = await import(\"./presentation/http/http-bootstrap.js\");\n return bootstrapHttp(config);\n}\n\nmain().then(\n (code) => {\n process.exit(code);\n },\n (error: unknown) => {\n process.stderr.write(`Fatal: ${error instanceof Error ? error.message : String(error)}\\n`);\n process.exit(1);\n }\n);\n"]}
1
+ {"version":3,"sources":["../src/shared/check-node-version.ts","../src/shared/oauth-scope-catalogue.ts","../src/shared/config.ts","../src/bin.ts"],"names":[],"mappings":";;;;;;AAoBO,IAAM,mBAAA,GAAsB,EAAA;AAC5B,IAAM,mBAAA,GAAsB,EAAA;AAU5B,SAAS,iBAAiB,WAAA,EAAgD;AAC/E,EAAA,MAAM,KAAA,GAAQ,WAAA,CAAY,KAAA,CAAM,GAAG,CAAA;AACnC,EAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,KAAA,CAAM,CAAC,CAAC,CAAA;AAC7B,EAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,KAAA,CAAM,CAAC,CAAC,CAAA;AAC7B,EAAA,IACE,MAAA,CAAO,KAAA,CAAM,KAAK,CAAA,IAClB,MAAA,CAAO,KAAA,CAAM,KAAK,CAAA,IAClB,KAAA,GAAQ,mBAAA,IACP,KAAA,KAAU,mBAAA,IAAuB,QAAQ,mBAAA,EAC1C;AACA,IAAA,MAAM,QAAA,GAAW,KAAK,MAAA,CAAO,mBAAmB,CAAC,CAAA,CAAA,EAAI,MAAA,CAAO,mBAAmB,CAAC,CAAA,EAAA,CAAA;AAChF,IAAA,OAAO,GAAA;AAAA,MACL;AAAA,QACE,CAAA,EAAG,IAAI,CAAA,kBAAA,EAAqB,QAAQ,eAAe,WAAW,CAAA,EAAA,CAAA;AAAA,QAC9D,EAAA;AAAA,QACA,8DAAA;AAAA,QACA,0DAAA;AAAA,QACA,4DAAA;AAAA,QACA,oDAAA;AAAA,QACA,EAAA;AAAA,QACA;AAAA,OACF,CAAE,KAAK,IAAI;AAAA,KACb;AAAA,EACF;AACA,EAAA,OAAO,GAAG,MAAS,CAAA;AACrB;;;ACpBO,IAAM,oBAAA,GAA0C,OAAO,MAAA,CAAO;AAAA,EACnE,kBAAA;AAAA,EACA,8BAAA;AAAA,EACA,+BAAA;AAAA,EACA,iBAAA;AAAA,EACA,kBAAA;AAAA,EACA,kBAAA;AAAA,EACA,oBAAA;AAAA,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;AAChC,IAAA,MAAM,EAAE,cAAA,EAAe,GAAI,MAAM,OAAO,+BAAyC,CAAA;AACjF,IAAA,OAAO,eAAe,MAAM,CAAA;AAAA,EAC9B;AACA,EAAA,MAAM,EAAE,aAAA,EAAc,GAAI,MAAM,OAAO,8BAAuC,CAAA;AAC9E,EAAA,OAAO,cAAc,MAAM,CAAA;AAC7B;AAEA,IAAA,EAAK,CAAE,IAAA;AAAA,EACL,CAAC,IAAA,KAAS;AACR,IAAA,OAAA,CAAQ,KAAK,IAAI,CAAA;AAAA,EACnB,CAAA;AAAA,EACA,CAAC,KAAA,KAAmB;AAClB,IAAA,OAAA,CAAQ,MAAA,CAAO,MAAM,CAAA,OAAA,EAAU,KAAA,YAAiB,QAAQ,KAAA,CAAM,OAAA,GAAU,MAAA,CAAO,KAAK,CAAC;AAAA,CAAI,CAAA;AACzF,IAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,EAChB;AACF,CAAA","file":"bin.js","sourcesContent":["/**\n * Pure Node-version preflight, extracted from {@link bin.ts} so it\n * can be unit-tested without `process.exit` side effects.\n *\n * Why this exists: `undici@8.x` removed feature probes in v8.0.3 and\n * imports `markAsUncloneable` from `node:worker_threads`\n * unconditionally — that symbol only exists on Node 22.19+. Older\n * Node versions crash at import time with the cryptic message\n * `webidl.util.markAsUncloneable is not a function`. We surface a\n * clean upgrade message instead, BEFORE any dynamic import pulls\n * undici.\n *\n * Keep {@link REQUIRED_NODE_MAJOR} / {@link REQUIRED_NODE_MINOR} in\n * sync with `engines.node` in `package.json` (currently\n * `>=22.19.0`).\n */\n\nimport { err, ok, type Result } from \"./result.js\";\nimport { NAME } from \"./version.js\";\n\nexport const REQUIRED_NODE_MAJOR = 22;\nexport const REQUIRED_NODE_MINOR = 19;\n\n/**\n * Check whether `nodeVersion` (e.g. `\"22.19.0\"`, the value of\n * `process.versions.node`) satisfies the package's runtime floor.\n *\n * Returns `Ok(undefined)` on pass, `Err(message)` with a multi-line\n * upgrade message on fail. The message is plain text ready to be\n * written to stderr verbatim.\n */\nexport function checkNodeVersion(nodeVersion: string): Result<undefined, string> {\n const parts = nodeVersion.split(\".\");\n const major = Number(parts[0]);\n const minor = Number(parts[1]);\n if (\n Number.isNaN(major) ||\n Number.isNaN(minor) ||\n major < REQUIRED_NODE_MAJOR ||\n (major === REQUIRED_NODE_MAJOR && minor < REQUIRED_NODE_MINOR)\n ) {\n const required = `>=${String(REQUIRED_NODE_MAJOR)}.${String(REQUIRED_NODE_MINOR)}.0`;\n return err(\n [\n `${NAME} requires Node.js ${required} (you have v${nodeVersion}).`,\n \"\",\n \"The underlying undici 8.x HTTP client uses markAsUncloneable\",\n \"from node:worker_threads, available only on Node 22.19+.\",\n \"Older Node crashes at import time with the cryptic message\",\n \"`webidl.util.markAsUncloneable is not a function`.\",\n \"\",\n \"Please upgrade Node and re-run: https://nodejs.org/en/download\",\n ].join(\"\\n\")\n );\n }\n return ok(undefined);\n}\n","/**\n * Canonical catalogue of OAuth 2.0 scopes the Kaminari Ad MCP server\n * advertises in its protected-resource metadata (RFC 9728) and\n * `WWW-Authenticate: Bearer scope=\"...\"` challenge.\n *\n * The catalogue is intentionally static and lives in `shared/` because\n * (a) it has no runtime behaviour — it is data — and (b) it is read by\n * both the `protected-resource-metadata-handler` and the\n * `www-authenticate` builder. If a new scope is added on the\n * Authorization Server side, mirror it here in the same release so the\n * Resource Server (this process) advertises it.\n *\n * `offline_access` is part of the catalogue per RFC 6749 §6 because\n * the Authorization Server issues refresh tokens only when the client\n * requests this scope. Anthropic's Claude clients append it\n * automatically when the server advertises it in\n * `scopes_supported`/the `WWW-Authenticate` `scope=` parameter.\n */\n\n/**\n * Default scope catalogue, frozen at build time.\n *\n * MUST stay byte-identical to the Authorization Server's advertised\n * catalogue (`app.oauth_authorization.domain.entities.scope.advertised_scopes()`\n * — i.e. `sorted(KNOWN_SCOPES)`). The order is lexicographic, which\n * happens to yield the desired semantics for free: `:read` sorts before\n * `:write` within a resource, and `offline_access` sorts after every\n * `mcp:` scope.\n *\n * Read scopes grant the resource's view permission; write scopes grant\n * read + the resource's mutating permissions. billing/invoicing/account\n * are read-only over OAuth by design (money-spend / privilege-escalation\n * tools stay API-key only). When the AS catalogue changes, mirror it\n * here in the same release — `tests/unit/shared/oauth-scope-catalogue.test.ts`\n * pins the exact list so drift fails CI.\n */\nexport const DEFAULT_OAUTH_SCOPES: readonly string[] = Object.freeze([\n \"mcp:account:read\",\n \"mcp:alert_notifications:read\",\n \"mcp:alert_notifications:write\",\n \"mcp:alerts:read\",\n \"mcp:alerts:write\",\n \"mcp:billing:read\",\n \"mcp:campaigns:read\",\n \"mcp:campaigns:write\",\n \"mcp:custom_rules:read\",\n \"mcp:custom_rules:write\",\n \"mcp:invoicing:read\",\n \"mcp:policies:read\",\n \"mcp:policies:write\",\n \"mcp:scans:read\",\n \"mcp:scans:write\",\n \"mcp:tags:read\",\n \"mcp:tags:write\",\n \"mcp:taxonomies:read\",\n \"mcp:taxonomies:write\",\n \"mcp:webhooks:read\",\n \"mcp:webhooks:write\",\n \"offline_access\",\n]);\n","/**\n * Runtime configuration for `@kaminari-ad/mcp`.\n *\n * The single source of truth for all env-var reads. `process.env.X`\n * outside this file is a code-review blocker — every config value flows\n * through the zod-parsed {@link Config} object.\n */\n\nimport { z } from \"zod\";\n\nimport { DEFAULT_OAUTH_SCOPES } from \"./oauth-scope-catalogue.js\";\nimport { err, ok, type Result } from \"./result.js\";\n\n/**\n * MCP transport. `stdio` is for local install (one process per user);\n * `http` is for the hosted multi-tenant endpoint.\n */\nexport const TransportSchema = z.enum([\"stdio\", \"http\"]);\nexport type Transport = z.infer<typeof TransportSchema>;\n\n/**\n * pino log level.\n */\nexport const LogLevelSchema = z.enum([\"trace\", \"debug\", \"info\", \"warn\", \"error\", \"fatal\"]);\nexport type LogLevel = z.infer<typeof LogLevelSchema>;\n\n/**\n * pino log output format.\n *\n * - `pretty` — colorised single-line ANSI output for terminals. Default\n * in stdio mode (operator reads stderr in their shell).\n * - `json` — newline-delimited JSON, one record per line. Default in\n * HTTP mode (Docker/k8s log aggregators expect JSON). MCP hosts that\n * capture stderr from the stdio process (Cursor, Claude Desktop)\n * parse much better with `json` — flip this when the operator is a\n * machine, not a human.\n */\nexport const LogFormatSchema = z.enum([\"pretty\", \"json\"]);\nexport type LogFormat = z.infer<typeof LogFormatSchema>;\n\n/**\n * Parsed configuration. All fields are `readonly` — mutation post-load\n * is a bug.\n */\nexport interface Config {\n readonly transport: Transport;\n readonly apiBaseUrl: string;\n readonly logLevel: LogLevel;\n readonly logFormat: LogFormat;\n readonly httpPort: number;\n readonly rateLimitRpm: number;\n /**\n * Set only in stdio mode. In HTTP mode the bootstrap MUST assert\n * this is `undefined` (see CONTRIBUTING.md \"Tenant isolation\" §5).\n */\n readonly stdioApiKey: string | undefined;\n /**\n * Canonical MCP endpoint URL advertised as the `resource` field of\n * the RFC 9728 protected-resource metadata document. Anthropic's\n * Claude clients require this to match the URL the user enters in\n * Claude exactly (including the path component).\n */\n readonly oauthProtectedResource: string;\n /**\n * Absolute URL where this server serves the protected-resource\n * metadata JSON. Advertised back to clients via\n * `WWW-Authenticate: Bearer resource_metadata=\"…\"` on 401.\n */\n readonly oauthProtectedResourceMetadataUrl: string;\n /**\n * Issuer URL of the Authorization Server that mints access tokens\n * accepted by this Resource Server. Advertised as the first (and\n * only) entry of the metadata's `authorization_servers` array.\n */\n readonly oauthAuthorizationServerUrl: string;\n /**\n * Scopes the Resource Server advertises in both the metadata's\n * `scopes_supported` field and the 401 `WWW-Authenticate scope=…`\n * parameter. Defaults to {@link DEFAULT_OAUTH_SCOPES}; operators\n * may override via `KAMINARI_AD_OAUTH_SCOPES` (space-separated).\n */\n readonly oauthScopes: readonly string[];\n}\n\n/**\n * Every env var carries the `KAMINARI_AD_` namespace prefix.\n *\n * Why: this process inherits the host's full environment (Cursor /\n * Claude Desktop / Docker compose / k8s pod), where `API_BASE_URL` /\n * `LOG_LEVEL` / `HTTP_PORT` are common generic names. Without a\n * namespace, another tool in the same shell trivially poisons our\n * config — e.g. `LOG_LEVEL=debug` set for some app library suddenly\n * makes the MCP server log every secret-redacted-but-still-noisy\n * request to stderr, and the user has no idea why. With the prefix\n * the boundary is explicit and `env | grep KAMINARI_AD_` enumerates\n * exactly what we read.\n */\nconst RawSchema = z.object({\n KAMINARI_AD_TRANSPORT: TransportSchema.default(\"stdio\"),\n // `app.kaminari.ad` is the API host; `kaminari.ad` (no subdomain)\n // is the marketing landing page and does NOT serve /api/v1/*.\n // Setting this wrong (e.g. the root domain) makes every tool call\n // fail with HTTP 404 — the symptom that surfaced this default bug\n // in v0.2.0.\n KAMINARI_AD_API_URL: z.string().url().default(\"https://app.kaminari.ad\"),\n KAMINARI_AD_LOG_LEVEL: LogLevelSchema.default(\"info\"),\n KAMINARI_AD_LOG_FORMAT: LogFormatSchema.optional(),\n KAMINARI_AD_HTTP_PORT: z.coerce.number().int().min(0).max(65535).default(8080),\n KAMINARI_AD_RATE_LIMIT_RPM: z.coerce.number().int().min(1).max(10_000).default(120),\n KAMINARI_AD_API_KEY: z.string().min(8).optional(),\n // OAuth discovery (RFC 9728 protected-resource + RFC 8414 AS\n // metadata). All three URLs default to the production deployment;\n // local/staging operators override per-environment.\n KAMINARI_AD_OAUTH_PROTECTED_RESOURCE: z.string().url().default(\"https://mcp.kaminari.ad/mcp\"),\n KAMINARI_AD_OAUTH_PROTECTED_RESOURCE_METADATA_URL: z\n .string()\n .url()\n .default(\"https://mcp.kaminari.ad/.well-known/oauth-protected-resource\"),\n KAMINARI_AD_OAUTH_AUTHORIZATION_SERVER_URL: z.string().url().default(\"https://app.kaminari.ad\"),\n // Space-separated scope list. We split on /\\s+/ post-parse and drop\n // empty tokens so accidental double-spaces don't corrupt the array.\n KAMINARI_AD_OAUTH_SCOPES: z.string().optional(),\n});\n\n/**\n * Parse and validate environment variables into a {@link Config}.\n *\n * Returns `Err<ConfigError>` on validation failure. Caller (typically\n * `bin.ts`) prints the error and exits non-zero.\n *\n * `KAMINARI_AD_LOG_FORMAT` defaults are transport-dependent: `pretty`\n * for stdio (terminal-facing) and `json` for http (aggregator-facing).\n * If the user sets the env var explicitly, that wins.\n */\nexport function loadConfig(env: NodeJS.ProcessEnv): Result<Config, ConfigError> {\n const parsed = RawSchema.safeParse(env);\n if (!parsed.success) {\n return err({ kind: \"invalid\", issues: parsed.error.flatten().fieldErrors });\n }\n const raw = parsed.data;\n const transport = raw.KAMINARI_AD_TRANSPORT;\n const logFormat = raw.KAMINARI_AD_LOG_FORMAT ?? (transport === \"stdio\" ? \"pretty\" : \"json\");\n const oauthScopesRaw = raw.KAMINARI_AD_OAUTH_SCOPES;\n const oauthScopes: readonly string[] =\n oauthScopesRaw === undefined\n ? DEFAULT_OAUTH_SCOPES\n : Object.freeze(oauthScopesRaw.split(/\\s+/).filter((s) => s.length > 0));\n return ok({\n transport,\n apiBaseUrl: raw.KAMINARI_AD_API_URL,\n logLevel: raw.KAMINARI_AD_LOG_LEVEL,\n logFormat,\n httpPort: raw.KAMINARI_AD_HTTP_PORT,\n rateLimitRpm: raw.KAMINARI_AD_RATE_LIMIT_RPM,\n stdioApiKey: raw.KAMINARI_AD_API_KEY,\n oauthProtectedResource: raw.KAMINARI_AD_OAUTH_PROTECTED_RESOURCE,\n oauthProtectedResourceMetadataUrl: raw.KAMINARI_AD_OAUTH_PROTECTED_RESOURCE_METADATA_URL,\n oauthAuthorizationServerUrl: raw.KAMINARI_AD_OAUTH_AUTHORIZATION_SERVER_URL,\n oauthScopes,\n });\n}\n\n/**\n * Errors from {@link loadConfig}.\n */\nexport interface ConfigError {\n readonly kind: \"invalid\";\n readonly issues: Readonly<Record<string, readonly string[] | undefined>>;\n}\n","/**\n * CLI entrypoint for `@kaminari-ad/mcp`.\n *\n * Dispatches to a transport-specific composition root (stdio or HTTP)\n * based on the `--transport` flag (or `TRANSPORT` env var, with stdio\n * as the default).\n *\n * Wire-up is intentionally minimal — every dependency is constructed\n * inside the chosen bootstrap, never here. This file just parses argv\n * and config, then hands off.\n *\n * Imports policy: the STATIC imports below MUST stay free of any\n * runtime dependency that requires Node >= 22.19 (undici, MCP SDK,\n * pino). Otherwise the Node-version preflight in `main()` runs too\n * late — those modules crash at import time on older Node. The\n * transport bootstraps pull undici / MCP SDK / pino via dynamic\n * `await import()` so the preflight gets to fire first.\n */\n\nimport process from \"node:process\";\n\nimport { checkNodeVersion } from \"./shared/check-node-version.js\";\nimport { loadConfig, type Transport } from \"./shared/config.js\";\nimport { NAME, VERSION } from \"./shared/version.js\";\n\nfunction parseTransportFlag(argv: readonly string[]): Transport | undefined {\n for (const arg of argv) {\n if (arg === \"--transport=stdio\" || arg === \"--transport=http\") {\n return arg === \"--transport=stdio\" ? \"stdio\" : \"http\";\n }\n if (arg.startsWith(\"--transport=\")) {\n const value = arg.slice(\"--transport=\".length);\n if (value === \"stdio\" || value === \"http\") return value;\n }\n }\n return undefined;\n}\n\nasync function main(): Promise<number> {\n const argv = process.argv.slice(2);\n\n // Informational flags handled BEFORE the Node preflight so users on\n // any Node can confirm the binary resolves and discover the help\n // text — the only paths that touch zero runtime deps.\n if (argv.includes(\"--version\") || argv.includes(\"-v\")) {\n process.stdout.write(`${NAME} ${VERSION}\\n`);\n return 0;\n }\n if (argv.includes(\"--help\") || argv.includes(\"-h\")) {\n process.stdout.write(\n [\n `${NAME} ${VERSION}`,\n ``,\n `Usage:`,\n ` kaminari-ad-mcp [--transport=stdio|http]`,\n ``,\n `Transports:`,\n ` stdio (default) Local install — auth via KAMINARI_AD_API_KEY env var.`,\n ` http Hosted multi-tenant server — auth via incoming Authorization header.`,\n ``,\n `Configuration is documented in .env.example.`,\n ``,\n ].join(\"\\n\")\n );\n return 0;\n }\n\n // Preflight: bail with a clean upgrade message BEFORE any dynamic\n // import pulls undici / MCP SDK / pino — all three require\n // Node 22.19+ and crash at import time on older Node. Without this\n // gate users see undici's cryptic\n // `webidl.util.markAsUncloneable is not a function` instead.\n const check = checkNodeVersion(process.versions.node);\n if (check.isErr()) {\n process.stderr.write(`${check.error}\\n`);\n return 2;\n }\n\n const cliTransport = parseTransportFlag(argv);\n const env: NodeJS.ProcessEnv = cliTransport\n ? { ...process.env, KAMINARI_AD_TRANSPORT: cliTransport }\n : process.env;\n\n const configResult = loadConfig(env);\n if (configResult.isErr()) {\n process.stderr.write(`Invalid configuration: ${JSON.stringify(configResult.error.issues)}\\n`);\n return 2;\n }\n const config = configResult.value;\n\n if (config.transport === \"stdio\") {\n const { bootstrapStdio } = await import(\"./presentation/stdio/stdio-bootstrap.js\");\n return bootstrapStdio(config);\n }\n const { bootstrapHttp } = await import(\"./presentation/http/http-bootstrap.js\");\n return bootstrapHttp(config);\n}\n\nmain().then(\n (code) => {\n process.exit(code);\n },\n (error: unknown) => {\n process.stderr.write(`Fatal: ${error instanceof Error ? error.message : String(error)}\\n`);\n process.exit(1);\n }\n);\n"]}
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { err, ok } from './chunk-SQVFFWOB.js';
2
+ import { err, ok } from './chunk-CEKRYHCR.js';
3
3
  import { createHash, randomUUID } from 'crypto';
4
4
  import createClient from 'openapi-fetch';
5
5
  import { fetch } from 'undici';
@@ -63,8 +63,8 @@ var BearerToken = class _BearerToken {
63
63
  return createHash("sha256").update(this.#raw).digest("hex").slice(0, BEARER_HASH_PREFIX_LEN);
64
64
  }
65
65
  /**
66
- * Returns the full SHA-256 hex digest. Used as the session-binding
67
- * key in {@link SessionStore}. Not for logs.
66
+ * Returns the full SHA-256 hex digest. Used as the per-bearer key for
67
+ * the rate limiter. Not for logs.
68
68
  */
69
69
  fullHash() {
70
70
  return createHash("sha256").update(this.#raw).digest("hex");
@@ -5376,5 +5376,5 @@ function formatToolError(error) {
5376
5376
  }
5377
5377
 
5378
5378
  export { BearerToken, SERVER_INSTRUCTIONS, createHttpApiGateway, createPinoLogger, declareEmptyResourcesAndPrompts, newRequestId, wireToolsIntoMcpServer };
5379
- //# sourceMappingURL=chunk-3CY2WEZF.js.map
5380
- //# sourceMappingURL=chunk-3CY2WEZF.js.map
5379
+ //# sourceMappingURL=chunk-AINV7DXM.js.map
5380
+ //# sourceMappingURL=chunk-AINV7DXM.js.map