slab-mcp 0.1.2 → 0.3.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 (59) hide show
  1. package/README.md +190 -107
  2. package/dist/client.d.ts +34 -13
  3. package/dist/client.js +99 -59
  4. package/dist/config.d.ts +7 -2
  5. package/dist/config.js +30 -7
  6. package/dist/context.d.ts +8 -12
  7. package/dist/context.js +7 -29
  8. package/dist/credentials.d.ts +33 -0
  9. package/dist/credentials.js +77 -0
  10. package/dist/errors.js +6 -2
  11. package/dist/format.d.ts +2 -0
  12. package/dist/format.js +7 -1
  13. package/dist/index.js +4 -2
  14. package/dist/prompts/index.js +31 -6
  15. package/dist/resources/index.d.ts +2 -1
  16. package/dist/resources/index.js +4 -3
  17. package/dist/tools/args.d.ts +18 -0
  18. package/dist/tools/args.js +26 -0
  19. package/dist/tools/catalog.d.ts +21 -6
  20. package/dist/tools/catalog.js +88 -47
  21. package/dist/tools/chases.d.ts +28 -0
  22. package/dist/tools/chases.js +72 -0
  23. package/dist/tools/collection.d.ts +26 -18
  24. package/dist/tools/collection.js +113 -82
  25. package/dist/tools/community.d.ts +16 -3
  26. package/dist/tools/community.js +110 -50
  27. package/dist/tools/filters.d.ts +6 -0
  28. package/dist/tools/filters.js +6 -0
  29. package/dist/tools/index.js +2 -0
  30. package/dist/tools/lines.d.ts +20 -0
  31. package/dist/tools/lines.js +31 -0
  32. package/dist/tools/meta.js +5 -4
  33. package/dist/tools/pricing.d.ts +21 -16
  34. package/dist/tools/pricing.js +167 -63
  35. package/dist/tools/writes.d.ts +43 -47
  36. package/dist/tools/writes.js +65 -29
  37. package/dist/types.d.ts +48 -77
  38. package/dist/types.js +6 -6
  39. package/dist/version.d.ts +13 -0
  40. package/dist/version.js +16 -0
  41. package/package.json +14 -5
  42. package/dist/client.js.map +0 -1
  43. package/dist/config.js.map +0 -1
  44. package/dist/context.js.map +0 -1
  45. package/dist/errors.js.map +0 -1
  46. package/dist/format.js.map +0 -1
  47. package/dist/index.js.map +0 -1
  48. package/dist/prompts/index.js.map +0 -1
  49. package/dist/resources/index.js.map +0 -1
  50. package/dist/tools/catalog.js.map +0 -1
  51. package/dist/tools/collection.js.map +0 -1
  52. package/dist/tools/community.js.map +0 -1
  53. package/dist/tools/filters.js.map +0 -1
  54. package/dist/tools/index.js.map +0 -1
  55. package/dist/tools/meta.js.map +0 -1
  56. package/dist/tools/pricing.js.map +0 -1
  57. package/dist/tools/types.js.map +0 -1
  58. package/dist/tools/writes.js.map +0 -1
  59. package/dist/types.js.map +0 -1
package/dist/client.js CHANGED
@@ -1,18 +1,34 @@
1
1
  /**
2
- * Thin typed HTTP client for the slab API.
2
+ * The one door to the network.
3
3
  *
4
- * Deliberately dumb: it knows about auth, timeouts, and error shapes, and
5
- * nothing about cards. Endpoint knowledge lives in the tool modules, so adding
6
- * an endpoint never means touching this file.
4
+ * Nothing else in this server calls `fetch` (a test holds that), so everything slab-mcp sends goes
5
+ * to the slab API at `config.apiUrl`, with the key in one header, and nowhere else:
7
6
  *
8
- * The response types are declared structurally in `types.ts` rather thanß
9
- * generated, because a generated client would have to be regenerated to stay
10
- * honest. `GET /openapi.json` is the authoritative contract and is exposed to
11
- * the model as a resource — see src/resources/index.ts.
7
+ * - Paths are built with `api\`...\``, which percent-encodes every interpolated value as ONE path
8
+ * segment. A model-supplied id can't climb out of its route: `../../account/keys/x` becomes
9
+ * `..%2F..%2Faccount%2Fkeys%2Fx`, a 404, instead of a DELETE on an API key.
10
+ * - Redirects are refused, so the key is never replayed to another host.
11
+ * - Reads retry a transient failure (network, 429, 502-504) twice, honouring Retry-After. Writes
12
+ * never retry: a POST that timed out may have landed, and a second one adds a second copy.
12
13
  *
13
- * deploy
14
+ * It knows nothing about cards. Endpoint knowledge lives in the tool modules; the response types
15
+ * come from the API's own spec (`types.ts`).
14
16
  */
15
17
  import { ApiConnectionError, ApiError } from './errors.js';
18
+ import { VERSION } from './version.js';
19
+ /** `api\`/cards/${uuid}/market\``: each interpolated value becomes one encoded path segment. */
20
+ export function api(strings, ...values) {
21
+ let out = strings[0] ?? '';
22
+ values.forEach((value, i) => {
23
+ out += encodeURIComponent(String(value)) + (strings[i + 1] ?? '');
24
+ });
25
+ return out;
26
+ }
27
+ /** Statuses worth one more try: rate limited, or the API's front door briefly down. */
28
+ const TRANSIENT = new Set([429, 502, 503, 504]);
29
+ const RETRIES = 2;
30
+ const BACKOFF_MS = [400, 1500];
31
+ const MAX_RETRY_AFTER_MS = 10_000;
16
32
  /** Strip undefined values so we never send `{"brand": undefined}` -> `{"brand": null}`. */
17
33
  function prune(value) {
18
34
  if (Array.isArray(value))
@@ -27,12 +43,54 @@ function prune(value) {
27
43
  }
28
44
  return value;
29
45
  }
46
+ /** Retry-After in ms (seconds or an HTTP date), capped; undefined when absent or unreadable. */
47
+ function retryAfterMs(response) {
48
+ const header = response.headers.get('retry-after');
49
+ if (!header)
50
+ return undefined;
51
+ const seconds = Number(header);
52
+ const ms = Number.isFinite(seconds) ? seconds * 1000 : Date.parse(header) - Date.now();
53
+ return Number.isFinite(ms) && ms >= 0 ? Math.min(ms, MAX_RETRY_AFTER_MS) : undefined;
54
+ }
55
+ /** The API's `detail`, or the raw body when it isn't JSON. Capped so an HTML error page can't flood. */
56
+ async function errorDetail(response) {
57
+ const body = await response.text();
58
+ try {
59
+ const parsed = JSON.parse(body);
60
+ if (parsed && typeof parsed === 'object' && 'detail' in parsed) {
61
+ return (typeof parsed.detail === 'string' ? parsed.detail : JSON.stringify(parsed.detail)).slice(0, 2000);
62
+ }
63
+ }
64
+ catch {
65
+ // Not JSON; the text is the best detail there is.
66
+ }
67
+ return body.slice(0, 2000);
68
+ }
30
69
  export class SlabClient {
31
70
  config;
32
- constructor(config) {
71
+ fetch;
72
+ sleep;
73
+ constructor(config, deps = {}) {
33
74
  this.config = config;
75
+ this.fetch = deps.fetch ?? globalThis.fetch;
76
+ this.sleep = deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
34
77
  }
35
78
  async request(method, path, options = {}) {
79
+ const text = await this.send(method, path, options, 'application/json');
80
+ if (!text)
81
+ return undefined;
82
+ try {
83
+ return JSON.parse(text);
84
+ }
85
+ catch {
86
+ throw new ApiError(502, `the API answered with something that isn't JSON: ${text.slice(0, 200)}`, method, path);
87
+ }
88
+ }
89
+ /** A document verbatim (the resources: /vocab, /glossary, /openapi.json). */
90
+ async raw(path) {
91
+ return this.send('GET', path, { read: true }, 'application/json');
92
+ }
93
+ async send(method, path, options, accept) {
36
94
  const url = new URL(this.config.apiUrl + path);
37
95
  for (const [key, value] of Object.entries(options.query ?? {})) {
38
96
  if (value !== undefined && value !== null)
@@ -40,62 +98,44 @@ export class SlabClient {
40
98
  }
41
99
  const headers = {
42
100
  'x-api-key': this.config.apiKey,
43
- accept: 'application/json',
44
- 'user-agent': 'slab-mcp',
101
+ accept,
102
+ 'user-agent': `slab-mcp/${VERSION}`,
45
103
  };
46
104
  if (options.body !== undefined)
47
105
  headers['content-type'] = 'application/json';
48
- let response;
49
- try {
50
- response = await fetch(url, {
51
- method,
52
- headers,
53
- body: options.body === undefined ? undefined : JSON.stringify(prune(options.body)),
54
- signal: AbortSignal.timeout(this.config.timeoutMs),
55
- });
56
- }
57
- catch (err) {
58
- const reason = err instanceof Error && err.name === 'TimeoutError'
59
- ? `request timed out after ${this.config.timeoutMs}ms`
60
- : err instanceof Error
61
- ? err.message
62
- : String(err);
63
- throw new ApiConnectionError(this.config.apiUrl, reason);
64
- }
65
- if (!response.ok) {
66
- let detail = await response.text();
106
+ const body = options.body === undefined ? undefined : JSON.stringify(prune(options.body));
107
+ const retries = method === 'GET' || options.read ? RETRIES : 0;
108
+ for (let attempt = 0;; attempt += 1) {
109
+ let response;
67
110
  try {
68
- const parsed = JSON.parse(detail);
69
- if (parsed && typeof parsed === 'object' && 'detail' in parsed) {
70
- detail = typeof parsed.detail === 'string' ? parsed.detail : JSON.stringify(parsed.detail);
111
+ response = await this.fetch(url, {
112
+ method,
113
+ headers,
114
+ body,
115
+ redirect: 'error',
116
+ signal: AbortSignal.timeout(this.config.timeoutMs),
117
+ });
118
+ }
119
+ catch (err) {
120
+ if (attempt < retries) {
121
+ await this.sleep(BACKOFF_MS[attempt] ?? 1500);
122
+ continue;
71
123
  }
124
+ const reason = err instanceof Error && err.name === 'TimeoutError'
125
+ ? `request timed out after ${this.config.timeoutMs}ms`
126
+ : err instanceof Error
127
+ ? err.message
128
+ : String(err);
129
+ throw new ApiConnectionError(this.config.apiUrl, reason);
72
130
  }
73
- catch {
74
- // Body was not JSON; the raw text is the best detail we have.
131
+ if (response.ok)
132
+ return response.status === 204 ? '' : await response.text();
133
+ if (TRANSIENT.has(response.status) && attempt < retries) {
134
+ await response.body?.cancel();
135
+ await this.sleep(retryAfterMs(response) ?? BACKOFF_MS[attempt] ?? 1500);
136
+ continue;
75
137
  }
76
- throw new ApiError(response.status, detail.slice(0, 2000), method, path);
77
- }
78
- if (response.status === 204)
79
- return undefined;
80
- const text = await response.text();
81
- return (text ? JSON.parse(text) : undefined);
82
- }
83
- /** Fetch a public document verbatim (used by the resource handlers). */
84
- async raw(path) {
85
- const url = this.config.apiUrl + path;
86
- try {
87
- const response = await fetch(url, {
88
- headers: { 'x-api-key': this.config.apiKey, 'user-agent': 'slab-mcp' },
89
- signal: AbortSignal.timeout(this.config.timeoutMs),
90
- });
91
- if (!response.ok)
92
- throw new ApiError(response.status, await response.text(), 'GET', path);
93
- return await response.text();
94
- }
95
- catch (err) {
96
- if (err instanceof ApiError)
97
- throw err;
98
- throw new ApiConnectionError(this.config.apiUrl, err instanceof Error ? err.message : String(err));
138
+ throw new ApiError(response.status, await errorDetail(response), method, path);
99
139
  }
100
140
  }
101
141
  }
package/dist/config.d.ts CHANGED
@@ -5,14 +5,19 @@
5
5
  * never included in a tool result, so the model on the other end of the
6
6
  * transport cannot read it, echo it, or be tricked into exfiltrating it.
7
7
  */
8
+ import { type KeySource } from './credentials.js';
8
9
  export declare const DEFAULT_API_URL = "https://api.slab.dev-jeb.com";
10
+ /** The API's name for "the collector this key acts for" (its default collector). */
11
+ export declare const ME = "me";
9
12
  export interface Config {
10
13
  /** Base URL of the slab API, no trailing slash. */
11
14
  apiUrl: string;
12
15
  /** Value sent as the `x-api-key` header on every request. */
13
16
  apiKey: string;
14
- /** Collector the key acts for. Undefined = resolve lazily from `GET /account`. */
15
- collectorUuid: string | undefined;
17
+ /** Which mechanism supplied the key. Logged at startup; never the key itself. */
18
+ keySource: KeySource;
19
+ /** Collector the key acts for: SLAB_COLLECTOR, else `me` (the account's default collector). */
20
+ collectorUuid: string;
16
21
  /** Whether mutating tools are registered at all. Off unless SLAB_MCP_WRITE=1. */
17
22
  writesEnabled: boolean;
18
23
  /** Per-request HTTP timeout. */
package/dist/config.js CHANGED
@@ -5,28 +5,51 @@
5
5
  * never included in a tool result, so the model on the other end of the
6
6
  * transport cannot read it, echo it, or be tricked into exfiltrating it.
7
7
  */
8
+ import { resolveApiKey } from './credentials.js';
8
9
  import { ConfigError } from './errors.js';
9
10
  export const DEFAULT_API_URL = 'https://api.slab.dev-jeb.com';
11
+ /** The API's name for "the collector this key acts for" (its default collector). */
12
+ export const ME = 'me';
10
13
  function truthy(value) {
11
14
  if (!value)
12
15
  return false;
13
16
  return ['1', 'true', 'yes', 'on'].includes(value.trim().toLowerCase());
14
17
  }
15
- export function loadConfig(env = process.env) {
16
- const apiKey = env.SLAB_API_KEY?.trim();
17
- if (!apiKey) {
18
- throw new ConfigError('SLAB_API_KEY is not set. Get a key at https://app.slab.dev-jeb.com -> Account -> API Keys, ' +
19
- 'then set it in the "env" block of your MCP client config (see this tool\'s README).');
18
+ /** The key travels in a header on every request, so it only travels encrypted — except to a
19
+ * server on this machine, which is how the API is developed. */
20
+ function apiUrlFrom(raw) {
21
+ const value = (raw?.trim() || DEFAULT_API_URL).replace(/\/+$/, '');
22
+ let url;
23
+ try {
24
+ url = new URL(value);
25
+ }
26
+ catch {
27
+ throw new ConfigError(`SLAB_API_URL is not a URL: "${value}".`);
28
+ }
29
+ const local = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
30
+ if (url.protocol !== 'https:' && !(local && url.protocol === 'http:')) {
31
+ throw new ConfigError(`SLAB_API_URL must be https (http only for localhost), got "${value}". The API key is sent with every request.`);
20
32
  }
33
+ if (url.search || url.hash)
34
+ throw new ConfigError(`SLAB_API_URL must be a base URL with no query or fragment, got "${value}".`);
35
+ return value;
36
+ }
37
+ export function loadConfig(env = process.env) {
38
+ const { key: apiKey, source: keySource } = resolveApiKey(env);
21
39
  const timeoutRaw = env.SLAB_MCP_TIMEOUT_MS?.trim();
22
40
  const timeoutMs = timeoutRaw ? Number(timeoutRaw) : 30_000;
23
41
  if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
24
42
  throw new ConfigError(`SLAB_MCP_TIMEOUT_MS must be a positive number of milliseconds, got "${timeoutRaw}".`);
25
43
  }
44
+ const collector = env.SLAB_COLLECTOR?.trim();
45
+ if (collector && !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(collector)) {
46
+ throw new ConfigError(`SLAB_COLLECTOR must be a collector UUID, got "${collector}". Leave it unset to use your account's default collector.`);
47
+ }
26
48
  return {
27
- apiUrl: (env.SLAB_API_URL?.trim() || DEFAULT_API_URL).replace(/\/+$/, ''),
49
+ apiUrl: apiUrlFrom(env.SLAB_API_URL),
28
50
  apiKey,
29
- collectorUuid: env.SLAB_COLLECTOR?.trim() || undefined,
51
+ keySource,
52
+ collectorUuid: collector || ME,
30
53
  writesEnabled: truthy(env.SLAB_MCP_WRITE),
31
54
  timeoutMs,
32
55
  };
package/dist/context.d.ts CHANGED
@@ -1,20 +1,16 @@
1
1
  /**
2
- * The object every tool handler receives.
2
+ * The object every tool handler receives: the client, the config, and the collector to act as.
3
3
  *
4
- * Collector resolution lives here because it is the one piece of state the
5
- * whole server shares. A model cannot invent a collector UUID, so no
6
- * collection tool should require one: the acting collector comes from
7
- * SLAB_COLLECTOR, or from `GET /account` once, memoised for the process.
4
+ * A model cannot invent a collector UUID, so no collection tool requires one: the acting collector
5
+ * is SLAB_COLLECTOR, or `me`, which the API reads as this key's default collector (a 404 when the
6
+ * account has none, which `errors.ts` explains).
8
7
  */
9
- import { SlabClient } from './client.js';
8
+ import { type ClientDeps, SlabClient } from './client.js';
10
9
  import type { Config } from './config.js';
11
10
  export interface ToolContext {
12
11
  client: SlabClient;
13
12
  config: Config;
14
- /**
15
- * The collector to act as. Pass an explicit UUID to override (the tools
16
- * expose an optional `collector_uuid` for multi-collector accounts).
17
- */
18
- collector(override?: string): Promise<string>;
13
+ /** The collector to act as: an explicit UUID (multi-collector accounts), else the configured one. */
14
+ collector(override?: string): string;
19
15
  }
20
- export declare function createContext(config: Config): ToolContext;
16
+ export declare function createContext(config: Config, deps?: ClientDeps): ToolContext;
package/dist/context.js CHANGED
@@ -1,39 +1,17 @@
1
1
  /**
2
- * The object every tool handler receives.
2
+ * The object every tool handler receives: the client, the config, and the collector to act as.
3
3
  *
4
- * Collector resolution lives here because it is the one piece of state the
5
- * whole server shares. A model cannot invent a collector UUID, so no
6
- * collection tool should require one: the acting collector comes from
7
- * SLAB_COLLECTOR, or from `GET /account` once, memoised for the process.
4
+ * A model cannot invent a collector UUID, so no collection tool requires one: the acting collector
5
+ * is SLAB_COLLECTOR, or `me`, which the API reads as this key's default collector (a 404 when the
6
+ * account has none, which `errors.ts` explains).
8
7
  */
9
8
  import { SlabClient } from './client.js';
10
- import { ApiError } from './errors.js';
11
- export function createContext(config) {
12
- const client = new SlabClient(config);
13
- let resolved;
14
- async function resolveDefault() {
15
- const account = await client.request('GET', '/account');
16
- const uuid = account.default_collector_uuid ?? account.collectors?.[0]?.uuid;
17
- if (!uuid) {
18
- throw new ApiError(404, 'This API key resolves to an account with no collectors. Create one in the slab portal or with `slab collector create`, then retry.', 'GET', '/account');
19
- }
20
- return uuid;
21
- }
9
+ export function createContext(config, deps = {}) {
10
+ const client = new SlabClient(config, deps);
22
11
  return {
23
12
  client,
24
13
  config,
25
- async collector(override) {
26
- if (override)
27
- return override;
28
- if (config.collectorUuid)
29
- return config.collectorUuid;
30
- // Memoise the promise, not the value, so concurrent first calls share one request.
31
- resolved ??= resolveDefault().catch((err) => {
32
- resolved = undefined; // let a later call retry after a transient failure
33
- throw err;
34
- });
35
- return resolved;
36
- },
14
+ collector: (override) => override || config.collectorUuid,
37
15
  };
38
16
  }
39
17
  //# sourceMappingURL=context.js.map
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Where the API key comes from.
3
+ *
4
+ * The obvious option — pasting the key into the MCP client's config as an env
5
+ * value — has a problem specific to agents, and it is not the usual
6
+ * plaintext-at-rest one. `~/.claude.json` is already 0600, so the OS is not the
7
+ * weak point. The weak point is that **the agent can read its own config**. Ask
8
+ * Claude Code to debug a flaky MCP server and a perfectly reasonable next step
9
+ * is to cat that file — at which point a live credential is sitting in a
10
+ * transcript, in scrollback, and in whatever that conversation gets pasted
11
+ * into. Nothing has been breached; the key just leaked sideways through normal
12
+ * use.
13
+ *
14
+ * So this resolves a key from one of two places:
15
+ *
16
+ * SLAB_API_KEY the literal key. Simple, and the right answer for CI,
17
+ * containers, and anywhere a secret manager is absent.
18
+ * SLAB_API_KEY_COMMAND a command whose stdout is the key. The config then
19
+ * holds an instruction, not a credential.
20
+ *
21
+ * The command form deliberately knows nothing about any particular vault. One
22
+ * seam covers macOS Keychain, 1Password, pass, Vault, or a script someone
23
+ * writes tomorrow — the same shape as the seeder's `sources/` and the CLI's
24
+ * `platforms/`: name the capability, let each backend implement it, and depend
25
+ * on none of them.
26
+ */
27
+ export type KeySource = 'SLAB_API_KEY' | 'SLAB_API_KEY_COMMAND';
28
+ export interface ResolvedKey {
29
+ key: string;
30
+ /** Which mechanism supplied it. Logged at startup so a wrong key is diagnosable. */
31
+ source: KeySource;
32
+ }
33
+ export declare function resolveApiKey(env?: NodeJS.ProcessEnv): ResolvedKey;
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Where the API key comes from.
3
+ *
4
+ * The obvious option — pasting the key into the MCP client's config as an env
5
+ * value — has a problem specific to agents, and it is not the usual
6
+ * plaintext-at-rest one. `~/.claude.json` is already 0600, so the OS is not the
7
+ * weak point. The weak point is that **the agent can read its own config**. Ask
8
+ * Claude Code to debug a flaky MCP server and a perfectly reasonable next step
9
+ * is to cat that file — at which point a live credential is sitting in a
10
+ * transcript, in scrollback, and in whatever that conversation gets pasted
11
+ * into. Nothing has been breached; the key just leaked sideways through normal
12
+ * use.
13
+ *
14
+ * So this resolves a key from one of two places:
15
+ *
16
+ * SLAB_API_KEY the literal key. Simple, and the right answer for CI,
17
+ * containers, and anywhere a secret manager is absent.
18
+ * SLAB_API_KEY_COMMAND a command whose stdout is the key. The config then
19
+ * holds an instruction, not a credential.
20
+ *
21
+ * The command form deliberately knows nothing about any particular vault. One
22
+ * seam covers macOS Keychain, 1Password, pass, Vault, or a script someone
23
+ * writes tomorrow — the same shape as the seeder's `sources/` and the CLI's
24
+ * `platforms/`: name the capability, let each backend implement it, and depend
25
+ * on none of them.
26
+ */
27
+ import { execSync } from 'node:child_process';
28
+ import { ConfigError } from './errors.js';
29
+ /** How long a credential command may take before we give up on it. */
30
+ const COMMAND_TIMEOUT_MS = 10_000;
31
+ const SETUP_HELP = 'Set one of:\n' +
32
+ ' SLAB_API_KEY — the key itself\n' +
33
+ ' SLAB_API_KEY_COMMAND — a command that prints the key, e.g.\n' +
34
+ ' security find-generic-password -s slab-mcp -w (macOS Keychain)\n' +
35
+ ' op read "op://Private/slab/credential" (1Password)\n' +
36
+ ' pass show slab/api-key (pass)\n' +
37
+ 'Get a key at https://app.slab.dev-jeb.com -> Account -> API Keys.';
38
+ export function resolveApiKey(env = process.env) {
39
+ const literal = env.SLAB_API_KEY?.trim();
40
+ const command = env.SLAB_API_KEY_COMMAND?.trim();
41
+ // The literal wins when both are set. Explicit beats indirect, matching how
42
+ // git and docker resolve credentials — and the startup log names the source,
43
+ // so a forgotten shell export shadowing a vault is visible rather than a
44
+ // mystery 401.
45
+ if (literal)
46
+ return { key: literal, source: 'SLAB_API_KEY' };
47
+ if (command) {
48
+ let output;
49
+ try {
50
+ output = execSync(command, {
51
+ encoding: 'utf8',
52
+ timeout: COMMAND_TIMEOUT_MS,
53
+ // stdin from /dev/null: a credential helper that tries to prompt should
54
+ // fail fast rather than hang forever holding up the handshake. stderr
55
+ // is passed through to our stderr so "keychain item not found" is
56
+ // visible to the user in the client's server log.
57
+ stdio: ['ignore', 'pipe', 'inherit'],
58
+ });
59
+ }
60
+ catch (err) {
61
+ // Deliberately does NOT include the command's stdout — on a partial
62
+ // failure that could be the secret itself.
63
+ const reason = err instanceof Error ? err.message : String(err);
64
+ throw new ConfigError(`SLAB_API_KEY_COMMAND failed: ${reason}\n` +
65
+ `Command was: ${command}\n` +
66
+ 'Run it yourself in a terminal — it must print the key to stdout and exit 0.');
67
+ }
68
+ const key = output.trim();
69
+ if (!key) {
70
+ throw new ConfigError(`SLAB_API_KEY_COMMAND produced no output.\nCommand was: ${command}\n` +
71
+ 'It must print the key to stdout.');
72
+ }
73
+ return { key, source: 'SLAB_API_KEY_COMMAND' };
74
+ }
75
+ throw new ConfigError(`No slab API key configured.\n\n${SETUP_HELP}`);
76
+ }
77
+ //# sourceMappingURL=credentials.js.map
package/dist/errors.js CHANGED
@@ -45,10 +45,14 @@ export class ApiConnectionError extends Error {
45
45
  */
46
46
  const STATUS_HINTS = {
47
47
  401: 'The API key is missing, unknown, revoked, or disabled. This is a configuration problem on the user\'s machine — tell them to check SLAB_API_KEY in their MCP client config. Do not retry.',
48
- 404: 'Either the UUID does not exist or it belongs to another account. slab does not distinguish the two, on purpose. Re-run the matching search tool to get a current UUID rather than guessing one.',
48
+ 404: 'Either the UUID does not exist or it belongs to another account. slab does not distinguish the two, on purpose. Re-run the matching search tool to get a current UUID rather than guessing one. On a collection tool it can also mean this account has no collector yet: the user creates one by signing in at collection.slab.dev-jeb.com.',
49
49
  409: 'The request conflicts with existing data (usually a duplicate). Read the current state before writing again.',
50
50
  422: 'The request body failed validation. Check the field names and value vocabularies with get_vocab, then retry.',
51
- 429: 'Rate limited. Wait before retrying, and batch work into fewer, larger calls.',
51
+ 429: 'Rate limited, and still limited after the server waited and retried. Wait before retrying, and batch work into fewer, larger calls.',
52
+ 500: 'The slab API failed on this request. Retrying the identical call is unlikely to help; tell the user, and try a narrower request.',
53
+ 502: 'The slab API was unreachable for a moment, and still was after two retries. Try again shortly.',
54
+ 503: 'The slab API was unavailable, and still was after two retries. Try again shortly.',
55
+ 504: 'The slab API took too long, and still did after two retries. Try a narrower request (a smaller limit, fewer filters at once).',
52
56
  };
53
57
  /**
54
58
  * Turn any thrown value into a tool result. Never leaks the API key: the key
package/dist/format.d.ts CHANGED
@@ -25,6 +25,8 @@ export interface ToolResult {
25
25
  export declare function text(...parts: Array<string | undefined | null | false>): ToolResult;
26
26
  /** Money, rendered the way a person reads it. `null` becomes an em dash. */
27
27
  export declare function money(value: number | string | null | undefined): string;
28
+ /** "1 sale", "3 sales", "1,204 sales". */
29
+ export declare function plural(n: number | null | undefined, noun: string, nouns?: string): string;
28
30
  /** A 0-1 ratio as a percentage. `portfolio_roi: 0.0645` reads as `6.45%`. */
29
31
  export declare function percent(value: number | string | null | undefined): string;
30
32
  /** A count, rendered as an integer with no currency symbol. */
package/dist/format.js CHANGED
@@ -27,7 +27,13 @@ export function money(value) {
27
27
  const n = typeof value === 'string' ? Number(value) : value;
28
28
  if (!Number.isFinite(n))
29
29
  return '—';
30
- return `$${n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
30
+ const abs = Math.abs(n).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
31
+ return n < 0 ? `-$${abs}` : `$${abs}`;
32
+ }
33
+ /** "1 sale", "3 sales", "1,204 sales". */
34
+ export function plural(n, noun, nouns = `${noun}s`) {
35
+ const value = n ?? 0;
36
+ return `${value.toLocaleString('en-US')} ${value === 1 ? noun : nouns}`;
31
37
  }
32
38
  /** A 0-1 ratio as a percentage. `portfolio_roi: 0.0645` reads as `6.45%`. */
33
39
  export function percent(value) {
package/dist/index.js CHANGED
@@ -20,7 +20,7 @@ import { ConfigError } from './errors.js';
20
20
  import { registerPrompts } from './prompts/index.js';
21
21
  import { registerResources } from './resources/index.js';
22
22
  import { registerTools } from './tools/index.js';
23
- const VERSION = '0.1.0';
23
+ import { VERSION } from './version.js';
24
24
  /** stderr only — see the note above. */
25
25
  function log(message) {
26
26
  process.stderr.write(`[slab-mcp] ${message}\n`);
@@ -43,8 +43,10 @@ function main() {
43
43
  const active = registerTools(server, ctx);
44
44
  registerResources(server, ctx);
45
45
  registerPrompts(server);
46
+ // Names the credential SOURCE, never the credential. Enough to diagnose
47
+ // "which key is it actually using", which is the usual cause of a 401.
46
48
  log(`serving ${active.length} tools against ${config.apiUrl} ` +
47
- `(writes ${config.writesEnabled ? 'ENABLED' : 'disabled'})`);
49
+ `(key from ${config.keySource}, writes ${config.writesEnabled ? 'ENABLED' : 'disabled'})`);
48
50
  return server;
49
51
  }, { onerror: (error) => log(`transport error: ${error.message}`) });
50
52
  }
@@ -49,9 +49,10 @@ export const PROMPTS = [
49
49
  `Research ${args.player}'s trading cards.`,
50
50
  args.budget ? `I am working with a budget of about ${args.budget}.` : '',
51
51
  '',
52
- 'Start with search_cards filtered by subject, using facets to see how the cards break down by',
53
- 'year, set, and finish rather than paging through every parallel. Then use get_card_pricing on',
54
- 'the handful worth a closer look.',
52
+ 'Start with search_cards filtered by subject with `collapse_parallels` and facets, to see how the',
53
+ 'cards break down by year and set rather than paging through every parallel. Use get_rainbow on',
54
+ 'the slots worth a closer look to see their parallels, print runs and odds, then get_card_pricing',
55
+ 'on the printings that matter.',
55
56
  '',
56
57
  'Tell me: what the notable cards are, which are genuinely scarce (print run, not vibes), and',
57
58
  'what recent sales actually show. When you talk about movement, count real sales from the comps',
@@ -73,9 +74,9 @@ export const PROMPTS = [
73
74
  `Help me decide whether to grade: ${args.card}.`,
74
75
  args.grading_cost ? `Grading would cost about ${args.grading_cost}.` : '',
75
76
  '',
76
- 'Find the card, then use get_card_pricing to compare the raw value against the graded values at',
77
- 'each grade key. The gap is the grading uplift, and it only pays if it exceeds the grading cost',
78
- 'at a grade the card would realistically receive.',
77
+ 'Find the card, then use get_grading_desk: its raw value beside what it sells for at each grade',
78
+ 'and grading company. The gap is the grading uplift, and it only pays if it exceeds the grading',
79
+ 'cost at a grade the card would realistically receive. A grade marked ESTIMATE has no sales.',
79
80
  '',
80
81
  'Be honest about the uncertainty: I do not know what grade it would get, and the graded value',
81
82
  'may rest on very few sales. Give me the break-even grade rather than a single recommendation,',
@@ -84,6 +85,30 @@ export const PROMPTS = [
84
85
  .filter(Boolean)
85
86
  .join('\n'),
86
87
  },
88
+ {
89
+ name: 'whats-hot',
90
+ title: "What's hot in hockey cards",
91
+ description: 'A read on the hockey card market right now: who is selling, what collectors want, how the market moved.',
92
+ argsSchema: z.object({
93
+ focus: z.string().optional().describe('Optional narrowing, e.g. "rookies", "this year\'s Young Guns", "hobby boxes".'),
94
+ }),
95
+ render: (args) => [
96
+ "Tell me what's happening in hockey cards right now.",
97
+ args.focus ? `Focus on: ${args.focus}.` : '',
98
+ '',
99
+ 'Use get_community for the hottest players, the most wanted and most collected cards and the',
100
+ 'card of the day, and get_market_index for how the market moved beyond what card age explains.',
101
+ 'Then look closer at two or three of the cards with get_card_pricing.',
102
+ '',
103
+ 'Constraints on how you report it:',
104
+ '- Hottest players are counted from sales slab saw. Say "sales seen", never "volume".',
105
+ "- The market index is slab's own measure; quote its glossary wording rather than calling it",
106
+ ' prices rising or falling.',
107
+ '- A value resting on one or two sales is thin. Say so.',
108
+ ]
109
+ .filter(Boolean)
110
+ .join('\n'),
111
+ },
87
112
  ];
88
113
  export function registerPrompts(server) {
89
114
  for (const prompt of PROMPTS) {
@@ -10,6 +10,7 @@
10
10
  * Adding a resource: one entry in RESOURCES.
11
11
  */
12
12
  import type { McpServer } from '@modelcontextprotocol/server';
13
+ import { type ApiPath } from '../client.js';
13
14
  import type { ToolContext } from '../context.js';
14
15
  interface ResourceModule {
15
16
  name: string;
@@ -18,7 +19,7 @@ interface ResourceModule {
18
19
  description: string;
19
20
  mimeType: string;
20
21
  /** Path on the slab API whose body is served verbatim. */
21
- path: string;
22
+ path: ApiPath;
22
23
  }
23
24
  export declare const RESOURCES: ResourceModule[];
24
25
  export declare function registerResources(server: McpServer, ctx: ToolContext): void;
@@ -9,6 +9,7 @@
9
9
  *
10
10
  * Adding a resource: one entry in RESOURCES.
11
11
  */
12
+ import { api } from '../client.js';
12
13
  export const RESOURCES = [
13
14
  {
14
15
  name: 'vocab',
@@ -18,7 +19,7 @@ export const RESOURCES = [
18
19
  'dimensions (brands, teams, attributes, finishes, grading companies) that grow as sets are ' +
19
20
  'seeded. Read this instead of assuming a filter value.',
20
21
  mimeType: 'application/json',
21
- path: '/vocab',
22
+ path: api `/vocab`,
22
23
  },
23
24
  {
24
25
  name: 'glossary',
@@ -27,7 +28,7 @@ export const RESOURCES = [
27
28
  description: 'Plain-language definition of every metric the slab API returns, keyed by namespaced id. Use ' +
28
29
  "slab's wording when explaining a number to a user rather than composing your own.",
29
30
  mimeType: 'application/json',
30
- path: '/glossary',
31
+ path: api `/glossary`,
31
32
  },
32
33
  {
33
34
  name: 'openapi',
@@ -37,7 +38,7 @@ export const RESOURCES = [
37
38
  'read this when you need to know exactly what a field means or what an endpoint returns. Large ' +
38
39
  '— fetch it deliberately, not by default.',
39
40
  mimeType: 'application/json',
40
- path: '/openapi.json',
41
+ path: api `/openapi.json`,
41
42
  },
42
43
  ];
43
44
  export function registerResources(server, ctx) {