@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/LICENSE +21 -0
- package/README.md +242 -2
- package/build/client.js +428 -0
- package/build/icon.js +22 -0
- package/build/index.js +26 -0
- package/build/server.js +25 -0
- package/build/stdio/auth.js +28 -0
- package/build/stdio/authTools.js +41 -0
- package/build/stdio/config.js +10 -0
- package/build/stdio/log.js +10 -0
- package/build/stdio/oauth.js +244 -0
- package/build/stdio/tokenStore.js +38 -0
- package/build/tools.js +682 -0
- package/build/types.js +138 -0
- package/package.json +70 -5
package/build/client.js
ADDED
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
// Shared API client: token refresh, URN normalization, and cursor pagination.
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { CommentSchema, FeedItemSchema, PlaylistSchema, pageOf, TrackSchema, TrackStreamsSchema, UserSchema, WebProfileSchema, } from "./types.js";
|
|
4
|
+
export const API_BASE = "https://api.soundcloud.com";
|
|
5
|
+
/** OAuth `/authorize` and `/oauth/token` live here, not on the API host. */
|
|
6
|
+
export const AUTH_BASE = "https://secure.soundcloud.com";
|
|
7
|
+
export class SoundCloudApiError extends Error {
|
|
8
|
+
status;
|
|
9
|
+
constructor(message, status) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.status = status;
|
|
12
|
+
this.name = "SoundCloudApiError";
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
/** Authorization is gone for good, e.g. a refresh failed or a second 401. */
|
|
16
|
+
export class SoundCloudAuthError extends Error {
|
|
17
|
+
constructor(message = "SoundCloud authorization has lapsed. Reconnect this MCP server to SoundCloud.") {
|
|
18
|
+
super(message);
|
|
19
|
+
this.name = "SoundCloudAuthError";
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
export class RateLimitedError extends Error {
|
|
23
|
+
constructor(retryAfterSeconds) {
|
|
24
|
+
super(retryAfterSeconds === undefined
|
|
25
|
+
? "SoundCloud is rate limiting right now. Wait a moment and try again."
|
|
26
|
+
: `SoundCloud is rate limiting right now. Try again in ${retryAfterSeconds} seconds.`);
|
|
27
|
+
this.name = "RateLimitedError";
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/** Reads Retry-After as delay seconds or an HTTP date. */
|
|
31
|
+
function retryAfterSeconds(header, now = Date.now()) {
|
|
32
|
+
if (!header)
|
|
33
|
+
return undefined;
|
|
34
|
+
const value = header.trim();
|
|
35
|
+
if (/^\d+$/.test(value))
|
|
36
|
+
return Number(value);
|
|
37
|
+
const date = Date.parse(value);
|
|
38
|
+
if (Number.isNaN(date))
|
|
39
|
+
return undefined;
|
|
40
|
+
return Math.max(0, Math.ceil((date - now) / 1000));
|
|
41
|
+
}
|
|
42
|
+
/** Upper bound for one API call, including token lookups and a retry after a refresh. */
|
|
43
|
+
export const REQUEST_TIMEOUT_MS = 20_000;
|
|
44
|
+
/**
|
|
45
|
+
* Waits for `work` until `signal` aborts. Only the wait stops: the work keeps
|
|
46
|
+
* running, so a shared refresh still saves its single-use replacement token.
|
|
47
|
+
*/
|
|
48
|
+
function abortable(work, signal) {
|
|
49
|
+
if (signal.aborted)
|
|
50
|
+
return Promise.reject(signal.reason);
|
|
51
|
+
let onAbort = () => { };
|
|
52
|
+
const aborted = new Promise((_, reject) => {
|
|
53
|
+
onAbort = () => reject(signal.reason);
|
|
54
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
55
|
+
});
|
|
56
|
+
return Promise.race([work, aborted]).finally(() => signal.removeEventListener("abort", onAbort));
|
|
57
|
+
}
|
|
58
|
+
/** Ids go into request paths, so allow only URN characters: no `/`, `?`, `#`, `.` or `%`. */
|
|
59
|
+
function pathSegment(value) {
|
|
60
|
+
if (!/^[A-Za-z0-9:_-]+$/.test(value)) {
|
|
61
|
+
throw new SoundCloudApiError(`"${value}" isn't a SoundCloud id or URN.`, 400);
|
|
62
|
+
}
|
|
63
|
+
return value;
|
|
64
|
+
}
|
|
65
|
+
/** Normalize numeric or permalink-style ids to SoundCloud URNs. */
|
|
66
|
+
export function toUrn(kind, idOrUrn) {
|
|
67
|
+
const raw = pathSegment(String(idOrUrn).trim());
|
|
68
|
+
if (raw.startsWith("soundcloud:"))
|
|
69
|
+
return raw;
|
|
70
|
+
return `soundcloud:${kind}:${raw}`;
|
|
71
|
+
}
|
|
72
|
+
const TrackPage = pageOf(TrackSchema);
|
|
73
|
+
const PlaylistPage = pageOf(PlaylistSchema);
|
|
74
|
+
const UserPage = pageOf(UserSchema);
|
|
75
|
+
export class SoundCloudClient {
|
|
76
|
+
tokens;
|
|
77
|
+
baseUrl;
|
|
78
|
+
fetchImpl;
|
|
79
|
+
signal;
|
|
80
|
+
constructor(tokens, baseUrl = API_BASE,
|
|
81
|
+
// Must stay bound: Workers throws "Illegal invocation" if the global fetch
|
|
82
|
+
// is called with anything but the global object as `this`.
|
|
83
|
+
fetchImpl = globalThis.fetch.bind(globalThis), signal) {
|
|
84
|
+
this.tokens = tokens;
|
|
85
|
+
this.baseUrl = baseUrl;
|
|
86
|
+
this.fetchImpl = fetchImpl;
|
|
87
|
+
this.signal = signal;
|
|
88
|
+
}
|
|
89
|
+
/** A client whose requests also stop when `signal` aborts, such as a cancelled MCP call. */
|
|
90
|
+
withSignal(signal) {
|
|
91
|
+
return new SoundCloudClient(this.tokens, this.baseUrl, this.fetchImpl, signal);
|
|
92
|
+
}
|
|
93
|
+
/** Sends one API call and returns the parsed JSON body, or undefined if it is empty. */
|
|
94
|
+
async request(path, spec = {}) {
|
|
95
|
+
const url = path.startsWith("http") ? new URL(path) : new URL(this.baseUrl + path);
|
|
96
|
+
// Every request carries the user's token, so never send one off the API host.
|
|
97
|
+
if (url.origin !== new URL(this.baseUrl).origin) {
|
|
98
|
+
throw new SoundCloudApiError("Only SoundCloud API URLs are allowed.", 400);
|
|
99
|
+
}
|
|
100
|
+
for (const [key, value] of Object.entries(spec.query ?? {})) {
|
|
101
|
+
if (value !== undefined)
|
|
102
|
+
url.searchParams.set(key, String(value));
|
|
103
|
+
}
|
|
104
|
+
const deadline = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
|
|
105
|
+
const signal = this.signal ? AbortSignal.any([this.signal, deadline]) : deadline;
|
|
106
|
+
try {
|
|
107
|
+
return await this.attempt(url.toString(), spec, signal);
|
|
108
|
+
}
|
|
109
|
+
catch (error) {
|
|
110
|
+
if (deadline.aborted && !this.signal?.aborted) {
|
|
111
|
+
throw new SoundCloudApiError("SoundCloud did not answer in time. Try again.", 504);
|
|
112
|
+
}
|
|
113
|
+
throw error;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
async attempt(url, spec, signal) {
|
|
117
|
+
let token = await abortable(this.tokens.getAccessToken(), signal);
|
|
118
|
+
let refreshed = false;
|
|
119
|
+
for (;;) {
|
|
120
|
+
const response = await this.send(url, token, spec, signal);
|
|
121
|
+
if (response.status === 401) {
|
|
122
|
+
if (refreshed)
|
|
123
|
+
throw new SoundCloudAuthError();
|
|
124
|
+
refreshed = true;
|
|
125
|
+
token = await abortable(this.tokens.refreshAccessToken(), signal);
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
if (response.status === 429) {
|
|
129
|
+
throw new RateLimitedError(retryAfterSeconds(response.headers.get("Retry-After")));
|
|
130
|
+
}
|
|
131
|
+
if (!response.ok) {
|
|
132
|
+
const message = response.status >= 500
|
|
133
|
+
? "SoundCloud is unavailable. Try again later."
|
|
134
|
+
: "SoundCloud rejected the request. Check the inputs and your access.";
|
|
135
|
+
throw new SoundCloudApiError(message, response.status);
|
|
136
|
+
}
|
|
137
|
+
if (response.status === 204)
|
|
138
|
+
return undefined;
|
|
139
|
+
const text = await response.text();
|
|
140
|
+
return text ? JSON.parse(text) : undefined;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
send(url, token, spec, signal) {
|
|
144
|
+
const headers = {
|
|
145
|
+
// SoundCloud uses the `OAuth` scheme, not `Bearer`.
|
|
146
|
+
Authorization: `OAuth ${token}`,
|
|
147
|
+
accept: "application/json; charset=utf-8",
|
|
148
|
+
};
|
|
149
|
+
let body;
|
|
150
|
+
if (spec.body !== undefined) {
|
|
151
|
+
headers["Content-Type"] = "application/json";
|
|
152
|
+
body = JSON.stringify(spec.body);
|
|
153
|
+
}
|
|
154
|
+
return this.fetchImpl(url, {
|
|
155
|
+
method: spec.method ?? "GET",
|
|
156
|
+
headers,
|
|
157
|
+
signal,
|
|
158
|
+
...(body !== undefined ? { body } : {}),
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
/** Checks the fields this server reads. Every other field passes through. */
|
|
162
|
+
async read(schema, path, spec) {
|
|
163
|
+
const parsed = schema.safeParse(await this.request(path, spec));
|
|
164
|
+
if (!parsed.success) {
|
|
165
|
+
throw new SoundCloudApiError("SoundCloud sent a response this server cannot read.", 502);
|
|
166
|
+
}
|
|
167
|
+
return parsed.data;
|
|
168
|
+
}
|
|
169
|
+
// Cursor pagination: `next_href` is a fully-qualified URL, so it is fetched
|
|
170
|
+
// as-is rather than being re-based onto the API root.
|
|
171
|
+
page(schema, path, query = {}) {
|
|
172
|
+
return this.read(schema, path, { query: { linked_partitioning: true, ...query } });
|
|
173
|
+
}
|
|
174
|
+
/** Any endpoint can sit behind a next_href, so the result is left unchecked. */
|
|
175
|
+
nextPage(nextHref) {
|
|
176
|
+
return this.request(nextHref);
|
|
177
|
+
}
|
|
178
|
+
// --- Discovery ---
|
|
179
|
+
searchTracks(query) {
|
|
180
|
+
return this.page(TrackPage, "/tracks", query);
|
|
181
|
+
}
|
|
182
|
+
searchPlaylists(q, limit) {
|
|
183
|
+
return this.page(PlaylistPage, "/playlists", { q, limit });
|
|
184
|
+
}
|
|
185
|
+
searchUsers(q, limit) {
|
|
186
|
+
return this.page(UserPage, "/users", { q, limit });
|
|
187
|
+
}
|
|
188
|
+
getTrack(id) {
|
|
189
|
+
return this.read(TrackSchema, `/tracks/${toUrn("tracks", id)}`);
|
|
190
|
+
}
|
|
191
|
+
getUser(id) {
|
|
192
|
+
return this.read(UserSchema, `/users/${toUrn("users", id)}`);
|
|
193
|
+
}
|
|
194
|
+
getPlaylist(id) {
|
|
195
|
+
return this.read(PlaylistSchema, `/playlists/${toUrn("playlists", id)}`);
|
|
196
|
+
}
|
|
197
|
+
getPlaylistTracks(id, limit) {
|
|
198
|
+
return this.page(TrackPage, `/playlists/${toUrn("playlists", id)}/tracks`, { limit });
|
|
199
|
+
}
|
|
200
|
+
getRelatedTracks(id, limit) {
|
|
201
|
+
return this.read(z.array(TrackSchema), `/tracks/${toUrn("tracks", id)}/related`, {
|
|
202
|
+
query: { limit },
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
getRelatedArtists(id, limit) {
|
|
206
|
+
return this.read(z.array(UserSchema), `/users/${toUrn("users", id)}/related`, {
|
|
207
|
+
query: { limit },
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
getUserTracks(id, limit, sort) {
|
|
211
|
+
return this.page(TrackPage, `/users/${toUrn("users", id)}/tracks`, { limit, sort });
|
|
212
|
+
}
|
|
213
|
+
getUserPlaylists(id, limit) {
|
|
214
|
+
return this.page(PlaylistPage, `/users/${toUrn("users", id)}/playlists`, { limit });
|
|
215
|
+
}
|
|
216
|
+
// Paths are spelled out per kind so the api-sync audit can match each literal.
|
|
217
|
+
getUserLikes(id, limit, kind = "tracks") {
|
|
218
|
+
const user = toUrn("users", id);
|
|
219
|
+
if (kind === "tracks")
|
|
220
|
+
return this.page(TrackPage, `/users/${user}/likes/tracks`, { limit });
|
|
221
|
+
const path = kind === "stations"
|
|
222
|
+
? `/users/${user}/likes/system-playlists`
|
|
223
|
+
: `/users/${user}/likes/playlists`;
|
|
224
|
+
return this.page(PlaylistPage, path, { limit });
|
|
225
|
+
}
|
|
226
|
+
getUserReposts(id, limit, kind = "tracks") {
|
|
227
|
+
const user = toUrn("users", id);
|
|
228
|
+
return kind === "playlists"
|
|
229
|
+
? this.page(PlaylistPage, `/users/${user}/reposts/playlists`, { limit })
|
|
230
|
+
: this.page(TrackPage, `/users/${user}/reposts/tracks`, { limit });
|
|
231
|
+
}
|
|
232
|
+
getUserFollowers(id, limit) {
|
|
233
|
+
return this.page(UserPage, `/users/${toUrn("users", id)}/followers`, { limit });
|
|
234
|
+
}
|
|
235
|
+
getUserFollowings(id, limit) {
|
|
236
|
+
return this.page(UserPage, `/users/${toUrn("users", id)}/followings`, { limit });
|
|
237
|
+
}
|
|
238
|
+
getUserWebProfiles(id, limit) {
|
|
239
|
+
return this.read(z.array(WebProfileSchema), `/users/${toUrn("users", id)}/web-profiles`, {
|
|
240
|
+
query: { limit },
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
getTrackStreams(id) {
|
|
244
|
+
return this.read(TrackStreamsSchema, `/tracks/${toUrn("tracks", id)}/streams`);
|
|
245
|
+
}
|
|
246
|
+
getComments(id, limit) {
|
|
247
|
+
return this.page(pageOf(CommentSchema), `/tracks/${toUrn("tracks", id)}/comments`, {
|
|
248
|
+
limit,
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
/** SoundCloud still calls likers "favoriters" in this path. */
|
|
252
|
+
getTrackLikers(id, limit) {
|
|
253
|
+
return this.page(UserPage, `/tracks/${toUrn("tracks", id)}/favoriters`, { limit });
|
|
254
|
+
}
|
|
255
|
+
getTrackReposters(id, limit) {
|
|
256
|
+
return this.page(UserPage, `/tracks/${toUrn("tracks", id)}/reposters`, { limit });
|
|
257
|
+
}
|
|
258
|
+
getPlaylistReposters(id, limit) {
|
|
259
|
+
return this.page(UserPage, `/playlists/${toUrn("playlists", id)}/reposters`, { limit });
|
|
260
|
+
}
|
|
261
|
+
/** Takes a `soundcloud:system-playlists:…` URN or its `track-stations:{id}` part. */
|
|
262
|
+
getSystemPlaylist(id) {
|
|
263
|
+
return this.read(PlaylistSchema, `/system-playlists/${pathSegment(id.trim())}`);
|
|
264
|
+
}
|
|
265
|
+
/** Turns a soundcloud.com permalink into a track, user, playlist or station, unchecked. */
|
|
266
|
+
resolve(url) {
|
|
267
|
+
return this.request("/resolve", { query: { url } });
|
|
268
|
+
}
|
|
269
|
+
// --- Me / library ---
|
|
270
|
+
getMe() {
|
|
271
|
+
return this.read(UserSchema, "/me");
|
|
272
|
+
}
|
|
273
|
+
getMyLikes(limit, kind = "tracks") {
|
|
274
|
+
if (kind === "tracks")
|
|
275
|
+
return this.page(TrackPage, "/me/likes/tracks", { limit });
|
|
276
|
+
const path = kind === "stations" ? "/me/likes/system-playlists" : "/me/likes/playlists";
|
|
277
|
+
return this.page(PlaylistPage, path, { limit });
|
|
278
|
+
}
|
|
279
|
+
getMyReposts(limit, kind = "tracks") {
|
|
280
|
+
return kind === "playlists"
|
|
281
|
+
? this.page(PlaylistPage, "/me/reposts/playlists", { limit })
|
|
282
|
+
: this.page(TrackPage, "/me/reposts/tracks", { limit });
|
|
283
|
+
}
|
|
284
|
+
getMyPlaylists(limit) {
|
|
285
|
+
return this.page(PlaylistPage, "/me/playlists", { limit });
|
|
286
|
+
}
|
|
287
|
+
getMyTracks(limit, sort) {
|
|
288
|
+
return this.page(TrackPage, "/me/tracks", { limit, sort });
|
|
289
|
+
}
|
|
290
|
+
getMyFollowings(limit) {
|
|
291
|
+
return this.page(UserPage, "/me/followings", { limit });
|
|
292
|
+
}
|
|
293
|
+
getMyFollowers(limit) {
|
|
294
|
+
return this.page(UserPage, "/me/followers", { limit });
|
|
295
|
+
}
|
|
296
|
+
// The spec deprecates this read in favor of /users/{urn}, which cannot
|
|
297
|
+
// answer the follow question. 404 means "not followed" (or no such user).
|
|
298
|
+
async isFollowing(id) {
|
|
299
|
+
try {
|
|
300
|
+
await this.request(`/me/followings/${toUrn("users", id)}`);
|
|
301
|
+
return true;
|
|
302
|
+
}
|
|
303
|
+
catch (error) {
|
|
304
|
+
if (error instanceof SoundCloudApiError && error.status === 404)
|
|
305
|
+
return false;
|
|
306
|
+
throw error;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
/** New tracks from people you follow — the closest thing to a home feed. */
|
|
310
|
+
getFeed(limit, kind = "tracks") {
|
|
311
|
+
return this.page(pageOf(FeedItemSchema), kind === "all" ? "/me/feed" : "/me/feed/tracks", {
|
|
312
|
+
limit,
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
/** This endpoint ignores `limit` and returns the whole history, so it is trimmed here. */
|
|
316
|
+
async getRecentlyPlayed(limit) {
|
|
317
|
+
const page = await this.page(TrackPage, "/me/recently-played/tracks", { limit });
|
|
318
|
+
return { ...page, collection: page.collection.slice(0, limit) };
|
|
319
|
+
}
|
|
320
|
+
/** Revokes this app's access for the user and invalidates every token it issued them. */
|
|
321
|
+
disconnect() {
|
|
322
|
+
return this.request("/disconnect", { method: "POST" });
|
|
323
|
+
}
|
|
324
|
+
// --- Social writes ---
|
|
325
|
+
likeTrack(id) {
|
|
326
|
+
return this.request(`/likes/tracks/${toUrn("tracks", id)}`, { method: "POST" });
|
|
327
|
+
}
|
|
328
|
+
unlikeTrack(id) {
|
|
329
|
+
return this.request(`/likes/tracks/${toUrn("tracks", id)}`, { method: "DELETE" });
|
|
330
|
+
}
|
|
331
|
+
repostTrack(id) {
|
|
332
|
+
return this.request(`/reposts/tracks/${toUrn("tracks", id)}`, { method: "POST" });
|
|
333
|
+
}
|
|
334
|
+
unrepostTrack(id) {
|
|
335
|
+
return this.request(`/reposts/tracks/${toUrn("tracks", id)}`, { method: "DELETE" });
|
|
336
|
+
}
|
|
337
|
+
likePlaylist(id) {
|
|
338
|
+
return this.request(`/likes/playlists/${toUrn("playlists", id)}`, { method: "POST" });
|
|
339
|
+
}
|
|
340
|
+
unlikePlaylist(id) {
|
|
341
|
+
return this.request(`/likes/playlists/${toUrn("playlists", id)}`, { method: "DELETE" });
|
|
342
|
+
}
|
|
343
|
+
repostPlaylist(id) {
|
|
344
|
+
return this.request(`/reposts/playlists/${toUrn("playlists", id)}`, { method: "POST" });
|
|
345
|
+
}
|
|
346
|
+
unrepostPlaylist(id) {
|
|
347
|
+
return this.request(`/reposts/playlists/${toUrn("playlists", id)}`, { method: "DELETE" });
|
|
348
|
+
}
|
|
349
|
+
followUser(id) {
|
|
350
|
+
return this.request(`/me/followings/${toUrn("users", id)}`, { method: "PUT" });
|
|
351
|
+
}
|
|
352
|
+
unfollowUser(id) {
|
|
353
|
+
return this.request(`/me/followings/${toUrn("users", id)}`, { method: "DELETE" });
|
|
354
|
+
}
|
|
355
|
+
addComment(id, body, timestamp) {
|
|
356
|
+
return this.read(CommentSchema, `/tracks/${toUrn("tracks", id)}/comments`, {
|
|
357
|
+
method: "POST",
|
|
358
|
+
body: { comment: { body, ...(timestamp !== undefined ? { timestamp } : {}) } },
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
// --- Playlist writes ---
|
|
362
|
+
createPlaylist(opts) {
|
|
363
|
+
return this.read(PlaylistSchema, "/playlists", {
|
|
364
|
+
method: "POST",
|
|
365
|
+
body: {
|
|
366
|
+
playlist: {
|
|
367
|
+
title: opts.title,
|
|
368
|
+
sharing: opts.sharing,
|
|
369
|
+
...(opts.description !== undefined ? { description: opts.description } : {}),
|
|
370
|
+
...(opts.trackIds ? { tracks: opts.trackIds.map(playlistTrackRef) } : {}),
|
|
371
|
+
},
|
|
372
|
+
},
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
updatePlaylist(id, updates) {
|
|
376
|
+
const playlist = {};
|
|
377
|
+
if (updates.title !== undefined)
|
|
378
|
+
playlist.title = updates.title;
|
|
379
|
+
if (updates.description !== undefined)
|
|
380
|
+
playlist.description = updates.description;
|
|
381
|
+
if (updates.sharing !== undefined)
|
|
382
|
+
playlist.sharing = updates.sharing;
|
|
383
|
+
if (updates.trackIds !== undefined)
|
|
384
|
+
playlist.tracks = updates.trackIds.map(playlistTrackRef);
|
|
385
|
+
return this.read(PlaylistSchema, `/playlists/${toUrn("playlists", id)}`, {
|
|
386
|
+
method: "PUT",
|
|
387
|
+
body: { playlist },
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
deletePlaylist(id) {
|
|
391
|
+
return this.request(`/playlists/${toUrn("playlists", id)}`, { method: "DELETE" });
|
|
392
|
+
}
|
|
393
|
+
/**
|
|
394
|
+
* Reads every track id for a read-modify-write. The playlist GET omits blocked
|
|
395
|
+
* tracks unless asked, and a PUT without them deletes them. Tracks the API
|
|
396
|
+
* never returns (track_count is higher) or returns without an id would also
|
|
397
|
+
* be deleted, so refuse.
|
|
398
|
+
*/
|
|
399
|
+
async getTracklist(id) {
|
|
400
|
+
const playlist = await this.read(PlaylistSchema, `/playlists/${toUrn("playlists", id)}`, {
|
|
401
|
+
query: { access: "playable,preview,blocked" },
|
|
402
|
+
});
|
|
403
|
+
const tracks = playlist.tracks ?? [];
|
|
404
|
+
const ids = tracks.flatMap((track) => {
|
|
405
|
+
const ref = track.urn ?? track.id;
|
|
406
|
+
return ref == null ? [] : [ref];
|
|
407
|
+
});
|
|
408
|
+
if (ids.length < Math.max(tracks.length, playlist.track_count ?? 0)) {
|
|
409
|
+
throw new SoundCloudApiError("SoundCloud hides some tracks in this playlist, and changing it here would delete them. Edit it on soundcloud.com instead.", 409);
|
|
410
|
+
}
|
|
411
|
+
return ids;
|
|
412
|
+
}
|
|
413
|
+
/** SoundCloud has no append endpoint; the whole tracklist must be re-sent. */
|
|
414
|
+
async addTracksToPlaylist(id, trackIds) {
|
|
415
|
+
const ids = [...(await this.getTracklist(id)), ...trackIds];
|
|
416
|
+
return this.updatePlaylist(id, { trackIds: ids });
|
|
417
|
+
}
|
|
418
|
+
async removeTrackFromPlaylist(id, trackId) {
|
|
419
|
+
const target = toUrn("tracks", trackId);
|
|
420
|
+
const ids = (await this.getTracklist(id)).filter((each) => toUrn("tracks", each) !== target);
|
|
421
|
+
return this.updatePlaylist(id, { trackIds: ids });
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
// SoundCloud mangles track IDs above int32 when they arrive as JSON numbers in
|
|
425
|
+
// a playlist body (returns 422), so every ref is sent as a URN string.
|
|
426
|
+
function playlistTrackRef(id) {
|
|
427
|
+
return { urn: toUrn("tracks", id) };
|
|
428
|
+
}
|
package/build/icon.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// One waveform mark, served as SVG and PNG. Used as the MCP server icon, the
|
|
2
|
+
// install page's favicon, and `/icon.svg` / `/icon.png` / `/favicon.ico`.
|
|
3
|
+
export const ICON_SVG = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="#f50"/><g fill="#fff"><rect x="12" y="25" width="5" height="14" rx="2.5"/><rect x="21" y="19" width="5" height="26" rx="2.5"/><rect x="30" y="14" width="5" height="36" rx="2.5"/><rect x="39" y="21" width="5" height="22" rx="2.5"/><rect x="48" y="26" width="5" height="12" rx="2.5"/></g></svg>';
|
|
4
|
+
// 128x128 render of the same mark, inlined so the worker needs no asset binding.
|
|
5
|
+
// Regenerate with `rsvg-convert -w 128 -h 128 icon.svg`.
|
|
6
|
+
const ICON_PNG_BASE64 = "iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAMAAAD04JH5AAABSlBMVEUAAAD/QAD/UwD/VAD/VgD/VQD/VQD/VQD/VQD/VQD/VQD/VQD/VQD/VQD/VQD/VQD/VgD/VQD/VQD/VQD/VgD/WQD/VQD/VAD/VQD/VgD/XQD/VQD/VQD/VAD/YAD/VAD/VQD/TQD/UgD/VQD/VQD/WAD/VwD/VQD/VQD/VQD/UwD/VQD/VQD/VwD/VQD/VQD/VQD/WAD/VQD/SQD/VQD/VAD/VgD/UQD/VQD/VAD/VQD/VQD/VAD/VQD/VgD/VQD/VQD/VwD/UwD/VgD/VQD/VQD/VQD/VQD/VQD/VgD/VQD/VAD/VQD/VAD/ZgD/VgD/VAD/VQD/VAD/VgD/VQD/UgD/UwD/VQD/VQD/VQD/VwD/VQD/VQD/VQD/ik//1cD/+PT/1L//iE3/sIj/////roX/iEz/1L7/9/P/9vL/9vH/073/h0v/rIO/KTX+AAAAXXRSTlMABDdzm8Le7vr5BlGu8vGtUBWE7IMUDIj0hgvi4U8IkaIKHNDOGiPc4Cco6ukmG9/jHc0HmZRNE/OFgetSTqrvAzg0cZzDwO34mHJwM6kFgIJLl5LLGSLbCRI13b82qvQ9AAAC8ElEQVR42u2b7VcSQRTGr4AgvgeWWFqRopIWJRtWpJKWVKaiZW82voVKaP//11RaBWZhd5iZez2deb6x58DzO2dnn2d3mQvgoDafP9AeDHUwRQqHgu0Bv68NPKmzq7uHaVFvX3+nq/2NSJRpVHTgZlP7W4MxplmxoduN/fvvMAQNjzSwv3uPIel+3Mn/wShD01iC9x+fYIiaTNb7P5xiqJp+VOv/OMWQ9eRpzfobZeiaSVcBWIxAz678uxiJMrZ/PEUDMGxn4iAjUqTiP/ucCiBWaaYXjEwvL/o/SgeQPb8/eMUINXcG0E0JMH92/9dLCbCQg9eMVIvgpwVYgje0ABa8pQVYhhQtQBDytABZCNMCvAO57+/s7u3tH8j8ghzAr+KFDqkAdor/dEQEsGsDHBMBlGyA30QAxUsZAAOABFCfe9gAXO4hA/C5hwzA5x4yAJ97TgCi/Qgya94BQLgfFQOI96NiAPF+VAwg3o+KAcSvCwMAMsmvF8BD8msF8JL83gCaZyPIJL+KbASZ5FeRjaB2zYtno3YAt2zUDuB2XRgAA2AADIABMAD/P8BlHZeJAPbtAyet3pKV5QAO7AOnggA8eYtn/LDy+Y/oTSlP3uqSOzoulU5OxR9MOHL0R7N6cvN0bABU5J52ALfc0w7glnv6X1S65J6aV7Xl1nNPCsBLO2h9We2lHfT+YeGhHfQCeGgHzQDu14UBMADIAOLdpxhAvPsUA4h3n2IA8e5TDSDcfQ4A5BuZyLdykW9mI9/OF6AFeA8faAFWwEcL8JF+Wy/0UQKs0k03VJQh3tw+tXa+vX6ADmD9egw4wBAVQOG6DLnACA3AxtWg0SaF/6fqUa8xfP/P1aNekEBfBsGt2nG75DSuf/24H8CXr5j+qSQ/cpmYQTz/W05Dp2m0oVcr3WDuNjOJsvw2Gg8exyPae6Gn8K3p7PVsIau1f9e/uw+/z80v6HEPrWbWvA3g534sWcvbeWVPbeH89k9rZTHn5PUXoz+AfC4ryhsAAAAASUVORK5CYII=";
|
|
7
|
+
export const ICON_PNG = Uint8Array.from(atob(ICON_PNG_BASE64), (c) => c.charCodeAt(0));
|
|
8
|
+
// The MCP icons spec requires clients to support https URLs and lets them
|
|
9
|
+
// reject data URIs, so the worker advertises a real URL. It is hardcoded
|
|
10
|
+
// because server metadata is built before any request tells us our origin;
|
|
11
|
+
// self-deployers should change it.
|
|
12
|
+
export const HOSTED_ICON = {
|
|
13
|
+
src: "https://soundcloud-mcp.jamie-7e9.workers.dev/icon.png",
|
|
14
|
+
mimeType: "image/png",
|
|
15
|
+
sizes: ["128x128"],
|
|
16
|
+
};
|
|
17
|
+
// stdio has no origin at all, so it inlines the mark.
|
|
18
|
+
export const INLINE_ICON = {
|
|
19
|
+
src: `data:image/svg+xml;utf8,${encodeURIComponent(ICON_SVG)}`,
|
|
20
|
+
mimeType: "image/svg+xml",
|
|
21
|
+
sizes: ["any"],
|
|
22
|
+
};
|
package/build/index.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { McpServer } from "@modelcontextprotocol/server";
|
|
3
|
+
import { serveStdio } from "@modelcontextprotocol/server/stdio";
|
|
4
|
+
import { SoundCloudClient } from "./client.js";
|
|
5
|
+
import { instructions, serverInfo } from "./server.js";
|
|
6
|
+
import { registerAuthTools } from "./stdio/authTools.js";
|
|
7
|
+
import { CLIENT_ID, CLIENT_SECRET } from "./stdio/config.js";
|
|
8
|
+
import { logError } from "./stdio/log.js";
|
|
9
|
+
import { tokenProvider } from "./stdio/oauth.js";
|
|
10
|
+
import { registerTools } from "./tools.js";
|
|
11
|
+
// Start anyway so clients can list tools; calls that need credentials say what's missing.
|
|
12
|
+
if (!CLIENT_ID || !CLIENT_SECRET) {
|
|
13
|
+
logError("Missing SOUNDCLOUD_CLIENT_ID or SOUNDCLOUD_CLIENT_SECRET. Set them in this server's environment (or .env in a checkout).");
|
|
14
|
+
}
|
|
15
|
+
// Use a user token when logged in, otherwise cached client credentials.
|
|
16
|
+
const sc = new SoundCloudClient(tokenProvider);
|
|
17
|
+
// serveStdio picks the protocol era from the client's first message.
|
|
18
|
+
serveStdio(() => {
|
|
19
|
+
const server = new McpServer(serverInfo("soundcloud"), {
|
|
20
|
+
instructions: instructions("- Public search needs no login. Use `connect_soundcloud` for personal data and writes."),
|
|
21
|
+
});
|
|
22
|
+
registerTools(server, sc);
|
|
23
|
+
registerAuthTools(server, sc);
|
|
24
|
+
return server;
|
|
25
|
+
}, { onerror: (error) => logError("MCP error:", error) });
|
|
26
|
+
logError("SoundCloud MCP server running on stdio");
|
package/build/server.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Shared identity; each transport supplies its own auth instructions.
|
|
2
|
+
import pkg from "../package.json" with { type: "json" };
|
|
3
|
+
import { INLINE_ICON } from "./icon.js";
|
|
4
|
+
export function serverInfo(name, icons = [INLINE_ICON]) {
|
|
5
|
+
return {
|
|
6
|
+
name,
|
|
7
|
+
version: pkg.version,
|
|
8
|
+
title: "SoundCloud",
|
|
9
|
+
description: "Search SoundCloud, read your library, and manage playlists, follows, likes and reposts.",
|
|
10
|
+
websiteUrl: "https://github.com/jamiew/soundcloud-mcp",
|
|
11
|
+
icons,
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
/** `authLine` describes how this transport gets credentials. */
|
|
15
|
+
export function instructions(authLine) {
|
|
16
|
+
return [
|
|
17
|
+
"SoundCloud, through the official API.",
|
|
18
|
+
"",
|
|
19
|
+
"- Resolve pasted SoundCloud links with `resolve_url`.",
|
|
20
|
+
"- Prefer URNs (`soundcloud:tracks:123`); numeric ids also work.",
|
|
21
|
+
"- Pass `next_href` to `next_page`. Page size: 50 by default, 200 max.",
|
|
22
|
+
authLine,
|
|
23
|
+
"- For recommendations, use `get_related_tracks` with a liked track or read `get_feed`.",
|
|
24
|
+
].join("\n");
|
|
25
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// CLI login: opens a browser, captures the SoundCloud OAuth callback, and
|
|
3
|
+
// stores tokens so the MCP server can use them across sessions. `--sign-out`
|
|
4
|
+
// revokes the app's access and deletes the stored token instead.
|
|
5
|
+
import { SoundCloudClient } from "../client.js";
|
|
6
|
+
import { CLIENT_ID, CLIENT_SECRET, TOKEN_FILE } from "./config.js";
|
|
7
|
+
import { loginWithBrowser, SIGN_OUT_MESSAGES, signOut, tokenProvider } from "./oauth.js";
|
|
8
|
+
async function main() {
|
|
9
|
+
if (!CLIENT_ID || !CLIENT_SECRET) {
|
|
10
|
+
console.error("Set SOUNDCLOUD_CLIENT_ID and SOUNDCLOUD_CLIENT_SECRET in the environment or .env.");
|
|
11
|
+
process.exit(1);
|
|
12
|
+
}
|
|
13
|
+
const client = new SoundCloudClient(tokenProvider);
|
|
14
|
+
if (process.argv.includes("--sign-out")) {
|
|
15
|
+
console.error(SIGN_OUT_MESSAGES[await signOut(client)]);
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
const noBrowser = process.argv.includes("--no-browser");
|
|
19
|
+
const token = await loginWithBrowser({ openBrowser: !noBrowser });
|
|
20
|
+
const me = await client.getMe();
|
|
21
|
+
console.error(`\nConnected as ${me.username} (id ${me.id}).`);
|
|
22
|
+
console.error(`Tokens saved to: ${TOKEN_FILE}`);
|
|
23
|
+
console.error(`Access token expires in ${token.expires_in}s and will auto-refresh.`);
|
|
24
|
+
}
|
|
25
|
+
main().catch((error) => {
|
|
26
|
+
console.error(`\nLogin failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
27
|
+
process.exit(1);
|
|
28
|
+
});
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { run } from "../tools.js";
|
|
2
|
+
import { hasUserToken, loginWithBrowser, SIGN_OUT_MESSAGES, signOut } from "./oauth.js";
|
|
3
|
+
// Stdio handles login through tools; the worker uses transport OAuth.
|
|
4
|
+
export function registerAuthTools(server, sc) {
|
|
5
|
+
server.registerTool("connect_soundcloud", {
|
|
6
|
+
title: "Connect SoundCloud",
|
|
7
|
+
description: "Log in through your browser and save the token for future sessions.",
|
|
8
|
+
annotations: {
|
|
9
|
+
title: "Connect SoundCloud",
|
|
10
|
+
readOnlyHint: false,
|
|
11
|
+
destructiveHint: false,
|
|
12
|
+
openWorldHint: true,
|
|
13
|
+
},
|
|
14
|
+
}, async () => run(async () => {
|
|
15
|
+
const token = await loginWithBrowser();
|
|
16
|
+
const me = await sc.getMe();
|
|
17
|
+
return `Connected as ${me.username} (id ${me.id}). Token expires in ${token.expires_in}s and refreshes automatically.`;
|
|
18
|
+
}));
|
|
19
|
+
server.registerTool("auth_status", {
|
|
20
|
+
title: "Auth status",
|
|
21
|
+
description: "Check whether a SoundCloud user is logged in.",
|
|
22
|
+
annotations: { title: "Auth status", readOnlyHint: true, openWorldHint: true },
|
|
23
|
+
}, async () => run(async () => {
|
|
24
|
+
if (!hasUserToken()) {
|
|
25
|
+
return "Not logged in. Use connect_soundcloud (public search still works).";
|
|
26
|
+
}
|
|
27
|
+
const me = await sc.getMe();
|
|
28
|
+
return `Logged in as ${me.username} (id ${me.id}).`;
|
|
29
|
+
}));
|
|
30
|
+
server.registerTool("sign_out", {
|
|
31
|
+
title: "Sign out",
|
|
32
|
+
description: "Revoke this app's SoundCloud access and delete the stored token. Public search still works afterward.",
|
|
33
|
+
annotations: {
|
|
34
|
+
title: "Sign out",
|
|
35
|
+
readOnlyHint: false,
|
|
36
|
+
destructiveHint: true,
|
|
37
|
+
idempotentHint: true,
|
|
38
|
+
openWorldHint: true,
|
|
39
|
+
},
|
|
40
|
+
}, async () => run(async () => SIGN_OUT_MESSAGES[await signOut(sc)]));
|
|
41
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import os from "node:os";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
export const CLIENT_ID = (process.env.SOUNDCLOUD_CLIENT_ID ?? "").trim();
|
|
4
|
+
export const CLIENT_SECRET = (process.env.SOUNDCLOUD_CLIENT_SECRET ?? "").trim();
|
|
5
|
+
export const REDIRECT_URI = (process.env.SOUNDCLOUD_REDIRECT_URI ?? "http://localhost:8888/callback").trim();
|
|
6
|
+
// Where user OAuth tokens are persisted between runs.
|
|
7
|
+
const defaultTokenFile = path.join(os.homedir(), ".soundcloud-mcp", "tokens.json");
|
|
8
|
+
export const TOKEN_FILE = (process.env.SOUNDCLOUD_TOKEN_FILE ?? defaultTokenFile).replace(/^~(?=$|\/)/, os.homedir());
|
|
9
|
+
// Verbose logging to stderr (never stdout — that's the MCP transport).
|
|
10
|
+
export const DEBUG = process.env.MCP_DEBUG === "true";
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { DEBUG } from "./config.js";
|
|
2
|
+
// IMPORTANT: a stdio MCP server uses stdout for JSON-RPC framing. Anything
|
|
3
|
+
// written to stdout corrupts the protocol stream, so all logging goes to stderr.
|
|
4
|
+
export function logError(...args) {
|
|
5
|
+
console.error(...args);
|
|
6
|
+
}
|
|
7
|
+
export function debug(...args) {
|
|
8
|
+
if (DEBUG)
|
|
9
|
+
console.error("[debug]", ...args);
|
|
10
|
+
}
|