@clipzi/cli 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sausito LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,53 @@
1
- # Temporary Holding Version
1
+ # Clipzi for agents and terminals
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [Clipzi](https://clipzi.app) turns long videos (podcasts, interviews, streams, lectures) into finished short vertical clips: it finds the moments that stand on their own, frames each one for vertical (the person talking, a split screen when two talk), captions it, removes dead air and renders the mp4.
4
+
5
+ This repository is everything an agent needs to use it:
6
+
7
+ - **`clipzi`**, the command line (`npx -y @clipzi/cli`, or `npm i -g @clipzi/cli` for the `clipzi` command), for terminals, scripts and agents that run commands.
8
+ - **The `clipzi` skill** (`skills/clipzi/SKILL.md`), which teaches an agent when and how to use it.
9
+ - **Plugins** for Claude Code and Gemini CLI that bring the skill and Clipzi's MCP server together.
10
+ - **A desktop extension** (`clipzi.mcpb`) for Claude Desktop: a small server on your computer, so Claude can upload a video file you have locally and save the finished clips to your Downloads folder, from a normal chat.
11
+
12
+ ## Quick start
13
+
14
+ ```bash
15
+ npx -y @clipzi/cli login # opens the browser: sign in and allow this terminal
16
+ npx -y @clipzi/cli make ./episode.mp4 --count 5 --out ./clips
17
+ ```
18
+
19
+ `make` uploads the file, lets Clipzi choose the moments, frames and captions each clip and saves every mp4 in `./clips` as it finishes. The source can also be a link to the video file (direct, Google Drive or Dropbox) or the id of a video already in your account.
20
+
21
+ No browser (a server, CI, a headless agent)? Create a key at https://clipzi.app/dashboard/agents and set `CLIPZI_API_KEY`.
22
+
23
+ ## Install it in your agent
24
+
25
+ | Agent | How |
26
+ |---|---|
27
+ | Any agent that reads skills | `npx skills add clipzi-app/clipzi-agent` |
28
+ | Claude Desktop (uses video files on your computer) | Download `clipzi.mcpb` from the [latest release](https://github.com/clipzi-app/clipzi-agent/releases/latest) and open it: Claude installs it as an extension |
29
+ | Claude Code (skill + MCP server) | `/plugin marketplace add clipzi-app/clipzi-agent`, then `/plugin install clipzi@clipzi` |
30
+ | Claude Code (MCP server only) | `claude mcp add --transport http clipzi https://clipzi.app/mcp` |
31
+ | Gemini CLI | `gemini extensions install https://github.com/clipzi-app/clipzi-agent` |
32
+ | Claude.ai, ChatGPT, Cursor and others | Add a connector with the address `https://clipzi.app/mcp`: https://clipzi.app/en/mcp |
33
+
34
+ ## Commands
35
+
36
+ ```
37
+ clipzi make <file | link | video_id> [--count 5] [--query "..."] [--template t] [--pace p] [--title] [--horizontal] [--out ./clips]
38
+ clipzi account | videos | video <id> | clips <video_id> | transcript <video_id> | find <video_id> <words>
39
+ clipzi upload <file> | import <link> | render <clip_id> | job <job_id>
40
+ clipzi tools | call <tool> '<json>'
41
+ ```
42
+
43
+ Every command prints JSON on stdout and progress on stderr. Exit codes: 0 done, 1 the tool could not (the JSON says why and what to do), 2 wrong usage, 3 not signed in.
44
+
45
+ ## Plans
46
+
47
+ Every Clipzi plan includes the agent tools. Without a plan you can try it with your own video (2 long videos, 5 clips edited by the AI): the clips come back as a page in Clipzi where you watch them, and downloading needs a plan. Plans: https://clipzi.app/en#pricing
48
+
49
+ The CLI is a client of Clipzi's MCP server, so it follows exactly the same rules as Claude or ChatGPT do. Developer docs: https://clipzi.app/en/developers
50
+
51
+ ## License
52
+
53
+ MIT
package/bin/clipzi.mjs ADDED
@@ -0,0 +1,36 @@
1
+ #!/usr/bin/env node
2
+ // clipzi: the command line of https://clipzi.app. See src/commands.mjs.
3
+
4
+ import { BOOLEAN_FLAGS, COMMANDS, HELP, ToolError } from '../src/commands.mjs';
5
+ import { AuthError } from '../src/auth.mjs';
6
+ import { parseArgs, print, UsageError } from '../src/util.mjs';
7
+
8
+ const [name, ...rest] = process.argv.slice(2);
9
+
10
+ if (!name || name === 'help' || name === '--help' || name === '-h') {
11
+ process.stdout.write(`${HELP}\n`);
12
+ process.exit(0);
13
+ }
14
+ if (name === '--version' || name === '-v') {
15
+ const { default: pkg } = await import('../package.json', { with: { type: 'json' } });
16
+ process.stdout.write(`${pkg.version}\n`);
17
+ process.exit(0);
18
+ }
19
+
20
+ const command = COMMANDS[name];
21
+ if (!command) {
22
+ print({ error: { code: 'unknown_command', message: `No command "${name}". Run clipzi help.` } });
23
+ process.exit(2);
24
+ }
25
+
26
+ try {
27
+ const args = parseArgs(rest, BOOLEAN_FLAGS);
28
+ if (args.flags.help) { process.stdout.write(`${HELP}\n`); process.exit(0); }
29
+ print(await command(args));
30
+ } catch (e) {
31
+ if (e instanceof UsageError) { print({ error: { code: 'usage', message: e.message } }); process.exit(2); }
32
+ if (e instanceof AuthError) { print({ error: { code: 'not_signed_in', message: e.message } }); process.exit(3); }
33
+ if (e instanceof ToolError) { print({ error: { code: e.code, message: e.message } }); process.exit(1); }
34
+ print({ error: { code: 'failed', message: e?.message ?? String(e) } });
35
+ process.exit(1);
36
+ }
package/icon.png ADDED
Binary file
package/manifest.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "manifest_version": "0.4",
3
+ "name": "clipzi",
4
+ "display_name": "Clipzi",
5
+ "version": "0.1.0",
6
+ "description": "Turn long videos into finished short vertical clips, straight from video files on your computer.",
7
+ "long_description": "Clipzi turns podcasts, interviews, streams and classes into short clips for TikTok, Reels and Shorts. This extension runs on your computer, so Claude can use a video file you have here: it uploads it to your Clipzi account, Clipzi finds the moments, frames whoever is talking (split screen for two people), adds captions, removes dead air and renders each clip, and Claude saves the finished mp4s to your Downloads folder.\n\nYou sign in with your Clipzi account in the browser the first time (it is created right there if you do not have one, no card). Without a plan you can try it with 2 long videos and watch your clips in Clipzi; downloading them needs a plan. Everything Claude makes also appears in your Clipzi editor, where you can change it.",
8
+ "author": { "name": "Clipzi", "email": "g@clipzi.app", "url": "https://clipzi.app" },
9
+ "repository": { "type": "git", "url": "https://github.com/clipzi-app/clipzi-agent" },
10
+ "homepage": "https://clipzi.app/en/mcp",
11
+ "documentation": "https://clipzi.app/en/developers",
12
+ "support": "https://clipzi.app/en/contact",
13
+ "icon": "icon.png",
14
+ "server": {
15
+ "type": "node",
16
+ "entry_point": "src/desktop-server.mjs",
17
+ "mcp_config": {
18
+ "command": "node",
19
+ "args": ["${__dirname}/src/desktop-server.mjs"],
20
+ "env": { "CLIPZI_API_KEY": "${user_config.api_key}" }
21
+ }
22
+ },
23
+ "tools": [
24
+ { "name": "upload_local_video", "description": "Bring a video file on this computer into Clipzi." },
25
+ { "name": "save_clip", "description": "Save a finished clip to a folder on this computer." },
26
+ { "name": "sign_in", "description": "Sign in to Clipzi in the browser." },
27
+ { "name": "sign_out", "description": "Forget the Clipzi sign-in on this computer." }
28
+ ],
29
+ "tools_generated": true,
30
+ "keywords": ["video", "clips", "shorts", "reels", "podcast", "captions"],
31
+ "license": "MIT",
32
+ "privacy_policies": ["https://clipzi.app/en/privacy"],
33
+ "compatibility": { "platforms": ["darwin", "win32", "linux"], "runtimes": { "node": ">=20.0.0" } },
34
+ "user_config": {
35
+ "api_key": {
36
+ "type": "string",
37
+ "title": "Clipzi API key (optional)",
38
+ "description": "Leave empty to sign in with your browser the first time. Or paste a key from clipzi.app/dashboard/agents.",
39
+ "sensitive": true,
40
+ "required": false
41
+ }
42
+ }
43
+ }
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "@clipzi/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Turn long videos into finished short clips from your terminal or your AI agent. The Clipzi command line: upload a video, let Clipzi find the moments, frame them for vertical, caption them and hand you the mp4s.",
5
+ "type": "module",
6
+ "bin": {
7
+ "clipzi": "bin/clipzi.mjs"
8
+ },
9
+ "files": [
10
+ "bin",
11
+ "src",
12
+ "skills",
13
+ "README.md",
14
+ "LICENSE",
15
+ "manifest.json",
16
+ "icon.png"
17
+ ],
18
+ "engines": {
19
+ "node": ">=20"
20
+ },
21
+ "scripts": {
22
+ "test": "node --test test/*.test.mjs",
23
+ "pack:desktop": "npx -y @anthropic-ai/mcpb pack . clipzi.mcpb"
24
+ },
25
+ "keywords": [
26
+ "clipzi",
27
+ "video",
28
+ "clips",
29
+ "shorts",
30
+ "reels",
31
+ "tiktok",
32
+ "podcast",
33
+ "mcp",
34
+ "agent",
35
+ "cli",
36
+ "claude",
37
+ "skill"
38
+ ],
39
+ "homepage": "https://clipzi.app/en/mcp",
40
+ "license": "MIT",
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "git+https://github.com/clipzi-app/clipzi-agent.git"
44
+ },
45
+ "bugs": {
46
+ "url": "https://github.com/clipzi-app/clipzi-agent/issues"
47
+ },
48
+ "publishConfig": {
49
+ "access": "public"
50
+ }
51
+ }
@@ -0,0 +1,46 @@
1
+ ---
2
+ name: clipzi
3
+ description: Turn a long video (podcast, interview, stream, lecture, webinar) into finished short vertical clips for TikTok, Reels and YouTube Shorts with Clipzi. Use when the user wants clips, shorts, reels or highlights from a long video file, wants the best or funniest moments of a recording, or wants a specific moment cut, framed for vertical (following whoever talks, split screen for two), captioned and exported as mp4.
4
+ ---
5
+
6
+ # Clipzi
7
+
8
+ Clipzi takes a long video and gives back finished short clips: it transcribes it, finds the moments that stand on their own (cut on whole sentences), frames each one for vertical (the person talking, a split screen when two talk), adds captions and a title, removes dead air, and renders the mp4. You drive it with the `clipzi` command: `npx -y @clipzi/cli <command>` runs it without installing; `npm i -g @clipzi/cli` installs it as `clipzi`. The examples below write `clipzi` for short. Every command prints JSON on stdout; progress goes to stderr.
9
+
10
+ ## Setup (once)
11
+
12
+ - A person with a browser: `npx -y @clipzi/cli login` opens Clipzi to sign in and allow this terminal. No account yet? The same screen creates one.
13
+ - A server, CI or an agent with no browser: set `CLIPZI_API_KEY` to a key the person creates at https://clipzi.app/dashboard/agents.
14
+ - Check with `npx -y @clipzi/cli account`: the plan, how many long videos are left, how many clips the AI can still edit.
15
+
16
+ ## The short way
17
+
18
+ ```bash
19
+ npx -y @clipzi/cli make ./episode.mp4 --count 5 --out ./clips
20
+ ```
21
+
22
+ - The source can be a local file (uploaded for you), a link to the video FILE (direct https, or a Google Drive / Dropbox share link set to "anyone with the link"), or the id of a video already in Clipzi (`clipzi videos`).
23
+ - `--query "where they talk about pricing"` makes the clips about that instead of the best moments overall.
24
+ - `--template` picks the caption look (`clipzi call list_templates` lists them), `--pace off|natural|fast|extra` how much dead air is cut, `--title` puts the suggested title on the video, `--horizontal` gives each clip as it was filmed (no framing or captions; faster).
25
+ - Each clip is saved in `--out` as it finishes, named after its title. Allow a few minutes for the analysis of a new video plus 2 to 4 minutes per clip.
26
+
27
+ ## Step by step (when the person wants to choose)
28
+
29
+ 1. `clipzi upload <file> --wait` or `clipzi import <link> --wait` brings the video in and waits for the analysis.
30
+ 2. `clipzi clips <video_id>` lists the moments Clipzi found. `clipzi find <video_id> the funniest story` searches what is said. `clipzi transcript <video_id>` reads it to choose start and end yourself.
31
+ 3. `clipzi call create_clip '{"video_id":"...","start":120.5,"end":158,"title":"..."}'` makes a clip from times you chose.
32
+ 4. `clipzi make <video_id> --clips <id1,id2>` plans and renders exactly those clips. Or one at a time: `clipzi call plan_clip '{"clip_id":"..."}'`, then `clipzi render <clip_id>`.
33
+ 5. To restyle a clip without planning it again (title, caption look, logo, texts on the video): `clipzi call edit_clip '{"clip_id":"...","template":"..."}'`, then `clipzi render <clip_id>`.
34
+
35
+ `clipzi tools` lists every tool the server has and `clipzi call <tool> '<json>'` runs any of them.
36
+
37
+ ## Rules
38
+
39
+ - Times are in seconds.
40
+ - Ask the person before deleting anything (`delete_clip`, `delete_clip_file`) or replacing a clip they edited (`plan_clip` with `force`).
41
+ - Links to pages that play a video (YouTube, TikTok, Instagram, Vimeo) do not work: ask for the file, or a Drive / Dropbox link to it.
42
+ - An account without a plan can try Clipzi (2 long videos, 5 clips edited by the AI). Its clips come back as `watch_page` instead of a file: give the person that link, where they watch the clip in Clipzi. Downloading needs a plan.
43
+ - When a command answers `quota`, `paid_plan_required` or `payment_required`, run `clipzi account` and offer `clipzi call get_upgrade_link '{"plan":"starter_2026"}'` (or `agency` for Pro, `studio` for Business). The person pays on that page; never you.
44
+ - Exit codes: 0 done, 1 the tool could not (the JSON `error.message` says what to do), 2 wrong usage, 3 not signed in.
45
+
46
+ Everything made here also shows up in the Clipzi web app (https://clipzi.app/dashboard), where the person can change any clip. Docs: https://clipzi.app/en/developers
package/src/auth.mjs ADDED
@@ -0,0 +1,213 @@
1
+ // Who the CLI works as. Two ways, the same two the Clipzi MCP server takes:
2
+ //
3
+ // - CLIPZI_API_KEY (ck_live_...): for scripts, servers and agents with no
4
+ // browser. Created at https://clipzi.app/dashboard/agents.
5
+ // - `clipzi login`: OAuth 2.1 in the browser, like Claude Code connects an
6
+ // MCP server. The CLI registers itself as a public client (dynamic client
7
+ // registration), opens Clipzi's own sign-in and "Allow" screen with PKCE,
8
+ // takes the code on a loopback address and keeps the tokens in
9
+ // ~/.config/clipzi/credentials.json (readable by this user only). The
10
+ // access token is refreshed when it runs out.
11
+ //
12
+ // Everything is discovered from the server (RFC 9728 then RFC 8414), nothing
13
+ // about the authorization server is written here.
14
+
15
+ import { createHash, randomBytes } from 'node:crypto';
16
+ import { createServer } from 'node:http';
17
+ import { mkdir, readFile, rm, writeFile, chmod } from 'node:fs/promises';
18
+ import { homedir } from 'node:os';
19
+ import { join } from 'node:path';
20
+ import { spawn } from 'node:child_process';
21
+ import { say } from './util.mjs';
22
+
23
+ export const SITE = (process.env.CLIPZI_URL || 'https://clipzi.app').replace(/\/+$/, '');
24
+ export const MCP_URL = `${SITE}/mcp`;
25
+ const DIR = process.env.CLIPZI_CONFIG_DIR || join(homedir(), '.config', 'clipzi');
26
+ const FILE = join(DIR, 'credentials.json');
27
+
28
+ export class AuthError extends Error {}
29
+
30
+ const b64url = (buf) => Buffer.from(buf).toString('base64url');
31
+
32
+ /** PKCE: a random verifier and its S256 challenge. */
33
+ export function pkcePair() {
34
+ const verifier = b64url(randomBytes(32));
35
+ const challenge = b64url(createHash('sha256').update(verifier).digest());
36
+ return { verifier, challenge };
37
+ }
38
+
39
+ async function readCredentials() {
40
+ try { return JSON.parse(await readFile(FILE, 'utf8')); } catch { return null; }
41
+ }
42
+
43
+ async function saveCredentials(creds) {
44
+ await mkdir(DIR, { recursive: true, mode: 0o700 });
45
+ await writeFile(FILE, JSON.stringify(creds, null, 2), { mode: 0o600 });
46
+ await chmod(FILE, 0o600).catch(() => {});
47
+ }
48
+
49
+ export async function logout() {
50
+ const had = !!(await readCredentials());
51
+ await rm(FILE, { force: true });
52
+ return had;
53
+ }
54
+
55
+ async function getJson(url, init) {
56
+ const res = await fetch(url, init);
57
+ const text = await res.text();
58
+ let body;
59
+ try { body = JSON.parse(text); } catch { body = { raw: text.slice(0, 300) }; }
60
+ if (!res.ok) throw new AuthError(`${init?.method ?? 'GET'} ${url} answered ${res.status}: ${body.error_description ?? body.error ?? body.msg ?? body.raw ?? ''}`.trim());
61
+ return body;
62
+ }
63
+
64
+ /** Where to sign in, as the server says (protected resource metadata, then the authorization server's). */
65
+ async function discover() {
66
+ const resource = await getJson(`${SITE}/.well-known/oauth-protected-resource/mcp`);
67
+ const issuer = resource.authorization_servers?.[0];
68
+ if (!issuer) throw new AuthError('The server names no authorization server.');
69
+ const as = await getJson(`${issuer.replace(/\/+$/, '')}/.well-known/oauth-authorization-server`);
70
+ for (const k of ['authorization_endpoint', 'token_endpoint', 'registration_endpoint']) {
71
+ if (!as[k]) throw new AuthError(`The authorization server has no ${k}.`);
72
+ }
73
+ return { resource: resource.resource ?? MCP_URL, scopes: resource.scopes_supported ?? [], ...as };
74
+ }
75
+
76
+ function openBrowser(url) {
77
+ const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open';
78
+ const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url];
79
+ try {
80
+ const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
81
+ child.on('error', () => {});
82
+ child.unref();
83
+ } catch { /* the URL is printed anyway */ }
84
+ }
85
+
86
+ /**
87
+ * A loopback server on a free port that waits for one ?code=&state= and
88
+ * answers the browser. Resolves with its port; `code` settles with the code.
89
+ */
90
+ function startLoopback(expectedState, timeoutMs) {
91
+ return new Promise((resolveStart, rejectStart) => {
92
+ let settle;
93
+ const code = new Promise((resolve, reject) => { settle = { resolve, reject }; });
94
+ code.catch(() => {});
95
+ let timer;
96
+ const server = createServer((req, res) => {
97
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1');
98
+ if (url.pathname !== '/callback') { res.writeHead(404).end(); return; }
99
+ const got = url.searchParams.get('code');
100
+ const error = url.searchParams.get('error');
101
+ const ok = !!got && url.searchParams.get('state') === expectedState && !error;
102
+ res.writeHead(ok ? 200 : 400, { 'Content-Type': 'text/html; charset=utf-8' });
103
+ res.end(`<!doctype html><meta charset="utf-8"><title>Clipzi</title><body style="font-family:system-ui;background:#09090b;color:#e4e4e7;display:grid;place-items:center;height:100vh;margin:0"><p>${ok ? 'Clipzi is connected. You can close this tab and go back to the terminal.' : 'The sign-in did not finish. Go back to the terminal and run clipzi login again.'}</p>`);
104
+ clearTimeout(timer);
105
+ server.close();
106
+ if (ok) settle.resolve(got);
107
+ else settle.reject(new AuthError(error ? `Sign-in refused: ${url.searchParams.get('error_description') ?? error}` : 'The sign-in answer did not match this login.'));
108
+ });
109
+ server.on('error', rejectStart);
110
+ server.listen(0, '127.0.0.1', () => {
111
+ timer = setTimeout(() => { server.close(); settle.reject(new AuthError('Nobody finished the sign-in in time. Run clipzi login again.')); }, timeoutMs);
112
+ resolveStart({ port: server.address().port, code, close: () => { clearTimeout(timer); server.close(); } });
113
+ });
114
+ });
115
+ }
116
+
117
+ /**
118
+ * `clipzi login`: the browser opens Clipzi's sign-in and "Allow" screen; the
119
+ * tokens are kept for the next commands. Returns the account's email when the
120
+ * server tells it.
121
+ */
122
+ export async function login({ browser = true, timeoutMs = 5 * 60_000 } = {}) {
123
+ const as = await discover();
124
+ const state = b64url(randomBytes(16));
125
+ const { verifier, challenge } = pkcePair();
126
+
127
+ const loop = await startLoopback(state, timeoutMs);
128
+ const redirectUri = `http://127.0.0.1:${loop.port}/callback`;
129
+
130
+ let client;
131
+ try {
132
+ client = await getJson(as.registration_endpoint, {
133
+ method: 'POST',
134
+ headers: { 'Content-Type': 'application/json' },
135
+ body: JSON.stringify({
136
+ client_name: 'Clipzi CLI',
137
+ redirect_uris: [redirectUri],
138
+ grant_types: ['authorization_code', 'refresh_token'],
139
+ response_types: ['code'],
140
+ token_endpoint_auth_method: 'none',
141
+ }),
142
+ });
143
+ } catch (e) { loop.close(); throw e; }
144
+
145
+ const authorize = new URL(as.authorization_endpoint);
146
+ authorize.search = new URLSearchParams({
147
+ response_type: 'code',
148
+ client_id: client.client_id,
149
+ redirect_uri: redirectUri,
150
+ code_challenge: challenge,
151
+ code_challenge_method: 'S256',
152
+ state,
153
+ resource: as.resource,
154
+ ...(as.scopes.length ? { scope: as.scopes.join(' ') } : {}),
155
+ }).toString();
156
+
157
+ say('Opening Clipzi in your browser to sign in and allow this terminal.');
158
+ say(`If it does not open, visit:\n ${authorize}`);
159
+ if (browser) openBrowser(authorize.toString());
160
+
161
+ const code = await loop.code;
162
+ const tokens = await getJson(as.token_endpoint, {
163
+ method: 'POST',
164
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
165
+ body: new URLSearchParams({ grant_type: 'authorization_code', code, redirect_uri: redirectUri, client_id: client.client_id, code_verifier: verifier }),
166
+ });
167
+ await saveCredentials({
168
+ kind: 'oauth',
169
+ site: SITE,
170
+ client_id: client.client_id,
171
+ token_endpoint: as.token_endpoint,
172
+ access_token: tokens.access_token,
173
+ refresh_token: tokens.refresh_token ?? null,
174
+ expires_at: Date.now() + (Number(tokens.expires_in) || 3600) * 1000,
175
+ });
176
+ return { connected: true };
177
+ }
178
+
179
+ async function refresh(creds) {
180
+ if (!creds.refresh_token) throw new AuthError('The sign-in ran out. Run clipzi login again.');
181
+ let tokens;
182
+ try {
183
+ tokens = await getJson(creds.token_endpoint, {
184
+ method: 'POST',
185
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
186
+ body: new URLSearchParams({ grant_type: 'refresh_token', refresh_token: creds.refresh_token, client_id: creds.client_id }),
187
+ });
188
+ } catch {
189
+ throw new AuthError('The sign-in ran out or was revoked. Run clipzi login again.');
190
+ }
191
+ const next = {
192
+ ...creds,
193
+ access_token: tokens.access_token,
194
+ refresh_token: tokens.refresh_token ?? creds.refresh_token,
195
+ expires_at: Date.now() + (Number(tokens.expires_in) || 3600) * 1000,
196
+ };
197
+ await saveCredentials(next);
198
+ return next;
199
+ }
200
+
201
+ /** The bearer for the next request: the API key when set, else the saved sign-in (refreshed when needed). */
202
+ export async function bearer({ forceRefresh = false } = {}) {
203
+ // Only a real key counts: a desktop app that leaves the optional setting empty may pass "" or its own placeholder.
204
+ const key = process.env.CLIPZI_API_KEY?.trim();
205
+ if (key && key.startsWith('ck_')) return { token: key, via: 'api_key' };
206
+ let creds = await readCredentials();
207
+ if (!creds || creds.kind !== 'oauth') {
208
+ throw new AuthError('Not signed in. Run `clipzi login` (opens the browser), or set CLIPZI_API_KEY to a key from https://clipzi.app/dashboard/agents.');
209
+ }
210
+ if (creds.site && creds.site !== SITE) throw new AuthError(`The saved sign-in is for ${creds.site}. Run clipzi login again.`);
211
+ if (forceRefresh || Date.now() > creds.expires_at - 60_000) creds = await refresh(creds);
212
+ return { token: creds.access_token, via: 'oauth' };
213
+ }
@@ -0,0 +1,259 @@
1
+ // What each `clipzi <command>` does, on top of the server's tools (src/mcp.mjs).
2
+ // Every command prints one JSON answer on stdout; progress goes to stderr.
3
+
4
+ import { createWriteStream, existsSync, openAsBlob, statSync } from 'node:fs';
5
+ import { mkdir } from 'node:fs/promises';
6
+ import { basename, extname, join, resolve } from 'node:path';
7
+ import { Readable } from 'node:stream';
8
+ import { pipeline } from 'node:stream/promises';
9
+ import { callTool, listTools, ToolError } from './mcp.mjs';
10
+ import { login, logout, SITE } from './auth.mjs';
11
+ import { fileNameFor, intFlag, say, sleep, sourceKind, uniqueName, UsageError } from './util.mjs';
12
+
13
+ const WAIT = 50; // seconds the server waits per get_job / get_video call (its maximum)
14
+
15
+ /** Calls get_video until the analysis finished (or failed). */
16
+ async function waitForVideo(videoId) {
17
+ let last = '';
18
+ for (;;) {
19
+ const { video } = await callTool('get_video', { video_id: videoId, wait_seconds: WAIT });
20
+ if (video.stage !== last) { say(`Video ${videoId}: ${video.stage}`); last = video.stage; }
21
+ if (video.status === 'completed' || video.status === 'failed') return video;
22
+ }
23
+ }
24
+
25
+ /** Calls get_job until it is done or failed; `onRead` sees every read (make_clips fills in as it goes). */
26
+ async function waitForJob(jobId, onRead) {
27
+ for (;;) {
28
+ const job = await callTool('get_job', { job_id: jobId, wait_seconds: WAIT });
29
+ if (onRead) await onRead(job);
30
+ if (job.status === 'done' || job.status === 'failed') return job;
31
+ }
32
+ }
33
+
34
+ export async function download(url, dir, name, taken) {
35
+ await mkdir(dir, { recursive: true });
36
+ const file = join(dir, uniqueName(name, taken));
37
+ const res = await fetch(url);
38
+ if (!res.ok || !res.body) throw new Error(`Downloading ${url} answered ${res.status}`);
39
+ await pipeline(Readable.fromWeb(res.body), createWriteStream(file));
40
+ return resolve(file);
41
+ }
42
+
43
+ /** A local file into Clipzi: upload_video, the PUT, finish_upload. Returns the new video's id. */
44
+ export async function uploadFile(path) {
45
+ const size = statSync(path).size;
46
+ const filename = basename(path);
47
+ if (!/\.(mp4|mov|m4v|mkv|webm)$/i.test(extname(filename))) {
48
+ throw new UsageError(`${filename} does not look like a video (mp4, mov, mkv, webm).`);
49
+ }
50
+ const up = await callTool('upload_video', { filename, size_bytes: size });
51
+ say(`Uploading ${filename} (${(size / 1e6).toFixed(1)} MB)...`);
52
+ const res = await fetch(up.put_url, { method: 'PUT', headers: { 'Content-Type': 'video/mp4' }, body: await openAsBlob(path) });
53
+ if (!res.ok) throw new Error(`The upload answered ${res.status}: ${(await res.text()).slice(0, 300)}`);
54
+ const done = await callTool('finish_upload', { upload_id: up.upload_id });
55
+ say(`Uploaded. Clipzi is analyzing it (transcript, then the moments): ${done.dashboard ?? ''}`);
56
+ return done.video.id;
57
+ }
58
+
59
+ export const COMMANDS = {
60
+ async login(a) {
61
+ return login({ browser: a.flags.browser !== false });
62
+ },
63
+
64
+ async logout() {
65
+ return { signed_out: await logout() };
66
+ },
67
+
68
+ async account() {
69
+ return callTool('get_account');
70
+ },
71
+
72
+ async tools() {
73
+ return (await listTools()).map((t) => ({ name: t.name, title: t.title ?? t.annotations?.title ?? null }));
74
+ },
75
+
76
+ /** Any tool, by name, with its arguments as JSON: everything the server can do. */
77
+ async call(a) {
78
+ const [name, json] = a._;
79
+ if (!name) throw new UsageError('clipzi call <tool> \'{"arg": "value"}\' (clipzi tools lists them)');
80
+ let args = {};
81
+ if (json) { try { args = JSON.parse(json); } catch { throw new UsageError('The arguments must be JSON, e.g. \'{"video_id": "clip-upload-..."}\''); } }
82
+ return callTool(name, args);
83
+ },
84
+
85
+ async videos(a) {
86
+ return callTool('list_videos', { limit: intFlag(a.flags, 'limit', 20) });
87
+ },
88
+
89
+ async video(a) {
90
+ const [id] = a._;
91
+ if (!id) throw new UsageError('clipzi video <video_id> [--wait]');
92
+ return a.flags.wait ? { video: await waitForVideo(id) } : callTool('get_video', { video_id: id });
93
+ },
94
+
95
+ async upload(a) {
96
+ const [path] = a._;
97
+ if (!path || !existsSync(path)) throw new UsageError('clipzi upload <video file> [--wait]');
98
+ const id = await uploadFile(path);
99
+ return { video: a.flags.wait ? await waitForVideo(id) : { id, status: 'pending' } };
100
+ },
101
+
102
+ async import(a) {
103
+ const [url] = a._;
104
+ if (!url) throw new UsageError('clipzi import <link to the video file, or a Drive / Dropbox share link> [--wait]');
105
+ const out = await callTool('import_video', { url });
106
+ return a.flags.wait ? { ...out, video: await waitForVideo(out.video.id) } : out;
107
+ },
108
+
109
+ async clips(a) {
110
+ const [id] = a._;
111
+ if (!id) throw new UsageError('clipzi clips <video_id>');
112
+ return callTool('list_clips', { video_id: id });
113
+ },
114
+
115
+ async transcript(a) {
116
+ const [id] = a._;
117
+ if (!id) throw new UsageError('clipzi transcript <video_id> [--start s] [--end s]');
118
+ const args = { video_id: id };
119
+ if (a.flags.start !== undefined) args.start = Number(a.flags.start);
120
+ if (a.flags.end !== undefined) args.end = Number(a.flags.end);
121
+ return callTool('get_transcript', args);
122
+ },
123
+
124
+ async find(a) {
125
+ const [id, ...words] = a._;
126
+ if (!id || !words.length) throw new UsageError('clipzi find <video_id> <what to look for> [--count 5]');
127
+ return callTool('find_moments', { video_id: id, query: words.join(' '), count: intFlag(a.flags, 'count', 5) });
128
+ },
129
+
130
+ async job(a) {
131
+ const [id] = a._;
132
+ if (!id) throw new UsageError('clipzi job <job_id> [--wait]');
133
+ return a.flags.wait ? waitForJob(id) : callTool('get_job', { job_id: id });
134
+ },
135
+
136
+ /**
137
+ * The short way: a file, a link or a video already in Clipzi, to finished
138
+ * clips on disk. Uploads a local file first, runs make_clips, follows the
139
+ * job and downloads each clip as it finishes (an account without a plan
140
+ * gets each clip's page to watch it instead).
141
+ */
142
+ async make(a) {
143
+ const [source] = a._;
144
+ if (!source) throw new UsageError('clipzi make <video file | link | video_id> [--count 5] [--query "..."] [--out ./clips]');
145
+ const f = a.flags;
146
+ const args = { count: intFlag(f, 'count', 5) };
147
+ if (f.query) args.query = String(f.query);
148
+ if (f.clips) args.clip_ids = String(f.clips).split(',').map((s) => s.trim()).filter(Boolean);
149
+ if (f.template) args.template = String(f.template);
150
+ if (f.pace) args.pace = String(f.pace);
151
+ if (f.title !== undefined) args.title = f.title !== false && f.title !== 'false';
152
+ if (f.horizontal) args.format = 'horizontal';
153
+
154
+ const kind = sourceKind(source, existsSync);
155
+ if (kind === 'file') args.video_id = await uploadFile(source);
156
+ else if (kind === 'url') args.url = source;
157
+ else args.video_id = source;
158
+
159
+ const started = await callTool('make_clips', args);
160
+ say(`Making clips (job ${started.job_id}). ${started.video?.dashboard ?? ''}`.trim());
161
+ if (f.wait === false) return started;
162
+
163
+ const out = resolve(String(f.out ?? 'clips'));
164
+ const fetchFiles = f.download !== false;
165
+ const files = new Map(); // clip_id -> local path
166
+ const taken = new Set();
167
+ let reported = '';
168
+ const job = await waitForJob(started.job_id, async (j) => {
169
+ const r = j.result ?? {};
170
+ const line = r.stage === 'waiting_for_video' ? 'waiting for the video analysis' : `${r.done ?? 0} of ${r.total ?? '?'} clips finished`;
171
+ if (line !== reported) { say(line); reported = line; }
172
+ for (const c of r.clips ?? []) {
173
+ if (c.status !== 'done' || files.has(c.clip_id)) continue;
174
+ if (c.url && fetchFiles) {
175
+ const path = await download(c.url, out, fileNameFor(c.title, 'mp4'), taken);
176
+ files.set(c.clip_id, path);
177
+ say(` saved ${path}`);
178
+ } else if (c.watch_page) {
179
+ files.set(c.clip_id, null);
180
+ say(` ready to watch: ${c.watch_page}`);
181
+ }
182
+ }
183
+ });
184
+ const r = job.result ?? {};
185
+ return {
186
+ job_id: job.job_id,
187
+ status: job.status,
188
+ video_id: r.video_id ?? args.video_id ?? null,
189
+ ...(job.error ? { error: job.error } : {}),
190
+ clips: (r.clips ?? []).map((c) => ({
191
+ clip_id: c.clip_id, title: c.title, start: c.start, end: c.end, status: c.status,
192
+ ...(files.get(c.clip_id) ? { file: files.get(c.clip_id) } : {}),
193
+ ...(c.url ? { url: c.url } : {}),
194
+ ...(c.watch_page ? { watch_page: c.watch_page } : {}),
195
+ ...(c.why ? { why: c.why } : {}),
196
+ ...(c.error ? { error: c.error } : {}),
197
+ })),
198
+ ...(job.note ? { note: job.note } : {}),
199
+ };
200
+ },
201
+
202
+ /** One clip's file: renders it when needed, waits, downloads it. */
203
+ async render(a) {
204
+ const [clipId] = a._;
205
+ if (!clipId) throw new UsageError('clipzi render <clip_id> [--horizontal] [--edited] [--out ./clips]');
206
+ const args = { clip_id: clipId };
207
+ if (a.flags.horizontal) { args.format = 'horizontal'; if (a.flags.edited) args.edited = true; }
208
+ const started = await callTool('render_clip', args);
209
+ if (a.flags.wait === false) return started;
210
+ const job = started.status === 'done' ? started : await waitForJob(started.job_id);
211
+ const url = job.result?.url;
212
+ if (job.status === 'done' && url && a.flags.download !== false) {
213
+ const { clip } = await callTool('get_clip', { clip_id: clipId });
214
+ const name = fileNameFor(args.format === 'horizontal' ? `${clip.title} (horizontal)` : clip.title, 'mp4');
215
+ return { ...job, file: await download(url, resolve(String(a.flags.out ?? 'clips')), name, new Set()) };
216
+ }
217
+ return job;
218
+ },
219
+ };
220
+
221
+ export const BOOLEAN_FLAGS = new Set(['wait', 'title', 'horizontal', 'edited', 'download', 'browser', 'help']);
222
+
223
+ export const HELP = `clipzi: long videos in, finished short clips out. ${SITE}
224
+ Run with npx -y @clipzi/cli <command>, or npm i -g @clipzi/cli for the clipzi command.
225
+
226
+ Sign in
227
+ clipzi login Opens the browser to sign in and allow this terminal
228
+ clipzi logout
229
+ (or set CLIPZI_API_KEY to a key from ${SITE}/dashboard/agents, for servers and CI)
230
+
231
+ The short way
232
+ clipzi make <file | link | video_id> [--count 5] [--query "the funny parts"]
233
+ [--template impacto] [--pace fast] [--title] [--horizontal]
234
+ [--out ./clips] [--no-wait] [--no-download]
235
+ Uploads a local file (or takes a link to the file, Drive or Dropbox),
236
+ lets Clipzi choose the moments, frames them for vertical, captions them,
237
+ and saves each mp4 in --out as it finishes.
238
+
239
+ Step by step
240
+ clipzi account Plan, what is left, what the agent may do
241
+ clipzi videos The videos in the account
242
+ clipzi upload <file> [--wait]
243
+ clipzi import <link> [--wait]
244
+ clipzi video <video_id> [--wait]
245
+ clipzi clips <video_id> The clips Clipzi found
246
+ clipzi transcript <video_id> [--start s] [--end s]
247
+ clipzi find <video_id> <what to look for> [--count 5]
248
+ clipzi render <clip_id> [--horizontal [--edited]] [--out ./clips]
249
+ clipzi job <job_id> [--wait]
250
+
251
+ Everything else
252
+ clipzi tools Every tool the server has
253
+ clipzi call <tool> '<json>' Call any of them
254
+
255
+ Every command prints JSON on stdout (progress on stderr). Exit codes: 0 done,
256
+ 1 the tool could not (the JSON says why and what to do), 2 wrong usage,
257
+ 3 not signed in. Docs: ${SITE}/en/developers`;
258
+
259
+ export { ToolError };
@@ -0,0 +1,172 @@
1
+ #!/usr/bin/env node
2
+ // Clipzi for Claude Desktop (and any app that runs local MCP servers): a small
3
+ // server on the person's own computer, over stdio. It is Clipzi's whole MCP
4
+ // server (https://clipzi.app/mcp, every tool passed through as the signed-in
5
+ // person) plus what only a program on their machine can do:
6
+ //
7
+ // upload_local_video a video FILE on this computer goes straight to Clipzi
8
+ // (a chat app's remote connector cannot read it);
9
+ // save_clip a finished clip is saved into a folder here;
10
+ // sign_in / sign_out the browser opens Clipzi's own sign-in and "Allow".
11
+ //
12
+ // No dependencies: the protocol is JSON-RPC, one message per line.
13
+ // Nothing but protocol messages may go to stdout; progress goes to stderr.
14
+
15
+ import { createInterface } from 'node:readline';
16
+ import { existsSync, statSync } from 'node:fs';
17
+ import { homedir } from 'node:os';
18
+ import { join, resolve } from 'node:path';
19
+ import { AuthError, bearer, login, logout, MCP_URL, SITE } from './auth.mjs';
20
+ import { rpc, ToolError } from './mcp.mjs';
21
+ import { download, uploadFile } from './commands.mjs';
22
+ import { fileNameFor, UsageError } from './util.mjs';
23
+
24
+ process.env.CLIPZI_QUIET ??= '';
25
+ const VERSION = '0.1.0';
26
+ const PROTOCOLS = ['2025-06-18', '2025-03-26', '2024-11-05'];
27
+ /** The remote tools this server replaces with its own (a local file needs no address to PUT to, and no upload page). */
28
+ const REPLACED = new Set(['upload_video', 'finish_upload', 'get_upload_link']);
29
+ /** Files are only saved from Clipzi's own hosts. */
30
+ const CLIP_HOSTS = new Set(['clips.clipzi.cc', 'clipzi.app']);
31
+
32
+ const send = (msg) => process.stdout.write(`${JSON.stringify(msg)}\n`);
33
+ const text = (value, isError = false) => ({ content: [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }], isError });
34
+ const expand = (p) => resolve(String(p).replace(/^~(?=$|\/)/, homedir()));
35
+
36
+ const LOCAL_TOOLS = [
37
+ {
38
+ name: 'upload_local_video',
39
+ title: 'Upload a video file from this computer',
40
+ description: 'Brings a long video into Clipzi from a FILE on this computer (mp4, mov, mkv, webm): give its full path. The file goes straight to the person\'s Clipzi account and the analysis starts (transcription, then clip detection). Returns the video id: pass it to make_clips, which waits for the analysis itself, or follow it with get_video and wait_seconds. Counts as one video of the plan. Use this whenever the video is on the person\'s computer; with a link to the file use import_video.',
41
+ inputSchema: { type: 'object', properties: { path: { type: 'string', description: 'Full path of the video file, e.g. /Users/ana/Movies/episode.mp4 (a leading ~ is the home folder).' } }, required: ['path'], additionalProperties: false },
42
+ annotations: { title: 'Upload a video file from this computer', readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
43
+ },
44
+ {
45
+ name: 'save_clip',
46
+ title: 'Save a finished clip to this computer',
47
+ description: 'Saves a finished clip (the url of a render_clip or make_clips result) as an mp4 in a folder of this computer: the Downloads folder unless another is given. The file is named after the title you pass; an existing file is never replaced. Only for clips that came with a url: an account without a plan gets watch_page instead, which is opened in the browser, not saved.',
48
+ inputSchema: { type: 'object', properties: {
49
+ url: { type: 'string', description: 'The clip\'s url, as a Clipzi tool returned it.' },
50
+ title: { type: 'string', description: 'The clip\'s title, used as the file name.' },
51
+ folder: { type: 'string', description: 'Folder to save into. Default: ~/Downloads.' },
52
+ }, required: ['url'], additionalProperties: false },
53
+ annotations: { title: 'Save a finished clip to this computer', readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
54
+ },
55
+ {
56
+ name: 'sign_out',
57
+ title: 'Sign this computer out of Clipzi',
58
+ description: 'Forgets the Clipzi sign-in kept on this computer. Ask the person before calling it.',
59
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
60
+ annotations: { title: 'Sign this computer out of Clipzi', readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
61
+ },
62
+ ];
63
+
64
+ const SIGN_IN = {
65
+ name: 'sign_in',
66
+ title: 'Sign in to Clipzi',
67
+ description: 'Opens Clipzi in the person\'s browser to sign in (or create their account, no card) and allow this computer. Returns at once: tell the person to finish in the browser and to say when it is done; then the Clipzi tools are available. Call this first whenever a Clipzi tool answers not_signed_in.',
68
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
69
+ annotations: { title: 'Sign in to Clipzi', readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
70
+ };
71
+
72
+ const INSTRUCTIONS =
73
+ 'Clipzi turns long videos into finished short clips. This server runs on the person\'s computer, so a video FILE on it can be used directly: upload_local_video with its path, then make_clips with the video id, then get_job with wait_seconds until done. ' +
74
+ 'With a link to the file (direct, Google Drive, Dropbox) use import_video or make_clips with url. save_clip puts a finished clip in the Downloads folder. ' +
75
+ 'If a tool answers not_signed_in, call sign_in and wait for the person to finish in the browser. ' +
76
+ 'An account without a plan gets each clip as watch_page (its page in Clipzi) instead of a file: give the person that link; downloading needs a plan, and the person pays on the page get_upgrade_link returns, never you. ' +
77
+ 'Ask before deleting anything. Times are in seconds.';
78
+
79
+ const signedIn = async () => { try { await bearer(); return true; } catch { return false; } };
80
+ let signingIn = null;
81
+
82
+ async function listTools() {
83
+ if (!(await signedIn())) return [SIGN_IN];
84
+ try {
85
+ const remote = (await rpc('tools/list', {}))?.tools ?? [];
86
+ return [...LOCAL_TOOLS.slice(0, 2), ...remote.filter((t) => !REPLACED.has(t.name)), SIGN_IN, LOCAL_TOOLS[2]];
87
+ } catch (e) {
88
+ // The sign-in was revoked or ran out: back to the one tool that fixes it.
89
+ if (e instanceof AuthError) return [SIGN_IN];
90
+ throw e;
91
+ }
92
+ }
93
+
94
+ async function callLocal(name, args) {
95
+ if (name === 'sign_in') {
96
+ if (await signedIn()) return text({ signed_in: true, next: 'Already signed in. Use the Clipzi tools.' });
97
+ if (!signingIn) {
98
+ signingIn = login().then(() => send({ jsonrpc: '2.0', method: 'notifications/tools/list_changed' }))
99
+ .catch((e) => process.stderr.write(`sign-in did not finish: ${e?.message ?? e}\n`))
100
+ .finally(() => { signingIn = null; });
101
+ }
102
+ return text({ signed_in: false, opened: 'A browser window opened on Clipzi\'s sign-in.', next: `Ask the person to sign in (or create their account, no card) and press Allow, then to tell you when it is done. If no window opened, they can connect at ${SITE}/en/mcp.` });
103
+ }
104
+ if (name === 'sign_out') {
105
+ const had = await logout();
106
+ send({ jsonrpc: '2.0', method: 'notifications/tools/list_changed' });
107
+ return text({ signed_out: had });
108
+ }
109
+ if (name === 'upload_local_video') {
110
+ const path = expand(args?.path ?? '');
111
+ if (!args?.path || !existsSync(path) || !statSync(path).isFile()) return text(`not_found: No file at "${path}". Ask the person for the full path of the video (they can drag the file into the chat to get it).`, true);
112
+ const id = await uploadFile(path);
113
+ return text({ video: { id, status: 'pending', dashboard: `${SITE}/dashboard/${id}` }, next: 'make_clips with this video_id (it waits for the analysis), or get_video with wait_seconds: 50 until status is completed.' });
114
+ }
115
+ if (name === 'save_clip') {
116
+ let url;
117
+ try { url = new URL(String(args?.url ?? '')); } catch { return text('invalid_input: url is not an address.', true); }
118
+ if (url.protocol !== 'https:' || !CLIP_HOSTS.has(url.host)) return text('invalid_input: Only a clip url returned by a Clipzi tool can be saved. A watch_page is opened in the browser instead.', true);
119
+ const folder = expand(args?.folder || join(homedir(), 'Downloads'));
120
+ const file = await download(url.toString(), folder, fileNameFor(args?.title, 'mp4'), new Set(existsSync(folder) ? (await import('node:fs')).readdirSync(folder) : []));
121
+ return text({ saved: file });
122
+ }
123
+ return null;
124
+ }
125
+
126
+ async function callTool(name, args) {
127
+ try {
128
+ const local = await callLocal(name, args);
129
+ if (local) return local;
130
+ if (REPLACED.has(name)) return text('not_available: On this computer use upload_local_video with the file\'s path.', true);
131
+ // Everything else is Clipzi's own tool, passed through as it answers.
132
+ return await rpc('tools/call', { name, arguments: args ?? {} });
133
+ } catch (e) {
134
+ if (e instanceof AuthError) return text('not_signed_in: Clipzi is not signed in on this computer. Call sign_in, then ask the person to finish in the browser.', true);
135
+ if (e instanceof ToolError) return text(`${e.code}: ${e.message}`, true);
136
+ if (e instanceof UsageError) return text(`invalid_input: ${e.message}`, true);
137
+ return text(`failed: ${e?.message ?? e}`, true);
138
+ }
139
+ }
140
+
141
+ async function handle(msg) {
142
+ const { id, method, params } = msg;
143
+ const reply = (result) => send({ jsonrpc: '2.0', id, result });
144
+ const fail = (code, message) => send({ jsonrpc: '2.0', id, error: { code, message } });
145
+ if (id === undefined || id === null) return; // a notification: nothing to answer
146
+ try {
147
+ if (method === 'initialize') {
148
+ return reply({
149
+ protocolVersion: PROTOCOLS.includes(params?.protocolVersion) ? params.protocolVersion : PROTOCOLS[0],
150
+ capabilities: { tools: { listChanged: true } },
151
+ serverInfo: { name: 'clipzi', title: 'Clipzi', version: VERSION },
152
+ instructions: INSTRUCTIONS,
153
+ });
154
+ }
155
+ if (method === 'ping') return reply({});
156
+ if (method === 'tools/list') return reply({ tools: await listTools() });
157
+ if (method === 'tools/call') return reply(await callTool(String(params?.name ?? ''), params?.arguments));
158
+ return fail(-32601, `Method not found: ${method}`);
159
+ } catch (e) {
160
+ return fail(-32603, e?.message ?? String(e));
161
+ }
162
+ }
163
+
164
+ const lines = createInterface({ input: process.stdin, crlfDelay: Infinity });
165
+ lines.on('line', (line) => {
166
+ if (!line.trim()) return;
167
+ let msg;
168
+ try { msg = JSON.parse(line); } catch { return send({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }); }
169
+ void handle(msg);
170
+ });
171
+ lines.on('close', () => process.exit(0));
172
+ process.stderr.write(`clipzi desktop server ${VERSION} ready (${MCP_URL})\n`);
package/src/mcp.mjs ADDED
@@ -0,0 +1,81 @@
1
+ // The CLI is a thin client of Clipzi's MCP server (https://clipzi.app/mcp):
2
+ // every command is one or more of the same tools Claude or ChatGPT call, with
3
+ // the same rules (plan, limits, a trial's clips as pages to watch). Stateless
4
+ // Streamable HTTP with plain JSON answers: one POST per call, no session.
5
+
6
+ import { AuthError, bearer, MCP_URL } from './auth.mjs';
7
+
8
+ /** A tool that could not do what was asked: its code (quota, not_found, paid_plan_required...) and what to do. */
9
+ export class ToolError extends Error {
10
+ constructor(code, message) {
11
+ super(message);
12
+ this.code = code;
13
+ }
14
+ }
15
+
16
+ let nextId = 1;
17
+
18
+ /** "code: message" (the server's error text) as its two parts. */
19
+ export function splitToolError(text) {
20
+ const m = /^([a-z_]+):\s*([\s\S]*)$/.exec(String(text ?? ''));
21
+ return m ? { code: m[1], message: m[2] } : { code: 'tool_error', message: String(text ?? 'The tool failed') };
22
+ }
23
+
24
+ /** A tools/call answer as the tool's value, or a ToolError. */
25
+ export function readToolResult(result) {
26
+ const text = result?.content?.find?.((c) => c?.type === 'text')?.text;
27
+ if (result?.isError) {
28
+ const { code, message } = splitToolError(text);
29
+ throw new ToolError(code, message);
30
+ }
31
+ if (result?.structuredContent && typeof result.structuredContent === 'object') return result.structuredContent;
32
+ try { return JSON.parse(text); } catch { return text ?? null; }
33
+ }
34
+
35
+ async function post(body, token) {
36
+ return fetch(MCP_URL, {
37
+ method: 'POST',
38
+ headers: {
39
+ 'Content-Type': 'application/json',
40
+ Accept: 'application/json, text/event-stream',
41
+ Authorization: `Bearer ${token}`,
42
+ 'User-Agent': 'clipzi-cli',
43
+ },
44
+ body: JSON.stringify(body),
45
+ });
46
+ }
47
+
48
+ /** One JSON-RPC request to the server, signed in. A 401 on a saved sign-in refreshes it once. */
49
+ export async function rpc(method, params) {
50
+ const body = { jsonrpc: '2.0', id: nextId++, method, ...(params ? { params } : {}) };
51
+ let auth = await bearer();
52
+ let res = await post(body, auth.token);
53
+ if (res.status === 401 && auth.via === 'oauth') {
54
+ auth = await bearer({ forceRefresh: true });
55
+ res = await post(body, auth.token);
56
+ }
57
+ if (res.status === 401) {
58
+ throw new AuthError(auth.via === 'api_key'
59
+ ? 'CLIPZI_API_KEY was refused (wrong or revoked). Make a new one at https://clipzi.app/dashboard/agents.'
60
+ : 'The sign-in was refused. Run clipzi login again.');
61
+ }
62
+ if (res.status === 429) {
63
+ const wait = Number(res.headers.get('retry-after')) || 10;
64
+ throw new ToolError('rate_limited', `Too many requests. Try again in ${wait} s.`);
65
+ }
66
+ const text = await res.text();
67
+ let msg;
68
+ try { msg = JSON.parse(text); } catch { throw new Error(`Clipzi answered ${res.status} with something that is not JSON.`); }
69
+ if (msg.error) throw new ToolError('protocol_error', msg.error.message ?? JSON.stringify(msg.error));
70
+ return msg.result;
71
+ }
72
+
73
+ /** Call one Clipzi tool: its value, or a ToolError with the server's code and advice. */
74
+ export async function callTool(name, args = {}) {
75
+ return readToolResult(await rpc('tools/call', { name, arguments: args }));
76
+ }
77
+
78
+ /** The tools the server offers this account, with their descriptions and inputs. */
79
+ export async function listTools() {
80
+ return (await rpc('tools/list', {}))?.tools ?? [];
81
+ }
package/src/util.mjs ADDED
@@ -0,0 +1,83 @@
1
+ // Small pieces every command uses: arguments, output, file names.
2
+ // Pure (no network, no disk) so the tests can hold them.
3
+
4
+ /**
5
+ * argv -> { _: positionals, flags }. `--count 5`, `--count=5` and `--title`
6
+ * (a flag with no value, true) all work; `--no-wait` sets wait: false.
7
+ * Names in BOOLEAN never take the next word as their value.
8
+ */
9
+ export function parseArgs(argv, BOOLEAN = new Set()) {
10
+ const out = { _: [], flags: {} };
11
+ for (let i = 0; i < argv.length; i++) {
12
+ const a = argv[i];
13
+ if (a === '--') { out._.push(...argv.slice(i + 1)); break; }
14
+ if (!a.startsWith('--') || a === '--') { out._.push(a); continue; }
15
+ const eq = a.indexOf('=');
16
+ const name = toCamel(eq > 0 ? a.slice(2, eq) : a.slice(2));
17
+ if (eq > 0) { out.flags[name] = a.slice(eq + 1); continue; }
18
+ if (name.startsWith('no') && name.length > 2 && name[2] === name[2].toUpperCase()) {
19
+ out.flags[name[2].toLowerCase() + name.slice(3)] = false;
20
+ continue;
21
+ }
22
+ const next = argv[i + 1];
23
+ if (BOOLEAN.has(name) || next === undefined || next.startsWith('--')) out.flags[name] = true;
24
+ else { out.flags[name] = next; i++; }
25
+ }
26
+ return out;
27
+ }
28
+
29
+ const toCamel = (s) => s.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
30
+
31
+ /** A whole number flag, or the default; a usage error when it is not a number. */
32
+ export function intFlag(flags, name, fallback) {
33
+ if (flags[name] === undefined) return fallback;
34
+ const n = Number(flags[name]);
35
+ if (!Number.isInteger(n)) throw new UsageError(`--${name} takes a whole number`);
36
+ return n;
37
+ }
38
+
39
+ export class UsageError extends Error {}
40
+
41
+ /** A clip's title as a file name that every system accepts, with its extension. */
42
+ export function fileNameFor(title, ext = 'mp4', fallback = 'clip') {
43
+ const base = String(title ?? '')
44
+ .normalize('NFKC')
45
+ .replace(/[\u0000-\u001f<>:"/\\|?*]+/g, ' ')
46
+ .replace(/\s+/g, ' ')
47
+ .trim()
48
+ .replace(/[. ]+$/, '')
49
+ .slice(0, 120)
50
+ .trim();
51
+ return `${base || fallback}.${ext}`;
52
+ }
53
+
54
+ /** The same name made unique among those already taken: "Title.mp4", "Title (2).mp4"... */
55
+ export function uniqueName(name, taken) {
56
+ if (!taken.has(name)) { taken.add(name); return name; }
57
+ const dot = name.lastIndexOf('.');
58
+ const stem = dot > 0 ? name.slice(0, dot) : name;
59
+ const ext = dot > 0 ? name.slice(dot) : '';
60
+ for (let i = 2; ; i++) {
61
+ const candidate = `${stem} (${i})${ext}`;
62
+ if (!taken.has(candidate)) { taken.add(candidate); return candidate; }
63
+ }
64
+ }
65
+
66
+ /** What a make/import argument is: a local file, a link, or the id of a video already in Clipzi. */
67
+ export function sourceKind(arg, exists) {
68
+ if (/^https?:\/\//i.test(arg)) return 'url';
69
+ if (exists(arg)) return 'file';
70
+ return 'video_id';
71
+ }
72
+
73
+ export const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
74
+
75
+ /** The answer of every command: JSON on stdout, so an agent can read it and a person too. */
76
+ export function print(value) {
77
+ process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
78
+ }
79
+
80
+ /** What is happening, for whoever watches: stderr, never mixed with the JSON answer. */
81
+ export function say(text) {
82
+ if (!process.env.CLIPZI_QUIET) process.stderr.write(`${text}\n`);
83
+ }