@cyanheads/sanctions-screening-mcp-server 0.1.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.
- package/AGENTS.md +452 -0
- package/CLAUDE.md +452 -0
- package/Dockerfile +126 -0
- package/LICENSE +201 -0
- package/README.md +354 -0
- package/changelog/0.1.x/0.1.0.md +26 -0
- package/changelog/template.md +127 -0
- package/dist/config/server-config.d.ts +37 -0
- package/dist/config/server-config.d.ts.map +1 -0
- package/dist/config/server-config.js +87 -0
- package/dist/config/server-config.js.map +1 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +70 -0
- package/dist/index.js.map +1 -0
- package/dist/mcp-server/prompts/definitions/index.d.ts +12 -0
- package/dist/mcp-server/prompts/definitions/index.d.ts.map +1 -0
- package/dist/mcp-server/prompts/definitions/index.js +9 -0
- package/dist/mcp-server/prompts/definitions/index.js.map +1 -0
- package/dist/mcp-server/prompts/definitions/vet-counterparty.prompt.d.ts +14 -0
- package/dist/mcp-server/prompts/definitions/vet-counterparty.prompt.d.ts.map +1 -0
- package/dist/mcp-server/prompts/definitions/vet-counterparty.prompt.js +42 -0
- package/dist/mcp-server/prompts/definitions/vet-counterparty.prompt.js.map +1 -0
- package/dist/mcp-server/resources/definitions/designation.resource.d.ts +25 -0
- package/dist/mcp-server/resources/definitions/designation.resource.d.ts.map +1 -0
- package/dist/mcp-server/resources/definitions/designation.resource.js +57 -0
- package/dist/mcp-server/resources/definitions/designation.resource.js.map +1 -0
- package/dist/mcp-server/resources/definitions/entity.resource.d.ts +17 -0
- package/dist/mcp-server/resources/definitions/entity.resource.d.ts.map +1 -0
- package/dist/mcp-server/resources/definitions/entity.resource.js +40 -0
- package/dist/mcp-server/resources/definitions/entity.resource.js.map +1 -0
- package/dist/mcp-server/resources/definitions/index.d.ts +32 -0
- package/dist/mcp-server/resources/definitions/index.d.ts.map +1 -0
- package/dist/mcp-server/resources/definitions/index.js +11 -0
- package/dist/mcp-server/resources/definitions/index.js.map +1 -0
- package/dist/mcp-server/resources/definitions/sources.resource.d.ts +9 -0
- package/dist/mcp-server/resources/definitions/sources.resource.d.ts.map +1 -0
- package/dist/mcp-server/resources/definitions/sources.resource.js +50 -0
- package/dist/mcp-server/resources/definitions/sources.resource.js.map +1 -0
- package/dist/mcp-server/tools/definitions/_shared.d.ts +13 -0
- package/dist/mcp-server/tools/definitions/_shared.d.ts.map +1 -0
- package/dist/mcp-server/tools/definitions/_shared.js +13 -0
- package/dist/mcp-server/tools/definitions/_shared.js.map +1 -0
- package/dist/mcp-server/tools/definitions/get-designation.tool.d.ts +78 -0
- package/dist/mcp-server/tools/definitions/get-designation.tool.d.ts.map +1 -0
- package/dist/mcp-server/tools/definitions/get-designation.tool.js +168 -0
- package/dist/mcp-server/tools/definitions/get-designation.tool.js.map +1 -0
- package/dist/mcp-server/tools/definitions/get-entity.tool.d.ts +55 -0
- package/dist/mcp-server/tools/definitions/get-entity.tool.d.ts.map +1 -0
- package/dist/mcp-server/tools/definitions/get-entity.tool.js +176 -0
- package/dist/mcp-server/tools/definitions/get-entity.tool.js.map +1 -0
- package/dist/mcp-server/tools/definitions/index.d.ts +306 -0
- package/dist/mcp-server/tools/definitions/index.d.ts.map +1 -0
- package/dist/mcp-server/tools/definitions/index.js +21 -0
- package/dist/mcp-server/tools/definitions/index.js.map +1 -0
- package/dist/mcp-server/tools/definitions/list-sources.tool.d.ts +23 -0
- package/dist/mcp-server/tools/definitions/list-sources.tool.d.ts.map +1 -0
- package/dist/mcp-server/tools/definitions/list-sources.tool.js +106 -0
- package/dist/mcp-server/tools/definitions/list-sources.tool.js.map +1 -0
- package/dist/mcp-server/tools/definitions/resolve-entity.tool.d.ts +51 -0
- package/dist/mcp-server/tools/definitions/resolve-entity.tool.d.ts.map +1 -0
- package/dist/mcp-server/tools/definitions/resolve-entity.tool.js +148 -0
- package/dist/mcp-server/tools/definitions/resolve-entity.tool.js.map +1 -0
- package/dist/mcp-server/tools/definitions/screen-name.tool.d.ts +82 -0
- package/dist/mcp-server/tools/definitions/screen-name.tool.d.ts.map +1 -0
- package/dist/mcp-server/tools/definitions/screen-name.tool.js +172 -0
- package/dist/mcp-server/tools/definitions/screen-name.tool.js.map +1 -0
- package/dist/mcp-server/tools/definitions/trace-ownership.tool.d.ts +74 -0
- package/dist/mcp-server/tools/definitions/trace-ownership.tool.d.ts.map +1 -0
- package/dist/mcp-server/tools/definitions/trace-ownership.tool.js +273 -0
- package/dist/mcp-server/tools/definitions/trace-ownership.tool.js.map +1 -0
- package/dist/services/screening/fixtures.d.ts +17 -0
- package/dist/services/screening/fixtures.d.ts.map +1 -0
- package/dist/services/screening/fixtures.js +162 -0
- package/dist/services/screening/fixtures.js.map +1 -0
- package/dist/services/screening/gleif-ingest.d.ts +68 -0
- package/dist/services/screening/gleif-ingest.d.ts.map +1 -0
- package/dist/services/screening/gleif-ingest.js +251 -0
- package/dist/services/screening/gleif-ingest.js.map +1 -0
- package/dist/services/screening/sanctions-ingest.d.ts +46 -0
- package/dist/services/screening/sanctions-ingest.d.ts.map +1 -0
- package/dist/services/screening/sanctions-ingest.js +688 -0
- package/dist/services/screening/sanctions-ingest.js.map +1 -0
- package/dist/services/screening/schema.d.ts +52 -0
- package/dist/services/screening/schema.d.ts.map +1 -0
- package/dist/services/screening/schema.js +125 -0
- package/dist/services/screening/schema.js.map +1 -0
- package/dist/services/screening/screening-service.d.ts +203 -0
- package/dist/services/screening/screening-service.d.ts.map +1 -0
- package/dist/services/screening/screening-service.js +702 -0
- package/dist/services/screening/screening-service.js.map +1 -0
- package/dist/services/screening/text-matching.d.ts +53 -0
- package/dist/services/screening/text-matching.d.ts.map +1 -0
- package/dist/services/screening/text-matching.js +514 -0
- package/dist/services/screening/text-matching.js.map +1 -0
- package/dist/services/screening/types.d.ts +154 -0
- package/dist/services/screening/types.d.ts.map +1 -0
- package/dist/services/screening/types.js +24 -0
- package/dist/services/screening/types.js.map +1 -0
- package/dist/services/screening/xml.d.ts +29 -0
- package/dist/services/screening/xml.d.ts.map +1 -0
- package/dist/services/screening/xml.js +46 -0
- package/dist/services/screening/xml.js.map +1 -0
- package/package.json +119 -0
- package/scripts/_mirror-context.ts +21 -0
- package/scripts/mirror-init.ts +66 -0
- package/scripts/mirror-refresh.ts +56 -0
- package/scripts/mirror-seed.ts +36 -0
- package/scripts/mirror-verify.ts +44 -0
- package/server.json +148 -0
package/AGENTS.md
ADDED
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
# Developer Protocol
|
|
2
|
+
|
|
3
|
+
**Server:** sanctions-screening-mcp-server
|
|
4
|
+
**Version:** 0.1.0
|
|
5
|
+
**Framework:** [@cyanheads/mcp-ts-core](https://www.npmjs.com/package/@cyanheads/mcp-ts-core) `^0.10.6`
|
|
6
|
+
**Engines:** Bun ≥1.3.0, Node ≥24.0.0
|
|
7
|
+
**MCP SDK:** `@modelcontextprotocol/sdk` ^1.29.0
|
|
8
|
+
**Zod:** ^4.4.3
|
|
9
|
+
|
|
10
|
+
> **Read the framework docs first:** `node_modules/@cyanheads/mcp-ts-core/CLAUDE.md` contains the full API reference — builders, Context, error codes, exports, patterns. This file covers server-specific conventions only.
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
## What This Server Is
|
|
15
|
+
|
|
16
|
+
Entity screening and resolution over the world's open sanctions data plus the global legal-entity registry, served offline. It screens a name against the consolidated OFAC (SDN + Consolidated), EU, UK (UKSL), and UN sanctions lists at once, and resolves legal entities against the GLEIF LEI database with corporate-ownership tracing.
|
|
17
|
+
|
|
18
|
+
**Screening aid, not a compliance determination.** Every tool returns *potential matches* with a transparent score and source provenance — never a verdict. This framing is load-bearing: it lives in `SCREENING_CAVEAT` (`src/mcp-server/tools/definitions/_shared.ts`), in every screening tool's description, and in its output. A hit is a candidate to verify against the official source; an empty result is never a clearance. Preserve it in any edit to the surface.
|
|
19
|
+
|
|
20
|
+
**The data path is a local mirror, not a live API.** All five sources are bulk, keyless, and clear for redistribution. They are normalized into two local SQLite + FTS5 mirrors via the framework `MirrorService` — a sanctions `designation` mirror with a per-alias `name` index (Double-Metaphone phonetic keys), and a GLEIF `lei_entity` mirror with a `lei_relationship` ownership table. The real corpus loads out-of-band via `bun run mirror:init`; the read path gates on mirror readiness. **Do not commit or modify the populated `data/` mirrors** — they are environment state, not source.
|
|
21
|
+
|
|
22
|
+
**Match signal is the raw Jaro-Winkler value (0–1) — never a fabricated confidence percentage.** Strict matching (exact-normalized → all-tokens-present via FTS5) is the default and the ~90% path; fuzzy (Jaro-Winkler + phonetic) is opt-in or auto-on-empty. Surface only real signal: `match_type` (`exact`/`strong`/`approximate`), the matched name and its type, and the raw score for approximate hits.
|
|
23
|
+
|
|
24
|
+
---
|
|
25
|
+
|
|
26
|
+
## Core Rules
|
|
27
|
+
|
|
28
|
+
- **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.
|
|
29
|
+
- **Use `ctx.log`** for request-scoped logging. No `console` calls.
|
|
30
|
+
- **Use `ctx.state`** for tenant-scoped storage. Never access persistence directly.
|
|
31
|
+
- **Check `ctx.elicit`** for presence before calling.
|
|
32
|
+
- **Secrets in env vars only** — never hardcoded.
|
|
33
|
+
- **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.
|
|
34
|
+
|
|
35
|
+
---
|
|
36
|
+
|
|
37
|
+
## Patterns
|
|
38
|
+
|
|
39
|
+
### Tool
|
|
40
|
+
|
|
41
|
+
Real example: `sanctions_screen_name` (trimmed). Note the typed error contract (`ctx.fail` + `ctx.recoveryFor`), the load-bearing caveat in the output, and the `enrichment` block for non-result metadata (normalized query, mode used, empty-result notice).
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
import { tool, z } from '@cyanheads/mcp-ts-core';
|
|
45
|
+
import { JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
|
|
46
|
+
import { getScreeningService } from '@/services/screening/screening-service.js';
|
|
47
|
+
import { SOURCE_CODES, SOURCE_LABELS } from '@/services/screening/types.js';
|
|
48
|
+
import { SCREENING_CAVEAT } from './_shared.js';
|
|
49
|
+
|
|
50
|
+
export const screenNameTool = tool('sanctions_screen_name', {
|
|
51
|
+
title: 'sanctions-screening-mcp-server: screen name',
|
|
52
|
+
description: 'Screen a name against all loaded sanctions watchlists at once … a screening AID, not a compliance determination.',
|
|
53
|
+
annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
|
|
54
|
+
input: z.object({
|
|
55
|
+
name: z.string().min(1).describe('The name to screen (person, organization, vessel, or aircraft).'),
|
|
56
|
+
matchMode: z.enum(['strict', 'fuzzy']).default('strict').describe('strict: exact then all-tokens-present. fuzzy: also Jaro-Winkler + phonetic.'),
|
|
57
|
+
limit: z.number().int().min(1).max(100).default(25).describe('Maximum number of potential matches to return.'),
|
|
58
|
+
// … entityType, minScore, sources
|
|
59
|
+
}),
|
|
60
|
+
output: z.object({
|
|
61
|
+
hits: z.array(HitSchema).describe('Scored potential matches, highest-confidence first.'),
|
|
62
|
+
caveat: z.string().describe('Decision-support caveat — a screening aid, not a compliance determination.'),
|
|
63
|
+
}),
|
|
64
|
+
enrichment: {
|
|
65
|
+
normalizedQuery: z.string().describe('The name as the server folded it for matching.'),
|
|
66
|
+
matchModeUsed: z.string().describe('The match mode actually applied (strict may auto-upgrade to fuzzy on empty).'),
|
|
67
|
+
totalCount: z.number().describe('Number of potential matches returned.'),
|
|
68
|
+
notice: z.string().optional().describe('Guidance when no candidate matched.'),
|
|
69
|
+
},
|
|
70
|
+
errors: [
|
|
71
|
+
{ reason: 'mirror_not_ready', code: JsonRpcErrorCode.ServiceUnavailable,
|
|
72
|
+
when: 'The sanctions mirror has never completed an initial sync.', retryable: true,
|
|
73
|
+
recovery: 'Run the mirror:init lifecycle script to load the sanctions lists, then retry.' },
|
|
74
|
+
],
|
|
75
|
+
|
|
76
|
+
async handler(input, ctx) {
|
|
77
|
+
const svc = getScreeningService();
|
|
78
|
+
if (!(await svc.sanctionsReady())) {
|
|
79
|
+
throw ctx.fail('mirror_not_ready', 'The local sanctions mirror is not yet populated.', { ...ctx.recoveryFor('mirror_not_ready') });
|
|
80
|
+
}
|
|
81
|
+
const sources = input.sources?.length ? input.sources : [...SOURCE_CODES];
|
|
82
|
+
const result = await svc.screenName({ query: input.name, matchMode: input.matchMode, sources, limit: input.limit }, ctx);
|
|
83
|
+
ctx.enrich({ normalizedQuery: result.normalizedQuery, matchModeUsed: result.modeUsed });
|
|
84
|
+
ctx.enrich.total(result.hits.length);
|
|
85
|
+
return { hits: result.hits.map((h) => ({ ...h, sourceLabel: SOURCE_LABELS[h.source] })), caveat: SCREENING_CAVEAT };
|
|
86
|
+
},
|
|
87
|
+
|
|
88
|
+
// format() populates content[] — the markdown twin of structuredContent. Both
|
|
89
|
+
// surfaces must carry the same data (lint-enforced). The caveat renders last.
|
|
90
|
+
format: (result) => [{ type: 'text', text: renderHits(result) }],
|
|
91
|
+
});
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
### Resource
|
|
95
|
+
|
|
96
|
+
Real example: `sanctions://entity/{lei}` — a URI mirror of `sanctions_get_entity`'s entity payload (the screening cross-reference is tool-only). Resources mirror tool data for resource-capable clients; tools are the primary path.
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
import { resource, z } from '@cyanheads/mcp-ts-core';
|
|
100
|
+
import { JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
|
|
101
|
+
import { getScreeningService } from '@/services/screening/screening-service.js';
|
|
102
|
+
|
|
103
|
+
export const entityResource = resource('sanctions://entity/{lei}', {
|
|
104
|
+
name: 'sanctions-screening-mcp-server: entity',
|
|
105
|
+
title: 'sanctions-screening-mcp-server: entity',
|
|
106
|
+
description: "Fetch one GLEIF Level 1 legal-entity record by LEI — a read-only URI mirror of sanctions_get_entity's entity payload.",
|
|
107
|
+
mimeType: 'application/json',
|
|
108
|
+
params: z.object({
|
|
109
|
+
lei: z.string().regex(/^[A-Z0-9]{18}[0-9]{2}$/, 'LEI must be 20 chars: 18 alphanumerics + 2 check digits.').describe('The 20-character GLEIF Legal Entity Identifier.'),
|
|
110
|
+
}),
|
|
111
|
+
errors: [
|
|
112
|
+
{ reason: 'lei_not_found', code: JsonRpcErrorCode.NotFound,
|
|
113
|
+
when: 'No GLEIF entity exists for the given LEI in the mirror.',
|
|
114
|
+
recovery: 'Resolve the entity name with sanctions_resolve_entity to obtain a valid LEI first.' },
|
|
115
|
+
],
|
|
116
|
+
async handler(params, ctx) {
|
|
117
|
+
const entity = await getScreeningService().getLeiEntity(params.lei);
|
|
118
|
+
if (!entity) throw ctx.fail('lei_not_found', `No GLEIF entity with LEI "${params.lei}".`, { ...ctx.recoveryFor('lei_not_found') });
|
|
119
|
+
return entity;
|
|
120
|
+
},
|
|
121
|
+
});
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
### Prompt
|
|
125
|
+
|
|
126
|
+
Real example: `sanctions_vet_counterparty` — sequences the existing tools into a due-diligence workflow. No new capability; a reusable framing.
|
|
127
|
+
|
|
128
|
+
```ts
|
|
129
|
+
import { prompt, z } from '@cyanheads/mcp-ts-core';
|
|
130
|
+
|
|
131
|
+
export const vetCounterpartyPrompt = prompt('sanctions_vet_counterparty', {
|
|
132
|
+
title: 'sanctions-screening-mcp-server: vet counterparty',
|
|
133
|
+
description: 'Structure a full counterparty due-diligence pass: resolve the name to an LEI, pull the ownership tree, screen the named entity and every beneficial owner, and summarize hits with provenance and the decision-support caveat.',
|
|
134
|
+
args: z.object({
|
|
135
|
+
name: z.string().describe('The counterparty name to vet (person or organization).'),
|
|
136
|
+
jurisdiction: z.string().optional().describe('Optional ISO 3166-1 alpha-2 jurisdiction to disambiguate (e.g. "US").'),
|
|
137
|
+
}),
|
|
138
|
+
generate: (args) => [
|
|
139
|
+
{ role: 'user', content: { type: 'text', text: `Run a counterparty due-diligence pass on "${args.name}". Screen the name, resolve it to an LEI, trace ownership with screen_nodes:true, then summarize every potential match as a candidate to verify — never a determination.` } },
|
|
140
|
+
],
|
|
141
|
+
});
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
### Server config
|
|
145
|
+
|
|
146
|
+
```ts
|
|
147
|
+
// src/config/server-config.ts — lazy-parsed, separate from framework config.
|
|
148
|
+
// All sources are keyless; there are no secret values here. Every field is
|
|
149
|
+
// optional with a default — the mirror path, fuzzy-match tuning, the refresh
|
|
150
|
+
// cron, and per-source URL overrides.
|
|
151
|
+
import { z } from '@cyanheads/mcp-ts-core';
|
|
152
|
+
import { parseEnvConfig } from '@cyanheads/mcp-ts-core/config';
|
|
153
|
+
|
|
154
|
+
const ServerConfigSchema = z.object({
|
|
155
|
+
mirrorPath: z.string().default('./data/sanctions.db').describe('Filesystem path for the SQLite mirror.'),
|
|
156
|
+
refreshCron: z.string().default('0 4 * * *').describe('Cron for the scheduled refresh (HTTP only).'),
|
|
157
|
+
fuzzyMinScore: z.coerce.number().min(0).max(1).default(0.85).describe('Default Jaro-Winkler floor for fuzzy matches.'),
|
|
158
|
+
fuzzyMaxResults: z.coerce.number().int().min(1).default(50).describe('Hard cap on fuzzy candidates scored per query.'),
|
|
159
|
+
// … per-source URL overrides (ofacSdnUrl, euFsfUrl, ukSanctionsUrl, unScUrl, gleifGoldenCopyBaseUrl)
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
let _config: z.infer<typeof ServerConfigSchema> | undefined;
|
|
163
|
+
export function getServerConfig() {
|
|
164
|
+
_config ??= parseEnvConfig(ServerConfigSchema, {
|
|
165
|
+
mirrorPath: 'SANCTIONS_MIRROR_PATH',
|
|
166
|
+
refreshCron: 'SANCTIONS_REFRESH_CRON',
|
|
167
|
+
fuzzyMinScore: 'SANCTIONS_FUZZY_MIN_SCORE',
|
|
168
|
+
fuzzyMaxResults: 'SANCTIONS_FUZZY_MAX_RESULTS',
|
|
169
|
+
// … OFAC_SDN_URL, EU_FSF_URL, UK_SANCTIONS_URL, UN_SC_URL, GLEIF_GOLDEN_COPY_BASE_URL
|
|
170
|
+
});
|
|
171
|
+
return _config;
|
|
172
|
+
}
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
`parseEnvConfig` maps Zod schema paths → env var names so errors name the variable (`SANCTIONS_MIRROR_PATH`) not the path (`mirrorPath`). Throws `ConfigurationError`, which the framework prints as a clean startup banner.
|
|
176
|
+
|
|
177
|
+
For env booleans use `z.stringbool()`, never `z.coerce.boolean()` — `Boolean("false")` is `true`, so a coerced flag can't be disabled through the environment. `z.stringbool()` parses `true/false/1/0/yes/no/on/off` and rejects anything else, so `=false` actually disables.
|
|
178
|
+
|
|
179
|
+
### Server identity and instructions
|
|
180
|
+
|
|
181
|
+
`createApp()` accepts optional identity fields forwarded to the SDK's `initialize` response and the server manifest (`/.well-known/mcp.json`):
|
|
182
|
+
|
|
183
|
+
```ts
|
|
184
|
+
await createApp({
|
|
185
|
+
name: 'my-mcp-server',
|
|
186
|
+
title: 'My Server', // human-readable display name
|
|
187
|
+
websiteUrl: 'https://github.com/owner/repo', // canonical homepage URL
|
|
188
|
+
description: 'One-line description.', // wins over MCP_SERVER_DESCRIPTION
|
|
189
|
+
icons: [{ src: 'https://example.com/icon.png', sizes: ['48x48'], mimeType: 'image/png' }],
|
|
190
|
+
instructions: 'Use shortcut alpha for the most common case.', // session-level context
|
|
191
|
+
});
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
`instructions` is optional server-level orientation, sent on every `initialize` as session-level context. Use it for deployment guidance (connection aliases, regional notes, scope hints) instead of repeating the same context across tool descriptions. Client adoption is uneven, but there's no downside when set.
|
|
195
|
+
|
|
196
|
+
---
|
|
197
|
+
|
|
198
|
+
## Context
|
|
199
|
+
|
|
200
|
+
Handlers receive a unified `ctx` object. Key properties:
|
|
201
|
+
|
|
202
|
+
| Property | Description |
|
|
203
|
+
|:---------|:------------|
|
|
204
|
+
| `ctx.log` | Request-scoped logger — `.debug()`, `.info()`, `.notice()`, `.warning()`, `.error()`. Auto-correlates requestId, traceId, tenantId. |
|
|
205
|
+
| `ctx.fail` / `ctx.recoveryFor` | Typed error contract — `ctx.fail(reason, msg, …)` against the tool's `errors[]` union; `ctx.recoveryFor(reason)` pulls the declared recovery metadata. Used by every read tool to throw `mirror_not_ready` / `*_not_found`. |
|
|
206
|
+
| `ctx.enrich` | Attach non-result metadata to the response — `ctx.enrich({ … })`, `ctx.enrich.total(n)`, `ctx.enrich.notice(text)`. Used by `screen_name` / `resolve_entity` for the normalized query, the mode actually applied, and the empty-result guidance. |
|
|
207
|
+
| `ctx.signal` | `AbortSignal` for cancellation (propagated into the mirror sync on the refresh path). |
|
|
208
|
+
| `ctx.requestId` | Unique request ID. |
|
|
209
|
+
| `ctx.tenantId` | Tenant ID from JWT or `'default'` for stdio. |
|
|
210
|
+
|
|
211
|
+
This server's persistence is the local SQLite mirror, owned by the screening service and reached via `getScreeningService()` — not `ctx.state`. The data is a shared global corpus, not tenant-scoped KV, so the service-accessor pattern replaces `ctx.state` here.
|
|
212
|
+
|
|
213
|
+
---
|
|
214
|
+
|
|
215
|
+
## Errors
|
|
216
|
+
|
|
217
|
+
Handlers throw — the framework catches, classifies, and formats.
|
|
218
|
+
|
|
219
|
+
**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.
|
|
220
|
+
|
|
221
|
+
```ts
|
|
222
|
+
import { JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
|
|
223
|
+
|
|
224
|
+
errors: [
|
|
225
|
+
{ reason: 'no_match', code: JsonRpcErrorCode.NotFound,
|
|
226
|
+
when: 'No item matched the query',
|
|
227
|
+
recovery: 'Broaden the query or check the spelling and try again.' },
|
|
228
|
+
],
|
|
229
|
+
async handler(input, ctx) {
|
|
230
|
+
const item = await db.find(input.id);
|
|
231
|
+
if (!item) throw ctx.fail('no_match', `No item ${input.id}`);
|
|
232
|
+
return item;
|
|
233
|
+
}
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
**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.
|
|
237
|
+
|
|
238
|
+
**Fallback (no contract entry fits):** throw via factories or plain `Error`.
|
|
239
|
+
|
|
240
|
+
```ts
|
|
241
|
+
// Error factories — explicit code
|
|
242
|
+
import { notFound, serviceUnavailable } from '@cyanheads/mcp-ts-core/errors';
|
|
243
|
+
throw notFound('Item not found', { itemId });
|
|
244
|
+
throw serviceUnavailable('API unavailable', { url }, { cause: err });
|
|
245
|
+
|
|
246
|
+
// Plain Error — framework auto-classifies from message patterns
|
|
247
|
+
throw new Error('Item not found'); // → NotFound
|
|
248
|
+
throw new Error('Invalid query format'); // → ValidationError
|
|
249
|
+
|
|
250
|
+
// McpError — when no factory exists for the code
|
|
251
|
+
import { McpError, JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
|
|
252
|
+
throw new McpError(JsonRpcErrorCode.DatabaseError, 'Connection failed', { pool: 'primary' });
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
See framework CLAUDE.md and the `api-errors` skill for the full auto-classification table, all available factories, and the contract reference.
|
|
256
|
+
|
|
257
|
+
---
|
|
258
|
+
|
|
259
|
+
## Structure
|
|
260
|
+
|
|
261
|
+
```text
|
|
262
|
+
src/
|
|
263
|
+
index.ts # createApp() entry point; schedules HTTP mirror refresh
|
|
264
|
+
config/
|
|
265
|
+
server-config.ts # Server-specific env vars (Zod schema) — mirror path, fuzzy tuning, source URLs
|
|
266
|
+
services/
|
|
267
|
+
screening/
|
|
268
|
+
screening-service.ts # Owns the local mirrors + matching engine (init/accessor pattern)
|
|
269
|
+
schema.ts # Normalized designation/name/lei_entity/lei_relationship schema + MirrorService defs
|
|
270
|
+
sanctions-ingest.ts # OFAC/EU/UK/UN sync ingesters (XML → normalized designations)
|
|
271
|
+
gleif-ingest.ts # GLEIF golden-copy + delta harvest (L1 entities, L2 relationships)
|
|
272
|
+
text-matching.ts # Fold/tokenize, Jaro-Winkler, Double-Metaphone
|
|
273
|
+
types.ts # Source codes, labels, domain types
|
|
274
|
+
fixtures.ts # Synthetic fixture for mirror:seed / tests
|
|
275
|
+
xml.ts # Streaming XML parse helpers
|
|
276
|
+
mcp-server/
|
|
277
|
+
tools/definitions/
|
|
278
|
+
*.tool.ts # Six tools (screen-name, get-designation, resolve-entity, get-entity, trace-ownership, list-sources)
|
|
279
|
+
_shared.ts # SCREENING_CAVEAT (load-bearing decision-support caveat)
|
|
280
|
+
resources/definitions/
|
|
281
|
+
*.resource.ts # Three URI mirrors (designation, entity, sources)
|
|
282
|
+
prompts/definitions/
|
|
283
|
+
vet-counterparty.prompt.ts # Counterparty due-diligence workflow prompt
|
|
284
|
+
scripts/
|
|
285
|
+
mirror-init.ts / mirror-refresh.ts / mirror-verify.ts / mirror-seed.ts # Mirror lifecycle CLI
|
|
286
|
+
_mirror-context.ts # Shared bootstrap shim for the mirror scripts
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
---
|
|
290
|
+
|
|
291
|
+
## Naming
|
|
292
|
+
|
|
293
|
+
| What | Convention | Example |
|
|
294
|
+
|:-----|:-----------|:--------|
|
|
295
|
+
| Files | kebab-case with suffix | `search-docs.tool.ts` |
|
|
296
|
+
| Tool/resource/prompt names | snake_case | `search_docs` |
|
|
297
|
+
| Directories | kebab-case | `src/services/doc-search/` |
|
|
298
|
+
| Descriptions | Single string or template literal, no `+` concatenation | `'Search items by query and filter.'` |
|
|
299
|
+
|
|
300
|
+
---
|
|
301
|
+
|
|
302
|
+
## Skills
|
|
303
|
+
|
|
304
|
+
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.
|
|
305
|
+
|
|
306
|
+
**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.
|
|
307
|
+
|
|
308
|
+
Available skills:
|
|
309
|
+
|
|
310
|
+
| Skill | Purpose |
|
|
311
|
+
|:------|:--------|
|
|
312
|
+
| `setup` | Post-init project orientation |
|
|
313
|
+
| `design-mcp-server` | Design tool surface, resources, and services for a new server |
|
|
314
|
+
| `add-tool` | Scaffold a new tool definition |
|
|
315
|
+
| `add-app-tool` | Scaffold an MCP App tool + paired UI resource |
|
|
316
|
+
| `add-resource` | Scaffold a new resource definition |
|
|
317
|
+
| `add-prompt` | Scaffold a new prompt definition |
|
|
318
|
+
| `add-service` | Scaffold a new service integration |
|
|
319
|
+
| `add-test` | Scaffold test file for a tool, resource, or service |
|
|
320
|
+
| `field-test` | Exercise tools/resources/prompts with real inputs, verify behavior, report issues |
|
|
321
|
+
| `tool-defs-analysis` | Read-only audit of MCP definition language across the surface — voice, leaks, defaults, recovery hints, output descriptions |
|
|
322
|
+
| `security-pass` | Audit server for MCP-flavored security gaps: output injection, scope blast radius, input sinks, tenant isolation |
|
|
323
|
+
| `code-simplifier` | Post-session cleanup against `git diff` — modernize syntax, consolidate duplication, align with the codebase |
|
|
324
|
+
| `devcheck` | Lint, format, typecheck, audit |
|
|
325
|
+
| `polish-docs-meta` | Finalize docs, README, metadata, and agent protocol for shipping |
|
|
326
|
+
| `git-wrapup` | Land working-tree changes as a versioned commit + annotated tag — version bump, changelog, verify, tag. Local only. |
|
|
327
|
+
| `release-and-publish` | Push + npm + MCP Registry + GH Release + Docker. Picks up from `git-wrapup` |
|
|
328
|
+
| `maintenance` | Investigate changelogs, adopt upstream changes, sync skills to agent dirs |
|
|
329
|
+
| `orchestrations` | Chain task skills into a gated multi-phase pipeline — build-out, QA-fix, update-ship — when you can spawn sub-agents |
|
|
330
|
+
| `report-issue-framework` | File a bug or feature request against `@cyanheads/mcp-ts-core` via `gh` CLI |
|
|
331
|
+
| `report-issue-local` | File a bug or feature request against this server's own repo via `gh` CLI |
|
|
332
|
+
| `api-auth` | Auth modes, scopes, JWT/OAuth |
|
|
333
|
+
| `api-canvas` | DataCanvas: register tabular data, run SQL, export, plus the `spillover()` helper for big result sets — Tier 3 opt-in |
|
|
334
|
+
| `api-mirror` | MirrorService — persistent self-refreshing local mirror of a bulk upstream dataset (embedded SQLite + FTS5). The data path this server is built on. |
|
|
335
|
+
| `api-config` | AppConfig, parseConfig, env vars |
|
|
336
|
+
| `api-context` | Context interface, logger, state, progress |
|
|
337
|
+
| `api-errors` | McpError, JsonRpcErrorCode, error patterns |
|
|
338
|
+
| `api-linter` | Definition linter rule catalog — invoked by `bun run lint:mcp` and `devcheck` |
|
|
339
|
+
| `api-services` | LLM, Speech, Graph services |
|
|
340
|
+
| `api-testing` | createMockContext, test patterns |
|
|
341
|
+
| `api-utils` | Formatting, parsing, security, pagination, scheduling, telemetry helpers |
|
|
342
|
+
| `api-telemetry` | OTel catalog: spans, metrics, completion logs, env config, cardinality rules |
|
|
343
|
+
| `api-workers` | Cloudflare Workers runtime |
|
|
344
|
+
|
|
345
|
+
**Chaining skills into pipelines.** When the user wants a multi-phase effort — build this server out, QA-and-fix the surface, update-and-ship — *and you can spawn sub-agents*, `skills/orchestrations/SKILL.md` sequences the task skills above into a gated pipeline with verification at each step. Read it to drive the run. Optional: skip it if you can't orchestrate sub-agents, and ignore it entirely if you were *spawned* as one — you've already been scoped to a single phase.
|
|
346
|
+
|
|
347
|
+
When you complete a skill's checklist, check the boxes and add a completion timestamp at the end (e.g., `Completed: 2026-03-11`).
|
|
348
|
+
|
|
349
|
+
---
|
|
350
|
+
|
|
351
|
+
## Commands
|
|
352
|
+
|
|
353
|
+
**Runtime:** Scripts use Bun's native TypeScript execution — `bun run <cmd>` is the standard invocation. `npm run <cmd>` also works (npm delegates to bun).
|
|
354
|
+
|
|
355
|
+
| Command | Purpose |
|
|
356
|
+
|:--------|:--------|
|
|
357
|
+
| `bun run build` | Compile TypeScript |
|
|
358
|
+
| `bun run rebuild` | Clean + build |
|
|
359
|
+
| `bun run clean` | Remove build artifacts |
|
|
360
|
+
| `bun run devcheck` | Lint + format + typecheck + security + changelog/skills/docs sync |
|
|
361
|
+
| `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. |
|
|
362
|
+
| `bun run tree` | Generate directory structure doc (`docs/tree.md`) |
|
|
363
|
+
| `bun run format` | Auto-fix formatting (safe fixes only) |
|
|
364
|
+
| `bun run format:unsafe` | Also apply Biome's unsafe autofixes — review the diff; they can change behavior |
|
|
365
|
+
| `bun run lint:mcp` | Validate MCP definitions against the linter rule catalog |
|
|
366
|
+
| `bun run lint:packaging` | Validate `manifest.json` ↔ `server.json` env-var consistency |
|
|
367
|
+
| `bun test` | Run the Vitest suite |
|
|
368
|
+
| `bun run start:stdio` | Production mode (stdio) |
|
|
369
|
+
| `bun run start:http` | Production mode (HTTP) |
|
|
370
|
+
| `bun run mirror:init` | Full out-of-band initial load of all sources (sanctions lists + GLEIF golden copy). Hours-long, resumable; never on the request path. |
|
|
371
|
+
| `bun run mirror:refresh` | Re-harvest sanctions lists and apply GLEIF deltas. Also runs on a cron under HTTP. |
|
|
372
|
+
| `bun run mirror:verify` | Report mirror readiness and per-source record counts. |
|
|
373
|
+
| `bun run mirror:seed` | Load a small synthetic fixture for local smoke tests (no downloads). |
|
|
374
|
+
| `bun run changelog:build` | Regenerate `CHANGELOG.md` from `changelog/*.md` |
|
|
375
|
+
| `bun run changelog:check` | Verify `CHANGELOG.md` is in sync (used by devcheck) |
|
|
376
|
+
| `bun run bundle` | Build, pack, and clean a `.mcpb` for one-click Claude Desktop install |
|
|
377
|
+
| `bun run release:github` | Create the GitHub release from the changelog/tag. |
|
|
378
|
+
|
|
379
|
+
---
|
|
380
|
+
|
|
381
|
+
## Bundling
|
|
382
|
+
|
|
383
|
+
`npm run bundle` produces a `.mcpb` extension bundle for one-click install in Claude Desktop. The pack step is followed by `scripts/clean-mcpb.ts`, which prunes dev dependencies (`mcpb clean`) and strips dependency-shipped agent docs (`node_modules/**` `skills/`, `.claude/`, `.agents/`, `SKILL.md`) that root-anchored `.mcpbignore` patterns cannot reach. MCPB is stdio-only — HTTP and Cloudflare Workers deployments are unaffected. Consumers who don't need it can delete `manifest.json` and `.mcpbignore`; `lint:packaging` skips cleanly.
|
|
384
|
+
|
|
385
|
+
**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.
|
|
386
|
+
|
|
387
|
+
**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`.
|
|
388
|
+
|
|
389
|
+
---
|
|
390
|
+
|
|
391
|
+
## Changelog
|
|
392
|
+
|
|
393
|
+
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.
|
|
394
|
+
|
|
395
|
+
Each per-version file opens with YAML frontmatter:
|
|
396
|
+
|
|
397
|
+
```markdown
|
|
398
|
+
---
|
|
399
|
+
summary: "One-line headline, ≤350 chars" # required — powers the rollup index
|
|
400
|
+
breaking: false # optional — true flags breaking changes
|
|
401
|
+
security: false # optional — true flags security fixes
|
|
402
|
+
---
|
|
403
|
+
|
|
404
|
+
# 0.1.0 — YYYY-MM-DD
|
|
405
|
+
...
|
|
406
|
+
```
|
|
407
|
+
|
|
408
|
+
`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`.
|
|
409
|
+
|
|
410
|
+
`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.
|
|
411
|
+
|
|
412
|
+
**Section order** (Keep a Changelog): Added, Changed, Deprecated, Removed, Fixed, Security. Include only sections with entries — don't ship empty headers.
|
|
413
|
+
|
|
414
|
+
**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.
|
|
415
|
+
|
|
416
|
+
---
|
|
417
|
+
|
|
418
|
+
## Imports
|
|
419
|
+
|
|
420
|
+
```ts
|
|
421
|
+
// Framework — z is re-exported, no separate zod import needed
|
|
422
|
+
import { tool, z } from '@cyanheads/mcp-ts-core';
|
|
423
|
+
import { McpError, JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
|
|
424
|
+
|
|
425
|
+
// Server's own code — via path alias
|
|
426
|
+
import { getScreeningService } from '@/services/screening/screening-service.js';
|
|
427
|
+
import { SCREENING_CAVEAT } from '@/mcp-server/tools/definitions/_shared.js';
|
|
428
|
+
```
|
|
429
|
+
|
|
430
|
+
---
|
|
431
|
+
|
|
432
|
+
## Checklist
|
|
433
|
+
|
|
434
|
+
- [ ] 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()`)
|
|
435
|
+
- [ ] 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`.
|
|
436
|
+
- [ ] JSDoc `@fileoverview` + `@module` on every file
|
|
437
|
+
- [ ] `ctx.log` for logging, `ctx.state` for storage
|
|
438
|
+
- [ ] Handlers throw on failure — error factories or plain `Error`, no try/catch
|
|
439
|
+
- [ ] `format()` renders all data the LLM needs — different clients forward different surfaces (Claude Code → `structuredContent`, Claude Desktop → `content[]`); both must carry the same data
|
|
440
|
+
- [ ] Source normalization reviewed against real upstream sparsity/nullability before finalizing required vs optional fields (the four sanctions XML shapes differ widely; UK XML is the messiest)
|
|
441
|
+
- [ ] Normalization and `format()` preserve uncertainty; never fabricate facts from missing source data
|
|
442
|
+
- [ ] Tests include at least one sparse payload case with omitted source fields
|
|
443
|
+
- [ ] **Screening-aid framing preserved** — `SCREENING_CAVEAT` in every screening tool's output; descriptions say "candidate to verify," empty result is "not a clearance"
|
|
444
|
+
- [ ] **No fabricated confidence** — approximate hits surface the raw Jaro-Winkler score (0–1); never a composite/synthesized percentage
|
|
445
|
+
- [ ] **Read path gates on mirror readiness** — `svc.sanctionsReady()` / `svc.leiReady()` before querying; throw `mirror_not_ready` otherwise
|
|
446
|
+
- [ ] Display identity is `sanctions-screening-mcp-server` everywhere (`name`/`title`, manifest, docs) — never Title Case
|
|
447
|
+
- [ ] Registered in `createApp()` arrays (directly or via barrel exports)
|
|
448
|
+
- [ ] Tests use `createMockContext()` from `@cyanheads/mcp-ts-core/testing`
|
|
449
|
+
- [ ] `.codex-plugin/plugin.json` populated — `name`, `version`, `description`, `repository`, `license` from `package.json`; `interface.displayName` = package name; `interface.shortDescription` from `package.json` description
|
|
450
|
+
- [ ] `.codex-plugin/mcp.json` updated — server name key matches `package.json` name; env vars added for any required API keys
|
|
451
|
+
- [ ] `.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
|
|
452
|
+
- [ ] `bun run devcheck` passes
|