[9] MCP-Brücke zur offenen App: KI-Zugriff (opt-in, Sitzungsschlüssel), gemeinsame Werkzeugliste, Protokoll und Pause
dossier-cli mcp --app spricht MCP über stdio und lauscht auf 127.0.0.1; die App verbindet sich nur mit „KI-Zugriff erlauben“ als WebSocket-Client (gegenseitige HMAC-Anmeldung). Werkzeuge für Datei und App aus einer Liste (core/aiToolDefs.ts, core/aiTools.ts), run_command über die Kern-Befehle, jede Änderung ein Undo-Schritt „KI: <werkzeug>“, KI-Protokoll mit Pause.
This commit is contained in:
25 files changed
+1594
-119
No files matched your search
+8
-4
@@ -21,13 +21,13 @@ const call = async (...a: string[]) => run([file, ...a]);
|
||||
describe("dossier-cli", () => {
|
||||
it("importiert ausschliesslich ../core", () => {
|
||||
const src = readFileSync(join(process.cwd(), "src", "cli", "main.ts"), "utf8");
|
||||
for (const f of ["main.ts", "mcp.ts"]) {
|
||||
for (const f of ["main.ts", "mcp.ts", "mcpBridge.ts"]) {
|
||||
const text = readFileSync(join(process.cwd(), "src", "cli", f), "utf8");
|
||||
const rel = [...text.matchAll(/from\s+"(\.[^"]+)"/g)].map((m) => m[1]);
|
||||
expect(rel.every((r) => r === "../core" || r === "./mcp"), f).toBe(true);
|
||||
expect(rel.every((r) => r === "../core" || r === "./mcp" || r === "./mcpBridge"), f).toBe(true);
|
||||
}
|
||||
expect(src.length).toBeGreaterThan(0);
|
||||
expect(readdirSync(join(process.cwd(), "src", "cli")).filter((f) => statSync(join(process.cwd(), "src", "cli", f)).isFile() && f.endsWith(".ts") && !f.endsWith(".test.ts")).sort()).toEqual(["main.ts", "mcp.ts"]);
|
||||
expect(readdirSync(join(process.cwd(), "src", "cli")).filter((f) => statSync(join(process.cwd(), "src", "cli", f)).isFile() && f.endsWith(".ts") && !f.endsWith(".test.ts")).sort()).toEqual(["main.ts", "mcp.ts", "mcpBridge.ts"]);
|
||||
});
|
||||
|
||||
it("info, validate, migrate", async () => {
|
||||
@@ -159,7 +159,11 @@ describe("MCP-Server", () => {
|
||||
const init = (await handleMessage(file, { jsonrpc: "2.0", id: 1, method: "initialize", params: {} })) as { result: { serverInfo: { name: string } } };
|
||||
expect(init.result.serverInfo.name).toBe("dossier");
|
||||
const list = (await handleMessage(file, { jsonrpc: "2.0", id: 2, method: "tools/list" })) as { result: { tools: Array<{ name: string }> } };
|
||||
expect(list.result.tools.map((t) => t.name)).toEqual(["project_info", "query", "render_svg", "apply_ops", "validate"]);
|
||||
// gemeinsame Liste (core/aiToolDefs.ts) ohne die App-Werkzeuge
|
||||
const names = list.result.tools.map((t) => t.name);
|
||||
expect(names.slice(0, 4)).toEqual(["project_info", "query", "render_svg", "apply_ops"]);
|
||||
expect(names).toContain("run_command");
|
||||
expect(names).not.toContain("select");
|
||||
expect(await handleMessage(file, { jsonrpc: "2.0", method: "notifications/initialized" })).toBeNull();
|
||||
|
||||
const call = async (name: string, args: Record<string, unknown>) =>
|
||||
|
||||
+28
-2
@@ -27,7 +27,8 @@
|
||||
// dossier-cli pdf-info <datei.pdf> [--page 1] Vektor-PDF lesen ([76]): Seiten, Pfade, Texte, BBox (pt) als JSON
|
||||
// dossier-cli convert plan.pdf plan.obp [--scale 100] [--page 1] [--no-text]
|
||||
// Vektor-PDF als 2D-Zeichnung (Ebenen nach Farbe/Strichstärke)
|
||||
// dossier-cli <projekt.obp> mcp MCP-Server (stdio): project_info, query, render_svg, apply_ops, validate
|
||||
// dossier-cli <projekt.obp> mcp MCP-Server (stdio) auf der Datei: Werkzeuge aus core/aiToolDefs.ts
|
||||
// dossier-cli mcp --app [--port 7979] [--token …] MCP-Brücke zur offenen App ([9], KI-Zugriff in den Einstellungen)
|
||||
// dossier-cli <projekt.obp> bench [--runs 10] Zeitprofil der Ableitungen (ms je Aufruf)
|
||||
//
|
||||
// Statt einer Datei nimmt `:beispiel` das eingebaute Demo-Haus (sampleProject).
|
||||
@@ -105,9 +106,11 @@ import {
|
||||
validateProject,
|
||||
projectWarnings,
|
||||
sampleProject,
|
||||
AI_BRIDGE_DEFAULT_PORT,
|
||||
} from "../core";
|
||||
import type { Project } from "../core";
|
||||
import { serveStdio } from "./mcp";
|
||||
import { startBridge } from "./mcpBridge";
|
||||
|
||||
type Args = { positional: string[]; flags: Map<string, string>; cmds: string[] };
|
||||
|
||||
@@ -299,6 +302,7 @@ export async function run(argv: string[]): Promise<number> {
|
||||
if (file === "bcf-info") return runBcfInfo(command);
|
||||
if (file === "pointcloud-info") return pointCloudInfo(args, command);
|
||||
if (file === "pdf-info") return runPdfInfo(args, command);
|
||||
if (file === "mcp" && args.flags.has("app")) return runAppBridge(args);
|
||||
if (!file || (!command && args.cmds.length === 0)) {
|
||||
process.stderr.write(
|
||||
"Aufruf: dossier-cli <projekt.obp> <info|validate|migrate|plan|section|elevation|dxf|dwg|ifc|import-ifc|import-mesh|step|obj|stl|glb|gltf|schedule|kennzahlen|raumprogramm|sun|model3d> [Optionen]\n" +
|
||||
@@ -306,7 +310,8 @@ export async function run(argv: string[]): Promise<number> {
|
||||
" dossier-cli <projekt.obp> --cmd \"befehl …\" [--cmd …] ({last} = zuletzt geschriebene Datei)\n" +
|
||||
" dossier-cli pointcloud-info <datei> [--voxel 0.05] [--max 2000000]\n" +
|
||||
" dossier-cli bcf-info <datei.bcfzip>\n" +
|
||||
" dossier-cli pdf-info <datei.pdf> [--page 1]\n",
|
||||
" dossier-cli pdf-info <datei.pdf> [--page 1]\n" +
|
||||
" dossier-cli mcp --app [--port 7979] [--token schlüssel] (MCP-Brücke zur offenen App)\n",
|
||||
);
|
||||
return 2;
|
||||
}
|
||||
@@ -323,6 +328,27 @@ export async function run(argv: string[]): Promise<number> {
|
||||
return code === 0 ? runCmds(project, file, args) : code;
|
||||
}
|
||||
|
||||
/**
|
||||
* [9] `dossier-cli mcp --app [--port 7979] [--token …]`: MCP über stdio, Werkzeuge laufen in der offenen App.
|
||||
* Schlüssel aus `--token` oder `DOSSIER_AI_TOKEN` (Einstellungen der App → KI-Zugriff).
|
||||
*/
|
||||
async function runAppBridge(args: Args): Promise<number> {
|
||||
const token = args.flags.get("token") ?? process.env.DOSSIER_AI_TOKEN ?? "";
|
||||
if (!token || token === "true") fail("mcp --app: Schlüssel fehlt (--token oder DOSSIER_AI_TOKEN, s. Einstellungen der App → KI-Zugriff)");
|
||||
const port = Number(args.flags.get("port") ?? AI_BRIDGE_DEFAULT_PORT);
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) fail("--port: 1 bis 65535");
|
||||
let bridge;
|
||||
try {
|
||||
bridge = await startBridge({ port, token });
|
||||
} catch (e) {
|
||||
fail(`mcp --app: Port ${port} nicht verfügbar (${e instanceof Error ? e.message : String(e)})`);
|
||||
}
|
||||
process.stderr.write(`Dossier MCP-Brücke auf 127.0.0.1:${bridge.port} — wartet auf die App.\n`);
|
||||
await serveStdio(bridge.handle);
|
||||
await bridge.close();
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** Endung (klein, ohne Punkt) eines Dateinamens. */
|
||||
const extOf = (path: string): string => (path.includes(".") ? (path.split(".").pop() ?? "").toLowerCase() : "");
|
||||
|
||||
|
||||
+51
-113
@@ -1,70 +1,28 @@
|
||||
// MCP-Server (stdio, JSON-RPC 2.0, newline-delimited) auf einer Projektdatei — lessons-bimcraft
|
||||
// [9] in der headless Variante: ein Agent liest, rendert und ändert das Projekt über dieselben
|
||||
// `CoreOp`s wie die UI (core/ops.ts). Änderungen werden validiert und atomar in die Datei
|
||||
// geschrieben. Start: `node dist-cli/dossier-cli.mjs projekt.obp mcp`.
|
||||
// Werkzeuge wie die Brücke zur laufenden App (`core/aiToolDefs.ts`, `core/aiTools.ts`; die
|
||||
// App-Werkzeuge fehlen hier). Änderungen werden validiert und atomar in die Datei geschrieben.
|
||||
// Start: `node dist-cli/dossier-cli.mjs projekt.obp mcp`.
|
||||
// Nur `../core` wird importiert (Wächter in cli.test.ts).
|
||||
|
||||
import { readFileSync, renameSync, writeFileSync } from "node:fs";
|
||||
import {
|
||||
applyOps,
|
||||
computeSection,
|
||||
generateElevationPlan,
|
||||
generatePlan,
|
||||
generateSectionPlan,
|
||||
parseProjectFile,
|
||||
planToSvgString,
|
||||
serializeProject,
|
||||
validateOps,
|
||||
validateProject,
|
||||
projectWarnings,
|
||||
} from "../core";
|
||||
import type { CoreOp, Project } from "../core";
|
||||
import { AI_TOOLS, aiText, applyOps, callAiTool, parseProjectFile, serializeProject, validateOps } from "../core";
|
||||
import type { AiHost, AiToolDef, AiToolResult, Project } from "../core";
|
||||
|
||||
interface Rpc {
|
||||
export interface Rpc {
|
||||
jsonrpc: "2.0";
|
||||
id?: number | string | null;
|
||||
method?: string;
|
||||
params?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
const TOOLS = [
|
||||
{
|
||||
name: "project_info",
|
||||
description: "Zählt Bauteile des Projekts und listet Geschosse/Schnitte/Ansichten.",
|
||||
inputSchema: { type: "object", properties: {} },
|
||||
},
|
||||
{
|
||||
name: "query",
|
||||
description: "Liest Elemente einer Liste (walls, ceilings, roofs, openings, stairs, rooms, drawings2d, extrudedSolids, …), optional eine id.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: { collection: { type: "string" }, id: { type: "string" }, limit: { type: "number" } },
|
||||
required: ["collection"],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "render_svg",
|
||||
description: "Rendert Grundriss (kind=floor), Schnitt (section) oder Ansicht (elevation) als SVG-Text.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: { kind: { type: "string", enum: ["floor", "section", "elevation"] }, name: { type: "string" }, scale: { type: "number" } },
|
||||
required: ["kind"],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "apply_ops",
|
||||
description:
|
||||
"Wendet CoreOps an (add/replace/remove/reorder/setField, JSON). Validiert (NaN, doppelte ids) und schreibt die Datei nur bei Erfolg.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: { ops: { type: "array", items: { type: "object" } } },
|
||||
required: ["ops"],
|
||||
},
|
||||
},
|
||||
{ name: "validate", description: "Prüft das gesamte Projekt auf nicht endliche Zahlen und doppelte ids.", inputSchema: { type: "object", properties: {} } },
|
||||
];
|
||||
|
||||
const text = (t: string, isError = false) => ({ content: [{ type: "text", text: t }], isError });
|
||||
/** Werkzeug für `tools/list` (ohne die internen Kennzeichen, mit MCP-Hinweisen). */
|
||||
export const mcpTool = (t: AiToolDef) => ({
|
||||
name: t.name,
|
||||
description: t.description,
|
||||
inputSchema: t.inputSchema,
|
||||
annotations: { readOnlyHint: !t.mutating },
|
||||
});
|
||||
|
||||
function load(file: string): Project {
|
||||
const r = parseProjectFile(readFileSync(file, "utf8"));
|
||||
@@ -78,63 +36,33 @@ function save(file: string, p: Project): void {
|
||||
renameSync(tmp, file); // atomar
|
||||
}
|
||||
|
||||
export async function callTool(file: string, name: string, args: Record<string, unknown>) {
|
||||
/** Host über eine Projektdatei: liest je Aufruf neu, schreibt nur angenommene Änderungen. */
|
||||
export function fileHost(file: string): AiHost {
|
||||
const project = load(file);
|
||||
const codes = new Set(project.layers.map((l) => l.code));
|
||||
switch (name) {
|
||||
case "project_info":
|
||||
return text(
|
||||
JSON.stringify({
|
||||
name: project.name,
|
||||
counts: Object.fromEntries(
|
||||
Object.entries(project as unknown as Record<string, unknown>)
|
||||
.filter(([, v]) => Array.isArray(v))
|
||||
.map(([k, v]) => [k, (v as unknown[]).length]),
|
||||
),
|
||||
levels: project.drawingLevels.map((l) => ({ id: l.id, name: l.name, kind: l.kind })),
|
||||
}),
|
||||
);
|
||||
case "query": {
|
||||
const list = (project as unknown as Record<string, unknown>)[String(args.collection)];
|
||||
if (!Array.isArray(list)) return text(`Keine Liste: ${String(args.collection)}`, true);
|
||||
const rows = args.id ? list.filter((e) => (e as { id?: string }).id === args.id) : list.slice(0, Number(args.limit ?? 50));
|
||||
return text(JSON.stringify(rows));
|
||||
}
|
||||
case "render_svg": {
|
||||
const kind = String(args.kind);
|
||||
const lvl = project.drawingLevels.find((l) => l.kind === kind && (!args.name || l.name === args.name || l.id === args.name));
|
||||
if (!lvl) return text(`Ebene nicht gefunden: ${kind} ${String(args.name ?? "")}`, true);
|
||||
const scale = Number(args.scale ?? 100);
|
||||
if (kind === "floor") return text(planToSvgString(generatePlan(project, lvl.id, codes), { scaleDenominator: scale }));
|
||||
if (kind === "section") {
|
||||
const o = await computeSection(project, lvl);
|
||||
if (!o) return text("keine gültige Schnittlinie", true);
|
||||
return text(planToSvgString(generateSectionPlan(o, false, { visibleCodes: codes }), { scaleDenominator: scale }));
|
||||
}
|
||||
const plan = generateElevationPlan(project, lvl, { scaleDenominator: scale });
|
||||
return plan ? text(planToSvgString(plan, { scaleDenominator: scale })) : text("keine gültige Ansichtslinie", true);
|
||||
}
|
||||
case "apply_ops": {
|
||||
const ops = args.ops as CoreOp[];
|
||||
if (!Array.isArray(ops)) return text("ops muss eine Liste sein", true);
|
||||
return {
|
||||
project: () => project,
|
||||
commit: (ops) => {
|
||||
const next = applyOps(project, ops);
|
||||
const problems = validateOps(next, ops, project);
|
||||
if (problems.length) return text(`Abgelehnt, nichts geschrieben: ${problems.join("; ")}`, true);
|
||||
if (problems.length) return problems.join("; ");
|
||||
save(file, next);
|
||||
return text(`ok: ${ops.length} Op(s) angewendet und gespeichert`);
|
||||
}
|
||||
case "validate": {
|
||||
const problems = validateProject(project);
|
||||
const warnings = projectWarnings(project).map((w) => `Warnung: ${w}`);
|
||||
return text([...problems, ...warnings].join("\n") || "ok", problems.length > 0);
|
||||
}
|
||||
default:
|
||||
return text(`unbekanntes Werkzeug: ${name}`, true);
|
||||
}
|
||||
return null;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Behandelt EINE JSON-RPC-Nachricht; `null` = keine Antwort (Notification). */
|
||||
export async function handleMessage(file: string, msg: Rpc): Promise<object | null> {
|
||||
export async function callTool(file: string, name: string, args: Record<string, unknown>): Promise<AiToolResult> {
|
||||
if (AI_TOOLS.find((t) => t.name === name)?.appOnly) return aiText(`${name}: nur mit der laufenden App (dossier-cli mcp --app)`, true);
|
||||
return callAiTool(fileHost(file), name, args);
|
||||
}
|
||||
|
||||
/** Behandelt EINE JSON-RPC-Nachricht mit Werkzeugliste `tools` und Ausführer `call`; `null` = keine Antwort. */
|
||||
export async function handleRpc(
|
||||
msg: Rpc,
|
||||
tools: AiToolDef[],
|
||||
call: (name: string, args: Record<string, unknown>) => Promise<AiToolResult>,
|
||||
serverName = "dossier",
|
||||
): Promise<object | null> {
|
||||
const reply = (result: unknown) => ({ jsonrpc: "2.0", id: msg.id ?? null, result });
|
||||
const error = (code: number, message: string) => ({ jsonrpc: "2.0", id: msg.id ?? null, error: { code, message } });
|
||||
if (msg.id === undefined) return null; // Notification (z. B. notifications/initialized)
|
||||
@@ -143,18 +71,18 @@ export async function handleMessage(file: string, msg: Rpc): Promise<object | nu
|
||||
return reply({
|
||||
protocolVersion: "2024-11-05",
|
||||
capabilities: { tools: {} },
|
||||
serverInfo: { name: "dossier", version: "0.1.0" },
|
||||
serverInfo: { name: serverName, version: "0.2.0" },
|
||||
});
|
||||
case "ping":
|
||||
return reply({});
|
||||
case "tools/list":
|
||||
return reply({ tools: TOOLS });
|
||||
return reply({ tools: tools.map(mcpTool) });
|
||||
case "tools/call": {
|
||||
const p = msg.params ?? {};
|
||||
try {
|
||||
return reply(await callTool(file, String(p.name), (p.arguments ?? {}) as Record<string, unknown>));
|
||||
return reply(await call(String(p.name), (p.arguments ?? {}) as Record<string, unknown>));
|
||||
} catch (e) {
|
||||
return reply(text(e instanceof Error ? e.message : String(e), true));
|
||||
return reply(aiText(e instanceof Error ? e.message : String(e), true));
|
||||
}
|
||||
}
|
||||
default:
|
||||
@@ -162,8 +90,18 @@ export async function handleMessage(file: string, msg: Rpc): Promise<object | nu
|
||||
}
|
||||
}
|
||||
|
||||
/** stdio-Schleife. */
|
||||
export async function serveStdio(file: string): Promise<void> {
|
||||
/** Headless: Werkzeuge ohne die App-Werkzeuge, auf der Datei. */
|
||||
export function handleMessage(file: string, msg: Rpc): Promise<object | null> {
|
||||
return handleRpc(
|
||||
msg,
|
||||
AI_TOOLS.filter((t) => !t.appOnly),
|
||||
(name, args) => callTool(file, name, args),
|
||||
);
|
||||
}
|
||||
|
||||
/** stdio-Schleife: jede Zeile eine JSON-RPC-Nachricht an `handle`. */
|
||||
export async function serveStdio(handle: string | ((msg: Rpc) => Promise<object | null>)): Promise<void> {
|
||||
const h = typeof handle === "string" ? (m: Rpc) => handleMessage(handle, m) : handle;
|
||||
let buf = "";
|
||||
process.stdin.setEncoding("utf8");
|
||||
for await (const chunk of process.stdin) {
|
||||
@@ -180,7 +118,7 @@ export async function serveStdio(file: string): Promise<void> {
|
||||
process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } }) + "\n");
|
||||
continue;
|
||||
}
|
||||
const res = await handleMessage(file, msg);
|
||||
const res = await h(msg);
|
||||
if (res) process.stdout.write(JSON.stringify(res) + "\n");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
// [9] Brücke MCP ↔ laufende App: echte Brücke (WebSocket auf 127.0.0.1) gegen den echten App-Client
|
||||
// (`net/aiBridge.ts`) mit einem Host im Speicher statt des Stores.
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { startBridge, wsFrame, type Bridge } from "./mcpBridge";
|
||||
import { connectAiBridge, type AiBridgeStatus } from "../net/aiBridge";
|
||||
import { aiText, callAiTool, randomHex, type AiHost } from "../core";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
|
||||
const until = async (f: () => boolean, ms = 5000) => {
|
||||
const t0 = Date.now();
|
||||
while (!f()) {
|
||||
if (Date.now() - t0 > ms) throw new Error("Zeitüberschreitung");
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
}
|
||||
};
|
||||
|
||||
let bridge: Bridge | null = null;
|
||||
let client: { close(): void } | null = null;
|
||||
afterEach(async () => {
|
||||
client?.close();
|
||||
client = null;
|
||||
await bridge?.close();
|
||||
bridge = null;
|
||||
});
|
||||
|
||||
const host: AiHost = { project: () => sampleProject, commit: () => null, select: () => {} };
|
||||
|
||||
describe("MCP-Brücke zur App", () => {
|
||||
it("ohne App: tools/list mit allen Werkzeugen, Aufruf meldet fehlende Verbindung", async () => {
|
||||
bridge = await startBridge({ port: 0, token: randomHex() });
|
||||
const list = (await bridge.handle({ jsonrpc: "2.0", id: 1, method: "tools/list" })) as { result: { tools: { name: string }[] } };
|
||||
expect(list.result.tools.map((t) => t.name)).toContain("zoom_to");
|
||||
const r = (await bridge.handle({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "project_info", arguments: {} } })) as {
|
||||
result: { isError: boolean; content: { text: string }[] };
|
||||
};
|
||||
expect(r.result.isError).toBe(true);
|
||||
expect(r.result.content[0].text).toContain("KI-Zugriff");
|
||||
});
|
||||
|
||||
it("App mit richtigem Schlüssel: Aufrufe laufen über die App", async () => {
|
||||
const token = randomHex();
|
||||
bridge = await startBridge({ port: 0, token });
|
||||
const seen: string[] = [];
|
||||
let status: AiBridgeStatus = "closed";
|
||||
client = connectAiBridge({
|
||||
port: bridge.port,
|
||||
token,
|
||||
retryMs: 50,
|
||||
onStatus: (s) => (status = s),
|
||||
call: (name, args) => {
|
||||
seen.push(name);
|
||||
return callAiTool(host, name, args);
|
||||
},
|
||||
});
|
||||
await until(() => bridge!.connected() && status === "connected");
|
||||
const r = (await bridge.handle({ jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "project_info", arguments: {} } })) as {
|
||||
result: { isError: boolean; content: { text: string }[] };
|
||||
};
|
||||
expect(r.result.isError).toBe(false);
|
||||
expect(JSON.parse(r.result.content[0].text).counts.walls).toBe(sampleProject.walls.length);
|
||||
// grosse Antwort (16-/64-Bit-Länge im Rahmen)
|
||||
const svg = await bridge.call("render_svg", { kind: "floor" });
|
||||
expect((svg.content[0] as { text: string }).text).toContain("<svg");
|
||||
expect(seen).toEqual(["project_info", "render_svg"]);
|
||||
});
|
||||
|
||||
it("falscher Schlüssel: keine Verbindung, Status auth-failed", async () => {
|
||||
bridge = await startBridge({ port: 0, token: randomHex() });
|
||||
let status: AiBridgeStatus = "closed";
|
||||
let called = false;
|
||||
client = connectAiBridge({
|
||||
port: bridge.port,
|
||||
token: randomHex(),
|
||||
retryMs: 50,
|
||||
onStatus: (s) => (status = s),
|
||||
call: async () => ((called = true), aiText("x")),
|
||||
});
|
||||
await until(() => status === "auth-failed");
|
||||
expect(bridge.connected()).toBe(false);
|
||||
expect((await bridge.call("project_info", {})).isError).toBe(true);
|
||||
expect(called).toBe(false);
|
||||
});
|
||||
|
||||
it("Fremder ohne Anmeldung wird getrennt und bekommt keine Aufrufe", async () => {
|
||||
bridge = await startBridge({ port: 0, token: randomHex() });
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${bridge.port}`);
|
||||
const msgs: string[] = [];
|
||||
ws.onmessage = (e) => msgs.push(String(e.data));
|
||||
await new Promise((r) => (ws.onopen = r));
|
||||
ws.send(JSON.stringify({ type: "ready" }));
|
||||
await new Promise((r) => (ws.onclose = r));
|
||||
expect(bridge.connected()).toBe(false);
|
||||
expect(msgs.map((m) => JSON.parse(m).type)).toEqual(["hello"]);
|
||||
});
|
||||
|
||||
it("Rahmen-Längen 7/16/64 Bit", () => {
|
||||
expect(wsFrame(1, Buffer.alloc(5))[1]).toBe(5);
|
||||
expect(wsFrame(1, Buffer.alloc(300))[1]).toBe(126);
|
||||
expect(wsFrame(1, Buffer.alloc(70000))[1]).toBe(127);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,209 @@
|
||||
// [9] MCP-Brücke zur laufenden App: `dossier-cli mcp --app [--port 7979] [--token …]` spricht MCP über
|
||||
// stdio mit dem KI-Client und reicht die Werkzeug-Aufrufe an die App weiter. Die App verbindet sich
|
||||
// (nur mit „KI-Zugriff erlauben“) als WebSocket-Client mit dieser Brücke, die nur auf 127.0.0.1 lauscht;
|
||||
// beide Seiten melden sich per HMAC mit dem Sitzungsschlüssel aus den Einstellungen der App an
|
||||
// (`core/aiToolDefs.ts`). So braucht der App-Host (Tauri/Electron/Browser) keinen eigenen Server.
|
||||
// Der WebSocket-Server ist bewusst minimal (RFC 6455: Text, Ping/Pong, Schliessen; keine Erweiterungen).
|
||||
|
||||
import { createHash } from "node:crypto";
|
||||
import { createServer, type IncomingMessage } from "node:http";
|
||||
import type { Duplex } from "node:stream";
|
||||
import { AI_TOOLS, aiText, hmacHex, randomHex, sameMac } from "../core";
|
||||
import type { AiBridgeMsg, AiToolResult } from "../core";
|
||||
import { handleRpc, type Rpc } from "./mcp";
|
||||
|
||||
const WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
|
||||
const MAX_MESSAGE = 64 * 1024 * 1024;
|
||||
|
||||
// ── WebSocket (Server-Seite, minimal) ─────────────────────────────────────────────────────────
|
||||
|
||||
interface WsConn {
|
||||
send(text: string): void;
|
||||
close(): void;
|
||||
onmessage?: (text: string) => void;
|
||||
onclose?: () => void;
|
||||
}
|
||||
|
||||
/** Rahmen (Server → Client: unmaskiert). */
|
||||
export function wsFrame(opcode: number, payload: Buffer): Buffer {
|
||||
const n = payload.length;
|
||||
const head = n < 126 ? Buffer.from([0x80 | opcode, n]) : n < 65536 ? Buffer.alloc(4) : Buffer.alloc(10);
|
||||
if (n >= 126 && n < 65536) {
|
||||
head[0] = 0x80 | opcode;
|
||||
head[1] = 126;
|
||||
head.writeUInt16BE(n, 2);
|
||||
} else if (n >= 65536) {
|
||||
head[0] = 0x80 | opcode;
|
||||
head[1] = 127;
|
||||
head.writeBigUInt64BE(BigInt(n), 2);
|
||||
}
|
||||
return Buffer.concat([head, payload]);
|
||||
}
|
||||
|
||||
function upgrade(req: IncomingMessage, socket: Duplex): WsConn | null {
|
||||
const key = req.headers["sec-websocket-key"];
|
||||
if (String(req.headers.upgrade).toLowerCase() !== "websocket" || typeof key !== "string" || req.headers["sec-websocket-version"] !== "13") {
|
||||
socket.end("HTTP/1.1 400 Bad Request\r\n\r\n");
|
||||
return null;
|
||||
}
|
||||
const accept = createHash("sha1").update(key + WS_GUID).digest("base64");
|
||||
socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`);
|
||||
let buf = Buffer.alloc(0);
|
||||
let parts: Buffer[] = [];
|
||||
let closed = false;
|
||||
const conn: WsConn = {
|
||||
send: (text) => {
|
||||
if (!closed) socket.write(wsFrame(1, Buffer.from(text, "utf8")));
|
||||
},
|
||||
close: () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
socket.end(wsFrame(8, Buffer.alloc(0)));
|
||||
conn.onclose?.();
|
||||
},
|
||||
};
|
||||
socket.on("data", (chunk: Buffer) => {
|
||||
buf = Buffer.concat([buf, chunk]);
|
||||
for (;;) {
|
||||
if (buf.length < 2) return;
|
||||
const fin = (buf[0] & 0x80) !== 0;
|
||||
const op = buf[0] & 0x0f;
|
||||
const masked = (buf[1] & 0x80) !== 0;
|
||||
let len = buf[1] & 0x7f;
|
||||
let off = 2;
|
||||
if (len === 126) {
|
||||
if (buf.length < 4) return;
|
||||
len = buf.readUInt16BE(2);
|
||||
off = 4;
|
||||
} else if (len === 127) {
|
||||
if (buf.length < 10) return;
|
||||
const big = buf.readBigUInt64BE(2);
|
||||
if (big > BigInt(MAX_MESSAGE)) return conn.close();
|
||||
len = Number(big);
|
||||
off = 10;
|
||||
}
|
||||
if (!masked || len > MAX_MESSAGE) return conn.close(); // Client-Rahmen müssen maskiert sein
|
||||
if (buf.length < off + 4 + len) return;
|
||||
const mask = buf.subarray(off, off + 4);
|
||||
const data = Buffer.from(buf.subarray(off + 4, off + 4 + len));
|
||||
for (let i = 0; i < data.length; i++) data[i] ^= mask[i & 3];
|
||||
buf = buf.subarray(off + 4 + len);
|
||||
if (op === 8) return conn.close();
|
||||
if (op === 9) socket.write(wsFrame(10, data));
|
||||
else if (op === 1 || op === 0) {
|
||||
parts.push(data);
|
||||
if (parts.reduce((s, p) => s + p.length, 0) > MAX_MESSAGE) return conn.close();
|
||||
if (fin) {
|
||||
const text = Buffer.concat(parts).toString("utf8");
|
||||
parts = [];
|
||||
conn.onmessage?.(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
const end = () => {
|
||||
if (!closed) {
|
||||
closed = true;
|
||||
conn.onclose?.();
|
||||
}
|
||||
};
|
||||
socket.on("close", end);
|
||||
socket.on("error", end);
|
||||
return conn;
|
||||
}
|
||||
|
||||
// ── Brücke ───────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface Bridge {
|
||||
port: number;
|
||||
connected(): boolean;
|
||||
call(name: string, args: Record<string, unknown>): Promise<AiToolResult>;
|
||||
handle(msg: Rpc): Promise<object | null>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
/** Startet die Brücke auf 127.0.0.1:`port` (0 = frei wählen). */
|
||||
export function startBridge(opts: { port: number; token: string; callTimeoutMs?: number }): Promise<Bridge> {
|
||||
let app: WsConn | null = null;
|
||||
let nextId = 1;
|
||||
const pending = new Map<number, (r: AiToolResult) => void>();
|
||||
const server = createServer((_req, res) => {
|
||||
res.writeHead(426, { "Content-Type": "text/plain" });
|
||||
res.end("Dossier MCP-Brücke: nur WebSocket\n");
|
||||
});
|
||||
server.on("upgrade", (req, socket) => {
|
||||
const conn = upgrade(req, socket);
|
||||
if (!conn) return;
|
||||
const nonce = randomHex();
|
||||
let authed = false;
|
||||
let ready = false;
|
||||
conn.onmessage = async (text) => {
|
||||
let m: AiBridgeMsg;
|
||||
try {
|
||||
m = JSON.parse(text) as AiBridgeMsg;
|
||||
} catch {
|
||||
return conn.close();
|
||||
}
|
||||
if (!ready && m.type === "auth" && typeof m.nonce === "string") {
|
||||
if (authed || !sameMac(m.mac, await hmacHex(opts.token, `app:${nonce}`))) return conn.close();
|
||||
authed = true;
|
||||
conn.send(JSON.stringify({ type: "auth", mac: await hmacHex(opts.token, `bridge:${m.nonce}`) } satisfies AiBridgeMsg));
|
||||
} else if (authed && !ready && m.type === "ready") {
|
||||
if (app) return conn.close(); // nur eine App zugleich
|
||||
ready = true;
|
||||
app = conn;
|
||||
} else if (ready && m.type === "result") {
|
||||
pending.get(m.id)?.(m.result);
|
||||
pending.delete(m.id);
|
||||
} else if (!ready) conn.close();
|
||||
};
|
||||
conn.onclose = () => {
|
||||
if (app !== conn) return;
|
||||
app = null;
|
||||
for (const [id, done] of pending) {
|
||||
done(aiText("Verbindung zur App getrennt", true));
|
||||
pending.delete(id);
|
||||
}
|
||||
};
|
||||
conn.send(JSON.stringify({ type: "hello", nonce } satisfies AiBridgeMsg));
|
||||
});
|
||||
|
||||
const call = (name: string, args: Record<string, unknown>): Promise<AiToolResult> => {
|
||||
const conn = app;
|
||||
if (!conn)
|
||||
return Promise.resolve(
|
||||
aiText("Dossier ist nicht verbunden: in der App unter Einstellungen „KI-Zugriff erlauben“ einschalten und den Schlüssel als --token übergeben.", true),
|
||||
);
|
||||
const id = nextId++;
|
||||
return new Promise((resolve) => {
|
||||
const timer = setTimeout(() => {
|
||||
pending.delete(id);
|
||||
resolve(aiText("Zeitüberschreitung: keine Antwort der App", true));
|
||||
}, opts.callTimeoutMs ?? 300_000);
|
||||
pending.set(id, (r) => {
|
||||
clearTimeout(timer);
|
||||
resolve(r);
|
||||
});
|
||||
conn.send(JSON.stringify({ type: "call", id, name, args } satisfies AiBridgeMsg));
|
||||
});
|
||||
};
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(opts.port, "127.0.0.1", () => {
|
||||
const addr = server.address();
|
||||
resolve({
|
||||
port: typeof addr === "object" && addr ? addr.port : opts.port,
|
||||
connected: () => app !== null,
|
||||
call,
|
||||
handle: (msg) => handleRpc(msg, AI_TOOLS, call, "dossier-app"),
|
||||
close: () =>
|
||||
new Promise<void>((done) => {
|
||||
app?.close();
|
||||
server.close(() => done());
|
||||
server.closeAllConnections?.();
|
||||
}),
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user