Skip to content

The VS Code of video editing, built for agents.

TypeScript

Refactor MCP integration and update dependencies

konstantin-paulus7a95fada7a34
diff --git a/README.md b/README.md
index 3e55eee6..c48a9fcd 100644
--- a/README.md
+++ b/README.md
@@ -217,7 +217,7 @@ Conventions throughout: every result is one JSON object, the same structured con
| --- | --- | --- |
| `apps/web` | `@diffusionstudio/web` | The editor UI (Solid + Vite) |
| `apps/desktop` | `@diffusionstudio/desktop` | Electron shell hosting the editor |
-| `apps/cli` | `@diffusionstudio/cli` | The `dapi` CLI: a client of the app's MCP server, plus the `dapi mcp` stdio proxy |
+| `apps/cli` | `@diffusionstudio/cli` | The `dapi` CLI: a client of the app's MCP server |
| `packages/runtime` | `@diffusionstudio/runtime` | Headless editor runtime: the koota world, traits, actions, systems, media decoding, capture. No DOM, no Solid |
| `packages/reconciler` | `@diffusionstudio/reconciler` | Evaluates a compiled project bundle and reconciles its element tree onto runtime entities, via Solid's universal renderer |
| `packages/jsx` | `@diffusionstudio/jsx` | The authoring API: element vocabulary, types, and generated assets (`generate.*`) |
diff --git a/apps/cli/src/cli-client.ts b/apps/cli/src/cli-client.ts
index 48a311d3..ceab127e 100644
--- a/apps/cli/src/cli-client.ts
+++ b/apps/cli/src/cli-client.ts
@@ -3,12 +3,11 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import { execFile } from "node:child_process";
-import { connect } from "node:net";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
-import { SOCKET_PATH, SocketTransport } from "@diffusionstudio/dapi/socket";
+import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
+import { MCP_URL } from "@diffusionstudio/dapi";
import { version } from "../../../package.json";
-import type { Socket } from "node:net";
import type { ToolInput, ToolName, ToolOutput } from "@diffusionstudio/dapi";
export const APP_NAME = "Diffusion Studio";
@@ -23,15 +22,15 @@ const TIMEOUTS: Record<string, number> = {
};
/**
- * Calls one tool in the running app over an MCP session on its socket.
- * Typed by the catalog: the input is what the tool's schema accepts, the
- * output its structured content. One session per call; a command makes one
- * or two, and the process exits when it settles.
+ * Calls one tool in the running app over an MCP session on its HTTP
+ * endpoint — the same URL agents register. Typed by the catalog: the input is
+ * what the tool's schema accepts, the output its structured content. One
+ * session per call; a command makes one or two, and the process exits when
+ * it settles.
*/
export async function call<N extends ToolName>(name: N, input: ToolInput<N>): Promise<ToolOutput<N>> {
- const client = new Client({ name: "dapi", version });
+ const client = await connect();
try {
- await client.connect(new SocketTransport(await openSocket()));
const result = await client.callTool({ name, arguments: input as Record<string, unknown> }, undefined, {
timeout: TIMEOUTS[name] ?? 60_000,
});
@@ -50,37 +49,39 @@ export async function call<N extends ToolName>(name: N, input: ToolInput<N>): Pr
/** Liveness: a round-trip through the app's MCP server. */
export async function ping(): Promise<void> {
- const client = new Client({ name: "dapi", version });
+ const client = await connect();
try {
- await client.connect(new SocketTransport(await openSocket()));
await client.ping();
} finally {
await client.close().catch(() => {});
}
}
-// Connecting is where "the app is not running" shows up, as ENOENT (no
-// socket file) or ECONNREFUSED (a stale one); see `isAppDown`.
-export function openSocket(): Promise<Socket> {
- return new Promise((resolve, reject) => {
- const socket = connect(SOCKET_PATH);
- socket.once("connect", () => {
- socket.off("error", reject);
- resolve(socket);
- });
- socket.once("error", reject);
- });
+// Connecting is where "the app is not running" shows up: the `initialize`
+// request's fetch is refused, see `isAppDown`.
+async function connect(): Promise<Client> {
+ const client = new Client({ name: "dapi", version });
+ await client.connect(new StreamableHTTPClientTransport(new URL(MCP_URL)));
+ return client;
}
+/**
+ * Nothing is listening on the app's port. Node's fetch reports that as a
+ * `fetch failed` TypeError whose cause carries the errno, so the chain of
+ * causes is searched.
+ */
export function isAppDown(e: unknown): boolean {
- const code = (e as NodeJS.ErrnoException | undefined)?.code;
- return code === "ENOENT" || code === "ECONNREFUSED";
+ for (let error = e, depth = 0; error && depth < 5; error = (error as { cause?: unknown }).cause, depth++) {
+ const code = (error as NodeJS.ErrnoException).code;
+ if (code === "ECONNREFUSED" || code === "ECONNRESET") return true;
+ }
+ return false;
}
/**
* Launches the app, or surfaces the running instance: `open -a` on a running
* app only activates it, so this is safe to always run. macOS only; elsewhere
- * it resolves false and the caller falls through to the socket.
+ * it resolves false and the caller falls through to the connection.
*/
export function launchApp(background: boolean): Promise<boolean> {
if (process.platform !== "darwin") return Promise.resolve(false);
@@ -90,8 +91,7 @@ export function launchApp(background: boolean): Promise<boolean> {
/**
* Bridges the cold-start gap after launching the app: retries while the app
- * looks down, until it answers a ping (a cold app binds the socket before
- * its session is ready, so connecting alone proves nothing).
+ * looks down, until it answers a ping.
*/
export async function waitForApp(timeoutMs = 30000): Promise<void> {
const start = Date.now();
diff --git a/apps/cli/src/index.ts b/apps/cli/src/index.ts
index 7eb5e5f7..5bd43480 100644
--- a/apps/cli/src/index.ts
+++ b/apps/cli/src/index.ts
@@ -8,10 +8,8 @@ import { isAbsolute, resolve } from "node:path";
import { Command } from "commander";
import { z } from "zod";
import { version } from "../../../package.json";
-import { toolByName } from "@diffusionstudio/dapi";
-import { MCP_URL } from "@diffusionstudio/dapi/socket";
+import { MCP_URL, toolByName } from "@diffusionstudio/dapi";
import { APP_NAME, call, isAppDown, launchApp, ping, waitForApp } from "./cli-client";
-import { runProxy } from "./mcp-proxy";
import type { GenericTool, ToolInput, ToolName } from "@diffusionstudio/dapi";
@@ -74,19 +72,9 @@ program
.description(
`The Diffusion Studio CLI: understand, generate, and edit footage.
Analyze video/audio/images, generate them with AI, and compose assets.
-Use for any media analysis, media generation, or video editing task. No ffmpeg needed.
-
-Every command wraps one tool of the running app's MCP server, which agents reach at ${MCP_URL} once the app runs (\`dapi open\`).`,
- )
+Use for any media analysis, media generation, or video editing task. No ffmpeg needed.`)
.version(version);
-program
- .command("mcp")
- .description(
- `Serve the app's MCP server on stdio, for agents that cannot connect over HTTP (Claude Desktop). Every other agent should register the URL ${MCP_URL} instead, which the running app serves — \`dapi open\` starts it. Register this with \`claude mcp add dapi -- dapi mcp\` (or the equivalent entry in the agent's MCP config) and the agent gets every command below as a tool, with the same descriptions. Launches ${APP_NAME} in the background if it is not running (macOS).`,
- )
- .action(() => runProxy().catch((e: Error) => fail(e.message)));
-
program
.command("open")
.description(
diff --git a/apps/cli/src/mcp-proxy.ts b/apps/cli/src/mcp-proxy.ts
deleted file mode 100644
index 92d99c68..00000000
--- a/apps/cli/src/mcp-proxy.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// `dapi mcp`: the entry point agents register. A byte pipe between stdio and
-// the app's socket — the socket already carries MCP in stdio framing, so
-// nothing here parses a message, and any app version works with any proxy
-// version. Stdout belongs to the protocol; anything for a human goes to
-// stderr.
-
-import { APP_NAME, isAppDown, launchApp, openSocket, waitForApp } from "./cli-client";
-
-import type { Socket } from "node:net";
-
-export async function runProxy(): Promise<void> {
- let socket: Socket;
- try {
- socket = await openSocket();
- } catch (e) {
- if (!isAppDown(e)) throw e;
- // Launching is macOS's job; elsewhere the user starts the app by hand.
- if (!(await launchApp(true))) {
- throw new Error(`${APP_NAME} is not running. Launch the app first, then retry.`);
- }
- await waitForApp();
- socket = await openSocket();
- }
-
- socket.on("error", (error) => {
- console.error(`[dapi mcp] ${error.message}`);
- process.exit(1);
- });
- // The app went away (quit, or the session was closed): the agent sees EOF.
- socket.on("close", () => process.exit(0));
- // The agent went away: tell the app, which ends the session.
- process.stdin.on("end", () => socket.end());
- process.stdout.on("error", () => socket.destroy());
-
- process.stdin.pipe(socket);
- socket.pipe(process.stdout);
-}
diff --git a/apps/desktop/src/dapi/server.ts b/apps/desktop/src/dapi/server.ts
index d7035768..eb0e51e9 100644
--- a/apps/desktop/src/dapi/server.ts
+++ b/apps/desktop/src/dapi/server.ts
@@ -2,18 +2,14 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-import { chmodSync, existsSync, unlinkSync } from "node:fs";
-import { createServer } from "node:net";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
-import { tools } from "@diffusionstudio/dapi";
-import { MCP_HOST, MCP_PATH, MCP_PORT, SOCKET_PATH, SocketTransport } from "@diffusionstudio/dapi/socket";
+import { MCP_HOST, MCP_PATH, MCP_PORT, tools } from "@diffusionstudio/dapi";
import { mainHandlers } from "./handlers";
import { DapiHttpServer } from "./http";
import { instructions, registerPrompts } from "./docs";
import { present, toCallToolResult, toErrorResult } from "./present";
import { RendererCalls } from "./renderer-calls";
-import type { Server, Socket } from "node:net";
import type { GenericTool, LogEntry, ToolName } from "@diffusionstudio/dapi";
import type { MainContext, MainToolName } from "./handler";
@@ -35,20 +31,16 @@ export type DapiServerDeps = {
};
/**
- * The app's MCP server, on two transports over one catalog: Streamable HTTP
- * on a fixed loopback port, which agents register by URL, and the local
- * socket the `dapi` CLI uses (and `dapi mcp` proxies for agents that only
- * speak stdio). Each connection gets its own MCP session. Main-process tools
- * run here; renderer tools are forwarded over IPC and their results
- * presented (files written, small images inlined) before they go back out.
+ * The app's MCP server: Streamable HTTP on a fixed loopback port, the URL
+ * agents register and the `dapi` CLI calls. Each client gets its own MCP
+ * session over one catalog. Main-process tools run here; renderer tools are
+ * forwarded over IPC and their results presented (files written, small
+ * images inlined) before they go back out.
*/
export class DapiServer {
private readonly deps: DapiServerDeps;
private readonly renderer = new RendererCalls();
- private readonly sessions = new Set<McpServer>();
private readonly http: DapiHttpServer;
- private server: Server | null = null;
- private connected = false;
private instructionsText: string | null = null;
private httpReady: Promise<boolean> = Promise.resolve(false);
@@ -64,7 +56,7 @@ export class DapiServer {
port: MCP_PORT,
path: MCP_PATH,
createSession: () => this.createSession(),
- onFirstConnection: () => this.firstConnection(),
+ onFirstConnection: () => deps.onFirstConnection(),
});
}
@@ -74,16 +66,9 @@ export class DapiServer {
}
start(): void {
- removeStaleSocket();
this.renderer.start();
- this.server = createServer((socket) => void this.accept(socket));
- this.server.on("error", (error) => console.error("[dapi] server error:", error));
- this.server.listen(SOCKET_PATH, () => {
- // Linux shares /tmp between users; the socket file's mode is the auth.
- if (process.platform !== "win32") chmodSync(SOCKET_PATH, 0o600);
- });
- // A taken port is the one way this fails; the socket keeps the CLI and
- // `dapi mcp` working meanwhile, so it is logged, not fatal.
+ // A taken port is the one way this fails. The app is still usable
+ // without agents, so it is logged, not fatal; `mcpUrl()` says so.
this.httpReady = this.http.start().then(
() => true,
(error: Error) => {
@@ -100,31 +85,6 @@ export class DapiServer {
stop(): void {
this.http.stop();
- for (const session of this.sessions) void session.close();
- this.sessions.clear();
- this.server?.close();
- this.server = null;
- removeStaleSocket();
- }
-
- private firstConnection(): void {
- if (this.connected) return;
- this.connected = true;
- this.deps.onFirstConnection();
- }
-
- private async accept(socket: Socket): Promise<void> {
- this.firstConnection();
- const session = this.createSession();
- this.sessions.add(session);
- session.server.onclose = () => this.sessions.delete(session);
- try {
- await session.connect(new SocketTransport(socket));
- } catch (error) {
- console.error("[dapi] session failed to start:", error);
- this.sessions.delete(session);
- socket.destroy();
- }
}
/** One MCP server over the whole catalog, plus the skills as prompts. The docs are plain files; the instructions say where. */
@@ -163,15 +123,3 @@ export class DapiServer {
return (mainHandlers[name] as (args: unknown, ctx: MainContext) => Promise<unknown>)(args, ctx);
}
}
-
-/**
- * A socket file left by a previous run (Unix). Safe to remove because the
- * single-instance lock guarantees no other instance of ours is running.
- */
-function removeStaleSocket(): void {
- try {
- if (process.platform !== "win32" && existsSync(SOCKET_PATH)) unlinkSync(SOCKET_PATH);
- } catch {
- // Best-effort.
- }
-}
diff --git a/apps/desktop/src/projects.ts b/apps/desktop/src/projects.ts
index 05991a18..ba96c2ff 100644
--- a/apps/desktop/src/projects.ts
+++ b/apps/desktop/src/projects.ts
@@ -9,7 +9,7 @@ import { cp, mkdir, readdir, readFile, realpath, rename, rm, stat, writeFile } f
import { createRequire } from "node:module";
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
import { nanoid } from "nanoid";
-import { MCP_URL } from "@diffusionstudio/dapi/socket";
+import { MCP_URL } from "@diffusionstudio/dapi";
import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
import type { PluginItem, TransformOptions } from "@babel/core";
diff --git a/docs/reference/tools/README.md b/docs/reference/tools/README.md
index efa000f1..dc2ffd9f 100644
--- a/docs/reference/tools/README.md
+++ b/docs/reference/tools/README.md
@@ -2,7 +2,7 @@
Diffusion Studio exposes one set of tools, reachable two ways:
-- **MCP.** The running app serves an MCP server at `http://127.0.0.1:3274/mcp` (Streamable HTTP) and on a local socket; `dapi mcp` pipes that socket to stdio for clients that only spawn processes. A connected agent gets every tool in `tools/list`, with the descriptions on these pages, and instructions that give the path of these docs in the installed app.
+- **MCP.** The running app serves an MCP server at `http://127.0.0.1:3274/mcp` (Streamable HTTP). A connected agent gets every tool in `tools/list`, with the descriptions on these pages, and instructions that give the path of these docs in the installed app. A client that can only spawn a stdio server can bridge to the URL with a generic proxy such as `mcp-remote`.
- **CLI.** `dapi`, the command-line client shipped with the app, wraps every tool as a command for shells, scripts and CI. `dapi <command> --help` prints the same description and the same field help.
Both validate against the same schemas and return the same result, so each tool is documented once, on its own page. The catalog behind all three (server, CLI, these pages) lives in `packages/dapi`.
diff --git a/package-lock.json b/package-lock.json
index 66359ad4..135e2e74 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -13924,7 +13924,6 @@
"license": "MPL-2.0",
"dependencies": {
"@diffusionstudio/jsx": "*",
- "@modelcontextprotocol/sdk": "^1.30.0",
"zod": "^4.4.3"
},
"devDependencies": {
diff --git a/packages/dapi/README.md b/packages/dapi/README.md
index 207f8dd9..dc1ece32 100644
--- a/packages/dapi/README.md
+++ b/packages/dapi/README.md
@@ -10,6 +10,6 @@ const grab = toolByName("media_grab");
const args: ToolArgs<"media_grab"> = grab.input.parse({ path: "/clip.mp4", times: ["45f", "1:10"] });
```
-The main export is free of Node built-ins so the renderer can import it. `@diffusionstudio/dapi/socket` exports the socket path and pulls in `node:os`; only Node processes import it.
+The package is free of Node built-ins so the renderer can import it. The MCP URL the app serves on (`MCP_URL`) is exported too, for the CLI and the docs the app writes.
Design: [docs/mcp-server.md](../../docs/mcp-server.md).
diff --git a/packages/dapi/package.json b/packages/dapi/package.json
index b25e0166..d7de5715 100644
--- a/packages/dapi/package.json
+++ b/packages/dapi/package.json
@@ -1,13 +1,12 @@
{
"name": "@diffusionstudio/dapi",
"version": "0.1.0",
- "description": "The dapi tool catalog: every tool the Diffusion Studio app exposes to agents and the CLI, as a name, a description, and zod input/output schemas. The one definition the app serves, the CLI derives its commands from, and the renderer validates against. Depends on zod and the Time parser only; the socket path lives behind the Node-only `./socket` export.",
+ "description": "The dapi tool catalog: every tool the Diffusion Studio app exposes to agents and the CLI, as a name, a description, and zod input/output schemas. The one definition the app serves, the CLI derives its commands from, and the renderer validates against. Depends on zod and the Time parser only.",
"license": "MPL-2.0",
"type": "module",
"sideEffects": false,
"exports": {
- ".": "./src/index.ts",
- "./socket": "./src/socket.ts"
+ ".": "./src/index.ts"
},
"scripts": {
"check": "tsc --noEmit",
@@ -20,7 +19,6 @@
],
"dependencies": {
"@diffusionstudio/jsx": "*",
- "@modelcontextprotocol/sdk": "^1.30.0",
"zod": "^4.4.3"
},
"devDependencies": {
diff --git a/packages/dapi/src/index.ts b/packages/dapi/src/index.ts
index ae9bdb2c..a6c46969 100644
--- a/packages/dapi/src/index.ts
+++ b/packages/dapi/src/index.ts
@@ -2,8 +2,6 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-// Free of Node built-ins on purpose: the renderer imports this. The socket
-// path, which needs node:os, lives in `@diffusionstudio/dapi/socket`.
import type { z } from "zod";
@@ -21,6 +19,7 @@ export type { DapiErrorCode } from "./errors";
export { MAX_FRAMES_PER_SHEET, Bytes } from "./schemas";
+export { MCP_HOST, MCP_PORT, MCP_PATH, MCP_URL } from "./mcp";
export { DAPI_WIRE } from "./ipc";
export type { DapiCall, DapiCancel, DapiReply } from "./ipc";
export { FRAME_CAP } from "./tools/media-grab";
diff --git a/packages/dapi/src/mcp.ts b/packages/dapi/src/mcp.ts
new file mode 100644
index 00000000..f6afa685
--- /dev/null
+++ b/packages/dapi/src/mcp.ts
@@ -0,0 +1,13 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+// Where the app serves MCP over Streamable HTTP: a fixed loopback port, so
+// the URL is the same on every machine and can be written into an agent's
+// config once. 3274 spells "dapi" on a phone keypad. Loopback only; no token
+// — the server checks the Host header, which is what keeps browser pages
+// out, and anything else running as the user can already reach the app.
+export const MCP_HOST = "127.0.0.1";
+export const MCP_PORT = 3274;
+export const MCP_PATH = "/mcp";
+export const MCP_URL = `http://${MCP_HOST}:${MCP_PORT}${MCP_PATH}`;
diff --git a/packages/dapi/src/socket.test.ts b/packages/dapi/src/socket.test.ts
deleted file mode 100644
index cdba741e..00000000
--- a/packages/dapi/src/socket.test.ts
+++ /dev/null
@@ -1,111 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-import { mkdtempSync, rmSync } from "node:fs";
-import { connect, createServer } from "node:net";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import { afterAll, beforeAll, describe, expect, it } from "vitest";
-import { Client } from "@modelcontextprotocol/sdk/client/index.js";
-import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
-import { LoggingMessageNotificationSchema } from "@modelcontextprotocol/sdk/types.js";
-import { tools } from "./catalog";
-import { SocketTransport } from "./socket";
-
-import type { Server, Socket } from "node:net";
-
-// A server over the real catalog with stub handlers, the way the app hosts
-// it: one McpServer per accepted connection, MCP framed over the socket.
-const dir = mkdtempSync(join(tmpdir(), "dapi-test-"));
-const path = join(dir, "app.sock");
-let server: Server;
-
-beforeAll(async () => {
- server = createServer((socket) => {
- const session = new McpServer({ name: "test", version: "0.0.0" }, { capabilities: { logging: {} } });
- for (const tool of tools) {
- session.registerTool(
- tool.name,
- { description: tool.description, inputSchema: tool.input, outputSchema: tool.output },
- async (_args, extra) => {
- if (tool.name === "context") {
- // A notification right before the response, in the same write burst:
- // the transport must not let the response overtake its handling.
- await extra.sendNotification({ method: "notifications/message", params: { level: "info", data: "about to reply" } });
- const output = { rootDir: "/p", projectDir: null, currentTime: null, fontFamilies: [], generations: [] };
- return { content: [{ type: "text", text: JSON.stringify(output) }], structuredContent: output };
- }
- return { isError: true, content: [{ type: "text", text: `stub has no ${tool.name}` }] };
- },
- );
- }
- void session.connect(new SocketTransport(socket));
- });
- await new Promise<void>((resolve) => server.listen(path, resolve));
-});
-
-afterAll(async () => {
- await new Promise<void>((resolve) => server.close(() => resolve()));
- rmSync(dir, { recursive: true, force: true });
-});
-
-async function open(): Promise<{ client: Client; socket: Socket }> {
- const socket = await new Promise<Socket>((resolve, reject) => {
- const s = connect(path);
- s.once("connect", () => resolve(s));
- s.once("error", reject);
- });
- const client = new Client({ name: "test-client", version: "0.0.0" });
- await client.connect(new SocketTransport(socket));
- return { client, socket };
-}
-
-describe("MCP over the socket", () => {
- it("lists the whole catalog with JSON Schema inputs", async () => {
- const { client } = await open();
- try {
- const { tools: listed } = await client.listTools();
- expect(listed.map((t) => t.name).sort()).toEqual(tools.map((t) => t.name).sort());
- const grab = listed.find((t) => t.name === "media_grab")!;
- expect(grab.inputSchema.type).toBe("object");
- expect(Object.keys(grab.inputSchema.properties ?? {})).toContain("times");
- expect(grab.outputSchema?.type).toBe("object");
- } finally {
- await client.close();
- }
- });
-
- it("returns structured content and rejects bad arguments with the field named", async () => {
- const { client } = await open();
- try {
- const messages: string[] = [];
- client.setNotificationHandler(LoggingMessageNotificationSchema, (n) => {
- messages.push(String(n.params.data));
- });
- const result = await client.callTool({ name: "context", arguments: {} });
- expect(result.structuredContent).toEqual({ rootDir: "/p", projectDir: null, currentTime: null, fontFamilies: [], generations: [] });
- expect(messages).toEqual(["about to reply"]);
-
- // Bad arguments come back as a result the agent can read, not a protocol error.
- const bad = await client.callTool({ name: "media_grab", arguments: { path: "/c.mp4", count: 0 } });
- expect(bad.isError).toBe(true);
- expect(JSON.stringify(bad.content)).toMatch(/count/);
- } finally {
- await client.close();
- }
- });
-
- it("serves several sessions at once", async () => {
- const a = await open();
- const b = await open();
- try {
- const [ra, rb] = await Promise.all([a.client.ping(), b.client.ping()]);
- expect(ra).toBeDefined();
- expect(rb).toBeDefined();
- } finally {
- await a.client.close();
- await b.client.close();
- }
- });
-});
diff --git a/packages/dapi/src/socket.ts b/packages/dapi/src/socket.ts
deleted file mode 100644
index 62c1b9db..00000000
--- a/packages/dapi/src/socket.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// The Node side of the protocol: where the app's socket lives and how MCP
-// travels over it. Its own entry point (`@diffusionstudio/dapi/socket`) so
-// the renderer can import the catalog without node:os or the MCP SDK.
-
-import { platform, tmpdir } from "node:os";
-import { join } from "node:path";
-import { ReadBuffer, serializeMessage } from "@modelcontextprotocol/sdk/shared/stdio.js";
-
-import type { Socket } from "node:net";
-import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
-import type { JSONRPCMessage } from "@modelcontextprotocol/sdk/types.js";
-
-// Where the app serves MCP over HTTP, for agents: a fixed loopback port, so
-// the URL is the same on every machine and can be written into a config once.
-// 3274 spells "dapi" on a phone keypad. Loopback only; no token — the server
-// checks the Host header, which is what keeps browser pages out, and anything
-// else running as the user can already reach the socket below.
-export const MCP_HOST = "127.0.0.1";
-export const MCP_PORT = 3274;
-export const MCP_PATH = "/mcp";
-export const MCP_URL = `http://${MCP_HOST}:${MCP_PORT}${MCP_PATH}`;
-
-// One socket / named pipe per host, for the CLI. On macOS tmpdir is per-user;
-// on Linux /tmp is global but the socket file's owner-only mode 0600 keeps it
-// isolated.
-export const SOCKET_PATH =
- platform() === "win32"
- ? "\\\\.\\pipe\\diffusion-studio"
- : join(tmpdir(), "diffusion-studio.sock");
-
-/**
- * MCP over a local socket, framed exactly like MCP over stdio: one JSON-RPC
- * message per line. The same class serves the app (one per accepted
- * connection) and the CLI (one per command); a stdio proxy needs neither,
- * since the bytes on the socket are already what a stdio client expects.
- */
-export class SocketTransport implements Transport {
- onclose?: () => void;
- onerror?: (error: Error) => void;
- onmessage?: (message: JSONRPCMessage) => void;
-
- private readonly socket: Socket;
- private readonly buffer = new ReadBuffer();
- private started = false;
- private draining = false;
-
- constructor(socket: Socket) {
- this.socket = socket;
- }
-
- async start(): Promise<void> {
- if (this.started) throw new Error("SocketTransport already started");
- this.started = true;
- this.socket.on("data", (chunk: Buffer) => {
- this.buffer.append(chunk);
- void this.drain();
- });
- this.socket.on("error", (error) => this.onerror?.(error));
- this.socket.on("close", () => this.onclose?.());
- }
-
- send(message: JSONRPCMessage): Promise<void> {
- return new Promise((resolve, reject) => {
- if (this.socket.destroyed) {
- reject(new Error("Socket is closed"));
- return;
- }
- this.socket.write(serializeMessage(message), (error) => (error ? reject(error) : resolve()));
- });
- }
-
- async close(): Promise<void> {
- this.socket.end();
- this.socket.destroy();
- }
-
- // Messages are handed over one per turn of the event loop. The SDK runs
- // notification handlers on a microtask, so a notification and the response
- // that follows it in the same chunk must not be dispatched back to back:
- // the response would settle the request before the notification's handler
- // ran. A drain in progress picks up chunks appended meanwhile.
- private async drain(): Promise<void> {
- if (this.draining) return;
- this.draining = true;
- try {
- while (true) {
- let message: JSONRPCMessage | null;
- try {
- message = this.buffer.readMessage();
- } catch (error) {
- this.onerror?.(error as Error);
- return;
- }
- if (!message) return;
- this.onmessage?.(message);
- await new Promise<void>((resolve) => setImmediate(resolve));
- }
- } finally {
- this.draining = false;
- }
- }
-}