@tapedock/mcp 0.0.0-stage → 0.1.1

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/dist/server.js ADDED
@@ -0,0 +1,1068 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import { z } from "zod";
4
+ import { VcrApiError } from "./api/client.js";
5
+ import { AuthRequiredError } from "./auth/credentials.js";
6
+ import { ALL_DOWNLOAD_CATEGORIES, } from "./downloads/manager.js";
7
+ import { buildInviteBlurb, buildSessionIcs, formatBytes, parseIsoToMs, parseTimecodeToMs, } from "./lib/format.js";
8
+ // Keep runtime dependency-free from raw-TS @vcr/protocol while enforcing compile-time parity
9
+ const QUALITY_TIERS = ["1080p", "4k"];
10
+ const MARKER_COLORS = ["Blue", "Green", "Red", "Yellow"];
11
+ const QualityTierSchema = z.enum(QUALITY_TIERS);
12
+ const STALE_PROCESSING_JOB_MS = 15 * 60 * 1000;
13
+ const MarkerColorSchema = z.enum(MARKER_COLORS);
14
+ function okResult(payload) {
15
+ return {
16
+ content: [{ type: "text", text: JSON.stringify(payload, null, 2) }],
17
+ structuredContent: payload,
18
+ };
19
+ }
20
+ function errorResult(err) {
21
+ if (err instanceof AuthRequiredError) {
22
+ return {
23
+ isError: true,
24
+ content: [{ type: "text", text: err.message }],
25
+ };
26
+ }
27
+ if (err instanceof VcrApiError) {
28
+ const scopeHint = err.requiredScope
29
+ ? ` (requires OAuth scope "${err.requiredScope}" — re-run \`vcr-mcp login\` without \`--read-only\`)`
30
+ : "";
31
+ return {
32
+ isError: true,
33
+ content: [{ type: "text", text: `API error (${err.status}): ${err.message}${scopeHint}` }],
34
+ };
35
+ }
36
+ return {
37
+ isError: true,
38
+ content: [{ type: "text", text: err instanceof Error ? err.message : String(err) }],
39
+ };
40
+ }
41
+ async function runTool(fn) {
42
+ try {
43
+ return okResult(await fn());
44
+ }
45
+ catch (err) {
46
+ return errorResult(err);
47
+ }
48
+ }
49
+ const InviteOutputSchema = z.object({
50
+ id: z.string(),
51
+ guestName: z.string().nullable(),
52
+ inviteUrl: z.string(),
53
+ createdAt: z.number(),
54
+ blurb: z.string().optional(),
55
+ });
56
+ const RoomOutputSchema = z.object({
57
+ id: z.string(),
58
+ slug: z.string(),
59
+ name: z.string(),
60
+ isLocked: z.boolean(),
61
+ defaultQuality: QualityTierSchema,
62
+ archivedAt: z.number().nullable(),
63
+ createdAt: z.number(),
64
+ hostUrl: z.string(),
65
+ guestInviteUrl: z.string().nullable(),
66
+ });
67
+ const DownloadFileOutputSchema = z.object({
68
+ name: z.string(),
69
+ category: z.enum(["bundle", "audio", "video", "screen"]),
70
+ byteSize: z.number(),
71
+ downloadedBytes: z.number(),
72
+ status: z.enum(["pending", "downloading", "completed", "skipped", "failed"]),
73
+ localPath: z.string(),
74
+ error: z.string().optional(),
75
+ });
76
+ const DownloadJobOutputSchema = z.object({
77
+ downloadId: z.string(),
78
+ sessionId: z.string(),
79
+ sessionTitle: z.string(),
80
+ mode: z.enum(["foreground", "background", "dry_run"]),
81
+ status: z.enum(["running", "completed", "failed", "dry_run"]),
82
+ targetDir: z.string(),
83
+ totalBytes: z.number(),
84
+ totalSizeFormatted: z.string(),
85
+ remainingBytes: z.number(),
86
+ remainingSizeFormatted: z.string(),
87
+ downloadedBytes: z.number(),
88
+ startedAtMs: z.number(),
89
+ completedAtMs: z.number().nullable(),
90
+ files: z.array(DownloadFileOutputSchema),
91
+ resolveOtioPath: z.string().optional(),
92
+ error: z.string().optional(),
93
+ });
94
+ function formatJobOutput(job) {
95
+ return {
96
+ ...job,
97
+ totalSizeFormatted: formatBytes(job.totalBytes),
98
+ remainingSizeFormatted: formatBytes(job.remainingBytes),
99
+ };
100
+ }
101
+ const PACKAGE_JSON = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
102
+ export const MCP_SERVER_VERSION = PACKAGE_JSON.version ?? "0.0.0";
103
+ export function createVcrMcpServer(deps) {
104
+ const { api, downloads } = deps;
105
+ const server = new McpServer({
106
+ name: "video-call-recorder",
107
+ version: MCP_SERVER_VERSION,
108
+ });
109
+ // 1. get_host_status
110
+ server.registerTool("get_host_status", {
111
+ title: "Get Host Status",
112
+ description: "Inspect the authenticated Host account, server origin, granted OAuth scopes, Room/Session counts, and current monthly Usage Ledger summary.",
113
+ inputSchema: {},
114
+ outputSchema: {
115
+ origin: z.string(),
116
+ host: z.object({
117
+ accountId: z.string(),
118
+ email: z.string(),
119
+ name: z.string(),
120
+ isFreeAccount: z.boolean(),
121
+ }),
122
+ scopes: z.array(z.string()),
123
+ counts: z.object({
124
+ activeRooms: z.number(),
125
+ archivedRooms: z.number(),
126
+ plannedSessions: z.number(),
127
+ recordedSessions: z.number(),
128
+ }),
129
+ usageSummary: z.object({
130
+ monthlyCogsUsd: z.number(),
131
+ totalSessions: z.number(),
132
+ }),
133
+ },
134
+ annotations: {
135
+ title: "Get Host Status",
136
+ readOnlyHint: true,
137
+ destructiveHint: false,
138
+ idempotentHint: true,
139
+ openWorldHint: true,
140
+ },
141
+ }, async () => runTool(async () => {
142
+ const [me, roomsResp, sessionsResp] = await Promise.all([
143
+ api.getAuthMe(),
144
+ api.listRooms(),
145
+ api.listSessions(),
146
+ ]);
147
+ if (!me.authenticated || !me.user) {
148
+ throw new AuthRequiredError(api.origin);
149
+ }
150
+ const activeRooms = roomsResp.rooms.filter((r) => !r.archivedAt).length;
151
+ const archivedRooms = roomsResp.rooms.length - activeRooms;
152
+ return {
153
+ origin: api.origin,
154
+ host: {
155
+ accountId: me.user.accountId,
156
+ email: me.user.email,
157
+ name: me.user.name,
158
+ isFreeAccount: Boolean(me.user.isFreeAccount),
159
+ },
160
+ scopes: me.scopes ?? [],
161
+ counts: {
162
+ activeRooms,
163
+ archivedRooms,
164
+ plannedSessions: sessionsResp.plannedSessions.length,
165
+ recordedSessions: sessionsResp.sessions.length,
166
+ },
167
+ usageSummary: {
168
+ monthlyCogsUsd: sessionsResp.usageSummary.monthlyCogsUsd,
169
+ totalSessions: sessionsResp.usageSummary.totalSessions,
170
+ },
171
+ };
172
+ }));
173
+ // 2. list_rooms
174
+ server.registerTool("list_rooms", {
175
+ title: "List Rooms",
176
+ description: "List persistent Rooms owned by the Host, including Host enter URLs and reusable Guest invite URLs.",
177
+ inputSchema: {
178
+ includeArchived: z
179
+ .boolean()
180
+ .default(false)
181
+ .describe("Include archived Rooms in the result."),
182
+ },
183
+ outputSchema: {
184
+ rooms: z.array(RoomOutputSchema),
185
+ },
186
+ annotations: {
187
+ title: "List Rooms",
188
+ readOnlyHint: true,
189
+ destructiveHint: false,
190
+ idempotentHint: true,
191
+ openWorldHint: true,
192
+ },
193
+ }, async ({ includeArchived }) => runTool(async () => {
194
+ const resp = await api.listRooms();
195
+ const filtered = includeArchived
196
+ ? resp.rooms
197
+ : resp.rooms.filter((r) => !r.archivedAt);
198
+ return {
199
+ rooms: filtered.map((r) => ({
200
+ id: r.id,
201
+ slug: r.slug,
202
+ name: r.name,
203
+ isLocked: r.isLocked,
204
+ defaultQuality: r.defaultQuality,
205
+ archivedAt: r.archivedAt ?? null,
206
+ createdAt: r.createdAt,
207
+ hostUrl: `${api.origin}/host/room/${r.id}`,
208
+ guestInviteUrl: r.inviteUrl ?? null,
209
+ })),
210
+ };
211
+ }));
212
+ // 3. create_room
213
+ server.registerTool("create_room", {
214
+ title: "Create Room",
215
+ description: "Create a new persistent Room with a reusable Guest invite link.",
216
+ inputSchema: {
217
+ name: z.string().trim().min(1).max(100).describe("Display name of the Room."),
218
+ defaultQuality: QualityTierSchema.default("1080p").describe("Default local recording video quality for Sessions in this Room."),
219
+ },
220
+ outputSchema: {
221
+ room: RoomOutputSchema,
222
+ },
223
+ annotations: {
224
+ title: "Create Room",
225
+ readOnlyHint: false,
226
+ destructiveHint: false,
227
+ idempotentHint: false,
228
+ openWorldHint: true,
229
+ },
230
+ }, async ({ name, defaultQuality }) => runTool(async () => {
231
+ const resp = await api.createRoom({ name, defaultQuality });
232
+ const r = resp.room;
233
+ return {
234
+ room: {
235
+ id: r.id,
236
+ slug: r.slug,
237
+ name: r.name,
238
+ isLocked: r.isLocked,
239
+ defaultQuality: r.defaultQuality,
240
+ archivedAt: r.archivedAt ?? null,
241
+ createdAt: r.createdAt,
242
+ hostUrl: `${api.origin}/host/room/${r.id}`,
243
+ guestInviteUrl: r.inviteUrl ?? null,
244
+ },
245
+ };
246
+ }));
247
+ // 4. update_room
248
+ server.registerTool("update_room", {
249
+ title: "Update Room",
250
+ description: "Lock/unlock a Room, archive/restore it, and/or rotate its reusable Guest invite link.",
251
+ inputSchema: {
252
+ roomId: z.string().min(1).describe("Room ID (e.g. room_...)."),
253
+ lock: z.boolean().optional().describe("Set Room lock state (true blocks new Guests)."),
254
+ archive: z.boolean().optional().describe("Archive (true) or restore (false) the Room."),
255
+ rotateInviteLink: z
256
+ .boolean()
257
+ .optional()
258
+ .describe("Generate a new reusable Guest invite link (revokes the previous Room link)."),
259
+ },
260
+ outputSchema: {
261
+ roomId: z.string(),
262
+ isLocked: z.boolean().optional(),
263
+ archivedAt: z.number().nullable().optional(),
264
+ guestInviteUrl: z.string().optional(),
265
+ },
266
+ annotations: {
267
+ title: "Update Room",
268
+ readOnlyHint: false,
269
+ destructiveHint: false,
270
+ idempotentHint: true,
271
+ openWorldHint: true,
272
+ },
273
+ }, async ({ roomId, lock, archive, rotateInviteLink }) => runTool(async () => {
274
+ if (lock === undefined && archive === undefined && !rotateInviteLink) {
275
+ throw new Error("Provide at least one of: lock, archive, or rotateInviteLink.");
276
+ }
277
+ const out = { roomId };
278
+ if (lock !== undefined) {
279
+ const r = await api.setRoomLock(roomId, lock);
280
+ out.isLocked = r.isLocked;
281
+ }
282
+ if (archive !== undefined) {
283
+ const r = await api.setRoomArchived(roomId, archive);
284
+ out.archivedAt = r.archivedAt;
285
+ }
286
+ if (rotateInviteLink) {
287
+ const r = await api.rotateRoomLink(roomId);
288
+ out.guestInviteUrl = r.inviteUrl;
289
+ }
290
+ return out;
291
+ }));
292
+ // 5. plan_session
293
+ server.registerTool("plan_session", {
294
+ title: "Plan Session",
295
+ description: "Plan an upcoming recording Session inside a Room (or create a new Room), minting a generic Session Invite plus optional personalized Guest invites, ready-to-paste invite blurbs, and optional .ics calendar text.",
296
+ inputSchema: {
297
+ title: z.string().trim().min(1).max(160).describe("Title of the planned Session."),
298
+ roomId: z
299
+ .string()
300
+ .optional()
301
+ .describe("Existing active Room ID. Optional if you only have one active Room or pass newRoomName."),
302
+ newRoomName: z
303
+ .string()
304
+ .trim()
305
+ .min(1)
306
+ .max(100)
307
+ .optional()
308
+ .describe("Create a new Room with this name for the Session."),
309
+ scheduledStartIso: z
310
+ .string()
311
+ .optional()
312
+ .describe("Optional ISO-8601 start timestamp (e.g. '2026-12-01T17:00:00Z')."),
313
+ guestNames: z
314
+ .array(z.string().trim().min(1).max(80))
315
+ .max(12)
316
+ .optional()
317
+ .describe("Optional list of Guest names to mint personalized Session Invite links for."),
318
+ includeIcs: z
319
+ .boolean()
320
+ .default(false)
321
+ .describe("Include an .ics calendar invite string (requires scheduledStartIso)."),
322
+ },
323
+ outputSchema: {
324
+ session: z.object({
325
+ id: z.string(),
326
+ roomId: z.string(),
327
+ title: z.string(),
328
+ qualityTier: QualityTierSchema,
329
+ status: z.literal("planned"),
330
+ scheduledStartAtMs: z.number().nullable(),
331
+ scheduledStartIso: z.string().nullable(),
332
+ hostUrl: z.string(),
333
+ genericInvite: InviteOutputSchema.nullable(),
334
+ guestInvites: z.array(InviteOutputSchema),
335
+ }),
336
+ ics: z.string().nullable(),
337
+ },
338
+ annotations: {
339
+ title: "Plan Session",
340
+ readOnlyHint: false,
341
+ destructiveHint: false,
342
+ idempotentHint: false,
343
+ openWorldHint: true,
344
+ },
345
+ }, async ({ title, roomId, newRoomName, scheduledStartIso, guestNames, includeIcs }) => runTool(async () => {
346
+ const scheduledStartAtMs = scheduledStartIso
347
+ ? parseIsoToMs(scheduledStartIso, "scheduledStartIso")
348
+ : null;
349
+ const [{ session }, me, roomsResp] = await Promise.all([
350
+ api.planSession({
351
+ roomId,
352
+ newRoomName,
353
+ title,
354
+ scheduledStartAtMs,
355
+ guestNames,
356
+ }),
357
+ api.getAuthMe().catch(() => null),
358
+ includeIcs ? api.listRooms().catch(() => null) : Promise.resolve(null),
359
+ ]);
360
+ const hostName = me?.user?.name?.trim() || "Host";
361
+ const roomName = roomsResp?.rooms.find((r) => r.id === session.roomId)?.name ||
362
+ newRoomName ||
363
+ "Recording Room";
364
+ const genericInvite = session.genericInvite
365
+ ? {
366
+ ...session.genericInvite,
367
+ blurb: buildInviteBlurb({
368
+ sessionTitle: session.title,
369
+ hostName,
370
+ guestName: null,
371
+ scheduledStartAtMs: session.scheduledStartAtMs,
372
+ inviteUrl: session.genericInvite.inviteUrl,
373
+ }),
374
+ }
375
+ : null;
376
+ const guestInvites = session.guestInvites.map((inv) => ({
377
+ ...inv,
378
+ blurb: buildInviteBlurb({
379
+ sessionTitle: session.title,
380
+ hostName,
381
+ guestName: inv.guestName,
382
+ scheduledStartAtMs: session.scheduledStartAtMs,
383
+ inviteUrl: inv.inviteUrl,
384
+ }),
385
+ }));
386
+ const ics = includeIcs && session.scheduledStartAtMs && genericInvite
387
+ ? buildSessionIcs({
388
+ sessionId: session.id,
389
+ sessionTitle: session.title,
390
+ hostName,
391
+ roomName,
392
+ scheduledStartAtMs: session.scheduledStartAtMs,
393
+ inviteUrl: genericInvite.inviteUrl,
394
+ })
395
+ : null;
396
+ return {
397
+ session: {
398
+ id: session.id,
399
+ roomId: session.roomId,
400
+ title: session.title,
401
+ qualityTier: session.qualityTier,
402
+ status: "planned",
403
+ scheduledStartAtMs: session.scheduledStartAtMs,
404
+ scheduledStartIso: session.scheduledStartAtMs
405
+ ? new Date(session.scheduledStartAtMs).toISOString()
406
+ : null,
407
+ hostUrl: `${api.origin}/host/room/${session.roomId}/session/${session.id}`,
408
+ genericInvite,
409
+ guestInvites,
410
+ },
411
+ ics,
412
+ };
413
+ }));
414
+ // 6. update_planned_session
415
+ server.registerTool("update_planned_session", {
416
+ title: "Update Planned Session",
417
+ description: "Update the title and/or scheduled start time of an upcoming planned Session.",
418
+ inputSchema: {
419
+ sessionId: z.string().min(1).describe("Planned Session ID."),
420
+ title: z.string().trim().min(1).max(160).optional().describe("New Session title."),
421
+ scheduledStartIso: z
422
+ .string()
423
+ .nullable()
424
+ .optional()
425
+ .describe("New ISO-8601 timestamp, or null to clear the scheduled time."),
426
+ },
427
+ outputSchema: {
428
+ ok: z.boolean(),
429
+ sessionId: z.string(),
430
+ title: z.string(),
431
+ scheduledStartAtMs: z.number().nullable(),
432
+ scheduledStartIso: z.string().nullable(),
433
+ },
434
+ annotations: {
435
+ title: "Update Planned Session",
436
+ readOnlyHint: false,
437
+ destructiveHint: false,
438
+ idempotentHint: true,
439
+ openWorldHint: true,
440
+ },
441
+ }, async ({ sessionId, title, scheduledStartIso }) => runTool(async () => {
442
+ if (title === undefined && scheduledStartIso === undefined) {
443
+ throw new Error("Provide title and/or scheduledStartIso.");
444
+ }
445
+ const payload = {};
446
+ if (title !== undefined)
447
+ payload.title = title;
448
+ if (scheduledStartIso !== undefined) {
449
+ payload.scheduledStartAtMs =
450
+ scheduledStartIso === null ? null : parseIsoToMs(scheduledStartIso);
451
+ }
452
+ const res = await api.updatePlannedSession(sessionId, payload);
453
+ return {
454
+ ok: res.ok,
455
+ sessionId,
456
+ title: res.title,
457
+ scheduledStartAtMs: res.scheduledStartAtMs,
458
+ scheduledStartIso: res.scheduledStartAtMs
459
+ ? new Date(res.scheduledStartAtMs).toISOString()
460
+ : null,
461
+ };
462
+ }));
463
+ // 7. cancel_planned_session
464
+ server.registerTool("cancel_planned_session", {
465
+ title: "Cancel Planned Session",
466
+ description: "Cancel an upcoming planned Session and clear any staged Room state.",
467
+ inputSchema: {
468
+ sessionId: z.string().min(1).describe("Planned Session ID to cancel."),
469
+ },
470
+ outputSchema: {
471
+ ok: z.boolean(),
472
+ sessionId: z.string(),
473
+ },
474
+ annotations: {
475
+ title: "Cancel Planned Session",
476
+ readOnlyHint: false,
477
+ destructiveHint: true,
478
+ idempotentHint: true,
479
+ openWorldHint: true,
480
+ },
481
+ }, async ({ sessionId }) => runTool(async () => {
482
+ const res = await api.cancelPlannedSession(sessionId);
483
+ return { ok: res.ok, sessionId };
484
+ }));
485
+ // 8. manage_session_invites
486
+ server.registerTool("manage_session_invites", {
487
+ title: "Manage Session Invites",
488
+ description: "Add a personalized Guest Session Invite, rename a Guest invite, rotate an invite link, or revoke an invite on a planned Session.",
489
+ inputSchema: {
490
+ action: z
491
+ .enum(["add", "rename", "rotate", "revoke"])
492
+ .describe("Invite operation to perform."),
493
+ sessionId: z
494
+ .string()
495
+ .optional()
496
+ .describe("Planned Session ID (required for action='add')."),
497
+ inviteId: z
498
+ .string()
499
+ .optional()
500
+ .describe("Session Invite ID (required for 'rename', 'rotate', 'revoke')."),
501
+ guestName: z
502
+ .string()
503
+ .trim()
504
+ .min(1)
505
+ .max(80)
506
+ .optional()
507
+ .describe("Guest display name (required for 'add' and 'rename')."),
508
+ },
509
+ outputSchema: {
510
+ action: z.enum(["add", "rename", "rotate", "revoke"]),
511
+ ok: z.boolean(),
512
+ inviteId: z.string().optional(),
513
+ guestName: z.string().optional(),
514
+ inviteUrl: z.string().optional(),
515
+ blurb: z.string().optional(),
516
+ },
517
+ annotations: {
518
+ title: "Manage Session Invites",
519
+ readOnlyHint: false,
520
+ destructiveHint: false,
521
+ idempotentHint: false,
522
+ openWorldHint: true,
523
+ },
524
+ }, async ({ action, sessionId, inviteId, guestName }) => runTool(async () => {
525
+ if (action === "add") {
526
+ if (!sessionId || !guestName) {
527
+ throw new Error("action='add' requires both sessionId and guestName.");
528
+ }
529
+ const [{ invite }, detail, me] = await Promise.all([
530
+ api.addSessionInvite(sessionId, guestName),
531
+ api.getSession(sessionId).catch(() => null),
532
+ api.getAuthMe().catch(() => null),
533
+ ]);
534
+ return {
535
+ action,
536
+ ok: true,
537
+ inviteId: invite.id,
538
+ guestName: invite.guestName ?? guestName,
539
+ inviteUrl: invite.inviteUrl,
540
+ blurb: buildInviteBlurb({
541
+ sessionTitle: detail?.session.title || "Recording Session",
542
+ hostName: me?.user?.name?.trim() || "Host",
543
+ guestName: invite.guestName,
544
+ scheduledStartAtMs: detail?.session.scheduledStartAtMs ?? null,
545
+ inviteUrl: invite.inviteUrl,
546
+ }),
547
+ };
548
+ }
549
+ if (!inviteId) {
550
+ throw new Error(`action='${action}' requires inviteId.`);
551
+ }
552
+ if (action === "rename") {
553
+ if (!guestName)
554
+ throw new Error("action='rename' requires guestName.");
555
+ const res = await api.renameSessionInvite(inviteId, guestName);
556
+ return { action, ok: res.ok, inviteId, guestName: res.guestName };
557
+ }
558
+ if (action === "rotate") {
559
+ const [res, me] = await Promise.all([
560
+ api.rotateSessionInvite(inviteId),
561
+ api.getAuthMe().catch(() => null),
562
+ ]);
563
+ return {
564
+ action,
565
+ ok: res.ok,
566
+ inviteId,
567
+ ...(res.guestName ? { guestName: res.guestName } : {}),
568
+ inviteUrl: res.inviteUrl,
569
+ blurb: buildInviteBlurb({
570
+ sessionTitle: res.sessionTitle || "Recording Session",
571
+ hostName: me?.user?.name?.trim() || "Host",
572
+ guestName: res.guestName ?? null,
573
+ scheduledStartAtMs: res.scheduledStartAtMs ?? null,
574
+ inviteUrl: res.inviteUrl,
575
+ }),
576
+ };
577
+ }
578
+ const res = await api.revokeSessionInvite(inviteId);
579
+ return { action, ok: res.ok, inviteId };
580
+ }));
581
+ // 9. list_sessions
582
+ server.registerTool("list_sessions", {
583
+ title: "List Sessions",
584
+ description: "List upcoming planned Sessions and/or recorded Sessions, with optional Room/status filters and Usage Ledger summary.",
585
+ inputSchema: {
586
+ filter: z
587
+ .enum(["all", "planned", "recorded"])
588
+ .default("all")
589
+ .describe("Return all Sessions, only upcoming planned Sessions, or only recorded Sessions."),
590
+ roomId: z.string().optional().describe("Filter by Room ID."),
591
+ status: z
592
+ .string()
593
+ .optional()
594
+ .describe("Filter recorded Sessions by exact status (e.g. 'ready', 'processing', 'uploading')."),
595
+ limit: z.number().int().min(1).max(100).default(25).describe("Maximum Sessions per list."),
596
+ },
597
+ outputSchema: {
598
+ plannedSessions: z.array(z.object({
599
+ id: z.string(),
600
+ roomId: z.string(),
601
+ title: z.string(),
602
+ qualityTier: QualityTierSchema,
603
+ scheduledStartAtMs: z.number().nullable(),
604
+ scheduledStartIso: z.string().nullable(),
605
+ hostUrl: z.string(),
606
+ genericInviteUrl: z.string().nullable(),
607
+ guestInviteCount: z.number(),
608
+ })),
609
+ recordedSessions: z.array(z.object({
610
+ id: z.string(),
611
+ roomId: z.string(),
612
+ title: z.string(),
613
+ qualityTier: QualityTierSchema,
614
+ status: z.string(),
615
+ startedAtMs: z.number(),
616
+ durationMs: z.number(),
617
+ mediaDeletedAt: z.number().nullable(),
618
+ syncQaPass: z.boolean().nullable(),
619
+ })),
620
+ usageSummary: z.object({
621
+ monthlyCogsUsd: z.number(),
622
+ totalSessions: z.number(),
623
+ }),
624
+ },
625
+ annotations: {
626
+ title: "List Sessions",
627
+ readOnlyHint: true,
628
+ destructiveHint: false,
629
+ idempotentHint: true,
630
+ openWorldHint: true,
631
+ },
632
+ }, async ({ filter, roomId, status, limit }) => runTool(async () => {
633
+ const resp = await api.listSessions();
634
+ const planned = filter === "recorded"
635
+ ? []
636
+ : resp.plannedSessions
637
+ .filter((p) => !roomId || p.roomId === roomId)
638
+ .slice(0, limit)
639
+ .map((p) => ({
640
+ id: p.id,
641
+ roomId: p.roomId,
642
+ title: p.title,
643
+ qualityTier: p.qualityTier,
644
+ scheduledStartAtMs: p.scheduledStartAtMs,
645
+ scheduledStartIso: p.scheduledStartAtMs
646
+ ? new Date(p.scheduledStartAtMs).toISOString()
647
+ : null,
648
+ hostUrl: `${api.origin}/host/room/${p.roomId}/session/${p.id}`,
649
+ genericInviteUrl: p.genericInvite?.inviteUrl ?? null,
650
+ guestInviteCount: p.guestInvites.length,
651
+ }));
652
+ const recorded = filter === "planned"
653
+ ? []
654
+ : resp.sessions
655
+ .filter((s) => (!roomId || s.roomId === roomId) && (!status || s.status === status))
656
+ .slice(0, limit)
657
+ .map((s) => ({
658
+ id: s.id,
659
+ roomId: s.roomId,
660
+ title: s.title,
661
+ qualityTier: s.qualityTier,
662
+ status: s.status,
663
+ startedAtMs: s.startedAtMs,
664
+ durationMs: s.durationMs,
665
+ mediaDeletedAt: s.mediaDeletedAt,
666
+ syncQaPass: s.syncQaPass,
667
+ }));
668
+ return {
669
+ plannedSessions: planned,
670
+ recordedSessions: recorded,
671
+ usageSummary: {
672
+ monthlyCogsUsd: resp.usageSummary.monthlyCogsUsd,
673
+ totalSessions: resp.usageSummary.totalSessions,
674
+ },
675
+ };
676
+ }));
677
+ // 10. get_session
678
+ server.registerTool("get_session", {
679
+ title: "Get Session Details",
680
+ description: "Inspect a single planned or recorded Session: status, Participants, Markers (with NDF timecodes), Sync Report, post-processing jobs, Usage Ledger, Session Invites (if planned), and export file inventory. Raw 1-hour presigned R2 URLs are omitted by default.",
681
+ inputSchema: {
682
+ sessionId: z.string().min(1).describe("Session ID (e.g. sess_...)."),
683
+ includeDownloadUrls: z
684
+ .boolean()
685
+ .default(false)
686
+ .describe("Include raw 1-hour presigned R2 download URLs (omit unless explicitly needed)."),
687
+ },
688
+ outputSchema: {
689
+ session: z.object({
690
+ id: z.string(),
691
+ roomId: z.string(),
692
+ title: z.string(),
693
+ qualityTier: QualityTierSchema,
694
+ status: z.string(),
695
+ scheduledStartAtMs: z.number().nullable(),
696
+ startedAtMs: z.number(),
697
+ endedAtMs: z.number().nullable(),
698
+ durationMs: z.number(),
699
+ mediaDeletedAt: z.number().nullable(),
700
+ syncQaPass: z.boolean().nullable(),
701
+ }),
702
+ guidance: z.string(),
703
+ participants: z.array(z.object({
704
+ id: z.string(),
705
+ participantId: z.string(),
706
+ displayName: z.string(),
707
+ role: z.string(),
708
+ })),
709
+ markers: z.array(z.object({
710
+ id: z.string(),
711
+ timeMs: z.number(),
712
+ timecode: z.string(),
713
+ color: MarkerColorSchema,
714
+ label: z.string(),
715
+ note: z.string(),
716
+ })),
717
+ jobs: z.array(z.object({
718
+ id: z.string(),
719
+ status: z.string(),
720
+ attempt: z.number(),
721
+ errorMessage: z.string().nullable(),
722
+ startedAt: z.number(),
723
+ completedAt: z.number().nullable(),
724
+ })),
725
+ ledger: z.array(z.object({
726
+ qualityTier: z.string(),
727
+ sessionDurationMs: z.number(),
728
+ recordedParticipantMs: z.number(),
729
+ rawBytesUploaded: z.number(),
730
+ exportBytesGenerated: z.number(),
731
+ estimatedCogsUsd: z.number(),
732
+ })),
733
+ syncReport: z.unknown().nullable(),
734
+ genericInvite: InviteOutputSchema.nullable().optional(),
735
+ guestInvites: z.array(InviteOutputSchema).optional(),
736
+ totalExportBytes: z.number(),
737
+ totalExportSizeFormatted: z.string(),
738
+ files: z.array(z.object({
739
+ name: z.string(),
740
+ category: z.enum(["bundle", "audio", "video", "screen"]),
741
+ byteSize: z.number(),
742
+ sizeFormatted: z.string(),
743
+ downloadUrl: z.string().optional(),
744
+ })),
745
+ },
746
+ annotations: {
747
+ title: "Get Session Details",
748
+ readOnlyHint: true,
749
+ destructiveHint: false,
750
+ idempotentHint: true,
751
+ openWorldHint: true,
752
+ },
753
+ }, async ({ sessionId, includeDownloadUrls }) => runTool(async () => {
754
+ const detail = await api.getSession(sessionId);
755
+ const s = detail.session;
756
+ const totalExportBytes = detail.files.reduce((sum, f) => sum + f.byteSize, 0);
757
+ let guidance = "Session exports are ready. Use download_session to save Tracks locally.";
758
+ if (s.mediaDeletedAt) {
759
+ guidance = "Media files for this Session were permanently deleted; only metadata and Markers remain.";
760
+ }
761
+ else if (s.status === "planned") {
762
+ guidance = "Session is planned. Share Session Invite links or enter the Room as Host to start recording.";
763
+ }
764
+ else if (s.status === "cancelled") {
765
+ guidance = "This planned Session was cancelled.";
766
+ }
767
+ else if (s.status === "recording") {
768
+ guidance = "Session is currently recording live.";
769
+ }
770
+ else if (s.status === "uploading") {
771
+ guidance =
772
+ "Tracks are still uploading. Poll get_session again shortly, or call process_session_now to process available Tracks early.";
773
+ }
774
+ else if (s.status === "awaiting_unlock") {
775
+ guidance =
776
+ "All raw Tracks are uploaded and awaiting Host unlock in the Dashboard (via Recording Credit or Pay-As-You-Go). MCP agents cannot initiate payments — share the Dashboard link with the Host.";
777
+ }
778
+ else if (s.status === "processing") {
779
+ const latestJob = detail.jobs[0];
780
+ const runningMs = latestJob ? Date.now() - latestJob.startedAt : 0;
781
+ if (latestJob && runningMs >= STALE_PROCESSING_JOB_MS && detail.files.length === 0) {
782
+ const minutes = Math.floor(runningMs / 60_000);
783
+ guidance = `Post-processing job ${latestJob.id} has been running for ${minutes} minutes without finishing (normal runs take 1–5 minutes). The remote Modal worker may have timed out or hit a billing/capacity limit. Call process_session_now to retry, or check the Modal logs for this job.`;
784
+ }
785
+ else {
786
+ guidance =
787
+ "Modal FFmpeg post-processing is running (typically 1–5 minutes). Poll get_session again until status is 'ready' or 'ready_partial'.";
788
+ }
789
+ }
790
+ else if (s.status === "ready" || s.status === "ready_partial") {
791
+ guidance = [
792
+ s.status === "ready_partial"
793
+ ? "Session exports are ready, but some Tracks failed to conform (see syncReport.tracks)."
794
+ : "Session exports are ready.",
795
+ "Plan edits from syncReport: activeSpeechRanges and liveVideoRanges for the rough cut, integratedLufs and truePeakDbfs for loudness, warnings for sync or capture problems, and screenClips (chronological) for screen-share inserts.",
796
+ 'Call download_session with categories: ["bundle", "audio"] first to transcribe and plan the cut before pulling multi-GB video.',
797
+ "download_session also writes session.resolve.otio with absolute local paths for one-click DaVinci Resolve import (File → Import → Timeline).",
798
+ ].join(" ");
799
+ }
800
+ else if (s.status === "failed") {
801
+ guidance =
802
+ "Post-processing failed. Inspect jobs[].errorMessage and call process_session_now to retry.";
803
+ }
804
+ return {
805
+ session: {
806
+ id: s.id,
807
+ roomId: s.roomId,
808
+ title: s.title,
809
+ qualityTier: s.qualityTier,
810
+ status: s.status,
811
+ scheduledStartAtMs: s.scheduledStartAtMs ?? null,
812
+ startedAtMs: s.startedAtMs,
813
+ endedAtMs: s.endedAtMs,
814
+ durationMs: s.durationMs,
815
+ mediaDeletedAt: s.mediaDeletedAt,
816
+ syncQaPass: s.syncQaPass,
817
+ },
818
+ guidance,
819
+ participants: detail.participants.map((p) => ({
820
+ id: p.id,
821
+ participantId: p.participantId,
822
+ displayName: p.displayName,
823
+ role: p.role,
824
+ })),
825
+ markers: detail.markers.map((m) => ({
826
+ id: m.id,
827
+ timeMs: m.timeMs,
828
+ timecode: m.timecode,
829
+ color: m.color,
830
+ label: m.label,
831
+ note: m.note,
832
+ })),
833
+ jobs: detail.jobs.map((j) => ({
834
+ id: j.id,
835
+ status: j.status,
836
+ attempt: j.attempt,
837
+ errorMessage: j.errorMessage,
838
+ startedAt: j.startedAt,
839
+ completedAt: j.completedAt,
840
+ })),
841
+ ledger: detail.ledger.map((l) => ({
842
+ qualityTier: l.qualityTier,
843
+ sessionDurationMs: l.sessionDurationMs,
844
+ recordedParticipantMs: l.recordedParticipantMs,
845
+ rawBytesUploaded: l.rawBytesUploaded,
846
+ exportBytesGenerated: l.exportBytesGenerated,
847
+ estimatedCogsUsd: l.estimatedCogsUsd,
848
+ })),
849
+ syncReport: detail.syncReport,
850
+ ...(detail.genericInvite !== undefined ? { genericInvite: detail.genericInvite } : {}),
851
+ ...(detail.guestInvites !== undefined ? { guestInvites: detail.guestInvites } : {}),
852
+ totalExportBytes,
853
+ totalExportSizeFormatted: formatBytes(totalExportBytes),
854
+ files: detail.files.map((f) => ({
855
+ name: f.name,
856
+ category: f.category,
857
+ byteSize: f.byteSize,
858
+ sizeFormatted: formatBytes(f.byteSize),
859
+ ...(includeDownloadUrls ? { downloadUrl: f.downloadUrl } : {}),
860
+ })),
861
+ };
862
+ }));
863
+ // 11. add_marker
864
+ server.registerTool("add_marker", {
865
+ title: "Add Marker",
866
+ description: "Add a timestamped Marker to a recorded Session (accepts timecode like '00:14:32' or timeMs) and instantly regenerate session.otio, markers.edl, and markers.json.",
867
+ inputSchema: {
868
+ sessionId: z.string().min(1).describe("Recorded Session ID."),
869
+ timeMs: z
870
+ .number()
871
+ .int()
872
+ .min(0)
873
+ .optional()
874
+ .describe("Timestamp in milliseconds from 00:00:00. Provide either timeMs or timecode."),
875
+ timecode: z
876
+ .string()
877
+ .optional()
878
+ .describe("Human-readable timestamp ('HH:MM:SS', 'MM:SS', or seconds)."),
879
+ label: z.string().trim().min(1).max(160).describe("Short Marker label."),
880
+ color: MarkerColorSchema.default("Blue").describe("Timeline Marker color (Blue=Highlight, Green=Quote, Red=Cut, Yellow=Chapter)."),
881
+ note: z.string().max(1000).default("").describe("Optional longer editorial note."),
882
+ },
883
+ outputSchema: {
884
+ ok: z.boolean(),
885
+ id: z.string(),
886
+ timeMs: z.number(),
887
+ },
888
+ annotations: {
889
+ title: "Add Marker",
890
+ readOnlyHint: false,
891
+ destructiveHint: false,
892
+ idempotentHint: false,
893
+ openWorldHint: true,
894
+ },
895
+ }, async ({ sessionId, timeMs, timecode, label, color, note }) => runTool(async () => {
896
+ if (timeMs === undefined && !timecode) {
897
+ throw new Error("Provide either timeMs or timecode (e.g. '00:14:32').");
898
+ }
899
+ const resolvedMs = timeMs !== undefined ? timeMs : parseTimecodeToMs(timecode);
900
+ const res = await api.addMarker(sessionId, {
901
+ timeMs: resolvedMs,
902
+ color,
903
+ label,
904
+ note,
905
+ });
906
+ return { ok: res.ok, id: res.id, timeMs: resolvedMs };
907
+ }));
908
+ // 12. delete_marker
909
+ server.registerTool("delete_marker", {
910
+ title: "Delete Marker",
911
+ description: "Delete a Marker from a recorded Session and immediately regenerate export metadata.",
912
+ inputSchema: {
913
+ sessionId: z.string().min(1).describe("Recorded Session ID."),
914
+ markerId: z.string().min(1).describe("Marker ID to remove."),
915
+ },
916
+ outputSchema: {
917
+ ok: z.boolean(),
918
+ sessionId: z.string(),
919
+ markerId: z.string(),
920
+ },
921
+ annotations: {
922
+ title: "Delete Marker",
923
+ readOnlyHint: false,
924
+ destructiveHint: true,
925
+ idempotentHint: true,
926
+ openWorldHint: true,
927
+ },
928
+ }, async ({ sessionId, markerId }) => runTool(async () => {
929
+ const res = await api.deleteMarker(sessionId, markerId);
930
+ return { ok: res.ok, sessionId, markerId };
931
+ }));
932
+ // 13. process_session_now
933
+ server.registerTool("process_session_now", {
934
+ title: "Process Session Now",
935
+ description: "Trigger post-processing early (or retry after failure) on an uploading or failed Session.",
936
+ inputSchema: {
937
+ sessionId: z.string().min(1).describe("Session ID to process."),
938
+ forcePartial: z
939
+ .boolean()
940
+ .default(true)
941
+ .describe("Proceed even if some Participant uploads are incomplete."),
942
+ onlyParticipantIds: z
943
+ .array(z.string().min(1))
944
+ .max(16)
945
+ .optional()
946
+ .describe("Optional subset of Participant IDs to include."),
947
+ },
948
+ outputSchema: {
949
+ ok: z.boolean(),
950
+ jobId: z.string().optional(),
951
+ error: z.string().optional(),
952
+ },
953
+ annotations: {
954
+ title: "Process Session Now",
955
+ readOnlyHint: false,
956
+ destructiveHint: false,
957
+ idempotentHint: false,
958
+ openWorldHint: true,
959
+ },
960
+ }, async ({ sessionId, forcePartial, onlyParticipantIds }) => runTool(async () => {
961
+ const res = await api.processSessionNow(sessionId, {
962
+ forcePartial,
963
+ onlyParticipantIds,
964
+ });
965
+ if (!res.ok) {
966
+ throw new Error(res.error || "Failed to start post-processing.");
967
+ }
968
+ return res;
969
+ }));
970
+ // 14. download_session
971
+ server.registerTool("download_session", {
972
+ title: "Download Session",
973
+ description: "Download exported Tracks and timeline bundles (.otio/.edl/.json) into a flat local folder with atomic .part streaming, HTTP Range resume, exact byteSize skipping, and automatic presigned URL refresh. When session.otio is on disk after the pull, also writes session.resolve.otio with absolute local paths (returned as resolveOtioPath) for one-click DaVinci Resolve import. To inspect or transcribe first, pass categories: [\"bundle\", \"audio\"] and fetch the multi-GB .mov video later. Under mode='auto', pulls <= 100 MB run foreground with progress notifications while larger pulls run in the background of this MCP server process and return a downloadId for get_download_status; they stop if the process exits, so short-lived or one-shot CLI invocations should pass mode: \"foreground\".",
974
+ inputSchema: {
975
+ sessionId: z.string().min(1).describe("Ready Session ID to download."),
976
+ destinationDir: z
977
+ .string()
978
+ .optional()
979
+ .describe("Base destination directory (defaults to TAPEDOCK_DOWNLOAD_DIR or ~/Downloads/tapedock)."),
980
+ createSubfolder: z
981
+ .boolean()
982
+ .default(true)
983
+ .describe("Create a flat <YYYY-MM-DD>_<title>_<shortId>/ subfolder (recommended for editor auto-linking)."),
984
+ categories: z
985
+ .array(z.enum(["bundle", "audio", "video", "screen"]))
986
+ .default(ALL_DOWNLOAD_CATEGORIES)
987
+ .describe('File categories to download. Use ["bundle", "audio"] to inspect or transcribe before pulling multi-GB "video"/"screen" .mov files.'),
988
+ overwrite: z
989
+ .boolean()
990
+ .default(false)
991
+ .describe("Re-download files even if an exact byteSize match already exists on disk."),
992
+ dryRun: z
993
+ .boolean()
994
+ .default(false)
995
+ .describe("Preview planned vs. skipped files and total GB without writing to disk."),
996
+ mode: z
997
+ .enum(["auto", "foreground", "background"])
998
+ .default("auto")
999
+ .describe("'auto' runs foreground <= 100 MB and background > 100 MB to avoid 60s client timeouts. Background pulls live only as long as this MCP server process, so short-lived or one-shot CLI invocations should pass 'foreground'."),
1000
+ },
1001
+ outputSchema: DownloadJobOutputSchema.shape,
1002
+ annotations: {
1003
+ title: "Download Session",
1004
+ readOnlyHint: false,
1005
+ destructiveHint: false,
1006
+ idempotentHint: true,
1007
+ openWorldHint: true,
1008
+ },
1009
+ }, async (args, extra) => runTool(async () => {
1010
+ const progressToken = extra._meta?.progressToken;
1011
+ const job = await downloads.startDownload({
1012
+ sessionId: args.sessionId,
1013
+ destinationDir: args.destinationDir,
1014
+ createSubfolder: args.createSubfolder,
1015
+ categories: args.categories,
1016
+ overwrite: args.overwrite,
1017
+ dryRun: args.dryRun,
1018
+ mode: args.mode,
1019
+ }, {
1020
+ signal: extra.signal,
1021
+ onProgress: progressToken !== undefined
1022
+ ? async ({ downloadedBytes, totalBytes, message }) => {
1023
+ await extra.sendNotification({
1024
+ method: "notifications/progress",
1025
+ params: {
1026
+ progressToken,
1027
+ progress: downloadedBytes,
1028
+ total: totalBytes,
1029
+ message,
1030
+ },
1031
+ });
1032
+ }
1033
+ : undefined,
1034
+ });
1035
+ return formatJobOutput(job);
1036
+ }));
1037
+ // 15. get_download_status
1038
+ server.registerTool("get_download_status", {
1039
+ title: "Get Download Status",
1040
+ description: "Inspect progress, per-file state, and completion status for a background download_session transfer (or list all transfers in this MCP server process).",
1041
+ inputSchema: {
1042
+ downloadId: z
1043
+ .string()
1044
+ .optional()
1045
+ .describe("Specific downloadId returned by download_session; omit to list all transfers."),
1046
+ },
1047
+ outputSchema: {
1048
+ jobs: z.array(DownloadJobOutputSchema),
1049
+ },
1050
+ annotations: {
1051
+ title: "Get Download Status",
1052
+ readOnlyHint: true,
1053
+ destructiveHint: false,
1054
+ idempotentHint: true,
1055
+ openWorldHint: false,
1056
+ },
1057
+ }, async ({ downloadId }) => runTool(async () => {
1058
+ if (downloadId) {
1059
+ const job = downloads.getJob(downloadId);
1060
+ if (!job) {
1061
+ throw new Error(`Download job "${downloadId}" not found in this MCP server session.`);
1062
+ }
1063
+ return { jobs: [formatJobOutput(job)] };
1064
+ }
1065
+ return { jobs: downloads.listJobs().map((j) => formatJobOutput(j)) };
1066
+ }));
1067
+ return server;
1068
+ }