@cyanheads/astronomy-mcp-server 0.1.2

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 (86) hide show
  1. package/AGENTS.md +431 -0
  2. package/CLAUDE.md +431 -0
  3. package/Dockerfile +104 -0
  4. package/LICENSE +201 -0
  5. package/README.md +320 -0
  6. package/changelog/0.1.x/0.1.1.md +28 -0
  7. package/changelog/0.1.x/0.1.2.md +16 -0
  8. package/changelog/template.md +127 -0
  9. package/dist/config/server-config.d.ts +22 -0
  10. package/dist/config/server-config.d.ts.map +1 -0
  11. package/dist/config/server-config.js +40 -0
  12. package/dist/config/server-config.js.map +1 -0
  13. package/dist/index.d.ts +11 -0
  14. package/dist/index.d.ts.map +1 -0
  15. package/dist/index.js +55 -0
  16. package/dist/index.js.map +1 -0
  17. package/dist/mcp-server/prompts/definitions/stargazing-plan.prompt.d.ts +12 -0
  18. package/dist/mcp-server/prompts/definitions/stargazing-plan.prompt.d.ts.map +1 -0
  19. package/dist/mcp-server/prompts/definitions/stargazing-plan.prompt.js +36 -0
  20. package/dist/mcp-server/prompts/definitions/stargazing-plan.prompt.js.map +1 -0
  21. package/dist/mcp-server/resources/definitions/body.resource.d.ts +29 -0
  22. package/dist/mcp-server/resources/definitions/body.resource.d.ts.map +1 -0
  23. package/dist/mcp-server/resources/definitions/body.resource.js +65 -0
  24. package/dist/mcp-server/resources/definitions/body.resource.js.map +1 -0
  25. package/dist/mcp-server/tools/definitions/find-events.tool.d.ts +157 -0
  26. package/dist/mcp-server/tools/definitions/find-events.tool.d.ts.map +1 -0
  27. package/dist/mcp-server/tools/definitions/find-events.tool.js +242 -0
  28. package/dist/mcp-server/tools/definitions/find-events.tool.js.map +1 -0
  29. package/dist/mcp-server/tools/definitions/get-ephemeris.tool.d.ts +62 -0
  30. package/dist/mcp-server/tools/definitions/get-ephemeris.tool.d.ts.map +1 -0
  31. package/dist/mcp-server/tools/definitions/get-ephemeris.tool.js +161 -0
  32. package/dist/mcp-server/tools/definitions/get-ephemeris.tool.js.map +1 -0
  33. package/dist/mcp-server/tools/definitions/get-moon-phase.tool.d.ts +53 -0
  34. package/dist/mcp-server/tools/definitions/get-moon-phase.tool.d.ts.map +1 -0
  35. package/dist/mcp-server/tools/definitions/get-moon-phase.tool.js +109 -0
  36. package/dist/mcp-server/tools/definitions/get-moon-phase.tool.js.map +1 -0
  37. package/dist/mcp-server/tools/definitions/get-rise-set.tool.d.ts +100 -0
  38. package/dist/mcp-server/tools/definitions/get-rise-set.tool.d.ts.map +1 -0
  39. package/dist/mcp-server/tools/definitions/get-rise-set.tool.js +200 -0
  40. package/dist/mcp-server/tools/definitions/get-rise-set.tool.js.map +1 -0
  41. package/dist/mcp-server/tools/definitions/get-satellite-passes.tool.d.ts +77 -0
  42. package/dist/mcp-server/tools/definitions/get-satellite-passes.tool.d.ts.map +1 -0
  43. package/dist/mcp-server/tools/definitions/get-satellite-passes.tool.js +180 -0
  44. package/dist/mcp-server/tools/definitions/get-satellite-passes.tool.js.map +1 -0
  45. package/dist/mcp-server/tools/definitions/get-sky-position.tool.d.ts +99 -0
  46. package/dist/mcp-server/tools/definitions/get-sky-position.tool.d.ts.map +1 -0
  47. package/dist/mcp-server/tools/definitions/get-sky-position.tool.js +196 -0
  48. package/dist/mcp-server/tools/definitions/get-sky-position.tool.js.map +1 -0
  49. package/dist/mcp-server/tools/definitions/list-visible.tool.d.ts +104 -0
  50. package/dist/mcp-server/tools/definitions/list-visible.tool.d.ts.map +1 -0
  51. package/dist/mcp-server/tools/definitions/list-visible.tool.js +151 -0
  52. package/dist/mcp-server/tools/definitions/list-visible.tool.js.map +1 -0
  53. package/dist/services/ephemeris/body-data.d.ts +25 -0
  54. package/dist/services/ephemeris/body-data.d.ts.map +1 -0
  55. package/dist/services/ephemeris/body-data.js +24 -0
  56. package/dist/services/ephemeris/body-data.js.map +1 -0
  57. package/dist/services/ephemeris/ephemeris-service.d.ts +93 -0
  58. package/dist/services/ephemeris/ephemeris-service.d.ts.map +1 -0
  59. package/dist/services/ephemeris/ephemeris-service.js +742 -0
  60. package/dist/services/ephemeris/ephemeris-service.js.map +1 -0
  61. package/dist/services/ephemeris/star-catalog.d.ts +17 -0
  62. package/dist/services/ephemeris/star-catalog.d.ts.map +1 -0
  63. package/dist/services/ephemeris/star-catalog.js +273 -0
  64. package/dist/services/ephemeris/star-catalog.js.map +1 -0
  65. package/dist/services/ephemeris/types.d.ts +150 -0
  66. package/dist/services/ephemeris/types.d.ts.map +1 -0
  67. package/dist/services/ephemeris/types.js +33 -0
  68. package/dist/services/ephemeris/types.js.map +1 -0
  69. package/dist/services/horizons/horizons-service.d.ts +47 -0
  70. package/dist/services/horizons/horizons-service.d.ts.map +1 -0
  71. package/dist/services/horizons/horizons-service.js +229 -0
  72. package/dist/services/horizons/horizons-service.js.map +1 -0
  73. package/dist/services/horizons/types.d.ts +21 -0
  74. package/dist/services/horizons/types.d.ts.map +1 -0
  75. package/dist/services/horizons/types.js +6 -0
  76. package/dist/services/horizons/types.js.map +1 -0
  77. package/dist/services/satellite/satellite-service.d.ts +48 -0
  78. package/dist/services/satellite/satellite-service.d.ts.map +1 -0
  79. package/dist/services/satellite/satellite-service.js +231 -0
  80. package/dist/services/satellite/satellite-service.js.map +1 -0
  81. package/dist/services/satellite/types.d.ts +32 -0
  82. package/dist/services/satellite/types.d.ts.map +1 -0
  83. package/dist/services/satellite/types.js +6 -0
  84. package/dist/services/satellite/types.js.map +1 -0
  85. package/package.json +104 -0
  86. package/server.json +139 -0
package/CLAUDE.md ADDED
@@ -0,0 +1,431 @@
1
+ # Developer Protocol
2
+
3
+ **Server:** astronomy-mcp-server
4
+ **Version:** 0.1.2
5
+ **Framework:** [@cyanheads/mcp-ts-core](https://www.npmjs.com/package/@cyanheads/mcp-ts-core) `^0.10.9`
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
+ ## Server Surface
15
+
16
+ Observational astronomy, computed in-process. The core is keyless and offline — `astronomy-engine` plus a bundled bright-star catalog, no upstream, no `ctx.state`, deterministic for `(body, time, observer)`. The server does **not** geocode: callers resolve a place name to latitude/longitude (e.g. via openstreetmap) and a timezone (e.g. via reference-data) upstream, then pass coordinates and an optional IANA `timezone` for observer-local output.
17
+
18
+ **Five core tools** (always registered):
19
+
20
+ | Tool | What it computes |
21
+ |:-----|:-----------------|
22
+ | `astronomy_get_sky_position` | Apparent topocentric position of one body or named star — equatorial / horizontal / ecliptic, magnitude, angular diameter, phase, constellation |
23
+ | `astronomy_get_rise_set` | Rise / set / transit cycles, plus twilight bands for the Sun; circumpolar / never-rises notes |
24
+ | `astronomy_get_moon_phase` | Phase angle, illumination, synodic age, next four quarter phases |
25
+ | `astronomy_find_events` | Next N of: equinox, solstice, moon_quarter, lunar/solar eclipse, opposition, conjunction, max_elongation, perigee_apogee |
26
+ | `astronomy_list_visible` | One-call "what is up now" — naked-eye bodies (+ optional catalog stars) above the horizon, ranked, with a sky-condition gate |
27
+
28
+ Plus the `astronomy://body/{body}` resource (static reference card) and the `astronomy_stargazing_plan` prompt (chains the tools for a "plan tonight from <place>" workflow).
29
+
30
+ **Two gated, network-backed extensions** register only when their env gate is on (default deployment is keyless + offline):
31
+
32
+ - `astronomy_get_ephemeris` — small-body / spacecraft ephemeris from JPL Horizons. Gate: `ASTRONOMY_ENABLE_HORIZONS`.
33
+ - `astronomy_get_satellite_passes` — visible passes via a CelesTrak TLE propagated with SGP4 offline. Gate: `ASTRONOMY_ENABLE_SATELLITES`.
34
+
35
+ Both extension services carry their own timeout + retry boundary, cache nothing on disk (Horizons is stateless; the satellite TLE cache is an in-process TTL `Map`), and degrade loudly — on any upstream failure they catch the framework's status-mapped `McpError` and re-throw a clean typed domain error (`{ reason, recovery }`, no `statusCode` / `responseBody` / `requestId` / internal URL), carrying the original as `cause` for server-side logs only. They never substitute core output.
36
+
37
+ **Config** (`src/config/server-config.ts`) is entirely optional — the core needs none. Every variable gates or tunes the two extensions (`ASTRONOMY_ENABLE_*`, `ASTRONOMY_*_BASE_URL`, `ASTRONOMY_DEFAULT_TIMEZONE`, `ASTRONOMY_REQUEST_TIMEOUT_MS`, `ASTRONOMY_TLE_CACHE_TTL_MS`).
38
+
39
+ ---
40
+
41
+ ## Core Rules
42
+
43
+ - **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.
44
+ - **Use `ctx.log`** for request-scoped logging. No `console` calls.
45
+ - **Use `ctx.state`** for tenant-scoped storage. Never access persistence directly.
46
+ - **Check `ctx.elicit`** for presence before calling.
47
+ - **Secrets in env vars only** — never hardcoded.
48
+ - **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.
49
+
50
+ ---
51
+
52
+ ## Patterns
53
+
54
+ ### Tool
55
+
56
+ ```ts
57
+ import { tool, z } from '@cyanheads/mcp-ts-core';
58
+ import { JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
59
+ import { getEphemerisService } from '@/services/ephemeris/ephemeris-service.js';
60
+
61
+ export const getMoonPhaseTool = tool('astronomy_get_moon_phase', {
62
+ title: 'astronomy-mcp-server: get moon phase',
63
+ description:
64
+ 'Report the Moon phase for an instant: illuminated fraction, phase name, synodic age, phase angle, and the next four quarter phases.',
65
+ annotations: { readOnlyHint: true, openWorldHint: false, idempotentHint: true },
66
+ input: z.object({
67
+ time: z.string().optional().describe('Instant to evaluate as an ISO 8601 UTC string. Defaults to now.'),
68
+ timezone: z.string().optional().describe('IANA timezone for localized output. UTC-only when omitted.'),
69
+ }),
70
+ output: MoonPhaseOutput,
71
+ errors: [
72
+ { reason: 'time_out_of_range', code: JsonRpcErrorCode.InvalidParams,
73
+ when: "The instant is outside the engine's high-accuracy span (≈1900–2100).",
74
+ recovery: 'Use a date between 1900 and 2100 and retry.' },
75
+ ],
76
+
77
+ // Core handler is synchronous — astronomy-engine computes in-process, no upstream.
78
+ handler(input, ctx) {
79
+ const svc = getEphemerisService();
80
+ const phase = svc.moonPhase(svc.resolveTime(input.time), svc.resolveTimezone(input.timezone));
81
+ ctx.log.info('Computed moon phase', { phaseName: phase.phaseName });
82
+ return toMoonPhaseOutput(phase);
83
+ },
84
+
85
+ // format() populates content[] — the markdown twin of structuredContent.
86
+ // Different clients read different surfaces (Claude Code → structuredContent,
87
+ // Claude Desktop → content[]); both must carry the same data.
88
+ // Enforced at lint time: every field in `output` must appear in the rendered text.
89
+ format: (r) => [{ type: 'text', text: `## Moon — ${r.phase_name}\n**Illuminated:** ${(r.illuminated_fraction * 100).toFixed(1)}%` }],
90
+ });
91
+ ```
92
+
93
+ ### Resource
94
+
95
+ ```ts
96
+ import { resource, z } from '@cyanheads/mcp-ts-core';
97
+ import { JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
98
+ import { BODY_META } from '@/services/ephemeris/body-data.js';
99
+ import { BODY_NAMES, type BodyName } from '@/services/ephemeris/types.js';
100
+
101
+ export const bodyResource = resource('astronomy://body/{body}', {
102
+ name: 'astronomy-body-reference',
103
+ title: 'astronomy-mcp-server: body reference card',
104
+ description: 'Static reference card for a solar-system body: name, type, mean radius (km), and naked-eye visibility.',
105
+ mimeType: 'application/json',
106
+ params: z.object({ body: z.string().describe('One of sun, moon, mercury … pluto.') }),
107
+ output: BodyCardOutput,
108
+ errors: [
109
+ { reason: 'unknown_body', code: JsonRpcErrorCode.NotFound,
110
+ when: 'The {body} segment is not a supported body.',
111
+ recovery: 'Use one of: sun, moon, mercury … pluto.' },
112
+ ],
113
+ handler(params, ctx) {
114
+ const key = params.body.trim().toLowerCase();
115
+ if (!(BODY_NAMES as readonly string[]).includes(key)) {
116
+ throw ctx.fail('unknown_body', `Unknown body "${params.body}".`, { ...ctx.recoveryFor('unknown_body') });
117
+ }
118
+ const meta = BODY_META[key as BodyName];
119
+ return { body: key, name: meta.name, type: meta.type, mean_radius_km: meta.meanRadiusKm, naked_eye: meta.nakedEye };
120
+ },
121
+
122
+ list: () => ({ resources: BODY_NAMES.map((b) => ({ uri: `astronomy://body/${b}`, name: BODY_META[b].name })) }),
123
+ });
124
+ ```
125
+
126
+ ### Prompt
127
+
128
+ ```ts
129
+ import { prompt, z } from '@cyanheads/mcp-ts-core';
130
+
131
+ export const stargazingPlanPrompt = prompt('astronomy_stargazing_plan', {
132
+ title: 'astronomy-mcp-server: plan stargazing session',
133
+ description:
134
+ 'Structure a "plan tonight\'s stargazing from <place>" workflow, chaining the astronomy tools and naming the cross-server geocoding and weather steps.',
135
+ args: z.object({
136
+ location: z.string().describe('The place to stargaze from, e.g. "Mount Rainier".'),
137
+ date: z.string().optional().describe('Target date (YYYY-MM-DD). Defaults to tonight.'),
138
+ }),
139
+ generate: (args) => {
140
+ const when = args.date ? ` on ${args.date}` : ' tonight';
141
+ return [{ role: 'user', content: { type: 'text', text: `Plan a stargazing session from ${args.location}${when}: resolve coordinates upstream, find the dark-sky window with astronomy_get_rise_set on the sun, check astronomy_get_moon_phase, then astronomy_list_visible just after astronomical dusk.` } }];
142
+ },
143
+ });
144
+ ```
145
+
146
+ ### Server config
147
+
148
+ ```ts
149
+ // src/config/server-config.ts — lazy-parsed, separate from framework config
150
+ import { z } from '@cyanheads/mcp-ts-core';
151
+ import { parseEnvConfig } from '@cyanheads/mcp-ts-core/config';
152
+
153
+ const ServerConfigSchema = z.object({
154
+ enableHorizons: z.stringbool().default(false),
155
+ enableSatellites: z.stringbool().default(false),
156
+ horizonsBaseUrl: z.string().default('https://ssd.jpl.nasa.gov/api/horizons.api'),
157
+ celestrakBaseUrl: z.string().default('https://celestrak.org/NORAD/elements/gp.php'),
158
+ defaultTimezone: z.string().optional(),
159
+ requestTimeoutMs: z.coerce.number().default(15000),
160
+ tleCacheTtlMs: z.coerce.number().default(7200000),
161
+ });
162
+
163
+ let _config: z.infer<typeof ServerConfigSchema> | undefined;
164
+ export function getServerConfig() {
165
+ _config ??= parseEnvConfig(ServerConfigSchema, {
166
+ enableHorizons: 'ASTRONOMY_ENABLE_HORIZONS',
167
+ enableSatellites: 'ASTRONOMY_ENABLE_SATELLITES',
168
+ horizonsBaseUrl: 'ASTRONOMY_HORIZONS_BASE_URL',
169
+ celestrakBaseUrl: 'ASTRONOMY_CELESTRAK_BASE_URL',
170
+ defaultTimezone: 'ASTRONOMY_DEFAULT_TIMEZONE',
171
+ requestTimeoutMs: 'ASTRONOMY_REQUEST_TIMEOUT_MS',
172
+ tleCacheTtlMs: 'ASTRONOMY_TLE_CACHE_TTL_MS',
173
+ });
174
+ return _config;
175
+ }
176
+ ```
177
+
178
+ `parseEnvConfig` maps Zod schema paths → env var names so errors name the variable (`ASTRONOMY_REQUEST_TIMEOUT_MS`) not the path (`requestTimeoutMs`). Throws `ConfigurationError`, which the framework prints as a clean startup banner.
179
+
180
+ 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.
181
+
182
+ ### Server identity and instructions
183
+
184
+ `createApp()` accepts optional identity fields forwarded to the SDK's `initialize` response and the server manifest (`/.well-known/mcp.json`):
185
+
186
+ ```ts
187
+ await createApp({
188
+ name: 'my-mcp-server',
189
+ title: 'My Server', // human-readable display name
190
+ websiteUrl: 'https://github.com/owner/repo', // canonical homepage URL
191
+ description: 'One-line description.', // wins over MCP_SERVER_DESCRIPTION
192
+ icons: [{ src: 'https://example.com/icon.png', sizes: ['48x48'], mimeType: 'image/png' }],
193
+ instructions: 'Use shortcut alpha for the most common case.', // session-level context
194
+ });
195
+ ```
196
+
197
+ `instructions` is optional server-level orientation, sent on every `initialize` as session-level context. Use it for deployment guidance (connection aliases, regional notes, scope hints) instead of repeating the same context across tool descriptions. Client adoption is uneven, but there's no downside when set.
198
+
199
+ ---
200
+
201
+ ## Context
202
+
203
+ Handlers receive a unified `ctx` object. Key properties:
204
+
205
+ | Property | Description |
206
+ |:---------|:------------|
207
+ | `ctx.log` | Request-scoped logger — `.debug()`, `.info()`, `.notice()`, `.warning()`, `.error()`. Auto-correlates requestId, traceId, tenantId. |
208
+ | `ctx.state` | Tenant-scoped KV — `.get(key)`, `.set(key, value, { ttl? })`, `.delete(key)`, `.list(prefix, { cursor, limit })`. Accepts any serializable value. |
209
+ | `ctx.elicit` | Ask user for structured input — form call `(message, schema)` or `.url(message, url)` for an external link. **Check for presence first:** `if (ctx.elicit) { ... }` |
210
+ | `ctx.signal` | `AbortSignal` for cancellation. |
211
+ | `ctx.progress` | Task progress (present when `task: true`) — `.setTotal(n)`, `.increment()`, `.update(message)`. |
212
+ | `ctx.requestId` | Unique request ID. |
213
+ | `ctx.tenantId` | Tenant ID from JWT or `'default'` for stdio. |
214
+
215
+ ---
216
+
217
+ ## Errors
218
+
219
+ Handlers throw — the framework catches, classifies, and formats.
220
+
221
+ **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.
222
+
223
+ ```ts
224
+ import { JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
225
+
226
+ errors: [
227
+ { reason: 'no_match', code: JsonRpcErrorCode.NotFound,
228
+ when: 'No item matched the query',
229
+ recovery: 'Broaden the query or check the spelling and try again.' },
230
+ ],
231
+ async handler(input, ctx) {
232
+ const item = await db.find(input.id);
233
+ if (!item) throw ctx.fail('no_match', `No item ${input.id}`);
234
+ return item;
235
+ }
236
+ ```
237
+
238
+ **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.
239
+
240
+ **Fallback (no contract entry fits):** throw via factories or plain `Error`.
241
+
242
+ ```ts
243
+ // Error factories — explicit code
244
+ import { notFound, serviceUnavailable } from '@cyanheads/mcp-ts-core/errors';
245
+ throw notFound('Item not found', { itemId });
246
+ throw serviceUnavailable('API unavailable', { url }, { cause: err });
247
+
248
+ // Plain Error — framework auto-classifies from message patterns
249
+ throw new Error('Item not found'); // → NotFound
250
+ throw new Error('Invalid query format'); // → ValidationError
251
+
252
+ // McpError — when no factory exists for the code
253
+ import { McpError, JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
254
+ throw new McpError(JsonRpcErrorCode.DatabaseError, 'Connection failed', { pool: 'primary' });
255
+ ```
256
+
257
+ See framework CLAUDE.md and the `api-errors` skill for the full auto-classification table, all available factories, and the contract reference.
258
+
259
+ ---
260
+
261
+ ## Structure
262
+
263
+ ```text
264
+ src/
265
+ index.ts # createApp() entry point
266
+ config/
267
+ server-config.ts # Server-specific env vars (Zod schema)
268
+ services/
269
+ [domain]/
270
+ [domain]-service.ts # Domain service (init/accessor pattern)
271
+ types.ts # Domain types
272
+ mcp-server/
273
+ tools/definitions/
274
+ [tool-name].tool.ts # Tool definitions
275
+ resources/definitions/
276
+ [resource-name].resource.ts # Resource definitions
277
+ prompts/definitions/
278
+ [prompt-name].prompt.ts # Prompt definitions
279
+ ```
280
+
281
+ ---
282
+
283
+ ## Naming
284
+
285
+ | What | Convention | Example |
286
+ |:-----|:-----------|:--------|
287
+ | Files | kebab-case with suffix | `search-docs.tool.ts` |
288
+ | Tool/resource/prompt names | snake_case | `search_docs` |
289
+ | Directories | kebab-case | `src/services/doc-search/` |
290
+ | Descriptions | Single string or template literal, no `+` concatenation | `'Search items by query and filter.'` |
291
+
292
+ ---
293
+
294
+ ## Skills
295
+
296
+ 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.
297
+
298
+ **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.
299
+
300
+ Available skills:
301
+
302
+ | Skill | Purpose |
303
+ |:------|:--------|
304
+ | `setup` | Post-init project orientation |
305
+ | `design-mcp-server` | Design tool surface, resources, and services for a new server |
306
+ | `add-tool` | Scaffold a new tool definition |
307
+ | `add-app-tool` | Scaffold an MCP App tool + paired UI resource |
308
+ | `add-resource` | Scaffold a new resource definition |
309
+ | `add-prompt` | Scaffold a new prompt definition |
310
+ | `add-service` | Scaffold a new service integration |
311
+ | `add-test` | Scaffold test file for a tool, resource, or service |
312
+ | `field-test` | Exercise tools/resources/prompts with real inputs, verify behavior, report issues |
313
+ | `tool-defs-analysis` | Read-only audit of MCP definition language across the surface — voice, leaks, defaults, recovery hints, output descriptions |
314
+ | `security-pass` | Audit server for MCP-flavored security gaps: output injection, scope blast radius, input sinks, tenant isolation |
315
+ | `code-simplifier` | Post-session cleanup against `git diff` — modernize syntax, consolidate duplication, align with the codebase |
316
+ | `devcheck` | Lint, format, typecheck, audit |
317
+ | `polish-docs-meta` | Finalize docs, README, metadata, and agent protocol for shipping |
318
+ | `git-wrapup` | Land working-tree changes as a versioned commit + annotated tag — version bump, changelog, verify, tag. Local only. |
319
+ | `release-and-publish` | Push + npm + MCP Registry + GH Release + Docker. Picks up from `git-wrapup` |
320
+ | `maintenance` | Investigate changelogs, adopt upstream changes, sync skills to agent dirs |
321
+ | `orchestrations` | Chain task skills into a gated multi-phase pipeline — build-out, QA-fix, update-ship — when you can spawn sub-agents |
322
+ | `report-issue-framework` | File a bug or feature request against `@cyanheads/mcp-ts-core` via `gh` CLI |
323
+ | `report-issue-local` | File a bug or feature request against this server's own repo via `gh` CLI |
324
+ | `api-auth` | Auth modes, scopes, JWT/OAuth |
325
+ | `api-canvas` | DataCanvas: register tabular data, run SQL, export, plus the `spillover()` helper for big result sets — Tier 3 opt-in |
326
+ | `api-config` | AppConfig, parseConfig, env vars |
327
+ | `api-context` | Context interface, logger, state, progress |
328
+ | `api-errors` | McpError, JsonRpcErrorCode, error patterns |
329
+ | `api-linter` | Definition linter rule catalog — invoked by `bun run lint:mcp` and `devcheck` |
330
+ | `api-services` | LLM, Speech, Graph services |
331
+ | `api-testing` | createMockContext, test patterns |
332
+ | `api-utils` | Formatting, parsing, security, pagination, scheduling, telemetry helpers |
333
+ | `api-telemetry` | OTel catalog: spans, metrics, completion logs, env config, cardinality rules |
334
+ | `api-workers` | Cloudflare Workers runtime |
335
+
336
+ **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.
337
+
338
+ When you complete a skill's checklist, check the boxes and add a completion timestamp at the end (e.g., `Completed: 2026-03-11`).
339
+
340
+ ---
341
+
342
+ ## Commands
343
+
344
+ **Runtime:** Scripts use Bun's native TypeScript execution — `bun run <cmd>` is the standard invocation. `npm run <cmd>` also works (npm delegates to bun).
345
+
346
+ | Command | Purpose |
347
+ |:--------|:--------|
348
+ | `npm run build` | Compile TypeScript |
349
+ | `npm run rebuild` | Clean + build |
350
+ | `npm run clean` | Remove build artifacts |
351
+ | `npm run devcheck` | Lint + format + typecheck + security + changelog sync |
352
+ | `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. |
353
+ | `npm run tree` | Generate directory structure doc |
354
+ | `npm run format` | Auto-fix formatting (safe fixes only) |
355
+ | `npm run format:unsafe` | Also apply Biome's unsafe autofixes — review the diff; they can change behavior |
356
+ | `npm test` | Run tests |
357
+ | `npm run start:stdio` | Production mode (stdio) |
358
+ | `npm run start:http` | Production mode (HTTP) |
359
+ | `npm run changelog:build` | Regenerate `CHANGELOG.md` from `changelog/*.md` |
360
+ | `npm run changelog:check` | Verify `CHANGELOG.md` is in sync (used by devcheck) |
361
+ | `npm run bundle` | Build, pack, and clean a `.mcpb` for one-click Claude Desktop install |
362
+
363
+ ---
364
+
365
+ ## Bundling
366
+
367
+ `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.
368
+
369
+ **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.
370
+
371
+ **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`.
372
+
373
+ ---
374
+
375
+ ## Changelog
376
+
377
+ 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.
378
+
379
+ Each per-version file opens with YAML frontmatter:
380
+
381
+ ```markdown
382
+ ---
383
+ summary: "One-line headline, ≤350 chars" # required — powers the rollup index
384
+ breaking: false # optional — true flags breaking changes
385
+ security: false # optional — true flags security fixes
386
+ ---
387
+
388
+ # 0.1.0 — YYYY-MM-DD
389
+ ...
390
+ ```
391
+
392
+ `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`.
393
+
394
+ `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.
395
+
396
+ **Section order** (Keep a Changelog): Added, Changed, Deprecated, Removed, Fixed, Security. Include only sections with entries — don't ship empty headers.
397
+
398
+ **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.
399
+
400
+ ---
401
+
402
+ ## Imports
403
+
404
+ ```ts
405
+ // Framework — z is re-exported, no separate zod import needed
406
+ import { tool, z } from '@cyanheads/mcp-ts-core';
407
+ import { McpError, JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
408
+
409
+ // Server's own code — via path alias
410
+ import { getMyService } from '@/services/my-domain/my-service.js';
411
+ ```
412
+
413
+ ---
414
+
415
+ ## Checklist
416
+
417
+ - [ ] 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()`)
418
+ - [ ] 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`.
419
+ - [ ] JSDoc `@fileoverview` + `@module` on every file
420
+ - [ ] `ctx.log` for logging, `ctx.state` for storage
421
+ - [ ] Handlers throw on failure — error factories or plain `Error`, no try/catch
422
+ - [ ] `format()` renders all data the LLM needs — different clients forward different surfaces (Claude Code → `structuredContent`, Claude Desktop → `content[]`); both must carry the same data
423
+ - [ ] If wrapping external API: raw/domain/output schemas reviewed against real upstream sparsity/nullability before finalizing required vs optional fields
424
+ - [ ] If wrapping external API: normalization and `format()` preserve uncertainty; do not fabricate facts from missing upstream data
425
+ - [ ] If wrapping external API: tests include at least one sparse payload case with omitted upstream fields
426
+ - [ ] Registered in `createApp()` arrays (directly or via barrel exports)
427
+ - [ ] Tests use `createMockContext()` from `@cyanheads/mcp-ts-core/testing`
428
+ - [ ] `.codex-plugin/plugin.json` populated — `name`, `version`, `description`, `repository`, `license` from `package.json`; `interface.displayName` = package name; `interface.shortDescription` from `package.json` description
429
+ - [ ] `.codex-plugin/mcp.json` updated — server name key matches `package.json` name; env vars added for any required API keys
430
+ - [ ] `.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
431
+ - [ ] `npm run devcheck` passes
package/Dockerfile ADDED
@@ -0,0 +1,104 @@
1
+ # ==============================================================================
2
+ # Build Stage
3
+ #
4
+ # This stage installs all dependencies (including dev), builds the TypeScript
5
+ # source code into JavaScript, and prepares the production assets.
6
+ # ==============================================================================
7
+ FROM oven/bun:1.3 AS build
8
+
9
+ WORKDIR /usr/src/app
10
+
11
+ # Copy dependency manifests for optimized layer caching
12
+ COPY package.json bun.lock ./
13
+
14
+ # Install all dependencies (including dev dependencies for building)
15
+ RUN bun install --frozen-lockfile
16
+
17
+ # Copy the rest of the source code
18
+ COPY . .
19
+
20
+ # Build the application
21
+ RUN bun run build
22
+
23
+
24
+ # ==============================================================================
25
+ # Production Stage
26
+ #
27
+ # This stage creates a minimal, optimized, and secure image for running the
28
+ # application. It uses a slim base image and only includes production
29
+ # dependencies and build artifacts.
30
+ # ==============================================================================
31
+ FROM oven/bun:1.3-slim AS production
32
+
33
+ WORKDIR /usr/src/app
34
+
35
+ # Set the environment to production for performance and to ensure only
36
+ # production dependencies are installed.
37
+ ENV NODE_ENV=production
38
+
39
+ # OCI image metadata (https://github.com/opencontainers/image-spec/blob/main/annotations.md)
40
+ ARG APP_VERSION
41
+ LABEL org.opencontainers.image.title="astronomy-mcp-server"
42
+ LABEL org.opencontainers.image.description="What's in the sky, computed offline — planet and moon positions, rise/set, phases, eclipses, and seasons for any place and time."
43
+ LABEL org.opencontainers.image.licenses="Apache-2.0"
44
+ LABEL org.opencontainers.image.version="${APP_VERSION}"
45
+ LABEL org.opencontainers.image.source="https://github.com/cyanheads/astronomy-mcp-server"
46
+
47
+ # Copy dependency manifests
48
+ COPY package.json bun.lock ./
49
+
50
+ # Install only production dependencies, ignoring any lifecycle scripts (like 'prepare')
51
+ # that are not needed in the final production image.
52
+ RUN bun install --production --frozen-lockfile --ignore-scripts
53
+
54
+ # Conditionally install OpenTelemetry optional peer dependencies (Tier 3).
55
+ # These are not bundled by default to keep the base image lean. Enable at build time
56
+ # with: docker build --build-arg OTEL_ENABLED=true
57
+ ARG OTEL_ENABLED=true
58
+ RUN if [ "$OTEL_ENABLED" = "true" ]; then \
59
+ bun add @hono/otel \
60
+ @opentelemetry/instrumentation-http \
61
+ @opentelemetry/exporter-metrics-otlp-http \
62
+ @opentelemetry/exporter-trace-otlp-http \
63
+ @opentelemetry/instrumentation-pino \
64
+ @opentelemetry/resources \
65
+ @opentelemetry/sdk-metrics \
66
+ @opentelemetry/sdk-node \
67
+ @opentelemetry/sdk-trace-node \
68
+ @opentelemetry/semantic-conventions; \
69
+ fi
70
+
71
+ # Copy the compiled application code from the build stage
72
+ COPY --from=build /usr/src/app/dist ./dist
73
+
74
+ # The 'oven/bun' image already provides a non-root user named 'bun'.
75
+ # We will use this existing user for enhanced security.
76
+
77
+ # Create and set permissions for the log directory, assigning ownership to the 'bun' user.
78
+ RUN mkdir -p /var/log/astronomy-mcp-server && chown -R bun:bun /var/log/astronomy-mcp-server
79
+
80
+ # Switch to the non-root user
81
+ USER bun
82
+
83
+ # Define an argument for the port, allowing it to be overridden at build time.
84
+ # The `PORT` variable is often injected by cloud environments at runtime.
85
+ ARG PORT
86
+
87
+ # Set runtime environment variables
88
+ # Note: PORT is an automatic variable in many cloud environments (e.g., Cloud Run)
89
+ ENV MCP_HTTP_PORT=${PORT:-3010}
90
+ ENV MCP_HTTP_HOST="0.0.0.0"
91
+ ENV MCP_TRANSPORT_TYPE="http"
92
+ ENV MCP_SESSION_MODE="stateless"
93
+ ENV MCP_LOG_LEVEL="info"
94
+ ENV LOGS_DIR="/var/log/astronomy-mcp-server"
95
+ ENV MCP_FORCE_CONSOLE_LOGGING="true"
96
+
97
+ # Expose the port the server listens on
98
+ EXPOSE ${MCP_HTTP_PORT}
99
+
100
+ # Health check using a bun-native fetch (slim image ships no curl/wget)
101
+ HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 CMD bun -e "fetch('http://localhost:'+(process.env.MCP_HTTP_PORT??'3010')+'/healthz').then((r)=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
102
+
103
+ # The command to start the server
104
+ CMD ["bun", "run", "dist/index.js"]