Skip to content

The open-source full-stack studio for Opus 5.5 motion video. Reverse engineering for any video. Code video with HTML: recreate, edit and render. BYOA + BYOK · Motion.md · Images, Video, Music & Voice.

fix(mcp): diagnose stale runtime connections before export

罗高13c5bd9383f5
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index d8a9d77f..f5e73fb4 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -70,7 +70,7 @@ jobs:
npm run typecheck:studio
npm run build:studio
- name: Validate standalone installation and packaging
- run: node --experimental-strip-types --test tests/install.test.ts tests/npm-installer.test.ts tests/npm-package.test.ts tests/test-package.test.ts tests/source-install.test.ts tests/bootstrap.test.ts tests/mcp-registry.test.ts tests/phase1.test.ts tests/adapters.test.ts tests/package.test.ts tests/recreate-measure.test.ts tests/workflow.test.ts tests/catalog.test.ts tests/prism-templates.test.ts tests/extension-boundary.test.ts tests/connections.test.ts
+ run: node --experimental-strip-types --test tests/install.test.ts tests/npm-installer.test.ts tests/npm-package.test.ts tests/test-package.test.ts tests/source-install.test.ts tests/bootstrap.test.ts tests/mcp-registry.test.ts tests/mcp-runtime.test.ts tests/phase1.test.ts tests/adapters.test.ts tests/package.test.ts tests/recreate-measure.test.ts tests/workflow.test.ts tests/catalog.test.ts tests/prism-templates.test.ts tests/extension-boundary.test.ts tests/connections.test.ts
- name: Studio regression
run: npm run test:studio -- --maxWorkers=2
- name: Build phase-one ZIP and exercise all public tools
diff --git a/docs/shared-editor.md b/docs/shared-editor.md
index 11aebef4..c2de7936 100644
--- a/docs/shared-editor.md
+++ b/docs/shared-editor.md
@@ -37,7 +37,8 @@ flowchart LR
| 显式打开预览 | 按需启动或复用原生 Studio;返回已有完整/嵌入链接契约 |
| 全部 MCP 会话退出 | 后台继续服务网页与导出;不会因某个 Agent 退出取消其他人的工作 |
| 用户停止后台 | 私有停止接口拒绝正在执行的 MCP、视频导出或素材任务;空闲时关闭子服务并退出 |
-| 发现协议、版本或运行时代码不兼容 | 明确报错,请用户停止旧后台;不自动杀进程或另起一个后台 |
+| Runtime protocol/version/build mismatch | Refuse the call with expected/actual identity; reconnect a stale MCP client before considering an idle older backend shutdown. Never automatically kill or launch a competing backend. |
+| A live MCP client's plugin directory was replaced or removed | Return `MCP_RUNTIME_RELOAD_REQUIRED` with `applied: false` before dispatch; reload the host connection. |
| 同目录已有旧版预览服务 | 拒绝另外启动共享后台;退出旧服务后重试 |
macOS 使用系统 `/usr/bin/perl` 取得 `flock` 后直接 exec Node;Perl 不常驻。锁描述符同时由后台和 Studio 守卫持有。后台死亡后,守卫先清理旧 Studio,再释放锁,新后台才能启动。锁文件保留不等于锁仍被占用;不通过删除锁文件来恢复。
diff --git a/editor-runtime.ts b/editor-runtime.ts
index 1480a18c..6517799d 100644
--- a/editor-runtime.ts
+++ b/editor-runtime.ts
@@ -53,7 +53,13 @@ export async function ensureEditor(directory: string): Promise<EditorRegistry> {
try {
const health = await editorRequest(registry, '/editor-api/health', undefined, 1200);
if (health.service !== service || health.dataDirectory !== data || health.instanceId !== registry.instanceId) throw Object.assign(new Error('编辑器实例身份不匹配'), { terminal: true });
- if (health.protocol !== protocol || health.version !== version || health.build !== editorBuild) throw Object.assign(new Error('编辑器协议或代码版本不兼容;请先停止旧后台后重试'), { terminal: true });
+ if (health.protocol !== protocol || health.version !== version || health.build !== editorBuild) throw Object.assign(
+ new Error('Editor runtime incompatible. Reconnect the Motion MCP connection to the installed runtime and compare the expected and actual versions/builds. Stop an older editor only after confirming it is idle; do not bypass MCP or switch workspaces to continue.'),
+ { terminal: true, code: 'EDITOR_RUNTIME_INCOMPATIBLE', details: {
+ dataDirectory: data, expected: { protocol, version, build: editorBuild },
+ actual: { protocol: health.protocol, version: health.version, build: health.build },
+ } },
+ );
return registry;
} catch (error) { if ((error as any).terminal || (error as any).status) throw error; }
}
diff --git a/mcp.ts b/mcp.ts
index f47beca3..17443757 100644
--- a/mcp.ts
+++ b/mcp.ts
@@ -1,4 +1,6 @@
import { createInterface } from 'node:readline';
+import { statSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
import { WorkspaceStore } from './workspace.ts';
import { ensureService, VERSION } from './preview.ts';
import { tools, callTool } from './mcp-tools.ts';
@@ -14,6 +16,8 @@ export function mcpRegistry(profile = releaseProfile) { return createToolRegistr
export const releaseRegistry = mcpRegistry();
export const publicTools = releaseRegistry.tools;
const selections = new WeakMap<WorkspaceStore, { sessionId: string; projectId: string }>();
+const runtimeRoot = fileURLToPath(new URL('./', import.meta.url));
+const runtimeDirectory = statSync(runtimeRoot);
export async function rpc(message: any, store = new WorkspaceStore(), registry = releaseRegistry, connection?: { selection: Selection }) {
if (!message || message.jsonrpc !== '2.0' || typeof message.method !== 'string') return { jsonrpc: '2.0', id: message?.id ?? null, error: { code: -32600, message: 'Invalid request' } };
@@ -29,6 +33,11 @@ export async function rpc(message: any, store = new WorkspaceStore(), registry =
if (message.method === 'tools/list') return result({ tools: registry.tools });
if (message.method === 'tools/call') {
try {
+ const current = statSync(runtimeRoot, { throwIfNoEntry: false });
+ if (!current || current.dev !== runtimeDirectory.dev || current.ino !== runtimeDirectory.ino) throw Object.assign(
+ new Error('The Motion plugin directory was replaced or removed. Reload the Motion MCP connection in the host before retrying; no project operation was applied.'),
+ { code: 'MCP_RUNTIME_RELOAD_REQUIRED' },
+ );
if (!registry.tools.some(tool => tool.name === message.params?.name)) throw new Error('MCP_TOOL_NOT_EXPOSED: ' + String(message.params?.name));
if (registry.profile === 'phase1') {
const name = message.params.name;
@@ -55,8 +64,10 @@ export async function rpc(message: any, store = new WorkspaceStore(), registry =
} catch (error) {
const message = error instanceof Error ? error.message : 'Tool failed';
const code = (error as any).code || /^([A-Z][A-Z_]+):?/.exec(message)?.[1] || 'TOOL_FAILED';
+ const runtimeFailure = ['MCP_RUNTIME_RELOAD_REQUIRED', 'EDITOR_RUNTIME_INCOMPATIBLE'].includes(code);
return result({ isError: true, content: [{ type: 'text', text: message }], structuredContent: { error: { code, message,
- applied: /^(INVALID_|VERSION_CONFLICT|PROJECT_NOT_|PROJECT_SESSION_|REQUEST_ID_CONFLICT|MCP_TOOL_NOT_EXPOSED|EXPORT_NOT_|TEMPLATE_NOT_)/.test(code) ? false : 'unknown' } } });
+ ...(runtimeFailure && (error as any).details ? { details: (error as any).details } : {}),
+ applied: runtimeFailure || /^(INVALID_|VERSION_CONFLICT|PROJECT_NOT_|PROJECT_SESSION_|REQUEST_ID_CONFLICT|MCP_TOOL_NOT_EXPOSED|EXPORT_NOT_|TEMPLATE_NOT_)/.test(code) ? false : 'unknown' } } });
}
}
return { jsonrpc: '2.0', id: message.id, error: { code: -32601, message: 'Method not found' } };
diff --git a/shared/mcp-profiles.json b/shared/mcp-profiles.json
index 2b3ffd8a..20ae8ccd 100644
--- a/shared/mcp-profiles.json
+++ b/shared/mcp-profiles.json
@@ -17,6 +17,6 @@
"motion_restore_version",
"motion_export_cancel"
],
- "instructions": "Use only the tools returned by tools/list. Follow the installed phase-one production skills. Read the selected project and current content version before editing. Save native source through motion_edit_project; preview and export perform their required checks internally. Use motion_list_versions to find project snapshots and motion_restore_version to restore one as a new version while retaining later history. A transport cancellation does not prove a background export stopped. Report actual export state and accessible results; technical validation does not replace visual, audio and player review. Never guess a project from another conversation. Read skills locally or with resources/list and resources/read (motion://workflow/production/start, or the selected specialist); engine authoring guidance is motion://engine/SKILL.md and relative Markdown references under motion://engine/. For new work create explicitly; motion_open_preview never silently creates a project. Persisted create/import/edit/restore/export/cancel and review requests require a stable requestId; preview action=open does not. Edits require projectId, expectedRevision and expectedVersionId. Query export progress through motion_get_project with projectId and exportJobId. Project list and version list are five per page; follow nextCursor. For template discovery, call motion_list_templates to obtain a local JSONL index path, then search that file with local tools. It does not return search results. Read the selected ID with motion_get_template; create its independent editable copy with motion_create_project projectType=template."
+ "instructions": "Use only the tools returned by tools/list. Follow the installed phase-one production skills. Read the selected project and current content version before editing. Save native source through motion_edit_project; preview and export perform their required checks internally. Use motion_list_versions to find project snapshots and motion_restore_version to restore one as a new version while retaining later history. A transport cancellation does not prove a background export stopped. Report actual export state and accessible results; technical validation does not replace visual, audio and player review. Never guess a project from another conversation. Read skills locally or with resources/list and resources/read (motion://workflow/production/start, or the selected specialist); engine authoring guidance is motion://engine/SKILL.md and relative Markdown references under motion://engine/. For new work create explicitly; motion_open_preview never silently creates a project. Persisted create/import/edit/restore/export/cancel and review requests require a stable requestId; preview action=open does not. Edits require projectId, expectedRevision and expectedVersionId. Query export progress through motion_get_project with projectId and exportJobId. Project list and version list are five per page; follow nextCursor. For template discovery, call motion_list_templates to obtain a local JSONL index path, then search that file with local tools. It does not return search results. Read the selected ID with motion_get_template; create its independent editable copy with motion_create_project projectType=template. Use the connected Motion MCP tools for project operations and exports; a shell HTTP call is not an MCP tool invocation. Before opening a project, verify the connection dataDirectory and project/version with motion_get_project. Browser URLs and project IDs do not select another workspace. If the transport is closed, the runtime was replaced or compatibility fails, reload the matching MCP connection and repeat the read; do not silently bypass MCP or change workspaces."
}
}
diff --git a/skills/motion-production/references/production.md b/skills/motion-production/references/production.md
index f870c25c..07ee02ae 100644
--- a/skills/motion-production/references/production.md
+++ b/skills/motion-production/references/production.md
@@ -1,6 +1,6 @@
# Motion runtime adapter · phase one
-Use the nine Tools actually returned by tools/list. Read [Native authoring](native.md) and the pinned engine guide before authoring. Keep one native project and one renderer; creative code is authored by the host Agent.
+Use only the Motion MCP Tools actually returned by tools/list. Read [Native authoring](native.md) and the pinned engine guide before authoring. Keep one native project and one renderer; creative code is authored by the host Agent.
| Responsibility | Public Tool / supported scope |
| --- | --- |
@@ -15,6 +15,14 @@ Use the nine Tools actually returned by tools/list. Read [Native authoring](nati
## Execution
+### Tool transport and workspace readiness
+
+Use the host's connected Motion MCP tools for project creation, reads, saves, previews, export requests and status checks. A shell HTTP request carrying the same tool name reaches shared business code but is not a host MCP tool invocation; report that distinction and its reason explicitly when a development fallback is necessary.
+
+Before opening a project for an Agent workflow, call `motion_get_project` through that connection and verify its `dataDirectory`, project/session identity and current version. Create new work through `motion_create_project`, then save and open the returned project through MCP. A browser URL or a matching project ID alone does not bind the connection to that workspace. A repository-only UI fixture can remain isolated, but must be identified as such; exporting it through MCP requires a matching connection or an explicitly scoped project import/copy, not an implicit data-directory change.
+
+For `MCP_RUNTIME_RELOAD_REQUIRED`, `EDITOR_RUNTIME_INCOMPATIBLE` or a closed transport, repair/reload the host connection and repeat the scoped read before writing. Compare the reported expected and actual version/build; a stale connection can disagree with a healthy current backend. Do not stop a matching backend or silently substitute shell/HTTP exports for failed MCP calls. Preserve existing projects and completed jobs, and query an applicable export before creating another.
+
1. Reuse complete guidance already read. Installed Skills and MCP resources/read provide the same documents; production start only routes a task that lacks a specialist. Changes to existing content use [edit workflow](edit.md). Missing instructions/source reads return to the model before dependent writes.
2. Reuse the target projectId or explicitly create a new one. Read its current revision and content version. No global most-recent project fallback. Five is a list page size, not a retention policy.
3. Use returned asset paths and native HTML/CSS/JS. Import and file save are separate operations. Images/footage/music generation belongs to the host's available tools or Studio; no generation Tool is exposed by this phase-one MCP package. Missing media capabilities must be stated.
diff --git a/tests/mcp-runtime.test.ts b/tests/mcp-runtime.test.ts
new file mode 100644
index 00000000..a72f2ccf
--- /dev/null
+++ b/tests/mcp-runtime.test.ts
@@ -0,0 +1,78 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createServer } from 'node:http';
+import { cp, mkdir, mkdtemp, readFile, readdir, rename, rm, symlink, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+import { tmpdir } from 'node:os';
+import { pathToFileURL } from 'node:url';
+import { editorBuild, editorDirectory, sharedEditorEnabled } from '../editor-runtime.ts';
+import { pluginRoot } from '../hyperframes.ts';
+import { rpc } from '../mcp.ts';
+import { WorkspaceStore } from '../workspace.ts';
+
+async function incompatibleEditor(directory: string, changed: Record<string, unknown>) {
+ const { data, runtime } = await editorDirectory(directory);
+ const requests: string[] = [];
+ const registry = { service: 'opendesign-editor', protocol: 1, version: JSON.parse(await readFile(path.join(pluginRoot, 'package.json'), 'utf8')).version,
+ build: editorBuild, dataDirectory: data, instanceId: 'test-instance', pid: process.pid, token: 'a'.repeat(64), endpoint: '' };
+ const health = { ...registry, ...changed, token: undefined };
+ const server = createServer((req, res) => {
+ requests.push(req.url!);
+ res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(health));
+ });
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
+ registry.endpoint = `http://127.0.0.1:${(server.address() as any).port}/`;
+ await writeFile(path.join(runtime, 'runtime.json'), JSON.stringify(registry), { mode: 0o600 });
+ return { requests, health, registry, close: async () => {
+ server.closeAllConnections(); await new Promise<void>(resolve => server.close(() => resolve()));
+ } };
+}
+
+const exportCall = { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'motion_export_request', arguments: {
+ projectId: 'project', requestId: 'must-not-export', expectedRevision: '0'.repeat(64), versionId: 'unavailable', audio: 'silent',
+} } };
+
+test('MCP reports incompatible editor identity fields without starting an export or exposing credentials', { skip: !sharedEditorEnabled }, async t => {
+ for (const changed of [{ protocol: 999 }, { version: '0.0.0' }, { build: '0'.repeat(64) }]) await t.test(Object.keys(changed)[0], async () => {
+ const directory = await mkdtemp(path.join(tmpdir(), 'motion-runtime-mismatch-'));
+ const editor = await incompatibleEditor(directory, changed);
+ try {
+ const response: any = await rpc(exportCall, new WorkspaceStore(directory));
+ const error = response.result.structuredContent.error;
+ assert.equal(error.code, 'EDITOR_RUNTIME_INCOMPATIBLE');
+ assert.equal(error.applied, false);
+ assert.deepEqual(error.details.expected, { protocol: 1, version: editor.registry.version, build: editorBuild });
+ assert.deepEqual(error.details.actual, { protocol: editor.health.protocol, version: editor.health.version, build: editor.health.build });
+ assert.match(error.message, /Reconnect.*MCP/i);
+ assert.ok(!JSON.stringify(response).includes(editor.registry.token));
+ assert.deepEqual(editor.requests, ['/editor-api/health']);
+ assert.deepEqual(await readdir(directory), ['.editor-runtime']);
+ assert.deepEqual(await readdir(path.join(directory, '.editor-runtime')), ['runtime.json']);
+ } finally { await editor.close(); await rm(directory, { recursive: true, force: true }); }
+ });
+});
+
+test('a replaced or removed plugin directory tells a live stdio MCP client to reload before dispatch', async t => {
+ for (const replaced of [true, false]) await t.test(replaced ? 'replaced' : 'removed', async () => {
+ const temporary = await mkdtemp(path.join(tmpdir(), 'motion-stale-plugin-'));
+ const app = path.join(temporary, 'app'), directory = path.join(temporary, 'data');
+ await cp(pluginRoot, app, { recursive: true, filter: source => !['.git', 'node_modules', 'studio', 'dist', '.artifacts'].includes(path.relative(pluginRoot, source).split(path.sep)[0]) });
+ await symlink(path.join(pluginRoot, 'node_modules'), path.join(app, 'node_modules'), 'dir');
+ const editor = await incompatibleEditor(directory, { protocol: 999 });
+ const { Client } = await import(pathToFileURL(path.join(app, 'tests/shared-editor-client.mjs')).href);
+ const client = new Client(directory);
+ try {
+ await client.initialize();
+ await rename(app, path.join(temporary, 'previous'));
+ if (replaced) await mkdir(app);
+ for (const params of [{ name: 'motion_get_project', arguments: {} }, exportCall.params]) {
+ const response = await client.rpc('tools/call', params);
+ assert.equal(response.structuredContent.error.code, 'MCP_RUNTIME_RELOAD_REQUIRED');
+ assert.equal(response.structuredContent.error.applied, false);
+ assert.match(response.structuredContent.error.message, /reload/i);
+ }
+ assert.deepEqual(editor.requests, []);
+ assert.deepEqual(await readdir(directory), ['.editor-runtime']);
+ } finally { await client.close(); await editor.close(); await rm(temporary, { recursive: true, force: true }); }
+ });
+});
diff --git a/tests/shared-editor.test.ts b/tests/shared-editor.test.ts
index 23fe928c..dc2f7c3b 100644
--- a/tests/shared-editor.test.ts
+++ b/tests/shared-editor.test.ts
@@ -134,7 +134,7 @@ test('production stdio connections use one authority and keep project identity',
await new Promise<void>(resolve => fake.listen(0, '127.0.0.1', resolve));
try {
await writeFile(path.join(directory, '.editor-runtime/runtime.json'), JSON.stringify({ ...registry, endpoint: `http://127.0.0.1:${(fake.address() as any).port}/` }));
- await assert.rejects(ensureEditor(directory), /不兼容/);
+ await assert.rejects(ensureEditor(directory), { code: 'EDITOR_RUNTIME_INCOMPATIBLE' });
assert.equal((await readFile(path.join(directory, '.editor-runtime/starts.jsonl'), 'utf8')).trim().split('\n').length, 2);
} finally {
await writeFile(path.join(directory, '.editor-runtime/runtime.json'), JSON.stringify(registry));