@cyanheads/art-institute-chicago-mcp-server 0.1.1

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 (82) hide show
  1. package/AGENTS.md +534 -0
  2. package/CLAUDE.md +534 -0
  3. package/Dockerfile +177 -0
  4. package/LICENSE +201 -0
  5. package/README.md +304 -0
  6. package/changelog/0.1.x/0.1.0.md +9 -0
  7. package/changelog/0.1.x/0.1.1.md +20 -0
  8. package/changelog/template.md +151 -0
  9. package/dist/config/server-config.d.ts +15 -0
  10. package/dist/config/server-config.d.ts.map +1 -0
  11. package/dist/config/server-config.js +33 -0
  12. package/dist/config/server-config.js.map +1 -0
  13. package/dist/index.d.ts +7 -0
  14. package/dist/index.d.ts.map +1 -0
  15. package/dist/index.js +25 -0
  16. package/dist/index.js.map +1 -0
  17. package/dist/mcp-server/resources/definitions/artwork.resource.d.ts +38 -0
  18. package/dist/mcp-server/resources/definitions/artwork.resource.d.ts.map +1 -0
  19. package/dist/mcp-server/resources/definitions/artwork.resource.js +72 -0
  20. package/dist/mcp-server/resources/definitions/artwork.resource.js.map +1 -0
  21. package/dist/mcp-server/resources/definitions/index.d.ts +34 -0
  22. package/dist/mcp-server/resources/definitions/index.d.ts.map +1 -0
  23. package/dist/mcp-server/resources/definitions/index.js +7 -0
  24. package/dist/mcp-server/resources/definitions/index.js.map +1 -0
  25. package/dist/mcp-server/tools/artwork-output.d.ts +45 -0
  26. package/dist/mcp-server/tools/artwork-output.d.ts.map +1 -0
  27. package/dist/mcp-server/tools/artwork-output.js +133 -0
  28. package/dist/mcp-server/tools/artwork-output.js.map +1 -0
  29. package/dist/mcp-server/tools/definitions/get-artworks.tool.d.ts +111 -0
  30. package/dist/mcp-server/tools/definitions/get-artworks.tool.d.ts.map +1 -0
  31. package/dist/mcp-server/tools/definitions/get-artworks.tool.js +233 -0
  32. package/dist/mcp-server/tools/definitions/get-artworks.tool.js.map +1 -0
  33. package/dist/mcp-server/tools/definitions/index.d.ts +549 -0
  34. package/dist/mcp-server/tools/definitions/index.d.ts.map +1 -0
  35. package/dist/mcp-server/tools/definitions/index.js +19 -0
  36. package/dist/mcp-server/tools/definitions/index.js.map +1 -0
  37. package/dist/mcp-server/tools/definitions/lookup-vocabulary.tool.d.ts +78 -0
  38. package/dist/mcp-server/tools/definitions/lookup-vocabulary.tool.d.ts.map +1 -0
  39. package/dist/mcp-server/tools/definitions/lookup-vocabulary.tool.js +138 -0
  40. package/dist/mcp-server/tools/definitions/lookup-vocabulary.tool.js.map +1 -0
  41. package/dist/mcp-server/tools/definitions/search-artists.tool.d.ts +97 -0
  42. package/dist/mcp-server/tools/definitions/search-artists.tool.d.ts.map +1 -0
  43. package/dist/mcp-server/tools/definitions/search-artists.tool.js +305 -0
  44. package/dist/mcp-server/tools/definitions/search-artists.tool.js.map +1 -0
  45. package/dist/mcp-server/tools/definitions/search-artworks.tool.d.ts +154 -0
  46. package/dist/mcp-server/tools/definitions/search-artworks.tool.d.ts.map +1 -0
  47. package/dist/mcp-server/tools/definitions/search-artworks.tool.js +267 -0
  48. package/dist/mcp-server/tools/definitions/search-artworks.tool.js.map +1 -0
  49. package/dist/mcp-server/tools/definitions/search-audio-guide.tool.d.ts +61 -0
  50. package/dist/mcp-server/tools/definitions/search-audio-guide.tool.d.ts.map +1 -0
  51. package/dist/mcp-server/tools/definitions/search-audio-guide.tool.js +159 -0
  52. package/dist/mcp-server/tools/definitions/search-audio-guide.tool.js.map +1 -0
  53. package/dist/mcp-server/tools/definitions/search-exhibitions.tool.d.ts +103 -0
  54. package/dist/mcp-server/tools/definitions/search-exhibitions.tool.d.ts.map +1 -0
  55. package/dist/mcp-server/tools/definitions/search-exhibitions.tool.js +241 -0
  56. package/dist/mcp-server/tools/definitions/search-exhibitions.tool.js.map +1 -0
  57. package/dist/services/aic/aic-service.d.ts +182 -0
  58. package/dist/services/aic/aic-service.d.ts.map +1 -0
  59. package/dist/services/aic/aic-service.js +804 -0
  60. package/dist/services/aic/aic-service.js.map +1 -0
  61. package/dist/services/aic/aic-text.d.ts +161 -0
  62. package/dist/services/aic/aic-text.d.ts.map +1 -0
  63. package/dist/services/aic/aic-text.js +455 -0
  64. package/dist/services/aic/aic-text.js.map +1 -0
  65. package/dist/services/aic/artist-records.d.ts +25 -0
  66. package/dist/services/aic/artist-records.d.ts.map +1 -0
  67. package/dist/services/aic/artist-records.js +32 -0
  68. package/dist/services/aic/artist-records.js.map +1 -0
  69. package/dist/services/aic/artwork-records.d.ts +37 -0
  70. package/dist/services/aic/artwork-records.d.ts.map +1 -0
  71. package/dist/services/aic/artwork-records.js +109 -0
  72. package/dist/services/aic/artwork-records.js.map +1 -0
  73. package/dist/services/aic/response-cache.d.ts +24 -0
  74. package/dist/services/aic/response-cache.d.ts.map +1 -0
  75. package/dist/services/aic/response-cache.js +48 -0
  76. package/dist/services/aic/response-cache.js.map +1 -0
  77. package/dist/services/aic/types.d.ts +260 -0
  78. package/dist/services/aic/types.d.ts.map +1 -0
  79. package/dist/services/aic/types.js +8 -0
  80. package/dist/services/aic/types.js.map +1 -0
  81. package/package.json +112 -0
  82. package/server.json +125 -0
package/AGENTS.md ADDED
@@ -0,0 +1,534 @@
1
+ # Developer Protocol
2
+
3
+ **Server:** art-institute-chicago-mcp-server
4
+ **Version:** 0.1.1
5
+ **Framework:** [@cyanheads/mcp-ts-core](https://www.npmjs.com/package/@cyanheads/mcp-ts-core) `^0.13.10`
6
+ **Engines:** Bun ≥1.4.0, Node ≥24.0.0
7
+ **MCP SDK:** `@modelcontextprotocol/server` ^2.1.0
8
+ **Zod:** ^4.6.5
9
+
10
+ > **Read the framework docs first:** `node_modules/@cyanheads/mcp-ts-core/CLAUDE.md` contains the full API reference — builders, Context, error codes, exports, patterns. This file covers server-specific conventions only.
11
+
12
+ ---
13
+
14
+ ## Domain
15
+
16
+ The server wraps the Art Institute of Chicago public API (`https://api.artic.edu/api/v1`): keyless, read-only, Elasticsearch-backed. `docs/design.md` is the spec — tool contracts, the request boundary, resilience settings, numbered design decisions, and the verified API reference. Read the relevant section before changing a definition or the service.
17
+
18
+ - **One service, one host.** `AicService` (`src/services/aic/aic-service.ts`) makes every upstream call: a process-wide pacer (`AIC_REQUESTS_PER_MINUTE`, default 50, under the published 60/min anonymous limit), `withRetry` inside a 20 s deadline per request, an in-process LRU cache keyed by request URL, a 5 MiB body ceiling, and the `AIC-User-Agent` header built from `AIC_CONTACT`. Image URLs are constructed in `aic-text.ts`, never fetched.
19
+ - **Request boundary.** Plain `fetch`, not `fetchWithTimeout`: the API reports paging errors as 403 JSON, search-backend rejections as 400 text, and firewall blocks as a non-JSON 403, and each maps to its own reason (`page_beyond_window`, `upstream_rejected_query`, `request_blocked`). Only a 429 is `rate_limited`.
20
+ - **Search window.** Anonymous callers reach only `offset + limit ≤ 1000`. Every search tool keeps `page × limit` inside it and names the window in its notice.
21
+ - **Licensing is per surface.** Artwork metadata, agents, exhibitions, vocabulary terms, and `/sounds` assets are CC0; artwork `description` is CC BY 4.0 (`description_attribution`); images are reusable only when `is_public_domain`; audio-guide content is for noncommercial educational and personal use (`license_text` plus `source_citation`). An output that returns licensed text carries its terms.
22
+ - **Upstream text is data.** HTML becomes plain text once, at the service boundary, where upstream URLs also pass `httpUrl()`, the IIIF base `iiifBaseUrl()`, and image ids `iiifImageId()`, so a value that fails is absent. In `format()`, free text goes through `quoteBlock()`, inline slots through `inlineSafe()`, and URLs through `printableUrl()`; `structuredContent` keeps every string as received.
23
+ - **Secondary calls degrade.** When the second request fails in `artic_get_artworks` (related media) or `artic_search_artists` (artwork counts), the primary records return with a notice. Cancellation still rethrows.
24
+
25
+ ---
26
+
27
+ ## What's Next?
28
+
29
+ When the user asks what's next or needs direction, suggest options based on the current project state. Common next steps:
30
+
31
+ 1. **Re-run the `setup` skill** — ensures CLAUDE.md, skills, structure, and metadata are populated and up to date with the current codebase
32
+ 2. **Run the `design-mcp-server` skill** — if the tool/resource surface hasn't been mapped yet, work through domain design
33
+ 3. **Add tools/resources/prompts** — scaffold new definitions using the `add-tool`, `add-app-tool`, `add-resource`, `add-prompt` skills
34
+ 4. **Add services** — scaffold domain service integrations using the `add-service` skill
35
+ 5. **Add tests** — scaffold tests for existing definitions using the `add-test` skill
36
+ 6. **Field-test definitions** — exercise tools/resources/prompts with real inputs using the `field-test` skill, get a report of issues and pain points
37
+ 7. **Run `devcheck`** — lint, format, typecheck, and security audit
38
+ 8. **Run the `security-pass` skill** — audit handlers for MCP-specific security gaps: output injection, scope blast radius, input sinks, tenant isolation
39
+ 9. **Run the `polish-docs-meta` skill** — finalize README, CHANGELOG, metadata, and agent protocol for shipping
40
+ 10. **Run the `maintenance` skill** — investigate changelogs, adopt upstream changes, and sync skills after `bun update --latest`
41
+
42
+ Tailor suggestions to what's actually missing or stale — don't recite the full list every time.
43
+
44
+ ---
45
+
46
+ ## Core Rules
47
+
48
+ - **Logic throws, framework catches.** Tool/resource handlers are pure — throw on failure, no `try/catch`. Plain `Error` is fine; the framework catches, classifies, and formats. Use error factories (`notFound()`, `validationError()`, etc.) when the error code matters.
49
+ - **Use `ctx.log`** for request-scoped logging. No `console` calls.
50
+ - **Use `ctx.state`** for tenant-scoped storage. Never access persistence directly.
51
+ - **Need input the caller didn't supply?** `return ctx.requestInput(...)` and read `ctx.inputs` when the handler is re-entered. Never `await` for user input mid-handler.
52
+ - **Secrets in env vars only** — never hardcoded.
53
+ - **Cut noise.** Add only what earns its place: no speculative generality, no guards for states the framework already prevents (Zod-validated params, classified errors), no abstraction until a third caller proves it, no option nothing sets.
54
+ - **Close the loop on issues.** When implementing work tracked by a GitHub issue, comment on the issue with what landed and close it. Do both — a comment without a close leaves stale issues open; a close without a comment leaves no record of what shipped. The comment is for future readers — state the concrete changes, not the conversation that produced them.
55
+
56
+ ---
57
+
58
+ ## Patterns
59
+
60
+ ### Tool
61
+
62
+ Abridged from `src/mcp-server/tools/definitions/lookup-vocabulary.tool.ts`:
63
+
64
+ ```ts
65
+ import { tool, z } from '@cyanheads/mcp-ts-core';
66
+ import { JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
67
+ import { getAicService } from '@/services/aic/aic-service.js';
68
+ import {
69
+ blankAsUnset,
70
+ containsPattern,
71
+ inlineSafe,
72
+ VOCABULARY_FIELDS,
73
+ VOCABULARY_FILTERS,
74
+ } from '@/services/aic/aic-text.js';
75
+
76
+ export const lookupVocabulary = tool('artic_lookup_vocabulary', {
77
+ title: 'Look up collection vocabulary',
78
+ description: 'List the values of an Art Institute of Chicago collection vocabulary with how many artworks carry each, …',
79
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: true },
80
+ input: z.object({
81
+ vocabulary: z.enum(VOCABULARIES).describe('Vocabulary to list. …'),
82
+ // Every optional input is wrapped: a form client's "" becomes unset, or the default.
83
+ contains: blankAsUnset(z.string().trim().max(60).optional()).describe('Case-insensitive substring …'),
84
+ public_domain_only: blankAsUnset(z.boolean().default(false)).describe('Count only public-domain artworks.'),
85
+ limit: blankAsUnset(z.number().int().min(1).max(100).default(25)).describe('Values to return, most common first (1-100).'),
86
+ }),
87
+ output: z.object({
88
+ vocabulary: z.enum(VOCABULARIES).describe('The vocabulary listed.'),
89
+ filter_param: z.enum(VOCABULARY_FILTERS).optional().describe('The artic_search_artworks parameter …'),
90
+ values: z.array(/* { value, artwork_count } */).describe('Values, most common first.'),
91
+ }),
92
+ enrichment: {
93
+ truncated: z.boolean().describe('True when more values exist beyond the limit.'),
94
+ shown: z.number().describe('Values returned.'),
95
+ cap: z.number().describe('The limit applied.'),
96
+ notice: z.string().optional().describe('Guidance when no value matched or the list was capped.'),
97
+ },
98
+ errors: [
99
+ // rate_limited and upstream_rejected_query are declared inline the same way
100
+ {
101
+ reason: 'request_blocked',
102
+ code: JsonRpcErrorCode.Forbidden,
103
+ when: "The Art Institute API's firewall blocked the request, as it does for markup or script-like text and for bursts of traffic.",
104
+ retryable: false,
105
+ recovery: 'Remove markup or script-like text, such as HTML tags, from contains, then call artic_lookup_vocabulary again; …',
106
+ thrownBy: 'service',
107
+ },
108
+ ],
109
+
110
+ async handler(input, ctx) {
111
+ // Required enrichment fields are written first, before any branch or upstream call.
112
+ ctx.enrich({ truncated: false, shown: 0, cap: input.limit });
113
+ const result = await getAicService().aggregate(
114
+ VOCABULARY_FIELDS[input.vocabulary],
115
+ {
116
+ size: input.limit,
117
+ include: input.contains ? containsPattern(input.contains) : undefined,
118
+ public_domain_only: input.public_domain_only,
119
+ },
120
+ ctx,
121
+ );
122
+ const values = result.buckets.map((b) => ({ value: b.key, artwork_count: b.doc_count }));
123
+ ctx.enrich({ shown: values.length });
124
+ if (result.sum_other_doc_count > 0) {
125
+ ctx.enrich.truncated({ shown: values.length, cap: input.limit, guidance: 'More values exist: raise limit or narrow with contains.' });
126
+ }
127
+ // … zero-value notice
128
+ return {
129
+ vocabulary: input.vocabulary,
130
+ ...(isFilterParam(input.vocabulary) ? { filter_param: input.vocabulary } : {}),
131
+ values,
132
+ };
133
+ },
134
+
135
+ // format() is the content[] twin of structuredContent: every output field appears,
136
+ // and upstream values pass through inlineSafe() here, never in structuredContent.
137
+ format: (result) => [{
138
+ type: 'text',
139
+ text: [
140
+ `# ${result.vocabulary} values (${result.values.length})`,
141
+ // … filter_param line
142
+ ...result.values.map((v) => `- ${inlineSafe(v.value)} (${v.artwork_count} artworks)`),
143
+ ].join('\n'),
144
+ }],
145
+ });
146
+ ```
147
+
148
+ The four search tools add the paging enrichment (`totalCount`, `truncated`, `shown`, `cap`, `notice`). Each handler writes it first (`ctx.enrich.total(0)`, then `ctx.enrich({ truncated: false, shown: 0, cap })`), pages with `pageInfo()` against the 1,000-match `SEARCH_WINDOW`, and composes one notice string that it writes once. `docs/design.md` § Shared conventions gives the order and the notice wording.
149
+
150
+ ### Resource
151
+
152
+ Abridged from `src/mcp-server/resources/definitions/artwork.resource.ts`. The resource builds its record through the same `loadArtworkRecords()` path as `artic_get_artworks`, and embeds the license text, attribution, and notice in the payload, since resources carry no enrichment block:
153
+
154
+ ```ts
155
+ import { resource, z } from '@cyanheads/mcp-ts-core';
156
+ import { JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
157
+ import { DEFAULT_SECTIONS, jsonBytes, loadArtworkRecords } from '@/services/aic/artwork-records.js';
158
+
159
+ export const artworkResource = resource('artic://artworks/{id}', {
160
+ name: 'artic-artwork',
161
+ title: 'Artwork record',
162
+ description: 'Read one Art Institute of Chicago artwork record by id as JSON: …',
163
+ mimeType: 'application/json',
164
+ params: z.object({
165
+ id: z.string().regex(/^\d+$/).describe('Artwork id (digits), from artic_search_artworks.'),
166
+ }),
167
+ cacheHint: { ttlMs: 21_600_000, cacheScope: 'public' },
168
+ errors: [
169
+ {
170
+ reason: 'artwork_not_found',
171
+ code: JsonRpcErrorCode.NotFound,
172
+ when: 'No artwork has this id.',
173
+ recovery: 'Find artwork ids with artic_search_artworks, then read artic://artworks/<id> again.',
174
+ },
175
+ // … rate_limited, request_blocked, upstream_rejected_query (thrownBy: 'service')
176
+ ],
177
+
178
+ async handler(params, ctx) {
179
+ const id = Number(params.id);
180
+ if (!Number.isSafeInteger(id)) {
181
+ throw ctx.fail('artwork_not_found', `No artwork exists for id ${params.id}.`);
182
+ }
183
+ const { artworks, license_text, description_attribution, notices } = await loadArtworkRecords(
184
+ { ids: [id], sections: DEFAULT_SECTIONS, include_related_media: true, wireBytes: jsonBytes },
185
+ ctx,
186
+ );
187
+ const [artwork] = artworks;
188
+ if (!artwork) throw ctx.fail('artwork_not_found', `No artwork exists for id ${params.id}.`);
189
+ return {
190
+ artwork,
191
+ license_text,
192
+ ...(description_attribution ? { description_attribution } : {}),
193
+ ...(notices.length > 0 ? { notice: notices.join(' ') } : {}),
194
+ };
195
+ },
196
+ });
197
+ ```
198
+
199
+ ### Prompt
200
+
201
+ None. The cross-tool workflow lives in the `createApp()` `instructions`.
202
+
203
+ ### Server config
204
+
205
+ `src/config/server-config.ts` (descriptions abridged):
206
+
207
+ ```ts
208
+ import { z } from '@cyanheads/mcp-ts-core';
209
+ import { parseEnvConfig } from '@cyanheads/mcp-ts-core/config';
210
+
211
+ const ServerConfigSchema = z.object({
212
+ contact: z
213
+ .string()
214
+ .trim()
215
+ .max(200)
216
+ .regex(/^[\x20-\x7E]*$/, 'Use printable ASCII only …') // a header value: anything else fails at startup
217
+ .default('https://github.com/cyanheads/art-institute-chicago-mcp-server')
218
+ .describe('Contact the museum can reach (an email or URL, printable ASCII), sent in the AIC-User-Agent header …'),
219
+ requestsPerMinute: z.coerce.number().int().min(1).max(600).default(50).describe('Outbound request budget per minute …'),
220
+ });
221
+
222
+ export type ServerConfig = z.infer<typeof ServerConfigSchema>;
223
+
224
+ let _config: ServerConfig | undefined;
225
+ export function getServerConfig(): ServerConfig {
226
+ _config ??= parseEnvConfig(ServerConfigSchema, {
227
+ contact: 'AIC_CONTACT',
228
+ requestsPerMinute: 'AIC_REQUESTS_PER_MINUTE',
229
+ });
230
+ return _config;
231
+ }
232
+ ```
233
+
234
+ `parseEnvConfig` maps Zod schema paths → env var names so errors name the variable (`AIC_REQUESTS_PER_MINUTE`) not the path (`requestsPerMinute`), and reads an empty value as unset, so a blank from a bundle install falls through to the default. Throws `ConfigurationError`, which the framework prints as a clean startup banner.
235
+
236
+ For env booleans use `z.stringbool()`, never `z.coerce.boolean()` — `Boolean("false")` is `true`, so a coerced flag can't be disabled through the environment. `z.stringbool()` parses `true/false/1/0/yes/no/on/off` and rejects anything else, so `=false` actually disables.
237
+
238
+ A new variable lands in `.env.example`, both `server.json` packages, `manifest.json` (`user_config` plus `mcp_config.env`), both plugin manifests, and the README Configuration table together.
239
+
240
+ ### Server identity, instructions, and lifecycle
241
+
242
+ `src/index.ts` (instructions abridged):
243
+
244
+ ```ts
245
+ await createApp({
246
+ name: 'art-institute-chicago-mcp-server',
247
+ title: 'art-institute-chicago-mcp-server',
248
+ tools: allToolDefinitions,
249
+ resources: allResourceDefinitions,
250
+ instructions: 'Art Institute of Chicago collection data: about 133,000 artworks, artists, exhibitions, and audio-guide stops. …',
251
+ setup(core) {
252
+ const { contact, requestsPerMinute } = getServerConfig();
253
+ initAicService({ contact, requestsPerMinute, version: core.config.mcpServerVersion });
254
+ },
255
+ teardown() {
256
+ disposeAicService();
257
+ },
258
+ });
259
+ ```
260
+
261
+ Identity is `name` + `title`, both the unscoped package name (`lint:packaging` enforces the match); `description` comes from `package.json`. `instructions` (under the 2,048-character limit) carries the cross-tool workflow and the licensing terms, so update it with the tool names whenever the surface changes. `teardown()` disposes the service's pacer. No `sessionMode` is set: no tool calls `ctx.requestInput`, so the default posture applies, and `.env.example` and the Dockerfile set `MCP_SESSION_MODE=stateless`.
262
+
263
+ ---
264
+
265
+ ## Context
266
+
267
+ Handlers receive a unified `ctx` object. The properties this server uses:
268
+
269
+ | Property | Description |
270
+ |:---------|:------------|
271
+ | `ctx.log` | Request-scoped logger — `.debug()`, `.info()`, `.notice()`, `.warning()`, `.error()`. Auto-correlates requestId, traceId, tenantId. Dual-sink: Pino **and** `notifications/message` to the client, so treat it as client-visible. A degraded secondary call logs at `warning`. |
272
+ | `ctx.enrich` | Success-path agent context — `ctx.enrich(...)` or `.notice()` / `.total()` / `.truncated()`. Every tool declares an `enrichment` block: the search tools carry `totalCount`, `truncated`, `shown`, `cap`, and `notice`; `artic_lookup_vocabulary` drops `totalCount`; `artic_get_artworks` carries `notice` only. Reaches `structuredContent` and `content[]`. |
273
+ | `ctx.fail` | Throws a declared error-contract reason, typed against the definition's `errors[]` (see Errors). |
274
+ | `ctx.signal` | `AbortSignal` for cancellation. The service hands it to `withRetry`, and a degraded secondary call rethrows when it is aborted. |
275
+
276
+ Unused here: `ctx.state` (the response cache is in-process and shared across tenants, since the data is public), `ctx.requestInput` / `ctx.inputs`, and `ctx.content`. See the framework CLAUDE.md for the full `ctx` surface.
277
+
278
+ ---
279
+
280
+ ## Errors
281
+
282
+ Handlers throw — the framework catches, classifies, and formats.
283
+
284
+ **Recommended: typed error contract.** Declare `errors: [{ reason, code, when, recovery, retryable?, severity?, thrownBy? }]` on `tool()` / `resource()` to receive `ctx.fail(reason, …)` typed against the reason union. TypeScript catches typos at compile time, `data.reason` is auto-populated for observability, linter enforces conformance against the handler body. `recovery` is required (≥ 5 words, lint-validated) — the single source of truth for the agent's next move. The framework puts it on the wire whenever a failure carrying that `reason` arrives without a hint — a bare `ctx.fail('reason')` or a service throw with `data: { reason }` — as `data.recovery.hint`, mirrored into `content[]` text unless the message already contains it verbatim; override with an explicit `{ recovery: { hint: '...' } }` when dynamic runtime context matters. Every error envelope also carries `data.requestId`, the id the server's log records for that call carry, and `content[]` closes with `(reason … · request <id>)`. Mark an entry the service layer throws with `thrownBy: 'service'` so `error-contract-unthrown` skips it — lint-only metadata, nothing at runtime reads it. Baseline codes (`InternalError`, `ServiceUnavailable`, `Timeout`, `ValidationError`, `SerializationError`, `RequestCancelled`) bubble freely and don't need declaring.
285
+
286
+ ```ts
287
+ import { JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
288
+
289
+ errors: [
290
+ { reason: 'no_match', code: JsonRpcErrorCode.NotFound,
291
+ when: 'No item matched the query',
292
+ recovery: 'Broaden the query or check the spelling and try again.' },
293
+ ],
294
+ async handler(input, ctx) {
295
+ const item = await db.find(input.id);
296
+ if (!item) throw ctx.fail('no_match', `No item ${input.id}`);
297
+ return item;
298
+ }
299
+ ```
300
+
301
+ **Declare contracts inline on each tool.** The contract is part of the tool's public surface — one file should give the full picture. Don't extract a shared `errors[]` constant; per-tool repetition is the intended cost of locality.
302
+
303
+ **Fallback (no contract entry fits):** throw via factories or plain `Error`.
304
+
305
+ ```ts
306
+ // Error factories — explicit code
307
+ import { notFound, serviceUnavailable } from '@cyanheads/mcp-ts-core/errors';
308
+ throw notFound('Item not found', { itemId });
309
+ throw serviceUnavailable('API unavailable', { url }, { cause: err });
310
+
311
+ // Plain Error — framework auto-classifies from message patterns
312
+ throw new Error('Item not found'); // → NotFound
313
+ throw new Error('Invalid query format'); // → ValidationError
314
+
315
+ // McpError — when no factory exists for the code
316
+ import { McpError, JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
317
+ throw new McpError(JsonRpcErrorCode.InitializationFailed, 'Connection failed', { pool: 'primary' });
318
+ ```
319
+
320
+ See framework CLAUDE.md and the `api-errors` skill for the full auto-classification table, all available factories, and the contract reference.
321
+
322
+ **This server's contracts.** Every tool and the resource declare `rate_limited` (`RateLimited`, retryable), `request_blocked` (`Forbidden`), and `upstream_rejected_query` (`InternalError`) inline with `thrownBy: 'service'`; `code` and `when` match across definitions, and each `recovery` names that tool's own levers. Caller-input reasons (`page_beyond_window`, `invalid_year_range`, `invalid_date_range`, `query_or_ids_required`, `query_and_ids_conflict`) are `ValidationError` with `severity: 'notice'`. Upstream 5xx, timeouts, and unreadable bodies bubble as baseline `ServiceUnavailable` / `Timeout`. `docs/design.md` § Request boundary maps each upstream response to its reason.
323
+
324
+ ---
325
+
326
+ ## Structure
327
+
328
+ ```text
329
+ src/
330
+ index.ts # createApp(): identity, instructions, service setup/teardown
331
+ config/
332
+ server-config.ts # AIC_CONTACT, AIC_REQUESTS_PER_MINUTE (Zod schema)
333
+ services/
334
+ aic/
335
+ aic-service.ts # AicService: request boundary, pacer, retry, cache (init/accessor pattern)
336
+ aic-text.ts # Pure helpers: HTML to text, inlineSafe, URL builders, input preprocessors, paging
337
+ artwork-records.ts # artic_get_artworks records: response budget, related media
338
+ artist-records.ts # Artwork counts and sample works for artic_search_artists
339
+ response-cache.ts # LRU bounded by entries and bytes
340
+ types.ts # Domain types
341
+ mcp-server/
342
+ tools/
343
+ artwork-output.ts # Artwork output schema and markdown shared by the artwork tools
344
+ definitions/
345
+ index.ts # allToolDefinitions barrel
346
+ search-artworks.tool.ts # artic_search_artworks
347
+ get-artworks.tool.ts # artic_get_artworks
348
+ search-artists.tool.ts # artic_search_artists
349
+ search-exhibitions.tool.ts # artic_search_exhibitions
350
+ search-audio-guide.tool.ts # artic_search_audio_guide
351
+ lookup-vocabulary.tool.ts # artic_lookup_vocabulary
352
+ resources/definitions/
353
+ index.ts # allResourceDefinitions barrel
354
+ artwork.resource.ts # artic://artworks/{id}
355
+ tests/
356
+ fixtures/ # Upstream payloads, service and tool kits
357
+ config/ services/ tools/ resources/ # Tests mirroring src/
358
+ ```
359
+
360
+ ---
361
+
362
+ ## Naming
363
+
364
+ | What | Convention | Example |
365
+ |:-----|:-----------|:--------|
366
+ | Files | kebab-case with suffix | `search-artworks.tool.ts` |
367
+ | Tool names | snake_case, `artic_` prefix | `artic_search_artworks` |
368
+ | Resource URIs | `artic://` scheme | `artic://artworks/{id}` |
369
+ | Directories | kebab-case | `src/services/aic/` |
370
+ | Descriptions | Single string or template literal, no `+` concatenation | `'Search items by query and filter.'` |
371
+
372
+ ---
373
+
374
+ ## Skills
375
+
376
+ Skills are modular instructions in `framework-skills/` at the project root. Read them directly when a task matches — e.g., `framework-skills/add-tool/SKILL.md` when adding a tool. `bun run list-skills` prints the full registry. The directory is deliberately not `skills/`: Claude Code and Codex auto-load a plugin's root `skills/`, so a server that ships `.claude-plugin/` or `.codex-plugin/` would hand these development skills to every agent that installs it. Keep `skills/` free for skills meant for those agents.
377
+
378
+ **Agent skill directory:** Copy skills into the directory your agent discovers (Claude Code: `.claude/skills/`, others: equivalent). Skills then load as context without referencing `framework-skills/` paths. After framework updates, run the `maintenance` skill — Phase B re-syncs the agent directory.
379
+
380
+ Available skills:
381
+
382
+ | Skill | Purpose |
383
+ |:------|:--------|
384
+ | `setup` | Post-init project orientation |
385
+ | `design-mcp-server` | Design tool surface, resources, and services for a new server |
386
+ | `add-tool` | Scaffold a new tool definition |
387
+ | `add-app-tool` | Scaffold an MCP App tool + paired UI resource |
388
+ | `add-resource` | Scaffold a new resource definition |
389
+ | `add-prompt` | Scaffold a new prompt definition |
390
+ | `add-service` | Scaffold a new service integration |
391
+ | `add-test` | Scaffold test file for a tool, resource, or service |
392
+ | `field-test` | Exercise tools/resources/prompts with real inputs, verify behavior, report issues |
393
+ | `tool-defs-analysis` | Read-only audit of MCP definition language across the surface — voice, leaks, defaults, recovery hints, output descriptions |
394
+ | `security-pass` | Audit server for MCP-flavored security gaps: output injection, scope blast radius, input sinks, tenant isolation |
395
+ | `code-simplifier` | Post-session cleanup against `git diff` — modernize syntax, consolidate duplication, align with the codebase |
396
+ | `polish-docs-meta` | Finalize docs, README, metadata, and agent protocol for shipping |
397
+ | `git-wrapup` | Land working-tree changes as a commit stack — version bump, changelog, verify, commit by concern, release commit on top. No tag, no push to main; opens the release PR when the project declares release PR mode |
398
+ | `release-pr-review` | Review pass on an open release PR — simplifier + correctness review, fixes as ordinary commits on top of the stack, PR body kept in sync. Release PR mode only |
399
+ | `release-and-publish` | Fast-forward merge (release PR mode) + tag + push + npm + MCP Registry + GH Release + Docker. Picks up from `git-wrapup` |
400
+ | `maintenance` | Investigate changelogs, adopt upstream changes, sync skills to agent dirs |
401
+ | `orchestrations` | Chain task skills into a gated multi-phase pipeline — build-out, QA-fix, update-ship — when you can spawn sub-agents |
402
+ | `report-issue-framework` | File a bug or feature request against `@cyanheads/mcp-ts-core` via `gh` CLI |
403
+ | `report-issue-local` | File a bug or feature request against this server's own repo via `gh` CLI |
404
+ | `techniques` | Catalog of response/data-shaping techniques — overflow handling, payload shaping, retrieval patterns |
405
+ | `api-auth` | Auth modes, scopes, JWT/OAuth |
406
+ | `api-canvas` | DataCanvas: register tabular data, run SQL, export, plus the `spillover()` helper for big result sets — Tier 3 opt-in |
407
+ | `api-config` | AppConfig, parseConfig, env vars |
408
+ | `api-context` | Context interface, RequestContext, logger, state, multi-round-trip input |
409
+ | `api-errors` | McpError, JsonRpcErrorCode, error patterns |
410
+ | `api-linter` | Definition linter rule catalog — invoked by `bun run lint:mcp` and `devcheck` |
411
+ | `api-mirror` | MirrorService: persistent self-refreshing local mirror (embedded SQLite + FTS5) of a bulk upstream dataset — Tier 3 opt-in |
412
+ | `api-services` | LLM, Speech, Graph services |
413
+ | `api-testing` | createMockContext, test patterns |
414
+ | `api-utils` | Formatting, parsing, security, pagination, scheduling, telemetry helpers |
415
+ | `api-telemetry` | OTel catalog: spans, metrics, completion logs, env config, cardinality rules |
416
+ | `api-workers` | Cloudflare Workers runtime |
417
+
418
+ **Chaining skills into pipelines.** When the user wants a multi-phase effort — build this server out, QA-and-fix the surface, update-and-ship — *and you can spawn sub-agents*, `framework-skills/orchestrations/SKILL.md` sequences the task skills above into a gated pipeline with verification at each step. Read it to drive the run. Optional: skip it if you can't orchestrate sub-agents, and ignore it entirely if you were *spawned* as one — you've already been scoped to a single phase.
419
+
420
+ When you complete a skill's checklist, check the boxes and add a completion timestamp at the end (e.g., `Completed: 2026-03-11`).
421
+
422
+ ---
423
+
424
+ ## Commands
425
+
426
+ **Runtime:** Scripts use Bun's native TypeScript execution — `bun run <cmd>` is the standard invocation. `npm run <cmd>` also works (npm delegates to bun).
427
+
428
+ | Command | Purpose |
429
+ |:--------|:--------|
430
+ | `bun run build` | Compile TypeScript |
431
+ | `bun run rebuild` | Clean + build |
432
+ | `bun run clean` | Remove build artifacts |
433
+ | `bun run devcheck` | Lint + format + typecheck + security + changelog sync |
434
+ | `bun run audit:fix` | `bun audit fix` — upgrade vulnerable packages to the lowest safe version within existing ranges (`--dry-run` previews, `--latest` rewrites ranges). First response when `devcheck` flags a transitive advisory; then `bun update <name>`, then `bun dedupe` |
435
+ | `bun run audit:refresh` | Delete `bun.lock` and reinstall. Last resort after `audit:fix`, `bun update <name>`, and `bun dedupe` — re-resolves every ranged dep (the framework pin included) and rewrites the lockfile as `lockfileVersion: 2` |
436
+ | `bun run lint:mcp` | Run the MCP definition linter standalone (rule catalog: `api-linter` skill) |
437
+ | `bun run lint:packaging` | Packaging surface checks — `server.json`/`manifest.json` env-var parity (run by devcheck) |
438
+ | `bun run list-skills` | Print the skill registry |
439
+ | `bun run tree` | Generate directory structure doc |
440
+ | `bun run format` | Auto-fix formatting (safe fixes only) |
441
+ | `bun run format:unsafe` | Also apply Biome's unsafe autofixes — review the diff; they can change behavior |
442
+ | `bun run test` | Run tests (Vitest — use `bun run test`, not `bun test`) |
443
+ | `bun run test:coverage` | Run tests with coverage |
444
+ | `bun run start` | Run the built server (`node dist/index.js`, transport from env) |
445
+ | `bun run start:stdio` | Production mode (stdio) |
446
+ | `bun run start:http` | Production mode (HTTP) |
447
+ | `bun run changelog:build` | Regenerate `CHANGELOG.md` from `changelog/*.md` |
448
+ | `bun run changelog:check` | Verify `CHANGELOG.md` is in sync (used by devcheck) |
449
+ | `bun run bundle` | Build, pack, and clean a `.mcpb` for one-click Claude Desktop install |
450
+ | `bun run release:github` | Create the GitHub Release from the pushed tag (release step) |
451
+ | `bun run publish-mcp` | Publish `server.json` to the MCP Registry (release step) |
452
+
453
+ **CI is one file.** `.github/workflows/codeql.yml` (scaffolded) is the only GitHub Actions workflow: CodeQL is GitHub-owned end to end, and the file runs only while the repo's CodeQL *default setup* is turned off. Verification — `devcheck`, tests, the release gates — runs locally; don't add a workflow that re-runs it.
454
+
455
+ ---
456
+
457
+ ## Bundling
458
+
459
+ `npm run bundle` produces a `.mcpb` extension bundle for one-click install in Claude Desktop. The pack step is followed by `scripts/clean-mcpb.ts`, which prunes dev dependencies (`mcpb clean`) and strips two classes of `node_modules/**` content that root-anchored `.mcpbignore` patterns cannot reach: dependency-shipped agent docs (`framework-skills/`, `skills/`, `.claude/`, `.agents/`, `SKILL.md`) and platform-specific native bindings, which would otherwise lock the bundle to the platform it was packed on. A server using DataCanvas therefore ships a portable bundle without the DuckDB native — `@duckdb/node-api` is an optional peer loaded lazily, so canvas tools report an actionable install hint and every other tool works normally. MCPB is stdio-only — HTTP and Cloudflare Workers deployments are unaffected. Consumers who don't need it can delete `manifest.json` and `.mcpbignore`; `lint:packaging` skips cleanly.
460
+
461
+ **Adding an env var requires both files:** `server.json` (registry discovery, `environmentVariables[]`) and `manifest.json` (bundle install UX, `mcp_config.env` + `user_config`). `lint:packaging` (run by `devcheck`) verifies the env var names match, that every `user_config` option is wired into `mcp_config.env` as `"X": "${user_config.X}"` (the host substitutes nothing else — `"${X}"` reaches the server as that literal string), and that an optional string option carries `"default": ""`.
462
+
463
+ **README install badges** (Claude Desktop `.mcpb`, Cursor, VS Code) and the `base64` / `encodeURIComponent` config-generation commands are ship-time concerns — run the `polish-docs-meta` skill, which carries the badge format, layout, and generation snippets in `framework-skills/polish-docs-meta/references/readme.md`.
464
+
465
+ ---
466
+
467
+ ## Changelog
468
+
469
+ Directory-based, grouped by minor series via the `.x` semver-wildcard convention. Source of truth: `changelog/<major.minor>.x/<version>.md` (e.g. `changelog/0.1.x/0.1.0.md`) — one file per release, shipped in the npm package. At release, author the per-version file with a concrete version and date, then run `npm run changelog:build` to regenerate the rollup. `changelog/template.md` is a **pristine format reference** — never edited or moved; read it for the frontmatter + section layout when scaffolding. `CHANGELOG.md` is a **navigation index** (header + link + summary per version), regenerated by `npm run changelog:build` — devcheck hard-fails on drift; never hand-edit it.
470
+
471
+ Each per-version file opens with YAML frontmatter:
472
+
473
+ ```markdown
474
+ ---
475
+ summary: "One-line headline, ≤350 chars" # required — powers the rollup index
476
+ breaking: false # optional — true flags breaking changes
477
+ security: false # optional — true ONLY for a source-code security fix, never a dependency CVE bump
478
+ ---
479
+
480
+ # 0.1.0 — YYYY-MM-DD
481
+ ...
482
+ ```
483
+
484
+ `breaking: true` renders a `· ⚠️ Breaking` badge — use it when consumers must update code on upgrade (signature changes, removed APIs, config renames). `security: true` renders a `· 🛡️ Security` badge and pairs with a `## Security` body section — set it only for a security fix in this server's *own source code*, never for a routine dependency or transitive CVE bump (record those under `## Dependencies`). When both are set, badges render `· ⚠️ Breaking · 🛡️ Security`.
485
+
486
+ `agent-notes` is an optional free-form field for maintenance agents processing the release downstream. Content here won't appear in the rendered CHANGELOG — it's consumed by agents running the `maintenance` skill. Use it for adoption instructions that don't fit the human-facing sections: new files to create, fields to populate, one-time migration steps. Omit entirely when there's nothing to say.
487
+
488
+ **Section order:** the Keep a Changelog sequence — Added, Changed, Deprecated, Removed, Fixed, Security — then `Dependencies` last. Include only sections with entries — don't ship empty headers.
489
+
490
+ **Tag annotations** render as GitHub Release bodies via `--notes-from-tag`. They must be structured markdown — never a flat comma-separated string. Subject omits the version number (GitHub prepends it). See `changelog/template.md` for the full format reference.
491
+
492
+ ---
493
+
494
+ ## Publishing
495
+
496
+ **Every release goes through a release PR, straight-through** — `git-wrapup`'s "Release PR mode", mode `straight-through`. One run: `git-wrapup` lands the commit stack on `release/<version>`, pushes it, and opens the PR (title = the release commit subject, body = the changelog entry plus a gates section); `release-and-publish` then fast-forwards `main` locally with `git merge --ff-only`, creates the tag on `main`'s tip, pushes `main` and the tag, deletes the branch, and publishes. A caller's brief may run a given release as `gated` instead — a `release-pr-review` pass on the open PR before `release-and-publish`. **Never merge through the GitHub UI or `gh pr merge`**: squash and rebase-merge are disabled in the repo settings because both rewrite the stack (rebase-merge also strips the SSH signatures), and a merge commit breaks the linear history.
497
+
498
+ ---
499
+
500
+ ## Imports
501
+
502
+ ```ts
503
+ // Framework — z is re-exported, no separate zod import needed
504
+ import { tool, z } from '@cyanheads/mcp-ts-core';
505
+ import { McpError, JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
506
+
507
+ // Server's own code — via path alias
508
+ import { getAicService } from '@/services/aic/aic-service.js';
509
+ ```
510
+
511
+ ---
512
+
513
+ ## Checklist
514
+
515
+ - [ ] Zod schemas: all fields have `.describe()`, only JSON-Schema-serializable types (no `z.custom()`, `z.date()`, `z.transform()`, `z.bigint()`, `z.symbol()`, `z.void()`, `z.map()`, `z.set()`, `z.function()`, `z.nan()`)
516
+ - [ ] Optional nested objects: handler guards for empty inner values from form-based clients (`if (input.obj?.field && ...)`, not just `if (input.obj)`). When regex/length constraints matter, use `z.union([z.literal(''), z.string().regex(...).describe(...)])` — literal variants are exempt from `describe-on-fields`.
517
+ - [ ] JSDoc `@fileoverview` + `@module` on every file
518
+ - [ ] `ctx.log` for logging, `ctx.state` for storage
519
+ - [ ] Handlers throw on failure — error factories or plain `Error`, no try/catch
520
+ - [ ] `format()` renders all data the LLM needs — different clients forward different surfaces (Claude Code → `structuredContent`, Claude Desktop → `content[]`); both must carry the same data
521
+ - [ ] If wrapping external API: raw/domain/output schemas reviewed against real upstream sparsity/nullability before finalizing required vs optional fields
522
+ - [ ] If wrapping external API: normalization and `format()` preserve uncertainty; do not fabricate facts from missing upstream data
523
+ - [ ] If wrapping external API: tests include at least one sparse payload case with omitted upstream fields
524
+ - [ ] Registered in `createApp()` arrays (directly or via barrel exports)
525
+ - [ ] Optional inputs wrapped in `blankAsUnset()`; array inputs go through `listInput()` with a `.max()` cap
526
+ - [ ] Upstream strings in `format()` pass through `inlineSafe()` (inline slots), `quoteBlock()` (free text), or `printableUrl()` (URLs); `structuredContent` keeps them as received
527
+ - [ ] Every definition that calls the service declares `rate_limited`, `request_blocked`, and `upstream_rejected_query` (`thrownBy: 'service'`), each `recovery` naming that tool's own levers
528
+ - [ ] Licensed text carries its terms: `license_text` on every artwork, artist, exhibition, and audio-guide result, `description_attribution` with description text, `source_citation` with audio-guide content
529
+ - [ ] A new or renamed tool is reflected in the `createApp()` `instructions` (under 2,048 characters), the README, and `docs/design.md`
530
+ - [ ] Tests use `createMockContext()` from `@cyanheads/mcp-ts-core/testing`
531
+ - [ ] `.codex-plugin/plugin.json` populated — `name`, `version`, `description`, `repository`, `license` from `package.json`; `interface.displayName` = the unscoped repo name (never the npm scope — `lint:packaging` enforces this); `interface.shortDescription` from `package.json` description
532
+ - [ ] `.codex-plugin/mcp.json` updated — server name key is the unscoped repo name; every user-supplied variable (API key, contact email, instance URL) is listed in `env_vars` so Codex forwards it from the user's environment. Never write `"KEY": ""` into `env` — an empty value replaces the user's exported key and is read as unset
533
+ - [ ] `.claude-plugin/plugin.json` populated — `name`, `version`, `description`, `author`, `repository`, `license`, `keywords` from `package.json`; inline `mcpServers` entry keyed by the unscoped repo name. Every user-supplied variable is declared under `userConfig` (`type`, `title`, `description`; `sensitive: true` for keys and tokens; `required: true` or `default: ""`) and referenced from `env` as `"KEY": "${user_config.<option>}"` — mirror the `user_config` block in `manifest.json`. Never write `"KEY": ""` into `env`
534
+ - [ ] `npm run devcheck` passes