@cyanheads/seerr-mcp-server 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/AGENTS.md +407 -0
  2. package/CLAUDE.md +407 -0
  3. package/Dockerfile +121 -0
  4. package/LICENSE +201 -0
  5. package/README.md +302 -0
  6. package/changelog/0.1.x/0.1.0.md +26 -0
  7. package/changelog/template.md +127 -0
  8. package/dist/config/server-config.d.ts +27 -0
  9. package/dist/config/server-config.d.ts.map +1 -0
  10. package/dist/config/server-config.js +45 -0
  11. package/dist/config/server-config.js.map +1 -0
  12. package/dist/index.d.ts +9 -0
  13. package/dist/index.d.ts.map +1 -0
  14. package/dist/index.js +24 -0
  15. package/dist/index.js.map +1 -0
  16. package/dist/mcp-server/resources/definitions/index.d.ts +47 -0
  17. package/dist/mcp-server/resources/definitions/index.d.ts.map +1 -0
  18. package/dist/mcp-server/resources/definitions/index.js +8 -0
  19. package/dist/mcp-server/resources/definitions/index.js.map +1 -0
  20. package/dist/mcp-server/resources/definitions/request.resource.d.ts +53 -0
  21. package/dist/mcp-server/resources/definitions/request.resource.d.ts.map +1 -0
  22. package/dist/mcp-server/resources/definitions/request.resource.js +70 -0
  23. package/dist/mcp-server/resources/definitions/request.resource.js.map +1 -0
  24. package/dist/mcp-server/tools/definitions/get-media.tool.d.ts +66 -0
  25. package/dist/mcp-server/tools/definitions/get-media.tool.d.ts.map +1 -0
  26. package/dist/mcp-server/tools/definitions/get-media.tool.js +197 -0
  27. package/dist/mcp-server/tools/definitions/get-media.tool.js.map +1 -0
  28. package/dist/mcp-server/tools/definitions/index.d.ts +341 -0
  29. package/dist/mcp-server/tools/definitions/index.d.ts.map +1 -0
  30. package/dist/mcp-server/tools/definitions/index.js +22 -0
  31. package/dist/mcp-server/tools/definitions/index.js.map +1 -0
  32. package/dist/mcp-server/tools/definitions/list-requests.tool.d.ts +76 -0
  33. package/dist/mcp-server/tools/definitions/list-requests.tool.d.ts.map +1 -0
  34. package/dist/mcp-server/tools/definitions/list-requests.tool.js +187 -0
  35. package/dist/mcp-server/tools/definitions/list-requests.tool.js.map +1 -0
  36. package/dist/mcp-server/tools/definitions/request-media.tool.d.ts +117 -0
  37. package/dist/mcp-server/tools/definitions/request-media.tool.d.ts.map +1 -0
  38. package/dist/mcp-server/tools/definitions/request-media.tool.js +347 -0
  39. package/dist/mcp-server/tools/definitions/request-media.tool.js.map +1 -0
  40. package/dist/mcp-server/tools/definitions/request-status.tool.d.ts +55 -0
  41. package/dist/mcp-server/tools/definitions/request-status.tool.d.ts.map +1 -0
  42. package/dist/mcp-server/tools/definitions/request-status.tool.js +111 -0
  43. package/dist/mcp-server/tools/definitions/request-status.tool.js.map +1 -0
  44. package/dist/mcp-server/tools/definitions/search-media.tool.d.ts +51 -0
  45. package/dist/mcp-server/tools/definitions/search-media.tool.d.ts.map +1 -0
  46. package/dist/mcp-server/tools/definitions/search-media.tool.js +167 -0
  47. package/dist/mcp-server/tools/definitions/search-media.tool.js.map +1 -0
  48. package/dist/mcp-server/tools/definitions/service-options.tool.d.ts +51 -0
  49. package/dist/mcp-server/tools/definitions/service-options.tool.d.ts.map +1 -0
  50. package/dist/mcp-server/tools/definitions/service-options.tool.js +195 -0
  51. package/dist/mcp-server/tools/definitions/service-options.tool.js.map +1 -0
  52. package/dist/services/seerr/errors.d.ts +33 -0
  53. package/dist/services/seerr/errors.d.ts.map +1 -0
  54. package/dist/services/seerr/errors.js +74 -0
  55. package/dist/services/seerr/errors.js.map +1 -0
  56. package/dist/services/seerr/normalizers.d.ts +111 -0
  57. package/dist/services/seerr/normalizers.d.ts.map +1 -0
  58. package/dist/services/seerr/normalizers.js +179 -0
  59. package/dist/services/seerr/normalizers.js.map +1 -0
  60. package/dist/services/seerr/seerr-service.d.ts +92 -0
  61. package/dist/services/seerr/seerr-service.d.ts.map +1 -0
  62. package/dist/services/seerr/seerr-service.js +187 -0
  63. package/dist/services/seerr/seerr-service.js.map +1 -0
  64. package/dist/services/seerr/status.d.ts +27 -0
  65. package/dist/services/seerr/status.d.ts.map +1 -0
  66. package/dist/services/seerr/status.js +70 -0
  67. package/dist/services/seerr/status.js.map +1 -0
  68. package/dist/services/seerr/types.d.ts +221 -0
  69. package/dist/services/seerr/types.d.ts.map +1 -0
  70. package/dist/services/seerr/types.js +11 -0
  71. package/dist/services/seerr/types.js.map +1 -0
  72. package/package.json +86 -0
  73. package/server.json +137 -0
package/AGENTS.md ADDED
@@ -0,0 +1,407 @@
1
+ # Developer Protocol
2
+
3
+ **Server:** seerr-mcp-server
4
+ **Version:** 0.1.0
5
+ **Framework:** [@cyanheads/mcp-ts-core](https://www.npmjs.com/package/@cyanheads/mcp-ts-core) `^0.10.6`
6
+ **Engines:** Bun ≥1.3.0, 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 This Server Does
15
+
16
+ A workflow MCP server over a self-hosted Jellyseerr/Overseerr instance: **search → confirm the TMDB-backed title → check availability/request state → create a guarded request** that Radarr/Sonarr act on. Jellyseerr owns permissions, quotas, routing, and status; this server never touches Radarr/Sonarr directly. Read + guarded-request only — admin-scope endpoints (approve/decline, retry, edit/delete, media/file deletion, user/settings/sync) are excluded by design.
17
+
18
+ **Surface:** six tools (`seerr_search_media`, `seerr_get_media`, `seerr_list_requests`, `seerr_request_media`, `seerr_request_status`, `seerr_service_options`) + one resource (`seerr://request/{requestId}`). No prompts.
19
+
20
+ **Two invariants that must never regress:**
21
+
22
+ 1. **Guarded write.** `seerr_request_media` is the only mutation. It defaults to `mode: preview` (resolve + validate, no POST); the real write fires only on `mode: request`, behind a `ctx.elicit` confirmation, with `destructiveHint: true` as the non-interactive fallback. Capability validation (4K/seasons/partial) runs locally against cached settings before any POST.
23
+ 2. **PII/infra redaction.** Every raw Jellyseerr payload is projected through `src/services/seerr/normalizers.ts` — the single choke point — before output. It allow-lists fields: `User` → `{ id, displayName }`, and drops operator email, Plex/Jellyfin tokens, `serviceUrl`, `vapidPublic`, and filesystem paths (gated behind `includePaths`). The base URL and API key live only in config and never appear in output. Redaction lives in normalizers, not `format()`, so both `structuredContent` and `content[]` are clean.
24
+
25
+ The authoritative tool surface, live API quirks, and status-decoding tables are in [`docs/design.md`](docs/design.md).
26
+
27
+ ---
28
+
29
+ ## Core Rules
30
+
31
+ - **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.
32
+ - **Use `ctx.log`** for request-scoped logging. No `console` calls.
33
+ - **Use `ctx.state`** for tenant-scoped storage. Never access persistence directly.
34
+ - **Check `ctx.elicit`** for presence before calling.
35
+ - **Secrets in env vars only** — never hardcoded.
36
+ - **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.
37
+
38
+ ---
39
+
40
+ ## Patterns
41
+
42
+ ### Tool
43
+
44
+ Real example, condensed from `src/mcp-server/tools/definitions/search-media.tool.ts`. Note the `title` is the hyphenated machine name prefix (`seerr-mcp-server: …`), statuses are `{ raw, label }` via `StatusRef`, and redaction happens in the normalizer (`redactAvailability`), never in `format()`.
45
+
46
+ ```ts
47
+ import { tool, z } from '@cyanheads/mcp-ts-core';
48
+ import { redactAvailability } from '@/services/seerr/normalizers.js';
49
+ import { getSeerrService } from '@/services/seerr/seerr-service.js';
50
+ import { StatusRef, statusText } from '@/services/seerr/status.js';
51
+
52
+ export const searchMediaTool = tool('seerr_search_media', {
53
+ title: 'seerr-mcp-server: search media',
54
+ description: 'Search movies and TV shows by title and return ranked matches ...',
55
+ annotations: { readOnlyHint: true, openWorldHint: true },
56
+ input: z.object({
57
+ query: z.string().min(1).describe('Title to search for, e.g. "Mulan".'),
58
+ mediaType: z.enum(['movie', 'tv', 'all']).default('all').describe('Restrict results ...'),
59
+ limit: z.number().int().min(1).max(20).default(10).describe('Max normalized results ...'),
60
+ }),
61
+ output: z.object({
62
+ results: z.array(z.object({
63
+ tmdbId: z.number().describe('TMDB ID — pass to seerr_get_media or seerr_request_media.'),
64
+ tracked: z.boolean().describe('True when Seerr already tracks this title.'),
65
+ availability: z.object({
66
+ status: StatusRef.describe('Decoded media availability {raw,label}.'),
67
+ }).optional().describe('Current Seerr availability; present only when tracked.'),
68
+ })).describe('Ranked movie/TV matches. Empty array when nothing matched.'),
69
+ }),
70
+ enrichment: { totalCount: z.number().describe('Total results before this page limit.') },
71
+
72
+ async handler(input, ctx) {
73
+ const seerr = getSeerrService();
74
+ const response = await seerr.search({ query: input.query }, ctx);
75
+ // ... filter to movie/tv, normalize, redact mediaInfo via redactAvailability ...
76
+ ctx.enrich.total(response.totalResults ?? 0);
77
+ ctx.log.info('Seerr search completed', { query: input.query });
78
+ return { results: [] };
79
+ },
80
+
81
+ // format() renders content[] (the markdown twin of structuredContent). Both surfaces
82
+ // must carry the same data — lint enforces every output field appears in the text.
83
+ format: (result) =>
84
+ [{ type: 'text', text: result.results.map((r) => `**${r.tmdbId}**`).join('\n') }],
85
+ });
86
+ ```
87
+
88
+ ### Resource
89
+
90
+ The one resource, from `src/mcp-server/resources/definitions/request.resource.ts`. It reuses the same `projectRequestDetail` redaction choke point as `seerr_request_status`, so the output is identical and equally PII-clean.
91
+
92
+ ```ts
93
+ import { resource, z } from '@cyanheads/mcp-ts-core';
94
+ import { JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
95
+ import { projectRequestDetail } from '@/services/seerr/normalizers.js';
96
+ import { getSeerrService } from '@/services/seerr/seerr-service.js';
97
+
98
+ export const seerrRequestResource = resource('seerr://request/{requestId}', {
99
+ name: 'seerr-request',
100
+ title: 'seerr-mcp-server: request',
101
+ description: 'Read-once summary of one Seerr media request by ID ...',
102
+ mimeType: 'application/json',
103
+ params: z.object({
104
+ requestId: z.string().regex(/^\d+$/).describe('Numeric Seerr request ID.'),
105
+ }),
106
+ errors: [
107
+ { reason: 'request_not_found', code: JsonRpcErrorCode.NotFound,
108
+ when: 'No request exists with the given ID (Seerr returns HTTP 404).',
109
+ recovery: 'List requests with seerr_list_requests to find a valid requestId, then retry.' },
110
+ ],
111
+ async handler(params, ctx) {
112
+ const seerr = getSeerrService();
113
+ const raw = await seerr.getRequest(Number.parseInt(params.requestId, 10), ctx);
114
+ return projectRequestDetail(raw);
115
+ },
116
+ });
117
+ ```
118
+
119
+ This server has no prompts — the guarded-write workflow lives in the tool, not a prompt template.
120
+
121
+ ### Server config
122
+
123
+ The real schema from `src/config/server-config.ts` — two required vars (base URL + API key) and an optional timeout.
124
+
125
+ ```ts
126
+ // src/config/server-config.ts — lazy-parsed, separate from framework config
127
+ import { z } from '@cyanheads/mcp-ts-core';
128
+ import { parseEnvConfig } from '@cyanheads/mcp-ts-core/config';
129
+
130
+ const ServerConfigSchema = z.object({
131
+ baseUrl: z.string().url().describe('Seerr instance base URL, e.g. http://host:5055. No /api/v1 suffix, no trailing slash.'),
132
+ apiKey: z.string().min(1).describe('Seerr API key (Settings → General → API Key). Sent as the X-Api-Key header.'),
133
+ requestTimeoutMs: z.coerce.number().int().positive().default(15000).describe('Per-request HTTP timeout in milliseconds.'),
134
+ });
135
+
136
+ let _config: z.infer<typeof ServerConfigSchema> | undefined;
137
+ export function getServerConfig() {
138
+ _config ??= parseEnvConfig(ServerConfigSchema, {
139
+ baseUrl: 'SEERR_BASE_URL',
140
+ apiKey: 'SEERR_API_KEY',
141
+ requestTimeoutMs: 'SEERR_REQUEST_TIMEOUT_MS',
142
+ });
143
+ return _config;
144
+ }
145
+ ```
146
+
147
+ `parseEnvConfig` maps Zod schema paths → env var names so errors name the variable (`SEERR_BASE_URL`) not the path (`baseUrl`). Throws `ConfigurationError`, which the framework prints as a clean startup banner.
148
+
149
+ 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.
150
+
151
+ ### Server identity and instructions
152
+
153
+ The real `createApp()` call from `src/index.ts`. The identity block is **`name` + `title` ONLY** — both the hyphenated machine name (`seerr-mcp-server`, never Title Case). `description` is NOT set here — it derives from `package.json` (the canonical source); `websiteUrl` is not an identity field for this server.
154
+
155
+ ```ts
156
+ await createApp({
157
+ name: 'seerr-mcp-server',
158
+ title: 'seerr-mcp-server',
159
+ tools: allToolDefinitions,
160
+ resources: allResourceDefinitions,
161
+ instructions:
162
+ 'Local Seerr request workflow. Search first (seerr_search_media), confirm the exact title ' +
163
+ '(seerr_get_media), then request via seerr_request_media — which defaults to mode:preview and ' +
164
+ 'only writes on mode:request. "Download X" means "create a Seerr request for X"; never bypass to Radarr/Sonarr.',
165
+ setup(core) {
166
+ initSeerrService(core.config, core.storage);
167
+ },
168
+ });
169
+ ```
170
+
171
+ `instructions` is optional server-level orientation, sent on every `initialize` as session-level context. Use it for deployment guidance instead of repeating the same context across tool descriptions. Client adoption is uneven, but there's no downside when set.
172
+
173
+ ---
174
+
175
+ ## Context
176
+
177
+ Handlers receive a unified `ctx` object. Key properties:
178
+
179
+ | Property | Description |
180
+ |:---------|:------------|
181
+ | `ctx.log` | Request-scoped logger — `.debug()`, `.info()`, `.notice()`, `.warning()`, `.error()`. Auto-correlates requestId, traceId, tenantId. |
182
+ | `ctx.state` | Tenant-scoped KV — used to cache `/settings/public` + `/status` with a short TTL so capability checks don't round-trip on every preview. |
183
+ | `ctx.elicit` | The guarded-write confirmation surface — `seerr_request_media` calls it on `mode: request` before the POST. **Check for presence first:** `if (ctx.elicit) { ... }` |
184
+ | `ctx.enrich` | Output enrichment — `.total(n)`, `.echo(query)`, `.truncated({ shown, cap })`, `.notice(msg)` for capped-list disclosure and effective-query echo. |
185
+ | `ctx.fail` / `ctx.recoveryFor` | Typed-error contract throw + recovery-metadata lookup against each tool's `errors[]`. |
186
+ | `ctx.signal` | `AbortSignal` for cancellation. |
187
+ | `ctx.requestId` | Unique request ID. |
188
+ | `ctx.tenantId` | Tenant ID from JWT or `'default'` for stdio. |
189
+
190
+ ---
191
+
192
+ ## Errors
193
+
194
+ Handlers throw — the framework catches, classifies, and formats.
195
+
196
+ **Recommended: typed error contract.** Declare `errors: [{ reason, code, when, recovery, retryable? }]` 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 descriptive metadata for the agent's next move (≥ 5 words, lint-validated); for the wire `data.recovery.hint` (mirrored into `content[]` text), pass explicitly at the throw site when dynamic context matters: `ctx.fail('reason', msg, { recovery: { hint: '...' } })`. Baseline codes (`InternalError`, `ServiceUnavailable`, `Timeout`, `ValidationError`, `SerializationError`) bubble freely and don't need declaring.
197
+
198
+ ```ts
199
+ import { JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
200
+
201
+ errors: [
202
+ { reason: 'no_match', code: JsonRpcErrorCode.NotFound,
203
+ when: 'No item matched the query',
204
+ recovery: 'Broaden the query or check the spelling and try again.' },
205
+ ],
206
+ async handler(input, ctx) {
207
+ const item = await db.find(input.id);
208
+ if (!item) throw ctx.fail('no_match', `No item ${input.id}`);
209
+ return item;
210
+ }
211
+ ```
212
+
213
+ **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.
214
+
215
+ **Fallback (no contract entry fits):** throw via factories or plain `Error`.
216
+
217
+ ```ts
218
+ // Error factories — explicit code
219
+ import { notFound, serviceUnavailable } from '@cyanheads/mcp-ts-core/errors';
220
+ throw notFound('Item not found', { itemId });
221
+ throw serviceUnavailable('API unavailable', { url }, { cause: err });
222
+
223
+ // Plain Error — framework auto-classifies from message patterns
224
+ throw new Error('Item not found'); // → NotFound
225
+ throw new Error('Invalid query format'); // → ValidationError
226
+
227
+ // McpError — when no factory exists for the code
228
+ import { McpError, JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
229
+ throw new McpError(JsonRpcErrorCode.DatabaseError, 'Connection failed', { pool: 'primary' });
230
+ ```
231
+
232
+ See framework CLAUDE.md and the `api-errors` skill for the full auto-classification table, all available factories, and the contract reference.
233
+
234
+ ---
235
+
236
+ ## Structure
237
+
238
+ ```text
239
+ src/
240
+ index.ts # createApp() entry point (name + title only)
241
+ config/
242
+ server-config.ts # SEERR_BASE_URL / SEERR_API_KEY / timeout (Zod schema)
243
+ services/
244
+ seerr/
245
+ seerr-service.ts # Jellyseerr REST client (init/accessor pattern)
246
+ status.ts # Pure status decoders → { raw, label }
247
+ normalizers.ts # PII/infra redaction choke point (the security boundary)
248
+ errors.ts # Upstream-error classifier (500 → media_not_found, 404 → request_not_found)
249
+ types.ts # Raw upstream + domain types
250
+ mcp-server/
251
+ tools/definitions/ # Six *.tool.ts + barrel
252
+ resources/definitions/ # request.resource.ts + barrel (no prompts/)
253
+ ```
254
+
255
+ ---
256
+
257
+ ## Naming
258
+
259
+ | What | Convention | Example |
260
+ |:-----|:-----------|:--------|
261
+ | Files | kebab-case with suffix | `search-docs.tool.ts` |
262
+ | Tool/resource/prompt names | snake_case | `search_docs` |
263
+ | Directories | kebab-case | `src/services/doc-search/` |
264
+ | Descriptions | Single string or template literal, no `+` concatenation | `'Search items by query and filter.'` |
265
+
266
+ ---
267
+
268
+ ## Skills
269
+
270
+ 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.
271
+
272
+ **Agent skill directory:** Copy skills into the directory your agent discovers (Claude Code: `.claude/skills/`, others: equivalent). Skills then load as context without referencing `skills/` paths. After framework updates, run the `maintenance` skill — Phase B re-syncs the agent directory.
273
+
274
+ Available skills:
275
+
276
+ | Skill | Purpose |
277
+ |:------|:--------|
278
+ | `setup` | Post-init project orientation |
279
+ | `design-mcp-server` | Design tool surface, resources, and services for a new server |
280
+ | `add-tool` | Scaffold a new tool definition |
281
+ | `add-app-tool` | Scaffold an MCP App tool + paired UI resource |
282
+ | `add-resource` | Scaffold a new resource definition |
283
+ | `add-prompt` | Scaffold a new prompt definition |
284
+ | `add-service` | Scaffold a new service integration |
285
+ | `add-test` | Scaffold test file for a tool, resource, or service |
286
+ | `field-test` | Exercise tools/resources/prompts with real inputs, verify behavior, report issues |
287
+ | `tool-defs-analysis` | Read-only audit of MCP definition language across the surface — voice, leaks, defaults, recovery hints, output descriptions |
288
+ | `techniques` | Catalog of reusable response/data-shaping patterns — overflow handling, payload shaping, retrieval |
289
+ | `security-pass` | Audit server for MCP-flavored security gaps: output injection, scope blast radius, input sinks, tenant isolation |
290
+ | `code-simplifier` | Post-session cleanup against `git diff` — modernize syntax, consolidate duplication, align with the codebase |
291
+ | `devcheck` | Lint, format, typecheck, audit |
292
+ | `polish-docs-meta` | Finalize docs, README, metadata, and agent protocol for shipping |
293
+ | `git-wrapup` | Land working-tree changes as a versioned commit + annotated tag — version bump, changelog, verify, tag. Local only. |
294
+ | `release-and-publish` | Push + npm + MCP Registry + GH Release + Docker. Picks up from `git-wrapup` |
295
+ | `maintenance` | Investigate changelogs, adopt upstream changes, sync skills to agent dirs |
296
+ | `orchestrations` | Chain task skills into a gated multi-phase pipeline — build-out, QA-fix, update-ship — when you can spawn sub-agents |
297
+ | `report-issue-framework` | File a bug or feature request against `@cyanheads/mcp-ts-core` via `gh` CLI |
298
+ | `report-issue-local` | File a bug or feature request against this server's own repo via `gh` CLI |
299
+ | `api-auth` | Auth modes, scopes, JWT/OAuth |
300
+ | `api-canvas` | DataCanvas: register tabular data, run SQL, export, plus the `spillover()` helper for big result sets — Tier 3 opt-in |
301
+ | `api-config` | AppConfig, parseConfig, env vars |
302
+ | `api-context` | Context interface, logger, state, progress |
303
+ | `api-errors` | McpError, JsonRpcErrorCode, error patterns |
304
+ | `api-linter` | Definition linter rule catalog — invoked by `bun run lint:mcp` and `devcheck` |
305
+ | `api-mirror` | MirrorService — persistent self-refreshing local mirror of a bulk upstream dataset (not used by this server) |
306
+ | `api-services` | LLM, Speech, Graph services |
307
+ | `api-testing` | createMockContext, test patterns |
308
+ | `api-utils` | Formatting, parsing, security, pagination, scheduling, telemetry helpers |
309
+ | `api-telemetry` | OTel catalog: spans, metrics, completion logs, env config, cardinality rules |
310
+ | `api-workers` | Cloudflare Workers runtime |
311
+
312
+ **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*, `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.
313
+
314
+ When you complete a skill's checklist, check the boxes and add a completion timestamp at the end (e.g., `Completed: 2026-03-11`).
315
+
316
+ ---
317
+
318
+ ## Commands
319
+
320
+ **Runtime:** Scripts use Bun's native TypeScript execution — `bun run <cmd>` is the standard invocation. `npm run <cmd>` also works (npm delegates to bun).
321
+
322
+ | Command | Purpose |
323
+ |:--------|:--------|
324
+ | `npm run build` | Compile TypeScript |
325
+ | `npm run rebuild` | Clean + build |
326
+ | `npm run clean` | Remove build artifacts |
327
+ | `npm run devcheck` | Lint + format + typecheck + security + changelog sync |
328
+ | `bun run audit:refresh` | Delete `bun.lock`, reinstall, and re-run `bun audit`. Use when `devcheck` flags a transitive advisory — Bun's `update` is sticky on transitive resolutions, so the advisory may be a stale-lockfile false positive. If it survives the refresh, it's real. |
329
+ | `npm run tree` | Generate directory structure doc |
330
+ | `npm run format` | Auto-fix formatting (safe fixes only) |
331
+ | `npm run format:unsafe` | Also apply Biome's unsafe autofixes — review the diff; they can change behavior |
332
+ | `npm test` | Run tests |
333
+ | `npm run start:stdio` | Production mode (stdio) |
334
+ | `npm run start:http` | Production mode (HTTP) |
335
+ | `npm run changelog:build` | Regenerate `CHANGELOG.md` from `changelog/*.md` |
336
+ | `npm run changelog:check` | Verify `CHANGELOG.md` is in sync (used by devcheck) |
337
+ | `npm run bundle` | Build, pack, and clean a `.mcpb` for one-click Claude Desktop install |
338
+
339
+ ---
340
+
341
+ ## Bundling
342
+
343
+ `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 dependency-shipped agent docs (`node_modules/**` `skills/`, `.claude/`, `.agents/`, `SKILL.md`) that root-anchored `.mcpbignore` patterns cannot reach. 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.
344
+
345
+ **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.
346
+
347
+ **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 `skills/polish-docs-meta/references/readme.md`.
348
+
349
+ ---
350
+
351
+ ## Changelog
352
+
353
+ 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.
354
+
355
+ Each per-version file opens with YAML frontmatter:
356
+
357
+ ```markdown
358
+ ---
359
+ summary: "One-line headline, ≤350 chars" # required — powers the rollup index
360
+ breaking: false # optional — true flags breaking changes
361
+ security: false # optional — true flags security fixes
362
+ ---
363
+
364
+ # 0.1.0 — YYYY-MM-DD
365
+ ...
366
+ ```
367
+
368
+ `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. When both are set, badges render `· ⚠️ Breaking · 🛡️ Security`.
369
+
370
+ `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.
371
+
372
+ **Section order** (Keep a Changelog): Added, Changed, Deprecated, Removed, Fixed, Security. Include only sections with entries — don't ship empty headers.
373
+
374
+ **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.
375
+
376
+ ---
377
+
378
+ ## Imports
379
+
380
+ ```ts
381
+ // Framework — z is re-exported, no separate zod import needed
382
+ import { tool, z } from '@cyanheads/mcp-ts-core';
383
+ import { McpError, JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
384
+
385
+ // Server's own code — via path alias
386
+ import { getMyService } from '@/services/my-domain/my-service.js';
387
+ ```
388
+
389
+ ---
390
+
391
+ ## Checklist
392
+
393
+ - [ ] 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()`)
394
+ - [ ] 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`.
395
+ - [ ] JSDoc `@fileoverview` + `@module` on every file
396
+ - [ ] `ctx.log` for logging, `ctx.state` for storage
397
+ - [ ] Handlers throw on failure — error factories or plain `Error`, no try/catch
398
+ - [ ] `format()` renders all data the LLM needs — different clients forward different surfaces (Claude Code → `structuredContent`, Claude Desktop → `content[]`); both must carry the same data
399
+ - [ ] If wrapping external API: raw/domain/output schemas reviewed against real upstream sparsity/nullability before finalizing required vs optional fields
400
+ - [ ] If wrapping external API: normalization and `format()` preserve uncertainty; do not fabricate facts from missing upstream data
401
+ - [ ] If wrapping external API: tests include at least one sparse payload case with omitted upstream fields
402
+ - [ ] Registered in `createApp()` arrays (directly or via barrel exports)
403
+ - [ ] Tests use `createMockContext()` from `@cyanheads/mcp-ts-core/testing`
404
+ - [ ] `.codex-plugin/plugin.json` populated — `name`, `version`, `description`, `repository`, `license` from `package.json`; `interface.displayName` = package name; `interface.shortDescription` from `package.json` description
405
+ - [ ] `.codex-plugin/mcp.json` updated — server name key matches `package.json` name; env vars added for any required API keys
406
+ - [ ] `.claude-plugin/plugin.json` populated — `name`, `version`, `description`, `repository`, `license` from `package.json`; inline `mcpServers` entry with server name key, env vars for any required API keys
407
+ - [ ] `npm run devcheck` passes