@cyanheads/musicbrainz-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 +466 -0
- package/CLAUDE.md +466 -0
- package/Dockerfile +121 -0
- package/LICENSE +201 -0
- package/README.md +329 -0
- package/changelog/0.1.x/0.1.0.md +27 -0
- package/changelog/template.md +127 -0
- package/dist/config/server-config.d.ts +24 -0
- package/dist/config/server-config.d.ts.map +1 -0
- package/dist/config/server-config.js +90 -0
- package/dist/config/server-config.js.map +1 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +27 -0
- package/dist/index.js.map +1 -0
- package/dist/mcp-server/resources/definitions/entity.resource.d.ts +33 -0
- package/dist/mcp-server/resources/definitions/entity.resource.d.ts.map +1 -0
- package/dist/mcp-server/resources/definitions/entity.resource.js +72 -0
- package/dist/mcp-server/resources/definitions/entity.resource.js.map +1 -0
- package/dist/mcp-server/resources/definitions/index.d.ts +27 -0
- package/dist/mcp-server/resources/definitions/index.d.ts.map +1 -0
- package/dist/mcp-server/resources/definitions/index.js +8 -0
- package/dist/mcp-server/resources/definitions/index.js.map +1 -0
- package/dist/mcp-server/tools/definitions/_shared.d.ts +105 -0
- package/dist/mcp-server/tools/definitions/_shared.d.ts.map +1 -0
- package/dist/mcp-server/tools/definitions/_shared.js +382 -0
- package/dist/mcp-server/tools/definitions/_shared.js.map +1 -0
- package/dist/mcp-server/tools/definitions/browse-entities.tool.d.ts +62 -0
- package/dist/mcp-server/tools/definitions/browse-entities.tool.d.ts.map +1 -0
- package/dist/mcp-server/tools/definitions/browse-entities.tool.js +236 -0
- package/dist/mcp-server/tools/definitions/browse-entities.tool.js.map +1 -0
- package/dist/mcp-server/tools/definitions/get-artist.tool.d.ts +78 -0
- package/dist/mcp-server/tools/definitions/get-artist.tool.d.ts.map +1 -0
- package/dist/mcp-server/tools/definitions/get-artist.tool.js +200 -0
- package/dist/mcp-server/tools/definitions/get-artist.tool.js.map +1 -0
- package/dist/mcp-server/tools/definitions/get-cover-art.tool.d.ts +42 -0
- package/dist/mcp-server/tools/definitions/get-cover-art.tool.d.ts.map +1 -0
- package/dist/mcp-server/tools/definitions/get-cover-art.tool.js +149 -0
- package/dist/mcp-server/tools/definitions/get-cover-art.tool.js.map +1 -0
- package/dist/mcp-server/tools/definitions/get-label.tool.d.ts +52 -0
- package/dist/mcp-server/tools/definitions/get-label.tool.d.ts.map +1 -0
- package/dist/mcp-server/tools/definitions/get-label.tool.js +110 -0
- package/dist/mcp-server/tools/definitions/get-label.tool.js.map +1 -0
- package/dist/mcp-server/tools/definitions/get-recording.tool.d.ts +58 -0
- package/dist/mcp-server/tools/definitions/get-recording.tool.d.ts.map +1 -0
- package/dist/mcp-server/tools/definitions/get-recording.tool.js +135 -0
- package/dist/mcp-server/tools/definitions/get-recording.tool.js.map +1 -0
- package/dist/mcp-server/tools/definitions/get-release-group.tool.d.ts +55 -0
- package/dist/mcp-server/tools/definitions/get-release-group.tool.d.ts.map +1 -0
- package/dist/mcp-server/tools/definitions/get-release-group.tool.js +140 -0
- package/dist/mcp-server/tools/definitions/get-release-group.tool.js.map +1 -0
- package/dist/mcp-server/tools/definitions/get-release.tool.d.ts +66 -0
- package/dist/mcp-server/tools/definitions/get-release.tool.d.ts.map +1 -0
- package/dist/mcp-server/tools/definitions/get-release.tool.js +213 -0
- package/dist/mcp-server/tools/definitions/get-release.tool.js.map +1 -0
- package/dist/mcp-server/tools/definitions/get-work.tool.d.ts +62 -0
- package/dist/mcp-server/tools/definitions/get-work.tool.d.ts.map +1 -0
- package/dist/mcp-server/tools/definitions/get-work.tool.js +132 -0
- package/dist/mcp-server/tools/definitions/get-work.tool.js.map +1 -0
- package/dist/mcp-server/tools/definitions/index.d.ts +468 -0
- package/dist/mcp-server/tools/definitions/index.d.ts.map +1 -0
- package/dist/mcp-server/tools/definitions/index.js +28 -0
- package/dist/mcp-server/tools/definitions/index.js.map +1 -0
- package/dist/mcp-server/tools/definitions/lookup-identifier.tool.d.ts +59 -0
- package/dist/mcp-server/tools/definitions/lookup-identifier.tool.d.ts.map +1 -0
- package/dist/mcp-server/tools/definitions/lookup-identifier.tool.js +214 -0
- package/dist/mcp-server/tools/definitions/lookup-identifier.tool.js.map +1 -0
- package/dist/mcp-server/tools/definitions/search-entities.tool.d.ts +42 -0
- package/dist/mcp-server/tools/definitions/search-entities.tool.d.ts.map +1 -0
- package/dist/mcp-server/tools/definitions/search-entities.tool.js +187 -0
- package/dist/mcp-server/tools/definitions/search-entities.tool.js.map +1 -0
- package/dist/services/cover-art/cover-art-service.d.ts +40 -0
- package/dist/services/cover-art/cover-art-service.d.ts.map +1 -0
- package/dist/services/cover-art/cover-art-service.js +118 -0
- package/dist/services/cover-art/cover-art-service.js.map +1 -0
- package/dist/services/musicbrainz/musicbrainz-service.d.ts +81 -0
- package/dist/services/musicbrainz/musicbrainz-service.d.ts.map +1 -0
- package/dist/services/musicbrainz/musicbrainz-service.js +188 -0
- package/dist/services/musicbrainz/musicbrainz-service.js.map +1 -0
- package/dist/services/musicbrainz/rate-limiter.d.ts +32 -0
- package/dist/services/musicbrainz/rate-limiter.d.ts.map +1 -0
- package/dist/services/musicbrainz/rate-limiter.js +54 -0
- package/dist/services/musicbrainz/rate-limiter.js.map +1 -0
- package/dist/services/musicbrainz/types.d.ts +301 -0
- package/dist/services/musicbrainz/types.d.ts.map +1 -0
- package/dist/services/musicbrainz/types.js +11 -0
- package/dist/services/musicbrainz/types.js.map +1 -0
- package/package.json +103 -0
- package/server.json +111 -0
package/AGENTS.md
ADDED
|
@@ -0,0 +1,466 @@
|
|
|
1
|
+
# Developer Protocol
|
|
2
|
+
|
|
3
|
+
**Server:** musicbrainz-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's Next?
|
|
15
|
+
|
|
16
|
+
When the user asks what's next or needs direction, suggest options based on the current project state. Common next steps:
|
|
17
|
+
|
|
18
|
+
1. **Re-run the `setup` skill** — ensures CLAUDE.md, skills, structure, and metadata are populated and up to date with the current codebase
|
|
19
|
+
2. **Run the `design-mcp-server` skill** — if the tool/resource surface hasn't been mapped yet, work through domain design
|
|
20
|
+
3. **Add tools/resources/prompts** — scaffold new definitions using the `add-tool`, `add-app-tool`, `add-resource`, `add-prompt` skills
|
|
21
|
+
4. **Add services** — scaffold domain service integrations using the `add-service` skill
|
|
22
|
+
5. **Add tests** — scaffold tests for existing definitions using the `add-test` skill
|
|
23
|
+
6. **Field-test definitions** — exercise tools/resources/prompts with real inputs using the `field-test` skill, get a report of issues and pain points
|
|
24
|
+
7. **Run `devcheck`** — lint, format, typecheck, and security audit
|
|
25
|
+
8. **Run the `security-pass` skill** — audit handlers for MCP-specific security gaps: output injection, scope blast radius, input sinks, tenant isolation
|
|
26
|
+
9. **Run the `polish-docs-meta` skill** — finalize README, CHANGELOG, metadata, and agent protocol for shipping
|
|
27
|
+
10. **Run the `maintenance` skill** — investigate changelogs, adopt upstream changes, and sync skills after `bun update --latest`
|
|
28
|
+
|
|
29
|
+
Tailor suggestions to what's actually missing or stale — don't recite the full list every time.
|
|
30
|
+
|
|
31
|
+
---
|
|
32
|
+
|
|
33
|
+
## Core Rules
|
|
34
|
+
|
|
35
|
+
- **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.
|
|
36
|
+
- **Use `ctx.log`** for request-scoped logging. No `console` calls.
|
|
37
|
+
- **Use `ctx.state`** for tenant-scoped storage. Never access persistence directly.
|
|
38
|
+
- **Check `ctx.elicit`** for presence before calling.
|
|
39
|
+
- **Secrets in env vars only** — never hardcoded.
|
|
40
|
+
- **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.
|
|
41
|
+
|
|
42
|
+
---
|
|
43
|
+
|
|
44
|
+
## Patterns
|
|
45
|
+
|
|
46
|
+
### Tool
|
|
47
|
+
|
|
48
|
+
Tools are `musicbrainz_{verb}_{noun}`, all read-only, with typed error contracts encoding the live 400-vs-404 split (`invalid_mbid` / `entity_not_found`). `search_entities` is the entry point — it resolves a name to an MBID that chains into the `get_*` tools.
|
|
49
|
+
|
|
50
|
+
```ts
|
|
51
|
+
import { tool, z } from '@cyanheads/mcp-ts-core';
|
|
52
|
+
import { getMusicBrainzService, MusicBrainzService } from '@/services/musicbrainz/musicbrainz-service.js';
|
|
53
|
+
|
|
54
|
+
const ENTITY_TYPES = ['artist', 'release-group', 'release', 'recording', 'work', 'label'] as const;
|
|
55
|
+
|
|
56
|
+
export const searchEntitiesTool = tool('musicbrainz_search_entities', {
|
|
57
|
+
title: 'musicbrainz-mcp-server: search entities',
|
|
58
|
+
description:
|
|
59
|
+
'Full-text Lucene search across a MusicBrainz entity type. Returns ranked matches with MBID, name/title, and a 0–100 relevance score. Chain the MBID into the matching musicbrainz_get_* tool.',
|
|
60
|
+
annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: true },
|
|
61
|
+
|
|
62
|
+
input: z.object({
|
|
63
|
+
entityType: z.enum(ENTITY_TYPES).describe('Which entity type to search.'),
|
|
64
|
+
query: z.string().min(1).describe('Lucene query string; field scoping (e.g. `artist:`) is supported.'),
|
|
65
|
+
limit: z.number().int().min(1).max(100).default(25).describe('Maximum results to return (1–100).'),
|
|
66
|
+
offset: z.number().int().min(0).default(0).describe('Result offset for pagination (0-based).'),
|
|
67
|
+
}),
|
|
68
|
+
|
|
69
|
+
output: z.object({
|
|
70
|
+
entityType: z.string().describe('The entity type that was searched.'),
|
|
71
|
+
results: z.array(ResultSchema).describe('Ranked matches, in MusicBrainz score-descending order.'),
|
|
72
|
+
}),
|
|
73
|
+
|
|
74
|
+
// enrich.echo/total/notice surface the effective query, upstream total, and a
|
|
75
|
+
// zero-hits hint — provenance the agent reasons about, not a fabricated score.
|
|
76
|
+
enrichment: {
|
|
77
|
+
effectiveQuery: z.string().describe('The query string as sent to MusicBrainz.'),
|
|
78
|
+
totalCount: z.number().describe('Total matches upstream before the limit/offset window.'),
|
|
79
|
+
notice: z.string().optional().describe('Guidance when zero results matched.'),
|
|
80
|
+
},
|
|
81
|
+
|
|
82
|
+
async handler(input, ctx) {
|
|
83
|
+
const service = getMusicBrainzService();
|
|
84
|
+
const envelope = await service.search(input.entityType, input.query, input, ctx, { signal: ctx.signal });
|
|
85
|
+
const rawHits = (envelope[MusicBrainzService.pluralKey(input.entityType)] ?? []) as unknown[];
|
|
86
|
+
const results = rawHits.map((h) => mapHit(input.entityType, h));
|
|
87
|
+
ctx.enrich.echo(input.query);
|
|
88
|
+
ctx.enrich.total(typeof envelope.count === 'number' ? envelope.count : results.length);
|
|
89
|
+
if (results.length === 0) ctx.enrich.notice(`No ${input.entityType} matched "${input.query}".`);
|
|
90
|
+
return { entityType: input.entityType, results };
|
|
91
|
+
},
|
|
92
|
+
|
|
93
|
+
// format() populates content[] — the markdown twin of structuredContent.
|
|
94
|
+
// Different clients read different surfaces (Claude Code → structuredContent,
|
|
95
|
+
// Claude Desktop → content[]); both must carry the same data.
|
|
96
|
+
format: (result) => [{
|
|
97
|
+
type: 'text',
|
|
98
|
+
text: result.results.map((r) => `**${r.name}** — MBID ${r.mbid} (score ${r.score})`).join('\n'),
|
|
99
|
+
}],
|
|
100
|
+
});
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
### Resource
|
|
104
|
+
|
|
105
|
+
One resource template mirrors the `get_*` lookups — the entity type is a path parameter. No `list()`: the corpus is millions of entities, so discovery is via `musicbrainz_search_entities`. The handler maps the service's `InvalidParams`/`NotFound` onto the typed `invalid_mbid` / `entity_not_found` contract via `ctx.fail` + `ctx.recoveryFor`.
|
|
106
|
+
|
|
107
|
+
```ts
|
|
108
|
+
import { resource, z } from '@cyanheads/mcp-ts-core';
|
|
109
|
+
import { JsonRpcErrorCode, McpError } from '@cyanheads/mcp-ts-core/errors';
|
|
110
|
+
import { getMusicBrainzService } from '@/services/musicbrainz/musicbrainz-service.js';
|
|
111
|
+
|
|
112
|
+
export const entityResource = resource('musicbrainz://{entity_type}/{mbid}', {
|
|
113
|
+
name: 'musicbrainz-entity',
|
|
114
|
+
title: 'musicbrainz-mcp-server: entity',
|
|
115
|
+
description: 'A single MusicBrainz entity by type and MBID, with default linked sub-resources folded in.',
|
|
116
|
+
mimeType: 'application/json',
|
|
117
|
+
errors: [
|
|
118
|
+
{ reason: 'invalid_mbid', code: JsonRpcErrorCode.InvalidParams,
|
|
119
|
+
when: 'The MBID is malformed / all-zeros, or entity_type is not one of the six valid types.',
|
|
120
|
+
recovery: 'Use a 36-character UUID MBID and a valid entity_type.' },
|
|
121
|
+
{ reason: 'entity_not_found', code: JsonRpcErrorCode.NotFound,
|
|
122
|
+
when: 'The MBID is well-formed but no entity of that type exists with it.',
|
|
123
|
+
recovery: 'Verify the MBID, or find it by name with musicbrainz_search_entities.' },
|
|
124
|
+
],
|
|
125
|
+
params: z.object({
|
|
126
|
+
entity_type: z.enum(ENTITY_TYPES).describe('Entity type.'),
|
|
127
|
+
mbid: z.string().describe('Entity MBID (36-character UUID).'),
|
|
128
|
+
}),
|
|
129
|
+
async handler(params, ctx) {
|
|
130
|
+
try {
|
|
131
|
+
return await getMusicBrainzService().lookup(params.entity_type, params.mbid, { inc: DEFAULT_INC[params.entity_type] }, ctx, { signal: ctx.signal });
|
|
132
|
+
} catch (error: unknown) {
|
|
133
|
+
if (error instanceof McpError && error.code === JsonRpcErrorCode.InvalidParams)
|
|
134
|
+
throw ctx.fail('invalid_mbid', `Malformed MBID "${params.mbid}".`, { ...ctx.recoveryFor('invalid_mbid') });
|
|
135
|
+
if (error instanceof McpError && error.code === JsonRpcErrorCode.NotFound)
|
|
136
|
+
throw ctx.fail('entity_not_found', `No ${params.entity_type} exists with MBID ${params.mbid}.`, { ...ctx.recoveryFor('entity_not_found') });
|
|
137
|
+
throw error;
|
|
138
|
+
}
|
|
139
|
+
},
|
|
140
|
+
});
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
### Prompts
|
|
144
|
+
|
|
145
|
+
None — this is a data/lookup server with no recurring multi-step interaction worth templating. `createApp()` is called with `prompts: []`.
|
|
146
|
+
|
|
147
|
+
### Server config
|
|
148
|
+
|
|
149
|
+
```ts
|
|
150
|
+
// src/config/server-config.ts — lazy-parsed, separate from framework config
|
|
151
|
+
import { z } from '@cyanheads/mcp-ts-core';
|
|
152
|
+
import { parseEnvConfig } from '@cyanheads/mcp-ts-core/config';
|
|
153
|
+
|
|
154
|
+
// Treats unset, set-but-empty (""), and an unsubstituted MCPB placeholder
|
|
155
|
+
// (${user_config.X}) identically as "not set" so each falls through to the default.
|
|
156
|
+
const PLACEHOLDER_PATTERN = /^\$\{[^}]+\}$/;
|
|
157
|
+
const emptyAsUndefined = (v: unknown) => {
|
|
158
|
+
if (v === '') return;
|
|
159
|
+
if (typeof v === 'string' && PLACEHOLDER_PATTERN.test(v)) return;
|
|
160
|
+
return v;
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
const ServerConfigSchema = z.object({
|
|
164
|
+
contact: z
|
|
165
|
+
.preprocess(emptyAsUndefined, z.string())
|
|
166
|
+
.default('https://github.com/cyanheads/musicbrainz-mcp-server')
|
|
167
|
+
.describe('Contact (email or URL) embedded in the mandatory MusicBrainz User-Agent'),
|
|
168
|
+
baseUrl: z.string().url().default('https://musicbrainz.org/ws/2').describe('MusicBrainz WS/2 base URL'),
|
|
169
|
+
coverArtBaseUrl: z.string().url().default('https://coverartarchive.org').describe('Cover Art Archive base URL'),
|
|
170
|
+
rateLimitRps: z.coerce.number().min(0.1).max(50).default(1).describe('Client-side MusicBrainz request/sec ceiling'),
|
|
171
|
+
cacheTtlSeconds: z.coerce.number().min(0).max(2_592_000).default(86_400).describe('Response cache TTL in seconds; 0 disables'),
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
let _config: z.infer<typeof ServerConfigSchema> | undefined;
|
|
175
|
+
export function getServerConfig() {
|
|
176
|
+
_config ??= parseEnvConfig(ServerConfigSchema, {
|
|
177
|
+
contact: 'MUSICBRAINZ_CONTACT',
|
|
178
|
+
baseUrl: 'MUSICBRAINZ_BASE_URL',
|
|
179
|
+
coverArtBaseUrl: 'COVER_ART_BASE_URL',
|
|
180
|
+
rateLimitRps: 'MUSICBRAINZ_RATE_LIMIT_RPS',
|
|
181
|
+
cacheTtlSeconds: 'MUSICBRAINZ_CACHE_TTL',
|
|
182
|
+
});
|
|
183
|
+
return _config;
|
|
184
|
+
}
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
`parseEnvConfig` maps Zod schema paths → env var names so errors name the variable (`MUSICBRAINZ_CONTACT`) not the path (`contact`). Throws `ConfigurationError`, which the framework prints as a clean startup banner. `MUSICBRAINZ_CONTACT` ships a default so the server runs out of the box; operators of a shared/hosted instance should set their own.
|
|
188
|
+
|
|
189
|
+
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.
|
|
190
|
+
|
|
191
|
+
### Server identity and instructions
|
|
192
|
+
|
|
193
|
+
`createApp()` accepts optional identity fields forwarded to the SDK's `initialize` response and the server manifest (`/.well-known/mcp.json`):
|
|
194
|
+
|
|
195
|
+
```ts
|
|
196
|
+
await createApp({
|
|
197
|
+
name: 'musicbrainz-mcp-server',
|
|
198
|
+
title: 'musicbrainz-mcp-server', // must match the unscoped package name — enforced by lint:packaging
|
|
199
|
+
websiteUrl: 'https://github.com/cyanheads/musicbrainz-mcp-server',
|
|
200
|
+
tools: allToolDefinitions,
|
|
201
|
+
resources: allResourceDefinitions,
|
|
202
|
+
prompts: [],
|
|
203
|
+
instructions:
|
|
204
|
+
'Entities are addressed by MBID (a UUID); from a name, call musicbrainz_search_entities first and chain the MBID into the matching musicbrainz_get_* tool. The get_* tools embed at most one page (25) of any linked list — use musicbrainz_browse_entities for the complete set. Rate-limited to ~1 request/second against MusicBrainz.',
|
|
205
|
+
setup(core) {
|
|
206
|
+
initMusicBrainzService(core.config.mcpServerVersion);
|
|
207
|
+
initCoverArtService();
|
|
208
|
+
},
|
|
209
|
+
});
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
`description` is **not** passed to `createApp()` — the framework derives the served description from `package.json` (the canonical source). `instructions` is optional server-level orientation, sent on every `initialize` as session-level context. Use it for deployment guidance (connection aliases, scope hints, the rate-limit note) instead of repeating the same context across tool descriptions. Client adoption is uneven, but there's no downside when set.
|
|
213
|
+
|
|
214
|
+
---
|
|
215
|
+
|
|
216
|
+
## Context
|
|
217
|
+
|
|
218
|
+
Handlers receive a unified `ctx` object. Key properties:
|
|
219
|
+
|
|
220
|
+
| Property | Description |
|
|
221
|
+
|:---------|:------------|
|
|
222
|
+
| `ctx.log` | Request-scoped logger — `.debug()`, `.info()`, `.notice()`, `.warning()`, `.error()`. Auto-correlates requestId, traceId, tenantId. |
|
|
223
|
+
| `ctx.state` | Tenant-scoped KV — `.get(key)`, `.set(key, value, { ttl? })`, `.delete(key)`. Backs the MusicBrainz response cache (shared across tenants — the data is public CC0). |
|
|
224
|
+
| `ctx.enrich` | Provenance helpers on search/browse — `.echo(query)`, `.total(n)`, `.notice(msg)`. Surface the effective query, upstream total, and a zero-hits hint without polluting the typed output. |
|
|
225
|
+
| `ctx.fail` / `ctx.recoveryFor` | Throw a typed contract error by reason (`ctx.fail('invalid_mbid', …)`); `ctx.recoveryFor(reason)` pulls the declared recovery metadata for the throw site. |
|
|
226
|
+
| `ctx.signal` | `AbortSignal` for cancellation — forwarded into every upstream fetch. |
|
|
227
|
+
| `ctx.requestId` | Unique request ID. |
|
|
228
|
+
| `ctx.tenantId` | Tenant ID from JWT or `'default'` for stdio. |
|
|
229
|
+
|
|
230
|
+
---
|
|
231
|
+
|
|
232
|
+
## Errors
|
|
233
|
+
|
|
234
|
+
Handlers throw — the framework catches, classifies, and formats.
|
|
235
|
+
|
|
236
|
+
**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.
|
|
237
|
+
|
|
238
|
+
```ts
|
|
239
|
+
import { JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
|
|
240
|
+
|
|
241
|
+
errors: [
|
|
242
|
+
{ reason: 'no_match', code: JsonRpcErrorCode.NotFound,
|
|
243
|
+
when: 'No item matched the query',
|
|
244
|
+
recovery: 'Broaden the query or check the spelling and try again.' },
|
|
245
|
+
],
|
|
246
|
+
async handler(input, ctx) {
|
|
247
|
+
const item = await db.find(input.id);
|
|
248
|
+
if (!item) throw ctx.fail('no_match', `No item ${input.id}`);
|
|
249
|
+
return item;
|
|
250
|
+
}
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
**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.
|
|
254
|
+
|
|
255
|
+
**Fallback (no contract entry fits):** throw via factories or plain `Error`.
|
|
256
|
+
|
|
257
|
+
```ts
|
|
258
|
+
// Error factories — explicit code
|
|
259
|
+
import { notFound, serviceUnavailable } from '@cyanheads/mcp-ts-core/errors';
|
|
260
|
+
throw notFound('Item not found', { itemId });
|
|
261
|
+
throw serviceUnavailable('API unavailable', { url }, { cause: err });
|
|
262
|
+
|
|
263
|
+
// Plain Error — framework auto-classifies from message patterns
|
|
264
|
+
throw new Error('Item not found'); // → NotFound
|
|
265
|
+
throw new Error('Invalid query format'); // → ValidationError
|
|
266
|
+
|
|
267
|
+
// McpError — when no factory exists for the code
|
|
268
|
+
import { McpError, JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
|
|
269
|
+
throw new McpError(JsonRpcErrorCode.DatabaseError, 'Connection failed', { pool: 'primary' });
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
See framework CLAUDE.md and the `api-errors` skill for the full auto-classification table, all available factories, and the contract reference.
|
|
273
|
+
|
|
274
|
+
---
|
|
275
|
+
|
|
276
|
+
## Structure
|
|
277
|
+
|
|
278
|
+
```text
|
|
279
|
+
src/
|
|
280
|
+
index.ts # createApp() entry point — registers tools/resources, inits both services
|
|
281
|
+
config/
|
|
282
|
+
server-config.ts # MusicBrainz/Cover Art env vars (Zod schema, lazy-parsed)
|
|
283
|
+
services/
|
|
284
|
+
musicbrainz/
|
|
285
|
+
musicbrainz-service.ts # WS/2 client — User-Agent, rate limiter, cache, withRetry
|
|
286
|
+
rate-limiter.ts # Process-wide ~1 req/sec token bucket
|
|
287
|
+
types.ts # Raw/domain entity types
|
|
288
|
+
cover-art/
|
|
289
|
+
cover-art-service.ts # Cover Art Archive client — 404 → empty set, follows 307
|
|
290
|
+
mcp-server/
|
|
291
|
+
tools/definitions/
|
|
292
|
+
search-entities.tool.ts # musicbrainz_search_entities (the entry point)
|
|
293
|
+
get-artist.tool.ts # get_artist / get_release_group / get_release /
|
|
294
|
+
get-recording.tool.ts # get_recording / get_work / get_label
|
|
295
|
+
lookup-identifier.tool.ts # musicbrainz_lookup_identifier (ISRC/ISWC/barcode)
|
|
296
|
+
browse-entities.tool.ts # musicbrainz_browse_entities (complete enumeration)
|
|
297
|
+
get-cover-art.tool.ts # musicbrainz_get_cover_art
|
|
298
|
+
_shared.ts # artist-credit / duration / url-rel helpers
|
|
299
|
+
index.ts # allToolDefinitions barrel
|
|
300
|
+
resources/definitions/
|
|
301
|
+
entity.resource.ts # musicbrainz://{entity_type}/{mbid}
|
|
302
|
+
index.ts # allResourceDefinitions barrel
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
No `prompts/` directory — this server registers no prompts.
|
|
306
|
+
|
|
307
|
+
---
|
|
308
|
+
|
|
309
|
+
## Naming
|
|
310
|
+
|
|
311
|
+
| What | Convention | Example |
|
|
312
|
+
|:-----|:-----------|:--------|
|
|
313
|
+
| Files | kebab-case with suffix | `search-docs.tool.ts` |
|
|
314
|
+
| Tool/resource/prompt names | snake_case | `search_docs` |
|
|
315
|
+
| Directories | kebab-case | `src/services/doc-search/` |
|
|
316
|
+
| Descriptions | Single string or template literal, no `+` concatenation | `'Search items by query and filter.'` |
|
|
317
|
+
|
|
318
|
+
---
|
|
319
|
+
|
|
320
|
+
## Skills
|
|
321
|
+
|
|
322
|
+
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.
|
|
323
|
+
|
|
324
|
+
**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.
|
|
325
|
+
|
|
326
|
+
Available skills:
|
|
327
|
+
|
|
328
|
+
| Skill | Purpose |
|
|
329
|
+
|:------|:--------|
|
|
330
|
+
| `setup` | Post-init project orientation |
|
|
331
|
+
| `design-mcp-server` | Design tool surface, resources, and services for a new server |
|
|
332
|
+
| `add-tool` | Scaffold a new tool definition |
|
|
333
|
+
| `add-app-tool` | Scaffold an MCP App tool + paired UI resource |
|
|
334
|
+
| `add-resource` | Scaffold a new resource definition |
|
|
335
|
+
| `add-prompt` | Scaffold a new prompt definition |
|
|
336
|
+
| `add-service` | Scaffold a new service integration |
|
|
337
|
+
| `add-test` | Scaffold test file for a tool, resource, or service |
|
|
338
|
+
| `field-test` | Exercise tools/resources/prompts with real inputs, verify behavior, report issues |
|
|
339
|
+
| `tool-defs-analysis` | Read-only audit of MCP definition language across the surface — voice, leaks, defaults, recovery hints, output descriptions |
|
|
340
|
+
| `security-pass` | Audit server for MCP-flavored security gaps: output injection, scope blast radius, input sinks, tenant isolation |
|
|
341
|
+
| `code-simplifier` | Post-session cleanup against `git diff` — modernize syntax, consolidate duplication, align with the codebase |
|
|
342
|
+
| `devcheck` | Lint, format, typecheck, audit |
|
|
343
|
+
| `polish-docs-meta` | Finalize docs, README, metadata, and agent protocol for shipping |
|
|
344
|
+
| `git-wrapup` | Land working-tree changes as a versioned commit + annotated tag — version bump, changelog, verify, tag. Local only. |
|
|
345
|
+
| `release-and-publish` | Push + npm + MCP Registry + GH Release + Docker. Picks up from `git-wrapup` |
|
|
346
|
+
| `maintenance` | Investigate changelogs, adopt upstream changes, sync skills to agent dirs |
|
|
347
|
+
| `orchestrations` | Chain task skills into a gated multi-phase pipeline — build-out, QA-fix, update-ship — when you can spawn sub-agents |
|
|
348
|
+
| `report-issue-framework` | File a bug or feature request against `@cyanheads/mcp-ts-core` via `gh` CLI |
|
|
349
|
+
| `report-issue-local` | File a bug or feature request against this server's own repo via `gh` CLI |
|
|
350
|
+
| `api-auth` | Auth modes, scopes, JWT/OAuth |
|
|
351
|
+
| `api-canvas` | DataCanvas: register tabular data, run SQL, export, plus the `spillover()` helper for big result sets — Tier 3 opt-in |
|
|
352
|
+
| `api-mirror` | MirrorService: stand up a self-refreshing local mirror of a bulk upstream dataset (SQLite + FTS5) — Tier 3 opt-in |
|
|
353
|
+
| `api-config` | AppConfig, parseConfig, env vars |
|
|
354
|
+
| `api-context` | Context interface, logger, state, progress |
|
|
355
|
+
| `api-errors` | McpError, JsonRpcErrorCode, error patterns |
|
|
356
|
+
| `api-linter` | Definition linter rule catalog — invoked by `bun run lint:mcp` and `devcheck` |
|
|
357
|
+
| `api-services` | LLM, Speech, Graph services |
|
|
358
|
+
| `api-testing` | createMockContext, test patterns |
|
|
359
|
+
| `api-utils` | Formatting, parsing, security, pagination, scheduling, telemetry helpers |
|
|
360
|
+
| `api-telemetry` | OTel catalog: spans, metrics, completion logs, env config, cardinality rules |
|
|
361
|
+
| `api-workers` | Cloudflare Workers runtime |
|
|
362
|
+
| `techniques` | Cross-cutting implementation techniques and recipes for the framework |
|
|
363
|
+
|
|
364
|
+
**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.
|
|
365
|
+
|
|
366
|
+
When you complete a skill's checklist, check the boxes and add a completion timestamp at the end (e.g., `Completed: 2026-03-11`).
|
|
367
|
+
|
|
368
|
+
---
|
|
369
|
+
|
|
370
|
+
## Commands
|
|
371
|
+
|
|
372
|
+
**Runtime:** Scripts use Bun's native TypeScript execution — `bun run <cmd>` is the standard invocation. `npm run <cmd>` also works (npm delegates to bun).
|
|
373
|
+
|
|
374
|
+
| Command | Purpose |
|
|
375
|
+
|:--------|:--------|
|
|
376
|
+
| `bun run build` | Compile TypeScript |
|
|
377
|
+
| `bun run rebuild` | Clean + build |
|
|
378
|
+
| `bun run clean` | Remove build artifacts |
|
|
379
|
+
| `bun run devcheck` | Lint + format + typecheck + security + packaging + changelog sync |
|
|
380
|
+
| `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. |
|
|
381
|
+
| `bun run tree` | Generate `docs/tree.md` directory structure doc |
|
|
382
|
+
| `bun run list-skills` | List the skills available in `.claude/skills/` |
|
|
383
|
+
| `bun run format` | Auto-fix formatting (safe fixes only) |
|
|
384
|
+
| `bun run format:unsafe` | Also apply Biome's unsafe autofixes — review the diff; they can change behavior |
|
|
385
|
+
| `bun run lint:mcp` | Validate MCP tool/resource definitions against the linter rules |
|
|
386
|
+
| `bun run lint:packaging` | Validate `manifest.json` ↔ `server.json` env var alignment + bundle/identity guards |
|
|
387
|
+
| `bun test` | Run the Vitest suite |
|
|
388
|
+
| `bun run start:stdio` | Production mode (stdio) |
|
|
389
|
+
| `bun run start:http` | Production mode (HTTP) |
|
|
390
|
+
| `bun run changelog:build` | Regenerate `CHANGELOG.md` from `changelog/*.md` |
|
|
391
|
+
| `bun run changelog:check` | Verify `CHANGELOG.md` is in sync (used by devcheck) |
|
|
392
|
+
| `bun run bundle` | Build, pack, and clean a `.mcpb` for one-click Claude Desktop install |
|
|
393
|
+
| `bun run release:github` | Create the GitHub release from the current tag |
|
|
394
|
+
|
|
395
|
+
---
|
|
396
|
+
|
|
397
|
+
## Bundling
|
|
398
|
+
|
|
399
|
+
`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.
|
|
400
|
+
|
|
401
|
+
**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.
|
|
402
|
+
|
|
403
|
+
**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`.
|
|
404
|
+
|
|
405
|
+
---
|
|
406
|
+
|
|
407
|
+
## Changelog
|
|
408
|
+
|
|
409
|
+
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.
|
|
410
|
+
|
|
411
|
+
Each per-version file opens with YAML frontmatter:
|
|
412
|
+
|
|
413
|
+
```markdown
|
|
414
|
+
---
|
|
415
|
+
summary: "One-line headline, ≤350 chars" # required — powers the rollup index
|
|
416
|
+
breaking: false # optional — true flags breaking changes
|
|
417
|
+
security: false # optional — true flags security fixes
|
|
418
|
+
---
|
|
419
|
+
|
|
420
|
+
# 0.1.0 — YYYY-MM-DD
|
|
421
|
+
...
|
|
422
|
+
```
|
|
423
|
+
|
|
424
|
+
`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`.
|
|
425
|
+
|
|
426
|
+
`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.
|
|
427
|
+
|
|
428
|
+
**Section order** (Keep a Changelog): Added, Changed, Deprecated, Removed, Fixed, Security. Include only sections with entries — don't ship empty headers.
|
|
429
|
+
|
|
430
|
+
**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.
|
|
431
|
+
|
|
432
|
+
---
|
|
433
|
+
|
|
434
|
+
## Imports
|
|
435
|
+
|
|
436
|
+
```ts
|
|
437
|
+
// Framework — z is re-exported, no separate zod import needed
|
|
438
|
+
import { tool, z } from '@cyanheads/mcp-ts-core';
|
|
439
|
+
import { McpError, JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
|
|
440
|
+
|
|
441
|
+
// Server's own code — via path alias
|
|
442
|
+
import { getMusicBrainzService } from '@/services/musicbrainz/musicbrainz-service.js';
|
|
443
|
+
import { getCoverArtService } from '@/services/cover-art/cover-art-service.js';
|
|
444
|
+
import type { EntityType } from '@/services/musicbrainz/types.js';
|
|
445
|
+
```
|
|
446
|
+
|
|
447
|
+
---
|
|
448
|
+
|
|
449
|
+
## Checklist
|
|
450
|
+
|
|
451
|
+
- [ ] 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()`)
|
|
452
|
+
- [ ] 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`.
|
|
453
|
+
- [ ] JSDoc `@fileoverview` + `@module` on every file
|
|
454
|
+
- [ ] `ctx.log` for logging, `ctx.state` for storage
|
|
455
|
+
- [ ] Handlers throw on failure — error factories or plain `Error`, no try/catch
|
|
456
|
+
- [ ] `format()` renders all data the LLM needs — different clients forward different surfaces (Claude Code → `structuredContent`, Claude Desktop → `content[]`); both must carry the same data
|
|
457
|
+
- [ ] If wrapping external API: raw/domain/output schemas reviewed against real upstream sparsity/nullability before finalizing required vs optional fields
|
|
458
|
+
- [ ] If wrapping external API: normalization and `format()` preserve uncertainty; do not fabricate facts from missing upstream data
|
|
459
|
+
- [ ] If wrapping external API: tests include at least one sparse payload case with omitted upstream fields
|
|
460
|
+
- [ ] Registered in `createApp()` arrays (directly or via barrel exports)
|
|
461
|
+
- [ ] Tests use `createMockContext()` from `@cyanheads/mcp-ts-core/testing`
|
|
462
|
+
- [ ] `.codex-plugin/plugin.json` populated — `name`, `version`, `description`, `repository`, `license` from `package.json`; `interface.displayName` = package name; `interface.shortDescription` from `package.json` description
|
|
463
|
+
- [ ] `.codex-plugin/mcp.json` updated — server name key matches `package.json` name; env vars added for any required API keys
|
|
464
|
+
- [ ] `.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
|
|
465
|
+
- [ ] All upstream calls route through `getMusicBrainzService()` / `getCoverArtService()` — never `fetch()` MusicBrainz directly. The service owns the mandatory descriptive `User-Agent` (with `MUSICBRAINZ_CONTACT`), the process-wide ~1 req/sec rate limiter, and the response cache; a stray fetch bypasses all three.
|
|
466
|
+
- [ ] `bun run devcheck` passes
|