@cyanheads/zenodo-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 (97) hide show
  1. package/AGENTS.md +435 -0
  2. package/CLAUDE.md +435 -0
  3. package/Dockerfile +140 -0
  4. package/LICENSE +201 -0
  5. package/README.md +292 -0
  6. package/changelog/0.1.x/0.1.1.md +21 -0
  7. package/changelog/template.md +151 -0
  8. package/dist/config/server-config.d.ts +13 -0
  9. package/dist/config/server-config.d.ts.map +1 -0
  10. package/dist/config/server-config.js +19 -0
  11. package/dist/config/server-config.js.map +1 -0
  12. package/dist/index.d.ts +7 -0
  13. package/dist/index.d.ts.map +1 -0
  14. package/dist/index.js +21 -0
  15. package/dist/index.js.map +1 -0
  16. package/dist/mcp-server/tools/definitions/get-record.tool.d.ts +186 -0
  17. package/dist/mcp-server/tools/definitions/get-record.tool.d.ts.map +1 -0
  18. package/dist/mcp-server/tools/definitions/get-record.tool.js +568 -0
  19. package/dist/mcp-server/tools/definitions/get-record.tool.js.map +1 -0
  20. package/dist/mcp-server/tools/definitions/index.d.ts +721 -0
  21. package/dist/mcp-server/tools/definitions/index.d.ts.map +1 -0
  22. package/dist/mcp-server/tools/definitions/index.js +21 -0
  23. package/dist/mcp-server/tools/definitions/index.js.map +1 -0
  24. package/dist/mcp-server/tools/definitions/list-files.tool.d.ts +108 -0
  25. package/dist/mcp-server/tools/definitions/list-files.tool.d.ts.map +1 -0
  26. package/dist/mcp-server/tools/definitions/list-files.tool.js +348 -0
  27. package/dist/mcp-server/tools/definitions/list-files.tool.js.map +1 -0
  28. package/dist/mcp-server/tools/definitions/list-versions.tool.d.ts +92 -0
  29. package/dist/mcp-server/tools/definitions/list-versions.tool.d.ts.map +1 -0
  30. package/dist/mcp-server/tools/definitions/list-versions.tool.js +268 -0
  31. package/dist/mcp-server/tools/definitions/list-versions.tool.js.map +1 -0
  32. package/dist/mcp-server/tools/definitions/lookup-vocabulary.tool.d.ts +99 -0
  33. package/dist/mcp-server/tools/definitions/lookup-vocabulary.tool.d.ts.map +1 -0
  34. package/dist/mcp-server/tools/definitions/lookup-vocabulary.tool.js +324 -0
  35. package/dist/mcp-server/tools/definitions/lookup-vocabulary.tool.js.map +1 -0
  36. package/dist/mcp-server/tools/definitions/read-file.tool.d.ts +104 -0
  37. package/dist/mcp-server/tools/definitions/read-file.tool.d.ts.map +1 -0
  38. package/dist/mcp-server/tools/definitions/read-file.tool.js +370 -0
  39. package/dist/mcp-server/tools/definitions/read-file.tool.js.map +1 -0
  40. package/dist/mcp-server/tools/definitions/search-records.tool.d.ts +181 -0
  41. package/dist/mcp-server/tools/definitions/search-records.tool.d.ts.map +1 -0
  42. package/dist/mcp-server/tools/definitions/search-records.tool.js +531 -0
  43. package/dist/mcp-server/tools/definitions/search-records.tool.js.map +1 -0
  44. package/dist/mcp-server/tools/record-miss.d.ts +37 -0
  45. package/dist/mcp-server/tools/record-miss.d.ts.map +1 -0
  46. package/dist/mcp-server/tools/record-miss.js +51 -0
  47. package/dist/mcp-server/tools/record-miss.js.map +1 -0
  48. package/dist/mcp-server/tools/render.d.ts +31 -0
  49. package/dist/mcp-server/tools/render.d.ts.map +1 -0
  50. package/dist/mcp-server/tools/render.js +53 -0
  51. package/dist/mcp-server/tools/render.js.map +1 -0
  52. package/dist/mcp-server/tools/schema-helpers.d.ts +20 -0
  53. package/dist/mcp-server/tools/schema-helpers.d.ts.map +1 -0
  54. package/dist/mcp-server/tools/schema-helpers.js +44 -0
  55. package/dist/mcp-server/tools/schema-helpers.js.map +1 -0
  56. package/dist/services/zenodo/cache.d.ts +25 -0
  57. package/dist/services/zenodo/cache.d.ts.map +1 -0
  58. package/dist/services/zenodo/cache.js +58 -0
  59. package/dist/services/zenodo/cache.js.map +1 -0
  60. package/dist/services/zenodo/html-to-text.d.ts +23 -0
  61. package/dist/services/zenodo/html-to-text.d.ts.map +1 -0
  62. package/dist/services/zenodo/html-to-text.js +148 -0
  63. package/dist/services/zenodo/html-to-text.js.map +1 -0
  64. package/dist/services/zenodo/http.d.ts +73 -0
  65. package/dist/services/zenodo/http.d.ts.map +1 -0
  66. package/dist/services/zenodo/http.js +378 -0
  67. package/dist/services/zenodo/http.js.map +1 -0
  68. package/dist/services/zenodo/identifiers.d.ts +104 -0
  69. package/dist/services/zenodo/identifiers.d.ts.map +1 -0
  70. package/dist/services/zenodo/identifiers.js +261 -0
  71. package/dist/services/zenodo/identifiers.js.map +1 -0
  72. package/dist/services/zenodo/normalize.d.ts +29 -0
  73. package/dist/services/zenodo/normalize.d.ts.map +1 -0
  74. package/dist/services/zenodo/normalize.js +324 -0
  75. package/dist/services/zenodo/normalize.js.map +1 -0
  76. package/dist/services/zenodo/query-builder.d.ts +87 -0
  77. package/dist/services/zenodo/query-builder.d.ts.map +1 -0
  78. package/dist/services/zenodo/query-builder.js +221 -0
  79. package/dist/services/zenodo/query-builder.js.map +1 -0
  80. package/dist/services/zenodo/resource-types.d.ts +34 -0
  81. package/dist/services/zenodo/resource-types.d.ts.map +1 -0
  82. package/dist/services/zenodo/resource-types.js +97 -0
  83. package/dist/services/zenodo/resource-types.js.map +1 -0
  84. package/dist/services/zenodo/text-preview.d.ts +56 -0
  85. package/dist/services/zenodo/text-preview.d.ts.map +1 -0
  86. package/dist/services/zenodo/text-preview.js +151 -0
  87. package/dist/services/zenodo/text-preview.js.map +1 -0
  88. package/dist/services/zenodo/types.d.ts +517 -0
  89. package/dist/services/zenodo/types.d.ts.map +1 -0
  90. package/dist/services/zenodo/types.js +8 -0
  91. package/dist/services/zenodo/types.js.map +1 -0
  92. package/dist/services/zenodo/zenodo-service.d.ts +98 -0
  93. package/dist/services/zenodo/zenodo-service.d.ts.map +1 -0
  94. package/dist/services/zenodo/zenodo-service.js +392 -0
  95. package/dist/services/zenodo/zenodo-service.js.map +1 -0
  96. package/package.json +110 -0
  97. package/server.json +113 -0
package/AGENTS.md ADDED
@@ -0,0 +1,435 @@
1
+ # Developer Protocol
2
+
3
+ **Server:** zenodo-mcp-server
4
+ **Version:** 0.1.1
5
+ **Framework:** [@cyanheads/mcp-ts-core](https://www.npmjs.com/package/@cyanheads/mcp-ts-core) `^0.13.6`
6
+ **Engines:** Bun ≥1.4.0, Node ≥24.0.0
7
+ **MCP SDK:** `@modelcontextprotocol/server` ^2.0.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
+ Six read-only tools over the Zenodo REST API (`https://zenodo.org/api`, InvenioRDM): `zenodo_search_records`, `zenodo_get_record`, `zenodo_list_versions`, `zenodo_list_files`, `zenodo_read_file`, `zenodo_lookup_vocabulary`. No resources, no prompts. No credentials are needed; the optional `ZENODO_ACCESS_TOKEN` raises the rate limit and changes nothing else. [`docs/design.md`](./docs/design.md) holds the per-tool contracts, the verified upstream behavior behind them, and the decisions log — read it before changing a tool.
13
+
14
+ ---
15
+
16
+ ## What's Next?
17
+
18
+ When the user asks what's next or needs direction, suggest options based on the current project state. Common next steps:
19
+
20
+ 1. **Re-run the `setup` skill** — ensures CLAUDE.md, skills, structure, and metadata are populated and up to date with the current codebase
21
+ 2. **Run the `design-mcp-server` skill** — before adding a tool, extend `docs/design.md` with its contract
22
+ 3. **Add tools** — scaffold new definitions using the `add-tool` skill, and register them in `src/mcp-server/tools/definitions/index.ts`
23
+ 4. **Add tests** — scaffold tests for existing definitions using the `add-test` skill
24
+ 5. **Field-test definitions** — exercise the tools against live Zenodo using the `field-test` skill (pace searches: 25/min per process)
25
+ 6. **Run `devcheck`** — lint, format, typecheck, and security audit
26
+ 7. **Run the `security-pass` skill** — audit handlers for MCP-specific security gaps: output injection, scope blast radius, input sinks, tenant isolation
27
+ 8. **Run the `polish-docs-meta` skill** — finalize README, CHANGELOG, metadata, and agent protocol for shipping
28
+ 9. **Run the `maintenance` skill** — investigate changelogs, adopt upstream changes, and sync skills after `bun update --latest`
29
+
30
+ Tailor suggestions to what's actually missing or stale — don't recite the full list every time.
31
+
32
+ ---
33
+
34
+ ## Core Rules
35
+
36
+ - **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.
37
+ - **Use `ctx.log`** for request-scoped logging. No `console` calls.
38
+ - **Use `ctx.state`** for tenant-scoped storage. Never access persistence directly.
39
+ - **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.
40
+ - **Secrets in env vars only** — never hardcoded.
41
+ - **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.
42
+ - **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.
43
+
44
+ ---
45
+
46
+ ## Zenodo conventions
47
+
48
+ - **One fetch boundary.** Every upstream call goes through `ZenodoHttp` in `src/services/zenodo/http.ts`: per-call accept-lists (206, 301/302, 403, 404, 410, 416 are results, not errors), at most one retry, and no caller-controlled host — the service builds every path under `https://zenodo.org/api`. Tools call `getZenodoService()`, never `fetch`.
49
+ - **Two pacers, one budget per process.** `zenodo-search` (25/min) and `zenodo-general` (55/min and 1,900/hr anonymous; 90/min and 4,800/hr with a token), plus a header gate on `X-RateLimit-*`. A search takes a general start slot first. Every caller of the process shares the budget, so never add bulk or fan-out calls.
50
+ - **Process-local cache, not `ctx.state`.** Zenodo data is public, so `TtlLruCache` (`cache.ts`) is shared across tenants: records 5 min, searches 60 s, containers 10 min, vocabularies 1 h.
51
+ - **Identifiers parse locally.** `parseRecordRef()` (`identifiers.ts`) classifies every `id` form — record id, Zenodo DOI, concept DOI, external DOI, zenodo.org / doi.org URL. URLs are never fetched. All four `id`-taking tools share it.
52
+ - **Misses by tool role.** `zenodo_get_record` and `zenodo_list_versions` return `found: false` with `miss_kind`, `guidance`, and `tombstone` (shared in `record-miss.ts`); `zenodo_list_files` and `zenodo_read_file` throw `record_not_found` / `record_deleted`.
53
+ - **Untrusted text through the render helpers.** Every depositor-supplied string in `format()` goes through `inline()`, `quoteBlock()`, or `fence()` (`src/mcp-server/tools/render.ts`). HTML descriptions are converted by `htmlToText()` — the only transformation of upstream text.
54
+ - **Blank optional inputs read as unset.** Wrap optional strings and arrays with `blankToUndefined` / `toOptionalArray`, and enums with `enumPreprocess` (`schema-helpers.ts`). Never `.min(1)` on an optional field.
55
+ - **Enrichment defaults first.** A handler with required enrichment keys writes all of them on its first line, then overwrites where they change — a one-branch write fails the output parse on every other path.
56
+ - **Sparse fields stay absent.** An upstream field Zenodo omits is omitted from the output, never coerced to `0`, `''`, or `false`, and its `.describe()` says when it is absent.
57
+
58
+ ---
59
+
60
+ ## Patterns
61
+
62
+ ### Tool
63
+
64
+ Abridged from `src/mcp-server/tools/definitions/list-versions.tool.ts`:
65
+
66
+ ```ts
67
+ import { tool, z } from '@cyanheads/mcp-ts-core';
68
+ import { JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
69
+ import { parseRecordRef } from '@/services/zenodo/identifiers.js';
70
+ import { getZenodoService } from '@/services/zenodo/zenodo-service.js';
71
+ import { notOnZenodoMiss, recordMiss, TombstoneSchema } from '../record-miss.js';
72
+
73
+ export const listVersions = tool('zenodo_list_versions', {
74
+ title: 'List Zenodo record versions',
75
+ description: "List every version of a Zenodo deposit's version series, newest first, …",
76
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: true },
77
+ input: z.object({
78
+ id: z.string().trim().min(1).max(500).describe('Any version or concept identifier of the deposit: …'),
79
+ page: z.number().int().min(1).default(1).describe('Result page, starting at 1. page × size may not exceed 10,000.'),
80
+ size: z.number().int().min(1).max(25).default(25).describe('Versions per page (1–25).'),
81
+ }),
82
+ output: z.object({ /* found, input_kind, miss_kind?, guidance?, tombstone?, total_versions?, versions[], … */ }),
83
+ enrichment: {
84
+ truncated: z.boolean().describe('True when more versions follow this page.'),
85
+ shown: z.number().describe('Versions returned on this page.'),
86
+ cap: z.number().describe('Page size applied.'),
87
+ totalCount: z.number().describe('Number of versions in the series.'),
88
+ notice: z.string().optional().describe('Guidance on paging or a page past the end.'),
89
+ },
90
+ errors: [
91
+ {
92
+ reason: 'invalid_identifier',
93
+ code: JsonRpcErrorCode.ValidationError,
94
+ when: 'id matches no accepted form, or is a GitHub-badge latestdoi id or a non-zenodo.org host',
95
+ recovery: 'Pass a Zenodo record id (22705923), a DOI (10.5281/zenodo.22705923), or a zenodo.org/records URL as id; …',
96
+ },
97
+ // result_window_exceeded, record_unavailable, upstream_timeout, rate_limited …
98
+ ],
99
+
100
+ async handler(input, ctx) {
101
+ ctx.enrich({ truncated: false, shown: 0, cap: input.size, totalCount: 0 }); // required keys, first line
102
+
103
+ const ref = parseRecordRef(input.id);
104
+ if (ref.kind === 'invalid') {
105
+ throw ctx.fail('invalid_identifier', ref.message, ctx.recoveryFor('invalid_identifier'));
106
+ }
107
+ const service = getZenodoService();
108
+ // … resolve an external DOI; on a miss return { found: false, ...notOnZenodoMiss(doi), … }
109
+ // … a record-GET miss returns { found: false, ...recordMiss(recid, lookup), … }
110
+
111
+ const lookup = await service.listVersions(recid, input.page, input.size, ctx);
112
+ const hasMore = input.page * input.size < lookup.total;
113
+ ctx.enrich({ shown: lookup.hits.length });
114
+ ctx.enrich.total(lookup.total);
115
+ if (hasMore) {
116
+ ctx.enrich.truncated({
117
+ shown: lookup.hits.length,
118
+ cap: input.size,
119
+ guidance: `Showing ${lookup.hits.length} of ${lookup.total} versions; call again with page ${input.page + 1}.`,
120
+ });
121
+ }
122
+ return { found: true, input_kind: ref.inputKind, total_versions: lookup.total, /* … */ versions: lookup.hits };
123
+ },
124
+
125
+ // format() renders every output field; depositor text goes through inline() / quoteBlock().
126
+ format: (result) => [{ type: 'text', text: /* … */ '' }],
127
+ });
128
+ ```
129
+
130
+ ### Server config
131
+
132
+ ```ts
133
+ // src/config/server-config.ts — lazy-parsed, separate from framework config
134
+ import { z } from '@cyanheads/mcp-ts-core';
135
+ import { parseEnvConfig } from '@cyanheads/mcp-ts-core/config';
136
+
137
+ const ServerConfigSchema = z.object({
138
+ accessToken: z
139
+ .string()
140
+ .optional()
141
+ .describe(
142
+ 'Zenodo personal access token (created with no scopes). Raises the global rate limit; tool behavior and page sizes are unchanged.',
143
+ ),
144
+ });
145
+
146
+ let _config: z.infer<typeof ServerConfigSchema> | undefined;
147
+ export function getServerConfig() {
148
+ _config ??= parseEnvConfig(ServerConfigSchema, { accessToken: 'ZENODO_ACCESS_TOKEN' });
149
+ return _config;
150
+ }
151
+ ```
152
+
153
+ `parseEnvConfig` maps Zod schema paths → env var names so errors name the variable (`ZENODO_ACCESS_TOKEN`) not the path (`accessToken`). A blank value or an unsubstituted `${…}` placeholder reads as unset. A new env var also goes into `server.json`, `manifest.json`, both plugin manifests, and `.env.example` (see Bundling).
154
+
155
+ 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.
156
+
157
+ ### Server identity and lifecycle
158
+
159
+ `src/index.ts`:
160
+
161
+ ```ts
162
+ await createApp({
163
+ name: 'zenodo-mcp-server',
164
+ title: 'zenodo-mcp-server',
165
+ instructions: "Zenodo is CERN's open research repository … metadata is CC0 and each file keeps its deposit's license.",
166
+ tools: allToolDefinitions,
167
+ setup(core) {
168
+ initZenodoService(core.config);
169
+ },
170
+ teardown() {
171
+ disposeZenodoService();
172
+ },
173
+ });
174
+ ```
175
+
176
+ The identity block is `name` + `title` only, both the bare hyphenated `zenodo-mcp-server` — never Title Case, never the npm scope, and never a duplicated `description` (it derives from `package.json`). `instructions` is session-level orientation sent on every `initialize`; keep it in step with the tool descriptions. `setup()` builds the service (pacers, cache, a User-Agent carrying the server version); `teardown()` disposes the pacers' timers.
177
+
178
+ No handler calls `ctx.requestInput`, so no `sessionMode` requirement is declared; the Dockerfile and `.env.example` run HTTP as `stateless`.
179
+
180
+ ---
181
+
182
+ ## Context
183
+
184
+ Handlers receive a unified `ctx` object. The properties this server uses:
185
+
186
+ | Property | Description |
187
+ |:---------|:------------|
188
+ | `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. |
189
+ | `ctx.enrich` | Success-path agent context — `ctx.enrich(...)` or `.notice()` / `.total()` / `.echo()` / `.truncated()`. Every tool declares an `enrichment` block; see *Enrichment defaults first*. |
190
+ | `ctx.fail` / `ctx.recoveryFor` | Throw a declared error-contract reason with its recovery hint: `throw ctx.fail('reason', message, ctx.recoveryFor('reason'))`. |
191
+ | `ctx.signal` | `AbortSignal` for cancellation — the service threads it into every upstream request and pacer wait. |
192
+ | `ctx.requestId` | Unique request ID. |
193
+ | `ctx.tenantId` | Tenant ID from JWT; `'default'` for stdio or HTTP with auth off. |
194
+
195
+ `ctx.state`, `ctx.requestInput` / `ctx.inputs`, and `ctx.content` are unused: responses are cached process-wide in the service, no tool asks for input mid-call, and every tool returns text.
196
+
197
+ ---
198
+
199
+ ## Errors
200
+
201
+ Handlers throw — the framework catches, classifies, and formats.
202
+
203
+ **Typed error contract.** Every tool declares `errors: [{ reason, code, when, recovery, retryable?, thrownBy? }]` inline and throws with `ctx.fail(reason, …, ctx.recoveryFor(reason))`. `when` is model-facing text (the framework advertises it), so write it for the calling model — no implementation terms like "record GET" or "pacer shed". `recovery` names the next tool call. Reasons the service throws (`rate_limited`, `record_unavailable`, `upstream_timeout`, `query_failed`, `archive_unavailable`) carry `thrownBy: 'service'`. Baseline codes (`InternalError`, `ServiceUnavailable`, `Timeout`, `ValidationError`, `SerializationError`, `RequestCancelled`) bubble freely and don't need declaring.
204
+
205
+ ```ts
206
+ errors: [
207
+ { reason: 'unknown_community', code: JsonRpcErrorCode.ValidationError,
208
+ when: 'community resolves to no Zenodo community',
209
+ recovery: 'Find the community’s slug with zenodo_lookup_vocabulary (vocabulary: communities), then pass it as community.' },
210
+ ],
211
+ async handler(input, ctx) {
212
+ const community = ref ? await service.getCommunity(ref, ctx) : undefined;
213
+ if (!community) {
214
+ throw ctx.fail('unknown_community', `No Zenodo community matches "${inline(input.community)}" …`, ctx.recoveryFor('unknown_community'));
215
+ }
216
+ }
217
+ ```
218
+
219
+ **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.
220
+
221
+ See framework CLAUDE.md and the `api-errors` skill for the full auto-classification table, all available factories, and the contract reference.
222
+
223
+ ---
224
+
225
+ ## Structure
226
+
227
+ ```text
228
+ src/
229
+ index.ts # createApp(): identity, instructions, tools, setup/teardown
230
+ config/
231
+ server-config.ts # ZENODO_ACCESS_TOKEN (Zod schema, lazy parse)
232
+ services/zenodo/
233
+ zenodo-service.ts # ZenodoService + init/get/dispose accessors
234
+ http.ts # Fetch boundary: accept-lists, retries, pacers, header gate
235
+ cache.ts # Process-local TTL LRU with a byte budget
236
+ normalize.ts # Raw RDM JSON → domain types
237
+ identifiers.ts # parseRecordRef, ROR / Funder DOI / ORCID / community parsing
238
+ query-builder.ts # Composes the search q from filters
239
+ html-to-text.ts # HTML description → plain text
240
+ text-preview.ts # Preview mode, byte cut, binary detection
241
+ resource-types.ts # Static 43-entry resource type table
242
+ types.ts # Raw upstream and domain types
243
+ mcp-server/tools/
244
+ definitions/
245
+ index.ts # allToolDefinitions barrel
246
+ [tool-name].tool.ts # The six tool definitions
247
+ render.ts # inline / quoteBlock / fence for untrusted text
248
+ schema-helpers.ts # blankToUndefined, toOptionalArray, enumPreprocess
249
+ record-miss.ts # Shared found:false outcome + TombstoneSchema
250
+ tests/
251
+ fixtures/zenodo/ # Recorded Zenodo responses
252
+ helpers/ # Fixture loaders
253
+ services/zenodo/ # Service and pure-module tests
254
+ mcp-server/tools/ # Tool handler and helper tests
255
+ fuzz/ # Adversarial-input fuzz tests
256
+ smoke/ # Definition smoke tests
257
+ docs/
258
+ design.md # Tool contracts, verified API behavior, decisions log
259
+ ```
260
+
261
+ ---
262
+
263
+ ## Naming
264
+
265
+ | What | Convention | Example |
266
+ |:-----|:-----------|:--------|
267
+ | Files | kebab-case with suffix | `list-versions.tool.ts` |
268
+ | Tool names | snake_case, `zenodo_` prefix | `zenodo_list_versions` |
269
+ | Directories | kebab-case | `src/services/zenodo/` |
270
+ | Descriptions | Single string or template literal, no `+` concatenation | `'Resolve names to the ids zenodo_search_records filters on, …'` |
271
+ | Input and output fields | snake_case | `concept_recid`, `latest_recid`, `next_offset` |
272
+
273
+ ---
274
+
275
+ ## Skills
276
+
277
+ 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.
278
+
279
+ **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.
280
+
281
+ Available skills:
282
+
283
+ | Skill | Purpose |
284
+ |:------|:--------|
285
+ | `setup` | Post-init project orientation |
286
+ | `design-mcp-server` | Design tool surface, resources, and services for a new server |
287
+ | `add-tool` | Scaffold a new tool definition |
288
+ | `add-app-tool` | Scaffold an MCP App tool + paired UI resource |
289
+ | `add-resource` | Scaffold a new resource definition |
290
+ | `add-prompt` | Scaffold a new prompt definition |
291
+ | `add-service` | Scaffold a new service integration |
292
+ | `add-test` | Scaffold test file for a tool, resource, or service |
293
+ | `field-test` | Exercise tools/resources/prompts with real inputs, verify behavior, report issues |
294
+ | `tool-defs-analysis` | Read-only audit of MCP definition language across the surface — voice, leaks, defaults, recovery hints, output descriptions |
295
+ | `security-pass` | Audit server for MCP-flavored security gaps: output injection, scope blast radius, input sinks, tenant isolation |
296
+ | `code-simplifier` | Post-session cleanup against `git diff` — modernize syntax, consolidate duplication, align with the codebase |
297
+ | `polish-docs-meta` | Finalize docs, README, metadata, and agent protocol for shipping |
298
+ | `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 |
299
+ | `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 |
300
+ | `release-and-publish` | Fast-forward merge (release PR mode) + tag + push + npm + MCP Registry + GH Release + Docker. Picks up from `git-wrapup` |
301
+ | `maintenance` | Investigate changelogs, adopt upstream changes, sync skills to agent dirs |
302
+ | `orchestrations` | Chain task skills into a gated multi-phase pipeline — build-out, QA-fix, update-ship — when you can spawn sub-agents |
303
+ | `report-issue-framework` | File a bug or feature request against `@cyanheads/mcp-ts-core` via `gh` CLI |
304
+ | `report-issue-local` | File a bug or feature request against this server's own repo via `gh` CLI |
305
+ | `techniques` | Catalog of response/data-shaping techniques — overflow handling, payload shaping, retrieval patterns |
306
+ | `api-auth` | Auth modes, scopes, JWT/OAuth |
307
+ | `api-canvas` | DataCanvas: register tabular data, run SQL, export, plus the `spillover()` helper for big result sets — Tier 3 opt-in |
308
+ | `api-config` | AppConfig, parseConfig, env vars |
309
+ | `api-context` | Context interface, RequestContext, logger, state, multi-round-trip input |
310
+ | `api-errors` | McpError, JsonRpcErrorCode, error patterns |
311
+ | `api-linter` | Definition linter rule catalog — invoked by `bun run lint:mcp` and `devcheck` |
312
+ | `api-mirror` | MirrorService: persistent self-refreshing local mirror (embedded SQLite + FTS5) of a bulk upstream dataset — Tier 3 opt-in |
313
+ | `api-services` | LLM, Speech, Graph services |
314
+ | `api-testing` | createMockContext, test patterns |
315
+ | `api-utils` | Formatting, parsing, security, pagination, scheduling, telemetry helpers |
316
+ | `api-telemetry` | OTel catalog: spans, metrics, completion logs, env config, cardinality rules |
317
+ | `api-workers` | Cloudflare Workers runtime |
318
+
319
+ **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.
320
+
321
+ When you complete a skill's checklist, check the boxes and add a completion timestamp at the end (e.g., `Completed: 2026-03-11`).
322
+
323
+ ---
324
+
325
+ ## Commands
326
+
327
+ **Runtime:** Scripts use Bun's native TypeScript execution — `bun run <cmd>` is the standard invocation. `npm run <cmd>` also works (npm delegates to bun).
328
+
329
+ | Command | Purpose |
330
+ |:--------|:--------|
331
+ | `bun run build` | Compile TypeScript |
332
+ | `bun run rebuild` | Clean + build |
333
+ | `bun run clean` | Remove build artifacts |
334
+ | `bun run devcheck` | Lint + format + typecheck + security + changelog sync |
335
+ | `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` |
336
+ | `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` |
337
+ | `bun run lint:mcp` | Run the MCP definition linter standalone (rule catalog: `api-linter` skill) |
338
+ | `bun run lint:packaging` | Packaging surface checks — `server.json`/`manifest.json` env-var parity, plugin manifest identity, README version badge (run by devcheck) |
339
+ | `bun run list-skills` | Print the skill registry |
340
+ | `bun run tree` | Generate directory structure doc |
341
+ | `bun run format` | Auto-fix formatting (safe fixes only) |
342
+ | `bun run format:unsafe` | Also apply Biome's unsafe autofixes — review the diff; they can change behavior |
343
+ | `bun run test` | Run tests (Vitest — use `bun run test`, not `bun test`) |
344
+ | `bun run test:coverage` | Run tests with coverage |
345
+ | `bun run start:stdio` | Production mode (stdio) |
346
+ | `bun run start:http` | Production mode (HTTP) |
347
+ | `bun run changelog:build` | Regenerate `CHANGELOG.md` from `changelog/*.md` |
348
+ | `bun run changelog:check` | Verify `CHANGELOG.md` is in sync (used by devcheck) |
349
+ | `bun run bundle` | Build, pack, and clean a `.mcpb` for one-click Claude Desktop install |
350
+ | `bun run release:github` | Create the GitHub Release from an annotated tag and attach the `.mcpb` bundle |
351
+
352
+ **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.
353
+
354
+ **Tests never touch the network.** Service and tool tests run the real service against recorded responses in `tests/fixtures/zenodo/` through a fetch mock; a new upstream shape gets a trimmed fixture, not a live call.
355
+
356
+ ---
357
+
358
+ ## Bundling
359
+
360
+ `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. MCPB is stdio-only — HTTP and Cloudflare Workers deployments are unaffected.
361
+
362
+ **Adding an env var touches every packaging surface:** `server.json` (registry discovery, `environmentVariables[]`), `manifest.json` (bundle install UX, `mcp_config.env` + `user_config`), `.claude-plugin/plugin.json` (`userConfig` + `env`), and `.codex-plugin/mcp.json` (`env_vars`). `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": ""`.
363
+
364
+ **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`.
365
+
366
+ ---
367
+
368
+ ## Changelog
369
+
370
+ 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.
371
+
372
+ Each per-version file opens with YAML frontmatter:
373
+
374
+ ```markdown
375
+ ---
376
+ summary: "One-line headline, ≤350 chars" # required — powers the rollup index
377
+ breaking: false # optional — true flags breaking changes
378
+ security: false # optional — true ONLY for a source-code security fix, never a dependency CVE bump
379
+ ---
380
+
381
+ # 0.1.0 — YYYY-MM-DD
382
+ ...
383
+ ```
384
+
385
+ `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`.
386
+
387
+ `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.
388
+
389
+ **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.
390
+
391
+ **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.
392
+
393
+ ---
394
+
395
+ ## Publishing
396
+
397
+ **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.
398
+
399
+ **Identity across publish surfaces.** The npm name `@cyanheads/zenodo-mcp-server` appears on install surfaces: the README `<h1>`, the npm and install badges, and every `bunx` / `npx -y` argument. `mcpName` and the `server.json` `name` are `io.github.cyanheads/zenodo-mcp-server`. Everywhere else — `createApp()`, `manifest.json` `name`, plugin names and server keys, the Docker image, the `.mcpb` file — it is the bare `zenodo-mcp-server`. `lint:packaging` enforces the split.
400
+
401
+ ---
402
+
403
+ ## Imports
404
+
405
+ ```ts
406
+ // Framework — z is re-exported, no separate zod import needed
407
+ import { tool, z } from '@cyanheads/mcp-ts-core';
408
+ import { McpError, JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
409
+
410
+ // Server's own code — via path alias
411
+ import { getZenodoService } from '@/services/zenodo/zenodo-service.js';
412
+ ```
413
+
414
+ ---
415
+
416
+ ## Checklist
417
+
418
+ - [ ] 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()`)
419
+ - [ ] Optional inputs wrapped with `blankToUndefined` / `toOptionalArray` / `enumPreprocess`, never `.min(1)` on an optional field
420
+ - [ ] JSDoc `@fileoverview` + `@module` on every file
421
+ - [ ] `ctx.log` for logging; upstream data cached in the service, not `ctx.state`
422
+ - [ ] Handlers throw on failure via declared contract reasons (`ctx.fail` + `ctx.recoveryFor`), no try/catch
423
+ - [ ] Every upstream call goes through `getZenodoService()` — no direct `fetch`, no caller-supplied host
424
+ - [ ] `format()` renders all data the LLM needs — different clients forward different surfaces (Claude Code → `structuredContent`, Claude Desktop → `content[]`); both must carry the same data
425
+ - [ ] Depositor-supplied text in `format()` passes through `inline()` / `quoteBlock()` / `fence()`
426
+ - [ ] Required enrichment keys written unconditionally on the handler's first line
427
+ - [ ] Sparse upstream fields optional in the output schema, left absent (never coerced), with `.describe()` saying when
428
+ - [ ] Tests include a sparse-payload case against a trimmed fixture; no live network in `bun run test`
429
+ - [ ] Registered in `allToolDefinitions` (`src/mcp-server/tools/definitions/index.ts`)
430
+ - [ ] Tests use `createMockContext()` from `@cyanheads/mcp-ts-core/testing`
431
+ - [ ] `docs/design.md` updated when a tool's contract changes
432
+ - [ ] `.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)
433
+ - [ ] `.codex-plugin/mcp.json` updated — server name key is the unscoped repo name; `ZENODO_ACCESS_TOKEN` listed in `env_vars` so Codex forwards it from the user's environment. Never write `"KEY": ""` into `env`
434
+ - [ ] `.claude-plugin/plugin.json` populated — `name`, `version`, `description`, `author`, `repository`, `license`, `keywords`; inline `mcpServers` entry keyed by the unscoped repo name, with `ZENODO_ACCESS_TOKEN` declared under `userConfig` and referenced from `env` as `"${user_config.zenodo_access_token}"`
435
+ - [ ] `bun run devcheck` passes with zero warnings, and `bun run test` passes