@cyanheads/nonprofit-explorer-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 (34) hide show
  1. package/AGENTS.md +285 -0
  2. package/CLAUDE.md +285 -0
  3. package/Dockerfile +99 -0
  4. package/LICENSE +201 -0
  5. package/README.md +279 -0
  6. package/changelog/0.1.x/0.1.0.md +11 -0
  7. package/changelog/0.1.x/0.1.1.md +23 -0
  8. package/changelog/template.md +127 -0
  9. package/dist/index.d.ts +7 -0
  10. package/dist/index.d.ts.map +1 -0
  11. package/dist/index.js +24 -0
  12. package/dist/index.js.map +1 -0
  13. package/dist/mcp-server/tools/definitions/nonprofit-get-filings.tool.d.ts +72 -0
  14. package/dist/mcp-server/tools/definitions/nonprofit-get-filings.tool.d.ts.map +1 -0
  15. package/dist/mcp-server/tools/definitions/nonprofit-get-filings.tool.js +391 -0
  16. package/dist/mcp-server/tools/definitions/nonprofit-get-filings.tool.js.map +1 -0
  17. package/dist/mcp-server/tools/definitions/nonprofit-get-organization.tool.d.ts +53 -0
  18. package/dist/mcp-server/tools/definitions/nonprofit-get-organization.tool.d.ts.map +1 -0
  19. package/dist/mcp-server/tools/definitions/nonprofit-get-organization.tool.js +245 -0
  20. package/dist/mcp-server/tools/definitions/nonprofit-get-organization.tool.js.map +1 -0
  21. package/dist/mcp-server/tools/definitions/nonprofit-search.tool.d.ts +85 -0
  22. package/dist/mcp-server/tools/definitions/nonprofit-search.tool.d.ts.map +1 -0
  23. package/dist/mcp-server/tools/definitions/nonprofit-search.tool.js +216 -0
  24. package/dist/mcp-server/tools/definitions/nonprofit-search.tool.js.map +1 -0
  25. package/dist/services/nonprofit-explorer/nonprofit-explorer-service.d.ts +37 -0
  26. package/dist/services/nonprofit-explorer/nonprofit-explorer-service.d.ts.map +1 -0
  27. package/dist/services/nonprofit-explorer/nonprofit-explorer-service.js +171 -0
  28. package/dist/services/nonprofit-explorer/nonprofit-explorer-service.js.map +1 -0
  29. package/dist/services/nonprofit-explorer/types.d.ts +89 -0
  30. package/dist/services/nonprofit-explorer/types.d.ts.map +1 -0
  31. package/dist/services/nonprofit-explorer/types.js +6 -0
  32. package/dist/services/nonprofit-explorer/types.js.map +1 -0
  33. package/package.json +101 -0
  34. package/server.json +105 -0
package/AGENTS.md ADDED
@@ -0,0 +1,285 @@
1
+ # Developer Protocol
2
+
3
+ **Server:** nonprofit-explorer-mcp-server
4
+ **Version:** 0.1.1
5
+ **Framework:** [@cyanheads/mcp-ts-core](https://www.npmjs.com/package/@cyanheads/mcp-ts-core) `^0.9.19`
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
+ - **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.
22
+
23
+ ---
24
+
25
+ ## Patterns
26
+
27
+ ### Tool
28
+
29
+ ```ts
30
+ import { tool, z } from '@cyanheads/mcp-ts-core';
31
+ import { JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
32
+ import { getNonprofitExplorerService } from '@/services/nonprofit-explorer/nonprofit-explorer-service.js';
33
+
34
+ export const nonprofitSearch = tool('nonprofit_search', {
35
+ title: 'Search Nonprofits',
36
+ description: 'Search 1.8M+ IRS-recognized tax-exempt organizations by name, keyword, city, or phrase.',
37
+ annotations: { readOnlyHint: true },
38
+ input: z.object({
39
+ query: z.string().describe('Keyword search string.'),
40
+ state: z.string().length(2).optional().describe('Two-letter US state abbreviation.'),
41
+ page: z.number().int().min(0).default(0).describe('Zero-indexed page number. 25 results per page.'),
42
+ }),
43
+ output: z.object({
44
+ total_results: z.number().describe('Total matching orgs.'),
45
+ organizations: z.array(z.object({
46
+ ein: z.number().describe('EIN as integer.'),
47
+ name: z.string().describe('Legal org name.'),
48
+ })).describe('Matching organizations for the current page.'),
49
+ }),
50
+ errors: [
51
+ {
52
+ reason: 'no_results',
53
+ code: JsonRpcErrorCode.NotFound,
54
+ when: 'No organizations match the given query and filters',
55
+ recovery: 'Broaden the keyword query, remove one or more filters, or check spelling.',
56
+ },
57
+ ],
58
+ async handler(input, ctx) {
59
+ const svc = getNonprofitExplorerService();
60
+ const raw = await svc.search(input, ctx);
61
+ const orgs = raw.organizations ?? [];
62
+ if (orgs.length === 0) throw ctx.fail('no_results', `No results for "${input.query}"`);
63
+ return { total_results: raw.total_results ?? 0, organizations: orgs.map(o => ({ ein: o.ein, name: o.name ?? '' })) };
64
+ },
65
+ format: (result) => [{ type: 'text', text: result.organizations.map(o => `**${o.name}** (EIN: ${o.ein})`).join('\n') }],
66
+ });
67
+ ```
68
+
69
+ ### Server instructions
70
+
71
+ `createApp({ instructions })` — sent to clients on every `initialize` as session-level context. The nonprofit server uses this to orient agents on the search-first workflow and the filing-year lag.
72
+
73
+ ---
74
+
75
+ ## Context
76
+
77
+ Handlers receive a unified `ctx` object. Key properties:
78
+
79
+ | Property | Description |
80
+ |:---------|:------------|
81
+ | `ctx.log` | Request-scoped logger — `.debug()`, `.info()`, `.notice()`, `.warning()`, `.error()`. Auto-correlates requestId, traceId, tenantId. |
82
+ | `ctx.state` | Tenant-scoped KV — `.get(key)`, `.set(key, value, { ttl? })`, `.delete(key)`, `.list(prefix, { cursor, limit })`. Accepts any serializable value. |
83
+ | `ctx.signal` | `AbortSignal` for cancellation. |
84
+ | `ctx.requestId` | Unique request ID. |
85
+ | `ctx.tenantId` | Tenant ID from JWT or `'default'` for stdio. |
86
+
87
+ ---
88
+
89
+ ## Errors
90
+
91
+ Handlers throw — the framework catches, classifies, and formats.
92
+
93
+ **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).
94
+
95
+ ```ts
96
+ import { JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
97
+
98
+ errors: [
99
+ { reason: 'not_found', code: JsonRpcErrorCode.NotFound,
100
+ when: 'EIN does not correspond to a known org',
101
+ recovery: 'Verify the EIN with nonprofit_search. Use the integer EIN value.' },
102
+ ],
103
+ async handler(input, ctx) {
104
+ const org = await svc.getOrganization(normalizeEin(input.ein), ctx);
105
+ // service throws notFound on missing org — propagated by framework
106
+ return org;
107
+ }
108
+ ```
109
+
110
+ **Fallback (no contract entry fits):** throw via factories or plain `Error`.
111
+
112
+ ```ts
113
+ import { notFound, serviceUnavailable } from '@cyanheads/mcp-ts-core/errors';
114
+ throw notFound('Organization not found', { ein });
115
+ throw serviceUnavailable('ProPublica API unavailable', { url }, { cause: err });
116
+ ```
117
+
118
+ See framework CLAUDE.md and the `api-errors` skill for the full auto-classification table, all available factories, and the contract reference.
119
+
120
+ ---
121
+
122
+ ## Structure
123
+
124
+ ```text
125
+ src/
126
+ index.ts # createApp() entry point — 3 tools, nonprofit service init
127
+ services/
128
+ nonprofit-explorer/
129
+ nonprofit-explorer-service.ts # ProPublica API client (init/accessor pattern)
130
+ types.ts # Domain types (RawOrg, RawFiling, etc.)
131
+ mcp-server/
132
+ tools/definitions/
133
+ nonprofit-search.tool.ts # nonprofit_search
134
+ nonprofit-get-organization.tool.ts# nonprofit_get_organization
135
+ nonprofit-get-filings.tool.ts # nonprofit_get_filings
136
+ ```
137
+
138
+ ---
139
+
140
+ ## Naming
141
+
142
+ | What | Convention | Example |
143
+ |:-----|:-----------|:--------|
144
+ | Files | kebab-case with suffix | `nonprofit-search.tool.ts` |
145
+ | Tool/resource/prompt names | snake_case | `nonprofit_search` |
146
+ | Directories | kebab-case | `src/services/nonprofit-explorer/` |
147
+ | Descriptions | Single string or template literal, no `+` concatenation | `'Search orgs by name and filter.'` |
148
+
149
+ ---
150
+
151
+ ## Skills
152
+
153
+ 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.
154
+
155
+ **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.
156
+
157
+ Available skills:
158
+
159
+ | Skill | Purpose |
160
+ |:------|:--------|
161
+ | `setup` | Post-init project orientation |
162
+ | `design-mcp-server` | Design tool surface, resources, and services for a new server |
163
+ | `add-tool` | Scaffold a new tool definition |
164
+ | `add-app-tool` | Scaffold an MCP App tool + paired UI resource |
165
+ | `add-resource` | Scaffold a new resource definition |
166
+ | `add-prompt` | Scaffold a new prompt definition |
167
+ | `add-service` | Scaffold a new service integration |
168
+ | `add-test` | Scaffold test file for a tool, resource, or service |
169
+ | `field-test` | Exercise tools/resources/prompts with real inputs, verify behavior, report issues |
170
+ | `tool-defs-analysis` | Read-only audit of MCP definition language across the surface — voice, leaks, defaults, recovery hints, output descriptions |
171
+ | `security-pass` | Audit server for MCP-flavored security gaps: output injection, scope blast radius, input sinks, tenant isolation |
172
+ | `code-simplifier` | Post-session cleanup against `git diff` — modernize syntax, consolidate duplication, align with the codebase |
173
+ | `devcheck` | Lint, format, typecheck, audit |
174
+ | `polish-docs-meta` | Finalize docs, README, metadata, and agent protocol for shipping |
175
+ | `git-wrapup` | Land working-tree changes as a versioned commit + annotated tag — version bump, changelog, verify, tag. Local only. |
176
+ | `release-and-publish` | Push + npm + MCP Registry + GH Release + Docker. Picks up from `git-wrapup` |
177
+ | `maintenance` | Investigate changelogs, adopt upstream changes, sync skills to agent dirs |
178
+ | `report-issue-framework` | File a bug or feature request against `@cyanheads/mcp-ts-core` via `gh` CLI |
179
+ | `report-issue-local` | File a bug or feature request against this server's own repo via `gh` CLI |
180
+ | `api-auth` | Auth modes, scopes, JWT/OAuth |
181
+ | `api-canvas` | DataCanvas: register tabular data, run SQL, export, plus the `spillover()` helper for big result sets — Tier 3 opt-in |
182
+ | `api-config` | AppConfig, parseConfig, env vars |
183
+ | `api-context` | Context interface, logger, state, progress |
184
+ | `api-errors` | McpError, JsonRpcErrorCode, error patterns |
185
+ | `api-linter` | Definition linter rule catalog — invoked by `bun run lint:mcp` and `devcheck` |
186
+ | `api-services` | LLM, Speech, Graph services |
187
+ | `api-testing` | createMockContext, test patterns |
188
+ | `api-utils` | Formatting, parsing, security, pagination, scheduling, telemetry helpers |
189
+ | `api-telemetry` | OTel catalog: spans, metrics, completion logs, env config, cardinality rules |
190
+ | `api-workers` | Cloudflare Workers runtime |
191
+
192
+ When you complete a skill's checklist, check the boxes and add a completion timestamp at the end (e.g., `Completed: 2026-06-01`).
193
+
194
+ ---
195
+
196
+ ## Commands
197
+
198
+ **Runtime:** Scripts run with `bun run <cmd>`.
199
+
200
+ | Command | Purpose |
201
+ |:--------|:--------|
202
+ | `bun run build` | Compile TypeScript |
203
+ | `bun run rebuild` | Clean + build |
204
+ | `bun run clean` | Remove build artifacts |
205
+ | `bun run devcheck` | Lint + format + typecheck + security + changelog sync |
206
+ | `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. |
207
+ | `bun run tree` | Generate directory structure doc |
208
+ | `bun run format` | Auto-fix formatting (safe fixes only) |
209
+ | `bun run format:unsafe` | Also apply Biome's unsafe autofixes — review the diff; they can change behavior |
210
+ | `bun run test` | Run tests |
211
+ | `bun run start:stdio` | Production mode (stdio) |
212
+ | `bun run start:http` | Production mode (HTTP) |
213
+ | `bun run changelog:build` | Regenerate `CHANGELOG.md` from `changelog/*.md` |
214
+ | `bun run changelog:check` | Verify `CHANGELOG.md` is in sync (used by devcheck) |
215
+ | `bun run bundle` | Build and pack as `.mcpb` for one-click Claude Desktop install |
216
+
217
+ ---
218
+
219
+ ## Bundling
220
+
221
+ `bun 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.
222
+
223
+ **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.
224
+
225
+ **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`.
226
+
227
+ ---
228
+
229
+ ## Changelog
230
+
231
+ 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.
232
+
233
+ Each per-version file opens with YAML frontmatter:
234
+
235
+ ```markdown
236
+ ---
237
+ summary: "One-line headline, ≤350 chars" # required — powers the rollup index
238
+ breaking: false # optional — true flags breaking changes
239
+ security: false # optional — true flags security fixes
240
+ ---
241
+
242
+ # 0.1.0 — YYYY-MM-DD
243
+ ...
244
+ ```
245
+
246
+ `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`.
247
+
248
+ `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.
249
+
250
+ **Section order** (Keep a Changelog): Added, Changed, Deprecated, Removed, Fixed, Security. Include only sections with entries — don't ship empty headers.
251
+
252
+ **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.
253
+
254
+ ---
255
+
256
+ ## Imports
257
+
258
+ ```ts
259
+ // Framework — z is re-exported, no separate zod import needed
260
+ import { tool, z } from '@cyanheads/mcp-ts-core';
261
+ import { McpError, JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
262
+
263
+ // Server's own code — via path alias
264
+ import { getNonprofitExplorerService } from '@/services/nonprofit-explorer/nonprofit-explorer-service.js';
265
+ ```
266
+
267
+ ---
268
+
269
+ ## Checklist
270
+
271
+ - [ ] 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()`)
272
+ - [ ] 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`.
273
+ - [ ] JSDoc `@fileoverview` + `@module` on every file
274
+ - [ ] `ctx.log` for logging, `ctx.state` for storage
275
+ - [ ] Handlers throw on failure — error factories or plain `Error`, no try/catch
276
+ - [ ] `format()` renders all data the LLM needs — different clients forward different surfaces (Claude Code → `structuredContent`, Claude Desktop → `content[]`); both must carry the same data
277
+ - [ ] If wrapping external API: raw/domain/output schemas reviewed against real upstream sparsity/nullability before finalizing required vs optional fields
278
+ - [ ] If wrapping external API: normalization and `format()` preserve uncertainty; do not fabricate facts from missing upstream data
279
+ - [ ] If wrapping external API: tests include at least one sparse payload case with omitted upstream fields
280
+ - [ ] Registered in `createApp()` arrays (directly or via barrel exports)
281
+ - [ ] Tests use `createMockContext()` from `@cyanheads/mcp-ts-core/testing`
282
+ - [ ] `.codex-plugin/plugin.json` populated — `name`, `version`, `description`, `repository`, `license` from `package.json`; `interface.displayName` = package name; `interface.shortDescription` from `package.json` description
283
+ - [ ] `.codex-plugin/mcp.json` updated — server name key matches `package.json` name; env vars added for any required API keys
284
+ - [ ] `.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
285
+ - [ ] `bun run devcheck` passes
package/CLAUDE.md ADDED
@@ -0,0 +1,285 @@
1
+ # Developer Protocol
2
+
3
+ **Server:** nonprofit-explorer-mcp-server
4
+ **Version:** 0.1.1
5
+ **Framework:** [@cyanheads/mcp-ts-core](https://www.npmjs.com/package/@cyanheads/mcp-ts-core) `^0.9.19`
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
+ - **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.
22
+
23
+ ---
24
+
25
+ ## Patterns
26
+
27
+ ### Tool
28
+
29
+ ```ts
30
+ import { tool, z } from '@cyanheads/mcp-ts-core';
31
+ import { JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
32
+ import { getNonprofitExplorerService } from '@/services/nonprofit-explorer/nonprofit-explorer-service.js';
33
+
34
+ export const nonprofitSearch = tool('nonprofit_search', {
35
+ title: 'Search Nonprofits',
36
+ description: 'Search 1.8M+ IRS-recognized tax-exempt organizations by name, keyword, city, or phrase.',
37
+ annotations: { readOnlyHint: true },
38
+ input: z.object({
39
+ query: z.string().describe('Keyword search string.'),
40
+ state: z.string().length(2).optional().describe('Two-letter US state abbreviation.'),
41
+ page: z.number().int().min(0).default(0).describe('Zero-indexed page number. 25 results per page.'),
42
+ }),
43
+ output: z.object({
44
+ total_results: z.number().describe('Total matching orgs.'),
45
+ organizations: z.array(z.object({
46
+ ein: z.number().describe('EIN as integer.'),
47
+ name: z.string().describe('Legal org name.'),
48
+ })).describe('Matching organizations for the current page.'),
49
+ }),
50
+ errors: [
51
+ {
52
+ reason: 'no_results',
53
+ code: JsonRpcErrorCode.NotFound,
54
+ when: 'No organizations match the given query and filters',
55
+ recovery: 'Broaden the keyword query, remove one or more filters, or check spelling.',
56
+ },
57
+ ],
58
+ async handler(input, ctx) {
59
+ const svc = getNonprofitExplorerService();
60
+ const raw = await svc.search(input, ctx);
61
+ const orgs = raw.organizations ?? [];
62
+ if (orgs.length === 0) throw ctx.fail('no_results', `No results for "${input.query}"`);
63
+ return { total_results: raw.total_results ?? 0, organizations: orgs.map(o => ({ ein: o.ein, name: o.name ?? '' })) };
64
+ },
65
+ format: (result) => [{ type: 'text', text: result.organizations.map(o => `**${o.name}** (EIN: ${o.ein})`).join('\n') }],
66
+ });
67
+ ```
68
+
69
+ ### Server instructions
70
+
71
+ `createApp({ instructions })` — sent to clients on every `initialize` as session-level context. The nonprofit server uses this to orient agents on the search-first workflow and the filing-year lag.
72
+
73
+ ---
74
+
75
+ ## Context
76
+
77
+ Handlers receive a unified `ctx` object. Key properties:
78
+
79
+ | Property | Description |
80
+ |:---------|:------------|
81
+ | `ctx.log` | Request-scoped logger — `.debug()`, `.info()`, `.notice()`, `.warning()`, `.error()`. Auto-correlates requestId, traceId, tenantId. |
82
+ | `ctx.state` | Tenant-scoped KV — `.get(key)`, `.set(key, value, { ttl? })`, `.delete(key)`, `.list(prefix, { cursor, limit })`. Accepts any serializable value. |
83
+ | `ctx.signal` | `AbortSignal` for cancellation. |
84
+ | `ctx.requestId` | Unique request ID. |
85
+ | `ctx.tenantId` | Tenant ID from JWT or `'default'` for stdio. |
86
+
87
+ ---
88
+
89
+ ## Errors
90
+
91
+ Handlers throw — the framework catches, classifies, and formats.
92
+
93
+ **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).
94
+
95
+ ```ts
96
+ import { JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
97
+
98
+ errors: [
99
+ { reason: 'not_found', code: JsonRpcErrorCode.NotFound,
100
+ when: 'EIN does not correspond to a known org',
101
+ recovery: 'Verify the EIN with nonprofit_search. Use the integer EIN value.' },
102
+ ],
103
+ async handler(input, ctx) {
104
+ const org = await svc.getOrganization(normalizeEin(input.ein), ctx);
105
+ // service throws notFound on missing org — propagated by framework
106
+ return org;
107
+ }
108
+ ```
109
+
110
+ **Fallback (no contract entry fits):** throw via factories or plain `Error`.
111
+
112
+ ```ts
113
+ import { notFound, serviceUnavailable } from '@cyanheads/mcp-ts-core/errors';
114
+ throw notFound('Organization not found', { ein });
115
+ throw serviceUnavailable('ProPublica API unavailable', { url }, { cause: err });
116
+ ```
117
+
118
+ See framework CLAUDE.md and the `api-errors` skill for the full auto-classification table, all available factories, and the contract reference.
119
+
120
+ ---
121
+
122
+ ## Structure
123
+
124
+ ```text
125
+ src/
126
+ index.ts # createApp() entry point — 3 tools, nonprofit service init
127
+ services/
128
+ nonprofit-explorer/
129
+ nonprofit-explorer-service.ts # ProPublica API client (init/accessor pattern)
130
+ types.ts # Domain types (RawOrg, RawFiling, etc.)
131
+ mcp-server/
132
+ tools/definitions/
133
+ nonprofit-search.tool.ts # nonprofit_search
134
+ nonprofit-get-organization.tool.ts# nonprofit_get_organization
135
+ nonprofit-get-filings.tool.ts # nonprofit_get_filings
136
+ ```
137
+
138
+ ---
139
+
140
+ ## Naming
141
+
142
+ | What | Convention | Example |
143
+ |:-----|:-----------|:--------|
144
+ | Files | kebab-case with suffix | `nonprofit-search.tool.ts` |
145
+ | Tool/resource/prompt names | snake_case | `nonprofit_search` |
146
+ | Directories | kebab-case | `src/services/nonprofit-explorer/` |
147
+ | Descriptions | Single string or template literal, no `+` concatenation | `'Search orgs by name and filter.'` |
148
+
149
+ ---
150
+
151
+ ## Skills
152
+
153
+ 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.
154
+
155
+ **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.
156
+
157
+ Available skills:
158
+
159
+ | Skill | Purpose |
160
+ |:------|:--------|
161
+ | `setup` | Post-init project orientation |
162
+ | `design-mcp-server` | Design tool surface, resources, and services for a new server |
163
+ | `add-tool` | Scaffold a new tool definition |
164
+ | `add-app-tool` | Scaffold an MCP App tool + paired UI resource |
165
+ | `add-resource` | Scaffold a new resource definition |
166
+ | `add-prompt` | Scaffold a new prompt definition |
167
+ | `add-service` | Scaffold a new service integration |
168
+ | `add-test` | Scaffold test file for a tool, resource, or service |
169
+ | `field-test` | Exercise tools/resources/prompts with real inputs, verify behavior, report issues |
170
+ | `tool-defs-analysis` | Read-only audit of MCP definition language across the surface — voice, leaks, defaults, recovery hints, output descriptions |
171
+ | `security-pass` | Audit server for MCP-flavored security gaps: output injection, scope blast radius, input sinks, tenant isolation |
172
+ | `code-simplifier` | Post-session cleanup against `git diff` — modernize syntax, consolidate duplication, align with the codebase |
173
+ | `devcheck` | Lint, format, typecheck, audit |
174
+ | `polish-docs-meta` | Finalize docs, README, metadata, and agent protocol for shipping |
175
+ | `git-wrapup` | Land working-tree changes as a versioned commit + annotated tag — version bump, changelog, verify, tag. Local only. |
176
+ | `release-and-publish` | Push + npm + MCP Registry + GH Release + Docker. Picks up from `git-wrapup` |
177
+ | `maintenance` | Investigate changelogs, adopt upstream changes, sync skills to agent dirs |
178
+ | `report-issue-framework` | File a bug or feature request against `@cyanheads/mcp-ts-core` via `gh` CLI |
179
+ | `report-issue-local` | File a bug or feature request against this server's own repo via `gh` CLI |
180
+ | `api-auth` | Auth modes, scopes, JWT/OAuth |
181
+ | `api-canvas` | DataCanvas: register tabular data, run SQL, export, plus the `spillover()` helper for big result sets — Tier 3 opt-in |
182
+ | `api-config` | AppConfig, parseConfig, env vars |
183
+ | `api-context` | Context interface, logger, state, progress |
184
+ | `api-errors` | McpError, JsonRpcErrorCode, error patterns |
185
+ | `api-linter` | Definition linter rule catalog — invoked by `bun run lint:mcp` and `devcheck` |
186
+ | `api-services` | LLM, Speech, Graph services |
187
+ | `api-testing` | createMockContext, test patterns |
188
+ | `api-utils` | Formatting, parsing, security, pagination, scheduling, telemetry helpers |
189
+ | `api-telemetry` | OTel catalog: spans, metrics, completion logs, env config, cardinality rules |
190
+ | `api-workers` | Cloudflare Workers runtime |
191
+
192
+ When you complete a skill's checklist, check the boxes and add a completion timestamp at the end (e.g., `Completed: 2026-06-01`).
193
+
194
+ ---
195
+
196
+ ## Commands
197
+
198
+ **Runtime:** Scripts run with `bun run <cmd>`.
199
+
200
+ | Command | Purpose |
201
+ |:--------|:--------|
202
+ | `bun run build` | Compile TypeScript |
203
+ | `bun run rebuild` | Clean + build |
204
+ | `bun run clean` | Remove build artifacts |
205
+ | `bun run devcheck` | Lint + format + typecheck + security + changelog sync |
206
+ | `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. |
207
+ | `bun run tree` | Generate directory structure doc |
208
+ | `bun run format` | Auto-fix formatting (safe fixes only) |
209
+ | `bun run format:unsafe` | Also apply Biome's unsafe autofixes — review the diff; they can change behavior |
210
+ | `bun run test` | Run tests |
211
+ | `bun run start:stdio` | Production mode (stdio) |
212
+ | `bun run start:http` | Production mode (HTTP) |
213
+ | `bun run changelog:build` | Regenerate `CHANGELOG.md` from `changelog/*.md` |
214
+ | `bun run changelog:check` | Verify `CHANGELOG.md` is in sync (used by devcheck) |
215
+ | `bun run bundle` | Build and pack as `.mcpb` for one-click Claude Desktop install |
216
+
217
+ ---
218
+
219
+ ## Bundling
220
+
221
+ `bun 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.
222
+
223
+ **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.
224
+
225
+ **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`.
226
+
227
+ ---
228
+
229
+ ## Changelog
230
+
231
+ 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.
232
+
233
+ Each per-version file opens with YAML frontmatter:
234
+
235
+ ```markdown
236
+ ---
237
+ summary: "One-line headline, ≤350 chars" # required — powers the rollup index
238
+ breaking: false # optional — true flags breaking changes
239
+ security: false # optional — true flags security fixes
240
+ ---
241
+
242
+ # 0.1.0 — YYYY-MM-DD
243
+ ...
244
+ ```
245
+
246
+ `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`.
247
+
248
+ `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.
249
+
250
+ **Section order** (Keep a Changelog): Added, Changed, Deprecated, Removed, Fixed, Security. Include only sections with entries — don't ship empty headers.
251
+
252
+ **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.
253
+
254
+ ---
255
+
256
+ ## Imports
257
+
258
+ ```ts
259
+ // Framework — z is re-exported, no separate zod import needed
260
+ import { tool, z } from '@cyanheads/mcp-ts-core';
261
+ import { McpError, JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
262
+
263
+ // Server's own code — via path alias
264
+ import { getNonprofitExplorerService } from '@/services/nonprofit-explorer/nonprofit-explorer-service.js';
265
+ ```
266
+
267
+ ---
268
+
269
+ ## Checklist
270
+
271
+ - [ ] 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()`)
272
+ - [ ] 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`.
273
+ - [ ] JSDoc `@fileoverview` + `@module` on every file
274
+ - [ ] `ctx.log` for logging, `ctx.state` for storage
275
+ - [ ] Handlers throw on failure — error factories or plain `Error`, no try/catch
276
+ - [ ] `format()` renders all data the LLM needs — different clients forward different surfaces (Claude Code → `structuredContent`, Claude Desktop → `content[]`); both must carry the same data
277
+ - [ ] If wrapping external API: raw/domain/output schemas reviewed against real upstream sparsity/nullability before finalizing required vs optional fields
278
+ - [ ] If wrapping external API: normalization and `format()` preserve uncertainty; do not fabricate facts from missing upstream data
279
+ - [ ] If wrapping external API: tests include at least one sparse payload case with omitted upstream fields
280
+ - [ ] Registered in `createApp()` arrays (directly or via barrel exports)
281
+ - [ ] Tests use `createMockContext()` from `@cyanheads/mcp-ts-core/testing`
282
+ - [ ] `.codex-plugin/plugin.json` populated — `name`, `version`, `description`, `repository`, `license` from `package.json`; `interface.displayName` = package name; `interface.shortDescription` from `package.json` description
283
+ - [ ] `.codex-plugin/mcp.json` updated — server name key matches `package.json` name; env vars added for any required API keys
284
+ - [ ] `.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
285
+ - [ ] `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="nonprofit-explorer-mcp-server"
41
+ LABEL org.opencontainers.image.description="MCP server for US nonprofit financials via ProPublica — IRS Form 990 data for 1.8M+ tax-exempt organizations."
42
+ LABEL org.opencontainers.image.licenses="Apache-2.0"
43
+ LABEL org.opencontainers.image.source="https://github.com/cyanheads/nonprofit-explorer-mcp-server"
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/nonprofit-explorer-mcp-server && chown -R bun:bun /var/log/nonprofit-explorer-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/nonprofit-explorer-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"]