@mcut/mcp-server 0.1.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,187 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ https://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and
10
+ distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by the
13
+ copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other
16
+ entities that control, are controlled by, or are under common control with
17
+ that entity. For the purposes of this definition, "control" means (i) the
18
+ power, direct or indirect, to cause the direction or management of such
19
+ entity, whether by contract or otherwise, or (ii) ownership of fifty percent
20
+ (50%) or more of the outstanding shares, or (iii) beneficial ownership of
21
+ such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity exercising
24
+ permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation source, and
28
+ configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical transformation
31
+ or translation of a Source form, including but not limited to compiled object
32
+ code, generated documentation, and conversions to other media types.
33
+
34
+ "Work" shall mean the work of authorship, whether in Source or Object form,
35
+ made available under the License, as indicated by a copyright notice that is
36
+ included in or attached to the work (an example is provided in the Appendix
37
+ below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object form,
40
+ that is based on (or derived from) the Work and for which the editorial
41
+ revisions, annotations, elaborations, or other modifications represent, as a
42
+ whole, an original work of authorship. For the purposes of this License,
43
+ Derivative Works shall not include works that remain separable from, or
44
+ merely link (or bind by name) to the interfaces of, the Work and Derivative
45
+ Works thereof.
46
+
47
+ "Contribution" shall mean any work of authorship, including the original
48
+ version of the Work and any modifications or additions to that Work or
49
+ Derivative Works thereof, that is intentionally submitted to Licensor for
50
+ inclusion in the Work by the copyright owner or by an individual or Legal
51
+ Entity authorized to submit on behalf of the copyright owner. For the
52
+ purposes of this definition, "submitted" means any form of electronic,
53
+ verbal, or written communication sent to the Licensor or its representatives,
54
+ including but not limited to communication on electronic mailing lists,
55
+ source code control systems, and issue tracking systems that are managed by,
56
+ or on behalf of, the Licensor for the purpose of discussing and improving the
57
+ Work, but excluding communication that is conspicuously marked or otherwise
58
+ designated in writing by the copyright owner as "Not a Contribution."
59
+
60
+ "Contributor" shall mean Licensor and any individual or Legal Entity on
61
+ behalf of whom a Contribution has been received by Licensor and subsequently
62
+ incorporated within the Work.
63
+
64
+ 2. Grant of Copyright License. Subject to the terms and conditions of this
65
+ License, each Contributor hereby grants to You a perpetual, worldwide,
66
+ non-exclusive, no-charge, royalty-free, irrevocable copyright license to
67
+ reproduce, prepare Derivative Works of, publicly display, publicly perform,
68
+ sublicense, and distribute the Work and such Derivative Works in Source or
69
+ Object form.
70
+
71
+ 3. Grant of Patent License. Subject to the terms and conditions of this
72
+ License, each Contributor hereby grants to You a perpetual, worldwide,
73
+ non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this
74
+ section) patent license to make, have made, use, offer to sell, sell, import,
75
+ and otherwise transfer the Work, where such license applies only to those
76
+ patent claims licensable by such Contributor that are necessarily infringed
77
+ by their Contribution(s) alone or by combination of their Contribution(s)
78
+ with the Work to which such Contribution(s) was submitted. If You institute
79
+ patent litigation against any entity (including a cross-claim or counterclaim
80
+ in a lawsuit) alleging that the Work or a Contribution incorporated within
81
+ the Work constitutes direct or contributory patent infringement, then any
82
+ patent licenses granted to You under this License for that Work shall
83
+ terminate as of the date such litigation is filed.
84
+
85
+ 4. Redistribution. You may reproduce and distribute copies of the Work or
86
+ Derivative Works thereof in any medium, with or without modifications, and in
87
+ Source or Object form, provided that You meet the following conditions:
88
+
89
+ (a) You must give any other recipients of the Work or Derivative Works a
90
+ copy of this License; and
91
+
92
+ (b) You must cause any modified files to carry prominent notices stating that
93
+ You changed the files; and
94
+
95
+ (c) You must retain, in the Source form of any Derivative Works that You
96
+ distribute, all copyright, patent, trademark, and attribution notices from
97
+ the Source form of the Work, excluding those notices that do not pertain to
98
+ any part of the Derivative Works; and
99
+
100
+ (d) If the Work includes a "NOTICE" text file as part of its distribution,
101
+ then any Derivative Works that You distribute must include a readable copy of
102
+ the attribution notices contained within such NOTICE file, excluding those
103
+ notices that do not pertain to any part of the Derivative Works, in at least
104
+ one of the following places: within a NOTICE text file distributed as part of
105
+ the Derivative Works; within the Source form or documentation, if provided
106
+ along with the Derivative Works; or, within a display generated by the
107
+ Derivative Works, if and wherever such third-party notices normally appear.
108
+ The contents of the NOTICE file are for informational purposes only and do
109
+ not modify the License. You may add Your own attribution notices within
110
+ Derivative Works that You distribute, alongside or as an addendum to the
111
+ NOTICE text from the Work, provided that such additional attribution notices
112
+ cannot be construed as modifying the License.
113
+
114
+ You may add Your own copyright statement to Your modifications and may
115
+ provide additional or different license terms and conditions for use,
116
+ reproduction, or distribution of Your modifications, or for any such
117
+ Derivative Works as a whole, provided Your use, reproduction, and
118
+ distribution of the Work otherwise complies with the conditions stated in
119
+ this License.
120
+
121
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any
122
+ Contribution intentionally submitted for inclusion in the Work by You to the
123
+ Licensor shall be under the terms and conditions of this License, without any
124
+ additional terms or conditions. Notwithstanding the above, nothing herein
125
+ shall supersede or modify the terms of any separate license agreement you may
126
+ have executed with Licensor regarding such Contributions.
127
+
128
+ 6. Trademarks. This License does not grant permission to use the trade names,
129
+ trademarks, service marks, or product names of the Licensor, except as
130
+ required for reasonable and customary use in describing the origin of the
131
+ Work and reproducing the content of the NOTICE file.
132
+
133
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in
134
+ writing, Licensor provides the Work (and each Contributor provides its
135
+ Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
136
+ KIND, either express or implied, including, without limitation, any warranties
137
+ or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
138
+ PARTICULAR PURPOSE. You are solely responsible for determining the
139
+ appropriateness of using or redistributing the Work and assume any risks
140
+ associated with Your exercise of permissions under this License.
141
+
142
+ 8. Limitation of Liability. In no event and under no legal theory, whether in
143
+ tort (including negligence), contract, or otherwise, unless required by
144
+ applicable law (such as deliberate and grossly negligent acts) or agreed to
145
+ in writing, shall any Contributor be liable to You for damages, including any
146
+ direct, indirect, special, incidental, or consequential damages of any
147
+ character arising as a result of this License or out of the use or inability
148
+ to use the Work (including but not limited to damages for loss of goodwill,
149
+ work stoppage, computer failure or malfunction, or any and all other
150
+ commercial damages or losses), even if such Contributor has been advised of
151
+ the possibility of such damages.
152
+
153
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work
154
+ or Derivative Works thereof, You may choose to offer, and charge a fee for,
155
+ acceptance of support, warranty, indemnity, or other liability obligations
156
+ and/or rights consistent with this License. However, in accepting such
157
+ obligations, You may act only on Your own behalf and on Your sole
158
+ responsibility, not on behalf of any other Contributor, and only if You agree
159
+ to indemnify, defend, and hold each Contributor harmless for any liability
160
+ incurred by, or claims asserted against, such Contributor by reason of your
161
+ accepting any such warranty or additional liability.
162
+
163
+ END OF TERMS AND CONDITIONS
164
+
165
+ APPENDIX: How to apply the Apache License to your work.
166
+
167
+ To apply the Apache License to your work, attach the following boilerplate
168
+ notice, with the fields enclosed by brackets "[]" replaced with your own
169
+ identifying information. (Don't include the brackets!) The text should be
170
+ enclosed in the appropriate comment syntax for the file format. We also
171
+ recommend that a file or class name and description of purpose be included on
172
+ the same "printed page" as the copyright notice for easier identification
173
+ within third-party archives.
174
+
175
+ Copyright [yyyy] [name of copyright owner]
176
+
177
+ Licensed under the Apache License, Version 2.0 (the "License");
178
+ you may not use this file except in compliance with the License.
179
+ You may obtain a copy of the License at
180
+
181
+ https://www.apache.org/licenses/LICENSE-2.0
182
+
183
+ Unless required by applicable law or agreed to in writing, software
184
+ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
185
+ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
186
+ See the License for the specific language governing permissions and
187
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,11 @@
1
+ # @mcut/mcp-server
2
+
3
+ MCP server and local browser bridge for mcut.
4
+
5
+ ```sh
6
+ bunx @mcut/mcp-server
7
+ ```
8
+
9
+ This package exposes mcut commands and editor operators as Model Context
10
+ Protocol tools. It also includes local bridge commands for connecting MCP
11
+ clients to a live browser editor session.
@@ -0,0 +1 @@
1
+ export { };
@@ -0,0 +1,205 @@
1
+ #!/usr/bin/env node
2
+ import { n as createMcutMcpServerForTarget } from "./server-DyDMot4v.js";
3
+ import { a as parseLiveBridgePort, i as createHttpBridgeTarget, r as LiveMcutBridge, t as DEFAULT_BRIDGE_PORT } from "./live-bridge-ky67GOTs.js";
4
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
+ //#region src/bridge-cli.ts
6
+ /**
7
+ * Local bridge entry point:
8
+ *
9
+ * mcut-bridge start
10
+ * mcut-bridge get-summary
11
+ * mcut-bridge get-transcript
12
+ * mcut-bridge dispatch addTrack --json '{"name":"B-roll"}'
13
+ * mcut-bridge mcp
14
+ */
15
+ function usage() {
16
+ return [
17
+ "Usage:",
18
+ " mcut-bridge start [--port 44737] [--editor-url http://localhost:3000/editor] [--allow-origin https://mcut.com]",
19
+ " mcut-bridge status [--port 44737]",
20
+ " mcut-bridge url [--editor-url http://localhost:3000/editor] [--port 44737]",
21
+ " mcut-bridge get-summary [--port 44737]",
22
+ " mcut-bridge get-project [--port 44737]",
23
+ " mcut-bridge get-media-context [--port 44737]",
24
+ " mcut-bridge get-transcript [--json '{\"includeWords\":true}'] [--port 44737]",
25
+ " mcut-bridge search-transcript <query> [--port 44737]",
26
+ " mcut-bridge ensure-transcript [--json '{\"elementId\":\"e-...\",\"replace\":false}'] [--port 44737]",
27
+ " mcut-bridge list-actions [--port 44737]",
28
+ " mcut-bridge action <actionId> [--json '{...}'] [--port 44737]",
29
+ " mcut-bridge dispatch <commandName> [--json '{...}'] [--port 44737]",
30
+ " mcut-bridge operator <operatorId> [--json '{...}'] [--port 44737]",
31
+ " mcut-bridge undo [--port 44737]",
32
+ " mcut-bridge redo [--port 44737]",
33
+ " mcut-bridge mcp [--port 44737]"
34
+ ].join("\n");
35
+ }
36
+ function parseJson(value) {
37
+ if (!value) return {};
38
+ return JSON.parse(value);
39
+ }
40
+ function parseArgs(argv) {
41
+ const command = argv[0] ?? "help";
42
+ const rest = [];
43
+ let port = DEFAULT_BRIDGE_PORT;
44
+ let json = {};
45
+ let editorUrl = "http://localhost:3000/editor";
46
+ const allowedOrigins = [];
47
+ for (let i = 1; i < argv.length; i++) {
48
+ const arg = argv[i];
49
+ if (!arg) continue;
50
+ if (arg === "--port") port = parseLiveBridgePort(argv[++i]) ?? 44737;
51
+ else if (arg === "--json") json = parseJson(argv[++i]);
52
+ else if (arg === "--editor-url") editorUrl = argv[++i] ?? editorUrl;
53
+ else if (arg === "--allow-origin") {
54
+ const origin = argv[++i];
55
+ if (origin) allowedOrigins.push(origin);
56
+ } else rest.push(arg);
57
+ }
58
+ return {
59
+ command,
60
+ rest,
61
+ port,
62
+ json,
63
+ editorUrl,
64
+ allowedOrigins
65
+ };
66
+ }
67
+ async function rpc(port, type, payload = {}) {
68
+ const response = await fetch(`http://127.0.0.1:${port}/rpc`, {
69
+ method: "POST",
70
+ headers: {
71
+ "content-type": "application/json",
72
+ "x-mcut-bridge-client": "cli"
73
+ },
74
+ body: JSON.stringify({
75
+ type,
76
+ payload
77
+ })
78
+ });
79
+ const json = await response.json();
80
+ if (!response.ok || !json.ok) throw new Error(json.error ?? `mcut bridge request failed (${response.status})`);
81
+ return json.result;
82
+ }
83
+ async function status(port) {
84
+ const response = await fetch(`http://127.0.0.1:${port}/status`);
85
+ const json = await response.json();
86
+ if (!response.ok || !json.ok) throw new Error(json.error ?? "mcut bridge is not running.");
87
+ return json.result;
88
+ }
89
+ function editorUrl(base, port) {
90
+ const url = new URL(base);
91
+ url.searchParams.set("mcpBridge", String(port));
92
+ return url.toString();
93
+ }
94
+ function originOf(value) {
95
+ try {
96
+ return new URL(value).origin;
97
+ } catch {
98
+ return null;
99
+ }
100
+ }
101
+ function print(value) {
102
+ if (typeof value === "string") {
103
+ console.log(value);
104
+ return;
105
+ }
106
+ console.log(JSON.stringify(value, null, 2));
107
+ }
108
+ async function main() {
109
+ const args = parseArgs(process.argv.slice(2));
110
+ switch (args.command) {
111
+ case "help":
112
+ case "--help":
113
+ case "-h":
114
+ console.log(usage());
115
+ return;
116
+ case "start": {
117
+ const editorOrigin = originOf(args.editorUrl);
118
+ const port = await new LiveMcutBridge({
119
+ token: null,
120
+ allowedOrigins: [...args.allowedOrigins, ...editorOrigin ? [editorOrigin] : []]
121
+ }).listen(args.port);
122
+ console.error(`mcut bridge ready — ws://127.0.0.1:${port}/mcut-mcp`);
123
+ console.error(`Editor URL: ${editorUrl(args.editorUrl, port)}`);
124
+ console.error("Leave this process running while agents edit the browser project.");
125
+ await new Promise(() => {});
126
+ return;
127
+ }
128
+ case "status":
129
+ print(await status(args.port));
130
+ return;
131
+ case "url":
132
+ console.log(editorUrl(args.editorUrl, args.port));
133
+ return;
134
+ case "get-summary":
135
+ print(await rpc(args.port, "get_summary"));
136
+ return;
137
+ case "get-project":
138
+ print(await rpc(args.port, "get_project"));
139
+ return;
140
+ case "get-media-context":
141
+ print(await rpc(args.port, "get_media_context"));
142
+ return;
143
+ case "get-transcript":
144
+ print(await rpc(args.port, "get_transcript", args.json));
145
+ return;
146
+ case "search-transcript": {
147
+ const query = args.rest.join(" ").trim();
148
+ if (!query) throw new Error("search-transcript requires a query.");
149
+ print(await rpc(args.port, "search_transcript", { query }));
150
+ return;
151
+ }
152
+ case "ensure-transcript":
153
+ print(await rpc(args.port, "ensure_transcript", args.json));
154
+ return;
155
+ case "list-actions":
156
+ print(await rpc(args.port, "list_actions"));
157
+ return;
158
+ case "action": {
159
+ const actionId = args.rest[0];
160
+ if (!actionId) throw new Error("action requires an action id.");
161
+ print(await rpc(args.port, "run_action", {
162
+ actionId,
163
+ input: args.json
164
+ }));
165
+ return;
166
+ }
167
+ case "dispatch": {
168
+ const commandName = args.rest[0];
169
+ if (!commandName) throw new Error("dispatch requires a command name.");
170
+ print(await rpc(args.port, "dispatch_command", {
171
+ commandName,
172
+ input: args.json
173
+ }));
174
+ return;
175
+ }
176
+ case "operator": {
177
+ const operatorId = args.rest[0];
178
+ if (!operatorId) throw new Error("operator requires an operator id.");
179
+ print(await rpc(args.port, "run_operator", {
180
+ operatorId,
181
+ input: args.json
182
+ }));
183
+ return;
184
+ }
185
+ case "undo":
186
+ print(await rpc(args.port, "undo"));
187
+ return;
188
+ case "redo":
189
+ print(await rpc(args.port, "redo"));
190
+ return;
191
+ case "mcp":
192
+ await createMcutMcpServerForTarget({
193
+ target: createHttpBridgeTarget(args.port),
194
+ name: "mcut-bridge"
195
+ }).connect(new StdioServerTransport());
196
+ return;
197
+ default: throw new Error(`Unknown mcut-bridge command "${args.command}".\n\n${usage()}`);
198
+ }
199
+ }
200
+ main().catch((error) => {
201
+ console.error(error instanceof Error ? error.message : String(error));
202
+ process.exit(1);
203
+ });
204
+ //#endregion
205
+ export {};
package/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ export { };
package/dist/cli.js ADDED
@@ -0,0 +1,30 @@
1
+ #!/usr/bin/env node
2
+ import { t as createMcutMcpServer } from "./server-DyDMot4v.js";
3
+ import { EditorEngine, parseProject } from "@mcut/timeline";
4
+ import { existsSync } from "node:fs";
5
+ import { readFile, writeFile } from "node:fs/promises";
6
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
7
+ //#region src/cli.ts
8
+ /**
9
+ * Stdio entry point:
10
+ *
11
+ * bunx @mcut/mcp-server [path/to/project.json]
12
+ *
13
+ * The project file (default `project.mcut.json`, or $MCUT_PROJECT) is created
14
+ * when missing and rewritten after every successful edit.
15
+ */
16
+ const projectPath = process.argv[2] ?? process.env.MCUT_PROJECT ?? "project.mcut.json";
17
+ async function loadEngine() {
18
+ if (!existsSync(projectPath)) return new EditorEngine();
19
+ return new EditorEngine({ project: parseProject(JSON.parse(await readFile(projectPath, "utf8"))) });
20
+ }
21
+ const engine = await loadEngine();
22
+ await createMcutMcpServer({
23
+ engine,
24
+ onChange: async () => {
25
+ await writeFile(projectPath, `${JSON.stringify(engine.toJSON(), null, 2)}\n`, "utf8");
26
+ }
27
+ }).connect(new StdioServerTransport());
28
+ console.error(`mcut MCP server ready — project: ${projectPath}`);
29
+ //#endregion
30
+ export {};
@@ -0,0 +1,83 @@
1
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
+ import { EditorOperatorRegistry } from "@mcut/editor";
3
+ import { EditorEngine, ProjectTranscriptOptions } from "@mcut/timeline";
4
+
5
+ //#region src/server.d.ts
6
+ interface McutMcpTarget {
7
+ getSummary(): string | Promise<string>;
8
+ getProject(): unknown | Promise<unknown>;
9
+ getMediaContext?(): unknown | Promise<unknown>;
10
+ getTranscript?(options?: ProjectTranscriptOptions): unknown | Promise<unknown>;
11
+ searchTranscript?(query: string): unknown | Promise<unknown>;
12
+ ensureTranscript?(input: unknown): unknown | Promise<unknown>;
13
+ listActions(): unknown | Promise<unknown>;
14
+ listOperators(): unknown | Promise<unknown>;
15
+ runAction(actionId: string, input: unknown): unknown | Promise<unknown>;
16
+ undo(): boolean | Promise<boolean>;
17
+ redo(): boolean | Promise<boolean>;
18
+ runOperator(operatorId: string, input: unknown): unknown | Promise<unknown>;
19
+ dispatchCommand(commandName: string, input: unknown): unknown | Promise<unknown>;
20
+ }
21
+ interface McutMcpServerOptions {
22
+ engine: EditorEngine;
23
+ /** Called after every successful edit — persist the project here. */
24
+ onChange?: () => void | Promise<void>;
25
+ /** Defaults to the core operator set. */
26
+ operators?: EditorOperatorRegistry;
27
+ name?: string;
28
+ version?: string;
29
+ }
30
+ interface McutMcpServerForTargetOptions {
31
+ target: McutMcpTarget;
32
+ /** Defaults to the core operator set. Used for tool schema generation. */
33
+ operators?: EditorOperatorRegistry;
34
+ name?: string;
35
+ version?: string;
36
+ }
37
+ declare const operatorToolName: (id: string) => string;
38
+ /**
39
+ * Build the server around an existing engine. The caller owns the transport:
40
+ * `await createMcutMcpServer({ engine }).connect(new StdioServerTransport())`.
41
+ */
42
+ declare function createMcutMcpServer(options: McutMcpServerOptions): Server;
43
+ /** Build the same MCP tool surface around any target, including a live browser tab. */
44
+ declare function createMcutMcpServerForTarget(options: McutMcpServerForTargetOptions): Server;
45
+ //#endregion
46
+ //#region src/live-bridge.d.ts
47
+ declare const DEFAULT_BRIDGE_PORT = 44737;
48
+ interface LiveBridgeOptions {
49
+ token?: string | null;
50
+ allowedOrigins?: string[];
51
+ requestTimeoutMs?: number;
52
+ transcriptionTimeoutMs?: number;
53
+ }
54
+ declare class LiveBridgeError extends Error {
55
+ readonly code: string;
56
+ constructor(code: string, message: string);
57
+ }
58
+ declare class LiveMcutBridge {
59
+ readonly token: string | null;
60
+ readonly requestTimeoutMs: number;
61
+ readonly transcriptionTimeoutMs: number;
62
+ private readonly server;
63
+ private readonly wss;
64
+ private readonly pending;
65
+ private socket;
66
+ private nextId;
67
+ private tabInfo;
68
+ constructor(options?: LiveBridgeOptions);
69
+ listen(port?: number): Promise<number>;
70
+ close(): void;
71
+ isConnected(): boolean;
72
+ getTabInfo(): unknown;
73
+ rpc(type: string, payload?: unknown): Promise<unknown>;
74
+ request(type: string, payload?: unknown): Promise<unknown>;
75
+ createTarget(): McutMcpTarget;
76
+ private attach;
77
+ private receive;
78
+ private handleHttp;
79
+ }
80
+ declare function parseLiveBridgePort(value: string | undefined): number | undefined;
81
+ declare function createHttpBridgeTarget(port?: number): McutMcpTarget;
82
+ //#endregion
83
+ export { DEFAULT_BRIDGE_PORT, LiveBridgeError, type LiveBridgeOptions, LiveMcutBridge, type McutMcpServerForTargetOptions, type McutMcpServerOptions, type McutMcpTarget, createHttpBridgeTarget, createMcutMcpServer, createMcutMcpServerForTarget, operatorToolName, parseLiveBridgePort };
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ import { n as createMcutMcpServerForTarget, r as operatorToolName, t as createMcutMcpServer } from "./server-DyDMot4v.js";
2
+ import { a as parseLiveBridgePort, i as createHttpBridgeTarget, n as LiveBridgeError, r as LiveMcutBridge, t as DEFAULT_BRIDGE_PORT } from "./live-bridge-ky67GOTs.js";
3
+ export { DEFAULT_BRIDGE_PORT, LiveBridgeError, LiveMcutBridge, createHttpBridgeTarget, createMcutMcpServer, createMcutMcpServerForTarget, operatorToolName, parseLiveBridgePort };
@@ -0,0 +1,300 @@
1
+ import { createServer } from "node:http";
2
+ import { randomBytes } from "node:crypto";
3
+ import { WebSocket, WebSocketServer } from "ws";
4
+ //#region src/live-bridge.ts
5
+ const DEFAULT_BRIDGE_PORT = 44737;
6
+ var LiveBridgeError = class extends Error {
7
+ code;
8
+ constructor(code, message) {
9
+ super(message);
10
+ this.name = "LiveBridgeError";
11
+ this.code = code;
12
+ }
13
+ };
14
+ function parsePort(value) {
15
+ if (!value) return null;
16
+ const port = Number(value);
17
+ return Number.isInteger(port) && port >= 0 && port <= 65535 ? port : null;
18
+ }
19
+ function isAllowedOrigin(origin, allowedOrigins) {
20
+ if (!origin) return true;
21
+ let parsed;
22
+ try {
23
+ parsed = new URL(origin);
24
+ } catch {
25
+ return false;
26
+ }
27
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false;
28
+ if (allowedOrigins.includes(origin)) return true;
29
+ return parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1";
30
+ }
31
+ function tokenFrom(req) {
32
+ const host = req.headers.host ?? "127.0.0.1";
33
+ return new URL(req.url ?? "/", `http://${host}`).searchParams.get("token");
34
+ }
35
+ function hasCliHeader(req) {
36
+ return req.headers["x-mcut-bridge-client"] === "cli";
37
+ }
38
+ function sendJson(res, status, value) {
39
+ res.writeHead(status, {
40
+ "content-type": "application/json; charset=utf-8",
41
+ "cache-control": "no-store"
42
+ });
43
+ res.end(`${JSON.stringify(value)}\n`);
44
+ }
45
+ async function readJson(req) {
46
+ const chunks = [];
47
+ for await (const chunk of req) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
48
+ if (chunks.length === 0) return {};
49
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
50
+ }
51
+ function messageError(error) {
52
+ const prefix = error.code ? `${error.name ?? "Error"} (${error.code})` : error.name ?? "Error";
53
+ return new LiveBridgeError(error.code ?? "browser-error", `${prefix}: ${error.message ?? "Unknown error"}`);
54
+ }
55
+ var LiveMcutBridge = class {
56
+ token;
57
+ requestTimeoutMs;
58
+ transcriptionTimeoutMs;
59
+ server = createServer((req, res) => void this.handleHttp(req, res));
60
+ wss;
61
+ pending = /* @__PURE__ */ new Map();
62
+ socket = null;
63
+ nextId = 1;
64
+ tabInfo = null;
65
+ constructor(options = {}) {
66
+ this.token = options.token === void 0 ? randomBytes(32).toString("hex") : options.token;
67
+ this.requestTimeoutMs = options.requestTimeoutMs ?? 3e4;
68
+ this.transcriptionTimeoutMs = options.transcriptionTimeoutMs ?? 10 * 6e4;
69
+ const allowedOrigins = options.allowedOrigins ?? [];
70
+ const verifyClient = ({ origin, req }) => (this.token === null || tokenFrom(req) === this.token) && isAllowedOrigin(origin, allowedOrigins);
71
+ this.wss = new WebSocketServer({
72
+ server: this.server,
73
+ path: "/mcut-mcp",
74
+ verifyClient
75
+ });
76
+ this.wss.on("connection", (socket) => this.attach(socket));
77
+ }
78
+ async listen(port = 0) {
79
+ await new Promise((resolve, reject) => {
80
+ this.server.once("error", reject);
81
+ this.server.listen(port, "127.0.0.1", () => {
82
+ this.server.off("error", reject);
83
+ resolve();
84
+ });
85
+ });
86
+ const address = this.server.address();
87
+ if (!address || typeof address === "string") throw new LiveBridgeError("invalid-listener", "Could not determine live bridge port.");
88
+ return address.port;
89
+ }
90
+ close() {
91
+ this.socket?.close();
92
+ this.wss.close();
93
+ this.server.close();
94
+ for (const [id, pending] of this.pending) {
95
+ clearTimeout(pending.timer);
96
+ pending.reject(new LiveBridgeError("bridge-closed", `Live bridge closed before response ${id}.`));
97
+ }
98
+ this.pending.clear();
99
+ }
100
+ isConnected() {
101
+ return this.socket?.readyState === WebSocket.OPEN;
102
+ }
103
+ getTabInfo() {
104
+ return this.tabInfo;
105
+ }
106
+ async rpc(type, payload = {}) {
107
+ switch (type) {
108
+ case "status": return {
109
+ connected: this.isConnected(),
110
+ tab: this.tabInfo
111
+ };
112
+ default: return await this.request(type, payload);
113
+ }
114
+ }
115
+ async request(type, payload = {}) {
116
+ const socket = this.socket;
117
+ if (!socket || socket.readyState !== WebSocket.OPEN) throw new LiveBridgeError("browser-not-connected", "No mcut editor tab is connected. Open the live editor URL printed by the MCP server.");
118
+ const timeoutMs = type === "ensure_transcript" ? this.transcriptionTimeoutMs : this.requestTimeoutMs;
119
+ const id = String(this.nextId++);
120
+ const body = JSON.stringify({
121
+ id,
122
+ type,
123
+ payload
124
+ });
125
+ return await new Promise((resolve, reject) => {
126
+ const timer = setTimeout(() => {
127
+ this.pending.delete(id);
128
+ reject(new LiveBridgeError("request-timeout", `Timed out waiting for browser response to ${type}.`));
129
+ }, timeoutMs);
130
+ this.pending.set(id, {
131
+ resolve,
132
+ reject,
133
+ timer
134
+ });
135
+ socket.send(body, (error) => {
136
+ if (!error) return;
137
+ clearTimeout(timer);
138
+ this.pending.delete(id);
139
+ reject(error);
140
+ });
141
+ });
142
+ }
143
+ createTarget() {
144
+ return {
145
+ getSummary: async () => String(await this.request("get_summary")),
146
+ getProject: () => this.request("get_project"),
147
+ getMediaContext: () => this.request("get_media_context"),
148
+ getTranscript: (options) => this.request("get_transcript", options ?? {}),
149
+ searchTranscript: (query) => this.request("search_transcript", { query }),
150
+ ensureTranscript: (input) => this.request("ensure_transcript", input ?? {}),
151
+ listActions: () => this.request("list_actions"),
152
+ listOperators: () => this.request("list_operators"),
153
+ undo: async () => Boolean(await this.request("undo")),
154
+ redo: async () => Boolean(await this.request("redo")),
155
+ runAction: (actionId, input) => this.request("run_action", {
156
+ actionId,
157
+ input: input ?? {}
158
+ }),
159
+ runOperator: (operatorId, input) => this.request("run_operator", {
160
+ operatorId,
161
+ input: input ?? {}
162
+ }),
163
+ dispatchCommand: (commandName, input) => this.request("dispatch_command", {
164
+ commandName,
165
+ input: input ?? {}
166
+ })
167
+ };
168
+ }
169
+ attach(socket) {
170
+ this.socket?.close(1012, "Another mcut editor tab connected.");
171
+ this.socket = socket;
172
+ this.tabInfo = null;
173
+ socket.on("message", (raw) => this.receive(raw.toString()));
174
+ socket.on("close", () => {
175
+ if (this.socket === socket) {
176
+ this.socket = null;
177
+ this.tabInfo = null;
178
+ }
179
+ for (const [id, pending] of this.pending) {
180
+ clearTimeout(pending.timer);
181
+ pending.reject(new LiveBridgeError("browser-disconnected", `Browser disconnected before response ${id}.`));
182
+ }
183
+ this.pending.clear();
184
+ });
185
+ }
186
+ receive(raw) {
187
+ let message;
188
+ try {
189
+ message = JSON.parse(raw);
190
+ } catch {
191
+ return;
192
+ }
193
+ if (!message.id && message.type === "hello") {
194
+ this.tabInfo = message.payload ?? null;
195
+ return;
196
+ }
197
+ if (!message.id) return;
198
+ const pending = this.pending.get(message.id);
199
+ if (!pending) return;
200
+ clearTimeout(pending.timer);
201
+ this.pending.delete(message.id);
202
+ if (message.ok === false) {
203
+ pending.reject(messageError(message.error ?? {}));
204
+ return;
205
+ }
206
+ pending.resolve(message.result);
207
+ }
208
+ async handleHttp(req, res) {
209
+ if (req.method === "GET" && req.url === "/status") {
210
+ sendJson(res, 200, {
211
+ ok: true,
212
+ result: await this.rpc("status")
213
+ });
214
+ return;
215
+ }
216
+ if (req.method !== "POST" || req.url !== "/rpc") {
217
+ sendJson(res, 404, {
218
+ ok: false,
219
+ error: "Not found."
220
+ });
221
+ return;
222
+ }
223
+ if (req.headers.origin || !hasCliHeader(req)) {
224
+ sendJson(res, 403, {
225
+ ok: false,
226
+ error: "Bridge RPC is only available to local CLI clients."
227
+ });
228
+ return;
229
+ }
230
+ try {
231
+ const body = await readJson(req);
232
+ if (typeof body.type !== "string") {
233
+ sendJson(res, 400, {
234
+ ok: false,
235
+ error: "RPC request requires a string type."
236
+ });
237
+ return;
238
+ }
239
+ sendJson(res, 200, {
240
+ ok: true,
241
+ result: await this.rpc(body.type, body.payload ?? {})
242
+ });
243
+ } catch (error) {
244
+ sendJson(res, 500, {
245
+ ok: false,
246
+ error: error instanceof Error ? error.message : String(error)
247
+ });
248
+ }
249
+ }
250
+ };
251
+ function parseLiveBridgePort(value) {
252
+ if (value === void 0) return void 0;
253
+ const port = parsePort(value);
254
+ if (port === null) throw new LiveBridgeError("invalid-port", `Invalid port: ${value}`);
255
+ return port;
256
+ }
257
+ function createHttpBridgeTarget(port = DEFAULT_BRIDGE_PORT) {
258
+ const rpc = async (type, payload = {}) => {
259
+ const response = await fetch(`http://127.0.0.1:${port}/rpc`, {
260
+ method: "POST",
261
+ headers: {
262
+ "content-type": "application/json",
263
+ "x-mcut-bridge-client": "cli"
264
+ },
265
+ body: JSON.stringify({
266
+ type,
267
+ payload
268
+ })
269
+ });
270
+ const json = await response.json();
271
+ if (!response.ok || !json.ok) throw new LiveBridgeError("bridge-rpc-failed", json.error ?? `Bridge RPC failed (${response.status}).`);
272
+ return json.result;
273
+ };
274
+ return {
275
+ getSummary: async () => String(await rpc("get_summary")),
276
+ getProject: () => rpc("get_project"),
277
+ getMediaContext: () => rpc("get_media_context"),
278
+ getTranscript: (options) => rpc("get_transcript", options ?? {}),
279
+ searchTranscript: (query) => rpc("search_transcript", { query }),
280
+ ensureTranscript: (input) => rpc("ensure_transcript", input ?? {}),
281
+ listActions: () => rpc("list_actions"),
282
+ listOperators: () => rpc("list_operators"),
283
+ undo: async () => Boolean(await rpc("undo")),
284
+ redo: async () => Boolean(await rpc("redo")),
285
+ runAction: (actionId, input) => rpc("run_action", {
286
+ actionId,
287
+ input: input ?? {}
288
+ }),
289
+ runOperator: (operatorId, input) => rpc("run_operator", {
290
+ operatorId,
291
+ input: input ?? {}
292
+ }),
293
+ dispatchCommand: (commandName, input) => rpc("dispatch_command", {
294
+ commandName,
295
+ input: input ?? {}
296
+ })
297
+ };
298
+ }
299
+ //#endregion
300
+ export { parseLiveBridgePort as a, createHttpBridgeTarget as i, LiveBridgeError as n, LiveMcutBridge as r, DEFAULT_BRIDGE_PORT as t };
@@ -0,0 +1 @@
1
+ export { };
@@ -0,0 +1,75 @@
1
+ #!/usr/bin/env node
2
+ import { n as createMcutMcpServerForTarget } from "./server-DyDMot4v.js";
3
+ import { a as parseLiveBridgePort, r as LiveMcutBridge } from "./live-bridge-ky67GOTs.js";
4
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
+ //#region src/live-cli.ts
6
+ /**
7
+ * Live browser entry point:
8
+ *
9
+ * mcut-mcp-live [--port 54319] [--editor-url http://localhost:3000/editor]
10
+ *
11
+ * Starts an MCP server over stdio and a localhost WebSocket bridge. Open the
12
+ * printed editor URL so the browser tab becomes the source of truth.
13
+ */
14
+ function readArgs(argv) {
15
+ const args = { editorUrl: "http://localhost:3000/editor" };
16
+ for (let i = 0; i < argv.length; i++) {
17
+ const arg = argv[i];
18
+ if (arg === "--port") args.port = parseLiveBridgePort(argv[++i]);
19
+ else if (arg === "--token") args.token = argv[++i];
20
+ else if (arg === "--editor-url") args.editorUrl = argv[++i] ?? args.editorUrl;
21
+ else if (arg === "--help" || arg === "-h") {
22
+ console.error([
23
+ "Usage: mcut-mcp-live [--port 54319] [--editor-url http://localhost:3000/editor]",
24
+ "",
25
+ "Starts a stdio MCP server that forwards mcut tools to a live browser editor tab."
26
+ ].join("\n"));
27
+ process.exit(0);
28
+ }
29
+ }
30
+ return args;
31
+ }
32
+ function editorBridgeUrl(editorUrl, port, token) {
33
+ const url = new URL(editorUrl);
34
+ url.searchParams.set("mcpBridge", String(port));
35
+ url.searchParams.set("mcpToken", token);
36
+ return url.toString();
37
+ }
38
+ const args = readArgs(process.argv.slice(2));
39
+ const bridge = new LiveMcutBridge({ token: args.token });
40
+ const port = await bridge.listen(args.port);
41
+ console.error([
42
+ `mcut live MCP server ready — bridge: ws://127.0.0.1:${port}/mcut-mcp`,
43
+ `Open editor: ${editorBridgeUrl(args.editorUrl, port, bridge.token ?? "")}`,
44
+ "",
45
+ "MCP client config:",
46
+ JSON.stringify({ mcpServers: { "mcut-live": {
47
+ command: "bunx",
48
+ args: [
49
+ "-p",
50
+ "@mcut/mcp-server",
51
+ "mcut-mcp-live",
52
+ "--port",
53
+ String(port),
54
+ "--token",
55
+ bridge.token ?? "",
56
+ "--editor-url",
57
+ args.editorUrl
58
+ ]
59
+ } } }, null, 2)
60
+ ].join("\n"));
61
+ const server = createMcutMcpServerForTarget({
62
+ target: bridge.createTarget(),
63
+ name: "mcut-live"
64
+ });
65
+ process.on("SIGINT", () => {
66
+ bridge.close();
67
+ process.exit(130);
68
+ });
69
+ process.on("SIGTERM", () => {
70
+ bridge.close();
71
+ process.exit(143);
72
+ });
73
+ await server.connect(new StdioServerTransport());
74
+ //#endregion
75
+ export {};
@@ -0,0 +1,340 @@
1
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
+ import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
3
+ import { OperatorError, createEditorOperatorRegistry, registerCoreOperators } from "@mcut/editor";
4
+ import { CommandError, ProjectFormatError, getProjectCaptions, getProjectMediaContext, getProjectTranscript, listCommands, summarizeProject } from "@mcut/timeline";
5
+ import { searchCaptions } from "@mcut/transcription";
6
+ import { z } from "zod";
7
+ //#region src/server.ts
8
+ /**
9
+ * mcut as an MCP server: every registered editor command becomes an MCP tool,
10
+ * straight from the zod command registry — plus user-level operators from
11
+ * @mcut/editor and a handful of static tools (summary, project, undo/redo).
12
+ *
13
+ * The target can be a local EditorEngine or a live browser tab. Export stays
14
+ * in the browser (WebCodecs); MCP edits the project document/state.
15
+ */
16
+ const operatorToolName = (id) => `operator_${id.replace(/[^A-Za-z0-9_-]/g, "_")}`;
17
+ const toInputSchema = (schema) => z.toJSONSchema(schema, {
18
+ io: "input",
19
+ unrepresentable: "any"
20
+ });
21
+ const STATIC_TOOLS = [
22
+ {
23
+ name: "get_summary",
24
+ description: "A compact textual rendering of the current project: tracks (topmost first), elements with ids/timing/keyframes/effects/transitions, and assets. Read this before editing, then use get_media_context/get_transcript for video metadata and transcript details.",
25
+ inputSchema: {
26
+ type: "object",
27
+ properties: {},
28
+ additionalProperties: false
29
+ }
30
+ },
31
+ {
32
+ name: "get_project",
33
+ description: "The full project document as JSON (the serializable source of truth).",
34
+ inputSchema: {
35
+ type: "object",
36
+ properties: {},
37
+ additionalProperties: false
38
+ }
39
+ },
40
+ {
41
+ name: "get_media_context",
42
+ description: "Agent-friendly project/video metadata: project dimensions/fps/duration, playback, selection, assets, tracks, elements, clip source ranges, markers, and transcript availability. Use this before content-aware edits.",
43
+ inputSchema: {
44
+ type: "object",
45
+ properties: {},
46
+ additionalProperties: false
47
+ }
48
+ },
49
+ {
50
+ name: "get_transcript",
51
+ description: "Read the current transcript derived from caption elements. This never starts transcription. If no transcript exists and speech context is needed, call ensure_transcript in live bridge mode.",
52
+ inputSchema: {
53
+ type: "object",
54
+ properties: { includeWords: {
55
+ type: "boolean",
56
+ description: "Include absolute word timings for precise speech-boundary edits."
57
+ } },
58
+ additionalProperties: false
59
+ }
60
+ },
61
+ {
62
+ name: "search_transcript",
63
+ description: "Search the caption-derived transcript and return timeline times for matches. Use this to locate spoken words/phrases before cutting or annotating.",
64
+ inputSchema: {
65
+ type: "object",
66
+ properties: { query: { type: "string" } },
67
+ required: ["query"],
68
+ additionalProperties: false
69
+ }
70
+ },
71
+ {
72
+ name: "ensure_transcript",
73
+ description: "Live bridge only: if the target clip has no caption transcript, transcribe it with local Whisper in the connected browser, then apply word-timed captions to the timeline. Explicit tool only; get_transcript never auto-transcribes.",
74
+ inputSchema: {
75
+ type: "object",
76
+ properties: {
77
+ elementId: {
78
+ type: "string",
79
+ description: "Optional video/audio element id. Defaults to selected media, then first video, then first audio."
80
+ },
81
+ replace: {
82
+ type: "boolean",
83
+ description: "When true, replace captions overlapping the target clip. Defaults to false."
84
+ },
85
+ language: {
86
+ type: "string",
87
+ description: "Optional language hint for Whisper."
88
+ }
89
+ },
90
+ additionalProperties: false
91
+ }
92
+ },
93
+ {
94
+ name: "list_operators",
95
+ description: "List user-level editor operators available to agents. Prefer these for UI-parity actions; use raw command tools for low-level document edits.",
96
+ inputSchema: {
97
+ type: "object",
98
+ properties: {},
99
+ additionalProperties: false
100
+ }
101
+ },
102
+ {
103
+ name: "list_actions",
104
+ description: "List browser editor actions available in the live editor, including menu/palette/hotkey actions. Use this in live bridge mode when you need exact UI parity.",
105
+ inputSchema: {
106
+ type: "object",
107
+ properties: {},
108
+ additionalProperties: false
109
+ }
110
+ },
111
+ {
112
+ name: "run_action",
113
+ description: "Run a browser editor action by id in the live editor. These are the same actions used by menus, hotkeys, and the command palette.",
114
+ inputSchema: {
115
+ type: "object",
116
+ properties: {
117
+ actionId: { type: "string" },
118
+ input: {
119
+ type: "object",
120
+ additionalProperties: true
121
+ }
122
+ },
123
+ required: ["actionId"],
124
+ additionalProperties: false
125
+ }
126
+ },
127
+ {
128
+ name: "undo",
129
+ description: "Undo the most recent edit.",
130
+ inputSchema: {
131
+ type: "object",
132
+ properties: {},
133
+ additionalProperties: false
134
+ }
135
+ },
136
+ {
137
+ name: "redo",
138
+ description: "Redo the most recently undone edit.",
139
+ inputSchema: {
140
+ type: "object",
141
+ properties: {},
142
+ additionalProperties: false
143
+ }
144
+ }
145
+ ];
146
+ const text = (value) => ({ content: [{
147
+ type: "text",
148
+ text: value
149
+ }] });
150
+ const failure = (value) => ({
151
+ ...text(value),
152
+ isError: true
153
+ });
154
+ function viewState(engine) {
155
+ const playback = engine.playback.state;
156
+ const selection = engine.selection.elementIds;
157
+ return `Playhead: ${(playback.currentTimeMs / 1e3).toFixed(2)}s (${playback.isPlaying ? "playing" : "paused"}) · Selection: ${selection.length > 0 ? selection.join(", ") : "none"}`;
158
+ }
159
+ function summarizeEngine(engine) {
160
+ return `${summarizeProject(engine.project)}\n${viewState(engine)}`;
161
+ }
162
+ function transcriptOptions(args) {
163
+ return { includeWords: (args ?? {}).includeWords === true };
164
+ }
165
+ function transcriptQuery(args) {
166
+ const input = args ?? {};
167
+ const query = typeof input.query === "string" ? input.query.trim() : "";
168
+ return query.length > 0 ? query : null;
169
+ }
170
+ function searchProjectTranscript(project, query) {
171
+ const captionRefs = getProjectCaptions(project);
172
+ const captions = captionRefs.map((ref) => ref.caption);
173
+ const byId = new Map(captionRefs.map((ref) => [ref.caption.id, ref]));
174
+ const matches = searchCaptions(captions, query).map((match) => {
175
+ const ref = byId.get(match.captionId);
176
+ const text = ref?.caption.text ?? "";
177
+ return {
178
+ ...match,
179
+ text: text.slice(match.startChar, match.endChar),
180
+ captionText: text,
181
+ trackId: ref?.trackId,
182
+ trackName: ref?.trackName,
183
+ startMs: match.timeMs,
184
+ endMs: match.endTimeMs
185
+ };
186
+ });
187
+ return {
188
+ query,
189
+ count: matches.length,
190
+ matches
191
+ };
192
+ }
193
+ function createEngineTarget(engine, operators, onChange) {
194
+ return {
195
+ getSummary: () => summarizeEngine(engine),
196
+ getProject: () => engine.toJSON(),
197
+ getMediaContext: () => getProjectMediaContext(engine.project, {
198
+ playback: engine.playback.state,
199
+ selection: engine.selection
200
+ }),
201
+ getTranscript: (options) => getProjectTranscript(engine.project, options),
202
+ searchTranscript: (query) => searchProjectTranscript(engine.project, query),
203
+ ensureTranscript: async () => {
204
+ throw new Error("ensure_transcript requires a live browser bridge connected to an editor tab.");
205
+ },
206
+ listActions: () => [],
207
+ listOperators: () => operators.listAvailable({ engine }).map((operator) => ({
208
+ id: operator.id,
209
+ label: operator.label,
210
+ category: operator.category,
211
+ enabled: operator.enabled,
212
+ disabledReason: operator.disabledReason,
213
+ tool: operatorToolName(operator.id),
214
+ description: operator.description
215
+ })),
216
+ undo: async () => {
217
+ const applied = engine.undo();
218
+ if (applied) await onChange();
219
+ return applied;
220
+ },
221
+ redo: async () => {
222
+ const applied = engine.redo();
223
+ if (applied) await onChange();
224
+ return applied;
225
+ },
226
+ runAction: async (actionId) => {
227
+ throw new Error(`Browser action "${actionId}" is only available through a live browser bridge.`);
228
+ },
229
+ runOperator: async (operatorId, input) => {
230
+ const result = await operators.run(operatorId, { engine }, input ?? {});
231
+ await onChange();
232
+ return result;
233
+ },
234
+ dispatchCommand: async (commandName, input) => {
235
+ engine.dispatch({
236
+ type: commandName,
237
+ ...input ?? {}
238
+ });
239
+ await onChange();
240
+ }
241
+ };
242
+ }
243
+ /**
244
+ * Build the server around an existing engine. The caller owns the transport:
245
+ * `await createMcutMcpServer({ engine }).connect(new StdioServerTransport())`.
246
+ */
247
+ function createMcutMcpServer(options) {
248
+ const operators = options.operators ?? registerCoreOperators(createEditorOperatorRegistry());
249
+ return createMcutMcpServerForTarget({
250
+ target: createEngineTarget(options.engine, operators, options.onChange ?? (() => {})),
251
+ operators,
252
+ name: options.name,
253
+ version: options.version
254
+ });
255
+ }
256
+ /** Build the same MCP tool surface around any target, including a live browser tab. */
257
+ function createMcutMcpServerForTarget(options) {
258
+ const { target } = options;
259
+ const operators = options.operators ?? registerCoreOperators(createEditorOperatorRegistry());
260
+ const commandTools = listCommands().map((command) => ({
261
+ name: command.type,
262
+ description: command.description,
263
+ inputSchema: toInputSchema(command.payloadSchema)
264
+ }));
265
+ const operatorIdsByTool = /* @__PURE__ */ new Map();
266
+ const operatorTools = operators.list().map((operator) => {
267
+ const name = operatorToolName(operator.id);
268
+ operatorIdsByTool.set(name, operator.id);
269
+ return {
270
+ name,
271
+ description: `Editor operator "${operator.id}": ${operator.description}`,
272
+ inputSchema: toInputSchema(operator.inputSchema)
273
+ };
274
+ });
275
+ const server = new Server({
276
+ name: options.name ?? "mcut",
277
+ version: options.version ?? "0.1.0"
278
+ }, { capabilities: { tools: {} } });
279
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [
280
+ ...STATIC_TOOLS,
281
+ ...operatorTools,
282
+ ...commandTools
283
+ ] }));
284
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
285
+ const { name, arguments: args } = request.params;
286
+ try {
287
+ switch (name) {
288
+ case "get_summary": return text(await target.getSummary());
289
+ case "get_project": return text(JSON.stringify(await target.getProject(), null, 2));
290
+ case "get_media_context":
291
+ if (!target.getMediaContext) return failure("get_media_context is not available on this target.");
292
+ return text(JSON.stringify(await target.getMediaContext(), null, 2));
293
+ case "get_transcript":
294
+ if (!target.getTranscript) return failure("get_transcript is not available on this target.");
295
+ return text(JSON.stringify(await target.getTranscript(transcriptOptions(args)), null, 2));
296
+ case "search_transcript": {
297
+ if (!target.searchTranscript) return failure("search_transcript is not available on this target.");
298
+ const query = transcriptQuery(args);
299
+ if (!query) return failure("search_transcript requires a non-empty query string.");
300
+ return text(JSON.stringify(await target.searchTranscript(query), null, 2));
301
+ }
302
+ case "ensure_transcript": {
303
+ if (!target.ensureTranscript) return failure("ensure_transcript is not available on this target.");
304
+ const result = await target.ensureTranscript(args ?? {});
305
+ return text(`OK: transcript ensured.${result === void 0 ? "" : `\n\nResult:\n${JSON.stringify(result, null, 2)}`}\n\n${await target.getSummary()}`);
306
+ }
307
+ case "list_operators": return text(JSON.stringify(await target.listOperators(), null, 2));
308
+ case "list_actions": return text(JSON.stringify(await target.listActions(), null, 2));
309
+ case "run_action": {
310
+ const input = args ?? {};
311
+ if (typeof input.actionId !== "string") return failure("run_action requires an actionId string.");
312
+ const result = await target.runAction(input.actionId, input.input ?? {});
313
+ const suffix = result === void 0 ? "" : `\n\nResult:\n${JSON.stringify(result, null, 2)}`;
314
+ return text(`OK: action ${input.actionId} applied.${suffix}\n\n${await target.getSummary()}`);
315
+ }
316
+ case "undo":
317
+ if (!await target.undo()) return failure("Nothing to undo.");
318
+ return text(`Undone.\n\n${await target.getSummary()}`);
319
+ case "redo":
320
+ if (!await target.redo()) return failure("Nothing to redo.");
321
+ return text(`Redone.\n\n${await target.getSummary()}`);
322
+ default: {
323
+ const operatorId = operatorIdsByTool.get(name);
324
+ if (operatorId) {
325
+ const result = await target.runOperator(operatorId, args ?? {});
326
+ return text(`OK: operator ${operatorId} applied.${result === void 0 ? "" : `\n\nResult:\n${JSON.stringify(result, null, 2)}`}\n\n${await target.getSummary()}`);
327
+ }
328
+ await target.dispatchCommand(name, args ?? {});
329
+ return text(`OK: ${name} applied.\n\n${await target.getSummary()}`);
330
+ }
331
+ }
332
+ } catch (error) {
333
+ if (error instanceof CommandError || error instanceof ProjectFormatError || error instanceof OperatorError) return failure(`${error.name} (${error.code}): ${error.message}`);
334
+ return failure(error instanceof Error ? error.message : String(error));
335
+ }
336
+ });
337
+ return server;
338
+ }
339
+ //#endregion
340
+ export { createMcutMcpServerForTarget as n, operatorToolName as r, createMcutMcpServer as t };
package/package.json ADDED
@@ -0,0 +1,68 @@
1
+ {
2
+ "name": "@mcut/mcp-server",
3
+ "version": "0.1.0-alpha.0",
4
+ "description": "mcut as an MCP server: every editor command and operator becomes a tool any MCP client can call",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "bin": {
8
+ "mcut-bridge": "./dist/bridge-cli.js",
9
+ "mcut-mcp": "./dist/cli.js",
10
+ "mcut-mcp-live": "./dist/live-cli.js"
11
+ },
12
+ "main": "./dist/index.js",
13
+ "types": "./dist/index.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "import": "./dist/index.js"
18
+ }
19
+ },
20
+ "files": [
21
+ "dist"
22
+ ],
23
+ "sideEffects": false,
24
+ "scripts": {
25
+ "build": "tsdown",
26
+ "dev": "tsdown --watch --no-clean",
27
+ "typecheck": "tsc --noEmit",
28
+ "test": "bun test"
29
+ },
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "https://github.com/mattppal/mcut.git",
33
+ "directory": "packages/mcp-server"
34
+ },
35
+ "publishConfig": {
36
+ "access": "public",
37
+ "provenance": true
38
+ },
39
+ "dependencies": {
40
+ "@mcut/editor": "0.1.0-alpha.0",
41
+ "@mcut/timeline": "0.1.0-alpha.0",
42
+ "@mcut/transcription": "0.1.0-alpha.0",
43
+ "@modelcontextprotocol/sdk": "^1.21.0",
44
+ "ws": "8.18.3",
45
+ "zod": "4.4.3"
46
+ },
47
+ "devDependencies": {
48
+ "@types/ws": "8.18.1"
49
+ },
50
+ "author": "Matt Palmer",
51
+ "homepage": "https://github.com/mattppal/mcut/tree/main/packages/mcp-server#readme",
52
+ "bugs": {
53
+ "url": "https://github.com/mattppal/mcut/issues"
54
+ },
55
+ "keywords": [
56
+ "mcut",
57
+ "video",
58
+ "video-editing",
59
+ "timeline",
60
+ "typescript",
61
+ "mcp",
62
+ "model-context-protocol",
63
+ "agents"
64
+ ],
65
+ "engines": {
66
+ "node": ">=20.11"
67
+ }
68
+ }