openstates-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 (77) hide show
  1. package/CLAUDE.md +397 -0
  2. package/Dockerfile +99 -0
  3. package/LICENSE +201 -0
  4. package/README.md +324 -0
  5. package/changelog/0.1.x/0.1.0.md +23 -0
  6. package/changelog/0.1.x/0.1.1.md +29 -0
  7. package/changelog/template.md +119 -0
  8. package/dist/config/server-config.d.ts +13 -0
  9. package/dist/config/server-config.d.ts.map +1 -0
  10. package/dist/config/server-config.js +19 -0
  11. package/dist/config/server-config.js.map +1 -0
  12. package/dist/index.d.ts +7 -0
  13. package/dist/index.d.ts.map +1 -0
  14. package/dist/index.js +50 -0
  15. package/dist/index.js.map +1 -0
  16. package/dist/mcp-server/prompts/definitions/bill-research.prompt.d.ts +11 -0
  17. package/dist/mcp-server/prompts/definitions/bill-research.prompt.d.ts.map +1 -0
  18. package/dist/mcp-server/prompts/definitions/bill-research.prompt.js +65 -0
  19. package/dist/mcp-server/prompts/definitions/bill-research.prompt.js.map +1 -0
  20. package/dist/mcp-server/prompts/definitions/legislator-profile.prompt.d.ts +10 -0
  21. package/dist/mcp-server/prompts/definitions/legislator-profile.prompt.d.ts.map +1 -0
  22. package/dist/mcp-server/prompts/definitions/legislator-profile.prompt.js +55 -0
  23. package/dist/mcp-server/prompts/definitions/legislator-profile.prompt.js.map +1 -0
  24. package/dist/mcp-server/resources/definitions/jurisdiction.resource.d.ts +9 -0
  25. package/dist/mcp-server/resources/definitions/jurisdiction.resource.d.ts.map +1 -0
  26. package/dist/mcp-server/resources/definitions/jurisdiction.resource.js +60 -0
  27. package/dist/mcp-server/resources/definitions/jurisdiction.resource.js.map +1 -0
  28. package/dist/mcp-server/tools/definitions/get-bill.tool.d.ts +121 -0
  29. package/dist/mcp-server/tools/definitions/get-bill.tool.d.ts.map +1 -0
  30. package/dist/mcp-server/tools/definitions/get-bill.tool.js +319 -0
  31. package/dist/mcp-server/tools/definitions/get-bill.tool.js.map +1 -0
  32. package/dist/mcp-server/tools/definitions/get-committee.tool.d.ts +30 -0
  33. package/dist/mcp-server/tools/definitions/get-committee.tool.d.ts.map +1 -0
  34. package/dist/mcp-server/tools/definitions/get-committee.tool.js +89 -0
  35. package/dist/mcp-server/tools/definitions/get-committee.tool.js.map +1 -0
  36. package/dist/mcp-server/tools/definitions/get-event.tool.d.ts +65 -0
  37. package/dist/mcp-server/tools/definitions/get-event.tool.d.ts.map +1 -0
  38. package/dist/mcp-server/tools/definitions/get-event.tool.js +231 -0
  39. package/dist/mcp-server/tools/definitions/get-event.tool.js.map +1 -0
  40. package/dist/mcp-server/tools/definitions/get-jurisdiction.tool.d.ts +34 -0
  41. package/dist/mcp-server/tools/definitions/get-jurisdiction.tool.d.ts.map +1 -0
  42. package/dist/mcp-server/tools/definitions/get-jurisdiction.tool.js +99 -0
  43. package/dist/mcp-server/tools/definitions/get-jurisdiction.tool.js.map +1 -0
  44. package/dist/mcp-server/tools/definitions/get-legislators-by-location.tool.d.ts +53 -0
  45. package/dist/mcp-server/tools/definitions/get-legislators-by-location.tool.d.ts.map +1 -0
  46. package/dist/mcp-server/tools/definitions/get-legislators-by-location.tool.js +156 -0
  47. package/dist/mcp-server/tools/definitions/get-legislators-by-location.tool.js.map +1 -0
  48. package/dist/mcp-server/tools/definitions/list-jurisdictions.tool.d.ts +42 -0
  49. package/dist/mcp-server/tools/definitions/list-jurisdictions.tool.d.ts.map +1 -0
  50. package/dist/mcp-server/tools/definitions/list-jurisdictions.tool.js +110 -0
  51. package/dist/mcp-server/tools/definitions/list-jurisdictions.tool.js.map +1 -0
  52. package/dist/mcp-server/tools/definitions/search-bills.tool.d.ts +102 -0
  53. package/dist/mcp-server/tools/definitions/search-bills.tool.d.ts.map +1 -0
  54. package/dist/mcp-server/tools/definitions/search-bills.tool.js +285 -0
  55. package/dist/mcp-server/tools/definitions/search-bills.tool.js.map +1 -0
  56. package/dist/mcp-server/tools/definitions/search-committees.tool.d.ts +44 -0
  57. package/dist/mcp-server/tools/definitions/search-committees.tool.d.ts.map +1 -0
  58. package/dist/mcp-server/tools/definitions/search-committees.tool.js +127 -0
  59. package/dist/mcp-server/tools/definitions/search-committees.tool.js.map +1 -0
  60. package/dist/mcp-server/tools/definitions/search-events.tool.d.ts +62 -0
  61. package/dist/mcp-server/tools/definitions/search-events.tool.d.ts.map +1 -0
  62. package/dist/mcp-server/tools/definitions/search-events.tool.js +198 -0
  63. package/dist/mcp-server/tools/definitions/search-events.tool.js.map +1 -0
  64. package/dist/mcp-server/tools/definitions/search-people.tool.d.ts +64 -0
  65. package/dist/mcp-server/tools/definitions/search-people.tool.d.ts.map +1 -0
  66. package/dist/mcp-server/tools/definitions/search-people.tool.js +193 -0
  67. package/dist/mcp-server/tools/definitions/search-people.tool.js.map +1 -0
  68. package/dist/services/openstates/openstates-service.d.ts +30 -0
  69. package/dist/services/openstates/openstates-service.d.ts.map +1 -0
  70. package/dist/services/openstates/openstates-service.js +246 -0
  71. package/dist/services/openstates/openstates-service.js.map +1 -0
  72. package/dist/services/openstates/types.d.ts +324 -0
  73. package/dist/services/openstates/types.d.ts.map +1 -0
  74. package/dist/services/openstates/types.js +6 -0
  75. package/dist/services/openstates/types.js.map +1 -0
  76. package/package.json +90 -0
  77. package/server.json +99 -0
package/CLAUDE.md ADDED
@@ -0,0 +1,397 @@
1
+ # Developer Protocol
2
+
3
+ **Server:** openstates-mcp-server
4
+ **Version:** 0.1.1
5
+ **Framework:** [@cyanheads/mcp-ts-core](https://www.npmjs.com/package/@cyanheads/mcp-ts-core) `^0.9.7`
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
+ ## Core Rules
15
+
16
+ - **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.
17
+ - **Use `ctx.log`** for request-scoped logging. No `console` calls.
18
+ - **Use `ctx.state`** for tenant-scoped storage. Never access persistence directly.
19
+ - **Check `ctx.elicit` / `ctx.sample`** for presence before calling.
20
+ - **Secrets in env vars only** — never hardcoded.
21
+
22
+ ---
23
+
24
+ ## Patterns
25
+
26
+ ### Tool
27
+
28
+ ```ts
29
+ import { tool, z } from '@cyanheads/mcp-ts-core';
30
+ import { JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
31
+ import { getOpenStatesApiService } from '@/services/openstates/openstates-service.js';
32
+
33
+ export const searchBills = tool('openstates_search_bills', {
34
+ title: 'Search Bills',
35
+ description: 'Search state legislative bills across all covered US jurisdictions...',
36
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: true },
37
+ input: z.object({
38
+ jurisdiction: z.string().optional().describe('State name, abbreviation, or OCD-ID.'),
39
+ q: z.string().optional().describe('Full-text search across bill titles, abstracts, and text.'),
40
+ // ... additional filters
41
+ }),
42
+ output: z.object({
43
+ results: z.array(z.object({ id: z.string().describe('OCD bill ID.'), /* ... */ })).describe('Bills.'),
44
+ pagination: z.object({ total_items: z.number().describe('Total matching bills.'), /* ... */ }).describe('Pagination.'),
45
+ message: z.string().optional().describe('Recovery hint when results are empty.'),
46
+ }),
47
+ errors: [
48
+ {
49
+ reason: 'missing_scope',
50
+ code: JsonRpcErrorCode.InvalidParams,
51
+ when: 'Neither jurisdiction nor q was provided.',
52
+ recovery: 'Provide a jurisdiction or a full-text search term via q, or both.',
53
+ },
54
+ ],
55
+
56
+ async handler(input, ctx) {
57
+ if (!input.jurisdiction && !input.q) {
58
+ throw ctx.fail('missing_scope', 'Either jurisdiction or q is required.', {
59
+ ...ctx.recoveryFor('missing_scope'),
60
+ });
61
+ }
62
+ const svc = getOpenStatesApiService();
63
+ const result = await svc.searchBills(input, ctx);
64
+ ctx.log.info('Searched bills', { count: result.results.length });
65
+ return result;
66
+ },
67
+
68
+ format: (result) => [{ type: 'text', text: result.results.map(b => `## ${b.identifier}`).join('\n') }],
69
+ });
70
+ ```
71
+
72
+ ### Resource
73
+
74
+ ```ts
75
+ import { resource, z } from '@cyanheads/mcp-ts-core';
76
+ import { notFound } from '@cyanheads/mcp-ts-core/errors';
77
+ import { getOpenStatesApiService } from '@/services/openstates/openstates-service.js';
78
+
79
+ export const jurisdictionResource = resource('openstates://jurisdiction/{jurisdiction_id}', {
80
+ title: 'Jurisdiction Metadata',
81
+ description: 'Jurisdiction metadata including current sessions, coverage dates, and bill/people update timestamps.',
82
+ mimeType: 'application/json',
83
+ params: z.object({
84
+ jurisdiction_id: z.string().describe('OCD jurisdiction ID, state name, or two-letter abbreviation.'),
85
+ }),
86
+ async handler(params, ctx) {
87
+ const svc = getOpenStatesApiService();
88
+ const jurisdiction = await svc.getJurisdiction(params.jurisdiction_id, ['legislative_sessions'], ctx);
89
+ if (!jurisdiction) throw notFound(`Jurisdiction not found: ${params.jurisdiction_id}`, { jurisdiction_id: params.jurisdiction_id });
90
+ return jurisdiction;
91
+ },
92
+ });
93
+ ```
94
+
95
+ ### Prompt
96
+
97
+ ```ts
98
+ import { prompt, z } from '@cyanheads/mcp-ts-core';
99
+
100
+ export const billResearch = prompt('openstates_bill_research', {
101
+ description: 'Structured framework for analyzing a state bill: summary, sponsors, committee referrals, action timeline, vote record, and related legislation.',
102
+ args: z.object({
103
+ jurisdiction: z.string().describe('State name, abbreviation, or OCD-ID.'),
104
+ session: z.string().describe('Session identifier.'),
105
+ bill_id: z.string().describe('Bill identifier as used by the legislature (e.g., "HB 1000").'),
106
+ }),
107
+ generate: (args) => [
108
+ { role: 'user', content: { type: 'text', text: `Research bill ${args.bill_id} in ${args.jurisdiction} session ${args.session}...` } },
109
+ ],
110
+ });
111
+ ```
112
+
113
+ ### Server config
114
+
115
+ ```ts
116
+ // src/config/server-config.ts
117
+ import { z } from '@cyanheads/mcp-ts-core';
118
+ import { parseEnvConfig } from '@cyanheads/mcp-ts-core/config';
119
+
120
+ const ServerConfigSchema = z.object({
121
+ apiKey: z.string().min(1).describe('Open States API key from open.pluralpolicy.com'),
122
+ apiBaseUrl: z.string().default('https://v3.openstates.org').describe('Open States API base URL'),
123
+ });
124
+
125
+ let _config: z.infer<typeof ServerConfigSchema> | undefined;
126
+ export function getServerConfig() {
127
+ _config ??= parseEnvConfig(ServerConfigSchema, {
128
+ apiKey: 'OPENSTATES_API_KEY',
129
+ apiBaseUrl: 'OPENSTATES_API_BASE_URL',
130
+ });
131
+ return _config;
132
+ }
133
+ ```
134
+
135
+ `parseEnvConfig` maps Zod schema paths → env var names so errors name the variable (`MY_API_KEY`) not the path (`apiKey`). Throws `ConfigurationError`, which the framework prints as a clean startup banner.
136
+
137
+ ---
138
+
139
+ ## Context
140
+
141
+ Handlers receive a unified `ctx` object. Key properties:
142
+
143
+ | Property | Description |
144
+ |:---------|:------------|
145
+ | `ctx.log` | Request-scoped logger — `.debug()`, `.info()`, `.notice()`, `.warning()`, `.error()`. Auto-correlates requestId, traceId, tenantId. |
146
+ | `ctx.state` | Tenant-scoped KV — `.get(key)`, `.set(key, value, { ttl? })`, `.delete(key)`, `.list(prefix, { cursor, limit })`. Accepts any serializable value. |
147
+ | `ctx.elicit` | Ask user for structured input. **Check for presence first:** `if (ctx.elicit) { ... }` |
148
+ | `ctx.sample` | Request LLM completion from the client. **Check for presence first:** `if (ctx.sample) { ... }` |
149
+ | `ctx.signal` | `AbortSignal` for cancellation. |
150
+ | `ctx.progress` | Task progress (present when `task: true`) — `.setTotal(n)`, `.increment()`, `.update(message)`. |
151
+ | `ctx.requestId` | Unique request ID. |
152
+ | `ctx.tenantId` | Tenant ID from JWT or `'default'` for stdio. |
153
+
154
+ ---
155
+
156
+ ## Errors
157
+
158
+ Handlers throw — the framework catches, classifies, and formats.
159
+
160
+ **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.
161
+
162
+ ```ts
163
+ errors: [
164
+ { reason: 'no_match', code: JsonRpcErrorCode.NotFound,
165
+ when: 'No item matched the query',
166
+ recovery: 'Broaden the query or check the spelling and try again.' },
167
+ ],
168
+ async handler(input, ctx) {
169
+ const item = await db.find(input.id);
170
+ if (!item) throw ctx.fail('no_match', `No item ${input.id}`);
171
+ return item;
172
+ }
173
+ ```
174
+
175
+ **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.
176
+
177
+ **Fallback (no contract entry fits):** throw via factories or plain `Error`.
178
+
179
+ ```ts
180
+ // Error factories — explicit code
181
+ import { notFound, serviceUnavailable } from '@cyanheads/mcp-ts-core/errors';
182
+ throw notFound('Item not found', { itemId });
183
+ throw serviceUnavailable('API unavailable', { url }, { cause: err });
184
+
185
+ // Plain Error — framework auto-classifies from message patterns
186
+ throw new Error('Item not found'); // → NotFound
187
+ throw new Error('Invalid query format'); // → ValidationError
188
+
189
+ // McpError — when no factory exists for the code
190
+ import { McpError, JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
191
+ throw new McpError(JsonRpcErrorCode.DatabaseError, 'Connection failed', { pool: 'primary' });
192
+ ```
193
+
194
+ See framework CLAUDE.md and the `api-errors` skill for the full auto-classification table, all available factories, and the contract reference.
195
+
196
+ ---
197
+
198
+ ## Structure
199
+
200
+ ```text
201
+ src/
202
+ index.ts # createApp() entry point
203
+ config/
204
+ server-config.ts # Server-specific env vars (OPENSTATES_API_KEY, OPENSTATES_API_BASE_URL)
205
+ services/
206
+ openstates/
207
+ openstates-service.ts # Open States API v3 HTTP client (init/accessor pattern)
208
+ types.ts # Domain types (Bill, Person, Committee, Event, Jurisdiction)
209
+ mcp-server/
210
+ tools/definitions/
211
+ search-bills.tool.ts # openstates_search_bills
212
+ get-bill.tool.ts # openstates_get_bill
213
+ search-people.tool.ts # openstates_search_people
214
+ get-legislators-by-location.tool.ts # openstates_get_legislators_by_location
215
+ search-committees.tool.ts # openstates_search_committees
216
+ get-committee.tool.ts # openstates_get_committee
217
+ search-events.tool.ts # openstates_search_events
218
+ get-event.tool.ts # openstates_get_event
219
+ list-jurisdictions.tool.ts # openstates_list_jurisdictions
220
+ get-jurisdiction.tool.ts # openstates_get_jurisdiction
221
+ resources/definitions/
222
+ jurisdiction.resource.ts # openstates://jurisdiction/{jurisdiction_id}
223
+ prompts/definitions/
224
+ bill-research.prompt.ts # openstates_bill_research
225
+ legislator-profile.prompt.ts # openstates_legislator_profile
226
+ ```
227
+
228
+ ---
229
+
230
+ ## Naming
231
+
232
+ | What | Convention | Example |
233
+ |:-----|:-----------|:--------|
234
+ | Files | kebab-case with suffix | `search-docs.tool.ts` |
235
+ | Tool/resource/prompt names | snake_case | `search_docs` |
236
+ | Directories | kebab-case | `src/services/doc-search/` |
237
+ | Descriptions | Single string or template literal, no `+` concatenation | `'Search items by query and filter.'` |
238
+
239
+ ---
240
+
241
+ ## Skills
242
+
243
+ 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.
244
+
245
+ **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.
246
+
247
+ Available skills:
248
+
249
+ | Skill | Purpose |
250
+ |:------|:--------|
251
+ | `setup` | Post-init project orientation |
252
+ | `design-mcp-server` | Design tool surface, resources, and services for a new server |
253
+ | `add-tool` | Scaffold a new tool definition |
254
+ | `add-app-tool` | Scaffold an MCP App tool + paired UI resource |
255
+ | `add-resource` | Scaffold a new resource definition |
256
+ | `add-prompt` | Scaffold a new prompt definition |
257
+ | `add-service` | Scaffold a new service integration |
258
+ | `add-test` | Scaffold test file for a tool, resource, or service |
259
+ | `field-test` | Exercise tools/resources/prompts with real inputs, verify behavior, report issues |
260
+ | `security-pass` | Audit server for MCP-flavored security gaps: output injection, scope blast radius, input sinks, tenant isolation |
261
+ | `devcheck` | Lint, format, typecheck, audit |
262
+ | `polish-docs-meta` | Finalize docs, README, metadata, and agent protocol for shipping |
263
+ | `maintenance` | Investigate changelogs, adopt upstream changes, sync skills to agent dirs |
264
+ | `report-issue-framework` | File a bug or feature request against `@cyanheads/mcp-ts-core` via `gh` CLI |
265
+ | `report-issue-local` | File a bug or feature request against this server's own repo via `gh` CLI |
266
+ | `api-auth` | Auth modes, scopes, JWT/OAuth |
267
+ | `api-canvas` | DataCanvas: register tabular data, run SQL, export, plus the `spillover()` helper for big result sets — Tier 3 opt-in |
268
+ | `api-config` | AppConfig, parseConfig, env vars |
269
+ | `api-context` | Context interface, logger, state, progress |
270
+ | `api-errors` | McpError, JsonRpcErrorCode, error patterns |
271
+ | `api-services` | LLM, Speech, Graph services |
272
+ | `api-testing` | createMockContext, test patterns |
273
+ | `api-utils` | Formatting, parsing, security, pagination, scheduling, telemetry helpers |
274
+ | `api-telemetry` | OTel catalog: spans, metrics, completion logs, env config, cardinality rules |
275
+ | `api-workers` | Cloudflare Workers runtime |
276
+
277
+ When you complete a skill's checklist, check the boxes and add a completion timestamp at the end (e.g., `Completed: 2026-03-11`).
278
+
279
+ ---
280
+
281
+ ## Commands
282
+
283
+ **Runtime:** Scripts use `tsx` — both `npm run <cmd>` and `bun run <cmd>` work. `bun` is slightly faster for script invocation but not required.
284
+
285
+ | Command | Purpose |
286
+ |:--------|:--------|
287
+ | `npm run build` | Compile TypeScript |
288
+ | `npm run rebuild` | Clean + build |
289
+ | `npm run clean` | Remove build artifacts |
290
+ | `npm run devcheck` | Lint + format + typecheck + security + changelog sync |
291
+ | `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. |
292
+ | `npm run tree` | Generate directory structure doc |
293
+ | `npm run format` | Auto-fix formatting |
294
+ | `npm test` | Run tests |
295
+ | `npm run start:stdio` | Production mode (stdio) |
296
+ | `npm run start:http` | Production mode (HTTP) |
297
+ | `npm run changelog:build` | Regenerate `CHANGELOG.md` from `changelog/*.md` |
298
+ | `npm run changelog:check` | Verify `CHANGELOG.md` is in sync (used by devcheck) |
299
+ | `npm run bundle` | Build and pack as `.mcpb` for one-click Claude Desktop install |
300
+
301
+ ---
302
+
303
+ ## Bundling
304
+
305
+ `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.
306
+
307
+ **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.
308
+
309
+ **README install badges.** Drop these into the project README to give users one-click install paths. Fill in `<OWNER>` / `<REPO>` / `<PACKAGE_NAME>` and encode the per-server config. Cursor + VS Code badges assume the server is published to npm; Claude Desktop downloads the `.mcpb` directly so npm publishing isn't required.
310
+
311
+ | Client | Mechanism |
312
+ |:-------|:----------|
313
+ | Claude Desktop | Browser downloads the `.mcpb` from the latest GitHub Release; OS file handler routes it to Claude Desktop, which opens the install dialog. No deep-link URL scheme yet — this is the canonical path. |
314
+ | Cursor | Official `https://cursor.com/en/install-mcp` endpoint with base64 JSON config. |
315
+ | VS Code / Insiders | Official `vscode:mcp/install?...` deep link, wrapped in `https://vscode.dev/redirect?url=` so GitHub-rendered markdown doesn't strip the non-HTTP scheme. |
316
+ | Claude Code / Codex | CLI only (`claude mcp add` / `codex mcp add`); no URL scheme. |
317
+
318
+ ```markdown
319
+ [![Install in Claude Desktop](https://img.shields.io/badge/Install_in-Claude_Desktop-D97757?style=for-the-badge&logo=anthropic&logoColor=white)](https://github.com/<OWNER>/<REPO>/releases/latest/download/<PACKAGE_NAME>.mcpb)
320
+ [![Install in Cursor](https://cursor.com/deeplink/mcp-install-dark.svg)](https://cursor.com/en/install-mcp?name=<PACKAGE_NAME>&config=<BASE64_CONFIG>)
321
+ [![Install in VS Code](https://img.shields.io/badge/VS_Code-Install_Server-0098FF?style=for-the-badge&logo=visualstudiocode&logoColor=white)](https://vscode.dev/redirect?url=vscode:mcp/install?<URLENCODED_JSON>)
322
+ ```
323
+
324
+ Both install links route through HTTPS endpoints (`cursor.com/en/install-mcp` and `vscode.dev/redirect`) — GitHub-rendered markdown strips non-HTTP URL schemes from anchors, so a raw `cursor://` or `vscode:` link won't click through from github.com.
325
+
326
+ Generate the encoded configs (replace `<PACKAGE_NAME>` and add env vars for any required API keys):
327
+
328
+ ```bash
329
+ # Cursor: base64-encoded JSON. Split command/args, add env when keys are needed.
330
+ echo -n '{"command":"npx","args":["-y","<PACKAGE_NAME>"],"env":{"API_KEY":"your-api-key"}}' | base64
331
+ # Without env (no required keys):
332
+ echo -n '{"command":"npx","args":["-y","<PACKAGE_NAME>"]}' | base64
333
+
334
+ # VS Code: URL-encoded JSON. Same shape plus a `name` field.
335
+ node -p 'encodeURIComponent(JSON.stringify({name:"<SHORT_NAME>",command:"npx",args:["-y","<PACKAGE_NAME>"],env:{API_KEY:"your-api-key"}}))'
336
+ # Without env:
337
+ node -p 'encodeURIComponent(JSON.stringify({name:"<SHORT_NAME>",command:"npx",args:["-y","<PACKAGE_NAME>"]}))'
338
+ ```
339
+
340
+ Both clients use the same `{command, args, env}` shape (matching `mcp.json` schema). VS Code adds a top-level `name` field. Omit `env` entirely when no API keys are needed — don't include empty objects or framework-only vars like `MCP_TRANSPORT_TYPE`.
341
+
342
+ The Claude Desktop badge requires the bundle to ship with a stable filename — `bun run bundle` outputs `dist/<PACKAGE_NAME>.mcpb`, and `release-and-publish` attaches that file to the GitHub Release. `releases/latest/download/<PACKAGE_NAME>.mcpb` then redirects to the most recent release.
343
+
344
+ ---
345
+
346
+ ## Changelog
347
+
348
+ 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.
349
+
350
+ Each per-version file opens with YAML frontmatter:
351
+
352
+ ```markdown
353
+ ---
354
+ summary: "One-line headline, ≤350 chars" # required — powers the rollup index
355
+ breaking: false # optional — true flags breaking changes
356
+ security: false # optional — true flags security fixes
357
+ ---
358
+
359
+ # 0.1.0 — YYYY-MM-DD
360
+ ...
361
+ ```
362
+
363
+ `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`.
364
+
365
+ **Section order** (Keep a Changelog): Added, Changed, Deprecated, Removed, Fixed, Security. Include only sections with entries — don't ship empty headers.
366
+
367
+ **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.
368
+
369
+ ---
370
+
371
+ ## Imports
372
+
373
+ ```ts
374
+ // Framework — z is re-exported, no separate zod import needed
375
+ import { tool, z } from '@cyanheads/mcp-ts-core';
376
+ import { McpError, JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
377
+
378
+ // Server's own code — via path alias
379
+ import { getMyService } from '@/services/my-domain/my-service.js';
380
+ ```
381
+
382
+ ---
383
+
384
+ ## Checklist
385
+
386
+ - [ ] 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()`)
387
+ - [ ] 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`.
388
+ - [ ] JSDoc `@fileoverview` + `@module` on every file
389
+ - [ ] `ctx.log` for logging, `ctx.state` for storage
390
+ - [ ] Handlers throw on failure — error factories or plain `Error`, no try/catch
391
+ - [ ] `format()` renders all data the LLM needs — different clients forward different surfaces (Claude Code → `structuredContent`, Claude Desktop → `content[]`); both must carry the same data
392
+ - [ ] If wrapping external API: raw/domain/output schemas reviewed against real upstream sparsity/nullability before finalizing required vs optional fields
393
+ - [ ] If wrapping external API: normalization and `format()` preserve uncertainty; do not fabricate facts from missing upstream data
394
+ - [ ] If wrapping external API: tests include at least one sparse payload case with omitted upstream fields
395
+ - [ ] Registered in `createApp()` arrays (directly or via barrel exports)
396
+ - [ ] Tests use `createMockContext()` from `@cyanheads/mcp-ts-core/testing`
397
+ - [ ] `npm 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="openstates-mcp-server"
41
+ LABEL org.opencontainers.image.description="Search bills, legislators, committees, and events across all 50 US states, DC, and Puerto Rico via MCP."
42
+ LABEL org.opencontainers.image.source="https://github.com/cyanheads/openstates-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/openstates-mcp-server && chown -R bun:bun /var/log/openstates-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/openstates-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"]