@cliptude/cli 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/README.md +46 -0
- package/cliptude_mcp/__init__.py +1 -0
- package/cliptude_mcp/__main__.py +4 -0
- package/cliptude_mcp/__pycache__/__init__.cpython-313.pyc +0 -0
- package/cliptude_mcp/__pycache__/auth.cpython-313.pyc +0 -0
- package/cliptude_mcp/__pycache__/auth_login.cpython-313.pyc +0 -0
- package/cliptude_mcp/__pycache__/cli.cpython-313.pyc +0 -0
- package/cliptude_mcp/__pycache__/client.cpython-313.pyc +0 -0
- package/cliptude_mcp/__pycache__/credentials.cpython-313.pyc +0 -0
- package/cliptude_mcp/auth.py +82 -0
- package/cliptude_mcp/auth_login.py +220 -0
- package/cliptude_mcp/cli.py +152 -0
- package/cliptude_mcp/client.py +238 -0
- package/cliptude_mcp/credentials.py +52 -0
- package/cliptude_mcp/server.py +225 -0
- package/npm/bin/cliptude.js +65 -0
- package/package.json +27 -0
- package/pyproject.toml +23 -0
package/README.md
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# Cliptude CLI + MCP
|
|
2
|
+
|
|
3
|
+
Generate videos from a saved template. Same account and credits as cliptude.com.
|
|
4
|
+
|
|
5
|
+
## Set up
|
|
6
|
+
|
|
7
|
+
1. Install the CLI: run `npm i -g @cliptude/cli`.
|
|
8
|
+
2. Authenticate: run `cliptude auth login` and complete the sign-in in the browser it opens.
|
|
9
|
+
3. Install the companion skills: run `npx skills add cliptude/cliptude --path mcp_server/skills`.
|
|
10
|
+
|
|
11
|
+
From this repo without npm:
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pip install -e .
|
|
15
|
+
cliptude auth login
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Commands
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
cliptude templates
|
|
22
|
+
cliptude generate --template "Finance vector weekly" --title "Why index funds win" --prompt "…"
|
|
23
|
+
cliptude generate --template "Finance vector weekly" --title "Why index funds win" --script-file script.txt
|
|
24
|
+
cliptude status <job-id>
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
`--title` is required. `generate` returns immediately (`queued`). Poll `status`.
|
|
28
|
+
|
|
29
|
+
Faceless bring-your-own coding:
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
cliptude generate --template "My Faceless" --title "…" --prompt "…" --faceless-coding external
|
|
33
|
+
cliptude kit <job-id> --out ./kit.zip
|
|
34
|
+
cliptude submit-project <job-id> ./project.zip
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## MCP
|
|
38
|
+
|
|
39
|
+
Remote Streamable HTTP: `https://mcp.cliptude.com/mcp` (OAuth or Bearer).
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
cliptude-mcp
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Unauthenticated `POST /mcp` returns 401 with `WWW-Authenticate` pointing at RFC 9728 metadata.
|
|
46
|
+
Stdio never writes to stdout except JSON-RPC.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Cliptude MCP/CLI skill for coding agents."""
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""TokenVerifier for Streamable HTTP MCP. Validates OAuth tokens and clp_ API keys via REST."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
from cliptude_mcp.client import resolve_base_url
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _resource_url() -> str:
|
|
14
|
+
return (os.environ.get("MCP_RESOURCE_URL") or "https://mcp.cliptude.com/mcp").rstrip("/")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _issuer_url() -> str:
|
|
18
|
+
return (os.environ.get("OAUTH_ISSUER") or "https://cliptude.com").rstrip("/")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class CliptudeTokenVerifier:
|
|
22
|
+
"""Accept django-oauth-toolkit access tokens and hashed clp_ API keys.
|
|
23
|
+
|
|
24
|
+
Verification is delegated to GET /api/v1/account so this process never imports Django.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(self, base_url: str | None = None, timeout: float = 10.0):
|
|
28
|
+
self.base_url = (base_url or resolve_base_url()).rstrip("/")
|
|
29
|
+
self.timeout = timeout
|
|
30
|
+
|
|
31
|
+
async def verify_token(self, token: str) -> Any:
|
|
32
|
+
token = (token or "").strip()
|
|
33
|
+
if not token:
|
|
34
|
+
return None
|
|
35
|
+
try:
|
|
36
|
+
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
|
37
|
+
resp = await client.get(
|
|
38
|
+
f"{self.base_url}/api/v1/account",
|
|
39
|
+
headers={
|
|
40
|
+
"Authorization": f"Bearer {token}",
|
|
41
|
+
"Accept": "application/json",
|
|
42
|
+
},
|
|
43
|
+
)
|
|
44
|
+
except httpx.HTTPError:
|
|
45
|
+
return None
|
|
46
|
+
if resp.status_code != 200:
|
|
47
|
+
return None
|
|
48
|
+
try:
|
|
49
|
+
payload = resp.json()
|
|
50
|
+
except ValueError:
|
|
51
|
+
payload = {}
|
|
52
|
+
email = ""
|
|
53
|
+
if isinstance(payload, dict):
|
|
54
|
+
email = str(payload.get("email") or "")
|
|
55
|
+
try:
|
|
56
|
+
from mcp.server.auth.provider import AccessToken
|
|
57
|
+
except ImportError: # pragma: no cover - stdio tests without the SDK
|
|
58
|
+
from types import SimpleNamespace
|
|
59
|
+
|
|
60
|
+
return SimpleNamespace(
|
|
61
|
+
token=token,
|
|
62
|
+
client_id=email or "cliptude",
|
|
63
|
+
scopes=["jobs"],
|
|
64
|
+
resource=_resource_url(),
|
|
65
|
+
)
|
|
66
|
+
return AccessToken(
|
|
67
|
+
token=token,
|
|
68
|
+
client_id=email or "cliptude",
|
|
69
|
+
scopes=["jobs"],
|
|
70
|
+
resource=_resource_url(),
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def auth_settings():
|
|
75
|
+
from pydantic import AnyHttpUrl
|
|
76
|
+
from mcp.server.auth.settings import AuthSettings
|
|
77
|
+
|
|
78
|
+
return AuthSettings(
|
|
79
|
+
issuer_url=AnyHttpUrl(_issuer_url()),
|
|
80
|
+
resource_server_url=AnyHttpUrl(_resource_url()),
|
|
81
|
+
required_scopes=["jobs"],
|
|
82
|
+
)
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
"""Browser OAuth login for the CLI (PKCE + loopback callback)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import hashlib
|
|
7
|
+
import secrets
|
|
8
|
+
import threading
|
|
9
|
+
import urllib.parse
|
|
10
|
+
import webbrowser
|
|
11
|
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
import httpx
|
|
15
|
+
|
|
16
|
+
from cliptude_mcp.client import DEFAULT_SAAS_URL, resolve_base_url
|
|
17
|
+
from cliptude_mcp.credentials import save_credentials
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class AuthLoginError(Exception):
|
|
21
|
+
pass
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _b64url(raw: bytes) -> str:
|
|
25
|
+
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def pkce_pair() -> tuple[str, str]:
|
|
29
|
+
verifier = _b64url(secrets.token_bytes(32))
|
|
30
|
+
challenge = _b64url(hashlib.sha256(verifier.encode("ascii")).digest())
|
|
31
|
+
return verifier, challenge
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _issuer() -> str:
|
|
35
|
+
return resolve_base_url().rstrip("/") or DEFAULT_SAAS_URL
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def register_public_client(issuer: str, redirect_uri: str, timeout: float = 20.0) -> str:
|
|
39
|
+
resp = httpx.post(
|
|
40
|
+
f"{issuer}/o/register/",
|
|
41
|
+
json={
|
|
42
|
+
"client_name": "Cliptude CLI",
|
|
43
|
+
"redirect_uris": [redirect_uri],
|
|
44
|
+
"token_endpoint_auth_method": "none",
|
|
45
|
+
"grant_types": ["authorization_code", "refresh_token"],
|
|
46
|
+
"response_types": ["code"],
|
|
47
|
+
},
|
|
48
|
+
timeout=timeout,
|
|
49
|
+
)
|
|
50
|
+
if resp.status_code >= 400:
|
|
51
|
+
raise AuthLoginError(f"Could not register CLI OAuth client ({resp.status_code}).")
|
|
52
|
+
data = resp.json()
|
|
53
|
+
client_id = data.get("client_id")
|
|
54
|
+
if not client_id:
|
|
55
|
+
raise AuthLoginError("OAuth registration did not return a client_id.")
|
|
56
|
+
return str(client_id)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def authorize_url(
|
|
60
|
+
issuer: str,
|
|
61
|
+
*,
|
|
62
|
+
client_id: str,
|
|
63
|
+
redirect_uri: str,
|
|
64
|
+
challenge: str,
|
|
65
|
+
state: str,
|
|
66
|
+
) -> str:
|
|
67
|
+
query = urllib.parse.urlencode(
|
|
68
|
+
{
|
|
69
|
+
"response_type": "code",
|
|
70
|
+
"client_id": client_id,
|
|
71
|
+
"redirect_uri": redirect_uri,
|
|
72
|
+
"scope": "jobs",
|
|
73
|
+
"code_challenge": challenge,
|
|
74
|
+
"code_challenge_method": "S256",
|
|
75
|
+
"state": state,
|
|
76
|
+
}
|
|
77
|
+
)
|
|
78
|
+
return f"{issuer}/o/authorize/?{query}"
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def exchange_code(
|
|
82
|
+
issuer: str,
|
|
83
|
+
*,
|
|
84
|
+
client_id: str,
|
|
85
|
+
redirect_uri: str,
|
|
86
|
+
code: str,
|
|
87
|
+
verifier: str,
|
|
88
|
+
timeout: float = 20.0,
|
|
89
|
+
) -> dict[str, Any]:
|
|
90
|
+
resp = httpx.post(
|
|
91
|
+
f"{issuer}/o/token/",
|
|
92
|
+
data={
|
|
93
|
+
"grant_type": "authorization_code",
|
|
94
|
+
"code": code,
|
|
95
|
+
"redirect_uri": redirect_uri,
|
|
96
|
+
"client_id": client_id,
|
|
97
|
+
"code_verifier": verifier,
|
|
98
|
+
},
|
|
99
|
+
timeout=timeout,
|
|
100
|
+
)
|
|
101
|
+
if resp.status_code >= 400:
|
|
102
|
+
raise AuthLoginError(f"Token exchange failed ({resp.status_code}).")
|
|
103
|
+
data = resp.json()
|
|
104
|
+
if not data.get("access_token"):
|
|
105
|
+
raise AuthLoginError("Token exchange did not return an access token.")
|
|
106
|
+
return data
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def refresh_access_token(creds: dict[str, Any], timeout: float = 20.0) -> dict[str, Any] | None:
|
|
110
|
+
refresh = creds.get("refresh_token")
|
|
111
|
+
client_id = creds.get("client_id")
|
|
112
|
+
issuer = (creds.get("issuer") or _issuer()).rstrip("/")
|
|
113
|
+
if not refresh or not client_id:
|
|
114
|
+
return None
|
|
115
|
+
resp = httpx.post(
|
|
116
|
+
f"{issuer}/o/token/",
|
|
117
|
+
data={
|
|
118
|
+
"grant_type": "refresh_token",
|
|
119
|
+
"refresh_token": refresh,
|
|
120
|
+
"client_id": client_id,
|
|
121
|
+
},
|
|
122
|
+
timeout=timeout,
|
|
123
|
+
)
|
|
124
|
+
if resp.status_code >= 400:
|
|
125
|
+
return None
|
|
126
|
+
data = resp.json()
|
|
127
|
+
if not data.get("access_token"):
|
|
128
|
+
return None
|
|
129
|
+
merged = dict(creds)
|
|
130
|
+
merged["access_token"] = data["access_token"]
|
|
131
|
+
if data.get("refresh_token"):
|
|
132
|
+
merged["refresh_token"] = data["refresh_token"]
|
|
133
|
+
save_credentials(merged)
|
|
134
|
+
return merged
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _wait_for_callback(
|
|
138
|
+
host: str,
|
|
139
|
+
) -> tuple[HTTPServer, dict[str, str | None], threading.Event]:
|
|
140
|
+
result: dict[str, str | None] = {"code": None, "state": None, "error": None}
|
|
141
|
+
done = threading.Event()
|
|
142
|
+
|
|
143
|
+
class Handler(BaseHTTPRequestHandler):
|
|
144
|
+
def do_GET(self): # noqa: N802
|
|
145
|
+
parsed = urllib.parse.urlparse(self.path)
|
|
146
|
+
if parsed.path.rstrip("/") != "/callback":
|
|
147
|
+
self.send_response(404)
|
|
148
|
+
self.end_headers()
|
|
149
|
+
return
|
|
150
|
+
qs = urllib.parse.parse_qs(parsed.query)
|
|
151
|
+
result["code"] = (qs.get("code") or [None])[0]
|
|
152
|
+
result["state"] = (qs.get("state") or [None])[0]
|
|
153
|
+
result["error"] = (qs.get("error") or [None])[0]
|
|
154
|
+
body = (
|
|
155
|
+
b"<html><body style='font-family:sans-serif;padding:2rem'>"
|
|
156
|
+
b"<h1>Cliptude CLI</h1><p>Signed in. You can close this tab.</p>"
|
|
157
|
+
b"</body></html>"
|
|
158
|
+
)
|
|
159
|
+
self.send_response(200)
|
|
160
|
+
self.send_header("Content-Type", "text/html; charset=utf-8")
|
|
161
|
+
self.send_header("Content-Length", str(len(body)))
|
|
162
|
+
self.end_headers()
|
|
163
|
+
self.wfile.write(body)
|
|
164
|
+
done.set()
|
|
165
|
+
|
|
166
|
+
def log_message(self, format, *args): # noqa: A003
|
|
167
|
+
return
|
|
168
|
+
|
|
169
|
+
server = HTTPServer((host, 0), Handler)
|
|
170
|
+
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
|
171
|
+
thread.start()
|
|
172
|
+
return server, result, done
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def login(*, open_browser: bool = True) -> dict[str, Any]:
|
|
176
|
+
issuer = _issuer()
|
|
177
|
+
host = "127.0.0.1"
|
|
178
|
+
server, result, done = _wait_for_callback(host)
|
|
179
|
+
try:
|
|
180
|
+
port = server.server_address[1]
|
|
181
|
+
redirect_uri = f"http://{host}:{port}/callback"
|
|
182
|
+
client_id = register_public_client(issuer, redirect_uri)
|
|
183
|
+
verifier, challenge = pkce_pair()
|
|
184
|
+
state = _b64url(secrets.token_bytes(16))
|
|
185
|
+
url = authorize_url(
|
|
186
|
+
issuer,
|
|
187
|
+
client_id=client_id,
|
|
188
|
+
redirect_uri=redirect_uri,
|
|
189
|
+
challenge=challenge,
|
|
190
|
+
state=state,
|
|
191
|
+
)
|
|
192
|
+
if open_browser:
|
|
193
|
+
webbrowser.open(url)
|
|
194
|
+
if not done.wait(300):
|
|
195
|
+
raise AuthLoginError("Timed out waiting for browser sign-in.")
|
|
196
|
+
if result.get("error"):
|
|
197
|
+
raise AuthLoginError(f"Sign-in was denied ({result['error']}).")
|
|
198
|
+
if result.get("state") != state:
|
|
199
|
+
raise AuthLoginError("OAuth state mismatch.")
|
|
200
|
+
if not result.get("code"):
|
|
201
|
+
raise AuthLoginError("No authorization code returned.")
|
|
202
|
+
tokens = exchange_code(
|
|
203
|
+
issuer,
|
|
204
|
+
client_id=client_id,
|
|
205
|
+
redirect_uri=redirect_uri,
|
|
206
|
+
code=str(result["code"]),
|
|
207
|
+
verifier=verifier,
|
|
208
|
+
)
|
|
209
|
+
creds = {
|
|
210
|
+
"issuer": issuer,
|
|
211
|
+
"client_id": client_id,
|
|
212
|
+
"access_token": tokens["access_token"],
|
|
213
|
+
"refresh_token": tokens.get("refresh_token") or "",
|
|
214
|
+
"token_type": tokens.get("token_type") or "Bearer",
|
|
215
|
+
}
|
|
216
|
+
save_credentials(creds)
|
|
217
|
+
return creds
|
|
218
|
+
finally:
|
|
219
|
+
server.shutdown()
|
|
220
|
+
server.server_close()
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"""Tiny CLI wrapping /api/v1: auth | templates | generate | status | jobs | account | cancel."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from cliptude_mcp.client import CliptudeApiError, CliptudeClient
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _print(payload) -> None:
|
|
14
|
+
json.dump(payload, sys.stdout, indent=2)
|
|
15
|
+
sys.stdout.write("\n")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _die(exc: Exception, code: int = 1) -> None:
|
|
19
|
+
if isinstance(exc, CliptudeApiError):
|
|
20
|
+
_print({"error": str(exc), "status": exc.status, "detail": exc.payload})
|
|
21
|
+
raise SystemExit(exc.status or code)
|
|
22
|
+
_print({"error": str(exc)})
|
|
23
|
+
raise SystemExit(code)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _resolve_template_id(client: CliptudeClient, value: str) -> str:
|
|
27
|
+
value = (value or "").strip()
|
|
28
|
+
if not value:
|
|
29
|
+
raise CliptudeApiError("Template name or id is required.")
|
|
30
|
+
listing = client.list_templates(limit=100)
|
|
31
|
+
results = listing.get("results") or []
|
|
32
|
+
for row in results:
|
|
33
|
+
if str(row.get("id")) == value or str(row.get("name", "")).lower() == value.lower():
|
|
34
|
+
return str(row["id"])
|
|
35
|
+
raise CliptudeApiError(f"Template not found: {value}")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _run_auth(auth_cmd: str) -> None:
|
|
39
|
+
from cliptude_mcp.auth_login import AuthLoginError, login
|
|
40
|
+
from cliptude_mcp.credentials import clear_credentials, stored_access_token
|
|
41
|
+
|
|
42
|
+
if auth_cmd == "login":
|
|
43
|
+
try:
|
|
44
|
+
login()
|
|
45
|
+
except AuthLoginError as exc:
|
|
46
|
+
print(str(exc), file=sys.stderr)
|
|
47
|
+
raise SystemExit(1) from exc
|
|
48
|
+
print("Logged in.")
|
|
49
|
+
return
|
|
50
|
+
if auth_cmd == "logout":
|
|
51
|
+
clear_credentials()
|
|
52
|
+
print("Logged out.")
|
|
53
|
+
return
|
|
54
|
+
if not stored_access_token():
|
|
55
|
+
print("Not authenticated. Run: cliptude auth login", file=sys.stderr)
|
|
56
|
+
raise SystemExit(1)
|
|
57
|
+
try:
|
|
58
|
+
account = CliptudeClient().get_account()
|
|
59
|
+
except Exception as exc:
|
|
60
|
+
_die(exc)
|
|
61
|
+
email = account.get("email") if isinstance(account, dict) else None
|
|
62
|
+
print(f"Logged in{f' as {email}' if email else '.'}")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def main(argv: list[str] | None = None) -> None:
|
|
66
|
+
parser = argparse.ArgumentParser(prog="cliptude", description="Cliptude jobs CLI")
|
|
67
|
+
sub = parser.add_subparsers(dest="cmd", required=True)
|
|
68
|
+
|
|
69
|
+
auth = sub.add_parser("auth", help="Sign in with a browser")
|
|
70
|
+
auth_sub = auth.add_subparsers(dest="auth_cmd", required=True)
|
|
71
|
+
auth_sub.add_parser("login", help="Open a browser and save a local session")
|
|
72
|
+
auth_sub.add_parser("logout", help="Delete the local session")
|
|
73
|
+
auth_sub.add_parser("status", help="Show whether this machine is signed in")
|
|
74
|
+
|
|
75
|
+
t = sub.add_parser("templates", help="List saved templates")
|
|
76
|
+
t.add_argument("--limit", type=int, default=20)
|
|
77
|
+
t.add_argument("--offset", type=int, default=0)
|
|
78
|
+
|
|
79
|
+
g = sub.add_parser("generate", help="Start a job")
|
|
80
|
+
g.add_argument("--template", required=True, help="Template name or UUID")
|
|
81
|
+
g.add_argument("--title", required=True)
|
|
82
|
+
g.add_argument("--prompt", default="")
|
|
83
|
+
g.add_argument("--script", default="")
|
|
84
|
+
g.add_argument("--script-file", default="")
|
|
85
|
+
g.add_argument(
|
|
86
|
+
"--faceless-coding",
|
|
87
|
+
default="",
|
|
88
|
+
help="external = you author Faceless storyboard/HTML; omit for Cliptude coding",
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
k = sub.add_parser("kit", help="Download Faceless coding kit zip")
|
|
92
|
+
k.add_argument("job_id")
|
|
93
|
+
k.add_argument("--out", default="kit.zip")
|
|
94
|
+
|
|
95
|
+
sp = sub.add_parser("submit-project", help="Upload Faceless project zip")
|
|
96
|
+
sp.add_argument("job_id")
|
|
97
|
+
sp.add_argument("zip_path")
|
|
98
|
+
|
|
99
|
+
s = sub.add_parser("status", help="Get job status")
|
|
100
|
+
s.add_argument("job_id")
|
|
101
|
+
|
|
102
|
+
j = sub.add_parser("jobs", help="List recent jobs")
|
|
103
|
+
j.add_argument("--status", default="")
|
|
104
|
+
j.add_argument("--limit", type=int, default=20)
|
|
105
|
+
|
|
106
|
+
sub.add_parser("account", help="Plan and credits")
|
|
107
|
+
|
|
108
|
+
c = sub.add_parser("cancel", help="Cancel a job")
|
|
109
|
+
c.add_argument("job_id")
|
|
110
|
+
|
|
111
|
+
args = parser.parse_args(argv)
|
|
112
|
+
if args.cmd == "auth":
|
|
113
|
+
_run_auth(args.auth_cmd)
|
|
114
|
+
return
|
|
115
|
+
client = CliptudeClient()
|
|
116
|
+
try:
|
|
117
|
+
if args.cmd == "templates":
|
|
118
|
+
_print(client.list_templates(limit=args.limit, offset=args.offset))
|
|
119
|
+
elif args.cmd == "generate":
|
|
120
|
+
script = args.script
|
|
121
|
+
if args.script_file:
|
|
122
|
+
script = Path(args.script_file).read_text(encoding="utf-8")
|
|
123
|
+
if not (args.prompt or script):
|
|
124
|
+
raise CliptudeApiError("Provide --prompt or --script / --script-file.")
|
|
125
|
+
template_id = _resolve_template_id(client, args.template)
|
|
126
|
+
_print(client.create_job(
|
|
127
|
+
template_id=template_id,
|
|
128
|
+
title=args.title,
|
|
129
|
+
prompt=args.prompt or None,
|
|
130
|
+
script=script or None,
|
|
131
|
+
faceless_coding=(args.faceless_coding or None),
|
|
132
|
+
))
|
|
133
|
+
elif args.cmd == "kit":
|
|
134
|
+
dest = Path(args.out)
|
|
135
|
+
client.download_coding_kit_file(args.job_id, dest)
|
|
136
|
+
_print({"ok": True, "path": str(dest.resolve())})
|
|
137
|
+
elif args.cmd == "submit-project":
|
|
138
|
+
_print(client.submit_faceless_project(args.job_id, args.zip_path))
|
|
139
|
+
elif args.cmd == "status":
|
|
140
|
+
_print(client.get_job(args.job_id))
|
|
141
|
+
elif args.cmd == "jobs":
|
|
142
|
+
_print(client.list_jobs(status=args.status or None, limit=args.limit))
|
|
143
|
+
elif args.cmd == "account":
|
|
144
|
+
_print(client.get_account())
|
|
145
|
+
elif args.cmd == "cancel":
|
|
146
|
+
_print(client.cancel_job(args.job_id))
|
|
147
|
+
except Exception as exc:
|
|
148
|
+
_die(exc)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
if __name__ == "__main__":
|
|
152
|
+
main()
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
"""HTTP client for Cliptude /api/v1. No Django imports."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
from contextvars import ContextVar
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
|
|
13
|
+
from cliptude_mcp.credentials import stored_access_token
|
|
14
|
+
|
|
15
|
+
DEFAULT_SAAS_URL = "https://cliptude.com"
|
|
16
|
+
_request_token: ContextVar[str | None] = ContextVar("cliptude_request_token", default=None)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def set_request_token(token: str | None):
|
|
20
|
+
return _request_token.set(token)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def reset_request_token(token):
|
|
24
|
+
_request_token.reset(token)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def discover_desktop_base_url() -> str | None:
|
|
28
|
+
appdata = os.environ.get("APPDATA") or os.environ.get("XDG_CONFIG_HOME")
|
|
29
|
+
candidates: list[Path] = []
|
|
30
|
+
if appdata:
|
|
31
|
+
candidates.append(Path(appdata) / "Cliptude" / "desktop-runtime.json")
|
|
32
|
+
home = Path.home()
|
|
33
|
+
candidates.append(home / "Library" / "Application Support" / "Cliptude" / "desktop-runtime.json")
|
|
34
|
+
candidates.append(home / ".cliptude" / "desktop-runtime.json")
|
|
35
|
+
for path in candidates:
|
|
36
|
+
try:
|
|
37
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
38
|
+
except OSError:
|
|
39
|
+
continue
|
|
40
|
+
except json.JSONDecodeError:
|
|
41
|
+
continue
|
|
42
|
+
port = data.get("port") or data.get("django_port")
|
|
43
|
+
if port:
|
|
44
|
+
return f"http://127.0.0.1:{port}"
|
|
45
|
+
return None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def resolve_base_url() -> str:
|
|
49
|
+
explicit = (os.environ.get("CLIPTUDE_BASE_URL") or "").rstrip("/")
|
|
50
|
+
if explicit:
|
|
51
|
+
return explicit
|
|
52
|
+
desktop = discover_desktop_base_url()
|
|
53
|
+
return desktop or DEFAULT_SAAS_URL
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class CliptudeApiError(Exception):
|
|
57
|
+
def __init__(self, message: str, status: int | None = None, payload: Any = None):
|
|
58
|
+
super().__init__(message)
|
|
59
|
+
self.status = status
|
|
60
|
+
self.payload = payload
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _resolve_token(explicit: str | None) -> str:
|
|
64
|
+
return (
|
|
65
|
+
(explicit or "").strip()
|
|
66
|
+
or (_request_token.get() or "").strip()
|
|
67
|
+
or (os.environ.get("CLIPTUDE_API_KEY") or "").strip()
|
|
68
|
+
or stored_access_token()
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class CliptudeClient:
|
|
73
|
+
def __init__(self, base_url: str | None = None, api_key: str | None = None, timeout: float = 30.0):
|
|
74
|
+
self.base_url = (base_url or resolve_base_url()).rstrip("/")
|
|
75
|
+
self.api_key = _resolve_token(api_key)
|
|
76
|
+
self.timeout = timeout
|
|
77
|
+
self._session_file = not bool(
|
|
78
|
+
(api_key or "").strip()
|
|
79
|
+
or (_request_token.get() or "").strip()
|
|
80
|
+
or (os.environ.get("CLIPTUDE_API_KEY") or "").strip()
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
def _headers(self) -> dict[str, str]:
|
|
84
|
+
if not self.api_key:
|
|
85
|
+
raise CliptudeApiError("Not authenticated. Run: cliptude auth login")
|
|
86
|
+
return {
|
|
87
|
+
"Authorization": f"Bearer {self.api_key}",
|
|
88
|
+
"Accept": "application/json",
|
|
89
|
+
"Content-Type": "application/json",
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
def _maybe_refresh(self) -> bool:
|
|
93
|
+
if not self._session_file:
|
|
94
|
+
return False
|
|
95
|
+
from cliptude_mcp.auth_login import refresh_access_token
|
|
96
|
+
from cliptude_mcp.credentials import load_credentials
|
|
97
|
+
|
|
98
|
+
creds = load_credentials()
|
|
99
|
+
if not creds:
|
|
100
|
+
return False
|
|
101
|
+
updated = refresh_access_token(creds)
|
|
102
|
+
if not updated:
|
|
103
|
+
return False
|
|
104
|
+
self.api_key = str(updated.get("access_token") or "")
|
|
105
|
+
return bool(self.api_key)
|
|
106
|
+
|
|
107
|
+
def request(self, method: str, path: str, *, params=None, json_body=None, _retried: bool = False) -> Any:
|
|
108
|
+
url = f"{self.base_url}{path}"
|
|
109
|
+
try:
|
|
110
|
+
resp = httpx.request(
|
|
111
|
+
method,
|
|
112
|
+
url,
|
|
113
|
+
headers=self._headers(),
|
|
114
|
+
params=params,
|
|
115
|
+
json=json_body,
|
|
116
|
+
timeout=self.timeout,
|
|
117
|
+
)
|
|
118
|
+
except httpx.HTTPError as exc:
|
|
119
|
+
raise CliptudeApiError(str(exc)) from exc
|
|
120
|
+
if resp.status_code == 401 and not _retried and self._maybe_refresh():
|
|
121
|
+
return self.request(method, path, params=params, json_body=json_body, _retried=True)
|
|
122
|
+
try:
|
|
123
|
+
payload = resp.json()
|
|
124
|
+
except ValueError:
|
|
125
|
+
payload = {"error": resp.text}
|
|
126
|
+
if resp.status_code >= 400:
|
|
127
|
+
message = payload.get("error") if isinstance(payload, dict) else str(payload)
|
|
128
|
+
if resp.status_code == 401:
|
|
129
|
+
message = message or "Not authenticated. Run: cliptude auth login"
|
|
130
|
+
raise CliptudeApiError(message or f"HTTP {resp.status_code}", status=resp.status_code, payload=payload)
|
|
131
|
+
return payload
|
|
132
|
+
|
|
133
|
+
def list_templates(self, *, limit: int = 20, offset: int = 0) -> Any:
|
|
134
|
+
return self.request("GET", "/api/v1/templates", params={"limit": limit, "offset": offset})
|
|
135
|
+
|
|
136
|
+
def get_template(self, template_id: str) -> Any:
|
|
137
|
+
return self.request("GET", f"/api/v1/templates/{template_id}")
|
|
138
|
+
|
|
139
|
+
def create_job(
|
|
140
|
+
self,
|
|
141
|
+
*,
|
|
142
|
+
template_id: str,
|
|
143
|
+
title: str,
|
|
144
|
+
prompt: str | None = None,
|
|
145
|
+
script: str | None = None,
|
|
146
|
+
faceless_coding: str | None = None,
|
|
147
|
+
) -> Any:
|
|
148
|
+
body: dict[str, Any] = {"template_id": template_id, "title": title}
|
|
149
|
+
if prompt:
|
|
150
|
+
body["prompt"] = prompt
|
|
151
|
+
if script:
|
|
152
|
+
body["script"] = script
|
|
153
|
+
if faceless_coding:
|
|
154
|
+
body["faceless_coding"] = faceless_coding
|
|
155
|
+
return self.request("POST", "/api/v1/jobs", json_body=body)
|
|
156
|
+
|
|
157
|
+
def get_job(self, job_id: str) -> Any:
|
|
158
|
+
return self.request("GET", f"/api/v1/jobs/{job_id}")
|
|
159
|
+
|
|
160
|
+
def download_coding_kit(self, job_id: str) -> Any:
|
|
161
|
+
"""Return coding_kit url/path from get_job. Never downloads zip bytes."""
|
|
162
|
+
job = self.get_job(job_id)
|
|
163
|
+
kit = job.get("coding_kit") if isinstance(job, dict) else None
|
|
164
|
+
if not kit:
|
|
165
|
+
raise CliptudeApiError("Coding kit is not ready yet. Poll until status is awaiting_project.")
|
|
166
|
+
return kit
|
|
167
|
+
|
|
168
|
+
def download_coding_kit_file(self, job_id: str, dest: Path) -> Path:
|
|
169
|
+
url = f"{self.base_url}/api/v1/jobs/{job_id}/coding-kit"
|
|
170
|
+
try:
|
|
171
|
+
with httpx.stream(
|
|
172
|
+
"GET",
|
|
173
|
+
url,
|
|
174
|
+
headers={
|
|
175
|
+
"Authorization": f"Bearer {self.api_key}",
|
|
176
|
+
"Accept": "application/zip, application/json",
|
|
177
|
+
},
|
|
178
|
+
timeout=self.timeout,
|
|
179
|
+
follow_redirects=True,
|
|
180
|
+
) as resp:
|
|
181
|
+
if resp.status_code >= 400:
|
|
182
|
+
try:
|
|
183
|
+
payload = resp.read()
|
|
184
|
+
data = json.loads(payload)
|
|
185
|
+
except Exception:
|
|
186
|
+
data = {"error": resp.reason_phrase}
|
|
187
|
+
message = data.get("error") if isinstance(data, dict) else str(data)
|
|
188
|
+
raise CliptudeApiError(message or f"HTTP {resp.status_code}", status=resp.status_code, payload=data)
|
|
189
|
+
dest = Path(dest)
|
|
190
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
191
|
+
with dest.open("wb") as fh:
|
|
192
|
+
for chunk in resp.iter_bytes():
|
|
193
|
+
fh.write(chunk)
|
|
194
|
+
except CliptudeApiError:
|
|
195
|
+
raise
|
|
196
|
+
except httpx.HTTPError as exc:
|
|
197
|
+
raise CliptudeApiError(str(exc)) from exc
|
|
198
|
+
return dest
|
|
199
|
+
|
|
200
|
+
def submit_faceless_project(self, job_id: str, zip_path: str | Path) -> Any:
|
|
201
|
+
path = Path(zip_path)
|
|
202
|
+
if not path.is_file():
|
|
203
|
+
raise CliptudeApiError(f"Project zip not found: {path}")
|
|
204
|
+
url = f"{self.base_url}/api/v1/jobs/{job_id}/project"
|
|
205
|
+
headers = {
|
|
206
|
+
"Authorization": f"Bearer {self.api_key}",
|
|
207
|
+
"Accept": "application/json",
|
|
208
|
+
}
|
|
209
|
+
try:
|
|
210
|
+
with path.open("rb") as fh:
|
|
211
|
+
resp = httpx.post(
|
|
212
|
+
url,
|
|
213
|
+
headers=headers,
|
|
214
|
+
files={"zip": (path.name, fh, "application/zip")},
|
|
215
|
+
timeout=max(self.timeout, 120.0),
|
|
216
|
+
)
|
|
217
|
+
except httpx.HTTPError as exc:
|
|
218
|
+
raise CliptudeApiError(str(exc)) from exc
|
|
219
|
+
try:
|
|
220
|
+
payload = resp.json()
|
|
221
|
+
except ValueError:
|
|
222
|
+
payload = {"error": resp.text}
|
|
223
|
+
if resp.status_code >= 400:
|
|
224
|
+
message = payload.get("error") if isinstance(payload, dict) else str(payload)
|
|
225
|
+
raise CliptudeApiError(message or f"HTTP {resp.status_code}", status=resp.status_code, payload=payload)
|
|
226
|
+
return payload
|
|
227
|
+
|
|
228
|
+
def list_jobs(self, *, status: str | None = None, limit: int = 20, offset: int = 0) -> Any:
|
|
229
|
+
params: dict[str, Any] = {"limit": limit, "offset": offset}
|
|
230
|
+
if status:
|
|
231
|
+
params["status"] = status
|
|
232
|
+
return self.request("GET", "/api/v1/jobs", params=params)
|
|
233
|
+
|
|
234
|
+
def cancel_job(self, job_id: str) -> Any:
|
|
235
|
+
return self.request("POST", f"/api/v1/jobs/{job_id}/cancel")
|
|
236
|
+
|
|
237
|
+
def get_account(self) -> Any:
|
|
238
|
+
return self.request("GET", "/api/v1/account")
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Local CLI session: ~/.cliptude/credentials.json."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def credentials_path() -> Path:
|
|
12
|
+
override = os.environ.get("CLIPTUDE_CREDENTIALS")
|
|
13
|
+
if override:
|
|
14
|
+
return Path(override)
|
|
15
|
+
return Path.home() / ".cliptude" / "credentials.json"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def load_credentials() -> dict[str, Any] | None:
|
|
19
|
+
path = credentials_path()
|
|
20
|
+
try:
|
|
21
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
22
|
+
except (OSError, json.JSONDecodeError):
|
|
23
|
+
return None
|
|
24
|
+
if not isinstance(data, dict) or not data.get("access_token"):
|
|
25
|
+
return None
|
|
26
|
+
return data
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def save_credentials(data: dict[str, Any]) -> Path:
|
|
30
|
+
path = credentials_path()
|
|
31
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
32
|
+
path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
|
|
33
|
+
try:
|
|
34
|
+
os.chmod(path, 0o600)
|
|
35
|
+
except OSError:
|
|
36
|
+
pass
|
|
37
|
+
return path
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def clear_credentials() -> None:
|
|
41
|
+
path = credentials_path()
|
|
42
|
+
try:
|
|
43
|
+
path.unlink()
|
|
44
|
+
except FileNotFoundError:
|
|
45
|
+
return
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def stored_access_token() -> str:
|
|
49
|
+
data = load_credentials()
|
|
50
|
+
if not data:
|
|
51
|
+
return ""
|
|
52
|
+
return str(data.get("access_token") or "")
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
"""stdio / Streamable HTTP MCP server. Never writes to stdout except JSON-RPC."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
from typing import Annotated, Any
|
|
9
|
+
|
|
10
|
+
from pydantic import Field
|
|
11
|
+
|
|
12
|
+
from cliptude_mcp.client import CliptudeApiError, CliptudeClient, set_request_token
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger("cliptude_mcp")
|
|
15
|
+
logging.basicConfig(stream=sys.stderr, level=logging.INFO)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _client() -> CliptudeClient:
|
|
19
|
+
token = None
|
|
20
|
+
try:
|
|
21
|
+
from mcp.server.auth.middleware.auth_context import get_access_token
|
|
22
|
+
|
|
23
|
+
access = get_access_token()
|
|
24
|
+
if access is not None and getattr(access, "token", None):
|
|
25
|
+
token = access.token
|
|
26
|
+
set_request_token(token)
|
|
27
|
+
except Exception:
|
|
28
|
+
pass
|
|
29
|
+
return CliptudeClient(api_key=token)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _err(exc: Exception) -> dict[str, Any]:
|
|
33
|
+
if isinstance(exc, CliptudeApiError):
|
|
34
|
+
return {"error": str(exc), "status": exc.status, "detail": exc.payload}
|
|
35
|
+
return {"error": str(exc)}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def build_server(*, with_http_auth: bool = False):
|
|
39
|
+
from mcp.server import MCPServer
|
|
40
|
+
from mcp.types import ToolAnnotations
|
|
41
|
+
|
|
42
|
+
kwargs: dict[str, Any] = {
|
|
43
|
+
"instructions": (
|
|
44
|
+
"Generate Cliptude videos from a saved template. "
|
|
45
|
+
"Call list_templates, then create_job with template_id + title + prompt or script. "
|
|
46
|
+
"create_job returns immediately; poll get_job until completed or failed. "
|
|
47
|
+
"If the user pastes a full narration, pass it as script, not prompt."
|
|
48
|
+
),
|
|
49
|
+
}
|
|
50
|
+
if with_http_auth:
|
|
51
|
+
from cliptude_mcp.auth import CliptudeTokenVerifier, auth_settings
|
|
52
|
+
|
|
53
|
+
kwargs["token_verifier"] = CliptudeTokenVerifier()
|
|
54
|
+
kwargs["auth"] = auth_settings()
|
|
55
|
+
|
|
56
|
+
mcp = MCPServer("Cliptude", **kwargs)
|
|
57
|
+
|
|
58
|
+
@mcp.tool(
|
|
59
|
+
title="List templates",
|
|
60
|
+
annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False),
|
|
61
|
+
)
|
|
62
|
+
def list_templates(
|
|
63
|
+
limit: Annotated[int, Field(ge=1, le=100, description="Page size")] = 20,
|
|
64
|
+
offset: Annotated[int, Field(ge=0, description="Offset")] = 0,
|
|
65
|
+
) -> dict[str, Any]:
|
|
66
|
+
"""List saved video templates (id, name, format). Empty list means the user has not saved a template in Cliptude yet."""
|
|
67
|
+
try:
|
|
68
|
+
return _client().list_templates(limit=limit, offset=offset)
|
|
69
|
+
except Exception as exc:
|
|
70
|
+
return _err(exc)
|
|
71
|
+
|
|
72
|
+
@mcp.tool(
|
|
73
|
+
title="Get template",
|
|
74
|
+
annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False),
|
|
75
|
+
)
|
|
76
|
+
def get_template(
|
|
77
|
+
template_id: Annotated[str, Field(min_length=8, description="Template UUID")],
|
|
78
|
+
) -> dict[str, Any]:
|
|
79
|
+
"""Get one saved template summary (not internal JSON)."""
|
|
80
|
+
try:
|
|
81
|
+
return _client().get_template(template_id)
|
|
82
|
+
except Exception as exc:
|
|
83
|
+
return _err(exc)
|
|
84
|
+
|
|
85
|
+
@mcp.tool(title="Create video job")
|
|
86
|
+
def create_job(
|
|
87
|
+
template_id: Annotated[str, Field(min_length=8, description="Saved template UUID")],
|
|
88
|
+
title: Annotated[str, Field(min_length=1, max_length=255, description="Video title")],
|
|
89
|
+
prompt: Annotated[str | None, Field(description="Topic/brief. Cliptude writes the narration.")] = None,
|
|
90
|
+
script: Annotated[str | None, Field(description="Custom spoken narration. Cliptude does not rewrite it.")] = None,
|
|
91
|
+
faceless_coding: Annotated[
|
|
92
|
+
str | None,
|
|
93
|
+
Field(description='Use "external" for Faceless Explainer BYO HTML. Omit for Cliptude coding.'),
|
|
94
|
+
] = None,
|
|
95
|
+
) -> dict[str, Any]:
|
|
96
|
+
"""Start generation and return a job id immediately. Do not wait for the MP4. Poll get_job. Provide prompt and/or script."""
|
|
97
|
+
try:
|
|
98
|
+
return _client().create_job(
|
|
99
|
+
template_id=template_id,
|
|
100
|
+
title=title,
|
|
101
|
+
prompt=prompt,
|
|
102
|
+
script=script,
|
|
103
|
+
faceless_coding=faceless_coding,
|
|
104
|
+
)
|
|
105
|
+
except Exception as exc:
|
|
106
|
+
return _err(exc)
|
|
107
|
+
|
|
108
|
+
@mcp.tool(
|
|
109
|
+
title="Get job",
|
|
110
|
+
annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False),
|
|
111
|
+
)
|
|
112
|
+
def get_job(
|
|
113
|
+
job_id: Annotated[str, Field(min_length=8, description="Job / video UUID")],
|
|
114
|
+
) -> dict[str, Any]:
|
|
115
|
+
"""Job status, progress, error, and output url (SaaS) or path (Desktop)."""
|
|
116
|
+
try:
|
|
117
|
+
return _client().get_job(job_id)
|
|
118
|
+
except Exception as exc:
|
|
119
|
+
return _err(exc)
|
|
120
|
+
|
|
121
|
+
@mcp.tool(
|
|
122
|
+
title="Download coding kit",
|
|
123
|
+
annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False),
|
|
124
|
+
)
|
|
125
|
+
def download_coding_kit(
|
|
126
|
+
job_id: Annotated[str, Field(min_length=8, description="Job UUID")],
|
|
127
|
+
) -> dict[str, Any]:
|
|
128
|
+
"""Return coding_kit url or path after awaiting_project. Never returns zip bytes. Do not wait for the MP4."""
|
|
129
|
+
try:
|
|
130
|
+
return _client().download_coding_kit(job_id)
|
|
131
|
+
except Exception as exc:
|
|
132
|
+
return _err(exc)
|
|
133
|
+
|
|
134
|
+
@mcp.tool(title="Submit Faceless project")
|
|
135
|
+
def submit_faceless_project(
|
|
136
|
+
job_id: Annotated[str, Field(min_length=8, description="Job UUID")],
|
|
137
|
+
zip_path: Annotated[str, Field(min_length=1, description="Local path to the project zip")],
|
|
138
|
+
) -> dict[str, Any]:
|
|
139
|
+
"""Upload a local Faceless project zip (storyboard.json + frames). Returns 202. Poll get_job. Do not wait for the MP4."""
|
|
140
|
+
try:
|
|
141
|
+
return _client().submit_faceless_project(job_id, zip_path)
|
|
142
|
+
except Exception as exc:
|
|
143
|
+
return _err(exc)
|
|
144
|
+
|
|
145
|
+
@mcp.tool(
|
|
146
|
+
title="List jobs",
|
|
147
|
+
annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False),
|
|
148
|
+
)
|
|
149
|
+
def list_jobs(
|
|
150
|
+
status: Annotated[str | None, Field(description="Optional status filter")] = None,
|
|
151
|
+
limit: Annotated[int, Field(ge=1, le=100)] = 20,
|
|
152
|
+
offset: Annotated[int, Field(ge=0)] = 0,
|
|
153
|
+
) -> dict[str, Any]:
|
|
154
|
+
"""Recent jobs for this account."""
|
|
155
|
+
try:
|
|
156
|
+
return _client().list_jobs(status=status, limit=limit, offset=offset)
|
|
157
|
+
except Exception as exc:
|
|
158
|
+
return _err(exc)
|
|
159
|
+
|
|
160
|
+
@mcp.tool(
|
|
161
|
+
title="Cancel job",
|
|
162
|
+
annotations=ToolAnnotations(destructive_hint=True, open_world_hint=False),
|
|
163
|
+
)
|
|
164
|
+
def cancel_job(
|
|
165
|
+
job_id: Annotated[str, Field(min_length=8, description="Job UUID")],
|
|
166
|
+
) -> dict[str, Any]:
|
|
167
|
+
"""Cancel a queued or running job."""
|
|
168
|
+
try:
|
|
169
|
+
return _client().cancel_job(job_id)
|
|
170
|
+
except Exception as exc:
|
|
171
|
+
return _err(exc)
|
|
172
|
+
|
|
173
|
+
@mcp.tool(
|
|
174
|
+
title="Get account",
|
|
175
|
+
annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False),
|
|
176
|
+
)
|
|
177
|
+
def get_account() -> dict[str, Any]:
|
|
178
|
+
"""Plan, credits remaining, and concurrency in use."""
|
|
179
|
+
try:
|
|
180
|
+
return _client().get_account()
|
|
181
|
+
except Exception as exc:
|
|
182
|
+
return _err(exc)
|
|
183
|
+
|
|
184
|
+
@mcp.resource("cliptude://templates")
|
|
185
|
+
def templates_resource() -> str:
|
|
186
|
+
"""Saved templates."""
|
|
187
|
+
try:
|
|
188
|
+
return str(_client().list_templates(limit=50))
|
|
189
|
+
except Exception as exc:
|
|
190
|
+
return str(_err(exc))
|
|
191
|
+
|
|
192
|
+
@mcp.resource("cliptude://jobs/{job_id}")
|
|
193
|
+
def job_resource(job_id: str) -> str:
|
|
194
|
+
"""One job snapshot."""
|
|
195
|
+
try:
|
|
196
|
+
return str(_client().get_job(job_id))
|
|
197
|
+
except Exception as exc:
|
|
198
|
+
return str(_err(exc))
|
|
199
|
+
|
|
200
|
+
@mcp.prompt()
|
|
201
|
+
def generate_video() -> str:
|
|
202
|
+
"""Use a saved Cliptude template to generate a video from a topic or a custom script."""
|
|
203
|
+
return (
|
|
204
|
+
"List my Cliptude templates, pick the one I name, then create_job "
|
|
205
|
+
"with title plus prompt (topic) or script (full narration). Poll get_job."
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
return mcp
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def main() -> None:
|
|
212
|
+
transport = (os.environ.get("CLIPTUDE_MCP_TRANSPORT") or "stdio").strip().lower()
|
|
213
|
+
http_mode = transport in {"http", "streamable-http", "streamable_http"}
|
|
214
|
+
mcp = build_server(with_http_auth=http_mode)
|
|
215
|
+
if http_mode:
|
|
216
|
+
host = os.environ.get("CLIPTUDE_MCP_HOST", "0.0.0.0")
|
|
217
|
+
port = int(os.environ.get("CLIPTUDE_MCP_PORT") or "8787")
|
|
218
|
+
logger.info("Starting Streamable HTTP MCP on %s:%s", host, port)
|
|
219
|
+
mcp.run(transport="streamable-http", host=host, port=port)
|
|
220
|
+
return
|
|
221
|
+
mcp.run()
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
if __name__ == "__main__":
|
|
225
|
+
main()
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
|
|
4
|
+
const { spawnSync } = require("child_process");
|
|
5
|
+
const fs = require("fs");
|
|
6
|
+
const path = require("path");
|
|
7
|
+
|
|
8
|
+
const pkgRoot = path.resolve(__dirname, "..", "..");
|
|
9
|
+
const args = process.argv.slice(2);
|
|
10
|
+
|
|
11
|
+
function pythonCandidates() {
|
|
12
|
+
if (process.platform === "win32") {
|
|
13
|
+
return ["py", "python", "python3"];
|
|
14
|
+
}
|
|
15
|
+
return ["python3", "python"];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function findPython() {
|
|
19
|
+
for (const cmd of pythonCandidates()) {
|
|
20
|
+
const probe = spawnSync(
|
|
21
|
+
cmd,
|
|
22
|
+
["-c", "import sys; sys.exit(0 if sys.version_info >= (3, 10) else 1)"],
|
|
23
|
+
{ encoding: "utf8" },
|
|
24
|
+
);
|
|
25
|
+
if (probe.status === 0) {
|
|
26
|
+
return cmd;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function ensurePackage(py) {
|
|
33
|
+
const check = spawnSync(py, ["-c", "import cliptude_mcp.cli"], {
|
|
34
|
+
encoding: "utf8",
|
|
35
|
+
});
|
|
36
|
+
if (check.status === 0) {
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
const pyproject = path.join(pkgRoot, "pyproject.toml");
|
|
40
|
+
if (!fs.existsSync(pyproject)) {
|
|
41
|
+
console.error("Cliptude CLI package is missing pyproject.toml.");
|
|
42
|
+
process.exit(1);
|
|
43
|
+
}
|
|
44
|
+
const install = spawnSync(
|
|
45
|
+
py,
|
|
46
|
+
["-m", "pip", "install", "--quiet", pkgRoot],
|
|
47
|
+
{ stdio: "inherit" },
|
|
48
|
+
);
|
|
49
|
+
if (install.status !== 0) {
|
|
50
|
+
console.error("Could not install the Cliptude Python CLI. Install Python 3.10+ and pip.");
|
|
51
|
+
process.exit(install.status ?? 1);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const py = findPython();
|
|
56
|
+
if (!py) {
|
|
57
|
+
console.error("Python 3.10+ is required. Install it, then re-run: npm i -g @cliptude/cli");
|
|
58
|
+
process.exit(1);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
ensurePackage(py);
|
|
62
|
+
const result = spawnSync(py, ["-m", "cliptude_mcp.cli", ...args], {
|
|
63
|
+
stdio: "inherit",
|
|
64
|
+
});
|
|
65
|
+
process.exit(result.status ?? 1);
|
package/package.json
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@cliptude/cli",
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Cliptude CLI — generate videos from saved templates.",
|
|
5
|
+
"homepage": "https://github.com/cliptude/cliptude#readme",
|
|
6
|
+
"bin": {
|
|
7
|
+
"cliptude": "./npm/bin/cliptude.js"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"cliptude_mcp",
|
|
11
|
+
"pyproject.toml",
|
|
12
|
+
"README.md",
|
|
13
|
+
"npm"
|
|
14
|
+
],
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": ">=18"
|
|
17
|
+
},
|
|
18
|
+
"license": "MIT",
|
|
19
|
+
"publishConfig": {
|
|
20
|
+
"access": "public"
|
|
21
|
+
},
|
|
22
|
+
"repository": {
|
|
23
|
+
"type": "git",
|
|
24
|
+
"url": "git+https://github.com/cliptude/cliptude.git",
|
|
25
|
+
"directory": "mcp_server"
|
|
26
|
+
}
|
|
27
|
+
}
|
package/pyproject.toml
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "cliptude-mcp"
|
|
7
|
+
version = "0.1.1"
|
|
8
|
+
description = "Cliptude jobs CLI and MCP server (thin client of /api/v1)."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
authors = [{ name = "Cliptude" }]
|
|
13
|
+
dependencies = [
|
|
14
|
+
"httpx>=0.28.1",
|
|
15
|
+
"mcp>=2.0.0",
|
|
16
|
+
"pydantic>=2.0",
|
|
17
|
+
]
|
|
18
|
+
[project.scripts]
|
|
19
|
+
cliptude = "cliptude_mcp.cli:main"
|
|
20
|
+
cliptude-mcp = "cliptude_mcp.server:main"
|
|
21
|
+
|
|
22
|
+
[tool.hatch.build.targets.wheel]
|
|
23
|
+
packages = ["cliptude_mcp"]
|