slab-mcp 0.2.1 → 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 (56) hide show
  1. package/README.md +140 -107
  2. package/dist/client.d.ts +34 -13
  3. package/dist/client.js +99 -59
  4. package/dist/config.d.ts +4 -2
  5. package/dist/config.js +27 -2
  6. package/dist/context.d.ts +8 -12
  7. package/dist/context.js +7 -29
  8. package/dist/errors.js +6 -2
  9. package/dist/format.d.ts +2 -0
  10. package/dist/format.js +7 -1
  11. package/dist/prompts/index.js +31 -6
  12. package/dist/resources/index.d.ts +2 -1
  13. package/dist/resources/index.js +4 -3
  14. package/dist/tools/args.d.ts +18 -0
  15. package/dist/tools/args.js +26 -0
  16. package/dist/tools/catalog.d.ts +21 -6
  17. package/dist/tools/catalog.js +88 -47
  18. package/dist/tools/chases.d.ts +28 -0
  19. package/dist/tools/chases.js +72 -0
  20. package/dist/tools/collection.d.ts +26 -18
  21. package/dist/tools/collection.js +113 -82
  22. package/dist/tools/community.d.ts +16 -3
  23. package/dist/tools/community.js +110 -50
  24. package/dist/tools/filters.d.ts +6 -0
  25. package/dist/tools/filters.js +6 -0
  26. package/dist/tools/index.js +2 -0
  27. package/dist/tools/lines.d.ts +20 -0
  28. package/dist/tools/lines.js +31 -0
  29. package/dist/tools/meta.js +5 -4
  30. package/dist/tools/pricing.d.ts +21 -16
  31. package/dist/tools/pricing.js +167 -63
  32. package/dist/tools/writes.d.ts +43 -47
  33. package/dist/tools/writes.js +65 -29
  34. package/dist/types.d.ts +48 -77
  35. package/dist/types.js +6 -6
  36. package/package.json +14 -5
  37. package/dist/client.js.map +0 -1
  38. package/dist/config.js.map +0 -1
  39. package/dist/context.js.map +0 -1
  40. package/dist/credentials.js.map +0 -1
  41. package/dist/errors.js.map +0 -1
  42. package/dist/format.js.map +0 -1
  43. package/dist/index.js.map +0 -1
  44. package/dist/prompts/index.js.map +0 -1
  45. package/dist/resources/index.js.map +0 -1
  46. package/dist/tools/catalog.js.map +0 -1
  47. package/dist/tools/collection.js.map +0 -1
  48. package/dist/tools/community.js.map +0 -1
  49. package/dist/tools/filters.js.map +0 -1
  50. package/dist/tools/index.js.map +0 -1
  51. package/dist/tools/meta.js.map +0 -1
  52. package/dist/tools/pricing.js.map +0 -1
  53. package/dist/tools/types.js.map +0 -1
  54. package/dist/tools/writes.js.map +0 -1
  55. package/dist/types.js.map +0 -1
  56. package/dist/version.js.map +0 -1
package/README.md CHANGED
@@ -1,23 +1,29 @@
1
1
  # slab-mcp
2
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.
3
+ An [MCP](https://modelcontextprotocol.io) server for [slab](https://collection.slab.dev-jeb.com), the
4
+ hockey card collection site. It gives an AI agent (Claude Code, Claude Desktop, Cursor, or anything
5
+ else that speaks MCP) slab's catalog, prices and community, and the user's own collection:
7
6
 
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.
7
+ - *"What's a PSA 10 Bedard Young Guns worth, and what have they actually sold for this month?"*
8
+ - *"Show me every parallel of Celebrini's Young Guns and how rare each one is."*
9
+ - *"Is my Schaefer worth grading?"*
10
+ - *"What's my collection worth, and what's on my want list?"*
11
+ - *"What's hot in hockey cards right now?"*
10
12
 
11
- **Read-only by default.** Write tools are not registered at all unless you opt in.
13
+ Every card is catalogued down to the exact parallel (over 550,000 printings), and every price is a
14
+ median of real sales with the count it rests on, so the agent can say how sure a number is.
15
+
16
+ It runs on your machine, uses **your slab API key**, and talks to **the slab API and nothing else**.
17
+ It is **read-only by default**: the write tools are not registered unless you turn them on.
12
18
 
13
19
  ## Prerequisites
14
20
 
15
21
  - **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)
22
+ - A **slab API key**: sign in at [app.slab.dev-jeb.com](https://app.slab.dev-jeb.com) → Account → API Keys. Accounts are free.
17
23
 
18
24
  ## Install
19
25
 
20
- Once published, no install step is needed — your MCP client runs it with `npx`.
26
+ Your MCP client runs it with `npx`; there is nothing else to install.
21
27
 
22
28
  ### Claude Code
23
29
 
@@ -43,7 +49,7 @@ Add this to the client's MCP config (`claude_desktop_config.json` for Claude Des
43
49
  }
44
50
  ```
45
51
 
46
- Restart the client. You should see a `slab` server with 8 tools.
52
+ Restart the client. You should see a `slab` server with 16 tools (23 with writes on).
47
53
 
48
54
  ### From source
49
55
 
@@ -57,18 +63,55 @@ npm run build
57
63
  Then point your client at `node /absolute/path/to/slab-community/slab-mcp/dist/index.js` instead of
58
64
  the `npx` command.
59
65
 
66
+ ## Tools
67
+
68
+ **Read** (always available)
69
+
70
+ | Tool | What it answers |
71
+ |---|---|
72
+ | `search_cards` | Find cards: player, set, team, rookie, autograph, parallel, print run, honors. The entry point. |
73
+ | `get_card_pricing` | What one printing is worth at each grade, the sales behind it, its value series, which serials have surfaced. |
74
+ | `get_rainbow` | Every printing of a card (base and parallels) with print runs, pack odds and values. |
75
+ | `get_grading_desk` | What a card sells for raw and at each grade, by grading company. |
76
+ | `search_sets` | Find a product, with its release date, size, sales seen and hobby box price. |
77
+ | `get_set_detail` | A product's sealed prices (box, case, blaster…) and its most valuable cards. |
78
+ | `search_collection` | The user's copies, with cost basis, value and a summary. |
79
+ | `get_dashboard` | Collection totals, make-up, most valuable, rarest, hardest pulls, value over time. |
80
+ | `get_collection_sets` | The user's collection by set: copies, printings, value. |
81
+ | `get_targets` | The user's want list, with values and what they've found. |
82
+ | `search_chases` / `get_chase` | Checklists collectors follow (a player's rookies, a team, award winners), with the user's progress. |
83
+ | `get_community` | Card of the day, most wanted, community favorite, hottest players, most valuable, rarest owned, records. |
84
+ | `get_market_index` | How the hockey card market moved each month beyond what card age explains. |
85
+ | `get_vocab` | Every value the API accepts, live from the catalog. |
86
+ | `explain_metrics` | What a slab number means, in slab's own words. |
87
+
88
+ **Write** (only when `SLAB_MCP_WRITE=1`)
89
+
90
+ | Tool | What it does |
91
+ |---|---|
92
+ | `add_copy` | Record a card the user owns. |
93
+ | `update_copy` | Change a copy: grade, favorite, status, or record a sale. |
94
+ | `remove_copy` | Delete a copy record. Destructive, no undo. |
95
+ | `log_break` | Log a sealed product that was opened, so pulls get a real cost basis. |
96
+ | `log_lot` | Log a multi-card purchase, same idea. |
97
+ | `add_target` / `remove_target` | Add a card to the want list, or take one off. |
98
+
99
+ Three **resources** give the agent reference material without a tool call: `slab://vocab`,
100
+ `slab://glossary` and `slab://openapi` (the full API contract), all read live from the API.
101
+ Four **prompts** appear in your client's slash menu: `appraise-collection`, `research-player`,
102
+ `grading-decision` and `whats-hot`.
103
+
60
104
  ## Configuration
61
105
 
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.
106
+ Every setting is an environment variable in your MCP client's `env` block. There is no config file
107
+ and no way to pass a credential as a tool argument, so the model never sees your key.
65
108
 
66
109
  | Variable | Required | Default | Description |
67
110
  |---|---|---|---|
68
111
  | `SLAB_API_KEY` | one of these two | — | Your slab API key, literally. |
69
112
  | `SLAB_API_KEY_COMMAND` | one of these two | — | A command that *prints* the key. See [Handling the API key](#handling-the-api-key). |
70
- | `SLAB_API_URL` | No | `https://api.slab.dev-jeb.com` | Override for local development. |
71
- | `SLAB_COLLECTOR` | No | your account's default | Collector UUID to act as. |
113
+ | `SLAB_API_URL` | No | `https://api.slab.dev-jeb.com` | Override for local development. Must be https (http only for localhost). |
114
+ | `SLAB_COLLECTOR` | No | your account's default | Collector UUID to act as, for an account with several. |
72
115
  | `SLAB_MCP_WRITE` | No | `0` | Set to `1` to register the write tools. |
73
116
  | `SLAB_MCP_TIMEOUT_MS` | No | `30000` | Per-request HTTP timeout. |
74
117
 
@@ -110,7 +153,7 @@ has never heard of works too.
110
153
 
111
154
  Two more things worth doing, both of which slab already supports:
112
155
 
113
- - **Mint a dedicated key for the MCP** and name it (`slab` portal → Account → API Keys). Keys carry
156
+ - **Mint a dedicated key for the MCP** and name it (slab portal → Account → API Keys). Keys carry
114
157
  a label and `last_used_dt` and revoke individually, so an agent-held key can be killed without
115
158
  disturbing your CLI or scripts, and you can see when it was last used.
116
159
  - **Leave writes off** unless you need them. A read-only key-holder cannot damage your collection
@@ -130,79 +173,68 @@ back in the error so you can debug it.
130
173
  }
131
174
  ```
132
175
 
133
- With this off, the five write tools are never registered, so the agent cannot call them — that is a
134
- stronger guarantee than telling it not to. With it on, each write tool declares the MCP annotations
135
- (`readOnlyHint`, `destructiveHint`) that let your client prompt you before it runs. Whether your
136
- client actually prompts is up to your client; the annotations only make it possible.
176
+ With this off, the seven write tools are never registered, so the agent cannot call them: a stronger
177
+ guarantee than telling it not to. With it on, each write tool declares the MCP annotations
178
+ (`readOnlyHint`, `destructiveHint`) that let your client ask you before it runs. Whether your client
179
+ actually asks is up to your client.
137
180
 
138
- ## Tools
181
+ ## Only the slab API
139
182
 
140
- **Read** (always available)
183
+ slab-mcp is a client of the slab API and nothing more. Each of these is held by a test in
184
+ `tests/boundary.test.ts` or `tests/client.test.ts`, so a later change can't quietly undo it:
141
185
 
142
- | Tool | What it does |
143
- |---|---|
144
- | `search_cards` | Search the catalog. The entry point — most other tools take a UUID from here. |
145
- | `search_sets` | Find a product/release. |
146
- | `get_set_detail` | A set's sealed prices and its most valuable cards. |
147
- | `get_card_pricing` | Fair market value, the individual sales behind it, and the daily series. |
148
- | `search_collection` | Search your own copies, with a financial summary. |
149
- | `get_dashboard` | Collection totals, top cards, and portfolio history. |
150
- | `get_community` | Public leaderboards and activity. |
151
- | `get_vocab` | Every value the API accepts, live from the catalog. |
152
- | `explain_metrics` | What a slab number means, in slab's own words. |
186
+ - **One network door.** Only `src/client.ts` makes requests, and only to `SLAB_API_URL`. The source
187
+ names no other host.
188
+ - **The key stays in one header.** It goes in `x-api-key` on each request, over https, and is never
189
+ a tool argument, never in a tool result, and never in an error. Requests refuse redirects, so the
190
+ key is never replayed to another host.
191
+ - **A model can't steer a request.** Every id argument must be a UUID, and every id is encoded as a
192
+ single path segment, so `../../account/keys/…` passed as a copy id is refused, not a request to
193
+ another route.
194
+ - **No retried writes.** Reads ride out a brief outage (two retries, honouring `Retry-After`); a
195
+ write is sent once, because a create that timed out may have landed.
196
+ - **The only local command it runs** is your `SLAB_API_KEY_COMMAND`, once, to read the key.
153
197
 
154
- **Write** (only when `SLAB_MCP_WRITE=1`)
198
+ ## How the tools are designed
155
199
 
156
- | Tool | What it does |
157
- |---|---|
158
- | `add_copy` | Record a card you own. |
159
- | `update_copy` | Change a copy, including recording a sale. |
160
- | `remove_copy` | Delete a copy record. Destructive, no undo. |
161
- | `log_break` | Log a sealed product you opened, so pulls get a real cost basis. |
162
- | `log_lot` | Log a multi-card purchase, same idea. |
200
+ **Task-shaped, not endpoint-shaped.** The slab API has 84 routes; this server exposes 23 tools. Each
201
+ answers a question a person asks, folding several endpoints where that's the natural unit:
202
+ `get_card_pricing` is `/market` + `/comps` + `/price-history` + `/serials`, because "what's it worth"
203
+ is one question.
163
204
 
164
- ## Resources and prompts
205
+ **Results are formatted, not dumped.** A tool result is spent out of the agent's context window, so
206
+ results render one entity per line with a labelled id first (`card:`, `copy:`, `set:`, `chase:`,
207
+ `target:`): the id is what the agent carries to the next call, and a copy id fed to a card tool is a
208
+ 404. Every paged result says how many rows exist.
165
209
 
166
- Three **resources** let an agent pull reference material without spending a tool call:
167
- `slab://vocab` (every accepted value), `slab://glossary` (what each metric means), and
168
- `slab://openapi` (the full API contract). All three are served from the live API rather than
169
- copied into this repo, so they can't go stale.
210
+ **Nothing enumerable or explanatory is written down here.** `get_vocab` serves accepted values (the
211
+ catalog grows with every set) and `explain_metrics` serves what a number means. Responses that embed
212
+ their own glossary render it beside the numbers, so the agent uses slab's wording instead of
213
+ inventing its own.
170
214
 
171
- Three **prompts** show up in your client's slash menu as starting points:
172
- `appraise-collection`, `research-player`, and `grading-decision`.
215
+ Two rules from the slab data model are written into the tool descriptions, because getting them
216
+ wrong produces a confident false statement about someone's money:
173
217
 
174
- ## How the tools are designed
218
+ - **A price is an appraisal, not a ticker.** A fair market value is a median of the trailing 90 days
219
+ of sales, so the difference between two of them is how the *appraisal* drifted, not what the
220
+ market did. What happened in a window comes from counting the sales.
221
+ - **The collection's value series is as-of.** It steps up when the user buys a card, so the
222
+ difference between two points mixes purchases with price movement and is not a return.
223
+
224
+ ## Staying in step with the API
175
225
 
176
- Two decisions explain most of the code, and are worth knowing before you extend it.
177
-
178
- **Task-shaped, not endpoint-shaped.** The slab API has ~46 routes; this server exposes 13 tools.
179
- Mapping routes 1:1 would put 46 schemas into the agent's context on every single request and make
180
- tool selection worse, not better. Each tool here answers a question a person actually asks, folding
181
- several endpoints where that's the natural unit — `get_card_pricing` is `/market` + `/comps` +
182
- `/price-history`, because "what's it worth" is one question.
183
-
184
- **Results are formatted, not dumped.** A tool result is spent out of the agent's context window. A
185
- raw search page is tens of thousands of tokens of JSON, mostly nulls and repeated keys. Results here
186
- render one entity per line with the UUID first, and every paged result says how many rows exist so
187
- the agent knows whether it has seen everything.
188
-
189
- **Nothing enumerable or explanatory is written down here.** slab serves both, so this server asks:
190
- `get_vocab` for values (statuses, sort keys, and the live catalog dimensions that grow with every
191
- seeded set) and `explain_metrics` for what a number means. No tool description lists a brand, team,
192
- attribute, or finish, and none writes its own definition of `priced_coverage` — a copy in this repo
193
- would rot, and a hand-written gloss would drift from what the portal and CLI show the same user.
194
- Tools that report figures point the agent at `explain_metrics`, responses that embed their own
195
- glossary render it inline, and a test fails the build if a metric-bearing tool stops doing either.
196
-
197
- Two rules from the slab data model are written into the tool descriptions rather than left to the
198
- agent to figure out, because getting them wrong produces a confident false statement about someone's
199
- money:
200
-
201
- - **Prices are appraisals, not tickers.** A fair market value is a trimmed median of the trailing 90
202
- days, so differencing two snapshots measures how the *appraisal* drifted — not what the market did
203
- over that window. Real market movement comes from counting comps.
204
- - **The portfolio series is as-of.** It steps up when you buy a card, so differencing two points
205
- mixes purchases with price movement and is not a return.
226
+ The response types are not hand-written. `src/generated/api.ts` is generated from the API's own
227
+ OpenAPI spec (`api/openapi.json`), and every tool reads responses through those types, so a field the
228
+ API renames fails `npm run typecheck`. The tests' sample responses are typed the same way, and each
229
+ tool's test checks the value actually appears in what it renders.
230
+
231
+ ```bash
232
+ npm run api:sync # re-read the live spec, regenerate the types; then typecheck and test
233
+ npm run api:check # exit 1 if the live spec differs from the committed snapshot
234
+ ```
235
+
236
+ CI does this every Monday against the live API (`.github/workflows/slab-mcp.yml`); with a
237
+ `SLAB_API_KEY` repository secret it also runs the live smoke test.
206
238
 
207
239
  ## Extending it
208
240
 
@@ -213,55 +245,55 @@ src/
213
245
  tools/
214
246
  index.ts <- THE REGISTRY: read tools, write tools, registration loop
215
247
  types.ts <- the ToolModule contract + annotation presets
248
+ args.ts <- shared inputs: UUIDs, dates, the collector, grade keys
216
249
  filters.ts <- the shared card filter grammar, defined once
217
- catalog.ts collection.ts pricing.ts writes.ts meta.ts
250
+ lines.ts <- one entity on one line
251
+ catalog.ts pricing.ts collection.ts chases.ts community.ts meta.ts writes.ts
218
252
  resources/index.ts <- add a resource: one entry in RESOURCES
219
253
  prompts/index.ts <- add a prompt: one entry in PROMPTS
220
- client.ts <- HTTP, auth, timeouts, error shapes. Knows nothing about cards.
254
+ client.ts <- the one network door: paths, auth, timeouts, retries
255
+ types.ts <- wire types by name, aliases into generated/api.ts
221
256
  index.ts <- wiring only. Adding a tool never touches this file.
222
257
  ```
223
258
 
224
- To add a tool:
225
-
226
259
  ```ts
227
260
  export const getMyThing = defineTool({
228
261
  name: 'get_my_thing',
229
262
  title: 'Get my thing',
230
263
  description: 'When to call this, and what the numbers mean. Name the tool that produces any UUID this one takes.',
231
264
  inputSchema: z.object({
232
- thing_uuid: z.string().describe('Thing UUID, from search_things.'),
265
+ thing_uuid: uuid('Thing UUID, from search_things.'),
233
266
  }),
234
267
  annotations: READ_ONLY, // or CREATES / UPDATES / DELETES
235
268
  mutates: false, // true puts it behind SLAB_MCP_WRITE
236
269
  async handler(input, ctx) {
237
- const thing = await ctx.client.request<Thing>('GET', `/things/${input.thing_uuid}`);
270
+ const thing = await ctx.client.request<Thing>('GET', api`/things/${input.thing_uuid}`);
238
271
  return text(`...`);
239
272
  },
240
273
  });
241
274
  ```
242
275
 
243
- Then add it to the array in `tools/index.ts`. That's it — registration, argument validation, error
244
- handling, and the write gate are all handled by the loop.
245
-
246
- `mutates` and `annotations` are required, not optional, because a write tool that looks read-only
247
- gets no confirmation prompt from the host. `npm test` enforces that they agree, along with the
248
- things prose can't check for itself: unique snake_case names, a description substantial enough to
249
- route on, a `.describe()` on every input field, destructive tools marked destructive, and no tool
250
- description that hardcodes a live catalog vocabulary or calls appraisal drift a market move.
276
+ Then add it to the array in `tools/index.ts`, a typed sample response in `tests/render.test.ts`, and
277
+ a call in `scripts/smoke.mjs`. `npm test` enforces the rest: unique snake_case names, descriptions
278
+ substantial enough to route on, a `.describe()` on every input, `mutates` agreeing with
279
+ `readOnlyHint`, destructive tools marked destructive, UUID-only id arguments, `api\`…\`` for every
280
+ path, and no tool description that hardcodes a catalog vocabulary or calls appraisal drift a market
281
+ move.
251
282
 
252
283
  ## Development
253
284
 
254
285
  ```bash
255
286
  npm install
256
- npm run dev # run against the API without building
257
- npm test # offline: no network, no key, no server
258
- npm run typecheck
287
+ npm run dev # run against the API without building
288
+ npm test # offline: no network, no key, no server
289
+ npm run typecheck # sources and tests
259
290
  npm run build
291
+ SLAB_API_KEY=... npm run smoke # build, then call every read tool against the live API
260
292
  ```
261
293
 
262
- **Never write to stdout.** In a stdio MCP server, stdout is the protocol — one stray `console.log`
294
+ **Never write to stdout.** In a stdio MCP server, stdout is the protocol: one stray `console.log`
263
295
  corrupts the JSON-RPC stream and the client drops the connection with an error that points nowhere
264
- near the cause. Diagnostics go to stderr, which your client surfaces as the server's log.
296
+ near the cause. Diagnostics go to stderr, which your client shows as the server's log.
265
297
 
266
298
  To inspect the server by hand:
267
299
 
@@ -302,10 +334,11 @@ Two remaining one-time steps:
302
334
  After that, releasing is:
303
335
 
304
336
  ```bash
305
- # bump "version" in slab-mcp/package.json, then:
306
- git commit -am "slab-mcp 0.1.1"
307
- git tag slab-mcp-v0.1.1
308
- git push origin main slab-mcp-v0.1.1
337
+ # bump "version" in slab-mcp/package.json, run the live smoke test, then:
338
+ SLAB_API_KEY=... npm run smoke
339
+ git commit -am "slab-mcp 0.3.1"
340
+ git tag slab-mcp-v0.3.1
341
+ git push origin main slab-mcp-v0.3.1
309
342
  ```
310
343
 
311
344
  The tag is namespaced per tool, so each directory in this repo releases on its own schedule. The
@@ -314,11 +347,11 @@ workflow re-runs typecheck, tests, and build, and refuses to publish if the tag
314
347
 
315
348
  ## Limits and caveats
316
349
 
317
- - Read-only unless you opt in, and it acts for exactly one collector.
318
- - No caching. Every tool call is a live request; `slab://openapi` is large, so fetch it deliberately.
319
- - stdio transport only. It is meant to run on your machine next to your agent, not to be hosted.
320
- - Tool inputs cover the well-trodden subset of slab's filter grammar. The full contract is always
321
- `GET /openapi.json` — if this server and the spec disagree, the spec is right.
350
+ - Read-only unless you opt in, and it acts for one collector at a time.
351
+ - No caching: every tool call is a live request. `slab://openapi` is large; fetch it deliberately.
352
+ - stdio transport only. It runs on your machine next to your agent; it is not a hosted service.
353
+ - Tool inputs cover the well-trodden part of slab's filter grammar. The full contract is always
354
+ `GET /openapi.json`; if this server and the spec disagree, the spec is right.
322
355
 
323
356
  ## License
324
357
 
package/dist/client.d.ts CHANGED
@@ -1,28 +1,49 @@
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 type { Config } from './config.js';
18
+ /** A path on the slab API, built only by `api`. */
19
+ export type ApiPath = string & {
20
+ readonly __apiPath: unique symbol;
21
+ };
22
+ /** `api\`/cards/${uuid}/market\``: each interpolated value becomes one encoded path segment. */
23
+ export declare function api(strings: TemplateStringsArray, ...values: Array<string | number>): ApiPath;
16
24
  export interface RequestOptions {
17
25
  /** JSON request body. Undefined keys are stripped before sending. */
18
26
  body?: unknown;
19
27
  /** Query parameters. Undefined/null values are dropped. */
20
28
  query?: Record<string, string | number | boolean | undefined | null>;
29
+ /**
30
+ * A POST that only reads (every `/search` route) may retry like a GET. Never set this on a
31
+ * write: a retried create is a duplicate.
32
+ */
33
+ read?: boolean;
34
+ }
35
+ /** Seams for tests: the network and the clock. */
36
+ export interface ClientDeps {
37
+ fetch?: typeof fetch;
38
+ sleep?: (ms: number) => Promise<void>;
21
39
  }
22
40
  export declare class SlabClient {
23
41
  private readonly config;
24
- constructor(config: Config);
25
- request<T>(method: string, path: string, options?: RequestOptions): Promise<T>;
26
- /** Fetch a public document verbatim (used by the resource handlers). */
27
- raw(path: string): Promise<string>;
42
+ private readonly fetch;
43
+ private readonly sleep;
44
+ constructor(config: Config, deps?: ClientDeps);
45
+ request<T>(method: string, path: ApiPath, options?: RequestOptions): Promise<T>;
46
+ /** A document verbatim (the resources: /vocab, /glossary, /openapi.json). */
47
+ raw(path: ApiPath): Promise<string>;
48
+ private send;
28
49
  }
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
  }