slab-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 (56) hide show
  1. package/README.md +264 -0
  2. package/dist/client.d.ts +26 -0
  3. package/dist/client.js +100 -0
  4. package/dist/client.js.map +1 -0
  5. package/dist/config.d.ts +21 -0
  6. package/dist/config.js +34 -0
  7. package/dist/config.js.map +1 -0
  8. package/dist/context.d.ts +20 -0
  9. package/dist/context.js +39 -0
  10. package/dist/context.js.map +1 -0
  11. package/dist/errors.d.ts +38 -0
  12. package/dist/errors.js +76 -0
  13. package/dist/errors.js.map +1 -0
  14. package/dist/format.d.ts +64 -0
  15. package/dist/format.js +125 -0
  16. package/dist/format.js.map +1 -0
  17. package/dist/index.d.ts +15 -0
  18. package/dist/index.js +52 -0
  19. package/dist/index.js.map +1 -0
  20. package/dist/prompts/index.d.ts +23 -0
  21. package/dist/prompts/index.js +104 -0
  22. package/dist/prompts/index.js.map +1 -0
  23. package/dist/resources/index.d.ts +25 -0
  24. package/dist/resources/index.js +60 -0
  25. package/dist/resources/index.js.map +1 -0
  26. package/dist/tools/catalog.d.ts +93 -0
  27. package/dist/tools/catalog.js +103 -0
  28. package/dist/tools/catalog.js.map +1 -0
  29. package/dist/tools/collection.d.ts +87 -0
  30. package/dist/tools/collection.js +130 -0
  31. package/dist/tools/collection.js.map +1 -0
  32. package/dist/tools/community.d.ts +10 -0
  33. package/dist/tools/community.js +74 -0
  34. package/dist/tools/community.js.map +1 -0
  35. package/dist/tools/filters.d.ts +51 -0
  36. package/dist/tools/filters.js +54 -0
  37. package/dist/tools/filters.js.map +1 -0
  38. package/dist/tools/index.d.ts +22 -0
  39. package/dist/tools/index.js +55 -0
  40. package/dist/tools/index.js.map +1 -0
  41. package/dist/tools/meta.d.ts +33 -0
  42. package/dist/tools/meta.js +98 -0
  43. package/dist/tools/meta.js.map +1 -0
  44. package/dist/tools/pricing.d.ts +30 -0
  45. package/dist/tools/pricing.js +90 -0
  46. package/dist/tools/pricing.js.map +1 -0
  47. package/dist/tools/types.d.ts +69 -0
  48. package/dist/tools/types.js +50 -0
  49. package/dist/tools/types.js.map +1 -0
  50. package/dist/tools/writes.d.ts +128 -0
  51. package/dist/tools/writes.js +168 -0
  52. package/dist/tools/writes.js.map +1 -0
  53. package/dist/types.d.ts +80 -0
  54. package/dist/types.js +11 -0
  55. package/dist/types.js.map +1 -0
  56. package/package.json +53 -0
package/README.md ADDED
@@ -0,0 +1,264 @@
1
+ # slab-mcp
2
+
3
+ An [MCP](https://modelcontextprotocol.io) server for the [slab](https://app.slab.dev-jeb.com)
4
+ trading-card API. It runs locally on your machine and gives an AI agent — Claude Code, Claude
5
+ Desktop, Cursor, or anything else that speaks MCP — the ability to search the card catalog, read
6
+ pricing, and (if you turn it on) manage your collection.
7
+
8
+ Ask your agent *"what are my three most valuable rookies, and is any of them worth grading?"* and it
9
+ has the tools to actually answer.
10
+
11
+ **Read-only by default.** Write tools are not registered at all unless you opt in.
12
+
13
+ ## Prerequisites
14
+
15
+ - **Node.js 20+** ([nodejs.org](https://nodejs.org))
16
+ - A **slab API key** ([app.slab.dev-jeb.com](https://app.slab.dev-jeb.com) → Account → API Keys)
17
+
18
+ ## Install
19
+
20
+ Once published, no install step is needed — your MCP client runs it with `npx`.
21
+
22
+ ### Claude Code
23
+
24
+ ```bash
25
+ claude mcp add slab --env SLAB_API_KEY=sk_live_your_key_here -- npx -y slab-mcp
26
+ ```
27
+
28
+ ### Claude Desktop, Cursor, and other config-file clients
29
+
30
+ Add this to the client's MCP config (`claude_desktop_config.json` for Claude Desktop):
31
+
32
+ ```json
33
+ {
34
+ "mcpServers": {
35
+ "slab": {
36
+ "command": "npx",
37
+ "args": ["-y", "slab-mcp"],
38
+ "env": {
39
+ "SLAB_API_KEY": "sk_live_your_key_here"
40
+ }
41
+ }
42
+ }
43
+ }
44
+ ```
45
+
46
+ Restart the client. You should see a `slab` server with 8 tools.
47
+
48
+ ### From source
49
+
50
+ ```bash
51
+ git clone https://github.com/dev-jeb/slab-community.git
52
+ cd slab-community/slab-mcp
53
+ npm install
54
+ npm run build
55
+ ```
56
+
57
+ Then point your client at `node /absolute/path/to/slab-community/slab-mcp/dist/index.js` instead of
58
+ the `npx` command.
59
+
60
+ ## Configuration
61
+
62
+ Every setting is an environment variable, set in your MCP client's `env` block. There is no config
63
+ file and no way to pass credentials as a tool argument — the model on the other end never sees your
64
+ key.
65
+
66
+ | Variable | Required | Default | Description |
67
+ |---|---|---|---|
68
+ | `SLAB_API_KEY` | Yes | — | Your slab API key. |
69
+ | `SLAB_API_URL` | No | `https://api.slab.dev-jeb.com` | Override for local development. |
70
+ | `SLAB_COLLECTOR` | No | your account's default | Collector UUID to act as. |
71
+ | `SLAB_MCP_WRITE` | No | `0` | Set to `1` to register the write tools. |
72
+ | `SLAB_MCP_TIMEOUT_MS` | No | `30000` | Per-request HTTP timeout. |
73
+
74
+ ### Enabling writes
75
+
76
+ ```json
77
+ "env": {
78
+ "SLAB_API_KEY": "sk_live_your_key_here",
79
+ "SLAB_MCP_WRITE": "1"
80
+ }
81
+ ```
82
+
83
+ With this off, the five write tools are never registered, so the agent cannot call them — that is a
84
+ stronger guarantee than telling it not to. With it on, each write tool declares the MCP annotations
85
+ (`readOnlyHint`, `destructiveHint`) that let your client prompt you before it runs. Whether your
86
+ client actually prompts is up to your client; the annotations only make it possible.
87
+
88
+ ## Tools
89
+
90
+ **Read** (always available)
91
+
92
+ | Tool | What it does |
93
+ |---|---|
94
+ | `search_cards` | Search the catalog. The entry point — most other tools take a UUID from here. |
95
+ | `search_sets` | Find a product/release. |
96
+ | `get_set_detail` | A set's sealed prices and its most valuable cards. |
97
+ | `get_card_pricing` | Fair market value, the individual sales behind it, and the daily series. |
98
+ | `search_collection` | Search your own copies, with a financial summary. |
99
+ | `get_dashboard` | Collection totals, top cards, and portfolio history. |
100
+ | `get_community` | Public leaderboards and activity. |
101
+ | `get_vocab` | Every value the API accepts, live from the catalog. |
102
+ | `explain_metrics` | What a slab number means, in slab's own words. |
103
+
104
+ **Write** (only when `SLAB_MCP_WRITE=1`)
105
+
106
+ | Tool | What it does |
107
+ |---|---|
108
+ | `add_copy` | Record a card you own. |
109
+ | `update_copy` | Change a copy, including recording a sale. |
110
+ | `remove_copy` | Delete a copy record. Destructive, no undo. |
111
+ | `log_break` | Log a sealed product you opened, so pulls get a real cost basis. |
112
+ | `log_lot` | Log a multi-card purchase, same idea. |
113
+
114
+ ## Resources and prompts
115
+
116
+ Three **resources** let an agent pull reference material without spending a tool call:
117
+ `slab://vocab` (every accepted value), `slab://glossary` (what each metric means), and
118
+ `slab://openapi` (the full API contract). All three are served from the live API rather than
119
+ copied into this repo, so they can't go stale.
120
+
121
+ Three **prompts** show up in your client's slash menu as starting points:
122
+ `appraise-collection`, `research-player`, and `grading-decision`.
123
+
124
+ ## How the tools are designed
125
+
126
+ Two decisions explain most of the code, and are worth knowing before you extend it.
127
+
128
+ **Task-shaped, not endpoint-shaped.** The slab API has ~46 routes; this server exposes 13 tools.
129
+ Mapping routes 1:1 would put 46 schemas into the agent's context on every single request and make
130
+ tool selection worse, not better. Each tool here answers a question a person actually asks, folding
131
+ several endpoints where that's the natural unit — `get_card_pricing` is `/market` + `/comps` +
132
+ `/price-history`, because "what's it worth" is one question.
133
+
134
+ **Results are formatted, not dumped.** A tool result is spent out of the agent's context window. A
135
+ raw search page is tens of thousands of tokens of JSON, mostly nulls and repeated keys. Results here
136
+ render one entity per line with the UUID first, and every paged result says how many rows exist so
137
+ the agent knows whether it has seen everything.
138
+
139
+ **Nothing enumerable or explanatory is written down here.** slab serves both, so this server asks:
140
+ `get_vocab` for values (statuses, sort keys, and the live catalog dimensions that grow with every
141
+ seeded set) and `explain_metrics` for what a number means. No tool description lists a brand, team,
142
+ attribute, or finish, and none writes its own definition of `priced_coverage` — a copy in this repo
143
+ would rot, and a hand-written gloss would drift from what the portal and CLI show the same user.
144
+ Tools that report figures point the agent at `explain_metrics`, responses that embed their own
145
+ glossary render it inline, and a test fails the build if a metric-bearing tool stops doing either.
146
+
147
+ Two rules from the slab data model are written into the tool descriptions rather than left to the
148
+ agent to figure out, because getting them wrong produces a confident false statement about someone's
149
+ money:
150
+
151
+ - **Prices are appraisals, not tickers.** A fair market value is a trimmed median of the trailing 90
152
+ days, so differencing two snapshots measures how the *appraisal* drifted — not what the market did
153
+ over that window. Real market movement comes from counting comps.
154
+ - **The portfolio series is as-of.** It steps up when you buy a card, so differencing two points
155
+ mixes purchases with price movement and is not a return.
156
+
157
+ ## Extending it
158
+
159
+ The whole surface is a registry. Adding a tool is a new module plus one line:
160
+
161
+ ```
162
+ src/
163
+ tools/
164
+ index.ts <- THE REGISTRY: read tools, write tools, registration loop
165
+ types.ts <- the ToolModule contract + annotation presets
166
+ filters.ts <- the shared card filter grammar, defined once
167
+ catalog.ts collection.ts pricing.ts writes.ts meta.ts
168
+ resources/index.ts <- add a resource: one entry in RESOURCES
169
+ prompts/index.ts <- add a prompt: one entry in PROMPTS
170
+ client.ts <- HTTP, auth, timeouts, error shapes. Knows nothing about cards.
171
+ index.ts <- wiring only. Adding a tool never touches this file.
172
+ ```
173
+
174
+ To add a tool:
175
+
176
+ ```ts
177
+ export const getMyThing = defineTool({
178
+ name: 'get_my_thing',
179
+ title: 'Get my thing',
180
+ description: 'When to call this, and what the numbers mean. Name the tool that produces any UUID this one takes.',
181
+ inputSchema: z.object({
182
+ thing_uuid: z.string().describe('Thing UUID, from search_things.'),
183
+ }),
184
+ annotations: READ_ONLY, // or CREATES / UPDATES / DELETES
185
+ mutates: false, // true puts it behind SLAB_MCP_WRITE
186
+ async handler(input, ctx) {
187
+ const thing = await ctx.client.request<Thing>('GET', `/things/${input.thing_uuid}`);
188
+ return text(`...`);
189
+ },
190
+ });
191
+ ```
192
+
193
+ Then add it to the array in `tools/index.ts`. That's it — registration, argument validation, error
194
+ handling, and the write gate are all handled by the loop.
195
+
196
+ `mutates` and `annotations` are required, not optional, because a write tool that looks read-only
197
+ gets no confirmation prompt from the host. `npm test` enforces that they agree, along with the
198
+ things prose can't check for itself: unique snake_case names, a description substantial enough to
199
+ route on, a `.describe()` on every input field, destructive tools marked destructive, and no tool
200
+ description that hardcodes a live catalog vocabulary or calls appraisal drift a market move.
201
+
202
+ ## Development
203
+
204
+ ```bash
205
+ npm install
206
+ npm run dev # run against the API without building
207
+ npm test # offline: no network, no key, no server
208
+ npm run typecheck
209
+ npm run build
210
+ ```
211
+
212
+ **Never write to stdout.** In a stdio MCP server, stdout is the protocol — one stray `console.log`
213
+ corrupts the JSON-RPC stream and the client drops the connection with an error that points nowhere
214
+ near the cause. Diagnostics go to stderr, which your client surfaces as the server's log.
215
+
216
+ To inspect the server by hand:
217
+
218
+ ```bash
219
+ npx @modelcontextprotocol/inspector node dist/index.js
220
+ ```
221
+
222
+ ## Releasing
223
+
224
+ Publishing runs on [npm trusted publishing](https://docs.npmjs.com/trusted-publishers) (OIDC).
225
+ There is **no `NPM_TOKEN` anywhere in this repo** — the workflow mints a short-lived identity token
226
+ that npm exchanges for a credential good for one publish, and attaches a provenance attestation
227
+ linking the tarball to the exact commit that built it. Nothing long-lived exists to leak.
228
+
229
+ One-time setup (OIDC cannot perform a package's *first* publish — npm requires the package to exist
230
+ before a trusted publisher can be attached):
231
+
232
+ 1. `cd slab-mcp && npm publish` once by hand, logged in as the package owner.
233
+ 2. On npmjs.com → the `slab-mcp` package → **Settings → Trusted Publisher → GitHub Actions**:
234
+ organization `dev-jeb`, repository `slab-community`, workflow filename
235
+ `slab-mcp-publish.yml` (filename only), environment `npm-publish`.
236
+ 3. GitHub → repo **Settings → Environments → New environment** `npm-publish`, and add yourself as a
237
+ required reviewer so every publish waits for a human click.
238
+
239
+ After that, releasing is:
240
+
241
+ ```bash
242
+ # bump "version" in slab-mcp/package.json, then:
243
+ git commit -am "slab-mcp 0.1.1"
244
+ git tag slab-mcp-v0.1.1
245
+ git push origin main slab-mcp-v0.1.1
246
+ ```
247
+
248
+ The tag is namespaced per tool, so each directory in this repo releases on its own schedule. The
249
+ workflow re-runs typecheck, tests, and build, and refuses to publish if the tag disagrees with
250
+ `package.json` — npm never lets a version number be reused, so that mistake is unfixable.
251
+
252
+ ## Limits and caveats
253
+
254
+ - Read-only unless you opt in, and it acts for exactly one collector.
255
+ - No caching. Every tool call is a live request; `slab://openapi` is large, so fetch it deliberately.
256
+ - stdio transport only. It is meant to run on your machine next to your agent, not to be hosted.
257
+ - Tool inputs cover the well-trodden subset of slab's filter grammar. The full contract is always
258
+ `GET /openapi.json` — if this server and the spec disagree, the spec is right.
259
+
260
+ ## License
261
+
262
+ MIT, same as the rest of this repo.
263
+
264
+ Maintained by [@dev-jeb](https://github.com/dev-jeb).
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Thin typed HTTP client for the slab API.
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.
7
+ *
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.
12
+ */
13
+ import type { Config } from './config.js';
14
+ export interface RequestOptions {
15
+ /** JSON request body. Undefined keys are stripped before sending. */
16
+ body?: unknown;
17
+ /** Query parameters. Undefined/null values are dropped. */
18
+ query?: Record<string, string | number | boolean | undefined | null>;
19
+ }
20
+ export declare class SlabClient {
21
+ private readonly config;
22
+ constructor(config: Config);
23
+ request<T>(method: string, path: string, options?: RequestOptions): Promise<T>;
24
+ /** Fetch a public document verbatim (used by the resource handlers). */
25
+ raw(path: string): Promise<string>;
26
+ }
package/dist/client.js ADDED
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Thin typed HTTP client for the slab API.
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.
7
+ *
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.
12
+ */
13
+ import { ApiConnectionError, ApiError } from './errors.js';
14
+ /** Strip undefined values so we never send `{"brand": undefined}` -> `{"brand": null}`. */
15
+ function prune(value) {
16
+ if (Array.isArray(value))
17
+ return value.map(prune);
18
+ if (value && typeof value === 'object') {
19
+ const out = {};
20
+ for (const [k, v] of Object.entries(value)) {
21
+ if (v !== undefined)
22
+ out[k] = prune(v);
23
+ }
24
+ return out;
25
+ }
26
+ return value;
27
+ }
28
+ export class SlabClient {
29
+ config;
30
+ constructor(config) {
31
+ this.config = config;
32
+ }
33
+ async request(method, path, options = {}) {
34
+ const url = new URL(this.config.apiUrl + path);
35
+ for (const [key, value] of Object.entries(options.query ?? {})) {
36
+ if (value !== undefined && value !== null)
37
+ url.searchParams.set(key, String(value));
38
+ }
39
+ const headers = {
40
+ 'x-api-key': this.config.apiKey,
41
+ accept: 'application/json',
42
+ 'user-agent': 'slab-mcp',
43
+ };
44
+ if (options.body !== undefined)
45
+ headers['content-type'] = 'application/json';
46
+ let response;
47
+ try {
48
+ response = await fetch(url, {
49
+ method,
50
+ headers,
51
+ body: options.body === undefined ? undefined : JSON.stringify(prune(options.body)),
52
+ signal: AbortSignal.timeout(this.config.timeoutMs),
53
+ });
54
+ }
55
+ catch (err) {
56
+ const reason = err instanceof Error && err.name === 'TimeoutError'
57
+ ? `request timed out after ${this.config.timeoutMs}ms`
58
+ : err instanceof Error
59
+ ? err.message
60
+ : String(err);
61
+ throw new ApiConnectionError(this.config.apiUrl, reason);
62
+ }
63
+ if (!response.ok) {
64
+ let detail = await response.text();
65
+ try {
66
+ const parsed = JSON.parse(detail);
67
+ if (parsed && typeof parsed === 'object' && 'detail' in parsed) {
68
+ detail = typeof parsed.detail === 'string' ? parsed.detail : JSON.stringify(parsed.detail);
69
+ }
70
+ }
71
+ catch {
72
+ // Body was not JSON; the raw text is the best detail we have.
73
+ }
74
+ throw new ApiError(response.status, detail.slice(0, 2000), method, path);
75
+ }
76
+ if (response.status === 204)
77
+ return undefined;
78
+ const text = await response.text();
79
+ return (text ? JSON.parse(text) : undefined);
80
+ }
81
+ /** Fetch a public document verbatim (used by the resource handlers). */
82
+ async raw(path) {
83
+ const url = this.config.apiUrl + path;
84
+ try {
85
+ const response = await fetch(url, {
86
+ headers: { 'x-api-key': this.config.apiKey, 'user-agent': 'slab-mcp' },
87
+ signal: AbortSignal.timeout(this.config.timeoutMs),
88
+ });
89
+ if (!response.ok)
90
+ throw new ApiError(response.status, await response.text(), 'GET', path);
91
+ return await response.text();
92
+ }
93
+ catch (err) {
94
+ if (err instanceof ApiError)
95
+ throw err;
96
+ throw new ApiConnectionError(this.config.apiUrl, err instanceof Error ? err.message : String(err));
97
+ }
98
+ }
99
+ }
100
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAGH,OAAO,EAAE,kBAAkB,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAS3D,2FAA2F;AAC3F,SAAS,KAAK,CAAC,KAAc;IAC3B,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IAClD,IAAI,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QACvC,MAAM,GAAG,GAA4B,EAAE,CAAC;QACxC,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAgC,CAAC,EAAE,CAAC;YACtE,IAAI,CAAC,KAAK,SAAS;gBAAE,GAAG,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;QACzC,CAAC;QACD,OAAO,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,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAM,CAAC;IACpD,CAAC;IAED,wEAAwE;IACxE,KAAK,CAAC,GAAG,CAAC,IAAY;QACpB,MAAM,GAAG,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,IAAI,CAAC;QACtC,IAAI,CAAC;YACH,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,EAAE;gBAChC,OAAO,EAAE,EAAE,WAAW,EAAE,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,YAAY,EAAE,UAAU,EAAE;gBACtE,MAAM,EAAE,WAAW,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC;aACnD,CAAC,CAAC;YACH,IAAI,CAAC,QAAQ,CAAC,EAAE;gBAAE,MAAM,IAAI,QAAQ,CAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,QAAQ,CAAC,IAAI,EAAE,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;YAC1F,OAAO,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QAC/B,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,IAAI,GAAG,YAAY,QAAQ;gBAAE,MAAM,GAAG,CAAC;YACvC,MAAM,IAAI,kBAAkB,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;QACrG,CAAC;IACH,CAAC;CACF"}
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Configuration, read from the environment exactly once at startup.
3
+ *
4
+ * The API key lives here and nowhere else. It is never a tool argument and is
5
+ * never included in a tool result, so the model on the other end of the
6
+ * transport cannot read it, echo it, or be tricked into exfiltrating it.
7
+ */
8
+ export declare const DEFAULT_API_URL = "https://api.slab.dev-jeb.com";
9
+ export interface Config {
10
+ /** Base URL of the slab API, no trailing slash. */
11
+ apiUrl: string;
12
+ /** Value sent as the `x-api-key` header on every request. */
13
+ apiKey: string;
14
+ /** Collector the key acts for. Undefined = resolve lazily from `GET /account`. */
15
+ collectorUuid: string | undefined;
16
+ /** Whether mutating tools are registered at all. Off unless SLAB_MCP_WRITE=1. */
17
+ writesEnabled: boolean;
18
+ /** Per-request HTTP timeout. */
19
+ timeoutMs: number;
20
+ }
21
+ export declare function loadConfig(env?: NodeJS.ProcessEnv): Config;
package/dist/config.js ADDED
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Configuration, read from the environment exactly once at startup.
3
+ *
4
+ * The API key lives here and nowhere else. It is never a tool argument and is
5
+ * never included in a tool result, so the model on the other end of the
6
+ * transport cannot read it, echo it, or be tricked into exfiltrating it.
7
+ */
8
+ import { ConfigError } from './errors.js';
9
+ export const DEFAULT_API_URL = 'https://api.slab.dev-jeb.com';
10
+ function truthy(value) {
11
+ if (!value)
12
+ return false;
13
+ return ['1', 'true', 'yes', 'on'].includes(value.trim().toLowerCase());
14
+ }
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).');
20
+ }
21
+ const timeoutRaw = env.SLAB_MCP_TIMEOUT_MS?.trim();
22
+ const timeoutMs = timeoutRaw ? Number(timeoutRaw) : 30_000;
23
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
24
+ throw new ConfigError(`SLAB_MCP_TIMEOUT_MS must be a positive number of milliseconds, got "${timeoutRaw}".`);
25
+ }
26
+ return {
27
+ apiUrl: (env.SLAB_API_URL?.trim() || DEFAULT_API_URL).replace(/\/+$/, ''),
28
+ apiKey,
29
+ collectorUuid: env.SLAB_COLLECTOR?.trim() || undefined,
30
+ writesEnabled: truthy(env.SLAB_MCP_WRITE),
31
+ timeoutMs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,EAAE,IAAI,SAAS;QACtD,aAAa,EAAE,MAAM,CAAC,GAAG,CAAC,cAAc,CAAC;QACzC,SAAS;KACV,CAAC;AACJ,CAAC"}
@@ -0,0 +1,20 @@
1
+ /**
2
+ * The object every tool handler receives.
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.
8
+ */
9
+ import { SlabClient } from './client.js';
10
+ import type { Config } from './config.js';
11
+ export interface ToolContext {
12
+ client: SlabClient;
13
+ 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>;
19
+ }
20
+ export declare function createContext(config: Config): ToolContext;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The object every tool handler receives.
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.
8
+ */
9
+ 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
+ }
22
+ return {
23
+ client,
24
+ 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
+ },
37
+ };
38
+ }
39
+ //# sourceMappingURL=context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.js","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAavC,MAAM,UAAU,aAAa,CAAC,MAAc;IAC1C,MAAM,MAAM,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC;IACtC,IAAI,QAAqC,CAAC;IAE1C,KAAK,UAAU,cAAc;QAC3B,MAAM,OAAO,GAAG,MAAM,MAAM,CAAC,OAAO,CAAa,KAAK,EAAE,UAAU,CAAC,CAAC;QACpE,MAAM,IAAI,GAAG,OAAO,CAAC,sBAAsB,IAAI,OAAO,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC;QAC7E,IAAI,CAAC,IAAI,EAAE,CAAC;YACV,MAAM,IAAI,QAAQ,CAChB,GAAG,EACH,oIAAoI,EACpI,KAAK,EACL,UAAU,CACX,CAAC;QACJ,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO;QACL,MAAM;QACN,MAAM;QACN,KAAK,CAAC,SAAS,CAAC,QAAiB;YAC/B,IAAI,QAAQ;gBAAE,OAAO,QAAQ,CAAC;YAC9B,IAAI,MAAM,CAAC,aAAa;gBAAE,OAAO,MAAM,CAAC,aAAa,CAAC;YACtD,mFAAmF;YACnF,QAAQ,KAAK,cAAc,EAAE,CAAC,KAAK,CAAC,CAAC,GAAY,EAAE,EAAE;gBACnD,QAAQ,GAAG,SAAS,CAAC,CAAC,mDAAmD;gBACzE,MAAM,GAAG,CAAC;YACZ,CAAC,CAAC,CAAC;YACH,OAAO,QAAQ,CAAC;QAClB,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Error types and the single place where an error becomes a tool result.
3
+ *
4
+ * MCP draws a line most HTTP clients don't: a *protocol* failure (bad method,
5
+ * server broken) is a JSON-RPC error, while a *tool* failure (the card wasn't
6
+ * found, the key was revoked) is a successful response carrying
7
+ * `isError: true`. The second kind is the one the model can see and react to,
8
+ * so every expected failure goes through `toToolError` and comes back as text
9
+ * the model can actually act on.
10
+ */
11
+ export declare class ConfigError extends Error {
12
+ constructor(message: string);
13
+ }
14
+ /** A 4xx/5xx from the slab API. */
15
+ export declare class ApiError extends Error {
16
+ readonly status: number;
17
+ readonly detail: string;
18
+ readonly method: string;
19
+ readonly path: string;
20
+ constructor(status: number, detail: string, method: string, path: string);
21
+ }
22
+ /** The slab API could not be reached at all. */
23
+ export declare class ApiConnectionError extends Error {
24
+ readonly url: string;
25
+ constructor(url: string, reason: string);
26
+ }
27
+ export interface ToolErrorResult {
28
+ content: Array<{
29
+ type: 'text';
30
+ text: string;
31
+ }>;
32
+ isError: true;
33
+ }
34
+ /**
35
+ * Turn any thrown value into a tool result. Never leaks the API key: the key
36
+ * is only ever a header value, and nothing here reads request headers back.
37
+ */
38
+ export declare function toToolError(err: unknown): ToolErrorResult;
package/dist/errors.js ADDED
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Error types and the single place where an error becomes a tool result.
3
+ *
4
+ * MCP draws a line most HTTP clients don't: a *protocol* failure (bad method,
5
+ * server broken) is a JSON-RPC error, while a *tool* failure (the card wasn't
6
+ * found, the key was revoked) is a successful response carrying
7
+ * `isError: true`. The second kind is the one the model can see and react to,
8
+ * so every expected failure goes through `toToolError` and comes back as text
9
+ * the model can actually act on.
10
+ */
11
+ export class ConfigError extends Error {
12
+ constructor(message) {
13
+ super(message);
14
+ this.name = 'ConfigError';
15
+ }
16
+ }
17
+ /** A 4xx/5xx from the slab API. */
18
+ export class ApiError extends Error {
19
+ status;
20
+ detail;
21
+ method;
22
+ path;
23
+ constructor(status, detail, method, path) {
24
+ super(`[${status}] ${method} ${path}: ${detail}`);
25
+ this.status = status;
26
+ this.detail = detail;
27
+ this.method = method;
28
+ this.path = path;
29
+ this.name = 'ApiError';
30
+ }
31
+ }
32
+ /** The slab API could not be reached at all. */
33
+ export class ApiConnectionError extends Error {
34
+ url;
35
+ constructor(url, reason) {
36
+ super(`Cannot reach the slab API at ${url}: ${reason}`);
37
+ this.url = url;
38
+ this.name = 'ApiConnectionError';
39
+ }
40
+ }
41
+ /**
42
+ * Guidance the model can act on, keyed by status. Without this an agent sees
43
+ * "[404] not found" and retries the identical call; with it, it knows the next
44
+ * move.
45
+ */
46
+ const STATUS_HINTS = {
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.',
49
+ 409: 'The request conflicts with existing data (usually a duplicate). Read the current state before writing again.',
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.',
52
+ };
53
+ /**
54
+ * Turn any thrown value into a tool result. Never leaks the API key: the key
55
+ * is only ever a header value, and nothing here reads request headers back.
56
+ */
57
+ export function toToolError(err) {
58
+ let text;
59
+ if (err instanceof ApiError) {
60
+ const hint = STATUS_HINTS[err.status];
61
+ text = `slab API error ${err.status} on ${err.method} ${err.path}: ${err.detail}`;
62
+ if (hint)
63
+ text += `\n\n${hint}`;
64
+ }
65
+ else if (err instanceof ApiConnectionError || err instanceof ConfigError) {
66
+ text = err.message;
67
+ }
68
+ else if (err instanceof Error) {
69
+ text = `Unexpected error: ${err.message}`;
70
+ }
71
+ else {
72
+ text = `Unexpected error: ${String(err)}`;
73
+ }
74
+ return { content: [{ type: 'text', text }], isError: true };
75
+ }
76
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js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