@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
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Service for the Cover Art Archive (coverartarchive.org) — a host
|
|
3
|
+
* distinct from MusicBrainz WS/2 with its own response shape and failure mode.
|
|
4
|
+
* A release legitimately having no art returns HTTP 404 (with an HTML body), so
|
|
5
|
+
* this service maps 404 to a clean empty image set rather than an error. Art is
|
|
6
|
+
* served at the release level; a release-group MBID returns HTTP 307 redirecting
|
|
7
|
+
* to the representative release's `index.json` — native `fetch` follows the
|
|
8
|
+
* redirect automatically and the response shape is identical afterward.
|
|
9
|
+
* @module services/cover-art/cover-art-service
|
|
10
|
+
*/
|
|
11
|
+
import { createHash } from 'node:crypto';
|
|
12
|
+
import { JsonRpcErrorCode, McpError, serviceUnavailable } from '@cyanheads/mcp-ts-core/errors';
|
|
13
|
+
import { fetchWithTimeout, logger, requestContextService, withRetry, } from '@cyanheads/mcp-ts-core/utils';
|
|
14
|
+
import { getServerConfig } from '../../config/server-config.js';
|
|
15
|
+
/**
|
|
16
|
+
* Wraps the Cover Art Archive image-metadata endpoints. Shares nothing with the
|
|
17
|
+
* MusicBrainz limiter — CAA is a different host (backed by archive.org) without
|
|
18
|
+
* the ~1 req/sec MusicBrainz constraint.
|
|
19
|
+
*/
|
|
20
|
+
export class CoverArtService {
|
|
21
|
+
baseUrl;
|
|
22
|
+
timeoutMs;
|
|
23
|
+
maxRetries;
|
|
24
|
+
cacheTtlSeconds;
|
|
25
|
+
constructor(baseUrl, timeoutMs, maxRetries, cacheTtlSeconds) {
|
|
26
|
+
this.baseUrl = baseUrl;
|
|
27
|
+
this.timeoutMs = timeoutMs;
|
|
28
|
+
this.maxRetries = maxRetries;
|
|
29
|
+
this.cacheTtlSeconds = cacheTtlSeconds;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Fetch image metadata for a release or release-group MBID. Returns an empty
|
|
33
|
+
* `{ images: [] }` when the entity has no art (CAA 404) — the absence of art
|
|
34
|
+
* is information, not a failure. A malformed/zero MBID still surfaces as the
|
|
35
|
+
* upstream 400 (`InvalidParams`); transient 5xx is retried.
|
|
36
|
+
*/
|
|
37
|
+
async getImages(entityType, mbid, ctx, options) {
|
|
38
|
+
const path = `/${entityType}/${mbid}`;
|
|
39
|
+
// Hash the path to a `ctx.state`-safe key. The storage validator allows only
|
|
40
|
+
// `[a-zA-Z0-9_.\-/]` — so a `:` separator is rejected, and a malformed MBID
|
|
41
|
+
// can carry characters that would otherwise throw a generic ValidationError
|
|
42
|
+
// here and pre-empt the upstream 400 → invalid_mbid. `_` joins the prefix.
|
|
43
|
+
const key = `caa_${createHash('sha256').update(path).digest('hex')}`;
|
|
44
|
+
if (this.cacheTtlSeconds > 0) {
|
|
45
|
+
const cached = await ctx.state.get(key);
|
|
46
|
+
if (cached !== null) {
|
|
47
|
+
ctx.log.debug('Cover Art Archive cache hit', { path });
|
|
48
|
+
return cached;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
const url = `${this.baseUrl}${path}`;
|
|
52
|
+
const reqCtx = requestContextService.createRequestContext({
|
|
53
|
+
operation: 'CoverArtRequest',
|
|
54
|
+
requestId: ctx.requestId,
|
|
55
|
+
...(ctx.traceId && { traceId: ctx.traceId }),
|
|
56
|
+
});
|
|
57
|
+
let result;
|
|
58
|
+
try {
|
|
59
|
+
result = await withRetry(async () => {
|
|
60
|
+
const response = await fetchWithTimeout(url, this.timeoutMs, reqCtx, {
|
|
61
|
+
headers: { Accept: 'application/json' },
|
|
62
|
+
...(options?.signal && { signal: options.signal }),
|
|
63
|
+
});
|
|
64
|
+
const text = await response.text();
|
|
65
|
+
if (/^\s*<(!DOCTYPE\s+html|html[\s>])/i.test(text)) {
|
|
66
|
+
throw serviceUnavailable('Cover Art Archive returned HTML instead of JSON.', {
|
|
67
|
+
reason: 'caa_html_response',
|
|
68
|
+
path,
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
return JSON.parse(text);
|
|
72
|
+
}, {
|
|
73
|
+
operation: 'coverArtRequest',
|
|
74
|
+
context: reqCtx,
|
|
75
|
+
baseDelayMs: 1000,
|
|
76
|
+
maxRetries: this.maxRetries,
|
|
77
|
+
...(options?.signal && { signal: options.signal }),
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
catch (error) {
|
|
81
|
+
// 404 = no art for this entity. Map to an empty set, not an error.
|
|
82
|
+
if (error instanceof McpError && error.code === JsonRpcErrorCode.NotFound) {
|
|
83
|
+
ctx.log.debug('Cover Art Archive: no art for entity', { entityType, mbid });
|
|
84
|
+
result = { images: [] };
|
|
85
|
+
}
|
|
86
|
+
else {
|
|
87
|
+
throw error;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (this.cacheTtlSeconds > 0) {
|
|
91
|
+
await ctx.state.set(key, result, { ttl: this.cacheTtlSeconds });
|
|
92
|
+
}
|
|
93
|
+
return result;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
// ─── Init / Accessor ─────────────────────────────────────────────────────────
|
|
97
|
+
let _service;
|
|
98
|
+
/** Initialize the Cover Art service. Call from `setup()` in createApp. */
|
|
99
|
+
export function initCoverArtService() {
|
|
100
|
+
const config = getServerConfig();
|
|
101
|
+
_service = new CoverArtService(config.coverArtBaseUrl, config.timeoutMs, config.maxRetries, config.cacheTtlSeconds);
|
|
102
|
+
logger.info('Cover Art service initialized.', requestContextService.createRequestContext({
|
|
103
|
+
operation: 'CoverArtInit',
|
|
104
|
+
baseUrl: config.coverArtBaseUrl,
|
|
105
|
+
}));
|
|
106
|
+
}
|
|
107
|
+
/** Get the initialized Cover Art service. Throws if not initialized. */
|
|
108
|
+
export function getCoverArtService() {
|
|
109
|
+
if (!_service) {
|
|
110
|
+
throw new Error('Cover Art service not initialized — call initCoverArtService() in setup().');
|
|
111
|
+
}
|
|
112
|
+
return _service;
|
|
113
|
+
}
|
|
114
|
+
/** Reset the service singleton — test-only seam. */
|
|
115
|
+
export function resetCoverArtService() {
|
|
116
|
+
_service = undefined;
|
|
117
|
+
}
|
|
118
|
+
//# sourceMappingURL=cover-art-service.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cover-art-service.js","sourceRoot":"","sources":["../../../src/services/cover-art/cover-art-service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAGzC,OAAO,EAAE,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v2. Owns the
|
|
3
|
+
* mandatory descriptive User-Agent, a process-wide ~1 req/sec rate limiter (so
|
|
4
|
+
* concurrent tool calls serialize and never exceed MusicBrainz's per-IP ceiling),
|
|
5
|
+
* a response cache keyed on the full request (MBIDs are stable, data changes
|
|
6
|
+
* slowly), and `withRetry` backoff over the full fetch + parse pipeline.
|
|
7
|
+
*
|
|
8
|
+
* Three access modes, one method each: `search` (Lucene text → ranked MBIDs),
|
|
9
|
+
* `lookup` (MBID + `inc` → one entity with linked sub-resources folded in),
|
|
10
|
+
* `browse` (complete linked-set enumeration with deep pagination), plus
|
|
11
|
+
* `resolveIdentifier` (ISRC/ISWC/barcode → entities). Uses the init/accessor pattern.
|
|
12
|
+
* @module services/musicbrainz/musicbrainz-service
|
|
13
|
+
*/
|
|
14
|
+
import type { Context } from '@cyanheads/mcp-ts-core';
|
|
15
|
+
import { RateLimiter } from './rate-limiter.js';
|
|
16
|
+
import type { BrowseEnvelope, BrowseLink, CallOptions, EntityType, IsrcEnvelope, SearchEnvelope } from './types.js';
|
|
17
|
+
export interface SearchParams {
|
|
18
|
+
limit: number;
|
|
19
|
+
offset: number;
|
|
20
|
+
}
|
|
21
|
+
export interface LookupParams {
|
|
22
|
+
/** Pre-resolved `inc` tokens (e.g. `['release-groups', 'artist-rels']`). Empty = bare entity. */
|
|
23
|
+
inc: string[];
|
|
24
|
+
}
|
|
25
|
+
export interface BrowseParams {
|
|
26
|
+
limit: number;
|
|
27
|
+
link: BrowseLink;
|
|
28
|
+
linkMbid: string;
|
|
29
|
+
offset: number;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Facade over the MusicBrainz WS/2 endpoints. Every public method runs through
|
|
33
|
+
* the shared rate limiter, the cache, and the retry wrapper.
|
|
34
|
+
*/
|
|
35
|
+
export declare class MusicBrainzService {
|
|
36
|
+
private readonly baseUrl;
|
|
37
|
+
private readonly limiter;
|
|
38
|
+
private readonly cacheTtlSeconds;
|
|
39
|
+
private readonly timeoutMs;
|
|
40
|
+
private readonly maxRetries;
|
|
41
|
+
private readonly userAgent;
|
|
42
|
+
constructor(baseUrl: string, contact: string, version: string, limiter: RateLimiter, cacheTtlSeconds: number, timeoutMs: number, maxRetries: number);
|
|
43
|
+
/** Full-text Lucene search over an entity type. Returns the raw search envelope. */
|
|
44
|
+
search(type: EntityType, query: string, params: SearchParams, ctx: Context, options?: CallOptions): Promise<SearchEnvelope>;
|
|
45
|
+
/** Look up one entity by MBID with the requested `inc` sub-resources folded in. */
|
|
46
|
+
lookup<T>(type: EntityType, mbid: string, params: LookupParams, ctx: Context, options?: CallOptions): Promise<T>;
|
|
47
|
+
/** Paginate the complete set of `target` entities linked to one parent MBID. */
|
|
48
|
+
browse(target: EntityType, params: BrowseParams, ctx: Context, options?: CallOptions): Promise<BrowseEnvelope>;
|
|
49
|
+
/**
|
|
50
|
+
* Resolve a standard identifier to entities. ISRC and ISWC are dedicated
|
|
51
|
+
* endpoints (deterministic, no `inc` — the endpoint returns 400 if `inc` is
|
|
52
|
+
* sent); barcode is a release search filter (`?query=barcode:...`), so the
|
|
53
|
+
* caller routes that through {@link search} instead.
|
|
54
|
+
*/
|
|
55
|
+
resolveIsrc(value: string, ctx: Context, options?: CallOptions): Promise<IsrcEnvelope>;
|
|
56
|
+
resolveIswc(value: string, ctx: Context, options?: CallOptions): Promise<BrowseEnvelope>;
|
|
57
|
+
/** Pluralized array key for an entity type — for handlers reading search/browse envelopes. */
|
|
58
|
+
static pluralKey(type: EntityType): keyof SearchEnvelope & keyof BrowseEnvelope;
|
|
59
|
+
/**
|
|
60
|
+
* Core request pipeline: cache check → rate-limited, retried fetch + parse →
|
|
61
|
+
* cache store. `path` is the full WS/2 path with query string (already
|
|
62
|
+
* `fmt=json`). A 400 (malformed MBID) maps to `InvalidParams` and a 404 (no
|
|
63
|
+
* such entity) to `NotFound` via `fetchWithTimeout`'s status table — both
|
|
64
|
+
* non-transient, so they fail fast without burning retries. A 503 / 5xx / HTML
|
|
65
|
+
* error page is transient and retried.
|
|
66
|
+
*/
|
|
67
|
+
private request;
|
|
68
|
+
/**
|
|
69
|
+
* Parse a JSON response body. MusicBrainz occasionally serves an HTML error
|
|
70
|
+
* page under load with a 200 — detect it and throw transient
|
|
71
|
+
* `ServiceUnavailable` (retryable) rather than a non-transient parse error.
|
|
72
|
+
*/
|
|
73
|
+
private parse;
|
|
74
|
+
}
|
|
75
|
+
/** Initialize the MusicBrainz service. Call from `setup()` in createApp. */
|
|
76
|
+
export declare function initMusicBrainzService(version: string): void;
|
|
77
|
+
/** Get the initialized MusicBrainz service. Throws if not initialized. */
|
|
78
|
+
export declare function getMusicBrainzService(): MusicBrainzService;
|
|
79
|
+
/** Reset the service singleton — test-only seam. */
|
|
80
|
+
export declare function resetMusicBrainzService(): void;
|
|
81
|
+
//# sourceMappingURL=musicbrainz-service.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"musicbrainz-service.d.ts","sourceRoot":"","sources":["../../../src/services/musicbrainz/musicbrainz-service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAIH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AAUtD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,KAAK,EACV,cAAc,EACd,UAAU,EACV,WAAW,EACX,UAAU,EACV,YAAY,EACZ,cAAc,EACf,MAAM,YAAY,CAAC;AAwBpB,MAAM,WAAW,YAAY;IAC3B,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,YAAY;IAC3B,iGAAiG;IACjG,GAAG,EAAE,MAAM,EAAE,CAAC;CACf;AAED,MAAM,WAAW,YAAY;IAC3B,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,UAAU,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;;;GAGG;AACH,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F,MAAM,CAAC,SAAS,CAAC,IAAI,EAAE,UAAU,GAAG,MAAM,cAAc,GAAG,MAAM,cAAc;IAI/E;;;;;;;OAOG;YACW,OAAO;IA0CrB;;;;OAIG;IACH,OAAO,CAAC,KAAK;CAmBd;AAMD,4EAA4E;AAC5E,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAqB5D;AAED,0EAA0E;AAC1E,wBAAgB,qBAAqB,IAAI,kBAAkB,CAO1D;AAED,oDAAoD;AACpD,wBAAgB,uBAAuB,IAAI,IAAI,CAE9C"}
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview High-level service for the MusicBrainz Web Service v2. Owns the
|
|
3
|
+
* mandatory descriptive User-Agent, a process-wide ~1 req/sec rate limiter (so
|
|
4
|
+
* concurrent tool calls serialize and never exceed MusicBrainz's per-IP ceiling),
|
|
5
|
+
* a response cache keyed on the full request (MBIDs are stable, data changes
|
|
6
|
+
* slowly), and `withRetry` backoff over the full fetch + parse pipeline.
|
|
7
|
+
*
|
|
8
|
+
* Three access modes, one method each: `search` (Lucene text → ranked MBIDs),
|
|
9
|
+
* `lookup` (MBID + `inc` → one entity with linked sub-resources folded in),
|
|
10
|
+
* `browse` (complete linked-set enumeration with deep pagination), plus
|
|
11
|
+
* `resolveIdentifier` (ISRC/ISWC/barcode → entities). Uses the init/accessor pattern.
|
|
12
|
+
* @module services/musicbrainz/musicbrainz-service
|
|
13
|
+
*/
|
|
14
|
+
import { createHash } from 'node:crypto';
|
|
15
|
+
import { serviceUnavailable } from '@cyanheads/mcp-ts-core/errors';
|
|
16
|
+
import { fetchWithTimeout, logger, requestContextService, withRetry, } from '@cyanheads/mcp-ts-core/utils';
|
|
17
|
+
import { getServerConfig } from '../../config/server-config.js';
|
|
18
|
+
import { RateLimiter } from './rate-limiter.js';
|
|
19
|
+
/**
|
|
20
|
+
* Build a `ctx.state`-safe cache key from a request path. The storage key
|
|
21
|
+
* validator allows only `[a-zA-Z0-9_.\-/]`, so neither the raw WS/2 path (which
|
|
22
|
+
* carries `?`, `=`, `&`) nor a `:` namespace separator is usable. The path is
|
|
23
|
+
* hashed to a stable hex digest and joined to the prefix with `_`. Same path →
|
|
24
|
+
* same key, so cache hits still land; the digest is always pattern-safe and
|
|
25
|
+
* fixed-length regardless of query content.
|
|
26
|
+
*/
|
|
27
|
+
function cacheKey(prefix, path) {
|
|
28
|
+
return `${prefix}_${createHash('sha256').update(path).digest('hex')}`;
|
|
29
|
+
}
|
|
30
|
+
/** Pluralized search/browse array keys, by entity type. */
|
|
31
|
+
const ENTITY_PLURAL = {
|
|
32
|
+
artist: 'artists',
|
|
33
|
+
'release-group': 'release-groups',
|
|
34
|
+
release: 'releases',
|
|
35
|
+
recording: 'recordings',
|
|
36
|
+
work: 'works',
|
|
37
|
+
label: 'labels',
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* Facade over the MusicBrainz WS/2 endpoints. Every public method runs through
|
|
41
|
+
* the shared rate limiter, the cache, and the retry wrapper.
|
|
42
|
+
*/
|
|
43
|
+
export class MusicBrainzService {
|
|
44
|
+
baseUrl;
|
|
45
|
+
limiter;
|
|
46
|
+
cacheTtlSeconds;
|
|
47
|
+
timeoutMs;
|
|
48
|
+
maxRetries;
|
|
49
|
+
userAgent;
|
|
50
|
+
constructor(baseUrl, contact, version, limiter, cacheTtlSeconds, timeoutMs, maxRetries) {
|
|
51
|
+
this.baseUrl = baseUrl;
|
|
52
|
+
this.limiter = limiter;
|
|
53
|
+
this.cacheTtlSeconds = cacheTtlSeconds;
|
|
54
|
+
this.timeoutMs = timeoutMs;
|
|
55
|
+
this.maxRetries = maxRetries;
|
|
56
|
+
this.userAgent = `musicbrainz-mcp-server/${version} ( ${contact} )`;
|
|
57
|
+
}
|
|
58
|
+
/** Full-text Lucene search over an entity type. Returns the raw search envelope. */
|
|
59
|
+
search(type, query, params, ctx, options) {
|
|
60
|
+
const search = new URLSearchParams({
|
|
61
|
+
query,
|
|
62
|
+
limit: String(params.limit),
|
|
63
|
+
offset: String(params.offset),
|
|
64
|
+
fmt: 'json',
|
|
65
|
+
});
|
|
66
|
+
return this.request(`/${type}?${search.toString()}`, ctx, options);
|
|
67
|
+
}
|
|
68
|
+
/** Look up one entity by MBID with the requested `inc` sub-resources folded in. */
|
|
69
|
+
lookup(type, mbid, params, ctx, options) {
|
|
70
|
+
const search = new URLSearchParams({ fmt: 'json' });
|
|
71
|
+
if (params.inc.length > 0)
|
|
72
|
+
search.set('inc', params.inc.join('+'));
|
|
73
|
+
return this.request(`/${type}/${mbid}?${search.toString()}`, ctx, options);
|
|
74
|
+
}
|
|
75
|
+
/** Paginate the complete set of `target` entities linked to one parent MBID. */
|
|
76
|
+
browse(target, params, ctx, options) {
|
|
77
|
+
const search = new URLSearchParams({
|
|
78
|
+
[params.link]: params.linkMbid,
|
|
79
|
+
limit: String(params.limit),
|
|
80
|
+
offset: String(params.offset),
|
|
81
|
+
fmt: 'json',
|
|
82
|
+
});
|
|
83
|
+
return this.request(`/${target}?${search.toString()}`, ctx, options);
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Resolve a standard identifier to entities. ISRC and ISWC are dedicated
|
|
87
|
+
* endpoints (deterministic, no `inc` — the endpoint returns 400 if `inc` is
|
|
88
|
+
* sent); barcode is a release search filter (`?query=barcode:...`), so the
|
|
89
|
+
* caller routes that through {@link search} instead.
|
|
90
|
+
*/
|
|
91
|
+
resolveIsrc(value, ctx, options) {
|
|
92
|
+
return this.request(`/isrc/${encodeURIComponent(value)}?fmt=json`, ctx, options);
|
|
93
|
+
}
|
|
94
|
+
resolveIswc(value, ctx, options) {
|
|
95
|
+
// ISWC endpoint returns a browse-style envelope: { work-count, work-offset, works[] }.
|
|
96
|
+
return this.request(`/iswc/${encodeURIComponent(value)}?fmt=json`, ctx, options);
|
|
97
|
+
}
|
|
98
|
+
/** Pluralized array key for an entity type — for handlers reading search/browse envelopes. */
|
|
99
|
+
static pluralKey(type) {
|
|
100
|
+
return ENTITY_PLURAL[type];
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Core request pipeline: cache check → rate-limited, retried fetch + parse →
|
|
104
|
+
* cache store. `path` is the full WS/2 path with query string (already
|
|
105
|
+
* `fmt=json`). A 400 (malformed MBID) maps to `InvalidParams` and a 404 (no
|
|
106
|
+
* such entity) to `NotFound` via `fetchWithTimeout`'s status table — both
|
|
107
|
+
* non-transient, so they fail fast without burning retries. A 503 / 5xx / HTML
|
|
108
|
+
* error page is transient and retried.
|
|
109
|
+
*/
|
|
110
|
+
async request(path, ctx, options) {
|
|
111
|
+
const key = cacheKey('mb', path);
|
|
112
|
+
if (this.cacheTtlSeconds > 0) {
|
|
113
|
+
const cached = await ctx.state.get(key);
|
|
114
|
+
if (cached !== null) {
|
|
115
|
+
ctx.log.debug('MusicBrainz cache hit', { path });
|
|
116
|
+
return cached;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
const url = `${this.baseUrl}${path}`;
|
|
120
|
+
const reqCtx = requestContextService.createRequestContext({
|
|
121
|
+
operation: 'MusicBrainzRequest',
|
|
122
|
+
requestId: ctx.requestId,
|
|
123
|
+
...(ctx.traceId && { traceId: ctx.traceId }),
|
|
124
|
+
});
|
|
125
|
+
const result = await withRetry(() => this.limiter.schedule(async () => {
|
|
126
|
+
const response = await fetchWithTimeout(url, this.timeoutMs, reqCtx, {
|
|
127
|
+
headers: { 'User-Agent': this.userAgent, Accept: 'application/json' },
|
|
128
|
+
...(options?.signal && { signal: options.signal }),
|
|
129
|
+
});
|
|
130
|
+
const text = await response.text();
|
|
131
|
+
return this.parse(text, path);
|
|
132
|
+
}, options?.signal), {
|
|
133
|
+
operation: 'musicbrainzRequest',
|
|
134
|
+
context: reqCtx,
|
|
135
|
+
baseDelayMs: 1500, // rate-limited tier — 503 carries Retry-After
|
|
136
|
+
maxRetries: this.maxRetries,
|
|
137
|
+
...(options?.signal && { signal: options.signal }),
|
|
138
|
+
});
|
|
139
|
+
if (this.cacheTtlSeconds > 0) {
|
|
140
|
+
await ctx.state.set(key, result, { ttl: this.cacheTtlSeconds });
|
|
141
|
+
}
|
|
142
|
+
return result;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Parse a JSON response body. MusicBrainz occasionally serves an HTML error
|
|
146
|
+
* page under load with a 200 — detect it and throw transient
|
|
147
|
+
* `ServiceUnavailable` (retryable) rather than a non-transient parse error.
|
|
148
|
+
*/
|
|
149
|
+
parse(text, path) {
|
|
150
|
+
if (/^\s*<(!DOCTYPE\s+html|html[\s>])/i.test(text)) {
|
|
151
|
+
throw serviceUnavailable('MusicBrainz returned an HTML page instead of JSON — likely rate-limited or degraded.', { reason: 'musicbrainz_html_response', path });
|
|
152
|
+
}
|
|
153
|
+
try {
|
|
154
|
+
return JSON.parse(text);
|
|
155
|
+
}
|
|
156
|
+
catch (error) {
|
|
157
|
+
// A non-HTML body that won't parse is rare; treat as transient (the
|
|
158
|
+
// upstream may have truncated mid-response under load).
|
|
159
|
+
throw serviceUnavailable('MusicBrainz returned a malformed JSON response.', { reason: 'musicbrainz_malformed_json', path }, { cause: error });
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
// ─── Init / Accessor ─────────────────────────────────────────────────────────
|
|
164
|
+
let _service;
|
|
165
|
+
/** Initialize the MusicBrainz service. Call from `setup()` in createApp. */
|
|
166
|
+
export function initMusicBrainzService(version) {
|
|
167
|
+
const config = getServerConfig();
|
|
168
|
+
const limiter = new RateLimiter(config.rateLimitRps);
|
|
169
|
+
_service = new MusicBrainzService(config.baseUrl, config.contact, version, limiter, config.cacheTtlSeconds, config.timeoutMs, config.maxRetries);
|
|
170
|
+
logger.info('MusicBrainz service initialized.', requestContextService.createRequestContext({
|
|
171
|
+
operation: 'MusicBrainzInit',
|
|
172
|
+
baseUrl: config.baseUrl,
|
|
173
|
+
rateLimitRps: config.rateLimitRps,
|
|
174
|
+
cacheTtlSeconds: config.cacheTtlSeconds,
|
|
175
|
+
}));
|
|
176
|
+
}
|
|
177
|
+
/** Get the initialized MusicBrainz service. Throws if not initialized. */
|
|
178
|
+
export function getMusicBrainzService() {
|
|
179
|
+
if (!_service) {
|
|
180
|
+
throw new Error('MusicBrainz service not initialized — call initMusicBrainzService() in setup().');
|
|
181
|
+
}
|
|
182
|
+
return _service;
|
|
183
|
+
}
|
|
184
|
+
/** Reset the service singleton — test-only seam. */
|
|
185
|
+
export function resetMusicBrainzService() {
|
|
186
|
+
_service = undefined;
|
|
187
|
+
}
|
|
188
|
+
//# sourceMappingURL=musicbrainz-service.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"musicbrainz-service.js","sourceRoot":"","sources":["../../../src/services/musicbrainz/musicbrainz-service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAGzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,EACL,gBAAgB,EAChB,MAAM,EACN,qBAAqB,EACrB,SAAS,GACV,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAUhD;;;;;;;GAOG;AACH,SAAS,QAAQ,CAAC,MAAc,EAAE,IAAY;IAC5C,OAAO,GAAG,MAAM,IAAI,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;AACxE,CAAC;AAED,2DAA2D;AAC3D,MAAM,aAAa,GAAoE;IACrF,MAAM,EAAE,SAAS;IACjB,eAAe,EAAE,gBAAgB;IACjC,OAAO,EAAE,UAAU;IACnB,SAAS,EAAE,YAAY;IACvB,IAAI,EAAE,OAAO;IACb,KAAK,EAAE,QAAQ;CAChB,CAAC;A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eAAe,EACtB,MAAM,CAAC,SAAS,EAChB,MAAM,CAAC,UAAU,CAClB,CAAC;IACF,MAAM,CAAC,IAAI,CACT,kCAAkC,EAClC,qBAAqB,CAAC,oBAAoB,CAAC;QACzC,SAAS,EAAE,iBAAiB;QAC5B,OAAO,EAAE,MAAM,CAAC,OAAO;QACvB,YAAY,EAAE,MAAM,CAAC,YAAY;QACjC,eAAe,EAAE,MAAM,CAAC,eAAe;KACxC,CAAC,CACH,CAAC;AACJ,CAAC;AAED,0EAA0E;AAC1E,MAAM,UAAU,qBAAqB;IACnC,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,MAAM,IAAI,KAAK,CACb,iFAAiF,CAClF,CAAC;IACJ,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,oDAAoD;AACpD,MAAM,UAAU,uBAAuB;IACrC,QAAQ,GAAG,SAAS,CAAC;AACvB,CAAC"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Process-wide request rate limiter for the MusicBrainz Web
|
|
3
|
+
* Service. MusicBrainz enforces ~1 request/second per IP across its whole
|
|
4
|
+
* hosted instance and returns HTTP 503 + `Retry-After` when exceeded, so a
|
|
5
|
+
* client-side limiter is mandatory: on a hosted multi-tenant deployment every
|
|
6
|
+
* tenant shares one limiter or concurrent callers starve each other.
|
|
7
|
+
*
|
|
8
|
+
* Implemented as a minimum-start-gap serializer (a token bucket of capacity 1,
|
|
9
|
+
* refilling one token every `1000 / rps` ms). Calls are dispatched one at a time
|
|
10
|
+
* with at least `minGapMs` between consecutive starts; concurrent callers queue
|
|
11
|
+
* FIFO. Waiting tasks honor an optional `AbortSignal` so a caller's cancellation
|
|
12
|
+
* or deadline bounds queue time end-to-end rather than sitting behind a backlog.
|
|
13
|
+
* @module services/musicbrainz/rate-limiter
|
|
14
|
+
*/
|
|
15
|
+
/**
|
|
16
|
+
* Serializes upstream calls to a fixed maximum start-rate. One instance is
|
|
17
|
+
* shared process-wide by the MusicBrainz service.
|
|
18
|
+
*/
|
|
19
|
+
export declare class RateLimiter {
|
|
20
|
+
private readonly minGapMs;
|
|
21
|
+
/** Tail of the dispatch chain — each scheduled call awaits the previous one's gap. */
|
|
22
|
+
private chain;
|
|
23
|
+
constructor(requestsPerSecond: number);
|
|
24
|
+
/**
|
|
25
|
+
* Schedule `task` behind any already-queued calls, enforcing the minimum gap
|
|
26
|
+
* between consecutive starts. Rejects with `signal.reason` if the signal
|
|
27
|
+
* aborts while still waiting in the queue (the in-flight `task` forwards its
|
|
28
|
+
* own signal to downstream I/O).
|
|
29
|
+
*/
|
|
30
|
+
schedule<T>(task: () => Promise<T>, signal?: AbortSignal): Promise<T>;
|
|
31
|
+
}
|
|
32
|
+
//# sourceMappingURL=rate-limiter.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rate-limiter.d.ts","sourceRoot":"","sources":["../../../src/services/musicbrainz/rate-limiter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH;;;GAGG;AACH,qBAAa,WAAW;IACtB,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,sFAAsF;IACtF,OAAO,CAAC,KAAK,CAAoC;gBAErC,iBAAiB,EAAE,MAAM;IAIrC;;;;;OAKG;IACG,QAAQ,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,CAAC,CAAC;CAoB5E"}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Process-wide request rate limiter for the MusicBrainz Web
|
|
3
|
+
* Service. MusicBrainz enforces ~1 request/second per IP across its whole
|
|
4
|
+
* hosted instance and returns HTTP 503 + `Retry-After` when exceeded, so a
|
|
5
|
+
* client-side limiter is mandatory: on a hosted multi-tenant deployment every
|
|
6
|
+
* tenant shares one limiter or concurrent callers starve each other.
|
|
7
|
+
*
|
|
8
|
+
* Implemented as a minimum-start-gap serializer (a token bucket of capacity 1,
|
|
9
|
+
* refilling one token every `1000 / rps` ms). Calls are dispatched one at a time
|
|
10
|
+
* with at least `minGapMs` between consecutive starts; concurrent callers queue
|
|
11
|
+
* FIFO. Waiting tasks honor an optional `AbortSignal` so a caller's cancellation
|
|
12
|
+
* or deadline bounds queue time end-to-end rather than sitting behind a backlog.
|
|
13
|
+
* @module services/musicbrainz/rate-limiter
|
|
14
|
+
*/
|
|
15
|
+
/**
|
|
16
|
+
* Serializes upstream calls to a fixed maximum start-rate. One instance is
|
|
17
|
+
* shared process-wide by the MusicBrainz service.
|
|
18
|
+
*/
|
|
19
|
+
export class RateLimiter {
|
|
20
|
+
minGapMs;
|
|
21
|
+
/** Tail of the dispatch chain — each scheduled call awaits the previous one's gap. */
|
|
22
|
+
chain = Promise.resolve();
|
|
23
|
+
constructor(requestsPerSecond) {
|
|
24
|
+
this.minGapMs = requestsPerSecond > 0 ? 1000 / requestsPerSecond : 0;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Schedule `task` behind any already-queued calls, enforcing the minimum gap
|
|
28
|
+
* between consecutive starts. Rejects with `signal.reason` if the signal
|
|
29
|
+
* aborts while still waiting in the queue (the in-flight `task` forwards its
|
|
30
|
+
* own signal to downstream I/O).
|
|
31
|
+
*/
|
|
32
|
+
async schedule(task, signal) {
|
|
33
|
+
const waitForTurn = this.chain;
|
|
34
|
+
let releaseGap;
|
|
35
|
+
// Extend the chain immediately so the next caller waits for THIS call's gap,
|
|
36
|
+
// before we ever await — keeps scheduling order deterministic under concurrency.
|
|
37
|
+
this.chain = new Promise((resolve) => {
|
|
38
|
+
releaseGap = resolve;
|
|
39
|
+
});
|
|
40
|
+
try {
|
|
41
|
+
await waitForTurn;
|
|
42
|
+
if (signal?.aborted)
|
|
43
|
+
throw signal.reason;
|
|
44
|
+
return await task();
|
|
45
|
+
}
|
|
46
|
+
finally {
|
|
47
|
+
// Release the next caller after the gap elapses. Detached from the task's
|
|
48
|
+
// own completion: the gap is measured from this call's start, and the timer
|
|
49
|
+
// must not be cancelled by the caller's signal (that would stall the queue).
|
|
50
|
+
setTimeout(releaseGap, this.minGapMs);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
//# sourceMappingURL=rate-limiter.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rate-limiter.js","sourceRoot":"","sources":["../../../src/services/musicbrainz/rate-limiter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH;;;GAGG;AACH,MAAM,OAAO,WAAW;IACL,QAAQ,CAAS;IAClC,sFAAsF;IAC9E,KAAK,GAAkB,OAAO,CAAC,OAAO,EAAE,CAAC;IAEjD,YAAY,iBAAyB;QACnC,IAAI,CAAC,QAAQ,GAAG,iBAAiB,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,iBAAiB,CAAC,CAAC,CAAC,CAAC,CAAC;IACvE,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,QAAQ,CAAI,IAAsB,EAAE,MAAoB;QAC5D,MAAM,WAAW,GAAG,IAAI,CAAC,KAAK,CAAC;QAC/B,IAAI,UAAuB,CAAC;QAC5B,6EAA6E;QAC7E,iFAAiF;QACjF,IAAI,CAAC,KAAK,GAAG,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE;YACzC,UAAU,GAAG,OAAO,CAAC;QACvB,CAAC,CAAC,CAAC;QAEH,IAAI,CAAC;YACH,MAAM,WAAW,CAAC;YAClB,IAAI,MAAM,EAAE,OAAO;gBAAE,MAAM,MAAM,CAAC,MAAM,CAAC;YACzC,OAAO,MAAM,IAAI,EAAE,CAAC;QACtB,CAAC;gBAAS,CAAC;YACT,0EAA0E;YAC1E,4EAA4E;YAC5E,6EAA6E;YAC7E,UAAU,CAAC,UAAU,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC;QACxC,CAAC;IACH,CAAC;CACF"}
|