@cyanheads/noaa-spaceweather-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 (49) hide show
  1. package/AGENTS.md +328 -0
  2. package/CLAUDE.md +328 -0
  3. package/Dockerfile +99 -0
  4. package/LICENSE +201 -0
  5. package/README.md +315 -0
  6. package/changelog/0.1.x/0.1.1.md +31 -0
  7. package/changelog/template.md +127 -0
  8. package/dist/index.d.ts +7 -0
  9. package/dist/index.d.ts.map +1 -0
  10. package/dist/index.js +23 -0
  11. package/dist/index.js.map +1 -0
  12. package/dist/mcp-server/tools/definitions/get-alerts.tool.d.ts +37 -0
  13. package/dist/mcp-server/tools/definitions/get-alerts.tool.d.ts.map +1 -0
  14. package/dist/mcp-server/tools/definitions/get-alerts.tool.js +114 -0
  15. package/dist/mcp-server/tools/definitions/get-alerts.tool.js.map +1 -0
  16. package/dist/mcp-server/tools/definitions/get-aurora-forecast.tool.d.ts +37 -0
  17. package/dist/mcp-server/tools/definitions/get-aurora-forecast.tool.d.ts.map +1 -0
  18. package/dist/mcp-server/tools/definitions/get-aurora-forecast.tool.js +202 -0
  19. package/dist/mcp-server/tools/definitions/get-aurora-forecast.tool.js.map +1 -0
  20. package/dist/mcp-server/tools/definitions/get-conditions.tool.d.ts +55 -0
  21. package/dist/mcp-server/tools/definitions/get-conditions.tool.d.ts.map +1 -0
  22. package/dist/mcp-server/tools/definitions/get-conditions.tool.js +129 -0
  23. package/dist/mcp-server/tools/definitions/get-conditions.tool.js.map +1 -0
  24. package/dist/mcp-server/tools/definitions/get-kp-index.tool.d.ts +34 -0
  25. package/dist/mcp-server/tools/definitions/get-kp-index.tool.d.ts.map +1 -0
  26. package/dist/mcp-server/tools/definitions/get-kp-index.tool.js +126 -0
  27. package/dist/mcp-server/tools/definitions/get-kp-index.tool.js.map +1 -0
  28. package/dist/mcp-server/tools/definitions/get-solar-activity.tool.d.ts +58 -0
  29. package/dist/mcp-server/tools/definitions/get-solar-activity.tool.d.ts.map +1 -0
  30. package/dist/mcp-server/tools/definitions/get-solar-activity.tool.js +237 -0
  31. package/dist/mcp-server/tools/definitions/get-solar-activity.tool.js.map +1 -0
  32. package/dist/mcp-server/tools/definitions/get-solar-wind.tool.d.ts +46 -0
  33. package/dist/mcp-server/tools/definitions/get-solar-wind.tool.d.ts.map +1 -0
  34. package/dist/mcp-server/tools/definitions/get-solar-wind.tool.js +197 -0
  35. package/dist/mcp-server/tools/definitions/get-solar-wind.tool.js.map +1 -0
  36. package/dist/mcp-server/tools/definitions/index.d.ts +225 -0
  37. package/dist/mcp-server/tools/definitions/index.d.ts.map +1 -0
  38. package/dist/mcp-server/tools/definitions/index.js +19 -0
  39. package/dist/mcp-server/tools/definitions/index.js.map +1 -0
  40. package/dist/services/space-weather/space-weather-service.d.ts +42 -0
  41. package/dist/services/space-weather/space-weather-service.d.ts.map +1 -0
  42. package/dist/services/space-weather/space-weather-service.js +402 -0
  43. package/dist/services/space-weather/space-weather-service.js.map +1 -0
  44. package/dist/services/space-weather/types.d.ts +189 -0
  45. package/dist/services/space-weather/types.d.ts.map +1 -0
  46. package/dist/services/space-weather/types.js +6 -0
  47. package/dist/services/space-weather/types.js.map +1 -0
  48. package/package.json +105 -0
  49. package/server.json +99 -0
package/AGENTS.md ADDED
@@ -0,0 +1,328 @@
1
+ # Developer Protocol
2
+
3
+ **Server:** noaa-spaceweather-mcp-server
4
+ **Version:** 0.1.1
5
+ **Framework:** [@cyanheads/mcp-ts-core](https://www.npmjs.com/package/@cyanheads/mcp-ts-core) `^0.9.21`
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's Next?
15
+
16
+ When the user asks what's next or needs direction, suggest options based on the current project state. Common next steps:
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
+ - **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.
41
+
42
+ ---
43
+
44
+ ## Patterns
45
+
46
+ ### Tool
47
+
48
+ ```ts
49
+ import { tool, z } from '@cyanheads/mcp-ts-core';
50
+
51
+ export const getConditions = tool('noaa_spaceweather_get_conditions', {
52
+ description: 'Current space-weather snapshot: NOAA R/S/G storm scales (today + 3-day forecast), latest Kp index, and a plain-language status summary.',
53
+ annotations: { readOnlyHint: true, openWorldHint: true },
54
+ input: z.object({}),
55
+ output: z.object({
56
+ observed_time: z.string().describe('Timestamp of the most recent data update (ISO 8601 UTC)'),
57
+ status_summary: z.string().describe('Plain-language summary of current conditions'),
58
+ current_kp: z.number().describe('Current planetary K-index (0–9)'),
59
+ geomagnetic: z.object({
60
+ scale: z.number().describe('Current G-scale level (0–5)'),
61
+ text: z.string().describe('G-scale descriptor and aurora-latitude guidance'),
62
+ }).describe('Current geomagnetic storm level'),
63
+ // ... additional fields
64
+ }),
65
+
66
+ errors: [
67
+ {
68
+ reason: 'feed_unavailable',
69
+ code: JsonRpcErrorCode.ServiceUnavailable,
70
+ when: 'SWPC endpoint returns non-OK or times out',
71
+ recovery: 'Retry in 30–60 s; SWPC feeds occasionally lag during high-activity events.',
72
+ },
73
+ ],
74
+
75
+ async handler(_input, ctx) {
76
+ const svc = getSpaceWeatherService();
77
+ const [scales, kpObserved] = await Promise.all([
78
+ svc.getNoaaScales(),
79
+ svc.getKpObserved(1),
80
+ ]);
81
+ ctx.log.info('Conditions fetched', { kp: kpObserved[0]?.kp });
82
+ return buildConditionsResponse(scales, kpObserved);
83
+ },
84
+
85
+ format: (result) => [{
86
+ type: 'text',
87
+ text: `**Space Weather Status** — ${result.observed_time}\n\n${result.status_summary}`,
88
+ }],
89
+ });
90
+ ```
91
+
92
+ ### Server instructions
93
+
94
+ `createApp({ instructions })` — this server sets server-level orientation for SWPC feed guidance (start with `get_conditions`, use `get_solar_wind` for Bz monitoring, feed cadences). Sent on every `initialize`; client adoption varies.
95
+
96
+ ---
97
+
98
+ ## Context
99
+
100
+ Handlers receive a unified `ctx` object. Key properties:
101
+
102
+ | Property | Description |
103
+ |:---------|:------------|
104
+ | `ctx.log` | Request-scoped logger — `.debug()`, `.info()`, `.notice()`, `.warning()`, `.error()`. Auto-correlates requestId, traceId, tenantId. |
105
+ | `ctx.fail` | Typed error thrower — `ctx.fail('reason', message, opts?)` maps to declared `errors[]` contract. |
106
+ | `ctx.enrich` | Attach advisory notices to a successful response — `ctx.enrich.notice(title, text)`. |
107
+ | `ctx.recoveryFor` | Spread into an error options object to attach the declared recovery hint: `...ctx.recoveryFor('reason')`. |
108
+ | `ctx.signal` | `AbortSignal` for cancellation. |
109
+ | `ctx.requestId` | Unique request ID. |
110
+ | `ctx.tenantId` | Tenant ID from JWT or `'default'` for stdio. |
111
+
112
+ ---
113
+
114
+ ## Errors
115
+
116
+ Handlers throw — the framework catches, classifies, and formats.
117
+
118
+ **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.
119
+
120
+ ```ts
121
+ import { JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
122
+
123
+ errors: [
124
+ { reason: 'no_match', code: JsonRpcErrorCode.NotFound,
125
+ when: 'No item matched the query',
126
+ recovery: 'Broaden the query or check the spelling and try again.' },
127
+ ],
128
+ async handler(input, ctx) {
129
+ const item = await db.find(input.id);
130
+ if (!item) throw ctx.fail('no_match', `No item ${input.id}`);
131
+ return item;
132
+ }
133
+ ```
134
+
135
+ **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.
136
+
137
+ **Fallback (no contract entry fits):** throw via factories or plain `Error`.
138
+
139
+ ```ts
140
+ // Error factories — explicit code
141
+ import { notFound, serviceUnavailable } from '@cyanheads/mcp-ts-core/errors';
142
+ throw notFound('Item not found', { itemId });
143
+ throw serviceUnavailable('API unavailable', { url }, { cause: err });
144
+
145
+ // Plain Error — framework auto-classifies from message patterns
146
+ throw new Error('Item not found'); // → NotFound
147
+ throw new Error('Invalid query format'); // → ValidationError
148
+
149
+ // McpError — when no factory exists for the code
150
+ import { McpError, JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
151
+ throw new McpError(JsonRpcErrorCode.DatabaseError, 'Connection failed', { pool: 'primary' });
152
+ ```
153
+
154
+ See framework CLAUDE.md and the `api-errors` skill for the full auto-classification table, all available factories, and the contract reference.
155
+
156
+ ---
157
+
158
+ ## Structure
159
+
160
+ ```text
161
+ src/
162
+ index.ts # createApp() entry point
163
+ services/
164
+ space-weather/
165
+ space-weather-service.ts # NOAA SWPC feed client + normalization
166
+ types.ts # Domain types (KpRecord, ScaleEntry, etc.)
167
+ mcp-server/
168
+ tools/definitions/
169
+ get-conditions.tool.ts # noaa_spaceweather_get_conditions
170
+ get-kp-index.tool.ts # noaa_spaceweather_get_kp_index
171
+ get-aurora-forecast.tool.ts # noaa_spaceweather_get_aurora_forecast
172
+ get-solar-wind.tool.ts # noaa_spaceweather_get_solar_wind
173
+ get-solar-activity.tool.ts # noaa_spaceweather_get_solar_activity
174
+ get-alerts.tool.ts # noaa_spaceweather_get_alerts
175
+ index.ts # Barrel — allToolDefinitions
176
+ ```
177
+
178
+ ---
179
+
180
+ ## Naming
181
+
182
+ | What | Convention | Example |
183
+ |:-----|:-----------|:--------|
184
+ | Files | kebab-case with suffix | `search-docs.tool.ts` |
185
+ | Tool/resource/prompt names | snake_case | `search_docs` |
186
+ | Directories | kebab-case | `src/services/doc-search/` |
187
+ | Descriptions | Single string or template literal, no `+` concatenation | `'Search items by query and filter.'` |
188
+
189
+ ---
190
+
191
+ ## Skills
192
+
193
+ 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.
194
+
195
+ **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.
196
+
197
+ Available skills:
198
+
199
+ | Skill | Purpose |
200
+ |:------|:--------|
201
+ | `setup` | Post-init project orientation |
202
+ | `design-mcp-server` | Design tool surface, resources, and services for a new server |
203
+ | `add-tool` | Scaffold a new tool definition |
204
+ | `add-app-tool` | Scaffold an MCP App tool + paired UI resource |
205
+ | `add-resource` | Scaffold a new resource definition |
206
+ | `add-prompt` | Scaffold a new prompt definition |
207
+ | `add-service` | Scaffold a new service integration |
208
+ | `add-test` | Scaffold test file for a tool, resource, or service |
209
+ | `field-test` | Exercise tools/resources/prompts with real inputs, verify behavior, report issues |
210
+ | `tool-defs-analysis` | Read-only audit of MCP definition language across the surface — voice, leaks, defaults, recovery hints, output descriptions |
211
+ | `security-pass` | Audit server for MCP-flavored security gaps: output injection, scope blast radius, input sinks, tenant isolation |
212
+ | `code-simplifier` | Post-session cleanup against `git diff` — modernize syntax, consolidate duplication, align with the codebase |
213
+ | `devcheck` | Lint, format, typecheck, audit |
214
+ | `polish-docs-meta` | Finalize docs, README, metadata, and agent protocol for shipping |
215
+ | `git-wrapup` | Land working-tree changes as a versioned commit + annotated tag — version bump, changelog, verify, tag. Local only. |
216
+ | `release-and-publish` | Push + npm + MCP Registry + GH Release + Docker. Picks up from `git-wrapup` |
217
+ | `maintenance` | Investigate changelogs, adopt upstream changes, sync skills to agent dirs |
218
+ | `orchestrations` | Chain task skills into a gated multi-phase pipeline — build-out, QA-fix, update-ship — when you can spawn sub-agents |
219
+ | `report-issue-framework` | File a bug or feature request against `@cyanheads/mcp-ts-core` via `gh` CLI |
220
+ | `report-issue-local` | File a bug or feature request against this server's own repo via `gh` CLI |
221
+ | `api-auth` | Auth modes, scopes, JWT/OAuth |
222
+ | `api-canvas` | DataCanvas: register tabular data, run SQL, export, plus the `spillover()` helper for big result sets — Tier 3 opt-in |
223
+ | `api-config` | AppConfig, parseConfig, env vars |
224
+ | `api-context` | Context interface, logger, state, progress |
225
+ | `api-errors` | McpError, JsonRpcErrorCode, error patterns |
226
+ | `api-linter` | Definition linter rule catalog — invoked by `bun run lint:mcp` and `devcheck` |
227
+ | `api-services` | LLM, Speech, Graph services |
228
+ | `api-testing` | createMockContext, test patterns |
229
+ | `api-utils` | Formatting, parsing, security, pagination, scheduling, telemetry helpers |
230
+ | `api-telemetry` | OTel catalog: spans, metrics, completion logs, env config, cardinality rules |
231
+ | `api-workers` | Cloudflare Workers runtime |
232
+
233
+ **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.
234
+
235
+ When you complete a skill's checklist, check the boxes and add a completion timestamp at the end (e.g., `Completed: 2026-03-11`).
236
+
237
+ ---
238
+
239
+ ## Commands
240
+
241
+ **Runtime:** Scripts use `bun run` — both `npm run <cmd>` and `bun run <cmd>` work.
242
+
243
+ | Command | Purpose |
244
+ |:--------|:--------|
245
+ | `bun run build` | Compile TypeScript |
246
+ | `bun run rebuild` | Clean + build |
247
+ | `bun run clean` | Remove build artifacts |
248
+ | `bun run devcheck` | Lint + format + typecheck + security + changelog sync |
249
+ | `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. |
250
+ | `bun run tree` | Generate directory structure doc |
251
+ | `bun run format` | Auto-fix formatting (safe fixes only) |
252
+ | `bun run format:unsafe` | Also apply Biome's unsafe autofixes — review the diff; they can change behavior |
253
+ | `bun run test` | Run tests |
254
+ | `bun run start:stdio` | Production mode (stdio) |
255
+ | `bun run start:http` | Production mode (HTTP) |
256
+ | `bun run changelog:build` | Regenerate `CHANGELOG.md` from `changelog/*.md` |
257
+ | `bun run changelog:check` | Verify `CHANGELOG.md` is in sync (used by devcheck) |
258
+ | `bun run bundle` | Build and pack as `.mcpb` for one-click Claude Desktop install |
259
+
260
+ ---
261
+
262
+ ## Bundling
263
+
264
+ `npm run bundle` produces a `.mcpb` extension bundle for one-click install in Claude Desktop. 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.
265
+
266
+ **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.
267
+
268
+ **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`.
269
+
270
+ ---
271
+
272
+ ## Changelog
273
+
274
+ 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.
275
+
276
+ Each per-version file opens with YAML frontmatter:
277
+
278
+ ```markdown
279
+ ---
280
+ summary: "One-line headline, ≤350 chars" # required — powers the rollup index
281
+ breaking: false # optional — true flags breaking changes
282
+ security: false # optional — true flags security fixes
283
+ ---
284
+
285
+ # 0.1.0 — YYYY-MM-DD
286
+ ...
287
+ ```
288
+
289
+ `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`.
290
+
291
+ `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.
292
+
293
+ **Section order** (Keep a Changelog): Added, Changed, Deprecated, Removed, Fixed, Security. Include only sections with entries — don't ship empty headers.
294
+
295
+ **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.
296
+
297
+ ---
298
+
299
+ ## Imports
300
+
301
+ ```ts
302
+ // Framework — z is re-exported, no separate zod import needed
303
+ import { tool, z } from '@cyanheads/mcp-ts-core';
304
+ import { McpError, JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
305
+
306
+ // Server's own code — via path alias
307
+ import { getMyService } from '@/services/my-domain/my-service.js';
308
+ ```
309
+
310
+ ---
311
+
312
+ ## Checklist
313
+
314
+ - [ ] 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()`)
315
+ - [ ] 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`.
316
+ - [ ] JSDoc `@fileoverview` + `@module` on every file
317
+ - [ ] `ctx.log` for logging, `ctx.state` for storage
318
+ - [ ] Handlers throw on failure — error factories or plain `Error`, no try/catch
319
+ - [ ] `format()` renders all data the LLM needs — different clients forward different surfaces (Claude Code → `structuredContent`, Claude Desktop → `content[]`); both must carry the same data
320
+ - [ ] If wrapping external API: raw/domain/output schemas reviewed against real upstream sparsity/nullability before finalizing required vs optional fields
321
+ - [ ] If wrapping external API: normalization and `format()` preserve uncertainty; do not fabricate facts from missing upstream data
322
+ - [ ] If wrapping external API: tests include at least one sparse payload case with omitted upstream fields
323
+ - [ ] Registered in `createApp()` arrays (directly or via barrel exports)
324
+ - [ ] Tests use `createMockContext()` from `@cyanheads/mcp-ts-core/testing`
325
+ - [ ] `.codex-plugin/plugin.json` populated — `name`, `version`, `description`, `repository`, `license` from `package.json`; `interface.displayName` = package name; `interface.shortDescription` from `package.json` description
326
+ - [ ] `.codex-plugin/mcp.json` updated — server name key matches `package.json` name; env vars added for any required API keys
327
+ - [ ] `.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
328
+ - [ ] `npm run devcheck` passes
package/CLAUDE.md ADDED
@@ -0,0 +1,328 @@
1
+ # Developer Protocol
2
+
3
+ **Server:** noaa-spaceweather-mcp-server
4
+ **Version:** 0.1.1
5
+ **Framework:** [@cyanheads/mcp-ts-core](https://www.npmjs.com/package/@cyanheads/mcp-ts-core) `^0.9.21`
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's Next?
15
+
16
+ When the user asks what's next or needs direction, suggest options based on the current project state. Common next steps:
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
+ - **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.
41
+
42
+ ---
43
+
44
+ ## Patterns
45
+
46
+ ### Tool
47
+
48
+ ```ts
49
+ import { tool, z } from '@cyanheads/mcp-ts-core';
50
+
51
+ export const getConditions = tool('noaa_spaceweather_get_conditions', {
52
+ description: 'Current space-weather snapshot: NOAA R/S/G storm scales (today + 3-day forecast), latest Kp index, and a plain-language status summary.',
53
+ annotations: { readOnlyHint: true, openWorldHint: true },
54
+ input: z.object({}),
55
+ output: z.object({
56
+ observed_time: z.string().describe('Timestamp of the most recent data update (ISO 8601 UTC)'),
57
+ status_summary: z.string().describe('Plain-language summary of current conditions'),
58
+ current_kp: z.number().describe('Current planetary K-index (0–9)'),
59
+ geomagnetic: z.object({
60
+ scale: z.number().describe('Current G-scale level (0–5)'),
61
+ text: z.string().describe('G-scale descriptor and aurora-latitude guidance'),
62
+ }).describe('Current geomagnetic storm level'),
63
+ // ... additional fields
64
+ }),
65
+
66
+ errors: [
67
+ {
68
+ reason: 'feed_unavailable',
69
+ code: JsonRpcErrorCode.ServiceUnavailable,
70
+ when: 'SWPC endpoint returns non-OK or times out',
71
+ recovery: 'Retry in 30–60 s; SWPC feeds occasionally lag during high-activity events.',
72
+ },
73
+ ],
74
+
75
+ async handler(_input, ctx) {
76
+ const svc = getSpaceWeatherService();
77
+ const [scales, kpObserved] = await Promise.all([
78
+ svc.getNoaaScales(),
79
+ svc.getKpObserved(1),
80
+ ]);
81
+ ctx.log.info('Conditions fetched', { kp: kpObserved[0]?.kp });
82
+ return buildConditionsResponse(scales, kpObserved);
83
+ },
84
+
85
+ format: (result) => [{
86
+ type: 'text',
87
+ text: `**Space Weather Status** — ${result.observed_time}\n\n${result.status_summary}`,
88
+ }],
89
+ });
90
+ ```
91
+
92
+ ### Server instructions
93
+
94
+ `createApp({ instructions })` — this server sets server-level orientation for SWPC feed guidance (start with `get_conditions`, use `get_solar_wind` for Bz monitoring, feed cadences). Sent on every `initialize`; client adoption varies.
95
+
96
+ ---
97
+
98
+ ## Context
99
+
100
+ Handlers receive a unified `ctx` object. Key properties:
101
+
102
+ | Property | Description |
103
+ |:---------|:------------|
104
+ | `ctx.log` | Request-scoped logger — `.debug()`, `.info()`, `.notice()`, `.warning()`, `.error()`. Auto-correlates requestId, traceId, tenantId. |
105
+ | `ctx.fail` | Typed error thrower — `ctx.fail('reason', message, opts?)` maps to declared `errors[]` contract. |
106
+ | `ctx.enrich` | Attach advisory notices to a successful response — `ctx.enrich.notice(title, text)`. |
107
+ | `ctx.recoveryFor` | Spread into an error options object to attach the declared recovery hint: `...ctx.recoveryFor('reason')`. |
108
+ | `ctx.signal` | `AbortSignal` for cancellation. |
109
+ | `ctx.requestId` | Unique request ID. |
110
+ | `ctx.tenantId` | Tenant ID from JWT or `'default'` for stdio. |
111
+
112
+ ---
113
+
114
+ ## Errors
115
+
116
+ Handlers throw — the framework catches, classifies, and formats.
117
+
118
+ **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.
119
+
120
+ ```ts
121
+ import { JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
122
+
123
+ errors: [
124
+ { reason: 'no_match', code: JsonRpcErrorCode.NotFound,
125
+ when: 'No item matched the query',
126
+ recovery: 'Broaden the query or check the spelling and try again.' },
127
+ ],
128
+ async handler(input, ctx) {
129
+ const item = await db.find(input.id);
130
+ if (!item) throw ctx.fail('no_match', `No item ${input.id}`);
131
+ return item;
132
+ }
133
+ ```
134
+
135
+ **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.
136
+
137
+ **Fallback (no contract entry fits):** throw via factories or plain `Error`.
138
+
139
+ ```ts
140
+ // Error factories — explicit code
141
+ import { notFound, serviceUnavailable } from '@cyanheads/mcp-ts-core/errors';
142
+ throw notFound('Item not found', { itemId });
143
+ throw serviceUnavailable('API unavailable', { url }, { cause: err });
144
+
145
+ // Plain Error — framework auto-classifies from message patterns
146
+ throw new Error('Item not found'); // → NotFound
147
+ throw new Error('Invalid query format'); // → ValidationError
148
+
149
+ // McpError — when no factory exists for the code
150
+ import { McpError, JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
151
+ throw new McpError(JsonRpcErrorCode.DatabaseError, 'Connection failed', { pool: 'primary' });
152
+ ```
153
+
154
+ See framework CLAUDE.md and the `api-errors` skill for the full auto-classification table, all available factories, and the contract reference.
155
+
156
+ ---
157
+
158
+ ## Structure
159
+
160
+ ```text
161
+ src/
162
+ index.ts # createApp() entry point
163
+ services/
164
+ space-weather/
165
+ space-weather-service.ts # NOAA SWPC feed client + normalization
166
+ types.ts # Domain types (KpRecord, ScaleEntry, etc.)
167
+ mcp-server/
168
+ tools/definitions/
169
+ get-conditions.tool.ts # noaa_spaceweather_get_conditions
170
+ get-kp-index.tool.ts # noaa_spaceweather_get_kp_index
171
+ get-aurora-forecast.tool.ts # noaa_spaceweather_get_aurora_forecast
172
+ get-solar-wind.tool.ts # noaa_spaceweather_get_solar_wind
173
+ get-solar-activity.tool.ts # noaa_spaceweather_get_solar_activity
174
+ get-alerts.tool.ts # noaa_spaceweather_get_alerts
175
+ index.ts # Barrel — allToolDefinitions
176
+ ```
177
+
178
+ ---
179
+
180
+ ## Naming
181
+
182
+ | What | Convention | Example |
183
+ |:-----|:-----------|:--------|
184
+ | Files | kebab-case with suffix | `search-docs.tool.ts` |
185
+ | Tool/resource/prompt names | snake_case | `search_docs` |
186
+ | Directories | kebab-case | `src/services/doc-search/` |
187
+ | Descriptions | Single string or template literal, no `+` concatenation | `'Search items by query and filter.'` |
188
+
189
+ ---
190
+
191
+ ## Skills
192
+
193
+ 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.
194
+
195
+ **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.
196
+
197
+ Available skills:
198
+
199
+ | Skill | Purpose |
200
+ |:------|:--------|
201
+ | `setup` | Post-init project orientation |
202
+ | `design-mcp-server` | Design tool surface, resources, and services for a new server |
203
+ | `add-tool` | Scaffold a new tool definition |
204
+ | `add-app-tool` | Scaffold an MCP App tool + paired UI resource |
205
+ | `add-resource` | Scaffold a new resource definition |
206
+ | `add-prompt` | Scaffold a new prompt definition |
207
+ | `add-service` | Scaffold a new service integration |
208
+ | `add-test` | Scaffold test file for a tool, resource, or service |
209
+ | `field-test` | Exercise tools/resources/prompts with real inputs, verify behavior, report issues |
210
+ | `tool-defs-analysis` | Read-only audit of MCP definition language across the surface — voice, leaks, defaults, recovery hints, output descriptions |
211
+ | `security-pass` | Audit server for MCP-flavored security gaps: output injection, scope blast radius, input sinks, tenant isolation |
212
+ | `code-simplifier` | Post-session cleanup against `git diff` — modernize syntax, consolidate duplication, align with the codebase |
213
+ | `devcheck` | Lint, format, typecheck, audit |
214
+ | `polish-docs-meta` | Finalize docs, README, metadata, and agent protocol for shipping |
215
+ | `git-wrapup` | Land working-tree changes as a versioned commit + annotated tag — version bump, changelog, verify, tag. Local only. |
216
+ | `release-and-publish` | Push + npm + MCP Registry + GH Release + Docker. Picks up from `git-wrapup` |
217
+ | `maintenance` | Investigate changelogs, adopt upstream changes, sync skills to agent dirs |
218
+ | `orchestrations` | Chain task skills into a gated multi-phase pipeline — build-out, QA-fix, update-ship — when you can spawn sub-agents |
219
+ | `report-issue-framework` | File a bug or feature request against `@cyanheads/mcp-ts-core` via `gh` CLI |
220
+ | `report-issue-local` | File a bug or feature request against this server's own repo via `gh` CLI |
221
+ | `api-auth` | Auth modes, scopes, JWT/OAuth |
222
+ | `api-canvas` | DataCanvas: register tabular data, run SQL, export, plus the `spillover()` helper for big result sets — Tier 3 opt-in |
223
+ | `api-config` | AppConfig, parseConfig, env vars |
224
+ | `api-context` | Context interface, logger, state, progress |
225
+ | `api-errors` | McpError, JsonRpcErrorCode, error patterns |
226
+ | `api-linter` | Definition linter rule catalog — invoked by `bun run lint:mcp` and `devcheck` |
227
+ | `api-services` | LLM, Speech, Graph services |
228
+ | `api-testing` | createMockContext, test patterns |
229
+ | `api-utils` | Formatting, parsing, security, pagination, scheduling, telemetry helpers |
230
+ | `api-telemetry` | OTel catalog: spans, metrics, completion logs, env config, cardinality rules |
231
+ | `api-workers` | Cloudflare Workers runtime |
232
+
233
+ **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.
234
+
235
+ When you complete a skill's checklist, check the boxes and add a completion timestamp at the end (e.g., `Completed: 2026-03-11`).
236
+
237
+ ---
238
+
239
+ ## Commands
240
+
241
+ **Runtime:** Scripts use `bun run` — both `npm run <cmd>` and `bun run <cmd>` work.
242
+
243
+ | Command | Purpose |
244
+ |:--------|:--------|
245
+ | `bun run build` | Compile TypeScript |
246
+ | `bun run rebuild` | Clean + build |
247
+ | `bun run clean` | Remove build artifacts |
248
+ | `bun run devcheck` | Lint + format + typecheck + security + changelog sync |
249
+ | `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. |
250
+ | `bun run tree` | Generate directory structure doc |
251
+ | `bun run format` | Auto-fix formatting (safe fixes only) |
252
+ | `bun run format:unsafe` | Also apply Biome's unsafe autofixes — review the diff; they can change behavior |
253
+ | `bun run test` | Run tests |
254
+ | `bun run start:stdio` | Production mode (stdio) |
255
+ | `bun run start:http` | Production mode (HTTP) |
256
+ | `bun run changelog:build` | Regenerate `CHANGELOG.md` from `changelog/*.md` |
257
+ | `bun run changelog:check` | Verify `CHANGELOG.md` is in sync (used by devcheck) |
258
+ | `bun run bundle` | Build and pack as `.mcpb` for one-click Claude Desktop install |
259
+
260
+ ---
261
+
262
+ ## Bundling
263
+
264
+ `npm run bundle` produces a `.mcpb` extension bundle for one-click install in Claude Desktop. 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.
265
+
266
+ **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.
267
+
268
+ **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`.
269
+
270
+ ---
271
+
272
+ ## Changelog
273
+
274
+ 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.
275
+
276
+ Each per-version file opens with YAML frontmatter:
277
+
278
+ ```markdown
279
+ ---
280
+ summary: "One-line headline, ≤350 chars" # required — powers the rollup index
281
+ breaking: false # optional — true flags breaking changes
282
+ security: false # optional — true flags security fixes
283
+ ---
284
+
285
+ # 0.1.0 — YYYY-MM-DD
286
+ ...
287
+ ```
288
+
289
+ `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`.
290
+
291
+ `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.
292
+
293
+ **Section order** (Keep a Changelog): Added, Changed, Deprecated, Removed, Fixed, Security. Include only sections with entries — don't ship empty headers.
294
+
295
+ **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.
296
+
297
+ ---
298
+
299
+ ## Imports
300
+
301
+ ```ts
302
+ // Framework — z is re-exported, no separate zod import needed
303
+ import { tool, z } from '@cyanheads/mcp-ts-core';
304
+ import { McpError, JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
305
+
306
+ // Server's own code — via path alias
307
+ import { getMyService } from '@/services/my-domain/my-service.js';
308
+ ```
309
+
310
+ ---
311
+
312
+ ## Checklist
313
+
314
+ - [ ] 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()`)
315
+ - [ ] 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`.
316
+ - [ ] JSDoc `@fileoverview` + `@module` on every file
317
+ - [ ] `ctx.log` for logging, `ctx.state` for storage
318
+ - [ ] Handlers throw on failure — error factories or plain `Error`, no try/catch
319
+ - [ ] `format()` renders all data the LLM needs — different clients forward different surfaces (Claude Code → `structuredContent`, Claude Desktop → `content[]`); both must carry the same data
320
+ - [ ] If wrapping external API: raw/domain/output schemas reviewed against real upstream sparsity/nullability before finalizing required vs optional fields
321
+ - [ ] If wrapping external API: normalization and `format()` preserve uncertainty; do not fabricate facts from missing upstream data
322
+ - [ ] If wrapping external API: tests include at least one sparse payload case with omitted upstream fields
323
+ - [ ] Registered in `createApp()` arrays (directly or via barrel exports)
324
+ - [ ] Tests use `createMockContext()` from `@cyanheads/mcp-ts-core/testing`
325
+ - [ ] `.codex-plugin/plugin.json` populated — `name`, `version`, `description`, `repository`, `license` from `package.json`; `interface.displayName` = package name; `interface.shortDescription` from `package.json` description
326
+ - [ ] `.codex-plugin/mcp.json` updated — server name key matches `package.json` name; env vars added for any required API keys
327
+ - [ ] `.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
328
+ - [ ] `npm run devcheck` passes