-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.ts
More file actions
470 lines (425 loc) Β· 16.5 KB
/
Copy pathhttp.ts
File metadata and controls
470 lines (425 loc) Β· 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
/**
* HTTP server β handles:
* GET / β health check
* GET /auth β kick off Spotify OAuth
* GET /auth/callback β Spotify redirects here with the code
* POST /mcp β MCP StreamableHTTP endpoint
* GET /mcp β MCP SSE stream (older clients)
* DELETE /mcp β MCP session teardown
*/
import express from "express";
import { randomBytes, createHash } from "crypto";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { SpotifyClient } from "./spotify.js";
import { createMcpServer } from "./mcp.js";
const SCOPES = [
"streaming",
"user-read-playback-state",
"user-modify-playback-state",
"user-read-currently-playing",
"playlist-read-private",
"playlist-modify-public",
"playlist-modify-private",
"user-library-read",
"user-read-private",
].join(" ");
// In-flight PKCE state (single-user server β one pending auth at a time is fine)
let pendingAuth: { codeVerifier: string; state: string } | null = null;
// SDK browser device registry β sdk-frame tab communicates with player via server
let _sdkDeviceId: string | null = null;
let _sdkSseClients: express.Response[] = [];
export function createApp(spotify: SpotifyClient): express.Express {
const app = express();
app.use(express.json());
// Allow cross-origin requests from the CopilotKit host (e.g. localhost:3000)
// The iframe's origin differs from the MCP server's origin (127.0.0.1:3124),
// so without this header the browser blocks fetch() calls from the iframe.
app.use((_req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, mcp-session-id");
if (_req.method === "OPTIONS") { res.sendStatus(204); return; }
next();
});
const CLIENT_ID = process.env.SPOTIFY_CLIENT_ID!;
const CLIENT_SECRET = process.env.SPOTIFY_CLIENT_SECRET!;
const REDIRECT_URI = process.env.SPOTIFY_REDIRECT_URI!;
// Base URL of this server β used so the iframe knows where to send the user for auth
const BASE_URL = REDIRECT_URI.replace(/\/auth\/callback$/, "");
// ββ Login page βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
app.get("/", (_req, res) => {
const authed = spotify.isAuthenticated();
res.send(`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>spotify-mcp</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
background: #121212;
color: #fff;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.card {
text-align: center;
display: flex;
flex-direction: column;
align-items: center;
gap: 20px;
}
.logo { font-size: 48px; }
h1 { font-size: 22px; font-weight: 700; }
p { color: #a7a7a7; font-size: 14px; }
.btn {
display: inline-block;
background: #1DB954;
color: #000;
font-weight: 700;
font-size: 15px;
padding: 14px 40px;
border-radius: 50px;
text-decoration: none;
letter-spacing: 0.05em;
transition: background 0.15s;
}
.btn:hover { background: #1ed760; }
.status {
font-size: 13px;
color: ${authed ? "#1DB954" : "#a7a7a7"};
}
</style>
</head>
<body>
<div class="card">
<div class="logo">π΅</div>
<h1>spotify-mcp</h1>
<p>Connect your Spotify account to use the MCP player.</p>
${authed
? `<div class="status">β
Connected β <a href="/auth" style="color:#1DB954">re-authenticate</a></div>`
: `<a href="/auth" class="btn">Connect Spotify</a>`
}
</div>
</body>
</html>`);
});
// ββ Spotify OAuth β step 1: redirect to Spotify ββββββββββββββββββββββββββββ
app.get("/auth", (_req, res) => {
const codeVerifier = randomBytes(32).toString("base64url");
const codeChallenge = createHash("sha256").update(codeVerifier).digest("base64url");
const state = randomBytes(16).toString("hex");
pendingAuth = { codeVerifier, state };
const url = new URL("https://accounts.spotify.com/authorize");
url.searchParams.set("client_id", CLIENT_ID);
url.searchParams.set("response_type", "code");
url.searchParams.set("redirect_uri", REDIRECT_URI);
url.searchParams.set("state", state);
url.searchParams.set("scope", SCOPES);
url.searchParams.set("code_challenge_method", "S256");
url.searchParams.set("code_challenge", codeChallenge);
res.redirect(url.toString());
});
// ββ Spotify OAuth β step 2: handle callback ββββββββββββββββββββββββββββββββ
app.get("/auth/callback", async (req, res) => {
try {
const { code, state, error } = req.query as Record<string, string>;
if (error) {
res.status(400).send(`Auth error: ${error}`);
return;
}
if (!pendingAuth || state !== pendingAuth.state || !code) {
res.status(400).send("Invalid state or missing code. Try /auth again.");
return;
}
const { codeVerifier } = pendingAuth;
pendingAuth = null;
const tokenRes = await fetch("https://accounts.spotify.com/api/token", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "authorization_code",
code,
redirect_uri: REDIRECT_URI,
client_id: CLIENT_ID,
code_verifier: codeVerifier,
}),
});
if (!tokenRes.ok) {
const err = await tokenRes.text();
res.status(500).send(`Token exchange failed: ${err}`);
return;
}
const tokens = await tokenRes.json() as {
access_token: string;
refresh_token: string;
expires_in: number;
};
spotify.saveTokens({
access_token: tokens.access_token,
refresh_token: tokens.refresh_token,
expires_at: Date.now() + tokens.expires_in * 1000,
});
res.send(`
<html>
<body style="font-family:sans-serif;text-align:center;padding:60px;background:#121212;color:#1DB954;">
<h1>β
Authenticated!</h1>
<p style="color:#fff;margin-top:12px">Spotify is connected. You can close this tab.</p>
<script>
// Try to close the tab automatically; works if opened via window.open or ui/open-link
setTimeout(() => window.close(), 1500);
</script>
</body>
</html>
`);
} catch (err) {
console.error("Auth callback error:", err);
if (!res.headersSent) {
res.status(500).send("Authentication failed. Please try again via /auth");
}
}
});
// ββ Auth status β polled by the iframe after triggering ui/open-link βββββββββ
app.get("/auth/status", (_req, res) => {
res.json({ authenticated: spotify.isAuthenticated() });
});
// ββ Auth token β used by the Web Playback SDK in the iframe ββββββββββββββββββ
app.get("/auth/token", async (_req, res) => {
if (!spotify.isAuthenticated()) {
res.status(401).json({ error: "Not authenticated" });
return;
}
try {
const access_token = await spotify.getFreshAccessToken();
res.json({ access_token });
} catch (err: any) {
res.status(500).json({ error: err.message });
}
});
// ββ SDK device registry βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// sdk-frame runs as a standalone top-level tab (opened via ui/open-link) so it
// has full Permissions Policy including encrypted-media. It communicates with
// the player UI via these server endpoints instead of postMessage.
// sdk-frame POSTs its device_id here when the SDK player is ready
app.post("/sdk-device", (req, res) => {
_sdkDeviceId = req.body?.device_id ?? null;
res.json({ ok: true });
});
// Player polls this to get the browser device_id
app.get("/sdk-device", (_req, res) => {
res.json({ device_id: _sdkDeviceId });
});
// sdk-frame subscribes here (SSE) to receive instant playback commands from the player
app.get("/sdk-events", (req, res) => {
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
res.write(`data: ${JSON.stringify({ type: "connected" })}\n\n`);
_sdkSseClients.push(res);
req.on("close", () => {
_sdkSseClients = _sdkSseClients.filter(c => c !== res);
if (_sdkSseClients.length === 0) _sdkDeviceId = null;
});
});
// Player POSTs playback commands here; forwarded instantly to sdk-frame via SSE
app.post("/sdk-command", (req, res) => {
const cmd = req.body;
_sdkSseClients.forEach(c => c.write(`data: ${JSON.stringify(cmd)}\n\n`));
res.json({ ok: true });
});
// ββ SDK frame βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Served as a real top-level page (opened via ui/open-link) so the Spotify Web
// Playback SDK has full Permissions Policy access including encrypted-media.
app.get("/sdk-frame", (_req, res) => {
res.setHeader("Content-Type", "text/html");
res.send(`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Claude Spotify Player</title>
<script src="https://sdk.scdn.co/spotify-player.js"></script>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
background: #0a0a0a;
color: #fff;
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.card {
background: #181818;
border-radius: 16px;
padding: 40px 48px;
text-align: center;
max-width: 380px;
width: 100%;
box-shadow: 0 8px 32px rgba(0,0,0,0.5);
}
.logo { font-size: 40px; margin-bottom: 16px; }
h2 { font-size: 18px; font-weight: 600; margin-bottom: 6px; }
.subtitle { font-size: 13px; color: #a7a7a7; margin-bottom: 32px; }
.status-row {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
font-size: 13px;
padding: 12px 20px;
border-radius: 999px;
background: #232323;
margin-bottom: 16px;
}
.dot {
width: 8px; height: 8px; border-radius: 50%;
background: #535353;
transition: background 0.3s;
flex-shrink: 0;
}
.dot.ready { background: #1db954; box-shadow: 0 0 6px #1db954; }
.dot.error { background: #e22134; }
.hint { font-size: 12px; color: #535353; margin-top: 24px; line-height: 1.5; }
</style>
</head>
<body>
<div class="card">
<div class="logo">π΅</div>
<h2>Claude Spotify Player</h2>
<p class="subtitle">Browser audio device</p>
<div class="status-row">
<span class="dot" id="dot"></span>
<span id="status-text">Connecting to Spotifyβ¦</span>
</div>
<p class="hint">This tab provides audio output for the Spotify player.<br>You can minimize it β don't close it.</p>
</div>
<script>
const SERVER = ${JSON.stringify(BASE_URL)};
function setStatus(msg, state) {
document.getElementById('status-text').textContent = msg;
const dot = document.getElementById('dot');
dot.className = 'dot' + (state ? ' ' + state : '');
}
window.onSpotifyWebPlaybackSDKReady = () => {
const player = new Spotify.Player({
name: 'Claude Spotify Player',
getOAuthToken: async (cb) => {
try {
const r = await fetch(SERVER + '/auth/token');
const d = await r.json();
cb(d.access_token);
} catch(e) {
setStatus('Failed to get token', 'error');
console.error('[sdk-frame] token fetch failed', e);
}
},
volume: 0.8,
});
function dispatch(action, extra = {}) {
switch (action) {
case 'pause': player.pause(); break;
case 'resume': player.resume(); break;
case 'next': player.nextTrack(); break;
case 'previous': player.previousTrack(); break;
case 'seek': player.seek(extra.position_ms); break;
case 'volume': player.setVolume(extra.volume / 100); break;
}
}
player.addListener('ready', ({ device_id }) => {
setStatus('Ready Β· browser audio active', 'ready');
// Notify parent iframe (when embedded)
try { window.parent.postMessage({ type: 'BROWSER_DEVICE_READY', device_id }, '*'); } catch(_) {}
});
player.addListener('not_ready', () => {
setStatus('Device went offline', 'error');
try { window.parent.postMessage({ type: 'BROWSER_DEVICE_OFFLINE' }, '*'); } catch(_) {}
});
player.addListener('player_state_changed', async (state) => {
if (!state) return;
// Unlock AudioContext whenever Spotify signals a non-paused state
if (!state.paused) await ensureAudioUnlocked();
const t = state.track_window?.current_track;
try {
window.parent.postMessage({ type: 'SDK_STATE', state: {
paused: state.paused, position: state.position,
shuffle: state.shuffle, repeat_mode: state.repeat_mode,
volume: state.playback_volume,
track: t ? { name: t.name, uri: t.uri, duration_ms: t.duration_ms,
artists: t.artists, album: t.album } : null,
}}, '*');
} catch(_) {}
});
player.addListener('account_error', () => {
setStatus('Spotify Premium required', 'error');
try { window.parent.postMessage({ type: 'SDK_PREMIUM_REQUIRED' }, '*'); } catch(_) {}
});
player.addListener('initialization_error', ({ message }) => setStatus('Error: ' + message, 'error'));
player.addListener('authentication_error', ({ message }) => setStatus('Auth error β please re-authenticate', 'error'));
// Unlock the browser AudioContext on first interaction.
// The SDK uses an internal AudioContext that starts "suspended" when there
// has been no user gesture directly inside this frame. We work around this
// by creating a silent AudioContext and calling resume() β Chrome's
// per-tab sticky activation means this succeeds once the user has clicked
// anywhere in the tab (e.g. the play button in the parent player frame).
let _audioUnlocked = false;
async function ensureAudioUnlocked() {
if (_audioUnlocked) return;
try {
const ctx = new AudioContext();
await ctx.resume();
// Play a silent buffer so the browser marks audio as "user-initiated"
const buf = ctx.createBuffer(1, 1, 22050);
const src = ctx.createBufferSource();
src.buffer = buf;
src.connect(ctx.destination);
src.start(0);
_audioUnlocked = true;
} catch(_) {}
}
player.connect();
window._player = player;
// Accept commands via postMessage from parent iframe
window.addEventListener('message', async (e) => {
const d = e.data;
if (d?.type === 'SDK_COMMAND') {
await ensureAudioUnlocked();
dispatch(d.action, d);
}
});
};
</script>
</body>
</html>`);
});
// ββ MCP endpoint ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// We create a fresh McpServer + transport per request (stateless mode).
// This keeps things simple for a single-user server and avoids session
// management complexity. Each tool call round-trip is self-contained.
app.all("/mcp", async (req, res) => {
try {
const mcpServer = createMcpServer(spotify, BASE_URL);
const transport = new StreamableHTTPServerTransport({
sessionIdGenerator: undefined, // stateless β no session IDs needed
});
// Clean up after the response is done
res.on("finish", async () => {
await transport.close();
await mcpServer.close();
});
await mcpServer.connect(transport);
await transport.handleRequest(req, res, req.body);
} catch (err) {
console.error("MCP request error:", err);
if (!res.headersSent) {
res.status(500).json({ error: "Internal server error" });
}
}
});
return app;
}