@jamiew/soundcloud-mcp 0.0.0-stage → 1.2.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/build/tools.js ADDED
@@ -0,0 +1,682 @@
1
+ import { ResourceNotFoundError, ResourceTemplate, } from "@modelcontextprotocol/server";
2
+ import { z } from "zod";
3
+ import { RateLimitedError, SoundCloudApiError, SoundCloudAuthError, } from "./client.js";
4
+ import { CompactPlaylist, CompactPlaylistSummary, CompactTrack, CompactUser, } from "./types.js";
5
+ // Every tool calls the external SoundCloud API.
6
+ const READ = { readOnlyHint: true, openWorldHint: true };
7
+ const WRITE = { readOnlyHint: false, destructiveHint: false, openWorldHint: true };
8
+ const DESTRUCTIVE = {
9
+ readOnlyHint: false,
10
+ destructiveHint: true,
11
+ idempotentHint: true,
12
+ openWorldHint: true,
13
+ };
14
+ // Describe only the page envelope. looseObject accepts new SoundCloud fields.
15
+ // next_page has no output schema because some endpoints return bare arrays.
16
+ const PAGE_OUT = z.looseObject({
17
+ collection: z.array(z.unknown()).describe("Page items"),
18
+ next_href: z.string().nullish().describe("Next page URL; pass to next_page"),
19
+ });
20
+ const LIST_OUT = z.looseObject({ items: z.array(z.unknown()) });
21
+ /** Accepts either a numeric id or a `soundcloud:…` URN. */
22
+ const id = z.union([z.string(), z.number()]);
23
+ const limit = z.number().int().min(1).max(200).default(50);
24
+ const trackSort = z.enum(["asc", "desc"]).optional();
25
+ const libraryKind = z.enum(["tracks", "playlists"]).default("tracks");
26
+ const likeKind = z.enum(["tracks", "playlists", "stations"]).default("tracks");
27
+ const verbose = z
28
+ .boolean()
29
+ .default(false)
30
+ .describe("Return every field SoundCloud sends, such as descriptions, not the compact summary");
31
+ // The text block mirrors structuredContent for clients that read only text.
32
+ // Compact JSON keeps it cheap in model context.
33
+ function ok(data, extra = []) {
34
+ const text = typeof data === "string" ? data : JSON.stringify(data);
35
+ const result = { content: [{ type: "text", text }, ...extra] };
36
+ if (data && typeof data === "object") {
37
+ result.structuredContent = Array.isArray(data)
38
+ ? { items: data }
39
+ : data;
40
+ }
41
+ return result;
42
+ }
43
+ // The URN's second part names the entity, e.g. soundcloud:tracks:123. A
44
+ // playlist read on its own keeps its tracklist; one inside a list keeps only
45
+ // track_count, since a page of playlists would otherwise repeat every track.
46
+ const COMPACT = {
47
+ tracks: [CompactTrack, CompactTrack],
48
+ users: [CompactUser, CompactUser],
49
+ playlists: [CompactPlaylist, CompactPlaylistSummary],
50
+ "system-playlists": [CompactPlaylist, CompactPlaylistSummary],
51
+ };
52
+ /**
53
+ * Trims every track, user and playlist in a result, at any depth, to the
54
+ * fields in types.ts. Anything else, such as page envelopes, feed wrappers and
55
+ * comments, keeps its own fields.
56
+ */
57
+ export function compact(value, top = true) {
58
+ if (Array.isArray(value))
59
+ return value.map((item) => compact(item, false));
60
+ if (typeof value !== "object" || value === null)
61
+ return value;
62
+ const kind = "urn" in value && typeof value.urn === "string" ? value.urn.split(":")[1] : "";
63
+ const schema = kind ? COMPACT[kind]?.[top ? 0 : 1] : undefined;
64
+ const parsed = schema?.safeParse(value);
65
+ if (parsed?.success)
66
+ return parsed.data;
67
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, compact(item, false)]));
68
+ }
69
+ // Keep API errors short and actionable.
70
+ function errorMessage(error) {
71
+ if (error instanceof SoundCloudAuthError || error instanceof RateLimitedError) {
72
+ return error.message;
73
+ }
74
+ if (error instanceof SoundCloudApiError) {
75
+ if (error.status === 404)
76
+ return "Resource not found on SoundCloud. Check the id or URN.";
77
+ if (error.status === 403) {
78
+ return "SoundCloud refused this action. The track or playlist may be private, or the creator disabled it.";
79
+ }
80
+ if (error.status === 405) {
81
+ return "SoundCloud no longer offers this endpoint to third-party apps.";
82
+ }
83
+ return error.message;
84
+ }
85
+ return "SoundCloud request failed. Try again or reconnect.";
86
+ }
87
+ /**
88
+ * Runs a tool handler, turning results into MCP content and errors into clean
89
+ * text. Results are compact unless `verbose`; `links` sees the full data.
90
+ */
91
+ export async function run(fn, { links, verbose = false } = {}) {
92
+ try {
93
+ const data = await fn();
94
+ return ok(verbose ? data : compact(data), links?.(data) ?? []);
95
+ }
96
+ catch (error) {
97
+ return { content: [{ type: "text", text: errorMessage(error) }], isError: true };
98
+ }
99
+ }
100
+ // Resources and prompts have no error result. Their failures become protocol
101
+ // errors, which pass the message to the client, so map it first.
102
+ async function orThrow(fn) {
103
+ try {
104
+ return await fn();
105
+ }
106
+ catch (error) {
107
+ throw new Error(errorMessage(error));
108
+ }
109
+ }
110
+ function trackLinks(track) {
111
+ const links = [];
112
+ const name = track.title ?? "track";
113
+ if (track.permalink_url) {
114
+ links.push({
115
+ type: "resource_link",
116
+ uri: track.permalink_url,
117
+ name,
118
+ mimeType: "text/html",
119
+ ...(track.user?.username ? { description: `by ${track.user.username}` } : {}),
120
+ });
121
+ }
122
+ if (track.artwork_url) {
123
+ links.push({
124
+ type: "resource_link",
125
+ uri: track.artwork_url,
126
+ name: `${name} — artwork`,
127
+ mimeType: "image/jpeg",
128
+ });
129
+ }
130
+ return links;
131
+ }
132
+ function playlistLinks(playlist) {
133
+ if (!playlist.permalink_url)
134
+ return [];
135
+ return [
136
+ {
137
+ type: "resource_link",
138
+ uri: playlist.permalink_url,
139
+ name: playlist.title ?? "playlist",
140
+ mimeType: "text/html",
141
+ },
142
+ ];
143
+ }
144
+ function webProfileLinks(profiles) {
145
+ return profiles.flatMap((profile) => profile.url
146
+ ? [
147
+ {
148
+ type: "resource_link",
149
+ uri: profile.url,
150
+ name: profile.title || profile.service || profile.url,
151
+ mimeType: "text/html",
152
+ },
153
+ ]
154
+ : []);
155
+ }
156
+ // Full-length streams are HLS only; the MP3 preview is a snippet, so it comes
157
+ // last. All URLs are time-limited by SoundCloud.
158
+ function streamLinks(streams) {
159
+ const hls = streams.hls_mp3_128_url ?? streams.hls_aac_160_url;
160
+ if (hls) {
161
+ return [
162
+ {
163
+ type: "resource_link",
164
+ uri: hls,
165
+ name: "audio stream",
166
+ mimeType: "application/vnd.apple.mpegurl",
167
+ },
168
+ ];
169
+ }
170
+ const preview = streams.preview_mp3_128_url;
171
+ if (!preview)
172
+ return [];
173
+ return [{ type: "resource_link", uri: preview, name: "audio preview", mimeType: "audio/mpeg" }];
174
+ }
175
+ /** `writes: false` leaves out every tool that changes the user's account. */
176
+ export function registerTools(server, sc, { writes = true } = {}) {
177
+ const api = (ctx) => sc.withSignal(ctx.mcpReq.signal);
178
+ // --- Discovery ---
179
+ server.registerTool("search_tracks", {
180
+ title: "Search tracks",
181
+ description: "Search SoundCloud tracks by keyword, with optional genre/tag/BPM filters.",
182
+ inputSchema: z.object({
183
+ query: z.string().min(1),
184
+ limit,
185
+ genres: z.array(z.string()).optional().describe("e.g. ['Electronic','House']"),
186
+ tags: z.array(z.string()).optional(),
187
+ bpmFrom: z.number().optional(),
188
+ bpmTo: z.number().optional(),
189
+ durationFrom: z.number().optional().describe("Milliseconds"),
190
+ durationTo: z.number().optional().describe("Milliseconds"),
191
+ access: z.array(z.enum(["playable", "preview", "blocked"])).optional(),
192
+ verbose,
193
+ }),
194
+ outputSchema: PAGE_OUT,
195
+ annotations: { title: "Search tracks", ...READ },
196
+ }, async ({ query, limit: max, genres, tags, bpmFrom, bpmTo, durationFrom, durationTo, access, verbose, }, ctx) => run(() => api(ctx).searchTracks({
197
+ q: query,
198
+ limit: max,
199
+ ...(genres?.length ? { genres: genres.join(",") } : {}),
200
+ ...(tags?.length ? { tags: tags.join(",") } : {}),
201
+ ...(bpmFrom !== undefined ? { "bpm[from]": bpmFrom } : {}),
202
+ ...(bpmTo !== undefined ? { "bpm[to]": bpmTo } : {}),
203
+ ...(durationFrom !== undefined ? { "duration[from]": durationFrom } : {}),
204
+ ...(durationTo !== undefined ? { "duration[to]": durationTo } : {}),
205
+ ...(access?.length ? { access: access.join(",") } : {}),
206
+ }), { verbose }));
207
+ server.registerTool("search_playlists", {
208
+ title: "Search playlists",
209
+ description: "Search SoundCloud playlists by keyword.",
210
+ inputSchema: z.object({ query: z.string().min(1), limit, verbose }),
211
+ outputSchema: PAGE_OUT,
212
+ annotations: { title: "Search playlists", ...READ },
213
+ }, async ({ query, limit: max, verbose }, ctx) => run(() => api(ctx).searchPlaylists(query, max), { verbose }));
214
+ server.registerTool("search_users", {
215
+ title: "Search users",
216
+ description: "Search SoundCloud users/artists by keyword.",
217
+ inputSchema: z.object({ query: z.string().min(1), limit, verbose }),
218
+ outputSchema: PAGE_OUT,
219
+ annotations: { title: "Search users", ...READ },
220
+ }, async ({ query, limit: max, verbose }, ctx) => run(() => api(ctx).searchUsers(query, max), { verbose }));
221
+ server.registerTool("resolve_url", {
222
+ title: "Resolve a SoundCloud URL",
223
+ description: "Resolve a soundcloud.com or on.soundcloud.com link to a track, user, playlist, or station. Use for pasted SoundCloud links; pass station URNs to get_station.",
224
+ inputSchema: z.object({ url: z.string().url(), verbose }),
225
+ annotations: { title: "Resolve a SoundCloud URL", ...READ },
226
+ }, async ({ url, verbose }, ctx) => run(() => api(ctx).resolve(url), { verbose }));
227
+ server.registerTool("get_track", {
228
+ title: "Get track",
229
+ description: "Get details for one track.",
230
+ inputSchema: z.object({ trackId: id, verbose }),
231
+ annotations: { title: "Get track", ...READ },
232
+ }, async ({ trackId, verbose }, ctx) => run(() => api(ctx).getTrack(trackId), { links: trackLinks, verbose }));
233
+ server.registerTool("get_user", {
234
+ title: "Get user",
235
+ description: "Get a user's public profile.",
236
+ inputSchema: z.object({ userId: id, verbose }),
237
+ annotations: { title: "Get user", ...READ },
238
+ }, async ({ userId, verbose }, ctx) => run(() => api(ctx).getUser(userId), { verbose }));
239
+ server.registerTool("get_user_tracks", {
240
+ title: "Get an artist's tracks",
241
+ description: "List a user's uploads. Find ids with search_users. Sort: asc for oldest first, desc for newest.",
242
+ inputSchema: z.object({ userId: id, limit, sort: trackSort, verbose }),
243
+ outputSchema: PAGE_OUT,
244
+ annotations: { title: "Get an artist's tracks", ...READ },
245
+ }, async ({ userId, limit: max, sort, verbose }, ctx) => run(() => api(ctx).getUserTracks(userId, max, sort), { verbose }));
246
+ server.registerTool("get_user_playlists", {
247
+ title: "Get an artist's playlists",
248
+ description: "List the playlists a user has published.",
249
+ inputSchema: z.object({ userId: id, limit, verbose }),
250
+ outputSchema: PAGE_OUT,
251
+ annotations: { title: "Get an artist's playlists", ...READ },
252
+ }, async ({ userId, limit: max, verbose }, ctx) => run(() => api(ctx).getUserPlaylists(userId, max), { verbose }));
253
+ server.registerTool("get_user_likes", {
254
+ title: "Get an artist's likes",
255
+ description: "List tracks, playlists, or stations a user has liked.",
256
+ inputSchema: z.object({ userId: id, limit, kind: likeKind, verbose }),
257
+ outputSchema: PAGE_OUT,
258
+ annotations: { title: "Get an artist's likes", ...READ },
259
+ }, async ({ userId, limit: max, kind, verbose }, ctx) => run(() => api(ctx).getUserLikes(userId, max, kind), { verbose }));
260
+ server.registerTool("get_user_reposts", {
261
+ title: "Get an artist's reposts",
262
+ description: "List tracks or playlists a user has reposted.",
263
+ inputSchema: z.object({ userId: id, limit, kind: libraryKind, verbose }),
264
+ outputSchema: PAGE_OUT,
265
+ annotations: { title: "Get an artist's reposts", ...READ },
266
+ }, async ({ userId, limit: max, kind, verbose }, ctx) => run(() => api(ctx).getUserReposts(userId, max, kind), { verbose }));
267
+ server.registerTool("get_user_followers", {
268
+ title: "Get an artist's followers",
269
+ description: "List the users who follow a user.",
270
+ inputSchema: z.object({ userId: id, limit, verbose }),
271
+ outputSchema: PAGE_OUT,
272
+ annotations: { title: "Get an artist's followers", ...READ },
273
+ }, async ({ userId, limit: max, verbose }, ctx) => run(() => api(ctx).getUserFollowers(userId, max), { verbose }));
274
+ server.registerTool("get_user_followings", {
275
+ title: "Get who an artist follows",
276
+ description: "List the users a user follows.",
277
+ inputSchema: z.object({ userId: id, limit, verbose }),
278
+ outputSchema: PAGE_OUT,
279
+ annotations: { title: "Get who an artist follows", ...READ },
280
+ }, async ({ userId, limit: max, verbose }, ctx) => run(() => api(ctx).getUserFollowings(userId, max), { verbose }));
281
+ server.registerTool("get_user_web_profiles", {
282
+ title: "Get an artist's links",
283
+ description: "List the external links on a user's profile, such as a website or socials.",
284
+ inputSchema: z.object({ userId: id, limit }),
285
+ outputSchema: LIST_OUT,
286
+ annotations: { title: "Get an artist's links", ...READ },
287
+ }, async ({ userId, limit: max }, ctx) => run(() => api(ctx).getUserWebProfiles(userId, max), { links: webProfileLinks }));
288
+ server.registerTool("get_playlist", {
289
+ title: "Get playlist",
290
+ description: "Get a playlist's details and its tracks.",
291
+ inputSchema: z.object({ playlistId: id, verbose }),
292
+ annotations: { title: "Get playlist", ...READ },
293
+ }, async ({ playlistId, verbose }, ctx) => run(() => api(ctx).getPlaylist(playlistId), { links: playlistLinks, verbose }));
294
+ server.registerTool("get_station", {
295
+ title: "Get station",
296
+ description: "Get a station (system playlist) and its tracks. Tracks and users carry a station_urn; get_my_likes with kind=stations lists liked ones.",
297
+ inputSchema: z.object({
298
+ stationUrn: z
299
+ .string()
300
+ .min(1)
301
+ .describe("soundcloud:system-playlists:track-stations:123, or the part after soundcloud:system-playlists:"),
302
+ verbose,
303
+ }),
304
+ annotations: { title: "Get station", ...READ },
305
+ }, async ({ stationUrn, verbose }, ctx) => run(() => api(ctx).getSystemPlaylist(stationUrn), { links: playlistLinks, verbose }));
306
+ server.registerTool("get_playlist_tracks", {
307
+ title: "Get playlist tracks",
308
+ description: "List a page of playlist tracks.",
309
+ inputSchema: z.object({ playlistId: id, limit, verbose }),
310
+ outputSchema: PAGE_OUT,
311
+ annotations: { title: "Get playlist tracks", ...READ },
312
+ }, async ({ playlistId, limit: max, verbose }, ctx) => run(() => api(ctx).getPlaylistTracks(playlistId, max), { verbose }));
313
+ server.registerTool("get_playlist_reposters", {
314
+ title: "Get playlist reposters",
315
+ description: "List the users who reposted a playlist.",
316
+ inputSchema: z.object({ playlistId: id, limit, verbose }),
317
+ outputSchema: PAGE_OUT,
318
+ annotations: { title: "Get playlist reposters", ...READ },
319
+ }, async ({ playlistId, limit: max, verbose }, ctx) => run(() => api(ctx).getPlaylistReposters(playlistId, max), { verbose }));
320
+ server.registerTool("get_related_tracks", {
321
+ title: "Get related tracks",
322
+ description: "Find related tracks, starting with a track the user likes.",
323
+ inputSchema: z.object({ trackId: id, limit, verbose }),
324
+ outputSchema: LIST_OUT,
325
+ annotations: { title: "Get related tracks", ...READ },
326
+ }, async ({ trackId, limit: max, verbose }, ctx) => run(() => api(ctx).getRelatedTracks(trackId, max), { verbose }));
327
+ server.registerTool("get_related_artists", {
328
+ title: "Get related artists",
329
+ description: "Find artists related to a user.",
330
+ inputSchema: z.object({ userId: id, limit, verbose }),
331
+ outputSchema: LIST_OUT,
332
+ annotations: { title: "Get related artists", ...READ },
333
+ }, async ({ userId, limit: max, verbose }, ctx) => run(() => api(ctx).getRelatedArtists(userId, max), { verbose }));
334
+ server.registerTool("get_stream_url", {
335
+ title: "Get stream URL",
336
+ description: "Get temporary audio URLs: HLS for full tracks, MP3 for previews. Blocked tracks have no stream.",
337
+ inputSchema: z.object({ trackId: id }),
338
+ annotations: { title: "Get stream URL", ...READ },
339
+ }, async ({ trackId }, ctx) => run(() => api(ctx).getTrackStreams(trackId), { links: streamLinks }));
340
+ server.registerTool("get_comments", {
341
+ title: "Get track comments",
342
+ description: "Get comments on a track, with their timestamps into the audio.",
343
+ inputSchema: z.object({ trackId: id, limit, verbose }),
344
+ outputSchema: PAGE_OUT,
345
+ annotations: { title: "Get track comments", ...READ },
346
+ }, async ({ trackId, limit: max, verbose }, ctx) => run(() => api(ctx).getComments(trackId, max), { verbose }));
347
+ server.registerTool("get_track_likers", {
348
+ title: "Get track likers",
349
+ description: "List the users who liked a track.",
350
+ inputSchema: z.object({ trackId: id, limit, verbose }),
351
+ outputSchema: PAGE_OUT,
352
+ annotations: { title: "Get track likers", ...READ },
353
+ }, async ({ trackId, limit: max, verbose }, ctx) => run(() => api(ctx).getTrackLikers(trackId, max), { verbose }));
354
+ server.registerTool("get_track_reposters", {
355
+ title: "Get track reposters",
356
+ description: "List the users who reposted a track.",
357
+ inputSchema: z.object({ trackId: id, limit, verbose }),
358
+ outputSchema: PAGE_OUT,
359
+ annotations: { title: "Get track reposters", ...READ },
360
+ }, async ({ trackId, limit: max, verbose }, ctx) => run(() => api(ctx).getTrackReposters(trackId, max), { verbose }));
361
+ server.registerTool("next_page", {
362
+ title: "Next page",
363
+ description: "Fetch next_href with a GET to the SoundCloud API (https://developers.soundcloud.com/docs/api/guide).",
364
+ inputSchema: z.object({
365
+ nextHref: z.string().url().describe("The next_href from a previous result"),
366
+ verbose,
367
+ }),
368
+ annotations: { title: "Next page", ...READ },
369
+ }, async ({ nextHref, verbose }, ctx) => run(() => api(ctx).nextPage(nextHref), { verbose }));
370
+ // --- My library ---
371
+ server.registerTool("get_profile", {
372
+ title: "Get my profile",
373
+ description: "Get the connected user's SoundCloud profile.",
374
+ inputSchema: z.object({ verbose }),
375
+ annotations: { title: "Get my profile", ...READ },
376
+ }, async ({ verbose }, ctx) => run(() => api(ctx).getMe(), { verbose }));
377
+ server.registerTool("get_my_likes", {
378
+ title: "Get my likes",
379
+ description: "List tracks, playlists, or stations the connected user has liked.",
380
+ inputSchema: z.object({ limit, kind: likeKind, verbose }),
381
+ outputSchema: PAGE_OUT,
382
+ annotations: { title: "Get my likes", ...READ },
383
+ }, async ({ limit: max, kind, verbose }, ctx) => run(() => api(ctx).getMyLikes(max, kind), { verbose }));
384
+ server.registerTool("get_my_reposts", {
385
+ title: "Get my reposts",
386
+ description: "List tracks or playlists the connected user has reposted.",
387
+ inputSchema: z.object({ limit, kind: libraryKind, verbose }),
388
+ outputSchema: PAGE_OUT,
389
+ annotations: { title: "Get my reposts", ...READ },
390
+ }, async ({ limit: max, kind, verbose }, ctx) => run(() => api(ctx).getMyReposts(max, kind), { verbose }));
391
+ server.registerTool("get_my_playlists", {
392
+ title: "Get my playlists",
393
+ description: "List the connected user's playlists.",
394
+ inputSchema: z.object({ limit, verbose }),
395
+ outputSchema: PAGE_OUT,
396
+ annotations: { title: "Get my playlists", ...READ },
397
+ }, async ({ limit: max, verbose }, ctx) => run(() => api(ctx).getMyPlaylists(max), { verbose }));
398
+ server.registerTool("get_my_tracks", {
399
+ title: "Get my uploads",
400
+ description: "List the connected user's uploads. Sort: asc for oldest first, desc for newest.",
401
+ inputSchema: z.object({ limit, sort: trackSort, verbose }),
402
+ outputSchema: PAGE_OUT,
403
+ annotations: { title: "Get my uploads", ...READ },
404
+ }, async ({ limit: max, sort, verbose }, ctx) => run(() => api(ctx).getMyTracks(max, sort), { verbose }));
405
+ server.registerTool("get_my_followings", {
406
+ title: "Get who I follow",
407
+ description: "List the users the connected user follows.",
408
+ inputSchema: z.object({ limit, verbose }),
409
+ outputSchema: PAGE_OUT,
410
+ annotations: { title: "Get who I follow", ...READ },
411
+ }, async ({ limit: max, verbose }, ctx) => run(() => api(ctx).getMyFollowings(max), { verbose }));
412
+ server.registerTool("get_my_followers", {
413
+ title: "Get my followers",
414
+ description: "List the users who follow the connected user.",
415
+ inputSchema: z.object({ limit, verbose }),
416
+ outputSchema: PAGE_OUT,
417
+ annotations: { title: "Get my followers", ...READ },
418
+ }, async ({ limit: max, verbose }, ctx) => run(() => api(ctx).getMyFollowers(max), { verbose }));
419
+ server.registerTool("is_following", {
420
+ title: "Check if I follow a user",
421
+ description: "Check whether the connected user follows a user. Unknown users count as not followed.",
422
+ inputSchema: z.object({ userId: id }),
423
+ outputSchema: z.looseObject({ following: z.boolean() }),
424
+ annotations: { title: "Check if I follow a user", ...READ },
425
+ }, async ({ userId }, ctx) => run(async () => ({ userId, following: await api(ctx).isFollowing(userId) })));
426
+ server.registerTool("get_feed", {
427
+ title: "Get my feed",
428
+ description: "List recent activity from people the connected user follows: tracks by default, or all for playlists too.",
429
+ inputSchema: z.object({
430
+ limit,
431
+ kind: z.enum(["tracks", "all"]).default("tracks"),
432
+ verbose,
433
+ }),
434
+ outputSchema: PAGE_OUT,
435
+ annotations: { title: "Get my feed", ...READ },
436
+ }, async ({ limit: max, kind, verbose }, ctx) => run(() => api(ctx).getFeed(max, kind), { verbose }));
437
+ server.registerTool("get_recently_played", {
438
+ title: "Get recently played",
439
+ description: "Tracks the connected user played recently, most recent first.",
440
+ inputSchema: z.object({ limit, verbose }),
441
+ outputSchema: PAGE_OUT,
442
+ annotations: { title: "Get recently played", ...READ },
443
+ }, async ({ limit: max, verbose }, ctx) => run(() => api(ctx).getRecentlyPlayed(max), { verbose }));
444
+ if (writes)
445
+ registerWriteTools(server, api);
446
+ registerPrompts(server, api);
447
+ registerResources(server, api);
448
+ }
449
+ function registerWriteTools(server, api) {
450
+ // --- Social writes ---
451
+ server.registerTool("like_track", {
452
+ title: "Like track",
453
+ description: "Like a track.",
454
+ inputSchema: z.object({ trackId: id }),
455
+ annotations: { title: "Like track", ...WRITE, idempotentHint: true },
456
+ }, async ({ trackId }, ctx) => run(async () => {
457
+ await api(ctx).likeTrack(trackId);
458
+ return `Liked track ${trackId}.`;
459
+ }));
460
+ server.registerTool("unlike_track", {
461
+ title: "Unlike track",
462
+ description: "Remove a like from a track.",
463
+ inputSchema: z.object({ trackId: id }),
464
+ annotations: { title: "Unlike track", ...WRITE, idempotentHint: true },
465
+ }, async ({ trackId }, ctx) => run(async () => {
466
+ await api(ctx).unlikeTrack(trackId);
467
+ return `Unliked track ${trackId}.`;
468
+ }));
469
+ server.registerTool("repost_track", {
470
+ title: "Repost track",
471
+ description: "Repost a track to the user's followers.",
472
+ inputSchema: z.object({ trackId: id }),
473
+ annotations: { title: "Repost track", ...WRITE, idempotentHint: true },
474
+ }, async ({ trackId }, ctx) => run(async () => {
475
+ await api(ctx).repostTrack(trackId);
476
+ return `Reposted track ${trackId}.`;
477
+ }));
478
+ server.registerTool("unrepost_track", {
479
+ title: "Remove repost",
480
+ description: "Remove a repost of a track.",
481
+ inputSchema: z.object({ trackId: id }),
482
+ annotations: { title: "Remove repost", ...WRITE, idempotentHint: true },
483
+ }, async ({ trackId }, ctx) => run(async () => {
484
+ await api(ctx).unrepostTrack(trackId);
485
+ return `Removed repost of track ${trackId}.`;
486
+ }));
487
+ server.registerTool("like_playlist", {
488
+ title: "Like playlist",
489
+ description: "Like a playlist or a station.",
490
+ inputSchema: z.object({ playlistId: id }),
491
+ annotations: { title: "Like playlist", ...WRITE, idempotentHint: true },
492
+ }, async ({ playlistId }, ctx) => run(async () => {
493
+ await api(ctx).likePlaylist(playlistId);
494
+ return `Liked playlist ${playlistId}.`;
495
+ }));
496
+ server.registerTool("unlike_playlist", {
497
+ title: "Unlike playlist",
498
+ description: "Remove a like from a playlist or a station.",
499
+ inputSchema: z.object({ playlistId: id }),
500
+ annotations: { title: "Unlike playlist", ...WRITE, idempotentHint: true },
501
+ }, async ({ playlistId }, ctx) => run(async () => {
502
+ await api(ctx).unlikePlaylist(playlistId);
503
+ return `Unliked playlist ${playlistId}.`;
504
+ }));
505
+ server.registerTool("repost_playlist", {
506
+ title: "Repost playlist",
507
+ description: "Repost a playlist to the user's followers.",
508
+ inputSchema: z.object({ playlistId: id }),
509
+ annotations: { title: "Repost playlist", ...WRITE, idempotentHint: true },
510
+ }, async ({ playlistId }, ctx) => run(async () => {
511
+ await api(ctx).repostPlaylist(playlistId);
512
+ return `Reposted playlist ${playlistId}.`;
513
+ }));
514
+ server.registerTool("unrepost_playlist", {
515
+ title: "Remove playlist repost",
516
+ description: "Remove a repost of a playlist.",
517
+ inputSchema: z.object({ playlistId: id }),
518
+ annotations: { title: "Remove playlist repost", ...WRITE, idempotentHint: true },
519
+ }, async ({ playlistId }, ctx) => run(async () => {
520
+ await api(ctx).unrepostPlaylist(playlistId);
521
+ return `Removed repost of playlist ${playlistId}.`;
522
+ }));
523
+ server.registerTool("follow_user", {
524
+ title: "Follow user",
525
+ description: "Follow a user.",
526
+ inputSchema: z.object({ userId: id }),
527
+ annotations: { title: "Follow user", ...WRITE, idempotentHint: true },
528
+ }, async ({ userId }, ctx) => run(async () => {
529
+ await api(ctx).followUser(userId);
530
+ return `Followed user ${userId}.`;
531
+ }));
532
+ server.registerTool("unfollow_user", {
533
+ title: "Unfollow user",
534
+ description: "Unfollow a user.",
535
+ inputSchema: z.object({ userId: id }),
536
+ annotations: { title: "Unfollow user", ...WRITE, idempotentHint: true },
537
+ }, async ({ userId }, ctx) => run(async () => {
538
+ await api(ctx).unfollowUser(userId);
539
+ return `Unfollowed user ${userId}.`;
540
+ }));
541
+ server.registerTool("add_comment", {
542
+ title: "Add comment",
543
+ description: "Post a comment with an optional timestamp. Comments must be enabled; the API has no undo.",
544
+ inputSchema: z.object({
545
+ trackId: id,
546
+ body: z.string().min(1),
547
+ timestamp: z.number().int().min(0).optional().describe("Milliseconds into the track"),
548
+ verbose,
549
+ }),
550
+ annotations: { title: "Add comment", ...WRITE },
551
+ }, async ({ trackId, body, timestamp, verbose }, ctx) => run(() => api(ctx).addComment(trackId, body, timestamp), { verbose }));
552
+ // --- Playlist writes ---
553
+ server.registerTool("create_playlist", {
554
+ title: "Create playlist",
555
+ description: "Create a playlist with optional tracks. Private by default.",
556
+ inputSchema: z.object({
557
+ title: z.string().min(1),
558
+ description: z.string().optional(),
559
+ sharing: z.enum(["public", "private"]).default("private"),
560
+ trackIds: z.array(id).optional(),
561
+ verbose,
562
+ }),
563
+ annotations: { title: "Create playlist", ...WRITE },
564
+ }, async ({ title, description, sharing, trackIds, verbose }, ctx) => run(() => api(ctx).createPlaylist({
565
+ title,
566
+ sharing,
567
+ ...(description !== undefined ? { description } : {}),
568
+ ...(trackIds ? { trackIds } : {}),
569
+ }), { links: playlistLinks, verbose }));
570
+ server.registerTool("update_playlist", {
571
+ title: "Update playlist",
572
+ description: "Edit a playlist's title, description, or sharing. trackIds replaces and orders the entire tracklist.",
573
+ inputSchema: z.object({
574
+ playlistId: id,
575
+ title: z.string().optional(),
576
+ description: z.string().optional(),
577
+ sharing: z.enum(["public", "private"]).optional(),
578
+ trackIds: z.array(id).optional().describe("Replaces the tracklist entirely, in this order"),
579
+ verbose,
580
+ }),
581
+ annotations: { title: "Update playlist", ...DESTRUCTIVE },
582
+ }, async ({ playlistId, verbose, ...updates }, ctx) => run(() => api(ctx).updatePlaylist(playlistId, updates), { links: playlistLinks, verbose }));
583
+ server.registerTool("add_tracks_to_playlist", {
584
+ title: "Add tracks to playlist",
585
+ description: "Append tracks to an existing playlist.",
586
+ inputSchema: z.object({ playlistId: id, trackIds: z.array(id).min(1), verbose }),
587
+ annotations: { title: "Add tracks to playlist", ...WRITE },
588
+ }, async ({ playlistId, trackIds, verbose }, ctx) => run(() => api(ctx).addTracksToPlaylist(playlistId, trackIds), {
589
+ links: playlistLinks,
590
+ verbose,
591
+ }));
592
+ server.registerTool("remove_track_from_playlist", {
593
+ title: "Remove track from playlist",
594
+ description: "Remove one track from a playlist.",
595
+ inputSchema: z.object({ playlistId: id, trackId: id, verbose }),
596
+ annotations: { title: "Remove track from playlist", ...DESTRUCTIVE },
597
+ }, async ({ playlistId, trackId, verbose }, ctx) => run(() => api(ctx).removeTrackFromPlaylist(playlistId, trackId), {
598
+ links: playlistLinks,
599
+ verbose,
600
+ }));
601
+ server.registerTool("delete_playlist", {
602
+ title: "Delete playlist",
603
+ description: "Delete a playlist permanently.",
604
+ inputSchema: z.object({ playlistId: id }),
605
+ annotations: { title: "Delete playlist", ...DESTRUCTIVE },
606
+ }, async ({ playlistId }, ctx) => run(async () => {
607
+ await api(ctx).deletePlaylist(playlistId);
608
+ return `Deleted playlist ${playlistId}.`;
609
+ }));
610
+ }
611
+ // A JSON resource body with every field SoundCloud sends. Templates are not
612
+ // listable — there is no endpoint that enumerates every track — so `list` is
613
+ // undefined and clients read them by URI.
614
+ async function json(uri, load) {
615
+ try {
616
+ const text = JSON.stringify(await load());
617
+ return { contents: [{ uri: uri.href, mimeType: "application/json", text }] };
618
+ }
619
+ catch (error) {
620
+ if (error instanceof SoundCloudApiError && error.status === 404) {
621
+ throw new ResourceNotFoundError(uri.href);
622
+ }
623
+ throw new Error(errorMessage(error));
624
+ }
625
+ }
626
+ function registerResources(server, api) {
627
+ server.registerResource("track", new ResourceTemplate("soundcloud://tracks/{id}", { list: undefined }), { title: "Track", description: "A track by id or URN", mimeType: "application/json" }, async (uri, { id }, ctx) => json(uri, () => api(ctx).getTrack(String(id))));
628
+ server.registerResource("user", new ResourceTemplate("soundcloud://users/{id}", { list: undefined }), { title: "User", description: "A user profile by id or URN", mimeType: "application/json" }, async (uri, { id }, ctx) => json(uri, () => api(ctx).getUser(String(id))));
629
+ server.registerResource("playlist", new ResourceTemplate("soundcloud://playlists/{id}", { list: undefined }), { title: "Playlist", description: "A playlist by id or URN", mimeType: "application/json" }, async (uri, { id }, ctx) => json(uri, () => api(ctx).getPlaylist(String(id))));
630
+ server.registerResource("my-profile", "soundcloud://me/profile", {
631
+ title: "My profile",
632
+ description: "The connected user's profile",
633
+ mimeType: "application/json",
634
+ }, async (uri, ctx) => json(uri, () => api(ctx).getMe()));
635
+ server.registerResource("my-playlists", "soundcloud://me/playlists", {
636
+ title: "My playlists",
637
+ description: "The connected user's playlists",
638
+ mimeType: "application/json",
639
+ }, async (uri, ctx) => json(uri, () => api(ctx).getMyPlaylists(50)));
640
+ server.registerResource("my-likes", "soundcloud://me/likes", {
641
+ title: "My likes",
642
+ description: "The connected user's liked tracks",
643
+ mimeType: "application/json",
644
+ }, async (uri, ctx) => json(uri, () => api(ctx).getMyLikes(50)));
645
+ }
646
+ // Prompts embed compact JSON: a page of full tracks would crowd out the request.
647
+ function userPrompt(text) {
648
+ return { messages: [{ role: "user", content: { type: "text", text } }] };
649
+ }
650
+ function registerPrompts(server, api) {
651
+ server.registerPrompt("analyze_music_taste", {
652
+ title: "Analyze music taste",
653
+ description: "Analyze the connected user's taste from their liked tracks",
654
+ }, async (ctx) => {
655
+ const likes = await orThrow(() => api(ctx).getMyLikes(50));
656
+ return userPrompt(`Analyze my liked tracks:\n\n${JSON.stringify(compact(likes))}\n\nIdentify favorite genres, artists, and production styles.`);
657
+ });
658
+ server.registerPrompt("discover_similar_tracks", {
659
+ title: "Discover similar tracks",
660
+ description: "Find tracks similar to one you like",
661
+ argsSchema: z.object({ trackId: z.string() }),
662
+ }, async ({ trackId }, ctx) => {
663
+ const [track, related] = await orThrow(() => Promise.all([api(ctx).getTrack(trackId), api(ctx).getRelatedTracks(trackId, 20)]));
664
+ return userPrompt(`A track I like:\n\n${JSON.stringify(compact(track))}\n\nRelated tracks:\n\n${JSON.stringify(compact(related))}\n\nExplain what they share and recommend three.`);
665
+ });
666
+ server.registerPrompt("discover_new_music", {
667
+ title: "Discover new music",
668
+ description: "Find music based on your likes, genres, and mood",
669
+ argsSchema: z.object({ genres: z.string().optional(), mood: z.string().optional() }),
670
+ }, async ({ genres, mood }, ctx) => {
671
+ const seed = genres?.split(",")[0]?.trim();
672
+ const [likes, search] = await orThrow(() => Promise.all([
673
+ api(ctx).getMyLikes(20),
674
+ seed ? api(ctx).searchTracks({ q: seed, limit: 20 }) : Promise.resolve(undefined),
675
+ ]));
676
+ const want = `${genres ? ` in these genres: ${genres}` : ""}${mood ? ` with a ${mood} mood` : ""}`;
677
+ const results = search
678
+ ? `\n\nSearch results for "${seed}":\n${JSON.stringify(compact(search))}`
679
+ : "";
680
+ return userPrompt(`Recommend new music${want}.\n\nMy likes:\n${JSON.stringify(compact(likes))}${results}\n\nSuggest tracks, artists, or genres and explain why.`);
681
+ });
682
+ }