[9] MCP-Server (stdio) im dossier-cli: project_info, query, render_svg, apply_ops (validiert, atomar), validate

This commit is contained in:
karim committed 2026-10-27 19:56:28 +01:00
1 parent c6e8714f60
commit 346798eee6
3 files changed
+232 -3

No files matched your search

+42 -3
View File
@@ -21,9 +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");
const rel = [...src.matchAll(/from\s+"(\.[^"]+)"/g)].map((m) => m[1]);
expect(rel.every((r) => r === "../core")).toBe(true);
expect(readdirSync(join(process.cwd(), "src", "cli")).filter((f) => statSync(join(process.cwd(), "src", "cli", f)).isFile() && f.endsWith(".ts") && !f.endsWith(".test.ts"))).toEqual(["main.ts"]);
for (const f of ["main.ts", "mcp.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(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"]);
});
it("info, validate, migrate", async () => {
@@ -68,3 +72,38 @@ describe("dossier-cli", () => {
expect(await run([])).toBe(2);
});
});
import { handleMessage } from "./mcp";
describe("MCP-Server", () => {
it("initialize, tools/list, project_info, apply_ops mit Validierung", async () => {
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"]);
expect(await handleMessage(file, { jsonrpc: "2.0", method: "notifications/initialized" })).toBeNull();
const call = async (name: string, args: Record<string, unknown>) =>
((await handleMessage(file, { jsonrpc: "2.0", id: 3, method: "tools/call", params: { name, arguments: args } })) as {
result: { content: Array<{ text: string }>; isError: boolean };
}).result;
const info = await call("project_info", {});
expect(JSON.parse(info.content[0].text).counts.walls).toBe(sampleProject.walls.length);
const w = sampleProject.walls[0];
// gültige Änderung → Datei geändert
const ok = await call("apply_ops", { ops: [{ kind: "replace", collection: "walls", entity: { ...w, height: 9 } }] });
expect(ok.isError).toBe(false);
const q = await call("query", { collection: "walls", id: w.id });
expect(JSON.parse(q.content[0].text)[0].height).toBe(9);
// ungültig (NaN → JSON-null ist nicht NaN; Doppel-id wird geprüft) → abgelehnt, Datei unverändert
const bad = await call("apply_ops", { ops: [{ kind: "add", collection: "walls", items: [{ ...w }] }] });
expect(bad.isError).toBe(true);
const q2 = await call("query", { collection: "walls", limit: 1000 });
expect(JSON.parse(q2.content[0].text).length).toBe(sampleProject.walls.length);
expect((await call("validate", {})).isError).toBe(false);
expect((await call("render_svg", { kind: "floor" })).content[0].text).toContain("<svg");
expect((await handleMessage(file, { jsonrpc: "2.0", id: 9, method: "gibts/nicht" })) as { error: { code: number } }).toMatchObject({ error: { code: -32601 } });
}, 30_000);
});
+5
View File
@@ -10,6 +10,7 @@
// dossier-cli <projekt.obp> elevation <Name> [--out ansicht.svg]
// dossier-cli <projekt.obp> dxf|ifc|step|obj|stl|schedule [--level EG] [--out datei]
// dossier-cli <projekt.obp> model3d [--out modell.json] 3D-Modell fürs Headless-Rendern (render_png)
// dossier-cli <projekt.obp> mcp MCP-Server (stdio): project_info, query, render_svg, apply_ops, validate
// dossier-cli <projekt.obp> bench [--runs 10] Zeitprofil der Ableitungen (ms je Aufruf)
//
// WASM-Pakete (src/engine/pkg*) werden aus DOSSIER_WASM_DIR bzw. `<repo>/src/engine` gelesen.
@@ -39,6 +40,7 @@ import {
validateProject,
} from "../core";
import type { Project } from "../core";
import { serveStdio } from "./mcp";
type Args = { positional: string[]; flags: Map<string, string> };
@@ -206,6 +208,9 @@ export async function run(argv: string[]): Promise<number> {
out(args, r.text, `${project.name || "projekt"}.stp`);
return 0;
}
case "mcp":
await serveStdio(file);
return 0;
case "model3d":
out(args, JSON.stringify(projectToModel3d(project)), `${project.name || "projekt"}.model3d.json`);
return 0;
+185
View File
@@ -0,0 +1,185 @@
// 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`.
// 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,
} from "../core";
import type { CoreOp, Project } from "../core";
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 });
function load(file: string): Project {
const r = parseProjectFile(readFileSync(file, "utf8"));
if (!r.ok) throw new Error(r.error);
return r.project;
}
function save(file: string, p: Project): void {
const tmp = `${file}.tmp`;
writeFileSync(tmp, serializeProject(p));
renameSync(tmp, file); // atomar
}
export async function callTool(file: string, name: string, args: Record<string, unknown>) {
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);
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);
const next = applyOps(project, ops);
const problems = validateOps(next, ops, project);
if (problems.length) return text(`Abgelehnt, nichts geschrieben: ${problems.join("; ")}`, true);
save(file, next);
return text(`ok: ${ops.length} Op(s) angewendet und gespeichert`);
}
case "validate": {
const problems = validateProject(project);
return text(problems.length ? problems.join("\n") : "ok", problems.length > 0);
}
default:
return text(`unbekanntes Werkzeug: ${name}`, true);
}
}
/** Behandelt EINE JSON-RPC-Nachricht; `null` = keine Antwort (Notification). */
export async function handleMessage(file: string, msg: Rpc): 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)
switch (msg.method) {
case "initialize":
return reply({
protocolVersion: "2024-11-05",
capabilities: { tools: {} },
serverInfo: { name: "dossier", version: "0.1.0" },
});
case "ping":
return reply({});
case "tools/list":
return reply({ tools: TOOLS });
case "tools/call": {
const p = msg.params ?? {};
try {
return reply(await callTool(file, String(p.name), (p.arguments ?? {}) as Record<string, unknown>));
} catch (e) {
return reply(text(e instanceof Error ? e.message : String(e), true));
}
}
default:
return error(-32601, `Methode nicht gefunden: ${msg.method}`);
}
}
/** stdio-Schleife. */
export async function serveStdio(file: string): Promise<void> {
let buf = "";
process.stdin.setEncoding("utf8");
for await (const chunk of process.stdin) {
buf += chunk;
let nl: number;
while ((nl = buf.indexOf("\n")) >= 0) {
const line = buf.slice(0, nl).trim();
buf = buf.slice(nl + 1);
if (!line) continue;
let msg: Rpc;
try {
msg = JSON.parse(line) as Rpc;
} catch {
process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } }) + "\n");
continue;
}
const res = await handleMessage(file, msg);
if (res) process.stdout.write(JSON.stringify(res) + "\n");
}
}
}