Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

feat(mcp): add semantic diagram editing

tianma-ifcaa596758064
diff --git a/README.md b/README.md
index 82a335c5..4a4f3d73 100644
--- a/README.md
+++ b/README.md
@@ -233,7 +233,7 @@ Repository file: [docs/openapi.json](docs/openapi.json).
## MCP
-Create an API token in **Profile** -> **MCP settings** and give it to your AI Agent. The Agent can then securely read, organize, and import notes, use `create_diagram_memo` to create editable mind map, flowchart, and architecture diagram notes from semantic graphs with automatic sizing and layout, manage note templates and AI instructions, and connect your notes with tools such as Notion databases and Feishu Bitable—all within your account permissions.
+Create an API token in **Profile** -> **MCP settings** and give it to your AI Agent. The Agent can then securely read, organize, and import notes, use `create_diagram_memo` to create editable mind map, flowchart, and architecture diagram notes from semantic graphs, and safely read or incrementally modify existing diagrams through `get_diagram` and `update_diagram`. EdgeEver manages node sizing and layout by default and only returns geometry when an explicit visual-layout task requests it. The Agent can also manage note templates and AI instructions and connect your notes with tools such as Notion databases and Feishu Bitable—all within your account permissions.
> Let your ideas run free: ask an AI Agent to organize fleeting thoughts, build a personal knowledge graph, create a profile from your notes, or tag them automatically.
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 617aa975..8c60712d 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -231,7 +231,7 @@ https://你的域名/api/openapi.json
## MCP
-在 **个人中心** -> **MCP 设置** 中创建 API Token 并交给 AI Agent,即可让 Agent 在账号授权范围内安全地读取、整理和导入笔记,使用 `create_diagram_memo` 通过语义图数据创建可编辑的思维导图、流程图和架构图笔记,节点尺寸与排版由 EdgeEver 自动生成;同时还可管理笔记模板与 AI 指令,并与 Notion Database、飞书多维表格等工具联动。
+在 **个人中心** -> **MCP 设置** 中创建 API Token 并交给 AI Agent,即可让 Agent 在账号授权范围内安全地读取、整理和导入笔记,使用 `create_diagram_memo` 通过语义图数据创建可编辑的思维导图、流程图和架构图笔记,并通过 `get_diagram` 与 `update_diagram` 安全读取和增量修改已有图表。节点尺寸与排版默认由 EdgeEver 管理,仅在明确的视觉布局任务中按需返回;同时还可管理笔记模板与 AI 指令,并与 Notion Database、飞书多维表格等工具联动。
> 放飞你的想法:让 AI Agent 归纳随手记录的灵感、构建个人知识图谱、根据笔记生成用户画像,或自动为笔记打标签。
diff --git a/apps/api/src/mcp-management-tools.test.mjs b/apps/api/src/mcp-management-tools.test.mjs
index 1d31bd85..cb56b360 100644
--- a/apps/api/src/mcp-management-tools.test.mjs
+++ b/apps/api/src/mcp-management-tools.test.mjs
@@ -101,7 +101,10 @@ describe("MCP template and AI instruction management", () => {
});
expect(created).toMatchObject({ diagramKind: kind, memo: { title: "Generated diagram", tags: ["design"] } });
- const diagram = parseDiagramDocument(created.memo.contentMarkdown);
+ expect(JSON.stringify(created.memo)).not.toContain("edgeever-diagram-v1");
+ expect(created.diagram.nodes[0].layout).toBeUndefined();
+ const stored = sqlite.query("SELECT content_markdown FROM memo_contents WHERE memo_id = ?").get(created.memo.id);
+ const diagram = parseDiagramDocument(stored.content_markdown);
expect(diagram).toMatchObject({ kind, theme: "brand" });
expect(diagram.nodes.map((node) => node.id)).toEqual(nodes.map((node) => node.id));
expect(diagram.nodes.every((node) => Number.isFinite(node.x) && Number.isFinite(node.y))).toBeTrue();
@@ -131,6 +134,94 @@ describe("MCP template and AI instruction management", () => {
})).rejects.toMatchObject({ code: "invalid_params" });
});
+ test("reads semantic diagrams without layout by default and applies revision-safe operations", async () => {
+ const { sqlite, auth, context } = createFixture();
+ sqlite.query("INSERT INTO notebooks (id, workspace_id, name) VALUES (?, ?, ?)")
+ .run("nb_diagrams", "ws_mcp", "Diagrams");
+ const created = await callMcpTool(context, auth, "create_diagram_memo", {
+ notebookId: "nb_diagrams",
+ title: "Architecture",
+ kind: "architecture",
+ nodes: [
+ { id: "system", label: "System", type: "boundary" },
+ { id: "api", label: "API", type: "service", parentId: "system" },
+ { id: "database", label: "Database", type: "database", parentId: "system" },
+ ],
+ edges: [{ source: "api", target: "database", type: "data" }],
+ });
+
+ const semantic = await callMcpTool(context, auth, "get_diagram", { memoId: created.memo.id });
+ expect(semantic.diagram.nodes[0].layout).toBeUndefined();
+ expect(JSON.stringify(semantic)).not.toContain("edgeever-diagram-v1");
+ const genericMemo = await callMcpTool(context, auth, "get_memo", { memoId: created.memo.id });
+ expect(genericMemo.diagram.nodes[0].layout).toBeUndefined();
+ expect(JSON.stringify(genericMemo)).not.toContain("edgeever-diagram-v1");
+ const withLayout = await callMcpTool(context, auth, "get_diagram", { memoId: created.memo.id, includeLayout: true });
+ const apiLayout = withLayout.diagram.nodes.find((node) => node.id === "api").layout;
+ expect(apiLayout).toMatchObject({ x: expect.any(Number), y: expect.any(Number), width: expect.any(Number), height: expect.any(Number) });
+
+ const operations = [
+ { op: "add_node", node: { id: "redis", label: "Redis", type: "database", parentId: "system", resourceIcon: "cache" } },
+ { op: "add_edge", edge: { source: "api", target: "redis", type: "data", label: "cache" } },
+ ];
+ const preview = await callMcpTool(context, auth, "update_diagram", {
+ memoId: created.memo.id,
+ expectedRevision: semantic.memo.revision,
+ operations,
+ dryRun: true,
+ });
+ expect(preview).toMatchObject({ dryRun: true, changes: { addedNodes: 1, addedEdges: 1 } });
+ expect((await callMcpTool(context, auth, "get_diagram", { memoId: created.memo.id })).diagram.nodes)
+ .toHaveLength(3);
+
+ const updated = await callMcpTool(context, auth, "update_diagram", {
+ memoId: created.memo.id,
+ expectedRevision: semantic.memo.revision,
+ operations,
+ });
+ expect(updated.memo.revision).toBe(semantic.memo.revision + 1);
+ expect(updated.diagram.nodes.find((node) => node.id === "redis")).toMatchObject({ type: "database", parentId: "system" });
+ const afterLayout = await callMcpTool(context, auth, "get_diagram", { memoId: created.memo.id, includeLayout: true });
+ expect(afterLayout.diagram.nodes.find((node) => node.id === "api").layout).toEqual(apiLayout);
+
+ await expect(callMcpTool(context, auth, "update_diagram", {
+ memoId: created.memo.id,
+ expectedRevision: semantic.memo.revision,
+ operations: [{ op: "remove_node", nodeId: "redis" }],
+ })).rejects.toMatchObject({ code: "revision_conflict", status: 409 });
+ await expect(callMcpTool(context, auth, "update_memo", {
+ memoId: created.memo.id,
+ contentMarkdown: "plain text",
+ })).rejects.toMatchObject({ code: "diagram_update_required" });
+
+ const stored = sqlite.query("SELECT content_markdown FROM memo_contents WHERE memo_id = ?").get(created.memo.id);
+ expect(parseDiagramDocument(stored.content_markdown).nodes.map((node) => node.id)).toContain("redis");
+ });
+
+ test("keeps mind-map hierarchy edges consistent when a node is reparented", async () => {
+ const { sqlite, auth, context } = createFixture();
+ sqlite.query("INSERT INTO notebooks (id, workspace_id, name) VALUES (?, ?, ?)")
+ .run("nb_diagrams", "ws_mcp", "Diagrams");
+ const created = await callMcpTool(context, auth, "create_diagram_memo", {
+ notebookId: "nb_diagrams",
+ kind: "mind-map",
+ nodes: [
+ { id: "root", label: "Root" },
+ { id: "left", label: "Left", parentId: "root" },
+ { id: "leaf", label: "Leaf", parentId: "left" },
+ ],
+ });
+ const updated = await callMcpTool(context, auth, "update_diagram", {
+ memoId: created.memo.id,
+ expectedRevision: created.memo.revision,
+ operations: [{ op: "update_node", nodeId: "leaf", changes: { parentId: "root" } }],
+ });
+ expect(updated.diagram.nodes.find((node) => node.id === "leaf").parentId).toBe("root");
+ expect(updated.diagram.edges.filter((edge) => edge.target === "leaf")).toMatchObject([
+ { source: "root", target: "leaf" },
+ ]);
+ });
+
test("manages note templates within the authenticated workspace", async () => {
const { sqlite, auth, context } = createFixture();
diff --git a/apps/api/src/mcp-tool-service.ts b/apps/api/src/mcp-tool-service.ts
index 01f2d922..a2aba632 100644
--- a/apps/api/src/mcp-tool-service.ts
+++ b/apps/api/src/mcp-tool-service.ts
@@ -4,9 +4,13 @@ import {
ARCHITECTURE_RESOURCE_ICONS,
TemplateCreateSchema,
TemplateUpdateSchema,
+ docToText,
markdownToDoc,
parseDiagramDocument,
serializeDiagramDocument,
+ stripDiagramDocumentMarker,
+ type DiagramDocument,
+ type DiagramNodeShape,
type MemoDetail,
type MemoSummary,
type MemoUpdateInput,
@@ -197,7 +201,7 @@ const assertMcpMutationAllowed = (environment: Bindings) => {
};
const DIAGRAM_IR_NODE_TYPES = new Set<DiagramIrNodeType>([
- "topic", "process", "decision", "start", "end", "client", "frontend", "service", "database", "storage",
+ "topic", "process", "decision", "start", "end", "terminator", "client", "frontend", "service", "database", "storage",
"queue", "security", "external", "boundary",
]);
const DIAGRAM_EDGE_KINDS = new Set(["dependency", "request", "async", "data"]);
@@ -304,7 +308,7 @@ const parseDiagramMemoIr = (args: Record<string, unknown>): DiagramIr => {
const allowedTypes = ir.kind === "mind-map"
? new Set([undefined, "topic"])
: ir.kind === "flowchart"
- ? new Set([undefined, "process", "decision", "start", "end"])
+ ? new Set([undefined, "process", "decision", "start", "end", "terminator"])
: new Set([undefined, "client", "frontend", "service", "database", "storage", "queue", "security", "external", "boundary"]);
if (!allowedTypes.has(node.type)) {
throw new AppError("invalid_params", `${node.type} is not a valid node type for ${ir.kind}`, 400);
@@ -345,6 +349,267 @@ const parseDiagramMemoIr = (args: Record<string, unknown>): DiagramIr => {
return ir;
};
+const diagramNodeType = (shape: DiagramNodeShape): DiagramIrNodeType => shape;
+
+const diagramSemanticGraph = (document: DiagramDocument, includeLayout = false) => ({
+ kind: document.kind,
+ ...(document.theme ? { theme: document.theme } : {}),
+ nodes: document.nodes.map((node) => ({
+ id: node.id,
+ label: node.label,
+ type: diagramNodeType(node.shape),
+ ...(node.parentId ? { parentId: node.parentId } : {}),
+ ...(node.resourceIcon ? { resourceIcon: node.resourceIcon } : {}),
+ ...(includeLayout ? { layout: { x: node.x, y: node.y, width: node.width, height: node.height } } : {}),
+ })),
+ edges: document.edges.map((edge) => ({
+ id: edge.id,
+ source: edge.source,
+ target: edge.target,
+ ...(edge.label ? { label: edge.label } : {}),
+ ...(edge.kind ? { type: edge.kind } : {}),
+ ...(edge.bidirectional !== undefined ? { bidirectional: edge.bidirectional } : {}),
+ })),
+});
+
+const memoWithoutDiagramPayload = (memo: MemoDetail) => {
+ const contentMarkdown = stripDiagramDocumentMarker(memo.contentMarkdown);
+ const contentJson = markdownToDoc(contentMarkdown);
+ return { ...memo, contentMarkdown, contentJson, contentText: docToText(contentJson) };
+};
+
+type MutableDiagramEdge = ReturnType<typeof diagramSemanticGraph>["edges"][number];
+
+const applyDiagramOperations = async (
+ args: Record<string, unknown>,
+ current: DiagramDocument,
+) => {
+ assertAllowedKeys(args, new Set(["memoId", "expectedRevision", "operations", "dryRun", "reflow"]), "arguments");
+ if (!Array.isArray(args.operations) || args.operations.length < 1 || args.operations.length > 100) {
+ throw new AppError("invalid_params", "operations must include between 1 and 100 items", 400);
+ }
+ if (args.reflow !== undefined && args.reflow !== "preserve" && args.reflow !== "all") {
+ throw new AppError("invalid_params", "reflow must be preserve or all", 400);
+ }
+
+ let nodes: DiagramIr["nodes"] = current.nodes.map((node) => ({
+ id: node.id,
+ label: node.label,
+ type: diagramNodeType(node.shape),
+ ...(node.parentId ? { parentId: node.parentId } : {}),
+ ...(node.resourceIcon ? { resourceIcon: node.resourceIcon } : {}),
+ }));
+ let edges: MutableDiagramEdge[] = diagramSemanticGraph(current).edges;
+ const resizedNodeIds = new Set<string>();
+ const repositionedNodeIds = new Set<string>();
+ const affectedBoundaryIds = new Set<string>();
+ const counts = { addedNodes: 0, updatedNodes: 0, removedNodes: 0, addedEdges: 0, updatedEdges: 0, removedEdges: 0 };
+
+ const requireOperation = (value: unknown, index: number) => {
+ if (!isPlainRecord(value) || typeof value.op !== "string") {
+ throw new AppError("invalid_params", `operations.${index} must be an object with an op`, 400);
+ }
+ return value;
+ };
+ const findNodeIndex = (nodeId: string) => {
+ const index = nodes.findIndex((node) => node.id === nodeId);
+ if (index < 0) throw new AppError("invalid_params", `diagram node ${nodeId} does not exist`, 400);
+ return index;
+ };
+ const findEdgeIndex = (edgeId: string) => {
+ const index = edges.findIndex((edge) => edge.id === edgeId);
+ if (index < 0) throw new AppError("invalid_params", `diagram edge ${edgeId} does not exist`, 400);
+ return index;
+ };
+
+ for (let operationIndex = 0; operationIndex < args.operations.length; operationIndex += 1) {
+ const operation = requireOperation(args.operations[operationIndex], operationIndex);
+ const path = `operations.${operationIndex}`;
+ if (operation.op === "add_node") {
+ assertAllowedKeys(operation, new Set(["op", "node"]), path);
+ const node = parseDiagramNode(operation.node, operationIndex);
+ if (nodes.some((candidate) => candidate.id === node.id)) {
+ throw new AppError("invalid_params", `diagram node ${node.id} already exists`, 400);
+ }
+ nodes.push(node);
+ if (node.parentId) affectedBoundaryIds.add(node.parentId);
+ counts.addedNodes += 1;
+ continue;
+ }
+ if (operation.op === "update_node") {
+ assertAllowedKeys(operation, new Set(["op", "nodeId", "changes"]), path);
+ const nodeId = getRequiredString(operation.nodeId, `${path}.nodeId`);
+ if (!isPlainRecord(operation.changes) || Object.keys(operation.changes).length === 0) {
+ throw new AppError("invalid_params", `${path}.changes must be a non-empty object`, 400);
+ }
+ assertAllowedKeys(operation.changes, new Set(["label", "type", "parentId", "resourceIcon"]), `${path}.changes`);
+ const index = findNodeIndex(nodeId);
+ const previous = nodes[index];
+ const candidate: Record<string, unknown> = { ...previous, ...operation.changes, id: nodeId };
+ if (operation.changes.parentId === null) delete candidate.parentId;
+ if (operation.changes.resourceIcon === null) delete candidate.resourceIcon;
+ const next = parseDiagramNode(candidate, operationIndex);
+ nodes[index] = next;
+ if (operation.changes.label !== undefined || operation.changes.type !== undefined) resizedNodeIds.add(nodeId);
+ if (operation.changes.parentId !== undefined && previous.parentId !== next.parentId) {
+ repositionedNodeIds.add(nodeId);
+ if (previous.parentId) affectedBoundaryIds.add(previous.parentId);
+ if (next.parentId) affectedBoundaryIds.add(next.parentId);
+ }
+ counts.updatedNodes += 1;
+ continue;
+ }
+ if (operation.op === "remove_node") {
+ assertAllowedKeys(operation, new Set(["op", "nodeId", "cascade"]), path);
+ const nodeId = getRequiredString(operation.nodeId, `${path}.nodeId`);
+ findNodeIndex(nodeId);
+ const removalIds = new Set([nodeId]);
+ let changed = true;
+ while (changed) {
+ changed = false;
+ for (const node of nodes) {
+ if (node.parentId && removalIds.has(node.parentId) && !removalIds.has(node.id)) {
+ if (operation.cascade !== true) {
+ throw new AppError("invalid_params", `${nodeId} contains child nodes; set cascade to true to remove them`, 400);
+ }
+ removalIds.add(node.id);
+ changed = true;
+ }
+ }
+ }
+ for (const node of nodes) if (removalIds.has(node.id) && node.parentId) affectedBoundaryIds.add(node.parentId);
+ const priorEdgeCount = edges.length;
+ nodes = nodes.filter((node) => !removalIds.has(node.id));
+ edges = edges.filter((edge) => !removalIds.has(edge.source) && !removalIds.has(edge.target));
+ counts.removedNodes += removalIds.size;
+ counts.removedEdges += priorEdgeCount - edges.length;
+ continue;
+ }
+ if (operation.op === "add_edge") {
+ assertAllowedKeys(operation, new Set(["op", "edge"]), path);
+ if (!isPlainRecord(operation.edge)) throw new AppError("invalid_params", `${path}.edge must be an object`, 400);
+ assertAllowedKeys(operation.edge, new Set([...DIAGRAM_EDGE_KEYS, "id"]), `${path}.edge`);
+ const { id: requestedId, ...edgeInput } = operation.edge;
+ const parsed = parseDiagramEdge(edgeInput, operationIndex);
+ const id = requestedId === undefined ? createId("edge") : getRequiredString(requestedId, `${path}.edge.id`);
+ if (id.length > 100 || edges.some((edge) => edge.id === id)) {
+ throw new AppError("invalid_params", `diagram edge ID ${id} is invalid or already exists`, 400);
+ }
+ edges.push({ id, ...parsed });
+ counts.addedEdges += 1;
+ continue;
+ }
+ if (operation.op === "update_edge") {
+ assertAllowedKeys(operation, new Set(["op", "edgeId", "changes"]), path);
+ const edgeId = getRequiredString(operation.edgeId, `${path}.edgeId`);
+ if (!isPlainRecord(operation.changes) || Object.keys(operation.changes).length === 0) {
+ throw new AppError("invalid_params", `${path}.changes must be a non-empty object`, 400);
+ }
+ assertAllowedKeys(operation.changes, DIAGRAM_EDGE_KEYS, `${path}.changes`);
+ const index = findEdgeIndex(edgeId);
+ const candidate: Record<string, unknown> = { ...edges[index], ...operation.changes };
+ delete candidate.id;
+ if (operation.changes.label === null) delete candidate.label;
+ if (operation.changes.type === null) delete candidate.type;
+ if (operation.changes.bidirectional === null) delete candidate.bidirectional;
+ edges[index] = { id: edgeId, ...parseDiagramEdge(candidate, operationIndex) };
+ counts.updatedEdges += 1;
+ continue;
+ }
+ if (operation.op === "remove_edge") {
+ assertAllowedKeys(operation, new Set(["op", "edgeId"]), path);
+ const edgeId = getRequiredString(operation.edgeId, `${path}.edgeId`);
+ edges.splice(findEdgeIndex(edgeId), 1);
+ counts.removedEdges += 1;
+ continue;
+ }
+ throw new AppError("invalid_params", `${path}.op is not supported`, 400);
+ }
+
+ if (nodes.length < 1) throw new AppError("invalid_params", "a diagram must contain at least one node", 400);
+ if (current.kind === "mind-map") {
+ const priorEdgeCount = edges.length;
+ edges = edges.filter((edge) => !repositionedNodeIds.has(edge.target)
+ || nodes.find((node) => node.id === edge.target)?.parentId === edge.source);
+ counts.removedEdges += priorEdgeCount - edges.length;
+ for (const node of nodes) {
+ if (!node.parentId || edges.some((edge) => edge.source === node.parentId && edge.target === node.id)) continue;
+ edges.push({ id: createId("edge"), source: node.parentId, target: node.id });
+ counts.addedEdges += 1;
+ }
+ }
+ const validatedIr = parseDiagramMemoIr({
+ kind: current.kind,
+ ...(current.theme ? { theme: current.theme } : {}),
+ nodes,
+ edges: edges.map(({ id: _id, ...edge }) => edge),
+ });
+ const { compileDiagramIr } = await import("@edgeever/shared/diagram-layout");
+ const next = compileDiagramIr(validatedIr);
+ next.edges = edges.map((edge) => ({
+ id: edge.id,
+ source: edge.source,
+ target: edge.target,
+ ...(edge.label ? { label: edge.label } : {}),
+ ...(edge.type ? { kind: edge.type } : {}),
+ ...(edge.bidirectional !== undefined ? { bidirectional: edge.bidirectional } : {}),
+ }));
+
+ if (args.reflow !== "all") {
+ const currentById = new Map(current.nodes.map((node) => [node.id, node]));
+ for (const node of next.nodes) {
+ const previous = currentById.get(node.id);
+ if (!previous) continue;
+ const boundaryNeedsLayout = node.shape === "boundary" && affectedBoundaryIds.has(node.id);
+ if (repositionedNodeIds.has(node.id) || boundaryNeedsLayout) continue;
+ node.x = previous.x;
+ node.y = previous.y;
+ if (!resizedNodeIds.has(node.id)) {
+ node.width = previous.width;
+ node.height = previous.height;
+ }
+ }
+ if (current.kind === "architecture" && affectedBoundaryIds.size > 0) {
+ const nodeById = new Map(next.nodes.map((node) => [node.id, node]));
+ for (const boundaryId of [...affectedBoundaryIds]) {
+ let parentId = nodeById.get(boundaryId)?.parentId;
+ while (parentId) {
+ affectedBoundaryIds.add(parentId);
+ parentId = nodeById.get(parentId)?.parentId;
+ }
+ }
+ const depth = (nodeId: string) => {
+ let result = 0;
+ let node = nodeById.get(nodeId);
+ while (node?.parentId) {
+ result += 1;
+ node = nodeById.get(node.parentId);
+ }
+ return result;
+ };
+ for (const boundaryId of [...affectedBoundaryIds].sort((left, right) => depth(right) - depth(left))) {
+ const boundary = nodeById.get(boundaryId);
+ const children = next.nodes.filter((node) => node.parentId === boundaryId);
+ if (!boundary || boundary.shape !== "boundary" || children.length === 0) continue;
+ const left = Math.min(...children.map((node) => node.x)) - 36;
+ const top = Math.min(...children.map((node) => node.y)) - 56;
+ const right = Math.max(...children.map((node) => node.x + node.width)) + 36;
+ const bottom = Math.max(...children.map((node) => node.y + node.height)) + 36;
+ boundary.x = left;
+ boundary.y = top;
+ boundary.width = Math.max(260, right - left);
+ boundary.height = Math.max(180, bottom - top);
+ }
+ }
+ }
+
+ const contentMarkdown = serializeDiagramDocument(next);
+ if (!parseDiagramDocument(contentMarkdown)) {
+ throw new AppError("invalid_params", "The diagram operations produced an invalid document", 400);
+ }
+ return { document: next, contentMarkdown, changes: counts };
+};
+
export const callMcpTool = async (
c: AppContext,
auth: AuthContext,
@@ -411,7 +676,10 @@ export const callMcpTool = async (
throw new Error("Memo not found");
}
- return { memo };
+ const diagram = parseDiagramDocument(memo.contentMarkdown);
+ return diagram
+ ? { memo: memoWithoutDiagramPayload(memo), diagram: diagramSemanticGraph(diagram) }
+ : { memo };
}
case "create_memo": {
assertScope(auth, "write:memos");
@@ -446,7 +714,58 @@ export const callMcpTool = async (
tags: getOptionalStringArray(args.tags),
}, getAuditActor(c), getActorLabel(c));
- return { memo, diagramKind: document.kind };
+ return {
+ memo: memoWithoutDiagramPayload(memo),
+ diagramKind: document.kind,
+ diagram: diagramSemanticGraph(document),
+ };
+ }
+ case "get_diagram": {
+ assertScope(auth, "read:memos");
+ const memoId = getRequiredString(args.memoId, "memoId");
+ const memo = await getMemoDetail(c.env.storage.db, auth.workspaceId, memoId);
+ if (!memo) throw new AppError("not_found", "Memo not found", 404);
+ const document = parseDiagramDocument(memo.contentMarkdown);
+ if (!document) throw new AppError("not_diagram", "Memo is not an editable diagram", 400);
+ return {
+ memo: { id: memo.id, title: memo.title, revision: memo.revision, updatedAt: memo.updatedAt },
+ diagram: diagramSemanticGraph(document, args.includeLayout === true),
+ };
+ }
+ case "update_diagram": {
+ assertScope(auth, "write:memos");
+ const memoId = getRequiredString(args.memoId, "memoId");
+ if (typeof args.expectedRevision !== "number" || !Number.isInteger(args.expectedRevision) || args.expectedRevision < 0) {
+ throw new AppError("invalid_params", "expectedRevision must be a non-negative integer", 400);
+ }
+ const memo = await getMemoDetail(c.env.storage.db, auth.workspaceId, memoId);
+ if (!memo) throw new AppError("not_found", "Memo not found", 404);
+ if (memo.revision !== args.expectedRevision) {
+ throw new AppError("revision_conflict", "Diagram was updated elsewhere. Read it again before applying operations.", 409);
+ }
+ const current = parseDiagramDocument(memo.contentMarkdown);
+ if (!current) throw new AppError("not_diagram", "Memo is not an editable diagram", 400);
+ const mutation = await applyDiagramOperations(args, current);
+ if (args.dryRun === true) {
+ return {
+ dryRun: true,
+ memo: { id: memo.id, title: memo.title, revision: memo.revision, updatedAt: memo.updatedAt },
+ changes: mutation.changes,
+ diagram: diagramSemanticGraph(mutation.document),
+ };
+ }
+ const result = await updateMemoRecord(c.env.storage.db, auth.workspaceId, memoId, {
+ expectedRevision: args.expectedRevision,
+ contentMarkdown: mutation.contentMarkdown,
+ }, getAuditActor(c), getActorLabel(c));
+ if (result.error !== undefined) {
+ throw new AppError(result.error, result.message, result.status ?? 400);
+ }
+ return {
+ memo: { id: result.memo.id, title: result.memo.title, revision: result.memo.revision, updatedAt: result.memo.updatedAt },
+ changes: mutation.changes,
+ diagram: diagramSemanticGraph(mutation.document),
+ };
}
case "import_memos": {
assertScope(auth, "write:memos");
@@ -462,6 +781,16 @@ export const callMcpTool = async (
case "update_memo": {
assertScope(auth, "write:memos");
const memoId = getRequiredString(args.memoId, "memoId");
+ if (args.contentMarkdown !== undefined) {
+ const existing = await getMemoDetail(c.env.storage.db, auth.workspaceId, memoId);
+ if (existing && parseDiagramDocument(existing.contentMarkdown)) {
+ throw new AppError(
+ "diagram_update_required",
+ "Diagram content cannot be replaced through update_memo. Use update_diagram for semantic changes.",
+ 400,
+ );
+ }
+ }
const actor = getAuditActor(c);
const actorLabel = getActorLabel(c);
const result = await updateMemoRecord(
diff --git a/apps/api/src/mcp-tools.test.mjs b/apps/api/src/mcp-tools.test.mjs
index 7197d2bc..b5d4aea8 100644
--- a/apps/api/src/mcp-tools.test.mjs
+++ b/apps/api/src/mcp-tools.test.mjs
@@ -52,6 +52,24 @@ describe("MCP tool catalog", () => {
});
expect(byName.get("create_diagram_memo")?.inputSchema.properties.nodes.items.properties.x).toBeUndefined();
expect(byName.get("create_diagram_memo")?.inputSchema.properties.nodes.items.properties.width).toBeUndefined();
+ expect(byName.get("get_diagram")?.annotations).toMatchObject({
+ readOnlyHint: true,
+ destructiveHint: false,
+ idempotentHint: true,
+ });
+ expect(byName.get("get_diagram")?.inputSchema).toMatchObject({
+ required: ["memoId"],
+ properties: { includeLayout: { type: "boolean" } },
+ });
+ expect(byName.get("update_diagram")?.annotations).toMatchObject({
+ readOnlyHint: false,
+ destructiveHint: true,
+ idempotentHint: false,
+ });
+ expect(byName.get("update_diagram")?.inputSchema).toMatchObject({
+ required: ["memoId", "expectedRevision", "operations"],
+ properties: { operations: { minItems: 1, maxItems: 100 } },
+ });
expect(byName.get("rename_notebook")?.annotations).toMatchObject({
readOnlyHint: false,
destructiveHint: false,
diff --git a/apps/api/src/mcp-tools.ts b/apps/api/src/mcp-tools.ts
index 17f7489c..be958d4e 100644
--- a/apps/api/src/mcp-tools.ts
+++ b/apps/api/src/mcp-tools.ts
@@ -6,6 +6,7 @@ const DIAGRAM_IR_NODE_TYPES = [
"decision",
"start",
"end",
+ "terminator",
"client",
"frontend",
"service",
@@ -150,6 +151,113 @@ const MCP_TOOL_DEFINITIONS = [
},
},
},
+ {
+ name: "get_diagram",
+ description:
+ "Read an editable diagram as a semantic graph. Coordinates and dimensions are omitted by default; set includeLayout only for an explicit visual-layout task.",
+ inputSchema: {
+ type: "object",
+ required: ["memoId"],
+ additionalProperties: false,
+ properties: {
+ memoId: { type: "string", minLength: 1 },
+ includeLayout: { type: "boolean", description: "Include node coordinates and dimensions. Defaults to false." },
+ },
+ },
+ },
+ {
+ name: "update_diagram",
+ description:
+ "Apply validated semantic operations to an existing diagram while preserving unaffected authored layout. Use expectedRevision to prevent concurrent overwrites. Set reflow to all only when the user explicitly wants a complete automatic layout.",
+ inputSchema: {
+ type: "object",
+ required: ["memoId", "expectedRevision", "operations"],
+ additionalProperties: false,
+ properties: {
+ memoId: { type: "string", minLength: 1 },
+ expectedRevision: { type: "integer", minimum: 0 },
+ dryRun: { type: "boolean" },
+ reflow: { type: "string", enum: ["preserve", "all"] },
+ operations: {
+ type: "array",
+ minItems: 1,
+ maxItems: 100,
+ items: {
+ oneOf: [
+ {
+ type: "object", required: ["op", "node"], additionalProperties: false,
+ properties: {
+ op: { const: "add_node" },
+ node: {
+ type: "object", required: ["id", "label"], additionalProperties: false,
+ properties: {
+ id: { type: "string", minLength: 1, maxLength: 100 },
+ label: { type: "string", maxLength: 500 },
+ type: { type: "string", enum: [...DIAGRAM_IR_NODE_TYPES] },
+ parentId: { type: "string", minLength: 1, maxLength: 100 },
+ resourceIcon: { type: "string", enum: [...ARCHITECTURE_RESOURCE_ICONS] },
+ },
+ },
+ },
+ },
+ {
+ type: "object", required: ["op", "nodeId", "changes"], additionalProperties: false,
+ properties: {
+ op: { const: "update_node" }, nodeId: { type: "string", minLength: 1 },
+ changes: {
+ type: "object", minProperties: 1, additionalProperties: false,
+ properties: {
+ label: { type: "string", maxLength: 500 },
+ type: { type: "string", enum: [...DIAGRAM_IR_NODE_TYPES] },
+ parentId: { type: ["string", "null"], maxLength: 100 },
+ resourceIcon: { type: ["string", "null"], enum: [...ARCHITECTURE_RESOURCE_ICONS, null] },
+ },
+ },
+ },
+ },
+ {
+ type: "object", required: ["op", "nodeId"], additionalProperties: false,
+ properties: { op: { const: "remove_node" }, nodeId: { type: "string", minLength: 1 }, cascade: { type: "boolean" } },
+ },
+ {
+ type: "object", required: ["op", "edge"], additionalProperties: false,
+ properties: {
+ op: { const: "add_edge" },
+ edge: {
+ type: "object", required: ["source", "target"], additionalProperties: false,
+ properties: {
+ id: { type: "string", minLength: 1, maxLength: 100 },
+ source: { type: "string", minLength: 1, maxLength: 100 }, target: { type: "string", minLength: 1, maxLength: 100 },
+ label: { type: "string", maxLength: 500 }, type: { type: "string", enum: ["dependency", "request", "async", "data"] },
+ bidirectional: { type: "boolean" },
+ },
+ },
+ },
+ },
+ {
+ type: "object", required: ["op", "edgeId", "changes"], additionalProperties: false,
+ properties: {
+ op: { const: "update_edge" }, edgeId: { type: "string", minLength: 1 },
+ changes: {
+ type: "object", minProperties: 1, additionalProperties: false,
+ properties: {
+ source: { type: "string", minLength: 1, maxLength: 100 }, target: { type: "string", minLength: 1, maxLength: 100 },
+ label: { type: ["string", "null"], maxLength: 500 }, type: { type: ["string", "null"], enum: ["dependency", "request", "async", "data", null] },
+ bidirectional: { type: ["boolean", "null"] },
+ },
+ },
+ },
+ },
+ {
+ type: "object", required: ["op", "edgeId"], additionalProperties: false,
+ properties: { op: { const: "remove_edge" }, edgeId: { type: "string", minLength: 1 } },
+ },
+ ],
+ },
+ },
+ },
+ },
+ },
{
name: "import_memos",
description:
@@ -702,6 +810,7 @@ const READ_ONLY_MCP_TOOLS = new Set([
"search_memos",
"list_memos",
"get_memo",
+ "get_diagram",
"list_memo_resources",
"list_resources",
"list_memo_revisions",
diff --git a/docs/visual-diagram-notes.md b/docs/visual-diagram-notes.md
index 7927bcef..0d3de5d6 100644
--- a/docs/visual-diagram-notes.md
+++ b/docs/visual-diagram-notes.md
@@ -78,9 +78,11 @@ The native apps currently hide regular rich-text editing, double-tap editing, an
For MCP and AI, the IR is a positive capability and the foundation of a stable tool protocol. An AI can work with semantic IR instead of producing X6 internals, SVG, or an entire Mermaid document. It can therefore perform a local request such as “add a Redis cache between the API and database” while preserving the user's other nodes and layout decisions.
-The `create_diagram_memo` MCP tool accepts this semantic creation IR: node identities, labels, semantic types, containment, and connections. EdgeEver generates edge identities, node dimensions, coordinates, deterministic layout, and architecture boundary geometry before compiling the result into the persisted `DiagramDocument`. An optional layout direction is a hint rather than authored geometry.
+The `create_diagram_memo` MCP tool accepts this semantic creation IR: node identities, labels, semantic types, containment, and connections. EdgeEver generates edge identities, node dimensions, coordinates, deterministic layout, and architecture boundary geometry before compiling the result into the persisted `DiagramDocument`. An optional layout direction is a hint rather than authored geometry. Tool results likewise return only the semantic graph instead of the encoded persistence payload.
-MCP should expose small, explicit operations such as reading a diagram, adding or updating a node, connecting components, moving a node into a boundary, validating changes, and applying layout. It should not rely solely on a high-risk `replace_diagram_ir` operation. The recommended flow is:
+`get_diagram` returns only the semantic graph and memo revision by default, without coordinates or dimensions; node geometry is included only when `includeLayout` is explicitly set. `update_diagram` accepts incremental operations that add, update, or remove nodes and edges, uses `expectedRevision` to prevent concurrent overwrites, supports `dryRun` previews, and preserves unaffected authored layout by default. The generic `update_memo` tool cannot replace diagram content, preventing callers from bypassing diagram validation.
+
+MCP exposes small, explicit operations for reading a diagram, adding or updating a node, connecting components, moving a node into a boundary, validating changes, and applying layout instead of a high-risk `replace_diagram_ir`. The recommended flow is:
```text
Read IR
diff --git a/docs/visual-diagram-notes.zh-CN.md b/docs/visual-diagram-notes.zh-CN.md
index 5a6d8f6d..79172be1 100644
--- a/docs/visual-diagram-notes.zh-CN.md
+++ b/docs/visual-diagram-notes.zh-CN.md
@@ -78,9 +78,11 @@ EdgeEver 已经围绕 AntV X6 建立了选择、拖拽、缩放、连线、撤
对于 MCP 和 AI,IR 是正向能力,也是稳定的工具协议基础。AI 面向语义化 IR 工作,不必生成 X6 内部配置、SVG 或整张 Mermaid 源码,因此可以理解和执行“在 API 与数据库之间增加 Redis 缓存”这类局部修改,同时保留用户已经调整好的其他节点和布局。
-`create_diagram_memo` MCP 工具已接收这层语义创建 IR:节点标识、名称、语义类型、容器关系与连接关系。EdgeEver 会生成连线标识、节点尺寸、坐标、确定性布局和架构边界几何信息,再编译为持久化 `DiagramDocument`。可选的布局方向只是提示,不是由 Agent 编排的几何数据。
+`create_diagram_memo` MCP 工具接收这层语义创建 IR:节点标识、名称、语义类型、容器关系与连接关系。EdgeEver 会生成连线标识、节点尺寸、坐标、确定性布局和架构边界几何信息,再编译为持久化 `DiagramDocument`。可选的布局方向只是提示,不是由 Agent 编排的几何数据。工具结果也只返回语义图,不返回编码后的持久化载荷。
-MCP 应优先暴露小而明确的操作,例如读取图表、增加或更新节点、连接组件、移动到系统边界、校验变更和应用布局,而不是只提供一个高风险的 `replace_diagram_ir`。推荐流程是:
+`get_diagram` 默认只返回语义图和笔记 revision,不包含坐标与尺寸;只有明确设置 `includeLayout` 时才附带节点几何信息。`update_diagram` 接收增加、更新、删除节点或连线的增量操作,使用 `expectedRevision` 防止并发覆盖,支持 `dryRun` 预览,并默认保留未受影响节点的已有布局。通用的 `update_memo` 不允许直接覆盖图表正文,避免绕过图表校验。
+
+MCP 暴露小而明确的操作,包括读取图表、增加或更新节点、连接组件、移动到系统边界、校验变更和应用布局,而不是提供高风险的 `replace_diagram_ir`。推荐流程是:
```text
读取 IR
diff --git a/packages/shared/src/diagram-layout.ts b/packages/shared/src/diagram-layout.ts
index cc94f084..16e95b43 100644
--- a/packages/shared/src/diagram-layout.ts
+++ b/packages/shared/src/diagram-layout.ts
@@ -45,6 +45,7 @@ export type DiagramIrNodeType =
| "decision"
| "start"
| "end"
+ | "terminator"
| "client"
| "frontend"
| "service"
@@ -393,7 +394,7 @@ const computeArchitectureLayout = (document: DiagramDocument, options: DiagramLa
const irNodeShape = (kind: DiagramKind, type: DiagramIrNodeType | undefined): DiagramNodeShape => {
if (kind === "mind-map") return "topic";
- if (kind === "flowchart") return type === "decision" ? "decision" : type === "start" || type === "end" ? "terminator" : "process";
+ if (kind === "flowchart") return type === "decision" ? "decision" : type === "start" || type === "end" || type === "terminator" ? "terminator" : "process";
return (type ?? "service") as DiagramNodeShape;
};