mr-magic-mcp-server 0.3.10 → 0.3.12

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.
@@ -4,6 +4,7 @@ import { normalizeLyricRecord } from '../provider-result-schema.js';
4
4
  import { createLogger } from '../utils/logger.js';
5
5
  import {
6
6
  getMusixmatchToken,
7
+ getMusixmatchDesktopCookie,
7
8
  invalidateMusixmatchToken
8
9
  } from '../utils/tokens/musixmatch-token-manager.js';
9
10
 
@@ -15,9 +16,60 @@ const DEFAULT_HEADERS = {
15
16
  authority: 'apic-desktop.musixmatch.com',
16
17
  'User-Agent': MOZILLA_USER_AGENT
17
18
  };
19
+ const MXM_COOKIE_FALLBACK = 'x-mxm-token-guid=';
18
20
 
19
21
  const logger = createLogger('provider:musixmatch');
20
22
 
23
+ function formatSubtitleTimestamp(item) {
24
+ if (!item || typeof item !== 'object') return null;
25
+
26
+ const text =
27
+ typeof item.text === 'string'
28
+ ? item.text
29
+ : typeof item.subtitle_body === 'string'
30
+ ? item.subtitle_body
31
+ : '';
32
+
33
+ const candidates = [
34
+ item.time,
35
+ item.timestamp,
36
+ item.ts,
37
+ item.line_time,
38
+ item.lineTime,
39
+ item.time_total,
40
+ item.timeTotal
41
+ ].filter((value) => value !== null && value !== undefined);
42
+
43
+ const numericCandidate = candidates.find((value) => typeof value === 'number');
44
+ if (typeof numericCandidate === 'number' && Number.isFinite(numericCandidate)) {
45
+ const totalCentiseconds = Math.max(0, Math.round(numericCandidate * 100));
46
+ const minutes = Math.floor(totalCentiseconds / 6000);
47
+ const seconds = Math.floor((totalCentiseconds % 6000) / 100);
48
+ const hundredths = totalCentiseconds % 100;
49
+ return `[${minutes.toString().padStart(2, '0')}:${seconds
50
+ .toString()
51
+ .padStart(2, '0')}.${hundredths.toString().padStart(2, '0')}] ${text}`.trim();
52
+ }
53
+
54
+ const timeObject = candidates.find((value) => value && typeof value === 'object');
55
+ if (timeObject) {
56
+ const minutes = Number(timeObject.minutes ?? timeObject.min ?? 0);
57
+ const seconds = Number(timeObject.seconds ?? timeObject.sec ?? 0);
58
+ const hundredths = Number(
59
+ timeObject.hundredths ?? timeObject.hundredth ?? timeObject.cs ?? timeObject.milliseconds ?? 0
60
+ );
61
+ if ([minutes, seconds, hundredths].every(Number.isFinite)) {
62
+ const normalizedHundredths =
63
+ hundredths > 99 ? Math.floor(hundredths / 10) : Math.max(0, hundredths);
64
+ return `[${minutes.toString().padStart(2, '0')}:${seconds
65
+ .toString()
66
+ .padStart(2, '0')}.${normalizedHundredths.toString().padStart(2, '0')}] ${text}`.trim();
67
+ }
68
+ }
69
+
70
+ return null;
71
+ }
72
+
21
73
  function buildParams(track, token) {
22
74
  const durationSeconds = track.duration ? Math.round(track.duration / 1000) : '';
23
75
  return new URLSearchParams({
@@ -36,13 +88,56 @@ function buildParams(track, token) {
36
88
  });
37
89
  }
38
90
 
91
+ function summarizeMacroStatus(body = {}) {
92
+ return {
93
+ matcher: body['matcher.track.get']?.message?.header ?? null,
94
+ lyrics: body['track.lyrics.get']?.message?.header ?? null,
95
+ subtitles: body['track.subtitles.get']?.message?.header ?? null
96
+ };
97
+ }
98
+
99
+ function buildBlockedRecord(track = {}, body = {}, reason = 'captcha') {
100
+ return normalizeLyricRecord({
101
+ provider: 'musixmatch',
102
+ id: null,
103
+ trackName: track.title || null,
104
+ artistName: track.artist || null,
105
+ albumName: track.album || null,
106
+ duration: track.duration ? Math.round(track.duration / 1000) : null,
107
+ plainLyrics: null,
108
+ syncedLyrics: null,
109
+ sourceUrl: null,
110
+ confidence: 0,
111
+ synced: false,
112
+ status: reason === 'captcha' ? 'captcha_blocked' : 'blocked',
113
+ raw: body
114
+ });
115
+ }
116
+
117
+ function classifyUnauthorizedPayload(payload) {
118
+ const hint = payload?.message?.header?.hint;
119
+ if (hint === 'renew') {
120
+ return 'MUSIXMATCH_TOKEN_RENEW';
121
+ }
122
+ return 'MUSIXMATCH_CAPTCHA';
123
+ }
124
+
39
125
  function normalizeBody(body) {
40
126
  const matcher = body['matcher.track.get']?.message?.body;
41
127
  if (!matcher) {
128
+ logger.warn('Musixmatch matcher body missing', { macroStatus: summarizeMacroStatus(body) });
42
129
  return null;
43
130
  }
44
131
 
45
132
  const meta = matcher.track || {};
133
+ if (!meta.track_id) {
134
+ logger.warn('Musixmatch matcher returned no track', {
135
+ macroStatus: summarizeMacroStatus(body),
136
+ matcherBodyType: Array.isArray(matcher) ? 'array' : typeof matcher,
137
+ matcherPreview: Array.isArray(matcher) ? matcher.slice(0, 2) : matcher
138
+ });
139
+ return null;
140
+ }
46
141
  const lyricsBody = body['track.lyrics.get']?.message?.body?.lyrics?.lyrics_body || '';
47
142
  const subtitlesRoot = body['track.subtitles.get']?.message?.body;
48
143
  const subtitleEntry =
@@ -73,18 +168,38 @@ function normalizeBody(body) {
73
168
  }
74
169
  }
75
170
 
76
- const syncedLyrics = syncedLines
77
- .map((item) => {
78
- const time = item?.time || {};
79
- return `[${time.minutes.toString().padStart(2, '0')}:${time.seconds.toString().padStart(2, '0')}.${(
80
- time.hundredths || 0
81
- )
82
- .toString()
83
- .padStart(2, '0')}] ${item.text}`.trim();
84
- })
85
- .join('\n');
171
+ const syncedLyricLines = [];
172
+ let skippedSubtitleItems = 0;
173
+ for (const item of Array.isArray(syncedLines) ? syncedLines : []) {
174
+ const formattedLine = formatSubtitleTimestamp(item);
175
+ if (formattedLine) {
176
+ syncedLyricLines.push(formattedLine);
177
+ } else {
178
+ skippedSubtitleItems += 1;
179
+ }
180
+ }
181
+
182
+ if (skippedSubtitleItems > 0) {
183
+ logger.warn('Musixmatch subtitle items skipped due to unrecognized shape', {
184
+ skippedSubtitleItems,
185
+ sample: Array.isArray(syncedLines) ? syncedLines.slice(0, 2) : syncedLines,
186
+ trackId: meta.track_id,
187
+ trackName: meta.track_name,
188
+ artistName: meta.artist_name
189
+ });
190
+ }
191
+
192
+ const syncedLyrics = syncedLyricLines.join('\n');
86
193
 
87
194
  const plainLyrics = lyricsBody.split('\n').filter(Boolean).join('\n');
195
+ if (!plainLyrics && !syncedLyrics) {
196
+ logger.warn('Musixmatch matched track but returned no lyric content', {
197
+ trackId: meta.track_id,
198
+ trackName: meta.track_name,
199
+ artistName: meta.artist_name,
200
+ macroStatus: summarizeMacroStatus(body)
201
+ });
202
+ }
88
203
  const sourceUrl = meta.share_url || '';
89
204
 
90
205
  return normalizeLyricRecord({
@@ -107,25 +222,122 @@ function normalizeBody(body) {
107
222
  async function macroRequest(track) {
108
223
  await ensureMusixmatchToken();
109
224
  let token = await getMusixmatchToken();
110
- const attempt = async (tok) => {
225
+ let desktopCookie = await getMusixmatchDesktopCookie();
226
+ const topLevel401 = (payload) => payload?.message?.header?.status_code === 401;
227
+ const attempt = async (tok, cookie) => {
111
228
  const params = buildParams(track, tok);
229
+ const requestHeaders = {
230
+ ...DEFAULT_HEADERS,
231
+ Cookie: cookie || MXM_COOKIE_FALLBACK
232
+ };
112
233
  const response = await axios.get(`${BASE_URL}?${params.toString()}`, {
113
234
  timeout: HTTP_TIMEOUT_MS,
114
- headers: DEFAULT_HEADERS
235
+ headers: requestHeaders,
236
+ validateStatus: () => true,
237
+ responseType: 'text',
238
+ transformResponse: [(value) => value]
239
+ });
240
+ const contentType = response.headers?.['content-type'] || null;
241
+ const bodyPreview =
242
+ typeof response.data === 'string' ? response.data.slice(0, 240) : (response.data ?? null);
243
+
244
+ logger.debug('Musixmatch raw response received', {
245
+ httpStatus: response.status,
246
+ contentType,
247
+ dataType: typeof response.data,
248
+ bodyPreview,
249
+ trackTitle: track?.title || null,
250
+ trackArtist: track?.artist || null,
251
+ desktopCookiePresent: Boolean(cookie),
252
+ usingFallbackCookie: !cookie
115
253
  });
116
- return response.data?.message?.body?.macro_calls || response.data?.message?.body || {};
254
+
255
+ if (typeof response.data !== 'string') {
256
+ logger.warn('Musixmatch returned non-text raw payload', {
257
+ httpStatus: response.status,
258
+ contentType,
259
+ dataType: typeof response.data
260
+ });
261
+ }
262
+
263
+ if (typeof response.data === 'string') {
264
+ const trimmed = response.data.trim();
265
+ const looksLikeHtml =
266
+ contentType?.includes('text/html') ||
267
+ /^<!doctype html/i.test(trimmed) ||
268
+ /^<html[\s>]/i.test(trimmed);
269
+ if (looksLikeHtml) {
270
+ const error = new Error('Musixmatch returned HTML instead of JSON');
271
+ error.code = 'MUSIXMATCH_HTML_RESPONSE';
272
+ error.response = {
273
+ status: response.status,
274
+ data: response.data,
275
+ headers: response.headers
276
+ };
277
+ throw error;
278
+ }
279
+ }
280
+
281
+ let payload;
282
+ try {
283
+ payload = typeof response.data === 'string' ? JSON.parse(response.data) : response.data;
284
+ } catch (parseError) {
285
+ logger.error('Failed to parse Musixmatch response as JSON', {
286
+ httpStatus: response.status,
287
+ contentType,
288
+ bodyPreview,
289
+ error: parseError
290
+ });
291
+ const error = new Error('Musixmatch returned invalid JSON');
292
+ error.code = 'MUSIXMATCH_INVALID_JSON';
293
+ error.response = {
294
+ status: response.status,
295
+ data: response.data,
296
+ headers: response.headers
297
+ };
298
+ throw error;
299
+ }
300
+
301
+ if (response.status === 401 || response.status === 403) {
302
+ const error = new Error(`Musixmatch HTTP ${response.status}`);
303
+ error.code =
304
+ response.status === 401 ? classifyUnauthorizedPayload(payload) : 'MUSIXMATCH_BLOCKED';
305
+ error.response = {
306
+ status: response.status,
307
+ data: payload,
308
+ headers: response.headers
309
+ };
310
+ throw error;
311
+ }
312
+
313
+ if (topLevel401(payload)) {
314
+ const error = new Error('Musixmatch unauthorized response');
315
+ error.code = classifyUnauthorizedPayload(payload);
316
+ error.response = {
317
+ status: 401,
318
+ data: payload,
319
+ headers: response.headers
320
+ };
321
+ throw error;
322
+ }
323
+ return payload?.message?.body?.macro_calls || payload?.message?.body || {};
117
324
  };
118
325
 
119
326
  try {
120
- return await attempt(token);
327
+ return await attempt(token, desktopCookie);
121
328
  } catch (error) {
122
329
  if (error.response?.status === 401 || error.response?.status === 403) {
123
- logger.warn('Musixmatch token rejected, invalidating', { status: error.response.status });
330
+ logger.warn('Musixmatch token rejected, invalidating', {
331
+ status: error.response.status,
332
+ desktopCookiePresent: Boolean(desktopCookie),
333
+ errorCode: error.code
334
+ });
124
335
  invalidateMusixmatchToken();
125
336
  token = await getMusixmatchToken();
337
+ desktopCookie = await getMusixmatchDesktopCookie();
126
338
  if (token) {
127
339
  try {
128
- return await attempt(token);
340
+ return await attempt(token, desktopCookie);
129
341
  } catch (retryError) {
130
342
  logger.error('Musixmatch retry failed', { error: retryError });
131
343
  }
@@ -154,6 +366,29 @@ export async function fetchFromMusixmatch(track) {
154
366
  const record = normalizeBody(body);
155
367
  return record;
156
368
  } catch (error) {
369
+ if (error.code === 'MUSIXMATCH_CAPTCHA' || error.code === 'MUSIXMATCH_HTML_RESPONSE') {
370
+ logger.warn('Musixmatch blocked by captcha challenge', {
371
+ trackTitle: track?.title || null,
372
+ trackArtist: track?.artist || null,
373
+ httpStatus: error.response?.status ?? null,
374
+ contentType: error.response?.headers?.['content-type'] ?? null
375
+ });
376
+ return buildBlockedRecord(track, error.response?.data, 'captcha');
377
+ }
378
+ if (
379
+ error.code === 'MUSIXMATCH_BLOCKED' ||
380
+ error.code === 'MUSIXMATCH_INVALID_JSON' ||
381
+ error.code === 'MUSIXMATCH_TOKEN_RENEW'
382
+ ) {
383
+ logger.warn('Musixmatch returned blocked or invalid response', {
384
+ trackTitle: track?.title || null,
385
+ trackArtist: track?.artist || null,
386
+ httpStatus: error.response?.status ?? null,
387
+ contentType: error.response?.headers?.['content-type'] ?? null,
388
+ errorCode: error.code
389
+ });
390
+ return buildBlockedRecord(track, error.response?.data, 'blocked');
391
+ }
157
392
  logger.error('Musixmatch request failed', { error });
158
393
  return null;
159
394
  }
@@ -166,5 +401,10 @@ export async function searchMusixmatch(track) {
166
401
 
167
402
  export async function checkMusixmatchTokenReady() {
168
403
  const token = await getMusixmatchToken();
404
+ const desktopCookie = await getMusixmatchDesktopCookie();
405
+ logger.debug('Musixmatch credential readiness checked', {
406
+ tokenPresent: Boolean(token),
407
+ desktopCookiePresent: Boolean(desktopCookie)
408
+ });
169
409
  return Boolean(token);
170
410
  }
@@ -7,13 +7,35 @@ import '../utils/config.js';
7
7
  import { describeKvBackend, isKvConfigured, kvSet } from '../utils/kv-store.js';
8
8
 
9
9
  const AUTH_URL = 'https://auth.musixmatch.com/';
10
+ const ACCOUNT_URL = 'https://account.musixmatch.com';
10
11
 
11
- async function saveToken(token, desktopCookie) {
12
+ async function waitForDesktopCookie(context, { attempts = 10, delayMs = 500 } = {}) {
13
+ let latestCookies = [];
14
+
15
+ for (let attempt = 1; attempt <= attempts; attempt += 1) {
16
+ latestCookies = await context.cookies(ACCOUNT_URL);
17
+ const desktopCookie = latestCookies.find((cookie) => cookie.name === 'web-desktop-app-v1.0');
18
+ if (desktopCookie) {
19
+ return { desktopCookie, cookies: latestCookies, attempts: attempt };
20
+ }
21
+
22
+ if (attempt < attempts) {
23
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
24
+ }
25
+ }
26
+
27
+ return { desktopCookie: null, cookies: latestCookies, attempts };
28
+ }
29
+
30
+ async function saveToken(token, desktopCookie, tokenPayload) {
12
31
  // Uses the same env var as the server runtime so both read/write the same path.
13
32
  const cachePath =
14
33
  process.env.MUSIXMATCH_TOKEN_CACHE || path.resolve('.cache', 'musixmatch-token.json');
15
34
  await mkdir(path.dirname(cachePath), { recursive: true });
16
35
  const payload = { token };
36
+ if (tokenPayload && typeof tokenPayload === 'object') {
37
+ payload.tokenPayload = tokenPayload;
38
+ }
17
39
  if (desktopCookie) {
18
40
  payload.desktopCookie = desktopCookie;
19
41
  }
@@ -22,11 +44,15 @@ async function saveToken(token, desktopCookie) {
22
44
  console.log('(Local and persistent servers read this file on startup.)');
23
45
  }
24
46
 
25
- async function saveToKv(token, desktopCookie) {
47
+ async function saveToKv(token, desktopCookie, tokenPayload) {
26
48
  if (!isKvConfigured()) return;
27
49
  const kvKey = process.env.MUSIXMATCH_TOKEN_KV_KEY || 'mr-magic:musixmatch-token';
28
50
  const kvTtl = parseInt(process.env.MUSIXMATCH_TOKEN_KV_TTL_SECONDS || '2592000', 10);
29
- const payload = JSON.stringify({ token, ...(desktopCookie ? { desktopCookie } : {}) });
51
+ const payload = JSON.stringify({
52
+ token,
53
+ ...(tokenPayload && typeof tokenPayload === 'object' ? { tokenPayload } : {}),
54
+ ...(desktopCookie ? { desktopCookie } : {})
55
+ });
30
56
  try {
31
57
  await kvSet(kvKey, payload, kvTtl);
32
58
  console.log(`Token written to KV store (${describeKvBackend()}) under key: ${kvKey}`);
@@ -35,11 +61,7 @@ async function saveToKv(token, desktopCookie) {
35
61
  }
36
62
  }
37
63
 
38
- function printDeploymentBlock(tokenValue) {
39
- const tokenString =
40
- typeof tokenValue === 'string'
41
- ? tokenValue
42
- : (tokenValue?.message?.body?.usertoken ?? JSON.stringify(tokenValue));
64
+ function printDeploymentBlock(tokenString) {
43
65
  const kvBackend = isKvConfigured() ? describeKvBackend() : null;
44
66
 
45
67
  console.log('\n' + '─'.repeat(68));
@@ -47,6 +69,7 @@ function printDeploymentBlock(tokenValue) {
47
69
 
48
70
  console.log('LOCAL & PERSISTENT SERVERS (cache token)');
49
71
  console.log(' Token written to .cache/musixmatch-token.json (or MUSIXMATCH_TOKEN_CACHE).');
72
+ console.log(' When available, the desktop cookie is written alongside the token.');
50
73
  console.log(' Any server with a writable, persistent filesystem (local dev, VPS,');
51
74
  console.log(' dedicated host) reads it automatically on startup.');
52
75
  console.log(' Re-run this script only when your token expires.\n');
@@ -78,6 +101,29 @@ function isHeadlessEnabled() {
78
101
  return value === '1' || value === 'true' || value === 'yes';
79
102
  }
80
103
 
104
+ function resolveTokenFromPayload(payload) {
105
+ if (!payload || typeof payload !== 'object') {
106
+ return null;
107
+ }
108
+
109
+ if (
110
+ typeof payload?.message?.body?.usertoken === 'string' &&
111
+ payload.message.body.usertoken.trim()
112
+ ) {
113
+ return payload.message.body.usertoken;
114
+ }
115
+
116
+ if (typeof payload?.tokens?.['web-desktop-app-v1.0'] === 'string') {
117
+ return payload.tokens['web-desktop-app-v1.0'].trim() || null;
118
+ }
119
+
120
+ if (typeof payload?.tokens?.['mxm-com-v1.0'] === 'string') {
121
+ return payload.tokens['mxm-com-v1.0'].trim() || null;
122
+ }
123
+
124
+ return null;
125
+ }
126
+
81
127
  async function main() {
82
128
  const headless = isHeadlessEnabled();
83
129
 
@@ -189,11 +235,17 @@ async function main() {
189
235
  // ERR_ABORTED on browsers like Comet that intercept or redirect during initial navigation.
190
236
  await page.goto(AUTH_URL, { waitUntil: 'commit' });
191
237
  console.log('Waiting to be redirected to https://account.musixmatch.com/ ...');
192
- await page.waitForURL('https://account.musixmatch.com/**', { timeout: 0 });
238
+ await page.waitForURL(`${ACCOUNT_URL}/**`, { timeout: 0 });
239
+ await page.waitForLoadState('domcontentloaded');
240
+ try {
241
+ await page.waitForLoadState('networkidle', { timeout: 5000 });
242
+ } catch {
243
+ // Best-effort stabilization: some pages keep background connections open.
244
+ }
193
245
 
194
- const cookies = await context.cookies('https://account.musixmatch.com');
246
+ const { desktopCookie, cookies, attempts } = await waitForDesktopCookie(context);
247
+ console.log(`Checked account.musixmatch.com cookies ${attempts} time(s) after login.`);
195
248
  const userCookie = cookies.find((cookie) => cookie.name === 'musixmatchUserToken');
196
- const desktopCookie = cookies.find((cookie) => cookie.name === 'web-desktop-app-v1.0');
197
249
  if (!userCookie) {
198
250
  console.error('musixmatchUserToken cookie not found; ensure you completed login.');
199
251
  process.exit(1);
@@ -210,18 +262,25 @@ async function main() {
210
262
  console.log('\nMusixmatch token payload:');
211
263
  console.log(JSON.stringify(parsed, null, 2));
212
264
 
265
+ const resolvedToken = resolveTokenFromPayload(parsed);
266
+ if (typeof resolvedToken !== 'string' || !resolvedToken.trim()) {
267
+ console.error('Unable to extract raw usertoken string from musixmatchUserToken payload.');
268
+ process.exit(1);
269
+ }
270
+
213
271
  const decodedDesktopCookie = desktopCookie ? decodeURIComponent(desktopCookie.value) : null;
272
+ console.log(`Desktop cookie captured: ${decodedDesktopCookie ? 'yes' : 'no'}`);
214
273
 
215
274
  // Write to all configured storage backends in parallel.
216
275
  await Promise.allSettled([
217
- saveToken(parsed, decodedDesktopCookie),
218
- saveToKv(parsed, decodedDesktopCookie)
276
+ saveToken(resolvedToken, decodedDesktopCookie, parsed),
277
+ saveToKv(resolvedToken, decodedDesktopCookie, parsed)
219
278
  ]);
220
279
 
221
280
  // Extract the raw token string for the deployment hint.
222
281
  // The parsed payload is the full musixmatchUserToken JSON object; the server
223
282
  // stores and reads the entire parsed object as the `token` field.
224
- printDeploymentBlock(parsed);
283
+ printDeploymentBlock(resolvedToken);
225
284
 
226
285
  await context.close();
227
286
  }
@@ -95,6 +95,10 @@ export async function buildCatalogPayload(track, actionOptions = {}) {
95
95
  return buildCatalogResponse(result, track, actionOptions);
96
96
  }
97
97
 
98
+ export async function buildCatalogPayloadFromResult(best, requestedTrack = {}, actionOptions = {}) {
99
+ return buildCatalogResponse({ best }, requestedTrack, actionOptions);
100
+ }
101
+
98
102
  export async function exportBestResult(result, context) {
99
103
  if (!context.shouldExport || !result?.best) return null;
100
104
  return exportLyrics(result.best, {
@@ -1,7 +1,11 @@
1
1
  import assert from 'node:assert/strict';
2
2
 
3
- import { mcpToolDefinitions, handleMcpTool } from '../src/transport/mcp-tools.js';
4
- import { buildMcpResponse } from '../src/transport/mcp-response.js';
3
+ import {
4
+ mcpToolDefinitions,
5
+ handleMcpTool,
6
+ buildResolvedReferenceResult
7
+ } from '../transport/mcp-tools.js';
8
+ import { buildMcpResponse } from '../transport/mcp-response.js';
5
9
 
6
10
  const sampleTrack = {
7
11
  title: 'Kill This Love',
@@ -60,6 +64,150 @@ async function testSearchProviderReturnsArray() {
60
64
  track: sampleTrack
61
65
  });
62
66
  assert.ok(Array.isArray(results));
67
+ const firstResult = results[0];
68
+ if (firstResult) {
69
+ assert.ok(!Object.prototype.hasOwnProperty.call(firstResult, 'plainLyrics'));
70
+ assert.ok(!Object.prototype.hasOwnProperty.call(firstResult, 'syncedLyrics'));
71
+ assert.ok(!Object.prototype.hasOwnProperty.call(firstResult, 'rawRecord'));
72
+ assert.equal(firstResult.reference?.provider, 'lrclib');
73
+ }
74
+ }
75
+
76
+ async function testSearchLyricsReturnsPreviewOnlyGroups() {
77
+ const groups = await handleMcpTool('search_lyrics', { track: sampleTrack });
78
+ assert.ok(Array.isArray(groups), 'search_lyrics should return provider groups');
79
+ const firstGroup = groups.find(
80
+ (group) => Array.isArray(group.results) && group.results.length > 0
81
+ );
82
+ if (firstGroup) {
83
+ const firstResult = firstGroup.results[0];
84
+ assert.ok(firstResult.reference?.provider, 'preview result should include provider reference');
85
+ assert.ok(!Object.prototype.hasOwnProperty.call(firstResult, 'plainLyrics'));
86
+ assert.ok(!Object.prototype.hasOwnProperty.call(firstResult, 'syncedLyrics'));
87
+ assert.ok(!Object.prototype.hasOwnProperty.call(firstResult, 'rawRecord'));
88
+ }
89
+ }
90
+
91
+ async function testSelectMatchAcceptsGroupedSearchResults() {
92
+ const response = await handleMcpTool('select_match', {
93
+ items: [
94
+ {
95
+ provider: 'melon',
96
+ results: [
97
+ {
98
+ provider: 'melon',
99
+ providerId: '38914304',
100
+ title: 'Summer Nights',
101
+ artist: 'St. Lucia',
102
+ synced: false,
103
+ reference: { provider: 'melon', providerId: '38914304', ids: { songId: '38914304' } }
104
+ }
105
+ ]
106
+ },
107
+ {
108
+ provider: 'lrclib',
109
+ results: [
110
+ {
111
+ provider: 'lrclib',
112
+ providerId: '25265938',
113
+ title: 'Summer Nights',
114
+ artist: 'St. Lucia',
115
+ synced: true,
116
+ reference: { provider: 'lrclib', providerId: '25265938', ids: { trackId: '25265938' } }
117
+ }
118
+ ]
119
+ }
120
+ ],
121
+ criteria: { provider: 'lrclib', requireSynced: true }
122
+ });
123
+ assert.equal(response?.result?.providerId, '25265938');
124
+ }
125
+
126
+ async function testFindLyricsAcceptsSelectedMatch() {
127
+ const results = await handleMcpTool('search_provider', {
128
+ provider: 'lrclib',
129
+ track: sampleTrack
130
+ });
131
+ const selected = results[0];
132
+ if (!selected) {
133
+ return;
134
+ }
135
+ const response = await handleMcpTool('find_lyrics', { match: selected });
136
+ assert.ok(response?.best, 'find_lyrics should resolve a selected search result');
137
+ assert.equal(response.best.providerId, selected.providerId);
138
+ }
139
+
140
+ async function testFindLyricsAcceptsReferenceOnlySelection() {
141
+ const results = await handleMcpTool('search_provider', {
142
+ provider: 'lrclib',
143
+ track: sampleTrack
144
+ });
145
+ const selected = results[0];
146
+ if (!selected?.reference) {
147
+ return;
148
+ }
149
+
150
+ const response = await handleMcpTool('find_lyrics', { reference: selected.reference });
151
+ assert.ok(response?.best, 'find_lyrics should resolve a bare provider reference');
152
+ assert.equal(response.best.providerId, selected.providerId);
153
+ }
154
+
155
+ async function testBuildCatalogPayloadAcceptsReferenceOnlySelection() {
156
+ const results = await handleMcpTool('search_provider', {
157
+ provider: 'lrclib',
158
+ track: sampleTrack
159
+ });
160
+ const selected = results[0];
161
+ if (!selected?.reference) {
162
+ return;
163
+ }
164
+
165
+ const response = await handleMcpTool('build_catalog_payload', {
166
+ reference: selected.reference,
167
+ options: { preferRomanized: false }
168
+ });
169
+ assert.ok(response?.provider, 'catalog payload should resolve from a bare provider reference');
170
+ assert.equal(response.providerId, selected.providerId);
171
+ }
172
+
173
+ async function testResolvedMelonReferenceWithoutLyricsIsRejected() {
174
+ const resolved = {
175
+ provider: 'melon',
176
+ providerId: '38914304',
177
+ title: 'Summer Nights',
178
+ artist: 'St. Lucia',
179
+ plainLyrics: null,
180
+ syncedLyrics: null,
181
+ synced: false
182
+ };
183
+
184
+ const result = buildResolvedReferenceResult(resolved);
185
+ assert.equal(result.best, null, 'empty Melon reference hydration should not become best');
186
+ assert.deepEqual(
187
+ result.matches,
188
+ [],
189
+ 'empty Melon reference hydration should not produce matches'
190
+ );
191
+ }
192
+
193
+ async function testResolvedGeniusReferenceWithoutLyricsIsRejected() {
194
+ const resolved = {
195
+ provider: 'genius',
196
+ providerId: '12345',
197
+ title: 'Song',
198
+ artist: 'Artist',
199
+ plainLyrics: ' ',
200
+ syncedLyrics: null,
201
+ synced: false
202
+ };
203
+
204
+ const result = buildResolvedReferenceResult(resolved);
205
+ assert.equal(result.best, null, 'empty Genius reference hydration should not become best');
206
+ assert.deepEqual(
207
+ result.matches,
208
+ [],
209
+ 'empty Genius reference hydration should not produce matches'
210
+ );
63
211
  }
64
212
 
65
213
  async function testFormatLyricsShape() {
@@ -233,6 +381,13 @@ async function run() {
233
381
  await testFindSyncedLyricsTool();
234
382
  await testSearchProviderRequiresProvider();
235
383
  await testSearchProviderReturnsArray();
384
+ await testSearchLyricsReturnsPreviewOnlyGroups();
385
+ await testSelectMatchAcceptsGroupedSearchResults();
386
+ await testFindLyricsAcceptsSelectedMatch();
387
+ await testFindLyricsAcceptsReferenceOnlySelection();
388
+ await testBuildCatalogPayloadAcceptsReferenceOnlySelection();
389
+ await testResolvedMelonReferenceWithoutLyricsIsRejected();
390
+ await testResolvedGeniusReferenceWithoutLyricsIsRejected();
236
391
  await testFormatLyricsShape();
237
392
  await testBuildCatalogPayload();
238
393
  await testBuildCatalogPayloadWithLyricsPayload();