@cyanheads/biorxiv-mcp-server 0.1.5

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 (63) hide show
  1. package/AGENTS.md +309 -0
  2. package/CLAUDE.md +309 -0
  3. package/Dockerfile +99 -0
  4. package/LICENSE +195 -0
  5. package/README.md +279 -0
  6. package/changelog/0.1.x/0.1.0.md +18 -0
  7. package/changelog/0.1.x/0.1.1.md +32 -0
  8. package/changelog/0.1.x/0.1.2.md +23 -0
  9. package/changelog/0.1.x/0.1.3.md +23 -0
  10. package/changelog/0.1.x/0.1.4.md +19 -0
  11. package/changelog/0.1.x/0.1.5.md +18 -0
  12. package/changelog/template.md +93 -0
  13. package/dist/biorxiv-mcp-server.mcpb +0 -0
  14. package/dist/config/server-config.d.ts +17 -0
  15. package/dist/config/server-config.d.ts.map +1 -0
  16. package/dist/config/server-config.js +34 -0
  17. package/dist/config/server-config.js.map +1 -0
  18. package/dist/index.d.ts +9 -0
  19. package/dist/index.d.ts.map +1 -0
  20. package/dist/index.js +25 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/mcp-server/tools/definitions/biorxiv-get-preprint.tool.d.ts +54 -0
  23. package/dist/mcp-server/tools/definitions/biorxiv-get-preprint.tool.d.ts.map +1 -0
  24. package/dist/mcp-server/tools/definitions/biorxiv-get-preprint.tool.js +208 -0
  25. package/dist/mcp-server/tools/definitions/biorxiv-get-preprint.tool.js.map +1 -0
  26. package/dist/mcp-server/tools/definitions/biorxiv-get-published-version.tool.d.ts +39 -0
  27. package/dist/mcp-server/tools/definitions/biorxiv-get-published-version.tool.d.ts.map +1 -0
  28. package/dist/mcp-server/tools/definitions/biorxiv-get-published-version.tool.js +99 -0
  29. package/dist/mcp-server/tools/definitions/biorxiv-get-published-version.tool.js.map +1 -0
  30. package/dist/mcp-server/tools/definitions/biorxiv-list-categories.tool.d.ts +13 -0
  31. package/dist/mcp-server/tools/definitions/biorxiv-list-categories.tool.d.ts.map +1 -0
  32. package/dist/mcp-server/tools/definitions/biorxiv-list-categories.tool.js +40 -0
  33. package/dist/mcp-server/tools/definitions/biorxiv-list-categories.tool.js.map +1 -0
  34. package/dist/mcp-server/tools/definitions/biorxiv-list-recent.tool.d.ts +65 -0
  35. package/dist/mcp-server/tools/definitions/biorxiv-list-recent.tool.d.ts.map +1 -0
  36. package/dist/mcp-server/tools/definitions/biorxiv-list-recent.tool.js +269 -0
  37. package/dist/mcp-server/tools/definitions/biorxiv-list-recent.tool.js.map +1 -0
  38. package/dist/mcp-server/tools/definitions/biorxiv-search-preprints.tool.d.ts +46 -0
  39. package/dist/mcp-server/tools/definitions/biorxiv-search-preprints.tool.d.ts.map +1 -0
  40. package/dist/mcp-server/tools/definitions/biorxiv-search-preprints.tool.js +279 -0
  41. package/dist/mcp-server/tools/definitions/biorxiv-search-preprints.tool.js.map +1 -0
  42. package/dist/mcp-server/tools/definitions/index.d.ts +171 -0
  43. package/dist/mcp-server/tools/definitions/index.d.ts.map +1 -0
  44. package/dist/mcp-server/tools/definitions/index.js +23 -0
  45. package/dist/mcp-server/tools/definitions/index.js.map +1 -0
  46. package/dist/services/biorxiv/biorxiv-service.d.ts +39 -0
  47. package/dist/services/biorxiv/biorxiv-service.d.ts.map +1 -0
  48. package/dist/services/biorxiv/biorxiv-service.js +307 -0
  49. package/dist/services/biorxiv/biorxiv-service.js.map +1 -0
  50. package/dist/services/biorxiv/types.d.ts +127 -0
  51. package/dist/services/biorxiv/types.d.ts.map +1 -0
  52. package/dist/services/biorxiv/types.js +9 -0
  53. package/dist/services/biorxiv/types.js.map +1 -0
  54. package/dist/services/europe-pmc/europe-pmc-service.d.ts +36 -0
  55. package/dist/services/europe-pmc/europe-pmc-service.d.ts.map +1 -0
  56. package/dist/services/europe-pmc/europe-pmc-service.js +100 -0
  57. package/dist/services/europe-pmc/europe-pmc-service.js.map +1 -0
  58. package/dist/services/europe-pmc/types.d.ts +33 -0
  59. package/dist/services/europe-pmc/types.d.ts.map +1 -0
  60. package/dist/services/europe-pmc/types.js +8 -0
  61. package/dist/services/europe-pmc/types.js.map +1 -0
  62. package/package.json +102 -0
  63. package/server.json +111 -0
package/AGENTS.md ADDED
@@ -0,0 +1,309 @@
1
+ # Agent Protocol
2
+
3
+ **Server:** biorxiv-mcp-server
4
+ **Version:** 0.1.5
5
+ **Framework:** [@cyanheads/mcp-ts-core](https://www.npmjs.com/package/@cyanheads/mcp-ts-core) `^0.9.6`
6
+ **Engines:** Bun ≥1.3.2, Node ≥24.0.0
7
+ **MCP SDK:** `@modelcontextprotocol/sdk` ^1.29.0
8
+ **Zod:** ^4.4.3
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
+ ## What's Next?
15
+
16
+ When the user asks what to do next, what's left, or needs direction, suggest relevant options based on the current project state:
17
+
18
+ 1. **Re-run the `setup` skill** — ensures CLAUDE.md, skills, structure, and metadata are populated and up to date with the current codebase
19
+ 2. **Run the `design-mcp-server` skill** — if the tool/resource surface hasn't been mapped yet, work through domain design
20
+ 3. **Add tools/resources/prompts** — scaffold new definitions using the `add-tool`, `add-app-tool`, `add-resource`, `add-prompt` skills
21
+ 4. **Add services** — scaffold domain service integrations using the `add-service` skill
22
+ 5. **Add tests** — scaffold tests for existing definitions using the `add-test` skill
23
+ 6. **Field-test definitions** — exercise tools/resources/prompts with real inputs using the `field-test` skill, get a report of issues and pain points
24
+ 7. **Run `devcheck`** — lint, format, typecheck, and security audit
25
+ 8. **Run the `security-pass` skill** — audit handlers for MCP-specific security gaps: output injection, scope blast radius, input sinks, tenant isolation
26
+ 9. **Run the `polish-docs-meta` skill** — finalize README, CHANGELOG, metadata, and agent protocol for shipping
27
+ 10. **Run the `maintenance` skill** — investigate changelogs, adopt upstream changes, and sync skills after `bun update --latest`
28
+
29
+ Tailor suggestions to what's actually missing or stale — don't recite the full list every time.
30
+
31
+ ---
32
+
33
+ ## Core Rules
34
+
35
+ - **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.
36
+ - **Use `ctx.log`** for request-scoped logging. No `console` calls.
37
+ - **Use `ctx.state`** for tenant-scoped storage. Never access persistence directly.
38
+ - **Check `ctx.elicit` / `ctx.sample`** for presence before calling.
39
+ - **Secrets in env vars only** — never hardcoded.
40
+
41
+ ---
42
+
43
+ ## Patterns
44
+
45
+ ### Tool
46
+
47
+ ```ts
48
+ import { tool, z } from '@cyanheads/mcp-ts-core';
49
+ import { getBiorxivApiService } from '@/services/biorxiv/biorxiv-service.js';
50
+
51
+ export const listCategoriesTools = tool('biorxiv_list_categories', {
52
+ description: 'List valid subject category strings for bioRxiv and medRxiv.',
53
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
54
+
55
+ input: z.object({}),
56
+
57
+ output: z.object({
58
+ biorxiv: z.array(z.string().describe('Category name')).describe('bioRxiv subject categories'),
59
+ medrxiv: z.array(z.string().describe('Category name')).describe('medRxiv subject categories'),
60
+ }),
61
+
62
+ async handler(_input, ctx) {
63
+ ctx.log.info('Executing biorxiv_list_categories tool');
64
+ return getBiorxivApiService().getCategories();
65
+ },
66
+
67
+ format: (result) => [{
68
+ type: 'text',
69
+ text: [
70
+ '**bioRxiv categories:**',
71
+ result.biorxiv.map(c => `- ${c}`).join('\n'),
72
+ '',
73
+ '**medRxiv categories:**',
74
+ result.medrxiv.map(c => `- ${c}`).join('\n'),
75
+ ].join('\n'),
76
+ }],
77
+ });
78
+ ```
79
+
80
+ ### Server config
81
+
82
+ ```ts
83
+ // src/config/server-config.ts — lazy-parsed, separate from framework config
84
+ import { z } from '@cyanheads/mcp-ts-core';
85
+ import { parseEnvConfig } from '@cyanheads/mcp-ts-core/config';
86
+
87
+ const ServerConfigSchema = z.object({
88
+ mailto: z.email().optional().describe('Contact email for User-Agent header — optional, for polite API access'),
89
+ apiBaseUrl: z.url().default('https://api.biorxiv.org').describe('bioRxiv API base URL'),
90
+ europePmcBaseUrl: z.url().default('https://www.ebi.ac.uk/europepmc/webservices/rest').describe('EuropePMC API base URL'),
91
+ });
92
+
93
+ let _config: z.infer<typeof ServerConfigSchema> | undefined;
94
+ export function getServerConfig(): z.infer<typeof ServerConfigSchema> {
95
+ _config ??= parseEnvConfig(ServerConfigSchema, {
96
+ mailto: 'BIORXIV_MAILTO',
97
+ apiBaseUrl: 'BIORXIV_API_BASE_URL',
98
+ europePmcBaseUrl: 'EUROPEPMC_API_BASE_URL',
99
+ });
100
+ return _config;
101
+ }
102
+ ```
103
+
104
+ `parseEnvConfig` maps Zod schema paths → env var names so validation errors name the actual variable rather than the internal path.
105
+
106
+ ---
107
+
108
+ ## Context
109
+
110
+ Handlers receive a unified `ctx` object. Key properties:
111
+
112
+ | Property | Description |
113
+ |:---------|:------------|
114
+ | `ctx.log` | Request-scoped logger — `.debug()`, `.info()`, `.notice()`, `.warning()`, `.error()`. Auto-correlates requestId, traceId, tenantId. |
115
+ | `ctx.state` | Tenant-scoped KV — `.get(key)`, `.set(key, value, { ttl? })`, `.delete(key)`, `.list(prefix, { cursor, limit })`. Accepts any serializable value. |
116
+ | `ctx.recoveryFor(reason)` | Typed lookup of the contract `recovery` for a declared reason. Returns `{ recovery: { hint } }` for known reasons, `{}` otherwise. Spread into `ctx.fail` data to mirror the contract hint into `content[]`. |
117
+ | `ctx.signal` | `AbortSignal` for cancellation. |
118
+ | `ctx.requestId` | Unique request ID. |
119
+ | `ctx.tenantId` | Tenant ID from JWT, `'default'` for stdio or HTTP+`MCP_AUTH_MODE=none`. |
120
+
121
+ ---
122
+
123
+ ## Errors
124
+
125
+ Handlers throw — the framework catches, classifies, and formats.
126
+
127
+ **Recommended: typed error contract.** Declare `errors: [{ reason, code, when, recovery, retryable? }]` on `tool()` / `resource()` to receive a typed `ctx.fail(reason, …)` keyed by the declared reason union. TypeScript catches `ctx.fail('typo')` at compile time, `data.reason` is auto-populated for observability, and the linter enforces conformance against the handler body. The `recovery` field is required (≥ 5 words, lint-validated). Spread `ctx.recoveryFor('reason')` into `data` to mirror the contract recovery onto the wire. Baseline codes (`InternalError`, `ServiceUnavailable`, `Timeout`, `ValidationError`, `SerializationError`) bubble freely and don't need declaring.
128
+
129
+ ```ts
130
+ errors: [
131
+ { reason: 'doi_not_found', code: JsonRpcErrorCode.NotFound,
132
+ when: 'DOI resolves to empty collection on all requested servers',
133
+ recovery: 'Verify DOI format (must be 10.1101/…) and try again.' },
134
+ ],
135
+ async handler(input, ctx) {
136
+ const result = await getBiorxivApiService().getDetails(input.doi, input.server ?? 'both');
137
+ if (result.collection.length === 0) {
138
+ throw ctx.fail('doi_not_found', `DOI not found: ${input.doi}`, {
139
+ ...ctx.recoveryFor('doi_not_found'),
140
+ });
141
+ }
142
+ return result;
143
+ }
144
+ ```
145
+
146
+ **Fallback (no contract entry fits):** error factories or plain `Error`.
147
+
148
+ ```ts
149
+ import { notFound, serviceUnavailable } from '@cyanheads/mcp-ts-core/errors';
150
+ throw notFound('Preprint not found', { doi });
151
+ throw serviceUnavailable('api.biorxiv.org unreachable', { url }, { cause: err });
152
+ ```
153
+
154
+ See framework CLAUDE.md and the `api-errors` skill for the full auto-classification table, all factories, and the contract reference.
155
+
156
+ ---
157
+
158
+ ## Structure
159
+
160
+ ```text
161
+ src/
162
+ index.ts # createApp() entry point
163
+ config/
164
+ server-config.ts # bioRxiv-specific env vars (BIORXIV_MAILTO, API base URLs)
165
+ services/
166
+ biorxiv/
167
+ biorxiv-service.ts # BiorxivApiService — details, publications, pubs endpoints
168
+ types.ts # Domain types (Preprint, PublishedVersion, …)
169
+ europe-pmc/
170
+ europe-pmc-service.ts # EuropePmcService — preprint keyword search
171
+ types.ts # EuropePMC response types
172
+ mcp-server/
173
+ tools/definitions/
174
+ biorxiv-get-preprint.tool.ts
175
+ biorxiv-list-recent.tool.ts
176
+ biorxiv-search-preprints.tool.ts
177
+ biorxiv-get-published-version.tool.ts
178
+ biorxiv-list-categories.tool.ts
179
+ ```
180
+
181
+ ---
182
+
183
+ ## Naming
184
+
185
+ | What | Convention | Example |
186
+ |:-----|:-----------|:--------|
187
+ | Files | kebab-case with suffix | `biorxiv-get-preprint.tool.ts` |
188
+ | Tool/resource/prompt names | snake_case | `biorxiv_get_preprint` |
189
+ | Directories | kebab-case | `src/services/biorxiv/` |
190
+ | Descriptions | Single string or template literal, no `+` concatenation | `'Fetch preprint metadata by DOI.'` |
191
+
192
+ ---
193
+
194
+ ## Domain Conventions
195
+
196
+ - **DOI format:** `10.1101/YYYY.MM.DD.NNNNNN`. Validate on input — the bioRxiv API returns empty collections for malformed DOIs without an error code.
197
+ - **Server parameter:** `"biorxiv" | "medrxiv" | "both"`. Default to `"both"` for discovery tools, `"biorxiv"` for resolution tools. Fan-out via `Promise.allSettled` when `"both"`.
198
+ - **Pagination:** integer `cursor` offset (0, 30, 60, …). Page size is fixed at 30 by the API — do not expose a `limit` parameter.
199
+ - **Two-server pagination:** when `server="both"`, surface per-server state: `{ biorxiv: { cursor, total }, medrxiv: { cursor, total } }`. A merged cursor is ambiguous.
200
+ - **EuropePMC enrichment:** `biorxiv_search_preprints` uses EuropePMC for relevance then enriches matching DOIs via the details endpoint. `10.1101/` prefix identifies bioRxiv; skip the parallel medRxiv enrichment call for those DOIs.
201
+ - **`format()` must be content-complete:** Claude Desktop reads `content[]` from `format()`, not `structuredContent`. Revision list, crosswalk data, pagination state, and abstracts must all appear in the rendered markdown, not just counts.
202
+ - **Polite access:** include `BIORXIV_MAILTO` in the `User-Agent` header when set: `biorxiv-mcp-server/0.1.0 (mailto:${config.mailto})`. The env var is optional — omit the mailto segment when not configured.
203
+
204
+ ---
205
+
206
+ ## Skills
207
+
208
+ Skills are modular instructions in `skills/` at the project root. Read them directly when a task matches — e.g., `skills/add-tool/SKILL.md` when adding a tool.
209
+
210
+ **Agent skill directory:** Copy skills into the directory your agent discovers (Claude Code: `.claude/skills/`, others: equivalent). This makes skills available as context without needing to reference `skills/` paths manually. After framework updates, run the `maintenance` skill — it re-syncs the agent directory automatically (Phase B).
211
+
212
+ Available skills:
213
+
214
+ | Skill | Purpose |
215
+ |:------|:--------|
216
+ | `setup` | Post-init project orientation |
217
+ | `design-mcp-server` | Design tool surface, resources, and services for a new server |
218
+ | `add-tool` | Scaffold a new tool definition |
219
+ | `add-app-tool` | Scaffold an MCP App tool + paired UI resource |
220
+ | `add-resource` | Scaffold a new resource definition |
221
+ | `add-prompt` | Scaffold a new prompt definition |
222
+ | `add-service` | Scaffold a new service integration |
223
+ | `add-test` | Scaffold test file for a tool, resource, or service |
224
+ | `field-test` | Exercise tools/resources/prompts with real inputs, verify behavior, report issues |
225
+ | `security-pass` | Audit server for MCP-flavored security gaps: output injection, scope blast radius, input sinks, tenant isolation |
226
+ | `devcheck` | Lint, format, typecheck, audit |
227
+ | `polish-docs-meta` | Finalize docs, README, metadata, and agent protocol for shipping |
228
+ | `maintenance` | Investigate changelogs, adopt upstream changes, and sync skills after `bun update --latest` |
229
+ | `release-and-publish` | Ship a release: verification gate, push commits+tags, publish to npm / MCP Registry / GHCR |
230
+ | `api-auth` | Auth modes, scopes, JWT/OAuth |
231
+ | `api-canvas` | DataCanvas: register tabular data, run SQL, export, plus the `spillover()` helper for big result sets — Tier 3 opt-in |
232
+ | `api-config` | AppConfig, parseConfig, env vars |
233
+ | `api-context` | Context interface, logger, state, progress |
234
+ | `api-errors` | McpError, JsonRpcErrorCode, error patterns |
235
+ | `api-services` | LLM, Speech, Graph services |
236
+ | `api-telemetry` | OTel catalog: spans, metrics, completion logs, env config, cardinality rules |
237
+ | `api-testing` | createMockContext, test patterns |
238
+ | `api-utils` | Formatting, parsing, security, pagination, scheduling, telemetry helpers |
239
+ | `api-workers` | Cloudflare Workers runtime |
240
+ | `report-issue-framework` | File bug/feature request against @cyanheads/mcp-ts-core |
241
+ | `report-issue-local` | File bug/feature request against this server's repo |
242
+
243
+ When you complete a skill's checklist, check the boxes and add a completion timestamp at the end (e.g., `Completed: 2026-05-21`).
244
+
245
+ ---
246
+
247
+ ## Commands
248
+
249
+ | Command | Purpose |
250
+ |:--------|:--------|
251
+ | `bun run build` | Compile TypeScript |
252
+ | `bun run rebuild` | Clean + build |
253
+ | `bun run clean` | Remove build artifacts |
254
+ | `bun run devcheck` | Lint + format + typecheck + security + changelog sync |
255
+ | `bun run audit:refresh` | Delete `bun.lock`, reinstall, re-audit. Use when `devcheck` flags a transitive advisory — stale lockfile can mask already-patched deps. If advisory survives, it's real. |
256
+ | `bun run tree` | Generate directory structure doc |
257
+ | `bun run format` | Auto-fix formatting |
258
+ | `bun run test` | Run tests |
259
+ | `bun run lint:mcp` | Validate MCP definitions against spec |
260
+ | `bun run lint:packaging` | Verify env var alignment between `manifest.json` and `server.json` |
261
+ | `bun run bundle` | Build and pack as `.mcpb` for one-click Claude Desktop install |
262
+ | `bun run list-skills` | Surface available local skills for sub-agents |
263
+ | `bun run start:stdio` | Production mode (stdio) |
264
+ | `bun run start:http` | Production mode (HTTP) |
265
+ | `bun run changelog:build` | Regenerate `CHANGELOG.md` from `changelog/*.md` |
266
+ | `bun run changelog:check` | Verify `CHANGELOG.md` is in sync (used by devcheck) |
267
+
268
+ ---
269
+
270
+ ## Bundling
271
+
272
+ `bun run bundle` produces a `.mcpb` extension bundle for one-click install in Claude Desktop. MCPB is stdio-only — HTTP deployments are unaffected. Delete `manifest.json` and `.mcpbignore` to opt out; `lint:packaging` skips cleanly.
273
+
274
+ **Adding an env var requires both files:** `server.json` (`environmentVariables[]`) and `manifest.json` (`mcp_config.env` + `user_config`). `lint:packaging` (run by `devcheck`) verifies alignment.
275
+
276
+ ---
277
+
278
+ ## Imports
279
+
280
+ ```ts
281
+ // Framework — z is re-exported, no separate zod import needed
282
+ import { tool, z } from '@cyanheads/mcp-ts-core';
283
+ import { McpError, JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
284
+
285
+ // Server's own code — via path alias
286
+ import { getBiorxivApiService } from '@/services/biorxiv/biorxiv-service.js';
287
+ import { getEuropePmcService } from '@/services/europe-pmc/europe-pmc-service.js';
288
+ ```
289
+
290
+ ---
291
+
292
+ ## Checklist
293
+
294
+ - [ ] 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()`)
295
+ - [ ] Optional nested objects: handler guards for empty inner values from form-based clients (`if (input.obj?.field && ...)`, not just `if (input.obj)`)
296
+ - [ ] JSDoc `@fileoverview` + `@module` on every file
297
+ - [ ] `ctx.log` for logging, `ctx.state` for storage
298
+ - [ ] Handlers throw on failure — error factories or plain `Error`, no try/catch
299
+ - [ ] `format()` renders all data the LLM needs — different clients forward different surfaces (Claude Code → `structuredContent`, Claude Desktop → `content[]`); both must carry the same data — including revision list, crosswalk fields, abstract, and pagination state
300
+ - [ ] bioRxiv API wrapping: raw/domain/output schemas reviewed against real upstream sparsity/nullability before finalizing required vs optional fields
301
+ - [ ] bioRxiv API wrapping: normalization and `format()` preserve uncertainty; do not fabricate facts from missing upstream data (e.g., `published` field may be `"NA"` — surface it as absent, not empty)
302
+ - [ ] bioRxiv API wrapping: tests include at least one sparse payload case with omitted upstream fields
303
+ - [ ] `BIORXIV_MAILTO` included in outbound User-Agent header when set (optional env var)
304
+ - [ ] DOI format validated on input (`10.1101/` prefix check) before calling API
305
+ - [ ] Two-server fan-out uses `Promise.allSettled`; partial failures reported per-DOI in `failed[]`
306
+ - [ ] `biorxiv_list_recent` with `server="both"` surfaces per-server pagination state, not a merged cursor
307
+ - [ ] Registered in `createApp()` arrays (directly or via barrel exports)
308
+ - [ ] Tests use `createMockContext()` from `@cyanheads/mcp-ts-core/testing`
309
+ - [ ] `bun run devcheck` passes
package/CLAUDE.md ADDED
@@ -0,0 +1,309 @@
1
+ # Agent Protocol
2
+
3
+ **Server:** biorxiv-mcp-server
4
+ **Version:** 0.1.5
5
+ **Framework:** [@cyanheads/mcp-ts-core](https://www.npmjs.com/package/@cyanheads/mcp-ts-core) `^0.9.6`
6
+ **Engines:** Bun ≥1.3.2, Node ≥24.0.0
7
+ **MCP SDK:** `@modelcontextprotocol/sdk` ^1.29.0
8
+ **Zod:** ^4.4.3
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
+ ## What's Next?
15
+
16
+ When the user asks what to do next, what's left, or needs direction, suggest relevant options based on the current project state:
17
+
18
+ 1. **Re-run the `setup` skill** — ensures CLAUDE.md, skills, structure, and metadata are populated and up to date with the current codebase
19
+ 2. **Run the `design-mcp-server` skill** — if the tool/resource surface hasn't been mapped yet, work through domain design
20
+ 3. **Add tools/resources/prompts** — scaffold new definitions using the `add-tool`, `add-app-tool`, `add-resource`, `add-prompt` skills
21
+ 4. **Add services** — scaffold domain service integrations using the `add-service` skill
22
+ 5. **Add tests** — scaffold tests for existing definitions using the `add-test` skill
23
+ 6. **Field-test definitions** — exercise tools/resources/prompts with real inputs using the `field-test` skill, get a report of issues and pain points
24
+ 7. **Run `devcheck`** — lint, format, typecheck, and security audit
25
+ 8. **Run the `security-pass` skill** — audit handlers for MCP-specific security gaps: output injection, scope blast radius, input sinks, tenant isolation
26
+ 9. **Run the `polish-docs-meta` skill** — finalize README, CHANGELOG, metadata, and agent protocol for shipping
27
+ 10. **Run the `maintenance` skill** — investigate changelogs, adopt upstream changes, and sync skills after `bun update --latest`
28
+
29
+ Tailor suggestions to what's actually missing or stale — don't recite the full list every time.
30
+
31
+ ---
32
+
33
+ ## Core Rules
34
+
35
+ - **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.
36
+ - **Use `ctx.log`** for request-scoped logging. No `console` calls.
37
+ - **Use `ctx.state`** for tenant-scoped storage. Never access persistence directly.
38
+ - **Check `ctx.elicit` / `ctx.sample`** for presence before calling.
39
+ - **Secrets in env vars only** — never hardcoded.
40
+
41
+ ---
42
+
43
+ ## Patterns
44
+
45
+ ### Tool
46
+
47
+ ```ts
48
+ import { tool, z } from '@cyanheads/mcp-ts-core';
49
+ import { getBiorxivApiService } from '@/services/biorxiv/biorxiv-service.js';
50
+
51
+ export const listCategoriesTools = tool('biorxiv_list_categories', {
52
+ description: 'List valid subject category strings for bioRxiv and medRxiv.',
53
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
54
+
55
+ input: z.object({}),
56
+
57
+ output: z.object({
58
+ biorxiv: z.array(z.string().describe('Category name')).describe('bioRxiv subject categories'),
59
+ medrxiv: z.array(z.string().describe('Category name')).describe('medRxiv subject categories'),
60
+ }),
61
+
62
+ async handler(_input, ctx) {
63
+ ctx.log.info('Executing biorxiv_list_categories tool');
64
+ return getBiorxivApiService().getCategories();
65
+ },
66
+
67
+ format: (result) => [{
68
+ type: 'text',
69
+ text: [
70
+ '**bioRxiv categories:**',
71
+ result.biorxiv.map(c => `- ${c}`).join('\n'),
72
+ '',
73
+ '**medRxiv categories:**',
74
+ result.medrxiv.map(c => `- ${c}`).join('\n'),
75
+ ].join('\n'),
76
+ }],
77
+ });
78
+ ```
79
+
80
+ ### Server config
81
+
82
+ ```ts
83
+ // src/config/server-config.ts — lazy-parsed, separate from framework config
84
+ import { z } from '@cyanheads/mcp-ts-core';
85
+ import { parseEnvConfig } from '@cyanheads/mcp-ts-core/config';
86
+
87
+ const ServerConfigSchema = z.object({
88
+ mailto: z.email().optional().describe('Contact email for User-Agent header — optional, for polite API access'),
89
+ apiBaseUrl: z.url().default('https://api.biorxiv.org').describe('bioRxiv API base URL'),
90
+ europePmcBaseUrl: z.url().default('https://www.ebi.ac.uk/europepmc/webservices/rest').describe('EuropePMC API base URL'),
91
+ });
92
+
93
+ let _config: z.infer<typeof ServerConfigSchema> | undefined;
94
+ export function getServerConfig(): z.infer<typeof ServerConfigSchema> {
95
+ _config ??= parseEnvConfig(ServerConfigSchema, {
96
+ mailto: 'BIORXIV_MAILTO',
97
+ apiBaseUrl: 'BIORXIV_API_BASE_URL',
98
+ europePmcBaseUrl: 'EUROPEPMC_API_BASE_URL',
99
+ });
100
+ return _config;
101
+ }
102
+ ```
103
+
104
+ `parseEnvConfig` maps Zod schema paths → env var names so validation errors name the actual variable rather than the internal path.
105
+
106
+ ---
107
+
108
+ ## Context
109
+
110
+ Handlers receive a unified `ctx` object. Key properties:
111
+
112
+ | Property | Description |
113
+ |:---------|:------------|
114
+ | `ctx.log` | Request-scoped logger — `.debug()`, `.info()`, `.notice()`, `.warning()`, `.error()`. Auto-correlates requestId, traceId, tenantId. |
115
+ | `ctx.state` | Tenant-scoped KV — `.get(key)`, `.set(key, value, { ttl? })`, `.delete(key)`, `.list(prefix, { cursor, limit })`. Accepts any serializable value. |
116
+ | `ctx.recoveryFor(reason)` | Typed lookup of the contract `recovery` for a declared reason. Returns `{ recovery: { hint } }` for known reasons, `{}` otherwise. Spread into `ctx.fail` data to mirror the contract hint into `content[]`. |
117
+ | `ctx.signal` | `AbortSignal` for cancellation. |
118
+ | `ctx.requestId` | Unique request ID. |
119
+ | `ctx.tenantId` | Tenant ID from JWT, `'default'` for stdio or HTTP+`MCP_AUTH_MODE=none`. |
120
+
121
+ ---
122
+
123
+ ## Errors
124
+
125
+ Handlers throw — the framework catches, classifies, and formats.
126
+
127
+ **Recommended: typed error contract.** Declare `errors: [{ reason, code, when, recovery, retryable? }]` on `tool()` / `resource()` to receive a typed `ctx.fail(reason, …)` keyed by the declared reason union. TypeScript catches `ctx.fail('typo')` at compile time, `data.reason` is auto-populated for observability, and the linter enforces conformance against the handler body. The `recovery` field is required (≥ 5 words, lint-validated). Spread `ctx.recoveryFor('reason')` into `data` to mirror the contract recovery onto the wire. Baseline codes (`InternalError`, `ServiceUnavailable`, `Timeout`, `ValidationError`, `SerializationError`) bubble freely and don't need declaring.
128
+
129
+ ```ts
130
+ errors: [
131
+ { reason: 'doi_not_found', code: JsonRpcErrorCode.NotFound,
132
+ when: 'DOI resolves to empty collection on all requested servers',
133
+ recovery: 'Verify DOI format (must be 10.1101/…) and try again.' },
134
+ ],
135
+ async handler(input, ctx) {
136
+ const result = await getBiorxivApiService().getDetails(input.doi, input.server ?? 'both');
137
+ if (result.collection.length === 0) {
138
+ throw ctx.fail('doi_not_found', `DOI not found: ${input.doi}`, {
139
+ ...ctx.recoveryFor('doi_not_found'),
140
+ });
141
+ }
142
+ return result;
143
+ }
144
+ ```
145
+
146
+ **Fallback (no contract entry fits):** error factories or plain `Error`.
147
+
148
+ ```ts
149
+ import { notFound, serviceUnavailable } from '@cyanheads/mcp-ts-core/errors';
150
+ throw notFound('Preprint not found', { doi });
151
+ throw serviceUnavailable('api.biorxiv.org unreachable', { url }, { cause: err });
152
+ ```
153
+
154
+ See framework CLAUDE.md and the `api-errors` skill for the full auto-classification table, all factories, and the contract reference.
155
+
156
+ ---
157
+
158
+ ## Structure
159
+
160
+ ```text
161
+ src/
162
+ index.ts # createApp() entry point
163
+ config/
164
+ server-config.ts # bioRxiv-specific env vars (BIORXIV_MAILTO, API base URLs)
165
+ services/
166
+ biorxiv/
167
+ biorxiv-service.ts # BiorxivApiService — details, publications, pubs endpoints
168
+ types.ts # Domain types (Preprint, PublishedVersion, …)
169
+ europe-pmc/
170
+ europe-pmc-service.ts # EuropePmcService — preprint keyword search
171
+ types.ts # EuropePMC response types
172
+ mcp-server/
173
+ tools/definitions/
174
+ biorxiv-get-preprint.tool.ts
175
+ biorxiv-list-recent.tool.ts
176
+ biorxiv-search-preprints.tool.ts
177
+ biorxiv-get-published-version.tool.ts
178
+ biorxiv-list-categories.tool.ts
179
+ ```
180
+
181
+ ---
182
+
183
+ ## Naming
184
+
185
+ | What | Convention | Example |
186
+ |:-----|:-----------|:--------|
187
+ | Files | kebab-case with suffix | `biorxiv-get-preprint.tool.ts` |
188
+ | Tool/resource/prompt names | snake_case | `biorxiv_get_preprint` |
189
+ | Directories | kebab-case | `src/services/biorxiv/` |
190
+ | Descriptions | Single string or template literal, no `+` concatenation | `'Fetch preprint metadata by DOI.'` |
191
+
192
+ ---
193
+
194
+ ## Domain Conventions
195
+
196
+ - **DOI format:** `10.1101/YYYY.MM.DD.NNNNNN`. Validate on input — the bioRxiv API returns empty collections for malformed DOIs without an error code.
197
+ - **Server parameter:** `"biorxiv" | "medrxiv" | "both"`. Default to `"both"` for discovery tools, `"biorxiv"` for resolution tools. Fan-out via `Promise.allSettled` when `"both"`.
198
+ - **Pagination:** integer `cursor` offset (0, 30, 60, …). Page size is fixed at 30 by the API — do not expose a `limit` parameter.
199
+ - **Two-server pagination:** when `server="both"`, surface per-server state: `{ biorxiv: { cursor, total }, medrxiv: { cursor, total } }`. A merged cursor is ambiguous.
200
+ - **EuropePMC enrichment:** `biorxiv_search_preprints` uses EuropePMC for relevance then enriches matching DOIs via the details endpoint. `10.1101/` prefix identifies bioRxiv; skip the parallel medRxiv enrichment call for those DOIs.
201
+ - **`format()` must be content-complete:** Claude Desktop reads `content[]` from `format()`, not `structuredContent`. Revision list, crosswalk data, pagination state, and abstracts must all appear in the rendered markdown, not just counts.
202
+ - **Polite access:** include `BIORXIV_MAILTO` in the `User-Agent` header when set: `biorxiv-mcp-server/0.1.0 (mailto:${config.mailto})`. The env var is optional — omit the mailto segment when not configured.
203
+
204
+ ---
205
+
206
+ ## Skills
207
+
208
+ Skills are modular instructions in `skills/` at the project root. Read them directly when a task matches — e.g., `skills/add-tool/SKILL.md` when adding a tool.
209
+
210
+ **Agent skill directory:** Copy skills into the directory your agent discovers (Claude Code: `.claude/skills/`, others: equivalent). This makes skills available as context without needing to reference `skills/` paths manually. After framework updates, run the `maintenance` skill — it re-syncs the agent directory automatically (Phase B).
211
+
212
+ Available skills:
213
+
214
+ | Skill | Purpose |
215
+ |:------|:--------|
216
+ | `setup` | Post-init project orientation |
217
+ | `design-mcp-server` | Design tool surface, resources, and services for a new server |
218
+ | `add-tool` | Scaffold a new tool definition |
219
+ | `add-app-tool` | Scaffold an MCP App tool + paired UI resource |
220
+ | `add-resource` | Scaffold a new resource definition |
221
+ | `add-prompt` | Scaffold a new prompt definition |
222
+ | `add-service` | Scaffold a new service integration |
223
+ | `add-test` | Scaffold test file for a tool, resource, or service |
224
+ | `field-test` | Exercise tools/resources/prompts with real inputs, verify behavior, report issues |
225
+ | `security-pass` | Audit server for MCP-flavored security gaps: output injection, scope blast radius, input sinks, tenant isolation |
226
+ | `devcheck` | Lint, format, typecheck, audit |
227
+ | `polish-docs-meta` | Finalize docs, README, metadata, and agent protocol for shipping |
228
+ | `maintenance` | Investigate changelogs, adopt upstream changes, and sync skills after `bun update --latest` |
229
+ | `release-and-publish` | Ship a release: verification gate, push commits+tags, publish to npm / MCP Registry / GHCR |
230
+ | `api-auth` | Auth modes, scopes, JWT/OAuth |
231
+ | `api-canvas` | DataCanvas: register tabular data, run SQL, export, plus the `spillover()` helper for big result sets — Tier 3 opt-in |
232
+ | `api-config` | AppConfig, parseConfig, env vars |
233
+ | `api-context` | Context interface, logger, state, progress |
234
+ | `api-errors` | McpError, JsonRpcErrorCode, error patterns |
235
+ | `api-services` | LLM, Speech, Graph services |
236
+ | `api-telemetry` | OTel catalog: spans, metrics, completion logs, env config, cardinality rules |
237
+ | `api-testing` | createMockContext, test patterns |
238
+ | `api-utils` | Formatting, parsing, security, pagination, scheduling, telemetry helpers |
239
+ | `api-workers` | Cloudflare Workers runtime |
240
+ | `report-issue-framework` | File bug/feature request against @cyanheads/mcp-ts-core |
241
+ | `report-issue-local` | File bug/feature request against this server's repo |
242
+
243
+ When you complete a skill's checklist, check the boxes and add a completion timestamp at the end (e.g., `Completed: 2026-05-21`).
244
+
245
+ ---
246
+
247
+ ## Commands
248
+
249
+ | Command | Purpose |
250
+ |:--------|:--------|
251
+ | `bun run build` | Compile TypeScript |
252
+ | `bun run rebuild` | Clean + build |
253
+ | `bun run clean` | Remove build artifacts |
254
+ | `bun run devcheck` | Lint + format + typecheck + security + changelog sync |
255
+ | `bun run audit:refresh` | Delete `bun.lock`, reinstall, re-audit. Use when `devcheck` flags a transitive advisory — stale lockfile can mask already-patched deps. If advisory survives, it's real. |
256
+ | `bun run tree` | Generate directory structure doc |
257
+ | `bun run format` | Auto-fix formatting |
258
+ | `bun run test` | Run tests |
259
+ | `bun run lint:mcp` | Validate MCP definitions against spec |
260
+ | `bun run lint:packaging` | Verify env var alignment between `manifest.json` and `server.json` |
261
+ | `bun run bundle` | Build and pack as `.mcpb` for one-click Claude Desktop install |
262
+ | `bun run list-skills` | Surface available local skills for sub-agents |
263
+ | `bun run start:stdio` | Production mode (stdio) |
264
+ | `bun run start:http` | Production mode (HTTP) |
265
+ | `bun run changelog:build` | Regenerate `CHANGELOG.md` from `changelog/*.md` |
266
+ | `bun run changelog:check` | Verify `CHANGELOG.md` is in sync (used by devcheck) |
267
+
268
+ ---
269
+
270
+ ## Bundling
271
+
272
+ `bun run bundle` produces a `.mcpb` extension bundle for one-click install in Claude Desktop. MCPB is stdio-only — HTTP deployments are unaffected. Delete `manifest.json` and `.mcpbignore` to opt out; `lint:packaging` skips cleanly.
273
+
274
+ **Adding an env var requires both files:** `server.json` (`environmentVariables[]`) and `manifest.json` (`mcp_config.env` + `user_config`). `lint:packaging` (run by `devcheck`) verifies alignment.
275
+
276
+ ---
277
+
278
+ ## Imports
279
+
280
+ ```ts
281
+ // Framework — z is re-exported, no separate zod import needed
282
+ import { tool, z } from '@cyanheads/mcp-ts-core';
283
+ import { McpError, JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
284
+
285
+ // Server's own code — via path alias
286
+ import { getBiorxivApiService } from '@/services/biorxiv/biorxiv-service.js';
287
+ import { getEuropePmcService } from '@/services/europe-pmc/europe-pmc-service.js';
288
+ ```
289
+
290
+ ---
291
+
292
+ ## Checklist
293
+
294
+ - [ ] 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()`)
295
+ - [ ] Optional nested objects: handler guards for empty inner values from form-based clients (`if (input.obj?.field && ...)`, not just `if (input.obj)`)
296
+ - [ ] JSDoc `@fileoverview` + `@module` on every file
297
+ - [ ] `ctx.log` for logging, `ctx.state` for storage
298
+ - [ ] Handlers throw on failure — error factories or plain `Error`, no try/catch
299
+ - [ ] `format()` renders all data the LLM needs — different clients forward different surfaces (Claude Code → `structuredContent`, Claude Desktop → `content[]`); both must carry the same data — including revision list, crosswalk fields, abstract, and pagination state
300
+ - [ ] bioRxiv API wrapping: raw/domain/output schemas reviewed against real upstream sparsity/nullability before finalizing required vs optional fields
301
+ - [ ] bioRxiv API wrapping: normalization and `format()` preserve uncertainty; do not fabricate facts from missing upstream data (e.g., `published` field may be `"NA"` — surface it as absent, not empty)
302
+ - [ ] bioRxiv API wrapping: tests include at least one sparse payload case with omitted upstream fields
303
+ - [ ] `BIORXIV_MAILTO` included in outbound User-Agent header when set (optional env var)
304
+ - [ ] DOI format validated on input (`10.1101/` prefix check) before calling API
305
+ - [ ] Two-server fan-out uses `Promise.allSettled`; partial failures reported per-DOI in `failed[]`
306
+ - [ ] `biorxiv_list_recent` with `server="both"` surfaces per-server pagination state, not a merged cursor
307
+ - [ ] Registered in `createApp()` arrays (directly or via barrel exports)
308
+ - [ ] Tests use `createMockContext()` from `@cyanheads/mcp-ts-core/testing`
309
+ - [ ] `bun run devcheck` passes