@cyanheads/eia-energy-mcp-server 0.2.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 (72) hide show
  1. package/CLAUDE.md +351 -0
  2. package/Dockerfile +99 -0
  3. package/LICENSE +195 -0
  4. package/README.md +274 -0
  5. package/changelog/0.1.x/0.1.0.md +18 -0
  6. package/changelog/0.1.x/0.1.1.md +42 -0
  7. package/changelog/0.1.x/0.1.2.md +22 -0
  8. package/changelog/0.1.x/0.1.3.md +17 -0
  9. package/changelog/0.1.x/0.1.4.md +17 -0
  10. package/changelog/0.1.x/0.1.5.md +19 -0
  11. package/changelog/0.1.x/0.1.6.md +19 -0
  12. package/changelog/0.1.x/0.1.7.md +11 -0
  13. package/changelog/0.2.x/0.2.0.md +22 -0
  14. package/changelog/template.md +93 -0
  15. package/dist/config/server-config.d.ts +18 -0
  16. package/dist/config/server-config.d.ts.map +1 -0
  17. package/dist/config/server-config.js +36 -0
  18. package/dist/config/server-config.js.map +1 -0
  19. package/dist/index.d.ts +7 -0
  20. package/dist/index.d.ts.map +1 -0
  21. package/dist/index.js +39 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/mcp-server/tools/definitions/browse-routes.tool.d.ts +28 -0
  24. package/dist/mcp-server/tools/definitions/browse-routes.tool.d.ts.map +1 -0
  25. package/dist/mcp-server/tools/definitions/browse-routes.tool.js +72 -0
  26. package/dist/mcp-server/tools/definitions/browse-routes.tool.js.map +1 -0
  27. package/dist/mcp-server/tools/definitions/dataframe-describe.tool.d.ts +34 -0
  28. package/dist/mcp-server/tools/definitions/dataframe-describe.tool.d.ts.map +1 -0
  29. package/dist/mcp-server/tools/definitions/dataframe-describe.tool.js +114 -0
  30. package/dist/mcp-server/tools/definitions/dataframe-describe.tool.js.map +1 -0
  31. package/dist/mcp-server/tools/definitions/dataframe-drop.tool.d.ts +22 -0
  32. package/dist/mcp-server/tools/definitions/dataframe-drop.tool.d.ts.map +1 -0
  33. package/dist/mcp-server/tools/definitions/dataframe-drop.tool.js +56 -0
  34. package/dist/mcp-server/tools/definitions/dataframe-drop.tool.js.map +1 -0
  35. package/dist/mcp-server/tools/definitions/dataframe-query.tool.d.ts +28 -0
  36. package/dist/mcp-server/tools/definitions/dataframe-query.tool.d.ts.map +1 -0
  37. package/dist/mcp-server/tools/definitions/dataframe-query.tool.js +124 -0
  38. package/dist/mcp-server/tools/definitions/dataframe-query.tool.js.map +1 -0
  39. package/dist/mcp-server/tools/definitions/describe-route.tool.d.ts +58 -0
  40. package/dist/mcp-server/tools/definitions/describe-route.tool.d.ts.map +1 -0
  41. package/dist/mcp-server/tools/definitions/describe-route.tool.js +164 -0
  42. package/dist/mcp-server/tools/definitions/describe-route.tool.js.map +1 -0
  43. package/dist/mcp-server/tools/definitions/query-route.tool.d.ts +66 -0
  44. package/dist/mcp-server/tools/definitions/query-route.tool.d.ts.map +1 -0
  45. package/dist/mcp-server/tools/definitions/query-route.tool.js +264 -0
  46. package/dist/mcp-server/tools/definitions/query-route.tool.js.map +1 -0
  47. package/dist/mcp-server/tools/definitions/search-routes.tool.d.ts +23 -0
  48. package/dist/mcp-server/tools/definitions/search-routes.tool.d.ts.map +1 -0
  49. package/dist/mcp-server/tools/definitions/search-routes.tool.js +94 -0
  50. package/dist/mcp-server/tools/definitions/search-routes.tool.js.map +1 -0
  51. package/dist/services/canvas-bridge/canvas-bridge.d.ts +68 -0
  52. package/dist/services/canvas-bridge/canvas-bridge.d.ts.map +1 -0
  53. package/dist/services/canvas-bridge/canvas-bridge.js +206 -0
  54. package/dist/services/canvas-bridge/canvas-bridge.js.map +1 -0
  55. package/dist/services/canvas-bridge/sql-gate-extras.d.ts +13 -0
  56. package/dist/services/canvas-bridge/sql-gate-extras.d.ts.map +1 -0
  57. package/dist/services/canvas-bridge/sql-gate-extras.js +37 -0
  58. package/dist/services/canvas-bridge/sql-gate-extras.js.map +1 -0
  59. package/dist/services/eia/eia-service.d.ts +72 -0
  60. package/dist/services/eia/eia-service.d.ts.map +1 -0
  61. package/dist/services/eia/eia-service.js +497 -0
  62. package/dist/services/eia/eia-service.js.map +1 -0
  63. package/dist/services/eia/route-cache.d.ts +65 -0
  64. package/dist/services/eia/route-cache.d.ts.map +1 -0
  65. package/dist/services/eia/route-cache.js +168 -0
  66. package/dist/services/eia/route-cache.js.map +1 -0
  67. package/dist/services/eia/types.d.ts +115 -0
  68. package/dist/services/eia/types.d.ts.map +1 -0
  69. package/dist/services/eia/types.js +7 -0
  70. package/dist/services/eia/types.js.map +1 -0
  71. package/package.json +104 -0
  72. package/server.json +163 -0
package/CLAUDE.md ADDED
@@ -0,0 +1,351 @@
1
+ # Agent Protocol
2
+
3
+ **Server:** @cyanheads/eia-energy-mcp-server
4
+ **Version:** 0.2.0
5
+ **Framework:** [@cyanheads/mcp-ts-core](https://www.npmjs.com/package/@cyanheads/mcp-ts-core) `^0.9.6`
6
+ **Engines:** Bun ≥1.3.0, Node ≥24.0.0
7
+
8
+ > **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.
9
+
10
+ ---
11
+
12
+ ## What's Next?
13
+
14
+ When the user asks what to do next, what's left, or needs direction, suggest relevant options based on the current project state:
15
+
16
+ 1. **Re-run the `setup` skill** — ensures CLAUDE.md, skills, structure, and metadata are populated and up to date with the current codebase
17
+ 2. **Run the `design-mcp-server` skill** — if the tool/resource surface hasn't been mapped yet, work through domain design
18
+ 3. **Add tools/resources/prompts** — scaffold new definitions using the `add-tool`, `add-app-tool`, `add-resource`, `add-prompt` skills
19
+ 4. **Add services** — scaffold domain service integrations using the `add-service` skill
20
+ 5. **Add tests** — scaffold tests for existing definitions using the `add-test` skill
21
+ 6. **Field-test definitions** — exercise tools/resources/prompts with real inputs using the `field-test` skill, get a report of issues and pain points
22
+ 7. **Run `devcheck`** — lint, format, typecheck, and security audit
23
+ 8. **Run the `security-pass` skill** — audit handlers for MCP-specific security gaps: output injection, scope blast radius, input sinks, tenant isolation
24
+ 9. **Run the `polish-docs-meta` skill** — finalize README, CHANGELOG, metadata, and agent protocol for shipping
25
+ 10. **Run the `maintenance` skill** — investigate changelogs, adopt upstream changes, and sync skills after `bun update --latest`
26
+
27
+ Tailor suggestions to what's actually missing or stale — don't recite the full list every time.
28
+
29
+ ---
30
+
31
+ ## Core Rules
32
+
33
+ - **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.
34
+ - **Use `ctx.log`** for request-scoped logging. No `console` calls.
35
+ - **Use `ctx.state`** for tenant-scoped storage. Never access persistence directly.
36
+ - **Check `ctx.elicit` / `ctx.sample`** for presence before calling.
37
+ - **Secrets in env vars only** — never hardcoded.
38
+
39
+ ---
40
+
41
+ ## Patterns
42
+
43
+ ### Tool
44
+
45
+ ```ts
46
+ import { tool, z } from '@cyanheads/mcp-ts-core';
47
+ import { getEiaApiService } from '@/services/eia/eia-service.js';
48
+
49
+ export const browseRoutes = tool('eia_browse_routes', {
50
+ description: 'Lists child routes under a given path in the EIA dataset taxonomy.',
51
+ annotations: { readOnlyHint: true, openWorldHint: false },
52
+
53
+ input: z.object({
54
+ path: z.string().optional().describe('Route path to browse (e.g. "electricity"). Omit for root.'),
55
+ }),
56
+
57
+ output: z.object({
58
+ path: z.string().describe('The path browsed'),
59
+ children: z.array(z.object({
60
+ id: z.string().describe('Route segment ID'),
61
+ name: z.string().describe('Human-readable name'),
62
+ description: z.string().describe('Route description'),
63
+ route: z.string().describe('Full route path'),
64
+ isLeaf: z.boolean().describe('True when this child is a queryable leaf route'),
65
+ })).describe('Child entries'),
66
+ isLeaf: z.boolean().describe('True when the browsed path itself is a leaf route'),
67
+ }),
68
+
69
+ errors: [
70
+ { reason: 'route_not_found', code: JsonRpcErrorCode.NotFound,
71
+ when: 'Path does not exist in the EIA taxonomy',
72
+ recovery: 'Call eia_browse_routes without a path to see valid top-level categories.' },
73
+ ],
74
+
75
+ async handler(input, ctx) {
76
+ ctx.log.info('Executing eia_browse_routes', { path: input.path });
77
+ const result = await getEiaApiService().browse(input.path);
78
+ return result;
79
+ },
80
+
81
+ format: (result) => [{
82
+ type: 'text',
83
+ text: result.children.map(c => `${c.isLeaf ? '[leaf]' : '[cat]'} ${c.route} — ${c.name}`).join('\n'),
84
+ }],
85
+ });
86
+ ```
87
+
88
+ ### Server config
89
+
90
+ ```ts
91
+ // src/config/server-config.ts — lazy-parsed, separate from framework config
92
+ import { z } from '@cyanheads/mcp-ts-core';
93
+ import { parseEnvConfig } from '@cyanheads/mcp-ts-core/config';
94
+
95
+ const ServerConfigSchema = z.object({
96
+ apiKey: z.string().describe('EIA API key'),
97
+ baseUrl: z.string().url().default('https://api.eia.gov/v2').describe('EIA API base URL'),
98
+ datasetTtlSeconds: z.coerce.number().int().positive().default(86400)
99
+ .describe('Per-table TTL for canvas dataframes in seconds (default 24 h)'),
100
+ dataframeDropEnabled: z.preprocess((v) => v === 'true' || v === true, z.boolean())
101
+ .default(false).describe('Expose eia_dataframe_drop when true'),
102
+ });
103
+
104
+ let _config: z.infer<typeof ServerConfigSchema> | undefined;
105
+ export function getServerConfig(): z.infer<typeof ServerConfigSchema> {
106
+ _config ??= parseEnvConfig(ServerConfigSchema, {
107
+ apiKey: 'EIA_API_KEY',
108
+ baseUrl: 'EIA_BASE_URL',
109
+ datasetTtlSeconds: 'EIA_DATASET_TTL_SECONDS',
110
+ dataframeDropEnabled: 'EIA_DATAFRAME_DROP_ENABLED',
111
+ });
112
+ return _config;
113
+ }
114
+ ```
115
+
116
+ `parseEnvConfig` maps Zod schema paths → env var names so validation errors name the actual variable (`EIA_API_KEY` is required) rather than the internal path.
117
+
118
+ ---
119
+
120
+ ## Context
121
+
122
+ Handlers receive a unified `ctx` object. Key properties:
123
+
124
+ | Property | Description |
125
+ |:---------|:------------|
126
+ | `ctx.log` | Request-scoped logger — `.debug()`, `.info()`, `.notice()`, `.warning()`, `.error()`. Auto-correlates requestId, traceId, tenantId. |
127
+ | `ctx.state` | Tenant-scoped KV — `.get(key)`, `.set(key, value, { ttl? })`, `.delete(key)`, `.list(prefix, { cursor, limit })`. Accepts any serializable value. |
128
+ | `ctx.recoveryFor(reason)` | Typed lookup of the contract `recovery` for a declared reason. Spread into `ctx.fail` data to mirror the contract hint into `content[]`. |
129
+ | `ctx.signal` | `AbortSignal` for cancellation. |
130
+ | `ctx.requestId` | Unique request ID. |
131
+ | `ctx.tenantId` | Tenant ID from JWT, `'default'` for stdio or HTTP+`MCP_AUTH_MODE=none`. |
132
+
133
+ ---
134
+
135
+ ## Errors
136
+
137
+ Handlers throw — the framework catches, classifies, and formats.
138
+
139
+ **Recommended: typed error contract.** Declare `errors: [{ reason, code, when, recovery, retryable? }]` on `tool()` / `resource()` to receive a typed `ctx.fail(reason, …)` keyed by the declared reason union. TypeScript catches `ctx.fail('typo')` at compile time, `data.reason` is auto-populated for observability, and the linter enforces conformance against the handler body. The `recovery` field is required (≥ 5 words, lint-validated) — it's the single source of truth for the recovery hint. Baseline codes (`InternalError`, `ServiceUnavailable`, `Timeout`, `ValidationError`, `SerializationError`) bubble freely and don't need declaring.
140
+
141
+ ```ts
142
+ errors: [
143
+ { reason: 'route_not_found', code: JsonRpcErrorCode.NotFound,
144
+ when: 'Route does not exist in the EIA taxonomy',
145
+ recovery: 'Call eia_browse_routes without a path to see top-level categories.' },
146
+ { reason: 'rate_limited', code: JsonRpcErrorCode.ServiceUnavailable,
147
+ retryable: true,
148
+ when: 'EIA rate limit exceeded',
149
+ recovery: 'Back off and retry; use a production API key for higher limits.' },
150
+ ],
151
+ async handler(input, ctx) {
152
+ const result = await getEiaApiService().query(input.route, input.filters);
153
+ if (!result) throw ctx.fail('route_not_found', `Route ${input.route} not found`);
154
+ return result;
155
+ }
156
+ ```
157
+
158
+ **Fallback:** error factories or plain `Error`.
159
+
160
+ ```ts
161
+ import { notFound, serviceUnavailable } from '@cyanheads/mcp-ts-core/errors';
162
+ throw notFound('Route not found', { route });
163
+ throw serviceUnavailable('EIA rate limit hit', { route }, { cause: err });
164
+ ```
165
+
166
+ For HTTP responses, use `httpErrorFromResponse(response, { service, data })` from `/utils` — covers the full 4xx/5xx → `JsonRpcErrorCode` table.
167
+
168
+ See framework CLAUDE.md and the `api-errors` skill for the full auto-classification table, all factories, and the contract reference.
169
+
170
+ ---
171
+
172
+ ## Structure
173
+
174
+ ```text
175
+ src/
176
+ index.ts # createApp() entry point
177
+ config/
178
+ server-config.ts # EIA-specific env vars (Zod schema)
179
+ services/
180
+ eia/
181
+ eia-service.ts # EIA API v2 service (init/accessor + HTTP client)
182
+ route-cache.ts # In-process route tree cache + Fuse.js index
183
+ types.ts # EIA domain types
184
+ canvas-bridge/
185
+ canvas-bridge.ts # DataCanvas bridge (register/describe/query/drop)
186
+ sql-gate-extras.ts # System-catalog deny-list for read-only enforcement
187
+ mcp-server/
188
+ tools/definitions/
189
+ browse-routes.tool.ts # eia_browse_routes
190
+ describe-route.tool.ts # eia_describe_route
191
+ search-routes.tool.ts # eia_search_routes
192
+ query-route.tool.ts # eia_query_route
193
+ dataframe-describe.tool.ts # eia_dataframe_describe
194
+ dataframe-query.tool.ts # eia_dataframe_query
195
+ dataframe-drop.tool.ts # eia_dataframe_drop (opt-in)
196
+ ```
197
+
198
+ ---
199
+
200
+ ## Naming
201
+
202
+ | What | Convention | Example |
203
+ |:-----|:-----------|:--------|
204
+ | Files | kebab-case with suffix | `browse-routes.tool.ts` |
205
+ | Tool/resource/prompt names | snake_case | `eia_browse_routes` |
206
+ | Directories | kebab-case | `src/services/eia/` |
207
+ | Descriptions | Single string or template literal, no `+` concatenation | `'Browse the EIA dataset taxonomy.'` |
208
+
209
+ ---
210
+
211
+ ## EIA-Specific Conventions
212
+
213
+ **Two-phase workflow:** Discovery (`eia_browse_routes` / `eia_search_routes` → `eia_describe_route`) must precede data retrieval (`eia_query_route`). Facet IDs and valid values are not embedded in route metadata — they require separate `GET /v2/{route}/facet/{facetId}` calls. Always describe the route before querying it.
214
+
215
+ **In-process caches:**
216
+ - Route tree: fetched lazily on first `eia_browse_routes` / `eia_search_routes` call; cached for server lifetime. STEO's 1,469 `seriesId` values are included in the Fuse.js index.
217
+ - Facet metadata: per-route cache keyed by route path; populated by `eia_describe_route` via fan-out (`Promise.all` over all facets). Reused by subsequent describe and query calls.
218
+
219
+ **STEO:** `steo` is a flat leaf (no sub-routes) with one facet: `seriesId` covering 1,469 named series. Query it via `eia_query_route` with `seriesId` filter. Discovery via `eia_search_routes` (series names are indexed).
220
+
221
+ **Data values are strings:** All numeric data from `/v2/{route}/data/` arrives as strings (e.g. `"9.13"`). Per-column units appear as `{col}-units` fields inline in each row. Surfaces in output schema — do not coerce silently.
222
+
223
+ **Retry / rate limits:** Wrap fetch + parse in `withRetry`. DEMO_KEY hits limits quickly; production keys have higher caps. Detect EIA's `OVER_RATE_LIMIT` response and classify as `ServiceUnavailable` (retryable).
224
+
225
+ **DataCanvas:** Opt-in via `CANVAS_PROVIDER_TYPE=duckdb`. Check `ctx.core.canvas?` at runtime; degrade gracefully to preview-only when absent. Large result sets (total > length) spill to canvas and return a `canvas_id` for SQL queries.
226
+
227
+ ---
228
+
229
+ ## Skills
230
+
231
+ 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.
232
+
233
+ **Agent skill directory:** Copy skills into the directory your agent discovers (Claude Code: `.claude/skills/`, others: equivalent). This makes skills available as context without needing to reference `skills/` paths manually. After framework updates, run the `maintenance` skill — it re-syncs the agent directory automatically (Phase B).
234
+
235
+ Available skills:
236
+
237
+ | Skill | Purpose |
238
+ |:------|:--------|
239
+ | `setup` | Post-init project orientation |
240
+ | `design-mcp-server` | Design tool surface, resources, and services for a new server |
241
+ | `add-tool` | Scaffold a new tool definition |
242
+ | `add-app-tool` | Scaffold an MCP App tool + paired UI resource |
243
+ | `add-resource` | Scaffold a new resource definition |
244
+ | `add-prompt` | Scaffold a new prompt definition |
245
+ | `add-service` | Scaffold a new service integration |
246
+ | `add-test` | Scaffold test file for a tool, resource, or service |
247
+ | `field-test` | Exercise tools/resources/prompts with real inputs, verify behavior, report issues |
248
+ | `security-pass` | Audit server for MCP-flavored security gaps: output injection, scope blast radius, input sinks, tenant isolation |
249
+ | `devcheck` | Lint, format, typecheck, audit |
250
+ | `polish-docs-meta` | Finalize docs, README, metadata, and agent protocol for shipping |
251
+ | `maintenance` | Investigate changelogs, adopt upstream changes, and sync skills after `bun update --latest` |
252
+ | `report-issue-framework` | File a bug or feature request against `@cyanheads/mcp-ts-core` via `gh` CLI |
253
+ | `report-issue-local` | File a bug or feature request against this server's own repo via `gh` CLI |
254
+ | `api-auth` | Auth modes, scopes, JWT/OAuth |
255
+ | `api-canvas` | DataCanvas: register tabular data, run SQL, export, plus the `spillover()` helper for big result sets — Tier 3 opt-in |
256
+ | `api-config` | AppConfig, parseConfig, env vars |
257
+ | `api-context` | Context interface, logger, state, progress |
258
+ | `api-errors` | McpError, JsonRpcErrorCode, error patterns |
259
+ | `api-services` | LLM, Speech, Graph services |
260
+ | `api-testing` | createMockContext, test patterns |
261
+ | `api-utils` | Formatting, parsing, security, pagination, scheduling, telemetry helpers |
262
+ | `api-telemetry` | OTel catalog: spans, metrics, completion logs, env config, cardinality rules |
263
+ | `api-workers` | Cloudflare Workers runtime |
264
+
265
+ When you complete a skill's checklist, check the boxes and add a completion timestamp at the end (e.g., `Completed: 2026-05-21`).
266
+
267
+ ---
268
+
269
+ ## Commands
270
+
271
+ | Command | Purpose |
272
+ |:--------|:--------|
273
+ | `bun run build` | Compile TypeScript |
274
+ | `bun run rebuild` | Clean + build |
275
+ | `bun run clean` | Remove build artifacts |
276
+ | `bun run devcheck` | Lint + format + typecheck + security + changelog sync |
277
+ | `bun run audit:refresh` | Delete `bun.lock`, reinstall, re-audit. Use when `devcheck` flags a transitive advisory — stale lockfile can mask already-patched deps. If advisory survives, it's real. |
278
+ | `bun run tree` | Generate directory structure doc |
279
+ | `bun run format` | Auto-fix formatting |
280
+ | `bun run test` | Run tests |
281
+ | `bun run lint:mcp` | Validate MCP definitions against spec |
282
+ | `bun run lint:packaging` | Validate env var alignment between `manifest.json` and `server.json` |
283
+ | `bun run bundle` | Build and pack as `.mcpb` for one-click Claude Desktop install |
284
+ | `bun run start:stdio` | Production mode (stdio) |
285
+ | `bun run start:http` | Production mode (HTTP) |
286
+ | `bun run changelog:build` | Regenerate `CHANGELOG.md` from per-version files |
287
+ | `bun run changelog:check` | Verify `CHANGELOG.md` is in sync (used by devcheck) |
288
+ | `bun run list-skills` | List available local skills (useful for sub-agents) |
289
+
290
+ ---
291
+
292
+ ## Bundling
293
+
294
+ `bun run bundle` produces a `.mcpb` extension bundle for one-click install in Claude Desktop. MCPB is stdio-only — HTTP deployments are unaffected. Delete `manifest.json` and `.mcpbignore` if not needed; `lint:packaging` skips cleanly.
295
+
296
+ **Adding an env var requires both files:** `server.json` (`environmentVariables[]`) and `manifest.json` (`mcp_config.env`). `lint:packaging` (run by `devcheck`) verifies the names match.
297
+
298
+ ---
299
+
300
+ ## Changelog
301
+
302
+ 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 `bun 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 `bun run changelog:build` — devcheck hard-fails on drift; never hand-edit it.
303
+
304
+ Each per-version file opens with YAML frontmatter:
305
+
306
+ ```markdown
307
+ ---
308
+ summary: "One-line headline, ≤350 chars" # required — powers the rollup index
309
+ breaking: false # optional — true flags breaking changes
310
+ security: false # optional — true flags security fixes
311
+ ---
312
+
313
+ # 0.1.0 — YYYY-MM-DD
314
+ ...
315
+ ```
316
+
317
+ `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`.
318
+
319
+ **Section order** (Keep a Changelog): Added, Changed, Deprecated, Removed, Fixed, Security. Include only sections with entries — don't ship empty headers.
320
+
321
+ ---
322
+
323
+ ## Imports
324
+
325
+ ```ts
326
+ // Framework — z is re-exported, no separate zod import needed
327
+ import { tool, z } from '@cyanheads/mcp-ts-core';
328
+ import { McpError, JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
329
+
330
+ // Server's own code — via path alias
331
+ import { getEiaApiService } from '@/services/eia/eia-service.js';
332
+ ```
333
+
334
+ ---
335
+
336
+ ## Checklist
337
+
338
+ - [ ] 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()`)
339
+ - [ ] 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`.
340
+ - [ ] JSDoc `@fileoverview` + `@module` on every file
341
+ - [ ] `ctx.log` for logging, `ctx.state` for storage
342
+ - [ ] Handlers throw on failure — error factories or plain `Error`, no try/catch
343
+ - [ ] `format()` renders all data the LLM needs — different clients forward different surfaces (Claude Code → `structuredContent`, Claude Desktop → `content[]`); both must carry the same data
344
+ - [ ] EIA wrapping: raw/domain/output schemas reviewed against real upstream sparsity/nullability; data values are strings — do not coerce silently
345
+ - [ ] EIA wrapping: normalization and `format()` preserve uncertainty; do not fabricate facts from missing upstream data
346
+ - [ ] EIA wrapping: tests include at least one sparse payload case with omitted upstream fields
347
+ - [ ] Route tree and facet caches populated before use; retry/rate-limit contract declared on each tool
348
+ - [ ] DataCanvas spillover via `ctx.core.canvas?` — graceful degradation when absent
349
+ - [ ] Registered in `createApp()` arrays (directly or via barrel exports)
350
+ - [ ] Tests use `createMockContext()` from `@cyanheads/mcp-ts-core/testing`
351
+ - [ ] `bun run devcheck` passes
package/Dockerfile ADDED
@@ -0,0 +1,99 @@
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
+ LABEL org.opencontainers.image.title="eia-energy-mcp-server"
41
+ LABEL org.opencontainers.image.description="Browse and query the U.S. Energy Information Administration API v2 — electricity, petroleum, natural gas, coal, forecasts, and more via MCP. STDIO or Streamable HTTP."
42
+ LABEL org.opencontainers.image.source="https://github.com/cyanheads/eia-energy-mcp-server"
43
+ LABEL org.opencontainers.image.licenses="Apache-2.0"
44
+
45
+ # Copy dependency manifests
46
+ COPY package.json bun.lock ./
47
+
48
+ # Install only production dependencies, ignoring any lifecycle scripts (like 'prepare')
49
+ # that are not needed in the final production image.
50
+ RUN bun install --production --frozen-lockfile --ignore-scripts
51
+
52
+ # Conditionally install OpenTelemetry optional peer dependencies (Tier 3).
53
+ # These are not bundled by default to keep the base image lean. Enable at build time
54
+ # with: docker build --build-arg OTEL_ENABLED=true
55
+ ARG OTEL_ENABLED=true
56
+ RUN if [ "$OTEL_ENABLED" = "true" ]; then \
57
+ bun add @hono/otel \
58
+ @opentelemetry/instrumentation-http \
59
+ @opentelemetry/exporter-metrics-otlp-http \
60
+ @opentelemetry/exporter-trace-otlp-http \
61
+ @opentelemetry/instrumentation-pino \
62
+ @opentelemetry/resources \
63
+ @opentelemetry/sdk-metrics \
64
+ @opentelemetry/sdk-node \
65
+ @opentelemetry/sdk-trace-node \
66
+ @opentelemetry/semantic-conventions; \
67
+ fi
68
+
69
+ # Copy the compiled application code from the build stage
70
+ COPY --from=build /usr/src/app/dist ./dist
71
+
72
+ # The 'oven/bun' image already provides a non-root user named 'bun'.
73
+ # We will use this existing user for enhanced security.
74
+
75
+ # Create and set permissions for the log directory, assigning ownership to the 'bun' user.
76
+ RUN mkdir -p /var/log/eia-energy-mcp-server && chown -R bun:bun /var/log/eia-energy-mcp-server
77
+
78
+ # Switch to the non-root user
79
+ USER bun
80
+
81
+ # Define an argument for the port, allowing it to be overridden at build time.
82
+ # The `PORT` variable is often injected by cloud environments at runtime.
83
+ ARG PORT
84
+
85
+ # Set runtime environment variables
86
+ # Note: PORT is an automatic variable in many cloud environments (e.g., Cloud Run)
87
+ ENV MCP_HTTP_PORT=${PORT:-3010}
88
+ ENV MCP_HTTP_HOST="0.0.0.0"
89
+ ENV MCP_TRANSPORT_TYPE="http"
90
+ ENV MCP_SESSION_MODE="stateless"
91
+ ENV MCP_LOG_LEVEL="info"
92
+ ENV LOGS_DIR="/var/log/eia-energy-mcp-server"
93
+ ENV MCP_FORCE_CONSOLE_LOGGING="true"
94
+
95
+ # Expose the port the server listens on
96
+ EXPOSE ${MCP_HTTP_PORT}
97
+
98
+ # The command to start the server
99
+ CMD ["bun", "run", "dist/index.js"]
package/LICENSE ADDED
@@ -0,0 +1,195 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
48
+ in the Work by the copyright owner or by an individual or Legal Entity
49
+ authorized to submit on behalf of the copyright owner. For the purposes
50
+ of this definition, "submitted" means any form of electronic, verbal,
51
+ or written communication sent to the Licensor or its representatives,
52
+ including but not limited to communication on electronic mailing lists,
53
+ source code control systems, and issue tracking systems that are managed
54
+ by, or on behalf of, the Licensor for the purpose of discussing and
55
+ improving the Work, but excluding communication that is conspicuously
56
+ marked or designated in writing by the copyright owner as "Not a
57
+ Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
60
+ whom a Contribution has been received by the Licensor and incorporated
61
+ within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of
64
+ this License, each Contributor hereby grants to You a perpetual,
65
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
66
+ copyright license to reproduce, prepare Derivative Works of,
67
+ publicly display, publicly perform, sublicense, and distribute the
68
+ Work and such Derivative Works in Source or Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ (except as stated in this section) patent license to make, have made,
74
+ use, offer to sell, sell, import, and otherwise transfer the Work,
75
+ where such license applies only to those patent claims licensable
76
+ by such Contributor that are necessarily infringed by their
77
+ Contribution(s) alone or by the combination of their Contribution(s)
78
+ with the Work to which such Contribution(s) was submitted. If You
79
+ institute patent litigation against any entity (including a cross-claim
80
+ or counterclaim in a lawsuit) alleging that the Work or any
81
+ Contribution embodied within the Work constitutes direct or contributory
82
+ patent infringement, then any patent licenses granted to You under
83
+ this License for that Work shall terminate as of the date such
84
+ litigation is filed.
85
+
86
+ 4. Redistribution. You may reproduce and distribute copies of the
87
+ Work or Derivative Works thereof in any medium, with or without
88
+ modifications, and in Source or Object form, provided that You
89
+ meet the following conditions:
90
+
91
+ (a) You must give any other recipients of the Work or Derivative
92
+ Works a copy of this License; and
93
+
94
+ (b) You must cause any modified files to carry prominent notices
95
+ stating that You changed the files; and
96
+
97
+ (c) You must retain, in the Source form of any Derivative Works
98
+ that You distribute, all copyright, patent, trademark, and
99
+ attribution notices from the Source form of the Work,
100
+ excluding those notices that do not pertain to any part of
101
+ the Derivative Works; and
102
+
103
+ (d) If the Work includes a "NOTICE" text file as part of its
104
+ distribution, You must include a readable copy of the
105
+ attribution notices contained within such NOTICE file, in
106
+ at least one of the following places: within a NOTICE text
107
+ file distributed as part of the Derivative Works; within
108
+ the Source form or documentation, if provided along with the
109
+ Derivative Works; or, within a display generated by the
110
+ Derivative Works, if and wherever such third-party notices
111
+ normally appear. The contents of the NOTICE file are for
112
+ informational purposes only and do not modify the License.
113
+ You may add Your own attribution notices within Derivative
114
+ Works that You distribute, alongside or as an addendum to
115
+ the NOTICE text from the Work, provided that such additional
116
+ attribution notices cannot be construed as modifying the
117
+ License.
118
+
119
+ You may add Your own license statement for Your modifications and
120
+ may provide additional grant of rights to use, copy, modify, merge,
121
+ publish, distribute, sublicense, and/or sell copies of Your
122
+ modifications, or for such Derivative Works as a whole, under
123
+ the terms and conditions of this License.
124
+
125
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
126
+ any Contribution intentionally submitted for inclusion in the Work
127
+ by You to the Licensor shall be under the terms and conditions of
128
+ this License, without any additional terms or conditions.
129
+ Notwithstanding the above, nothing herein shall supersede or modify
130
+ the terms of any separate license agreement you may have executed
131
+ with Licensor regarding such Contributions.
132
+
133
+ 6. Trademarks. This License does not grant permission to use the trade
134
+ names, trademarks, service marks, or product names of the Licensor,
135
+ except as required for reasonable and customary use in describing the
136
+ origin of the Work and reproducing the content of the NOTICE file.
137
+
138
+ 7. Disclaimer of Warranty. Unless required by applicable law or
139
+ agreed to in writing, Licensor provides the Work (and each
140
+ Contributor provides its Contributions) on an "AS IS" BASIS,
141
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
142
+ implied, including, without limitation, any warranties or conditions
143
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
144
+ PARTICULAR PURPOSE. You are solely responsible for determining the
145
+ appropriateness of using or reproducing the Work and assume any
146
+ risks associated with Your exercise of permissions under this License.
147
+
148
+ 8. Limitation of Liability. In no event and under no legal theory,
149
+ whether in tort (including negligence), contract, or otherwise,
150
+ unless required by applicable law (such as deliberate and grossly
151
+ negligent acts) or agreed to in writing, shall any Contributor be
152
+ liable to You for damages, including any direct, indirect, special,
153
+ incidental, or exemplary damages of any character arising as a
154
+ result of this License or out of the use or inability to use the
155
+ Work (including but not limited to damages for loss of goodwill,
156
+ work stoppage, computer failure or malfunction, or all other
157
+ commercial damages or losses), even if such Contributor has been
158
+ advised of the possibility of such damages.
159
+
160
+ 9. Accepting Warranty or Additional Liability. While redistributing
161
+ the Work or Derivative Works thereof, You may choose to offer,
162
+ and charge a fee for, acceptance of support, warranty, indemnity,
163
+ or other liability obligations and/or rights consistent with this
164
+ License. However, in accepting such obligations, You may offer such
165
+ obligations only on Your own behalf and on Your sole responsibility,
166
+ not on behalf of any other Contributor, and only if You agree to
167
+ indemnify, defend, and hold each Contributor harmless for any
168
+ liability incurred by, or claims asserted against, such Contributor
169
+ by reason of your accepting any such warranty or additional liability.
170
+
171
+ END OF TERMS AND CONDITIONS
172
+
173
+ APPENDIX: How to apply the Apache License to your work.
174
+
175
+ To apply the Apache License to your work, attach the following
176
+ boilerplate notice, with the fields enclosed by brackets "[]"
177
+ replaced with your own identifying information. (Don't include
178
+ the brackets!) The text should be enclosed in the appropriate
179
+ comment syntax for the comment format in use. We recommend that
180
+ you also include a "file or directory name and description of purpose"
181
+ on the same line as the copyright.
182
+
183
+ Copyright [yyyy] [name of copyright owner]
184
+
185
+ Licensed under the Apache License, Version 2.0 (the "License");
186
+ you may not use this file except in compliance with the License.
187
+ You may obtain a copy of the License at
188
+
189
+ http://www.apache.org/licenses/LICENSE-2.0
190
+
191
+ Unless required by applicable law or agreed to in writing, software
192
+ distributed under the License is distributed on an "AS IS" BASIS,
193
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
194
+ See the License for the specific language governing permissions and
195
+ limitations under the License.