@tapedock/mcp 0.0.0-stage → 0.1.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.
@@ -0,0 +1,244 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { constants as fsConstants } from "node:fs";
3
+ import * as fs from "node:fs/promises";
4
+ import * as os from "node:os";
5
+ import * as path from "node:path";
6
+ import { normalizeOrigin } from "../lib/format.js";
7
+ const EXPIRY_SKEW_BUFFER_MS = 60_000; // Refresh proactively 60s before expiry
8
+ const LOCK_STALE_MS = 30_000;
9
+ const LOCK_TIMEOUT_MS = 10_000;
10
+ export class AuthRequiredError extends Error {
11
+ origin;
12
+ constructor(origin, message) {
13
+ super(message ||
14
+ `Authentication required for ${origin} (not signed in or session expired/revoked). Ask the Host to run \`npx -y @tapedock/mcp login\` in their terminal, then retry.`);
15
+ this.origin = origin;
16
+ this.name = "AuthRequiredError";
17
+ }
18
+ }
19
+ export function resolveCredentialsPath(overridePath) {
20
+ const fromOverride = overridePath?.trim() ||
21
+ process.env.TAPEDOCK_CREDENTIALS_PATH?.trim() ||
22
+ process.env.VCR_MCP_CREDENTIALS_PATH?.trim();
23
+ if (fromOverride) {
24
+ return path.resolve(fromOverride);
25
+ }
26
+ const xdg = process.env.XDG_CONFIG_HOME?.trim();
27
+ const baseDir = xdg ? path.resolve(xdg) : path.join(os.homedir(), ".config");
28
+ return path.join(baseDir, "tapedock-mcp", "credentials.json");
29
+ }
30
+ function isProcessAlive(pid) {
31
+ if (!Number.isInteger(pid) || pid <= 0)
32
+ return false;
33
+ try {
34
+ process.kill(pid, 0);
35
+ return true;
36
+ }
37
+ catch (err) {
38
+ const code = err.code;
39
+ return code === "EPERM";
40
+ }
41
+ }
42
+ async function sleep(ms) {
43
+ await new Promise((resolve) => setTimeout(resolve, ms));
44
+ }
45
+ export class CredentialStore {
46
+ filePath;
47
+ lockPath;
48
+ inFlightRefreshes = new Map();
49
+ constructor(filePath) {
50
+ this.filePath = resolveCredentialsPath(filePath);
51
+ this.lockPath = `${this.filePath}.lock`;
52
+ }
53
+ async ensureParentDir() {
54
+ const dir = path.dirname(this.filePath);
55
+ await fs.mkdir(dir, { recursive: true, mode: 0o700 });
56
+ await fs.chmod(dir, 0o700).catch(() => { });
57
+ }
58
+ async readFileUnlocked() {
59
+ try {
60
+ const raw = await fs.readFile(this.filePath, "utf8");
61
+ const parsed = JSON.parse(raw);
62
+ if (parsed && parsed.version === 1 && parsed.origins && typeof parsed.origins === "object") {
63
+ return { version: 1, origins: { ...parsed.origins } };
64
+ }
65
+ return { version: 1, origins: {} };
66
+ }
67
+ catch (err) {
68
+ if (err.code === "ENOENT") {
69
+ return { version: 1, origins: {} };
70
+ }
71
+ return { version: 1, origins: {} };
72
+ }
73
+ }
74
+ async writeFileAtomicUnlocked(data) {
75
+ await this.ensureParentDir();
76
+ const dir = path.dirname(this.filePath);
77
+ const tmpPath = path.join(dir, `credentials.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
78
+ const flags = fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL;
79
+ const fh = await fs.open(tmpPath, flags, 0o600);
80
+ try {
81
+ await fh.writeFile(JSON.stringify(data, null, 2) + "\n", "utf8");
82
+ await fh.sync();
83
+ }
84
+ finally {
85
+ await fh.close();
86
+ }
87
+ try {
88
+ await fs.chmod(tmpPath, 0o600).catch(() => { });
89
+ await fs.rename(tmpPath, this.filePath);
90
+ }
91
+ catch (err) {
92
+ await fs.unlink(tmpPath).catch(() => { });
93
+ throw err;
94
+ }
95
+ }
96
+ async withCrossProcessLock(fn) {
97
+ await this.ensureParentDir();
98
+ const deadline = Date.now() + LOCK_TIMEOUT_MS;
99
+ let lockHandle = null;
100
+ while (!lockHandle) {
101
+ try {
102
+ const handle = await fs.open(this.lockPath, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL, 0o600);
103
+ try {
104
+ await handle.writeFile(JSON.stringify({ pid: process.pid, createdAtMs: Date.now() }), "utf8");
105
+ lockHandle = handle;
106
+ }
107
+ catch (writeErr) {
108
+ await handle.close().catch(() => { });
109
+ await fs.unlink(this.lockPath).catch(() => { });
110
+ throw writeErr;
111
+ }
112
+ }
113
+ catch (err) {
114
+ if (err.code !== "EEXIST") {
115
+ throw err;
116
+ }
117
+ // Check for stale lock from a crashed process; use atomic rename-to-stale before unlink to avoid TOCTOU
118
+ try {
119
+ const stat = await fs.stat(this.lockPath);
120
+ const rawLock = await fs.readFile(this.lockPath, "utf8").catch(() => "");
121
+ let lockPid = -1;
122
+ try {
123
+ lockPid = Number(JSON.parse(rawLock).pid ?? -1);
124
+ }
125
+ catch {
126
+ lockPid = -1;
127
+ }
128
+ const ageMs = Date.now() - stat.mtimeMs;
129
+ if (ageMs > LOCK_STALE_MS && !isProcessAlive(lockPid)) {
130
+ const stalePath = `${this.lockPath}.stale.${process.pid}.${randomBytes(4).toString("hex")}`;
131
+ await fs.rename(this.lockPath, stalePath).catch(() => { });
132
+ await fs.unlink(stalePath).catch(() => { });
133
+ continue;
134
+ }
135
+ }
136
+ catch {
137
+ // Lock vanished between EEXIST and stat; retry immediately
138
+ continue;
139
+ }
140
+ if (Date.now() >= deadline) {
141
+ throw new Error(`Timed out waiting for credential lock at ${this.lockPath}`);
142
+ }
143
+ await sleep(50 + Math.floor(Math.random() * 100));
144
+ }
145
+ }
146
+ try {
147
+ return await fn();
148
+ }
149
+ finally {
150
+ await lockHandle.close().catch(() => { });
151
+ await fs.unlink(this.lockPath).catch(() => { });
152
+ }
153
+ }
154
+ async get(originRaw) {
155
+ const origin = normalizeOrigin(originRaw);
156
+ const file = await this.readFileUnlocked();
157
+ return file.origins[origin] ?? null;
158
+ }
159
+ async save(originRaw, creds) {
160
+ const origin = normalizeOrigin(originRaw);
161
+ await this.withCrossProcessLock(async () => {
162
+ const file = await this.readFileUnlocked();
163
+ file.origins[origin] = creds;
164
+ await this.writeFileAtomicUnlocked(file);
165
+ });
166
+ }
167
+ async remove(originRaw) {
168
+ const origin = normalizeOrigin(originRaw);
169
+ await this.withCrossProcessLock(async () => {
170
+ const file = await this.readFileUnlocked();
171
+ if (origin in file.origins) {
172
+ delete file.origins[origin];
173
+ await this.writeFileAtomicUnlocked(file);
174
+ }
175
+ });
176
+ }
177
+ /**
178
+ * Return a valid access token for `origin`, refreshing transparently under a two-level lock
179
+ * (in-process single-flight mutex + cross-process lockfile + double-checked disk reload)
180
+ * so parallel tool calls never trigger RFC 9700 refresh-token reuse revocation.
181
+ */
182
+ async getValidCredentials(originRaw, refreshFn, opts) {
183
+ const origin = normalizeOrigin(originRaw);
184
+ const current = await this.get(origin);
185
+ if (!current) {
186
+ throw new AuthRequiredError(origin);
187
+ }
188
+ const failedToken = opts?.forceRefreshAfterFailedToken;
189
+ const isFresh = current.expiresAtMs > Date.now() + EXPIRY_SKEW_BUFFER_MS &&
190
+ (!failedToken || current.accessToken !== failedToken);
191
+ if (isFresh) {
192
+ return current;
193
+ }
194
+ const existingPromise = this.inFlightRefreshes.get(origin);
195
+ if (existingPromise) {
196
+ return existingPromise;
197
+ }
198
+ const promise = this.withCrossProcessLock(async () => {
199
+ // Double-checked disk reload after acquiring cross-process lock
200
+ const file = await this.readFileUnlocked();
201
+ const latest = file.origins[origin];
202
+ if (!latest) {
203
+ throw new AuthRequiredError(origin);
204
+ }
205
+ if (latest.expiresAtMs > Date.now() + EXPIRY_SKEW_BUFFER_MS &&
206
+ (!failedToken || latest.accessToken !== failedToken)) {
207
+ return latest;
208
+ }
209
+ try {
210
+ const refreshed = await refreshFn(latest.refreshToken);
211
+ const now = Date.now();
212
+ const nextCreds = {
213
+ accessToken: refreshed.accessToken,
214
+ refreshToken: refreshed.refreshToken,
215
+ expiresAtMs: now + refreshed.expiresInSec * 1000,
216
+ scope: refreshed.scope || latest.scope,
217
+ accountEmail: latest.accountEmail,
218
+ updatedAtMs: now,
219
+ };
220
+ file.origins[origin] = nextCreds;
221
+ await this.writeFileAtomicUnlocked(file);
222
+ return nextCreds;
223
+ }
224
+ catch (err) {
225
+ if (err instanceof InvalidGrantError) {
226
+ delete file.origins[origin];
227
+ await this.writeFileAtomicUnlocked(file);
228
+ throw new AuthRequiredError(origin, `OAuth session for ${origin} expired or was revoked. Ask the Host to run \`npx -y @tapedock/mcp login\` in their terminal, then retry.`);
229
+ }
230
+ throw err;
231
+ }
232
+ }).finally(() => {
233
+ this.inFlightRefreshes.delete(origin);
234
+ });
235
+ this.inFlightRefreshes.set(origin, promise);
236
+ return promise;
237
+ }
238
+ }
239
+ export class InvalidGrantError extends Error {
240
+ constructor(message = "invalid_grant") {
241
+ super(message);
242
+ this.name = "InvalidGrantError";
243
+ }
244
+ }
@@ -0,0 +1,22 @@
1
+ import { type CredentialStore, type OriginCredentials } from "./credentials.js";
2
+ export declare const OAUTH_CLIENT_ID = "tapedock-mcp-cli";
3
+ export declare function generatePkcePair(): {
4
+ verifier: string;
5
+ challenge: string;
6
+ };
7
+ export declare function runOAuthLogin(opts: {
8
+ origin: string;
9
+ store: CredentialStore;
10
+ readOnly?: boolean;
11
+ deviceLabel?: string;
12
+ openBrowser?: boolean;
13
+ fetchImpl?: typeof fetch;
14
+ onAuthorizeUrl?: (url: string) => void;
15
+ }): Promise<OriginCredentials>;
16
+ export declare function runOAuthLogout(opts: {
17
+ origin: string;
18
+ store: CredentialStore;
19
+ fetchImpl?: typeof fetch;
20
+ }): Promise<{
21
+ revokedRemotely: boolean;
22
+ }>;
@@ -0,0 +1,229 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createHash, randomBytes } from "node:crypto";
3
+ import * as http from "node:http";
4
+ import * as os from "node:os";
5
+ import { normalizeOrigin } from "../lib/format.js";
6
+ export const OAUTH_CLIENT_ID = "tapedock-mcp-cli";
7
+ const LOGIN_TIMEOUT_MS = 3 * 60 * 1000;
8
+ function toBase64Url(buf) {
9
+ return buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
10
+ }
11
+ export function generatePkcePair() {
12
+ const verifier = toBase64Url(randomBytes(32));
13
+ const challenge = toBase64Url(createHash("sha256").update(verifier).digest());
14
+ return { verifier, challenge };
15
+ }
16
+ function escapeHtml(raw) {
17
+ return raw
18
+ .replace(/&/g, "&amp;")
19
+ .replace(/</g, "&lt;")
20
+ .replace(/>/g, "&gt;")
21
+ .replace(/"/g, "&quot;")
22
+ .replace(/'/g, "&#39;");
23
+ }
24
+ function openSystemBrowser(url) {
25
+ try {
26
+ const platform = process.platform;
27
+ let child;
28
+ if (platform === "darwin") {
29
+ child = spawn("open", [url], { detached: true, stdio: "ignore" });
30
+ }
31
+ else if (platform === "win32") {
32
+ // Avoid cmd.exe splitting URL query strings at '&'
33
+ child = spawn("rundll32", ["url.dll,FileProtocolHandler", url], {
34
+ detached: true,
35
+ stdio: "ignore",
36
+ });
37
+ }
38
+ else {
39
+ child = spawn("xdg-open", [url], { detached: true, stdio: "ignore" });
40
+ }
41
+ child.on("error", () => {
42
+ // Headless / missing opener: user can open the printed authorize URL manually
43
+ });
44
+ child.unref();
45
+ return true;
46
+ }
47
+ catch {
48
+ return false;
49
+ }
50
+ }
51
+ function callbackResultHtml(ok, message) {
52
+ return `<!doctype html>
53
+ <html lang="en">
54
+ <head>
55
+ <meta charset="utf-8" />
56
+ <title>${ok ? "Authorized" : "Authorization Failed"} · TapeDock MCP</title>
57
+ <style>
58
+ body { margin: 0; min-height: 100vh; display: flex; align-items: center; justify-content: center; background: #0b0c0f; color: #f2f3f5; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; padding: 24px; }
59
+ .card { max-width: 420px; width: 100%; background: #12141a; border: 1px solid rgba(255,255,255,0.09); border-radius: 16px; padding: 28px; text-align: center; }
60
+ h1 { margin: 0 0 10px; font-size: 19px; color: ${ok ? "#6ee7b7" : "#fca5a5"}; }
61
+ p { margin: 0; font-size: 14px; color: #b2bac7; line-height: 1.5; }
62
+ </style>
63
+ </head>
64
+ <body>
65
+ <main class="card">
66
+ <h1>${ok ? "Agent Authorized" : "Authorization Failed"}</h1>
67
+ <p>${escapeHtml(message)}</p>
68
+ </main>
69
+ </body>
70
+ </html>`;
71
+ }
72
+ export async function runOAuthLogin(opts) {
73
+ const origin = normalizeOrigin(opts.origin);
74
+ const fetchFn = opts.fetchImpl ?? fetch;
75
+ const scope = opts.readOnly ? "host:read" : "host:read host:write";
76
+ const deviceLabel = (opts.deviceLabel?.trim() || os.hostname() || "Local Device").slice(0, 80);
77
+ const state = toBase64Url(randomBytes(24));
78
+ const { verifier, challenge } = generatePkcePair();
79
+ let resolveCallback;
80
+ const callbackPromise = new Promise((resolve) => {
81
+ resolveCallback = resolve;
82
+ });
83
+ let callbackHandled = false;
84
+ const server = http.createServer((req, res) => {
85
+ const reqUrl = new URL(req.url || "/", "http://127.0.0.1");
86
+ if (reqUrl.pathname !== "/callback") {
87
+ res.writeHead(404, { "Content-Type": "text/plain" });
88
+ res.end("Not found");
89
+ return;
90
+ }
91
+ const htmlHeaders = {
92
+ "Content-Type": "text/html; charset=utf-8",
93
+ "Cache-Control": "no-store",
94
+ "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'",
95
+ };
96
+ if (callbackHandled) {
97
+ res.writeHead(200, htmlHeaders);
98
+ res.end(callbackResultHtml(true, "Authorization already completed. You may close this tab."));
99
+ return;
100
+ }
101
+ const returnedState = reqUrl.searchParams.get("state");
102
+ const error = reqUrl.searchParams.get("error");
103
+ const code = reqUrl.searchParams.get("code");
104
+ if (!returnedState || returnedState !== state) {
105
+ // Ignore stray/unmatched local requests without aborting the Host's active login flow
106
+ res.writeHead(400, htmlHeaders);
107
+ res.end(callbackResultHtml(false, "State mismatch. Please complete login in the browser window opened by your terminal."));
108
+ return;
109
+ }
110
+ callbackHandled = true;
111
+ if (error || !code) {
112
+ res.writeHead(200, htmlHeaders);
113
+ res.end(callbackResultHtml(false, `Authorization declined (${error || "missing_code"}). You may close this tab.`));
114
+ resolveCallback({ error: error || "missing_code" });
115
+ return;
116
+ }
117
+ res.writeHead(200, htmlHeaders);
118
+ res.end(callbackResultHtml(true, "You are signed in. You may close this tab and return to your terminal."));
119
+ resolveCallback({ code });
120
+ });
121
+ await new Promise((resolve, reject) => {
122
+ server.once("error", reject);
123
+ server.listen(0, "127.0.0.1", () => resolve());
124
+ });
125
+ const addr = server.address();
126
+ if (!addr || typeof addr === "string") {
127
+ server.close();
128
+ throw new Error("Failed to bind loopback callback server on 127.0.0.1");
129
+ }
130
+ const redirectUri = `http://127.0.0.1:${addr.port}/callback`;
131
+ const authUrl = new URL(`${origin}/oauth/authorize`);
132
+ authUrl.searchParams.set("response_type", "code");
133
+ authUrl.searchParams.set("client_id", OAUTH_CLIENT_ID);
134
+ authUrl.searchParams.set("redirect_uri", redirectUri);
135
+ authUrl.searchParams.set("code_challenge", challenge);
136
+ authUrl.searchParams.set("code_challenge_method", "S256");
137
+ authUrl.searchParams.set("state", state);
138
+ authUrl.searchParams.set("scope", scope);
139
+ authUrl.searchParams.set("device_label", deviceLabel);
140
+ opts.onAuthorizeUrl?.(authUrl.toString());
141
+ if (opts.openBrowser !== false) {
142
+ openSystemBrowser(authUrl.toString());
143
+ }
144
+ let timeoutId;
145
+ try {
146
+ const result = await Promise.race([
147
+ callbackPromise,
148
+ new Promise((resolve) => {
149
+ timeoutId = setTimeout(() => resolve({ error: "timeout" }), LOGIN_TIMEOUT_MS);
150
+ }),
151
+ ]);
152
+ if (result.error || !result.code) {
153
+ throw new Error(result.error === "timeout"
154
+ ? "Login timed out after 3 minutes waiting for browser approval."
155
+ : `OAuth authorization failed: ${result.error || "missing_code"}`);
156
+ }
157
+ const tokenResp = await fetchFn(`${origin}/oauth/token`, {
158
+ method: "POST",
159
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
160
+ body: new URLSearchParams({
161
+ grant_type: "authorization_code",
162
+ code: result.code,
163
+ redirect_uri: redirectUri,
164
+ client_id: OAUTH_CLIENT_ID,
165
+ code_verifier: verifier,
166
+ }),
167
+ });
168
+ if (!tokenResp.ok) {
169
+ const errBody = await tokenResp.text().catch(() => "");
170
+ throw new Error(`Token exchange failed (${tokenResp.status}): ${errBody}`);
171
+ }
172
+ const tokens = (await tokenResp.json());
173
+ // Fetch Host email for friendlier local status reporting
174
+ let accountEmail;
175
+ try {
176
+ const meResp = await fetchFn(`${origin}/auth/me`, {
177
+ headers: { Authorization: `Bearer ${tokens.access_token}` },
178
+ });
179
+ if (meResp.ok) {
180
+ const me = (await meResp.json());
181
+ accountEmail = me.user?.email;
182
+ }
183
+ }
184
+ catch {
185
+ // non-fatal
186
+ }
187
+ const now = Date.now();
188
+ const creds = {
189
+ accessToken: tokens.access_token,
190
+ refreshToken: tokens.refresh_token,
191
+ expiresAtMs: now + tokens.expires_in * 1000,
192
+ scope: tokens.scope || scope,
193
+ accountEmail,
194
+ updatedAtMs: now,
195
+ };
196
+ await opts.store.save(origin, creds);
197
+ return creds;
198
+ }
199
+ finally {
200
+ if (timeoutId)
201
+ clearTimeout(timeoutId);
202
+ await new Promise((resolve) => server.close(() => resolve()));
203
+ }
204
+ }
205
+ export async function runOAuthLogout(opts) {
206
+ const origin = normalizeOrigin(opts.origin);
207
+ const fetchFn = opts.fetchImpl ?? fetch;
208
+ const existing = await opts.store.get(origin);
209
+ let revokedRemotely = false;
210
+ if (existing?.refreshToken) {
211
+ try {
212
+ const resp = await fetchFn(`${origin}/oauth/revoke`, {
213
+ method: "POST",
214
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
215
+ body: new URLSearchParams({
216
+ token: existing.refreshToken,
217
+ token_type_hint: "refresh_token",
218
+ client_id: OAUTH_CLIENT_ID,
219
+ }),
220
+ });
221
+ revokedRemotely = resp.ok;
222
+ }
223
+ catch {
224
+ revokedRemotely = false;
225
+ }
226
+ }
227
+ await opts.store.remove(origin);
228
+ return { revokedRemotely };
229
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,145 @@
1
+ #!/usr/bin/env node
2
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
+ import { VcrApiClient } from "./api/client.js";
4
+ import { AuthRequiredError, CredentialStore } from "./auth/credentials.js";
5
+ import { runOAuthLogin, runOAuthLogout } from "./auth/login.js";
6
+ import { DownloadManager } from "./downloads/manager.js";
7
+ import { normalizeOrigin } from "./lib/format.js";
8
+ import { createVcrMcpServer } from "./server.js";
9
+ function parseArgs(argv) {
10
+ const args = [...argv];
11
+ let command = "serve";
12
+ let origin = process.env.TAPEDOCK_ORIGIN || process.env.VCR_ORIGIN || "https://app.tapedock.com";
13
+ let readOnly = false;
14
+ let deviceLabel;
15
+ if (args[0] && !args[0].startsWith("-")) {
16
+ const sub = args.shift();
17
+ if (sub === "serve" || sub === "login" || sub === "check" || sub === "logout" || sub === "help") {
18
+ command = sub;
19
+ }
20
+ else {
21
+ throw new Error(`Unknown subcommand "${sub}". Use: serve, login, check, or logout.`);
22
+ }
23
+ }
24
+ for (let i = 0; i < args.length; i++) {
25
+ const flag = args[i];
26
+ if (flag === "--") {
27
+ continue;
28
+ }
29
+ else if (flag === "--check") {
30
+ command = "check";
31
+ }
32
+ else if (flag === "--login") {
33
+ command = "login";
34
+ }
35
+ else if (flag === "--logout") {
36
+ command = "logout";
37
+ }
38
+ else if (flag === "--help" || flag === "-h") {
39
+ command = "help";
40
+ }
41
+ else if (flag === "--read-only") {
42
+ readOnly = true;
43
+ }
44
+ else if (flag === "--origin") {
45
+ const next = args[++i];
46
+ if (!next)
47
+ throw new Error("--origin requires a URL value.");
48
+ origin = next;
49
+ }
50
+ else if (flag === "--label") {
51
+ const next = args[++i];
52
+ if (!next)
53
+ throw new Error("--label requires a device label value.");
54
+ deviceLabel = next;
55
+ }
56
+ else {
57
+ throw new Error(`Unknown option: ${flag}`);
58
+ }
59
+ }
60
+ return { command, origin: normalizeOrigin(origin), readOnly, deviceLabel };
61
+ }
62
+ function printHelp() {
63
+ process.stderr.write([
64
+ "TapeDock MCP Server (tapedock-mcp)",
65
+ "",
66
+ "Usage:",
67
+ " tapedock-mcp [serve] Start local stdio MCP server",
68
+ " tapedock-mcp login [--origin URL] [--read-only] [--label] Authorize via browser OAuth 2.0 + PKCE",
69
+ " tapedock-mcp check [--origin URL] Verify OAuth credentials & API reachability",
70
+ " tapedock-mcp logout [--origin URL] Revoke OAuth grant and clear local credentials",
71
+ "",
72
+ "Environment:",
73
+ " TAPEDOCK_ORIGIN Server origin (default: https://app.tapedock.com; alias: VCR_ORIGIN)",
74
+ " TAPEDOCK_DOWNLOAD_DIR Default download directory (default: ~/Downloads/tapedock; alias: VCR_DOWNLOAD_DIR)",
75
+ " TAPEDOCK_CREDENTIALS_PATH Override credentials file (default: ~/.config/tapedock-mcp/credentials.json)",
76
+ "",
77
+ ].join("\n"));
78
+ }
79
+ async function main() {
80
+ const opts = parseArgs(process.argv.slice(2));
81
+ const store = new CredentialStore();
82
+ if (opts.command === "help") {
83
+ printHelp();
84
+ return;
85
+ }
86
+ if (opts.command === "login") {
87
+ process.stderr.write(`Starting OAuth 2.0 login for ${opts.origin}...\n`);
88
+ const creds = await runOAuthLogin({
89
+ origin: opts.origin,
90
+ store,
91
+ readOnly: opts.readOnly,
92
+ deviceLabel: opts.deviceLabel,
93
+ onAuthorizeUrl: (url) => {
94
+ process.stderr.write(`Opening browser to authorize:\n ${url}\n`);
95
+ },
96
+ });
97
+ process.stderr.write(`Authorized${creds.accountEmail ? ` as ${creds.accountEmail}` : ""} (scopes: ${creds.scope}).\n` +
98
+ `Credentials saved to ${store.filePath} (0600).\n`);
99
+ return;
100
+ }
101
+ if (opts.command === "logout") {
102
+ const res = await runOAuthLogout({ origin: opts.origin, store });
103
+ process.stderr.write(res.revokedRemotely
104
+ ? `Revoked OAuth grant on ${opts.origin} and removed local credentials.\n`
105
+ : `Removed local credentials for ${opts.origin}.\n`);
106
+ return;
107
+ }
108
+ if (opts.command === "check") {
109
+ const api = new VcrApiClient({ origin: opts.origin, store });
110
+ try {
111
+ const [me, roomsResp] = await Promise.all([api.getAuthMe(), api.listRooms()]);
112
+ if (!me.authenticated || !me.user) {
113
+ throw new AuthRequiredError(opts.origin);
114
+ }
115
+ process.stdout.write([
116
+ `Status: OK`,
117
+ `Origin: ${opts.origin}`,
118
+ `Host: ${me.user.name} <${me.user.email}>`,
119
+ `Scopes: ${(me.scopes ?? []).join(" ") || "none"}`,
120
+ `Rooms: ${roomsResp.rooms.length}`,
121
+ `Credentials: ${store.filePath}`,
122
+ ].join("\n") + "\n");
123
+ return;
124
+ }
125
+ catch (err) {
126
+ process.stderr.write(`Check failed: ${err instanceof Error ? err.message : String(err)}\n`);
127
+ process.exitCode = 1;
128
+ return;
129
+ }
130
+ }
131
+ // Strict stdio discipline: stdout MUST carry only JSON-RPC frames
132
+ console.log = (...args) => console.error(...args);
133
+ console.info = (...args) => console.error(...args);
134
+ console.warn = (...args) => console.error(...args);
135
+ console.debug = (...args) => console.error(...args);
136
+ const api = new VcrApiClient({ origin: opts.origin, store });
137
+ const downloads = new DownloadManager({ api });
138
+ const server = createVcrMcpServer({ api, downloads });
139
+ const transport = new StdioServerTransport();
140
+ await server.connect(transport);
141
+ }
142
+ main().catch((err) => {
143
+ process.stderr.write(`vcr-mcp fatal error: ${err instanceof Error ? err.message : String(err)}\n`);
144
+ process.exit(1);
145
+ });