@simpligen/mcp 0.7.0 → 0.8.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 CHANGED
@@ -1,47 +1,47 @@
1
- # @simpligen/mcp
2
-
3
- MCP server that lets an AI agent drive SimpliGen (local + cloud AI image/video generation). Requires the SimpliGen desktop app running and a pairing token (Settings -> Connect an agent).
4
-
5
- ## Configure (Claude Code / Claude Desktop)
6
-
7
- The easiest path is in the SimpliGen app: **Settings -> Connect an agent**, pick your client, and click Install (or copy the guided command). The manual config below is the fallback.
8
-
9
- ```json
10
- {
11
- "mcpServers": {
12
- "simpligen": {
13
- "command": "npx",
14
- "args": ["-y", "@simpligen/mcp"],
15
- "env": { "SIMPLIGEN_TOKEN": "sg-agent-..." }
16
- }
17
- }
18
- }
19
- ```
20
-
21
- ## Tools
22
-
23
- `list_capabilities`, `get_status`, `list_projects`, `create_project`, `upload_file`, `generate`, `get_job`, `wait_for_result`, `list_jobs`, `cancel_job`, `prepare_preset`, `get_result_image`, `wait_for_approval`, `get_app_context`, `fill_generate_form`, `open_screen`, `accept_character_base`.
24
-
25
- **Approval flow (SimpliGen's in-app Assistant).** A token the app issues for its own Assistant panel is flagged `approvalRequired`. With it, any call that queues a generation, renders or exports a film, runs a recipe, or deletes a character or product does not run. It returns `awaiting_approval` with a `proposalId`, and the user sees an approval card in the app. Call `wait_for_approval(proposalId)` (it long-polls in short rounds, like `wait_for_result`). It returns the real result once the user clicks Approve, or `declined` with the user's optional reason so you can adjust and propose again. For `regenerate_character_base`, the approved result carries a base job id: wait on it with `wait_for_result`, then call `accept_character_base`. Normal pairing tokens (Claude Desktop and other clients) never see this flow.
26
-
27
- **Screen tools.** `get_app_context` returns what the user is looking at. `fill_generate_form` fills the visible Generate form and never presses Generate. `open_screen` navigates the app. They work for outside MCP clients too.
28
-
29
- **Video Studio** (connector 0.5.0 or newer): `list_films`, `create_film`, `get_film`, `update_film_settings`, `add_track`, `move_track`, `detect_tempo`, `add_clip`, `update_clip`, `move_clip`, `trim_clip`, `remove_clip`, `apply_film_plan`, `set_fades`, `add_marker`, `set_export_range`, `render_clips`, `wait_for_renders`, `list_takes`, `use_take`, `export_film`, `list_locations`, `create_location`. An agent can build a whole music video: a song, its tempo, clips on the bars, shots, renders and the export. With the film open in the Video Studio every change shows live and undoes with Ctrl+Z. These tools are listed only when your SimpliGen has the Video Studio (connector 0.5.1 or newer, SimpliGen 1.75 or newer). If the agent starts before SimpliGen is running, they appear within a minute of SimpliGen starting; an agent app that does not refresh its tool list shows them after a restart.
30
-
31
- `get_result_image` returns a completed job's result image inline (a viewable image block) so the agent can display it in chat. Claude clients cap a tool result at ~1MB and only render base64 image blocks, so large renders are re-encoded to a **full-resolution WebP** preview (same dimensions; quality steps down, and only very large images are resized) that fits the cap. The uncompressed original file path is always included in the caption, so the agent keeps the full-quality artifact. Video results return the file path instead.
32
-
33
- ## Env
34
-
35
- - `SIMPLIGEN_TOKEN` (required) -- pairing token from the app.
36
- - `SIMPLIGEN_API_PORT` (optional) -- override the control-API port (else read from the app's discovery file).
37
- - `SIMPLIGEN_USERDATA_DIR` / `SIMPLIGEN_APP_NAME` (optional) -- locate the app's data dir (CN variant / custom).
38
-
39
- ## Manual smoke (for maintainers)
40
-
41
- With the app running and a token issued:
42
-
43
- ```bash
44
- SIMPLIGEN_TOKEN=<token> npx @modelcontextprotocol/inspector node src/bin.js
45
- ```
46
-
47
- Verify: tool list appears; call `get_status`; call `list_capabilities`; call `upload_file` with a PNG path and confirm a handle is returned; call `generate` with a local preset and confirm a `jobId`; call `wait_for_result` and confirm a `resultPath`; call `get_result_image` and confirm the image renders inline.
1
+ # @simpligen/mcp
2
+
3
+ MCP server that lets an AI agent drive SimpliGen (local + cloud AI image/video generation). Requires the SimpliGen desktop app running and a pairing token (Settings -> Connect an agent).
4
+
5
+ ## Configure (Claude Code / Claude Desktop)
6
+
7
+ The easiest path is in the SimpliGen app: **Settings -> Connect an agent**, pick your client, and click Install (or copy the guided command). The manual config below is the fallback.
8
+
9
+ ```json
10
+ {
11
+ "mcpServers": {
12
+ "simpligen": {
13
+ "command": "npx",
14
+ "args": ["-y", "@simpligen/mcp"],
15
+ "env": { "SIMPLIGEN_TOKEN": "sg-agent-..." }
16
+ }
17
+ }
18
+ }
19
+ ```
20
+
21
+ ## Tools
22
+
23
+ `list_capabilities`, `get_status`, `list_projects`, `create_project`, `upload_file`, `generate`, `get_job`, `wait_for_result`, `list_jobs`, `cancel_job`, `prepare_preset`, `get_result_image`, `wait_for_approval`, `get_app_context`, `fill_generate_form`, `open_screen`, `accept_character_base`.
24
+
25
+ **Approval flow (SimpliGen's in-app Assistant).** A token the app issues for its own Assistant panel is flagged `approvalRequired`. With it, any call that queues a generation, renders or exports a film, runs a recipe, or deletes a character or product does not run. It returns `awaiting_approval` with a `proposalId`, and the user sees an approval card in the app. Call `wait_for_approval(proposalId)` (it long-polls in short rounds, like `wait_for_result`). It returns the real result once the user clicks Approve, or `declined` with the user's optional reason so you can adjust and propose again. For `regenerate_character_base`, the approved result carries a base job id: wait on it with `wait_for_result`, then call `accept_character_base`. Normal pairing tokens (Claude Desktop and other clients) never see this flow.
26
+
27
+ **Screen tools.** `get_app_context` returns what the user is looking at. `fill_generate_form` fills the visible Generate form and never presses Generate. `open_screen` navigates the app. They work for outside MCP clients too.
28
+
29
+ **Video Studio** (connector 0.5.0 or newer): `list_films`, `create_film`, `get_film`, `update_film_settings`, `add_track`, `move_track`, `detect_tempo`, `add_clip`, `import_clip` (0.8.1), `update_clip`, `move_clip`, `trim_clip`, `remove_clip`, `apply_film_plan`, `set_fades`, `add_marker`, `set_export_range`, `render_clips`, `wait_for_renders`, `list_takes`, `use_take`, `export_film`, `list_locations`, `create_location`. An agent can build a whole music video: a song, its tempo, clips on the bars, shots, renders and the export. With the film open in the Video Studio every change shows live and undoes with Ctrl+Z. They need the Video Studio in SimpliGen (SimpliGen 1.75 or newer). Since connector 0.8.0 they are always listed; without the studio each one answers `studio_not_installed`.
30
+
31
+ `get_result_image` returns a completed job's result image inline (a viewable image block) so the agent can display it in chat. Claude clients cap a tool result at ~1MB and only render base64 image blocks, so large renders are re-encoded to a **full-resolution WebP** preview (same dimensions; quality steps down, and only very large images are resized) that fits the cap. The uncompressed original file path is always included in the caption, so the agent keeps the full-quality artifact. Video results return the file path instead.
32
+
33
+ ## Env
34
+
35
+ - `SIMPLIGEN_TOKEN` (required) -- pairing token from the app.
36
+ - `SIMPLIGEN_API_PORT` (optional) -- override the control-API port (else read from the app's discovery file).
37
+ - `SIMPLIGEN_USERDATA_DIR` / `SIMPLIGEN_APP_NAME` (optional) -- locate the app's data dir (CN variant / custom).
38
+
39
+ ## Manual smoke (for maintainers)
40
+
41
+ With the app running and a token issued:
42
+
43
+ ```bash
44
+ SIMPLIGEN_TOKEN=<token> npx @modelcontextprotocol/inspector node src/bin.js
45
+ ```
46
+
47
+ Verify: tool list appears; call `get_status`; call `list_capabilities`; call `upload_file` with a PNG path and confirm a handle is returned; call `generate` with a local preset and confirm a `jobId`; call `wait_for_result` and confirm a `resultPath`; call `get_result_image` and confirm the image renders inline.
package/package.json CHANGED
@@ -1,37 +1,37 @@
1
- {
2
- "name": "@simpligen/mcp",
3
- "version": "0.7.0",
4
- "description": "MCP server for SimpliGen -- drive local/cloud AI image & video generation from an agent.",
5
- "type": "module",
6
- "license": "MIT",
7
- "homepage": "https://simpligen.io",
8
- "repository": {
9
- "type": "git",
10
- "url": "git+https://github.com/RaynoldVanHeyningen/SimpliGen.git",
11
- "directory": "packages/mcp-server"
12
- },
13
- "bin": {
14
- "simpligen-mcp": "src/bin.js"
15
- },
16
- "main": "src/index.js",
17
- "files": [
18
- "src",
19
- "README.md",
20
- "LICENSE"
21
- ],
22
- "engines": {
23
- "node": ">=18"
24
- },
25
- "publishConfig": {
26
- "access": "public"
27
- },
28
- "scripts": {
29
- "test": "node --test src/*.test.js",
30
- "prepublishOnly": "node --test src/*.test.js"
31
- },
32
- "dependencies": {
33
- "@modelcontextprotocol/sdk": "^1",
34
- "sharp": ">=0.34.5 <0.36",
35
- "zod": "^3"
36
- }
37
- }
1
+ {
2
+ "name": "@simpligen/mcp",
3
+ "version": "0.8.1",
4
+ "description": "MCP server for SimpliGen -- drive local/cloud AI image & video generation from an agent.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "homepage": "https://simpligen.io",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/RaynoldVanHeyningen/SimpliGen.git",
11
+ "directory": "packages/mcp-server"
12
+ },
13
+ "bin": {
14
+ "simpligen-mcp": "src/bin.js"
15
+ },
16
+ "main": "src/index.js",
17
+ "files": [
18
+ "src",
19
+ "README.md",
20
+ "LICENSE"
21
+ ],
22
+ "engines": {
23
+ "node": ">=18"
24
+ },
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "scripts": {
29
+ "test": "node --test src/*.test.js",
30
+ "prepublishOnly": "node --test src/*.test.js"
31
+ },
32
+ "dependencies": {
33
+ "@modelcontextprotocol/sdk": "^1",
34
+ "sharp": ">=0.34.5 <0.36",
35
+ "zod": "^3"
36
+ }
37
+ }
package/src/bin.js CHANGED
@@ -1,16 +1,13 @@
1
1
  #!/usr/bin/env node
2
- // packages/mcp-server/src/bin.js
3
- import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
- import { ControlApiClient } from './client.js';
5
- import { createMcpServer } from './server.js';
6
-
7
- async function main() {
8
- const client = new ControlApiClient(); // resolves port (discovery file) + token (SIMPLIGEN_TOKEN)
9
- const server = createMcpServer(client);
10
- // Whether the app holds the Video Studio decides which tools the client first sees.
11
- // A closed app answers at once; a stuck one gets 3 s, then the poll takes over.
12
- await Promise.race([server.studioGate.refresh(), new Promise((r) => setTimeout(r, 3000).unref())]);
13
- await server.connect(new StdioServerTransport());
14
- }
15
-
16
- main().catch((err) => { console.error('[simpligen-mcp] fatal:', err?.message || err); process.exit(1); });
2
+ // packages/mcp-server/src/bin.js
3
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
+ import { ControlApiClient } from './client.js';
5
+ import { createMcpServer } from './server.js';
6
+
7
+ async function main() {
8
+ const client = new ControlApiClient(); // resolves port (discovery file) + token (SIMPLIGEN_TOKEN)
9
+ const server = createMcpServer(client);
10
+ await server.connect(new StdioServerTransport());
11
+ }
12
+
13
+ main().catch((err) => { console.error('[simpligen-mcp] fatal:', err?.message || err); process.exit(1); });
package/src/client.js CHANGED
@@ -1,170 +1,171 @@
1
- // packages/mcp-server/src/client.js
2
- // Thin client over the SimpliGen local control API. Resolves base URL + token,
3
- // does authed fetch calls, throws a structured error on non-2xx.
4
- import fs from 'node:fs';
5
- import http from 'node:http';
6
- import path from 'node:path';
7
- import { resolveUserDataDir, readDiscoveryPort } from './userdata.js';
8
-
9
- export class ControlApiError extends Error {
10
- constructor(status, errorCode, message) {
11
- super(message || errorCode || `HTTP ${status}`);
12
- this.name = 'ControlApiError';
13
- this.status = status;
14
- this.errorCode = errorCode || null;
15
- }
16
- }
17
-
18
- // A film export may run for up to 20 minutes on the app's side. fetch (undici) gives up
19
- // waiting for the response headers after 5 minutes, so the export goes over node:http
20
- // with a socket timeout just past the route's own limit.
21
- export const LONG_REQUEST_TIMEOUT_MS = 21 * 60 * 1000;
22
-
23
- export class ControlApiClient {
24
- // opts: { baseUrl?, token?, fetchImpl?, env? }. Falls back to discovery file + env.
25
- constructor(opts = {}) {
26
- const env = opts.env || process.env;
27
- this.token = opts.token || env.SIMPLIGEN_TOKEN || null;
28
- this.fetch = opts.fetchImpl || globalThis.fetch;
29
- if (opts.baseUrl) {
30
- this.baseUrl = opts.baseUrl;
31
- } else {
32
- const port = env.SIMPLIGEN_API_PORT ? Number(env.SIMPLIGEN_API_PORT) : readDiscoveryPort(resolveUserDataDir(env));
33
- this.baseUrl = port ? `http://127.0.0.1:${port}` : null;
34
- }
35
- }
36
-
37
- async #req(method, p, body) {
38
- this.#ready();
39
- const res = await this.fetch(`${this.baseUrl}${p}`, {
40
- method,
41
- headers: { Authorization: `Bearer ${this.token}`, 'Content-Type': 'application/json' },
42
- ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
43
- });
44
- let json = {};
45
- try { json = await res.json(); } catch { /* empty body */ }
46
- if (!res.ok) throw new ControlApiError(res.status, json.errorCode, json.message);
47
- return json;
48
- }
49
-
50
- #ready() {
51
- if (!this.baseUrl) throw new ControlApiError(0, 'app_not_running', 'SimpliGen is not running (no control-API port found). Start the app.');
52
- if (!this.token) throw new ControlApiError(0, 'missing_token', 'No pairing token. Set SIMPLIGEN_TOKEN (Settings -> Connect an agent).');
53
- }
54
-
55
- /** The same request as #req, over node:http with a long socket timeout (for an export). */
56
- #longReq(method, p, body) {
57
- this.#ready();
58
- const data = body !== undefined ? JSON.stringify(body) : null;
59
- return new Promise((resolve, reject) => {
60
- const req = http.request(new URL(p, this.baseUrl), {
61
- method,
62
- headers: {
63
- Authorization: `Bearer ${this.token}`, 'Content-Type': 'application/json',
64
- ...(data !== null ? { 'Content-Length': Buffer.byteLength(data) } : {}),
65
- },
66
- timeout: LONG_REQUEST_TIMEOUT_MS,
67
- }, (res) => {
68
- let raw = '';
69
- res.setEncoding('utf8');
70
- res.on('data', (c) => { raw += c; });
71
- res.on('error', reject);
72
- res.on('end', () => {
73
- let json = {};
74
- try { json = raw ? JSON.parse(raw) : {}; } catch { /* not JSON */ }
75
- if (res.statusCode < 200 || res.statusCode >= 300) reject(new ControlApiError(res.statusCode, json.errorCode, json.message));
76
- else resolve(json);
77
- });
78
- });
79
- req.on('timeout', () => req.destroy(new ControlApiError(0, 'timeout', 'The app did not answer in time.')));
80
- req.on('error', reject);
81
- if (data !== null) req.write(data);
82
- req.end();
83
- });
84
- }
85
-
86
- getCapabilities() { return this.#req('GET', '/capabilities'); }
87
- getStatus() { return this.#req('GET', '/status'); }
88
- startEngine() { return this.#req('POST', '/engine/start'); }
89
- stopEngine() { return this.#req('POST', '/engine/stop'); }
90
- restartEngine() { return this.#req('POST', '/engine/restart'); }
91
- listProjects() { return this.#req('GET', '/projects'); }
92
- createProject(name) { return this.#req('POST', '/projects', { name }); }
93
- listLoras() { return this.#req('GET', '/loras'); }
94
- getPromptGuide(presetId) { return this.#req('GET', `/prompt-guide/${encodeURIComponent(presetId)}`); }
95
- generate(args) { return this.#req('POST', '/generate', args); }
96
- waitForApproval(id, timeoutSeconds) { return this.#req('GET', `/approvals/${encodeURIComponent(id)}/wait?timeoutSeconds=${timeoutSeconds}`); }
97
- getAppContext() { return this.#req('GET', '/app/context'); }
98
- fillGenerateForm(body) { return this.#req('POST', '/app/generate-form', body); }
99
- openScreen(body) { return this.#req('POST', '/app/screen', body); }
100
- getJob(id) { return this.#req('GET', `/jobs/${encodeURIComponent(id)}`); }
101
- listJobs() { return this.#req('GET', '/jobs'); }
102
- cancelJob(id) { return this.#req('POST', `/jobs/${encodeURIComponent(id)}/cancel`, {}); }
103
- preparePreset(args) { return this.#req('POST', '/presets/prepare', args); }
104
- getActiveDownloads() { return this.#req('GET', '/presets/prepare'); }
105
-
106
- listCharacters() { return this.#req('GET', '/characters'); }
107
- getCharacter(id) { return this.#req('GET', `/characters/${encodeURIComponent(id)}`); }
108
- listCharacterFeatures() { return this.#req('GET', '/character-features'); }
109
- listCharacterPresets() { return this.#req('GET', '/character-presets'); }
110
- createCharacter(args) { return this.#req('POST', '/characters', args); }
111
- generateCharacterImage(id, args) { return this.#req('POST', `/characters/${encodeURIComponent(id)}/generate-image`, args); }
112
- generateCharacterFrame(id, args) { return this.#req('POST', `/characters/${encodeURIComponent(id)}/generate-frame`, args); }
113
- animateCharacter(id, args) { return this.#req('POST', `/characters/${encodeURIComponent(id)}/animate`, args); }
114
- acceptBase(id, args) { return this.#req('POST', `/characters/${encodeURIComponent(id)}/accept-base`, args); }
115
- setCharacterPreset(id, args) { return this.#req('POST', `/characters/${encodeURIComponent(id)}/preset`, args); }
116
- enhanceCharacterMedia(id, args) { return this.#req('POST', `/characters/${encodeURIComponent(id)}/enhance`, args); }
117
- regenerateCharacterBase(id, args) { return this.#req('POST', `/characters/${encodeURIComponent(id)}/regenerate-base`, args); }
118
- removeCharacter(id) { return this.#req('DELETE', `/characters/${encodeURIComponent(id)}`); }
119
-
120
- listRecipeBlocks() { return this.#req('GET', '/recipe-blocks'); }
121
- composeRecipe(args) { return this.#req('POST', '/recipes', args); }
122
- validateRecipe(args) { return this.#req('POST', '/recipes/validate', args); }
123
- listRecipes() { return this.#req('GET', '/recipes'); }
124
- getRecipe(id) { return this.#req('GET', `/recipes/${encodeURIComponent(id)}`); }
125
- publishRecipe(id, args) { return this.#req('POST', `/recipes/${encodeURIComponent(id)}/publish`, args); }
126
- runRecipe(id, args) { return this.#req('POST', `/recipes/${encodeURIComponent(id)}/run`, args); }
127
- listRecipeRuns(id) { return this.#req('GET', `/recipes/${encodeURIComponent(id)}/runs`); }
128
- getRecipeRun(runId) { return this.#req('GET', `/recipe-runs/${encodeURIComponent(runId)}`); }
129
- cancelRecipeRun(runId) { return this.#req('POST', `/recipe-runs/${encodeURIComponent(runId)}/cancel`, {}); }
130
- listSubjects() { return this.#req('GET', '/subjects'); }
131
- listProducts() { return this.#req('GET', '/products'); }
132
- createProduct(args) { return this.#req('POST', '/products', args); }
133
- removeProduct(id) { return this.#req('DELETE', `/products/${encodeURIComponent(id)}`); }
134
-
135
- // The Video Studio (TASK-1310). Clips and tracks are named by id, name or number.
136
- #film(filmId, rest = '') { return `/films/${encodeURIComponent(filmId)}${rest}`; }
137
- #clip(filmId, clip, rest = '') { return this.#film(filmId, `/clips/${encodeURIComponent(String(clip))}${rest}`); }
138
- listFilms(projectId) { return this.#req('GET', `/films${projectId ? `?projectId=${encodeURIComponent(projectId)}` : ''}`); }
139
- createFilm(args) { return this.#req('POST', '/films', args); }
140
- getFilm(filmId) { return this.#req('GET', this.#film(filmId)); }
141
- updateFilmSettings(filmId, args) { return this.#req('PATCH', this.#film(filmId), args); }
142
- addTrack(filmId, args) { return this.#req('POST', this.#film(filmId, '/tracks'), args); }
143
- moveTrack(filmId, track, args) { return this.#req('PATCH', this.#film(filmId, `/tracks/${encodeURIComponent(String(track))}`), args); }
144
- detectTempo(filmId, args = {}) { return this.#req('POST', this.#film(filmId, '/tempo'), args); }
145
- addClip(filmId, args = {}) { return this.#req('POST', this.#film(filmId, '/clips'), args); }
146
- updateClip(filmId, clip, args) { return this.#req('PATCH', this.#clip(filmId, clip), args); }
147
- moveClip(filmId, clip, args) { return this.#req('POST', this.#clip(filmId, clip, '/move'), args); }
148
- trimClip(filmId, clip, args) { return this.#req('POST', this.#clip(filmId, clip, '/trim'), args); }
149
- removeClip(filmId, clip) { return this.#req('DELETE', this.#clip(filmId, clip)); }
150
- applyFilmPlan(filmId, plan) { return this.#req('POST', this.#film(filmId, '/plan'), plan); }
151
- setFades(filmId, args) { return this.#req('POST', this.#film(filmId, '/fades'), args); }
152
- addMarker(filmId, args) { return this.#req('POST', this.#film(filmId, '/markers'), args); }
153
- setExportRange(filmId, args) { return this.#req('POST', this.#film(filmId, '/export-range'), args); }
154
- renderClips(filmId, args = {}) { return this.#req('POST', this.#film(filmId, '/renders'), args); }
155
- listTakes(filmId, clip) { return this.#req('GET', this.#clip(filmId, clip, '/takes')); }
156
- useTake(filmId, clip, generationId) { return this.#req('POST', this.#clip(filmId, clip, '/take'), { generationId }); }
157
- exportFilm(filmId) { return this.#longReq('POST', this.#film(filmId, '/export'), {}); }
158
- listLocations() { return this.#req('GET', '/locations'); }
159
- createLocation(args) { return this.#req('POST', '/locations', args); }
160
-
161
- async uploadFile(filePath) {
162
- let buf;
163
- try {
164
- buf = fs.readFileSync(filePath);
165
- } catch (e) {
166
- throw new ControlApiError(0, 'file_not_found', `Cannot read file to upload: ${filePath} (${e.code || e.message}).`);
167
- }
168
- return this.#req('POST', '/uploads', { filename: path.basename(filePath), dataBase64: buf.toString('base64') });
169
- }
170
- }
1
+ // packages/mcp-server/src/client.js
2
+ // Thin client over the SimpliGen local control API. Resolves base URL + token,
3
+ // does authed fetch calls, throws a structured error on non-2xx.
4
+ import fs from 'node:fs';
5
+ import http from 'node:http';
6
+ import path from 'node:path';
7
+ import { resolveUserDataDir, readDiscoveryPort } from './userdata.js';
8
+
9
+ export class ControlApiError extends Error {
10
+ constructor(status, errorCode, message) {
11
+ super(message || errorCode || `HTTP ${status}`);
12
+ this.name = 'ControlApiError';
13
+ this.status = status;
14
+ this.errorCode = errorCode || null;
15
+ }
16
+ }
17
+
18
+ // A film export may run for up to 20 minutes on the app's side. fetch (undici) gives up
19
+ // waiting for the response headers after 5 minutes, so the export goes over node:http
20
+ // with a socket timeout just past the route's own limit.
21
+ export const LONG_REQUEST_TIMEOUT_MS = 21 * 60 * 1000;
22
+
23
+ export class ControlApiClient {
24
+ // opts: { baseUrl?, token?, fetchImpl?, env? }. Falls back to discovery file + env.
25
+ constructor(opts = {}) {
26
+ const env = opts.env || process.env;
27
+ this.token = opts.token || env.SIMPLIGEN_TOKEN || null;
28
+ this.fetch = opts.fetchImpl || globalThis.fetch;
29
+ if (opts.baseUrl) {
30
+ this.baseUrl = opts.baseUrl;
31
+ } else {
32
+ const port = env.SIMPLIGEN_API_PORT ? Number(env.SIMPLIGEN_API_PORT) : readDiscoveryPort(resolveUserDataDir(env));
33
+ this.baseUrl = port ? `http://127.0.0.1:${port}` : null;
34
+ }
35
+ }
36
+
37
+ async #req(method, p, body) {
38
+ this.#ready();
39
+ const res = await this.fetch(`${this.baseUrl}${p}`, {
40
+ method,
41
+ headers: { Authorization: `Bearer ${this.token}`, 'Content-Type': 'application/json' },
42
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
43
+ });
44
+ let json = {};
45
+ try { json = await res.json(); } catch { /* empty body */ }
46
+ if (!res.ok) throw new ControlApiError(res.status, json.errorCode, json.message);
47
+ return json;
48
+ }
49
+
50
+ #ready() {
51
+ if (!this.baseUrl) throw new ControlApiError(0, 'app_not_running', 'SimpliGen is not running (no control-API port found). Start the app.');
52
+ if (!this.token) throw new ControlApiError(0, 'missing_token', 'No pairing token. Set SIMPLIGEN_TOKEN (Settings -> Connect an agent).');
53
+ }
54
+
55
+ /** The same request as #req, over node:http with a long socket timeout (for an export). */
56
+ #longReq(method, p, body) {
57
+ this.#ready();
58
+ const data = body !== undefined ? JSON.stringify(body) : null;
59
+ return new Promise((resolve, reject) => {
60
+ const req = http.request(new URL(p, this.baseUrl), {
61
+ method,
62
+ headers: {
63
+ Authorization: `Bearer ${this.token}`, 'Content-Type': 'application/json',
64
+ ...(data !== null ? { 'Content-Length': Buffer.byteLength(data) } : {}),
65
+ },
66
+ timeout: LONG_REQUEST_TIMEOUT_MS,
67
+ }, (res) => {
68
+ let raw = '';
69
+ res.setEncoding('utf8');
70
+ res.on('data', (c) => { raw += c; });
71
+ res.on('error', reject);
72
+ res.on('end', () => {
73
+ let json = {};
74
+ try { json = raw ? JSON.parse(raw) : {}; } catch { /* not JSON */ }
75
+ if (res.statusCode < 200 || res.statusCode >= 300) reject(new ControlApiError(res.statusCode, json.errorCode, json.message));
76
+ else resolve(json);
77
+ });
78
+ });
79
+ req.on('timeout', () => req.destroy(new ControlApiError(0, 'timeout', 'The app did not answer in time.')));
80
+ req.on('error', reject);
81
+ if (data !== null) req.write(data);
82
+ req.end();
83
+ });
84
+ }
85
+
86
+ getCapabilities() { return this.#req('GET', '/capabilities'); }
87
+ getStatus() { return this.#req('GET', '/status'); }
88
+ startEngine() { return this.#req('POST', '/engine/start'); }
89
+ stopEngine() { return this.#req('POST', '/engine/stop'); }
90
+ restartEngine() { return this.#req('POST', '/engine/restart'); }
91
+ listProjects() { return this.#req('GET', '/projects'); }
92
+ createProject(name) { return this.#req('POST', '/projects', { name }); }
93
+ listLoras() { return this.#req('GET', '/loras'); }
94
+ getPromptGuide(presetId) { return this.#req('GET', `/prompt-guide/${encodeURIComponent(presetId)}`); }
95
+ generate(args) { return this.#req('POST', '/generate', args); }
96
+ waitForApproval(id, timeoutSeconds) { return this.#req('GET', `/approvals/${encodeURIComponent(id)}/wait?timeoutSeconds=${timeoutSeconds}`); }
97
+ getAppContext() { return this.#req('GET', '/app/context'); }
98
+ fillGenerateForm(body) { return this.#req('POST', '/app/generate-form', body); }
99
+ openScreen(body) { return this.#req('POST', '/app/screen', body); }
100
+ getJob(id) { return this.#req('GET', `/jobs/${encodeURIComponent(id)}`); }
101
+ listJobs() { return this.#req('GET', '/jobs'); }
102
+ cancelJob(id) { return this.#req('POST', `/jobs/${encodeURIComponent(id)}/cancel`, {}); }
103
+ preparePreset(args) { return this.#req('POST', '/presets/prepare', args); }
104
+ getActiveDownloads() { return this.#req('GET', '/presets/prepare'); }
105
+
106
+ listCharacters() { return this.#req('GET', '/characters'); }
107
+ getCharacter(id) { return this.#req('GET', `/characters/${encodeURIComponent(id)}`); }
108
+ listCharacterFeatures() { return this.#req('GET', '/character-features'); }
109
+ listCharacterPresets() { return this.#req('GET', '/character-presets'); }
110
+ createCharacter(args) { return this.#req('POST', '/characters', args); }
111
+ generateCharacterImage(id, args) { return this.#req('POST', `/characters/${encodeURIComponent(id)}/generate-image`, args); }
112
+ generateCharacterFrame(id, args) { return this.#req('POST', `/characters/${encodeURIComponent(id)}/generate-frame`, args); }
113
+ animateCharacter(id, args) { return this.#req('POST', `/characters/${encodeURIComponent(id)}/animate`, args); }
114
+ acceptBase(id, args) { return this.#req('POST', `/characters/${encodeURIComponent(id)}/accept-base`, args); }
115
+ setCharacterPreset(id, args) { return this.#req('POST', `/characters/${encodeURIComponent(id)}/preset`, args); }
116
+ enhanceCharacterMedia(id, args) { return this.#req('POST', `/characters/${encodeURIComponent(id)}/enhance`, args); }
117
+ regenerateCharacterBase(id, args) { return this.#req('POST', `/characters/${encodeURIComponent(id)}/regenerate-base`, args); }
118
+ removeCharacter(id) { return this.#req('DELETE', `/characters/${encodeURIComponent(id)}`); }
119
+
120
+ listRecipeBlocks() { return this.#req('GET', '/recipe-blocks'); }
121
+ composeRecipe(args) { return this.#req('POST', '/recipes', args); }
122
+ validateRecipe(args) { return this.#req('POST', '/recipes/validate', args); }
123
+ listRecipes() { return this.#req('GET', '/recipes'); }
124
+ getRecipe(id) { return this.#req('GET', `/recipes/${encodeURIComponent(id)}`); }
125
+ publishRecipe(id, args) { return this.#req('POST', `/recipes/${encodeURIComponent(id)}/publish`, args); }
126
+ runRecipe(id, args) { return this.#req('POST', `/recipes/${encodeURIComponent(id)}/run`, args); }
127
+ listRecipeRuns(id) { return this.#req('GET', `/recipes/${encodeURIComponent(id)}/runs`); }
128
+ getRecipeRun(runId) { return this.#req('GET', `/recipe-runs/${encodeURIComponent(runId)}`); }
129
+ cancelRecipeRun(runId) { return this.#req('POST', `/recipe-runs/${encodeURIComponent(runId)}/cancel`, {}); }
130
+ listSubjects() { return this.#req('GET', '/subjects'); }
131
+ listProducts() { return this.#req('GET', '/products'); }
132
+ createProduct(args) { return this.#req('POST', '/products', args); }
133
+ removeProduct(id) { return this.#req('DELETE', `/products/${encodeURIComponent(id)}`); }
134
+
135
+ // The Video Studio (TASK-1310). Clips and tracks are named by id, name or number.
136
+ #film(filmId, rest = '') { return `/films/${encodeURIComponent(filmId)}${rest}`; }
137
+ #clip(filmId, clip, rest = '') { return this.#film(filmId, `/clips/${encodeURIComponent(String(clip))}${rest}`); }
138
+ listFilms(projectId) { return this.#req('GET', `/films${projectId ? `?projectId=${encodeURIComponent(projectId)}` : ''}`); }
139
+ createFilm(args) { return this.#req('POST', '/films', args); }
140
+ getFilm(filmId) { return this.#req('GET', this.#film(filmId)); }
141
+ updateFilmSettings(filmId, args) { return this.#req('PATCH', this.#film(filmId), args); }
142
+ addTrack(filmId, args) { return this.#req('POST', this.#film(filmId, '/tracks'), args); }
143
+ moveTrack(filmId, track, args) { return this.#req('PATCH', this.#film(filmId, `/tracks/${encodeURIComponent(String(track))}`), args); }
144
+ detectTempo(filmId, args = {}) { return this.#req('POST', this.#film(filmId, '/tempo'), args); }
145
+ addClip(filmId, args = {}) { return this.#req('POST', this.#film(filmId, '/clips'), args); }
146
+ importClip(filmId, args = {}) { return this.#req('POST', this.#film(filmId, '/clips/import'), args); }
147
+ updateClip(filmId, clip, args) { return this.#req('PATCH', this.#clip(filmId, clip), args); }
148
+ moveClip(filmId, clip, args) { return this.#req('POST', this.#clip(filmId, clip, '/move'), args); }
149
+ trimClip(filmId, clip, args) { return this.#req('POST', this.#clip(filmId, clip, '/trim'), args); }
150
+ removeClip(filmId, clip) { return this.#req('DELETE', this.#clip(filmId, clip)); }
151
+ applyFilmPlan(filmId, plan) { return this.#req('POST', this.#film(filmId, '/plan'), plan); }
152
+ setFades(filmId, args) { return this.#req('POST', this.#film(filmId, '/fades'), args); }
153
+ addMarker(filmId, args) { return this.#req('POST', this.#film(filmId, '/markers'), args); }
154
+ setExportRange(filmId, args) { return this.#req('POST', this.#film(filmId, '/export-range'), args); }
155
+ renderClips(filmId, args = {}) { return this.#req('POST', this.#film(filmId, '/renders'), args); }
156
+ listTakes(filmId, clip) { return this.#req('GET', this.#clip(filmId, clip, '/takes')); }
157
+ useTake(filmId, clip, generationId) { return this.#req('POST', this.#clip(filmId, clip, '/take'), { generationId }); }
158
+ exportFilm(filmId) { return this.#longReq('POST', this.#film(filmId, '/export'), {}); }
159
+ listLocations() { return this.#req('GET', '/locations'); }
160
+ createLocation(args) { return this.#req('POST', '/locations', args); }
161
+
162
+ async uploadFile(filePath) {
163
+ let buf;
164
+ try {
165
+ buf = fs.readFileSync(filePath);
166
+ } catch (e) {
167
+ throw new ControlApiError(0, 'file_not_found', `Cannot read file to upload: ${filePath} (${e.code || e.message}).`);
168
+ }
169
+ return this.#req('POST', '/uploads', { filename: path.basename(filePath), dataBase64: buf.toString('base64') });
170
+ }
171
+ }
package/src/index.js CHANGED
@@ -1,7 +1,6 @@
1
- // packages/mcp-server/src/index.js
2
- export { ControlApiClient, ControlApiError } from './client.js';
3
- export { createMcpServer } from './server.js';
4
- export { registerTools, TOOL_NAMES, STUDIO_TOOL_NAMES } from './tools.js';
5
- export { createStudioGate } from './studioGate.js';
6
- export { buildResultImageContent } from './resultImage.js';
7
- export { resolveUserDataDir, readDiscoveryPort } from './userdata.js';
1
+ // packages/mcp-server/src/index.js
2
+ export { ControlApiClient, ControlApiError } from './client.js';
3
+ export { createMcpServer } from './server.js';
4
+ export { registerTools, TOOL_NAMES, STUDIO_TOOL_NAMES } from './tools.js';
5
+ export { buildResultImageContent } from './resultImage.js';
6
+ export { resolveUserDataDir, readDiscoveryPort } from './userdata.js';
package/src/server.js CHANGED
@@ -1,24 +1,15 @@
1
- // packages/mcp-server/src/server.js
2
- import { createRequire } from 'node:module';
3
- import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
4
- import { registerTools } from './tools.js';
5
- import { createStudioGate } from './studioGate.js';
6
-
7
- const { version } = createRequire(import.meta.url)('../package.json');
8
-
9
- /**
10
- * @param {object} client a ControlApiClient
11
- * @param {{ studioPollMs?: number }} [options] how often to ask the app whether it holds the Video Studio
12
- */
13
- export function createMcpServer(client, { studioPollMs } = {}) {
14
- const server = new McpServer({ name: 'simpligen', version });
15
- let gate = null;
16
- const { studioTools } = registerTools(server, client, { onStatus: (status) => gate?.observe(status) });
17
- gate = createStudioGate({ client, tools: studioTools, notify: () => server.sendToolListChanged(), pollMs: studioPollMs });
18
- // The gate asks the app once a client is connected, and stops when it goes.
19
- server.server.oninitialized = () => gate.start();
20
- server.server.onclose = () => gate.stop();
21
- // bin.js reads the status once before connecting, so the first tool list is already right.
22
- server.studioGate = gate;
23
- return server;
24
- }
1
+ // packages/mcp-server/src/server.js
2
+ import { createRequire } from 'node:module';
3
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
4
+ import { registerTools } from './tools.js';
5
+
6
+ const { version } = createRequire(import.meta.url)('../package.json');
7
+
8
+ /**
9
+ * @param {object} client a ControlApiClient
10
+ */
11
+ export function createMcpServer(client) {
12
+ const server = new McpServer({ name: 'simpligen', version });
13
+ registerTools(server, client);
14
+ return server;
15
+ }