From 786cecef9a80926752552d417e9720c207f4221f Mon Sep 17 00:00:00 2001 From: Victor Freitas Date: Sun, 1 Nov 2026 18:26:13 -0300 Subject: [PATCH] feat(schematic): net ports, hierarchical sheet connectors and multi-bit bus mutations (Phase 5.2) --- docs/tools.md | 72 +- extension/src/handlers/actionHandlers.ts | 7 + .../src/handlers/schematicHandlers.test.ts | 30 + extension/src/handlers/schematicHandlers.ts | 4 +- extension/src/identity.ts | 13 + extension/src/index.ts | 3 + .../schematicPortBusMutations.test.ts | 480 ++++++ .../src/mutation/schematicPortBusMutations.ts | 1339 +++++++++++++++++ src/mcp/server.test.ts | 5 +- src/mcp/tools/schematicMutationTools.test.ts | 97 ++ src/mcp/tools/schematicMutationTools.ts | 159 ++ src/mcp/tools/schematicTools.test.ts | 42 +- src/mcp/tools/schematicTools.ts | 19 + 13 files changed, 2262 insertions(+), 8 deletions(-) create mode 100644 extension/src/mutation/schematicPortBusMutations.test.ts create mode 100644 extension/src/mutation/schematicPortBusMutations.ts diff --git a/docs/tools.md b/docs/tools.md index b5a3b90..ee606dd 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -1,6 +1,6 @@ # Tools Reference -EasyEDA Pro MCP exposes **65 tools** across 8 categories. All inspection, tracing, navigation, and export tools are read-only (`readOnlyHint: true`). +EasyEDA Pro MCP exposes **68 tools** across 8 categories. All inspection, tracing, navigation, and export tools are read-only (`readOnlyHint: true`). ## Tool Catalog @@ -8,10 +8,10 @@ EasyEDA Pro MCP exposes **65 tools** across 8 categories. All inspection, tracin - [`easyeda_doctor`](#easyeda_doctor) · [`easyeda_live_status`](#easyeda_live_status) · [`easyeda_get_context`](#easyeda_get_context) · [`easyeda_get_selection`](#easyeda_get_selection) - **[Document Management & Canvas View](#document-management-canvas-view)** (3 tools) - [`easyeda_list_documents`](#easyeda_list_documents) · [`easyeda_open_document`](#easyeda_open_document) · [`easyeda_render_document_view`](#easyeda_render_document_view) -- **[Schematic Mutations & Lifecycle](#schematic-mutations-lifecycle)** (3 tools) - - [`easyeda_prepare_schematic_component`](#easyeda_prepare_schematic_component) · [`easyeda_prepare_schematic_wire`](#easyeda_prepare_schematic_wire) · [`easyeda_get_mutation_result`](#easyeda_get_mutation_result) -- **[Search & Schematic Inspection](#search-schematic-inspection)** (7 tools) - - [`easyeda_schematic_snapshot`](#easyeda_schematic_snapshot) · [`easyeda_get_schematic_nets`](#easyeda_get_schematic_nets) · [`easyeda_list_schematic_components`](#easyeda_list_schematic_components) · [`easyeda_get_component_pins`](#easyeda_get_component_pins) · [`easyeda_find_component`](#easyeda_find_component) · [`easyeda_find_net`](#easyeda_find_net) · [`easyeda_search_library`](#easyeda_search_library) +- **[Schematic Mutations & Lifecycle](#schematic-mutations-lifecycle)** (5 tools) + - [`easyeda_prepare_schematic_component`](#easyeda_prepare_schematic_component) · [`easyeda_prepare_schematic_wire`](#easyeda_prepare_schematic_wire) · [`easyeda_prepare_schematic_port`](#easyeda_prepare_schematic_port) · [`easyeda_prepare_schematic_bus`](#easyeda_prepare_schematic_bus) · [`easyeda_get_mutation_result`](#easyeda_get_mutation_result) +- **[Search & Schematic Inspection](#search-schematic-inspection)** (8 tools) + - [`easyeda_schematic_snapshot`](#easyeda_schematic_snapshot) · [`easyeda_get_schematic_nets`](#easyeda_get_schematic_nets) · [`easyeda_get_schematic_ports_buses`](#easyeda_get_schematic_ports_buses) · [`easyeda_list_schematic_components`](#easyeda_list_schematic_components) · [`easyeda_get_component_pins`](#easyeda_get_component_pins) · [`easyeda_find_component`](#easyeda_find_component) · [`easyeda_find_net`](#easyeda_find_net) · [`easyeda_search_library`](#easyeda_search_library) - **[Circuit Tracing & Verification](#circuit-tracing-verification)** (6 tools) - [`easyeda_run_schematic_erc`](#easyeda_run_schematic_erc) · [`easyeda_trace_net`](#easyeda_trace_net) · [`easyeda_trace_component`](#easyeda_trace_component) · [`easyeda_find_unconnected_pins`](#easyeda_find_unconnected_pins) · [`easyeda_validate_schematic_area`](#easyeda_validate_schematic_area) · [`easyeda_verify_connections`](#easyeda_verify_connections) - **[PCB Layout & DRC Rules](#pcb-layout-drc-rules)** (30 tools) @@ -170,6 +170,52 @@ Prepares a typed schematic wire or net label mutation (`createWire`, `modifyWire --- +### `easyeda_prepare_schematic_port` + +**Scope:** Editor RPC (`readOnlyHint: true`, `idempotentHint: false`, default timeout: `30000` ms) + +Prepares a typed schematic net port (hierarchical sheet or global connector) mutation (`createPort`, `modifyPort`, `deletePort`) with port type normalization (`input`, `output`, `bidirectional`, `unspecified`), coordinate validation, preview diff, and exact confirmation phrase. Does not modify the schematic until confirmed via `easyeda_confirmed_action`. + +**Parameters:** +- **`action`** (`string`, **required**, enum: `createPort`, `modifyPort`, `deletePort`): Port mutation action to perform. +- **`name`** (`string`, _optional_): Net name assigned to the port (e.g. `'TXD'`, `'CLK'`, `'RESET'`). Required for `createPort`. +- **`portType`** (`string`, _optional_, enum: `input`, `output`, `bidirectional`, `unspecified`): Port signal direction. +- **`x`** (`number`, _optional_): X coordinate for port placement. Required for `createPort`. +- **`y`** (`number`, _optional_): Y coordinate for port placement. Required for `createPort`. +- **`rotation`** (`number`, _optional_, default: `0`): Rotation angle in degrees (`0`, `90`, `180`, `270`). +- **`color`** (`string`, _optional_): Optional color hex or name string. +- **`portId`** (`string`, _optional_): Target port primitiveId for `modifyPort` or `deletePort`. +- **`target`** (`object`, _optional_): Expected document target specification. +- **`timeoutMs`** (`number`, _optional_, default: `30000`): RPC timeout in ms. + +--- + +### `easyeda_prepare_schematic_bus` + +**Scope:** Editor RPC (`readOnlyHint: true`, `idempotentHint: false`, default timeout: `30000` ms) + +Prepares a multi-bit bus polyline or diagonal bus entry tap mutation (`createBus`, `modifyBus`, `deleteBus`, `createBusEntry`, `deleteBusEntry`) with syntax parsing (`NAME[start..end]`, `NAME[start:end]`, `NAME[A,B,C]`), coordinate validation, connectivity diagnostics, preview diff, and exact confirmation phrase. Does not modify the schematic until confirmed via `easyeda_confirmed_action`. + +**Parameters:** +- **`action`** (`string`, **required**, enum: `createBus`, `modifyBus`, `deleteBus`, `createBusEntry`, `deleteBusEntry`): Bus or bus entry action to perform. +- **`name`** (`string`, _optional_): Bus name with syntax, e.g. `'DATA[0..7]'` or `'ADDR[15:0]'`. Required for `createBus`. +- **`coordinates`** (`array of numbers`, _optional_): Flat polyline coordinates `[x1, y1, x2, y2, ...]` (at least 2 points / 4 numbers) for bus polyline. +- **`lineWidth`** (`number`, _optional_): Bus stroke width. +- **`color`** (`string`, _optional_): Bus stroke color string. +- **`busId`** (`string`, _optional_): Target bus primitive ID for `modifyBus`, `deleteBus`, or attaching a bus entry. +- **`entryId`** (`string`, _optional_): Target bus entry primitive ID for `deleteBusEntry`. +- **`startX`** (`number`, _optional_): Start X coordinate for bus entry tap. +- **`startY`** (`number`, _optional_): Start Y coordinate for bus entry tap. +- **`endX`** (`number`, _optional_): End X coordinate for bus entry tap. +- **`endY`** (`number`, _optional_): End Y coordinate for bus entry tap. +- **`rotation`** (`number`, _optional_): Rotation angle for bus entry tap. +- **`net`** (`string`, _optional_): Net name for tapped signal (e.g. `'DATA0'`). Validated against parent bus signals. +- **`wireId`** (`string`, _optional_): Primitive ID of wire tapped by bus entry. +- **`target`** (`object`, _optional_): Expected document target specification. +- **`timeoutMs`** (`number`, _optional_, default: `30000`): RPC timeout in ms. + +--- + ### `easyeda_get_mutation_result` **Scope:** Editor RPC (`readOnlyHint: true`, `idempotentHint: true`, default timeout: `10000` ms) @@ -213,6 +259,22 @@ Queries native schematic nets from EasyEDA Pro per-sheet or project-wide via `ed --- +### `easyeda_get_schematic_ports_buses` + +**Scope:** Schematic RPC (`readOnlyHint: true`, `idempotentHint: true`, default timeout: `15000` ms) + +Inspects net ports (hierarchical/sheet connectors and global net flags), multi-bit buses (`sch_PrimitiveBus`), and diagonal bus entry taps (`sch_PrimitiveBusEntry`) in the active schematic. Parses bus name syntax (`NAME[start..end]`, `NAME[start:end]`, `NAME[A,B,C]`), expands signal sets, checks connectivity distances, and flags diagnostics for dangling taps, bus signal mismatches, and conflicting port directions. + +**Parameters:** +- **`includePorts`** (`boolean`, _optional_, default: `true`): Whether to include net ports. +- **`includeBuses`** (`boolean`, _optional_, default: `true`): Whether to include multi-bit buses. +- **`includeBusEntries`** (`boolean`, _optional_, default: `true`): Whether to include bus entry taps. +- **`includeRaw`** (`boolean`, _optional_, default: `false`): Include raw primitive records. +- **`target`** (`object`, _optional_): Expected active schematic target to guard against document drift. +- **`timeoutMs`** (`number`, _optional_, default: `15000`): RPC timeout in ms. + +--- + ### `easyeda_list_schematic_components` **Scope:** Schematic RPC (`readOnlyHint: true`, default timeout: `30000` ms) diff --git a/extension/src/handlers/actionHandlers.ts b/extension/src/handlers/actionHandlers.ts index 70ff031..ffab90d 100644 --- a/extension/src/handlers/actionHandlers.ts +++ b/extension/src/handlers/actionHandlers.ts @@ -15,6 +15,7 @@ import { } from "../mutation/pcbRoutingMutations.js"; import { executePcbTrackViaMutation } from "../mutation/pcbTrackViaMutations.js"; import { executeSchematicComponentMutation } from "../mutation/schematicComponentMutations.js"; +import { executeSchematicBusMutation, executeSchematicPortMutation } from "../mutation/schematicPortBusMutations.js"; import { executeSchematicWireMutation } from "../mutation/schematicWireMutations.js"; import type { EasyEdaApi, RpcHandler } from "../types.js"; @@ -42,6 +43,12 @@ export function createActionHandlers( let res: { executed: boolean; readback: Record }; if (["createWire", "modifyWire", "deleteWire", "addNetLabel"].includes(record.action)) { res = await executeSchematicWireMutation(record, api); + } else if (["createPort", "modifyPort", "deletePort"].includes(record.action)) { + res = await executeSchematicPortMutation(record, api); + } else if ( + ["createBus", "modifyBus", "deleteBus", "createBusEntry", "deleteBusEntry"].includes(record.action) + ) { + res = await executeSchematicBusMutation(record, api); } else { res = await executeSchematicComponentMutation(record, api); } diff --git a/extension/src/handlers/schematicHandlers.test.ts b/extension/src/handlers/schematicHandlers.test.ts index 633cb76..1de2ca6 100644 --- a/extension/src/handlers/schematicHandlers.test.ts +++ b/extension/src/handlers/schematicHandlers.test.ts @@ -323,4 +323,34 @@ describe("Extension Schematic Handlers - Native Nets and ERC", () => { ]); }); }); + + describe("getSchematicPortsBuses", () => { + it("delegates to fetchSchematicPortsBusesReport handler", async () => { + const mockApi = { + dmt_SelectControl: { + getCurrentDocumentInfo: vi.fn(async () => baseDocInfo) + }, + sch_PrimitiveNetPort: { + getAll: vi.fn(async () => [{ primitiveId: "port-1", name: "RXD", portType: "input", x: 10, y: 20 }]) + }, + sch_PrimitiveBus: { + getAll: vi.fn(async () => [{ primitiveId: "bus-1", name: "DATA[0..3]", pointList: [0, 0, 100, 0] }]) + }, + sch_PrimitiveBusEntry: { + getAll: vi.fn(async () => [ + { primitiveId: "entry-1", startX: 10, startY: 0, endX: 20, endY: 10, net: "DATA0" } + ]) + } + }; + + const handlers = createSchematicHandlers(() => mockApi); + const result = (await handlers.getSchematicPortsBuses({})) as any; + + expect(result.summary.portCount).toBe(1); + expect(result.summary.busCount).toBe(1); + expect(result.summary.busEntryCount).toBe(1); + expect(result.ports[0].name).toBe("RXD"); + expect(result.buses[0].name).toBe("DATA[0..3]"); + }); + }); }); diff --git a/extension/src/handlers/schematicHandlers.ts b/extension/src/handlers/schematicHandlers.ts index c22c87a..1ca3c7a 100644 --- a/extension/src/handlers/schematicHandlers.ts +++ b/extension/src/handlers/schematicHandlers.ts @@ -22,6 +22,7 @@ import { toArray } from "../helpers.js"; import type { EasyEdaApi, RpcHandler } from "../types.js"; +import { fetchSchematicPortsBusesReport } from "../mutation/schematicPortBusMutations.js"; import { getPcbComponents, getPcbNetNames } from "./pcbHandlers.js"; export async function getSchematicComponents(api: () => EasyEdaApi): Promise { @@ -559,6 +560,7 @@ export function createSchematicHandlers(api: () => EasyEdaApi): Record fetchSchematicPortsBusesReport(api, params) }; } diff --git a/extension/src/identity.ts b/extension/src/identity.ts index a9924e5..05f09c4 100644 --- a/extension/src/identity.ts +++ b/extension/src/identity.ts @@ -183,6 +183,19 @@ export function detectMethodCapabilities(api: () => EasyEdaApi): Record = { preparePcbTrackVia: (params) => preparePcbTrackViaMutation(getApi, params), prepareSchematicComponent: (params) => prepareSchematicComponentMutation(getApi, params), prepareSchematicWire: (params) => prepareSchematicWireMutation(getApi, params), + prepareSchematicPort: (params) => prepareSchematicPortMutation(getApi, params), + prepareSchematicBus: (params) => prepareSchematicBusMutation(getApi, params), ...contextHandlers, ...documentHandlers, ...schematicHandlers, diff --git a/extension/src/mutation/schematicPortBusMutations.test.ts b/extension/src/mutation/schematicPortBusMutations.test.ts new file mode 100644 index 0000000..0a3a7a6 --- /dev/null +++ b/extension/src/mutation/schematicPortBusMutations.test.ts @@ -0,0 +1,480 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { + analyzePortsAndBusesDiagnostics, + distanceToPolyline, + distanceToSegment, + fetchSchematicPortsBusesReport, + normalizeLineCoordinates, + parseBusName, + prepareSchematicBusMutation, + prepareSchematicPortMutation +} from "./schematicPortBusMutations.js"; +import { extensionMutations } from "./mutationManager.js"; +import { createActionHandlers } from "../handlers/actionHandlers.js"; +import type { EasyEdaApi } from "../types.js"; + +describe("schematicPortBusMutations", () => { + beforeEach(() => { + extensionMutations.invalidateAll(); + }); + + describe("parseBusName & geometry helpers", () => { + it("parses ascending bus ranges like DATA[0..7]", () => { + const res = parseBusName("DATA[0..7]"); + expect(res.prefix).toBe("DATA"); + expect(res.range).toEqual({ + start: 0, + end: 7, + count: 8, + signals: ["DATA0", "DATA1", "DATA2", "DATA3", "DATA4", "DATA5", "DATA6", "DATA7"] + }); + expect(res.signals).toHaveLength(8); + expect(res.signals[0]).toBe("DATA0"); + expect(res.signals[7]).toBe("DATA7"); + }); + + it("parses descending bus ranges like ADDR[3:0]", () => { + const res = parseBusName("ADDR[3:0]"); + expect(res.prefix).toBe("ADDR"); + expect(res.range?.signals).toEqual(["ADDR3", "ADDR2", "ADDR1", "ADDR0"]); + }); + + it("parses bracketed member lists like BUS[RX,TX,CTS]", () => { + const res = parseBusName("BUS[RX,TX,CTS]"); + expect(res.prefix).toBe("BUS"); + expect(res.signals).toEqual(["BUS_RX", "BUS_TX", "BUS_CTS"]); + }); + + it("parses comma-separated lists and single net names", () => { + const list = parseBusName("SPI_CLK, SPI_MISO, SPI_MOSI"); + expect(list.signals).toEqual(["SPI_CLK", "SPI_MISO", "SPI_MOSI"]); + + const single = parseBusName("VBUS"); + expect(single.signals).toEqual(["VBUS"]); + }); + + it("throws error for excessively large bus ranges", () => { + expect(() => parseBusName("DATA[0..1000]")).toThrowError(/maximum allowed is 512/); + }); + + it("normalizes coordinates and computes line/polyline distances", () => { + const flat = normalizeLineCoordinates([10, 20, 30, 40]); + expect(flat).toEqual([10, 20, 30, 40]); + + const pairs = normalizeLineCoordinates([ + [10, 20], + [30, 40] + ]); + expect(pairs).toEqual([10, 20, 30, 40]); + + expect(() => normalizeLineCoordinates([10])).toThrowError(/at least 2 points/); + + // Distance from point (15, 20) to segment (10, 20)-(30, 20) should be 0 + const dSeg = distanceToSegment({ x: 15, y: 20 }, { x: 10, y: 20 }, { x: 30, y: 20 }); + expect(dSeg).toBe(0); + + // Distance from point (15, 25) to same segment should be 5 + const dOff = distanceToSegment({ x: 15, y: 25 }, { x: 10, y: 20 }, { x: 30, y: 20 }); + expect(dOff).toBeCloseTo(5); + + // Distance to polyline + const dPoly = distanceToPolyline({ x: 15, y: 25 }, [ + { x: 0, y: 0 }, + { x: 10, y: 20 }, + { x: 30, y: 20 } + ]); + expect(dPoly).toBeCloseTo(5); + }); + }); + + describe("analyzePortsAndBusesDiagnostics", () => { + it("flags conflicting port directions and dangling bus entries", () => { + const diagnostics = analyzePortsAndBusesDiagnostics( + [ + { primitiveId: "p1", name: "TXD", portType: "output", x: 100, y: 100, rotation: 0 }, + { primitiveId: "p2", name: "TXD", portType: "input", x: 200, y: 200, rotation: 0 }, + { primitiveId: "p3", name: "", portType: "bidirectional", x: 300, y: 300, rotation: 0 } + ], + [ + { + primitiveId: "b1", + name: "DATA[0..3]", + prefix: "DATA", + signals: ["DATA0", "DATA1", "DATA2", "DATA3"], + coordinates: [100, 100, 200, 100], + points: [ + { x: 100, y: 100 }, + { x: 200, y: 100 } + ] + } + ], + [ + // Touching bus at (120, 100) with matching net + { + primitiveId: "be1", + startX: 120, + startY: 100, + endX: 130, + endY: 110, + net: "DATA1" + }, + // Touching bus at (150, 100) with mismatched net + { + primitiveId: "be2", + startX: 150, + startY: 100, + endX: 160, + endY: 110, + net: "RESET" + }, + // Far away from bus (dangling) + { + primitiveId: "be3", + startX: 500, + startY: 500, + endX: 510, + endY: 510, + net: "DATA0" + } + ] + ); + + const codes = diagnostics.map((d) => d.code); + expect(codes).toContain("conflicting_port_types"); + expect(codes).toContain("unnamed_port"); + expect(codes).toContain("bus_signal_mismatch"); + expect(codes).toContain("dangling_bus_entry"); + }); + }); + + describe("fetchSchematicPortsBusesReport", () => { + it("collects ports, buses, and bus entries from EasyEDA Pro API", async () => { + const mockApi: EasyEdaApi = { + dmt_SelectControl: { + getCurrentDocumentInfo: vi.fn(async () => ({ + documentType: "schematic", + uuid: "doc-sch-1", + title: "Main.json" + })) + }, + sch_PrimitiveNetPort: { + getAll: vi.fn(async () => [ + { primitiveId: "port-1", name: "CLK", portType: "input", x: 50, y: 80, rotation: 0 } + ]) + }, + sch_PrimitiveBus: { + getAll: vi.fn(async () => [ + { + primitiveId: "bus-1", + name: "ADDR[0..15]", + pointList: [0, 100, 400, 100], + lineWidth: 2 + } + ]) + }, + sch_PrimitiveBusEntry: { + getAll: vi.fn(async () => [ + { + primitiveId: "entry-1", + startX: 50, + startY: 100, + endX: 60, + endY: 110, + net: "ADDR0" + } + ]) + } + }; + + const report = await fetchSchematicPortsBusesReport(() => mockApi); + expect(report.summary.portCount).toBe(1); + expect(report.summary.busCount).toBe(1); + expect(report.summary.busEntryCount).toBe(1); + expect(report.summary.totalSignalsInBuses).toBe(16); + expect(report.ports[0].name).toBe("CLK"); + expect(report.buses[0].name).toBe("ADDR[0..15]"); + expect(report.busEntries[0].net).toBe("ADDR0"); + expect(report.diagnostics).toHaveLength(0); + }); + + it("rejects non-schematic active documents", async () => { + const mockApi: EasyEdaApi = { + dmt_SelectControl: { + getCurrentDocumentInfo: vi.fn(async () => ({ + documentType: "pcb", + uuid: "doc-pcb-1", + title: "Board.pcb" + })) + } + }; + + await expect(fetchSchematicPortsBusesReport(() => mockApi)).rejects.toThrowError(/active schematic/); + }); + }); + + describe("prepareSchematicPortMutation & execution", () => { + it("prepares and executes createPort mutation", async () => { + let createdPortRecord: any = null; + const mockApi: EasyEdaApi = { + dmt_SelectControl: { + getCurrentDocumentInfo: vi.fn(async () => ({ + documentType: "schematic", + uuid: "doc-sch-1", + title: "Main.json" + })) + }, + sch_PrimitiveNetPort: { + getAll: vi.fn(async () => (createdPortRecord ? [createdPortRecord] : [])), + create: vi.fn(async (params) => { + createdPortRecord = { primitiveId: "port-new-1", ...params }; + return createdPortRecord; + }) + } + }; + + const prep = await prepareSchematicPortMutation(() => mockApi, { + action: "createPort", + name: "SPI_CS", + portType: "output", + x: 120, + y: 240, + rotation: 90 + }); + + expect(typeof prep.mutationId).toBe("string"); + expect(prep.confirmation).toContain("CONFIRM schematic:createPort"); + + const actionHandlers = createActionHandlers(() => mockApi, {} as any, extensionMutations); + const res = (await actionHandlers.confirmedAction({ + action: "mutation", + params: { mutationId: prep.mutationId }, + confirmation: prep.confirmation + })) as any; + + expect(res.status).toBe("applied"); + expect((res.after as any).name).toBe("SPI_CS"); + expect((res.after as any).portType).toBe("output"); + expect((res.after as any).verified).toBe(true); + }); + + it("prepares and executes modifyPort mutation", async () => { + let portRecord: any = { + primitiveId: "port-10", + name: "OLD_NET", + portType: "bidirectional", + x: 100, + y: 100, + rotation: 0 + }; + + const mockApi: EasyEdaApi = { + dmt_SelectControl: { + getCurrentDocumentInfo: vi.fn(async () => ({ + documentType: "schematic", + uuid: "doc-sch-1", + title: "Main.json" + })) + }, + sch_PrimitiveNetPort: { + getAll: vi.fn(async () => [portRecord]), + modify: vi.fn(async (id, props) => { + portRecord = { ...portRecord, ...props }; + return true; + }) + } + }; + + const prep = await prepareSchematicPortMutation(() => mockApi, { + action: "modifyPort", + portId: "port-10", + name: "NEW_NET", + portType: "input" + }); + + expect(typeof prep.mutationId).toBe("string"); + expect(prep.confirmation).toContain("CONFIRM schematic:modifyPort"); + + const actionHandlers = createActionHandlers(() => mockApi, {} as any, extensionMutations); + const res = (await actionHandlers.confirmedAction({ + action: "mutation", + params: { mutationId: prep.mutationId }, + confirmation: prep.confirmation + })) as any; + + expect(res.status).toBe("applied"); + expect((res.after as any).port.name).toBe("NEW_NET"); + expect((res.after as any).port.portType).toBe("input"); + }); + + it("prepares and executes deletePort mutation", async () => { + let portList = [ + { primitiveId: "port-del-1", name: "UNUSED", portType: "bidirectional", x: 10, y: 10, rotation: 0 } + ]; + + const mockApi: EasyEdaApi = { + dmt_SelectControl: { + getCurrentDocumentInfo: vi.fn(async () => ({ + documentType: "schematic", + uuid: "doc-sch-1", + title: "Main.json" + })) + }, + sch_PrimitiveNetPort: { + getAll: vi.fn(async () => portList), + delete: vi.fn(async ([id]) => { + portList = portList.filter((p) => p.primitiveId !== id); + return true; + }) + } + }; + + const prep = await prepareSchematicPortMutation(() => mockApi, { + action: "deletePort", + portId: "port-del-1" + }); + + const actionHandlers = createActionHandlers(() => mockApi, {} as any, extensionMutations); + const res = (await actionHandlers.confirmedAction({ + action: "mutation", + params: { mutationId: prep.mutationId }, + confirmation: prep.confirmation + })) as any; + + expect(res.status).toBe("applied"); + expect((res.after as any).deleted).toBe(true); + expect(portList).toHaveLength(0); + }); + }); + + describe("prepareSchematicBusMutation & execution", () => { + it("prepares and executes createBus mutation", async () => { + let createdBusRecord: any = null; + const mockApi: EasyEdaApi = { + dmt_SelectControl: { + getCurrentDocumentInfo: vi.fn(async () => ({ + documentType: "schematic", + uuid: "doc-sch-1", + title: "Main.json" + })) + }, + sch_PrimitiveBus: { + getAll: vi.fn(async () => (createdBusRecord ? [createdBusRecord] : [])), + create: vi.fn(async (coords, options) => { + createdBusRecord = { + primitiveId: "bus-created-1", + name: options.name, + pointList: coords, + lineWidth: options.strokeWidth + }; + return createdBusRecord; + }) + } + }; + + const prep = await prepareSchematicBusMutation(() => mockApi, { + action: "createBus", + name: "DATA[0..7]", + coordinates: [100, 200, 300, 200], + lineWidth: 3 + }); + + expect(typeof prep.mutationId).toBe("string"); + expect(prep.confirmation).toContain("CONFIRM schematic:createBus"); + expect((prep.preview as any).impact).toContain("DATA[0..7]"); + + const actionHandlers = createActionHandlers(() => mockApi, {} as any, extensionMutations); + const res = (await actionHandlers.confirmedAction({ + action: "mutation", + params: { mutationId: prep.mutationId }, + confirmation: prep.confirmation + })) as any; + + expect(res.status).toBe("applied"); + expect((res.after as any).name).toBe("DATA[0..7]"); + expect((res.after as any).signalsCount).toBe(8); + expect((res.after as any).verified).toBe(true); + }); + + it("prepares and executes createBusEntry mutation", async () => { + let createdEntryRecord: any = null; + const mockApi: EasyEdaApi = { + dmt_SelectControl: { + getCurrentDocumentInfo: vi.fn(async () => ({ + documentType: "schematic", + uuid: "doc-sch-1", + title: "Main.json" + })) + }, + sch_PrimitiveBusEntry: { + getAll: vi.fn(async () => (createdEntryRecord ? [createdEntryRecord] : [])), + create: vi.fn(async (params) => { + createdEntryRecord = { + primitiveId: "entry-created-1", + ...params + }; + return createdEntryRecord; + }) + } + }; + + const prep = await prepareSchematicBusMutation(() => mockApi, { + action: "createBusEntry", + startX: 120, + startY: 200, + endX: 130, + endY: 210, + net: "DATA0" + }); + + expect(typeof prep.mutationId).toBe("string"); + expect(prep.confirmation).toContain("CONFIRM schematic:createBusEntry"); + + const actionHandlers = createActionHandlers(() => mockApi, {} as any, extensionMutations); + const res = (await actionHandlers.confirmedAction({ + action: "mutation", + params: { mutationId: prep.mutationId }, + confirmation: prep.confirmation + })) as any; + + expect(res.status).toBe("applied"); + expect((res.after as any).net).toBe("DATA0"); + expect((res.after as any).verified).toBe(true); + }); + + it("prepares and executes deleteBusEntry mutation", async () => { + let entries = [{ primitiveId: "entry-del-1", startX: 10, startY: 10, endX: 20, endY: 20 }]; + const mockApi: EasyEdaApi = { + dmt_SelectControl: { + getCurrentDocumentInfo: vi.fn(async () => ({ + documentType: "schematic", + uuid: "doc-sch-1", + title: "Main.json" + })) + }, + sch_PrimitiveBusEntry: { + getAll: vi.fn(async () => entries), + delete: vi.fn(async ([id]) => { + entries = entries.filter((e) => e.primitiveId !== id); + return true; + }) + } + }; + + const prep = await prepareSchematicBusMutation(() => mockApi, { + action: "deleteBusEntry", + entryId: "entry-del-1" + }); + + const actionHandlers = createActionHandlers(() => mockApi, {} as any, extensionMutations); + const res = (await actionHandlers.confirmedAction({ + action: "mutation", + params: { mutationId: prep.mutationId }, + confirmation: prep.confirmation + })) as any; + + expect(res.status).toBe("applied"); + expect((res.after as any).deleted).toBe(true); + expect(entries).toHaveLength(0); + }); + }); +}); diff --git a/extension/src/mutation/schematicPortBusMutations.ts b/extension/src/mutation/schematicPortBusMutations.ts new file mode 100644 index 0000000..374a48c --- /dev/null +++ b/extension/src/mutation/schematicPortBusMutations.ts @@ -0,0 +1,1339 @@ +import { + apiError, + ensureApi, + isRecord, + numeric, + optionalCall, + pickString, + sanitize, + stringOrUndefined, + toArray +} from "../helpers.js"; +import { assertDocumentTargetMatch, extractDocumentIdentity, type DocumentIdentity } from "../identity.js"; +import { extensionMutations } from "./mutationManager.js"; +import type { EasyEdaApi } from "../types.js"; +import type { MutationRecord } from "../../../src/mutation/contracts.js"; + +export type SchematicPortType = "input" | "output" | "bidirectional" | "unspecified"; + +export interface NormalizedSchematicPort { + primitiveId: string; + name: string; + portType: SchematicPortType; + x: number; + y: number; + rotation: number; + sheet?: string; + color?: string; + raw?: Record; +} + +export interface BusRangeInfo { + start: number; + end: number; + count: number; + signals: string[]; +} + +export interface NormalizedSchematicBus { + primitiveId: string; + name: string; + prefix: string; + range?: BusRangeInfo; + signals: string[]; + coordinates: number[]; + points: Array<{ x: number; y: number }>; + lineWidth?: number; + color?: string; + sheet?: string; + raw?: Record; +} + +export interface NormalizedSchematicBusEntry { + primitiveId: string; + busId?: string; + wireId?: string; + startX: number; + startY: number; + endX: number; + endY: number; + rotation?: number; + net?: string; + sheet?: string; + raw?: Record; +} + +export interface SchematicPortBusDiagnostic { + code: string; + severity: "info" | "warning" | "error"; + message: string; + busId?: string; + portId?: string; + entryId?: string; + suggestion?: string; +} + +export interface SchematicPortsBusesReport { + target: DocumentIdentity; + summary: { + portCount: number; + busCount: number; + busEntryCount: number; + totalSignalsInBuses: number; + warningsCount: number; + }; + ports: NormalizedSchematicPort[]; + buses: NormalizedSchematicBus[]; + busEntries: NormalizedSchematicBusEntry[]; + diagnostics: SchematicPortBusDiagnostic[]; +} + +export function normalizeLineCoordinates(rawLine: unknown): number[] { + if (Array.isArray(rawLine)) { + if (rawLine.every((n) => typeof n === "number" && Number.isFinite(n))) { + if (rawLine.length >= 4 && rawLine.length % 2 === 0) { + return rawLine as number[]; + } + } + if (rawLine.every((pair) => Array.isArray(pair) && pair.length >= 2)) { + const flat: number[] = []; + for (const pair of rawLine) { + const x = numeric(pair[0]); + const y = numeric(pair[1]); + if (x === undefined || y === undefined) { + throw apiError("invalid_coordinates", "Coordinate pairs must contain finite numbers."); + } + flat.push(x, y); + } + if (flat.length >= 4) { + return flat; + } + } + } + + throw apiError( + "invalid_coordinates", + "Bus coordinates must be an array of at least 2 points (e.g. [x1, y1, x2, y2] or [[x1, y1], [x2, y2]])." + ); +} + +export function extractPointsFromFlat(flat: number[]): Array<{ x: number; y: number }> { + const points: Array<{ x: number; y: number }> = []; + for (let i = 0; i < flat.length; i += 2) { + points.push({ x: flat[i], y: flat[i + 1] }); + } + return points; +} + +export function pointDistance(p1: { x: number; y: number }, p2: { x: number; y: number }): number { + const dx = p1.x - p2.x; + const dy = p1.y - p2.y; + return Math.sqrt(dx * dx + dy * dy); +} + +export function distanceToSegment( + p: { x: number; y: number }, + v: { x: number; y: number }, + w: { x: number; y: number } +): number { + const l2 = (v.x - w.x) * (v.x - w.x) + (v.y - w.y) * (v.y - w.y); + if (l2 === 0) return pointDistance(p, v); + let t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2; + t = Math.max(0, Math.min(1, t)); + const projection = { + x: v.x + t * (w.x - v.x), + y: v.y + t * (w.y - v.y) + }; + return pointDistance(p, projection); +} + +export function distanceToPolyline(p: { x: number; y: number }, points: Array<{ x: number; y: number }>): number { + if (points.length === 0) return Infinity; + if (points.length === 1) return pointDistance(p, points[0]); + let minDist = Infinity; + for (let i = 0; i < points.length - 1; i++) { + const d = distanceToSegment(p, points[i], points[i + 1]); + if (d < minDist) { + minDist = d; + } + } + return minDist; +} + +export function parseBusName(rawName: string): { + prefix: string; + range?: BusRangeInfo; + signals: string[]; +} { + const name = rawName.trim(); + const rangeMatch = name.match(/^([a-zA-Z0-9_]+)\[(\d+)(?:\.\.|:)(\d+)\]$/); + if (rangeMatch) { + const prefix = rangeMatch[1]; + const start = parseInt(rangeMatch[2], 10); + const end = parseInt(rangeMatch[3], 10); + const step = start <= end ? 1 : -1; + const count = Math.abs(end - start) + 1; + const signals: string[] = []; + + // Guard against accidentally enormous ranges + if (count > 512) { + throw apiError("invalid_bus_range", `Bus range ${name} specifies ${count} signals (maximum allowed is 512).`); + } + + for (let i = start; step > 0 ? i <= end : i >= end; i += step) { + signals.push(`${prefix}${i}`); + } + + return { + prefix, + range: { start, end, count, signals }, + signals + }; + } + + const listMatch = name.match(/^([a-zA-Z0-9_]+)\[([^\]]+)\]$/); + if (listMatch) { + const prefix = listMatch[1]; + const items = listMatch[2] + .split(",") + .map((s) => s.trim()) + .filter((s) => s.length > 0); + const signals = items.map((item) => (item.startsWith(prefix) ? item : `${prefix}_${item}`)); + return { + prefix, + signals + }; + } + + const commaMatch = name + .split(",") + .map((s) => s.trim()) + .filter((s) => s.length > 0); + if (commaMatch.length > 1) { + return { + prefix: commaMatch[0], + signals: commaMatch + }; + } + + return { + prefix: name, + signals: name ? [name] : [] + }; +} + +export function normalizePortType(raw: unknown): SchematicPortType { + const str = String(raw ?? "") + .toLowerCase() + .trim(); + if (str === "input" || str === "in") return "input"; + if (str === "output" || str === "out") return "output"; + if (str === "bidirectional" || str === "bi" || str === "io" || str === "inout") return "bidirectional"; + return "unspecified"; +} + +export function normalizeSchematicPort(raw: unknown, includeRaw = false): NormalizedSchematicPort | null { + if (!isRecord(raw)) return null; + const primitiveId = pickString(raw, ["primitiveId", "id", "uuid", "gId"]); + if (!primitiveId) return null; + + const name = pickString(raw, ["name", "net", "netName", "displayName", "label"]) ?? ""; + const rawType = raw.portType ?? raw.type ?? raw.direction ?? raw.flagType; + const portType = normalizePortType(rawType); + const x = numeric(raw.x) ?? 0; + const y = numeric(raw.y) ?? 0; + const rotation = numeric(raw.rotation) ?? 0; + const sheet = pickString(raw, ["sheet", "pageId", "sheetId"]); + const color = pickString(raw, ["color", "strokeColor"]); + + return { + primitiveId, + name, + portType, + x, + y, + rotation, + sheet, + color, + raw: includeRaw ? (sanitize(raw) as Record) : undefined + }; +} + +export function normalizeSchematicBus(raw: unknown, includeRaw = false): NormalizedSchematicBus | null { + if (!isRecord(raw)) return null; + const primitiveId = pickString(raw, ["primitiveId", "id", "uuid", "gId"]); + if (!primitiveId) return null; + + const name = pickString(raw, ["name", "net", "busName", "label"]) ?? ""; + const { prefix, range, signals } = parseBusName(name); + + let coordinates: number[]; + const rawCoords = raw.pointList ?? raw.coordinates ?? raw.line ?? raw.points; + try { + coordinates = normalizeLineCoordinates(rawCoords); + } catch { + coordinates = []; + } + + const points = extractPointsFromFlat(coordinates); + const lineWidth = numeric(raw.lineWidth ?? raw.strokeWidth); + const color = pickString(raw, ["color", "strokeColor"]); + const sheet = pickString(raw, ["sheet", "pageId", "sheetId"]); + + return { + primitiveId, + name, + prefix, + range, + signals, + coordinates, + points, + lineWidth, + color, + sheet, + raw: includeRaw ? (sanitize(raw) as Record) : undefined + }; +} + +export function normalizeSchematicBusEntry(raw: unknown, includeRaw = false): NormalizedSchematicBusEntry | null { + if (!isRecord(raw)) return null; + const primitiveId = pickString(raw, ["primitiveId", "id", "uuid", "gId"]); + if (!primitiveId) return null; + + const startX = numeric(raw.startX ?? raw.x1) ?? (Array.isArray(raw.pointList) ? numeric(raw.pointList[0]) : 0) ?? 0; + const startY = numeric(raw.startY ?? raw.y1) ?? (Array.isArray(raw.pointList) ? numeric(raw.pointList[1]) : 0) ?? 0; + const endX = numeric(raw.endX ?? raw.x2) ?? (Array.isArray(raw.pointList) ? numeric(raw.pointList[2]) : 0) ?? 0; + const endY = numeric(raw.endY ?? raw.y2) ?? (Array.isArray(raw.pointList) ? numeric(raw.pointList[3]) : 0) ?? 0; + const rotation = numeric(raw.rotation) ?? 0; + const busId = pickString(raw, ["busId", "busPrimitiveId"]); + const wireId = pickString(raw, ["wireId", "wirePrimitiveId"]); + const net = pickString(raw, ["net", "netName", "signal"]); + const sheet = pickString(raw, ["sheet", "pageId", "sheetId"]); + + return { + primitiveId, + busId, + wireId, + startX, + startY, + endX, + endY, + rotation, + net, + sheet, + raw: includeRaw ? (sanitize(raw) as Record) : undefined + }; +} + +export function analyzePortsAndBusesDiagnostics( + ports: NormalizedSchematicPort[], + buses: NormalizedSchematicBus[], + busEntries: NormalizedSchematicBusEntry[], + tolerance = 15 +): SchematicPortBusDiagnostic[] { + const diagnostics: SchematicPortBusDiagnostic[] = []; + + // 1. Port diagnostics + const portsByName = new Map(); + for (const port of ports) { + if (!port.name) { + diagnostics.push({ + code: "unnamed_port", + severity: "warning", + message: `Port ${port.primitiveId} has an empty net name.`, + portId: port.primitiveId, + suggestion: "Assign a meaningful net name to this port." + }); + continue; + } + + const list = portsByName.get(port.name) ?? []; + list.push(port); + portsByName.set(port.name, list); + } + + for (const [name, pList] of portsByName.entries()) { + if (pList.length > 1) { + const distinctTypes = new Set(pList.map((p) => p.portType).filter((t) => t !== "unspecified")); + if (distinctTypes.has("input") && distinctTypes.has("output") && distinctTypes.size > 1) { + diagnostics.push({ + code: "conflicting_port_types", + severity: "warning", + message: `Net port '${name}' is declared with conflicting types: [${Array.from(distinctTypes).join(", ")}].`, + suggestion: "Ensure driving ports are output and sink ports are input, or use bidirectional." + }); + } + } + } + + // 2. Bus diagnostics + for (const bus of buses) { + if (!bus.name) { + diagnostics.push({ + code: "unnamed_bus", + severity: "warning", + message: `Bus ${bus.primitiveId} has no name specified.`, + busId: bus.primitiveId, + suggestion: "Assign a bus syntax name like 'DATA[0..7]'." + }); + } else if (bus.signals.length === 0) { + diagnostics.push({ + code: "empty_bus_signals", + severity: "warning", + message: `Bus '${bus.name}' does not resolve to any signals.`, + busId: bus.primitiveId, + suggestion: "Check syntax; use 'NAME[start..end]' or 'NAME[A,B,C]'." + }); + } + + if (bus.points.length < 2) { + diagnostics.push({ + code: "degenerate_bus", + severity: "warning", + message: `Bus '${bus.name || bus.primitiveId}' has fewer than 2 coordinate points.`, + busId: bus.primitiveId + }); + } + } + + // 3. Bus entry diagnostics + for (const entry of busEntries) { + const ptStart = { x: entry.startX, y: entry.startY }; + const ptEnd = { x: entry.endX, y: entry.endY }; + + // Find nearest bus to either start or end point + let nearestBus: NormalizedSchematicBus | undefined; + let minDistance = Infinity; + + for (const bus of buses) { + if (bus.points.length < 2) continue; + const dStart = distanceToPolyline(ptStart, bus.points); + const dEnd = distanceToPolyline(ptEnd, bus.points); + const best = Math.min(dStart, dEnd); + if (best < minDistance) { + minDistance = best; + nearestBus = bus; + } + } + + if (!nearestBus || minDistance > tolerance) { + diagnostics.push({ + code: "dangling_bus_entry", + severity: "warning", + message: `Bus entry ${entry.primitiveId} is not connected to any bus polyline (nearest distance: ${Number.isFinite(minDistance) ? minDistance.toFixed(1) : "none"}).`, + entryId: entry.primitiveId, + suggestion: "Align the bus entry endpoint exactly with the bus polyline." + }); + } else { + // If connected to nearestBus, check whether entry's net belongs to nearestBus signals + if (entry.net && nearestBus.signals.length > 0) { + const netUpper = entry.net.toUpperCase(); + const busSignalsUpper = nearestBus.signals.map((s) => s.toUpperCase()); + if (!busSignalsUpper.includes(netUpper)) { + diagnostics.push({ + code: "bus_signal_mismatch", + severity: "warning", + message: `Bus entry ${entry.primitiveId} net '${entry.net}' is not in connected bus '${nearestBus.name}' signals [${nearestBus.signals.slice(0, 5).join(", ")}${nearestBus.signals.length > 5 ? "..." : ""}].`, + entryId: entry.primitiveId, + busId: nearestBus.primitiveId, + suggestion: `Rename the wire/net to match one of ${nearestBus.name} signals.` + }); + } + } + } + } + + return diagnostics; +} + +export async function fetchSchematicPortsBusesReport( + api: () => EasyEdaApi, + params: Record = {} +): Promise { + const eda = api(); + const documentInfo = await optionalCall(() => eda.dmt_SelectControl?.getCurrentDocumentInfo?.()); + const currentTarget = extractDocumentIdentity(documentInfo, undefined, "native_api"); + + const expectedTarget = params.expectedTarget ?? params.target; + if (expectedTarget) { + assertDocumentTargetMatch(expectedTarget, currentTarget); + } + + if ( + currentTarget.documentType && + currentTarget.documentType !== "schematic" && + currentTarget.documentType !== "unknown" + ) { + throw apiError("wrong_document", "Schematic ports and buses report requires an active schematic document."); + } + + const includePorts = params.includePorts !== false; + const includeBuses = params.includeBuses !== false; + const includeBusEntries = params.includeBusEntries !== false; + const includeRaw = Boolean(params.includeRaw); + + const ports: NormalizedSchematicPort[] = []; + const buses: NormalizedSchematicBus[] = []; + const busEntries: NormalizedSchematicBusEntry[] = []; + + // Fetch Ports + if (includePorts) { + let rawPorts: unknown[] = []; + if (eda.sch_PrimitiveNetPort?.getAll) { + rawPorts = toArray(await optionalCall(() => eda.sch_PrimitiveNetPort.getAll())); + } else if (eda.sch_PrimitivePort?.getAll) { + rawPorts = toArray(await optionalCall(() => eda.sch_PrimitivePort.getAll())); + } else if (eda.sch_PrimitiveComponent?.getAll) { + const allComponents = toArray(await optionalCall(() => eda.sch_PrimitiveComponent.getAll(undefined, true))); + rawPorts = allComponents.filter((c) => { + if (!isRecord(c)) return false; + const type = String(c.type ?? c.itemType ?? c.primitiveType ?? "").toLowerCase(); + return type === "netport" || type === "port" || type === "net_port"; + }); + } + + for (const p of rawPorts) { + const norm = normalizeSchematicPort(p, includeRaw); + if (norm) ports.push(norm); + } + } + + // Fetch Buses + if (includeBuses) { + let rawBuses: unknown[] = []; + if (eda.sch_PrimitiveBus?.getAll) { + rawBuses = toArray(await optionalCall(() => eda.sch_PrimitiveBus.getAll())); + } + + for (const b of rawBuses) { + const norm = normalizeSchematicBus(b, includeRaw); + if (norm) buses.push(norm); + } + } + + // Fetch Bus Entries + if (includeBusEntries) { + let rawBusEntries: unknown[] = []; + if (eda.sch_PrimitiveBusEntry?.getAll) { + rawBusEntries = toArray(await optionalCall(() => eda.sch_PrimitiveBusEntry.getAll())); + } + + for (const e of rawBusEntries) { + const norm = normalizeSchematicBusEntry(e, includeRaw); + if (norm) busEntries.push(norm); + } + } + + const diagnostics = analyzePortsAndBusesDiagnostics(ports, buses, busEntries); + const totalSignalsInBuses = buses.reduce((acc, b) => acc + b.signals.length, 0); + const warningsCount = diagnostics.filter((d) => d.severity === "warning" || d.severity === "error").length; + + return { + target: currentTarget, + summary: { + portCount: ports.length, + busCount: buses.length, + busEntryCount: busEntries.length, + totalSignalsInBuses, + warningsCount + }, + ports, + buses, + busEntries, + diagnostics + }; +} + +export async function prepareSchematicPortMutation( + api: () => EasyEdaApi, + params: Record +): Promise> { + const eda = api(); + const documentInfo = await optionalCall(() => eda.dmt_SelectControl?.getCurrentDocumentInfo?.()); + const currentTarget = extractDocumentIdentity(documentInfo, undefined, "native_api"); + + const expectedTarget = params.expectedTarget ?? params.target; + if (expectedTarget) { + assertDocumentTargetMatch(expectedTarget, currentTarget); + } + + if ( + currentTarget.documentType && + currentTarget.documentType !== "schematic" && + currentTarget.documentType !== "unknown" + ) { + throw apiError("wrong_document", "Schematic port mutations require an active schematic document."); + } + + const action = String(params.action ?? "") + .toLowerCase() + .trim(); + if (!["createport", "modifyport", "deleteport", "create", "modify", "delete"].includes(action)) { + throw apiError("invalid_parameters", "Port action must be 'createPort', 'modifyPort', or 'deletePort'."); + } + + if (action === "createport" || action === "create") { + const name = stringOrUndefined(params.name); + if (!name) { + throw apiError("missing_parameters", "Parameter 'name' is required to create a net port."); + } + const x = numeric(params.x); + const y = numeric(params.y); + if (x === undefined || y === undefined) { + throw apiError("missing_parameters", "Parameters 'x' and 'y' are required to create a net port."); + } + const portType = normalizePortType(params.portType ?? params.type ?? "bidirectional"); + const rotation = numeric(params.rotation) ?? 0; + const color = stringOrUndefined(params.color); + + const operation = { + action: "createPort", + name, + portType, + x, + y, + rotation, + color + }; + + const preview = { + before: null, + requestedAfter: operation, + changedKeys: ["name", "portType", "x", "y", "rotation"], + scope: `port:${name}`, + impact: `Creates net port '${name}' (type: ${portType}) at (${x}, ${y}, rotation: ${rotation}°).` + }; + + const record = extensionMutations.prepare({ + domain: "schematic", + action: "createPort", + target: currentTarget, + operation, + before: preview.before, + requestedAfter: preview.requestedAfter, + changedKeys: preview.changedKeys, + scope: preview.scope, + impact: preview.impact, + ttlMs: 5 * 60_000 + }); + + return { + mutationId: record.mutationId, + confirmation: record.confirmation, + action: record.action, + target: record.target, + preview: record.preview, + expiresAt: record.expiresAt + }; + } + + if (action === "modifyport" || action === "modify") { + const portId = stringOrUndefined(params.portId ?? params.primitiveId ?? params.id); + if (!portId) { + throw apiError("missing_parameters", "Parameter 'portId' is required to modify a port."); + } + + const report = await fetchSchematicPortsBusesReport(api, { includeBuses: false, includeBusEntries: false }); + const existing = report.ports.find((p) => p.primitiveId === portId); + if (!existing) { + throw apiError("not_found", `Port with id '${portId}' not found in active schematic.`); + } + + const changedKeys: string[] = []; + const updates: Record = {}; + + if (params.name !== undefined && String(params.name) !== existing.name) { + updates.name = String(params.name); + changedKeys.push("name"); + } + if (params.portType !== undefined) { + const pType = normalizePortType(params.portType); + if (pType !== existing.portType) { + updates.portType = pType; + changedKeys.push("portType"); + } + } + if (params.x !== undefined && numeric(params.x) !== existing.x) { + updates.x = numeric(params.x); + changedKeys.push("x"); + } + if (params.y !== undefined && numeric(params.y) !== existing.y) { + updates.y = numeric(params.y); + changedKeys.push("y"); + } + if (params.rotation !== undefined && numeric(params.rotation) !== existing.rotation) { + updates.rotation = numeric(params.rotation); + changedKeys.push("rotation"); + } + if (params.color !== undefined && String(params.color) !== existing.color) { + updates.color = String(params.color); + changedKeys.push("color"); + } + + if (changedKeys.length === 0) { + throw apiError("no_changes", "No property changes specified for port modification."); + } + + const operation = { + action: "modifyPort", + portId, + properties: updates + }; + + const preview = { + before: existing, + requestedAfter: { ...existing, ...updates }, + changedKeys, + scope: `port:${portId}`, + impact: `Modifies properties [${changedKeys.join(", ")}] on port ${portId} (${existing.name}).` + }; + + const record = extensionMutations.prepare({ + domain: "schematic", + action: "modifyPort", + target: currentTarget, + operation, + before: preview.before, + requestedAfter: preview.requestedAfter, + changedKeys: preview.changedKeys, + scope: preview.scope, + impact: preview.impact, + ttlMs: 5 * 60_000 + }); + + return { + mutationId: record.mutationId, + confirmation: record.confirmation, + action: record.action, + target: record.target, + preview: record.preview, + expiresAt: record.expiresAt + }; + } + + // deleteport + const portId = stringOrUndefined(params.portId ?? params.primitiveId ?? params.id); + if (!portId) { + throw apiError("missing_parameters", "Parameter 'portId' is required to delete a port."); + } + + const report = await fetchSchematicPortsBusesReport(api, { includeBuses: false, includeBusEntries: false }); + const existing = report.ports.find((p) => p.primitiveId === portId); + + const operation = { + action: "deletePort", + portId + }; + + const preview = { + before: existing ?? { primitiveId: portId }, + requestedAfter: null, + changedKeys: ["deleted"], + scope: `port:${portId}`, + impact: `Deletes net port ${portId} (${existing?.name ?? "unnamed"}) from the active schematic.` + }; + + const record = extensionMutations.prepare({ + domain: "schematic", + action: "deletePort", + target: currentTarget, + operation, + before: preview.before, + requestedAfter: preview.requestedAfter, + changedKeys: preview.changedKeys, + scope: preview.scope, + impact: preview.impact, + ttlMs: 5 * 60_000 + }); + + return { + mutationId: record.mutationId, + confirmation: record.confirmation, + action: record.action, + target: record.target, + preview: record.preview, + expiresAt: record.expiresAt + }; +} + +export async function prepareSchematicBusMutation( + api: () => EasyEdaApi, + params: Record +): Promise> { + const eda = api(); + const documentInfo = await optionalCall(() => eda.dmt_SelectControl?.getCurrentDocumentInfo?.()); + const currentTarget = extractDocumentIdentity(documentInfo, undefined, "native_api"); + + const expectedTarget = params.expectedTarget ?? params.target; + if (expectedTarget) { + assertDocumentTargetMatch(expectedTarget, currentTarget); + } + + if ( + currentTarget.documentType && + currentTarget.documentType !== "schematic" && + currentTarget.documentType !== "unknown" + ) { + throw apiError("wrong_document", "Schematic bus mutations require an active schematic document."); + } + + const action = String(params.action ?? "") + .toLowerCase() + .trim(); + const validActions = [ + "createbus", + "modifybus", + "deletebus", + "createbusentry", + "deletebusentry", + "create", + "modify", + "delete" + ]; + + if (!validActions.includes(action)) { + throw apiError( + "invalid_parameters", + "Bus action must be 'createBus', 'modifyBus', 'deleteBus', 'createBusEntry', or 'deleteBusEntry'." + ); + } + + if (action === "createbus" || (action === "create" && !params.busEntry)) { + const name = stringOrUndefined(params.name); + if (!name) { + throw apiError("missing_parameters", "Parameter 'name' is required to create a bus (e.g. 'DATA[0..7]')."); + } + + const { prefix, signals } = parseBusName(name); + const coordinates = normalizeLineCoordinates(params.coordinates ?? params.pointList ?? params.line); + const lineWidth = numeric(params.lineWidth) ?? 2; + const color = stringOrUndefined(params.color); + + const operation = { + action: "createBus", + name, + prefix, + signals, + coordinates, + lineWidth, + color + }; + + const preview = { + before: null, + requestedAfter: operation, + changedKeys: ["name", "coordinates", "lineWidth"], + scope: `bus:${name}`, + impact: `Creates bus '${name}' (${signals.length} signals: ${signals.slice(0, 4).join(", ")}${signals.length > 4 ? "..." : ""}) with ${coordinates.length / 2} points.` + }; + + const record = extensionMutations.prepare({ + domain: "schematic", + action: "createBus", + target: currentTarget, + operation, + before: preview.before, + requestedAfter: preview.requestedAfter, + changedKeys: preview.changedKeys, + scope: preview.scope, + impact: preview.impact, + ttlMs: 5 * 60_000 + }); + + return { + mutationId: record.mutationId, + confirmation: record.confirmation, + action: record.action, + target: record.target, + preview: record.preview, + expiresAt: record.expiresAt + }; + } + + if (action === "modifybus" || (action === "modify" && !params.busEntry)) { + const busId = stringOrUndefined(params.busId ?? params.primitiveId ?? params.id); + if (!busId) { + throw apiError("missing_parameters", "Parameter 'busId' is required to modify a bus."); + } + + const report = await fetchSchematicPortsBusesReport(api, { includePorts: false, includeBusEntries: false }); + const existing = report.buses.find((b) => b.primitiveId === busId); + if (!existing) { + throw apiError("not_found", `Bus with id '${busId}' not found in active schematic.`); + } + + const changedKeys: string[] = []; + const updates: Record = {}; + + if (params.name !== undefined && String(params.name) !== existing.name) { + updates.name = String(params.name); + changedKeys.push("name"); + } + if (params.coordinates !== undefined || params.pointList !== undefined) { + const coords = normalizeLineCoordinates(params.coordinates ?? params.pointList); + updates.coordinates = coords; + changedKeys.push("coordinates"); + } + if (params.lineWidth !== undefined && numeric(params.lineWidth) !== existing.lineWidth) { + updates.lineWidth = numeric(params.lineWidth); + changedKeys.push("lineWidth"); + } + if (params.color !== undefined && String(params.color) !== existing.color) { + updates.color = String(params.color); + changedKeys.push("color"); + } + + if (changedKeys.length === 0) { + throw apiError("no_changes", "No property changes specified for bus modification."); + } + + const operation = { + action: "modifyBus", + busId, + properties: updates + }; + + const preview = { + before: existing, + requestedAfter: { ...existing, ...updates }, + changedKeys, + scope: `bus:${busId}`, + impact: `Modifies properties [${changedKeys.join(", ")}] on bus ${busId} (${existing.name}).` + }; + + const record = extensionMutations.prepare({ + domain: "schematic", + action: "modifyBus", + target: currentTarget, + operation, + before: preview.before, + requestedAfter: preview.requestedAfter, + changedKeys: preview.changedKeys, + scope: preview.scope, + impact: preview.impact, + ttlMs: 5 * 60_000 + }); + + return { + mutationId: record.mutationId, + confirmation: record.confirmation, + action: record.action, + target: record.target, + preview: record.preview, + expiresAt: record.expiresAt + }; + } + + if (action === "deletebus" || (action === "delete" && !params.busEntry && !params.entryId)) { + const busId = stringOrUndefined(params.busId ?? params.primitiveId ?? params.id); + if (!busId) { + throw apiError("missing_parameters", "Parameter 'busId' is required to delete a bus."); + } + + const report = await fetchSchematicPortsBusesReport(api, { includePorts: false, includeBusEntries: false }); + const existing = report.buses.find((b) => b.primitiveId === busId); + + const operation = { + action: "deleteBus", + busId + }; + + const preview = { + before: existing ?? { primitiveId: busId }, + requestedAfter: null, + changedKeys: ["deleted"], + scope: `bus:${busId}`, + impact: `Deletes bus ${busId} (${existing?.name ?? "unnamed"}) from the active schematic.` + }; + + const record = extensionMutations.prepare({ + domain: "schematic", + action: "deleteBus", + target: currentTarget, + operation, + before: preview.before, + requestedAfter: preview.requestedAfter, + changedKeys: preview.changedKeys, + scope: preview.scope, + impact: preview.impact, + ttlMs: 5 * 60_000 + }); + + return { + mutationId: record.mutationId, + confirmation: record.confirmation, + action: record.action, + target: record.target, + preview: record.preview, + expiresAt: record.expiresAt + }; + } + + if (action === "createbusentry" || (action === "create" && params.busEntry)) { + let startX = numeric(params.startX ?? params.x1); + let startY = numeric(params.startY ?? params.y1); + let endX = numeric(params.endX ?? params.x2); + let endY = numeric(params.endY ?? params.y2); + + if (startX === undefined || startY === undefined || endX === undefined || endY === undefined) { + if (params.coordinates || params.pointList) { + const coords = normalizeLineCoordinates(params.coordinates ?? params.pointList); + if (coords.length >= 4) { + startX = coords[0]; + startY = coords[1]; + endX = coords[2]; + endY = coords[3]; + } + } + } + + if (startX === undefined || startY === undefined || endX === undefined || endY === undefined) { + throw apiError( + "missing_parameters", + "Bus entry creation requires start and end coordinates (startX, startY, endX, endY)." + ); + } + + const rotation = numeric(params.rotation) ?? 0; + const busId = stringOrUndefined(params.busId); + const wireId = stringOrUndefined(params.wireId); + const net = stringOrUndefined(params.net ?? params.signal); + + const operation = { + action: "createBusEntry", + startX, + startY, + endX, + endY, + rotation, + busId, + wireId, + net + }; + + const preview = { + before: null, + requestedAfter: operation, + changedKeys: ["startX", "startY", "endX", "endY"], + scope: `busEntry:(${startX},${startY})->(${endX},${endY})`, + impact: `Creates diagonal bus entry tap from (${startX}, ${startY}) to (${endX}, ${endY})${net ? ` for net '${net}'` : ""}.` + }; + + const record = extensionMutations.prepare({ + domain: "schematic", + action: "createBusEntry", + target: currentTarget, + operation, + before: preview.before, + requestedAfter: preview.requestedAfter, + changedKeys: preview.changedKeys, + scope: preview.scope, + impact: preview.impact, + ttlMs: 5 * 60_000 + }); + + return { + mutationId: record.mutationId, + confirmation: record.confirmation, + action: record.action, + target: record.target, + preview: record.preview, + expiresAt: record.expiresAt + }; + } + + // deletebusentry + const entryId = stringOrUndefined(params.entryId ?? params.primitiveId ?? params.id); + if (!entryId) { + throw apiError("missing_parameters", "Parameter 'entryId' is required to delete a bus entry."); + } + + const report = await fetchSchematicPortsBusesReport(api, { includePorts: false, includeBuses: false }); + const existing = report.busEntries.find((e) => e.primitiveId === entryId); + + const operation = { + action: "deleteBusEntry", + entryId + }; + + const preview = { + before: existing ?? { primitiveId: entryId }, + requestedAfter: null, + changedKeys: ["deleted"], + scope: `busEntry:${entryId}`, + impact: `Deletes bus entry tap ${entryId} from the active schematic.` + }; + + const record = extensionMutations.prepare({ + domain: "schematic", + action: "deleteBusEntry", + target: currentTarget, + operation, + before: preview.before, + requestedAfter: preview.requestedAfter, + changedKeys: preview.changedKeys, + scope: preview.scope, + impact: preview.impact, + ttlMs: 5 * 60_000 + }); + + return { + mutationId: record.mutationId, + confirmation: record.confirmation, + action: record.action, + target: record.target, + preview: record.preview, + expiresAt: record.expiresAt + }; +} + +export async function executeSchematicPortMutation( + record: MutationRecord, + api: () => EasyEdaApi +): Promise<{ executed: boolean; readback: Record }> { + const eda = api(); + const op = record.operation as Record; + + if (op.action === "createPort") { + let created: any; + if (eda.sch_PrimitiveNetPort?.create) { + created = await eda.sch_PrimitiveNetPort.create({ + name: op.name, + portType: op.portType, + x: op.x, + y: op.y, + rotation: op.rotation, + color: op.color + }); + } else if (eda.sch_PrimitivePort?.create) { + created = await eda.sch_PrimitivePort.create({ + name: op.name, + portType: op.portType, + x: op.x, + y: op.y, + rotation: op.rotation + }); + } else if (eda.sch_PrimitiveComponent?.createNetFlag) { + created = await eda.sch_PrimitiveComponent.createNetFlag( + op.portType === "input" ? "InputPort" : op.portType === "output" ? "OutputPort" : "NetPort", + op.name, + op.x, + op.y, + op.rotation + ); + } else { + throw apiError( + "capability_unavailable", + "Schematic port creation (sch_PrimitiveNetPort.create / sch_PrimitivePort.create) is not available in the connected EasyEDA Pro version." + ); + } + + const createdPrimitiveId = + created?.primitiveId ?? created?.id ?? created?.uuid ?? (typeof created === "string" ? created : undefined); + + const report = await fetchSchematicPortsBusesReport(api, { includeBuses: false, includeBusEntries: false }); + const verifiedPort = report.ports.find((p) => p.name === op.name || p.primitiveId === createdPrimitiveId); + + return { + executed: true, + readback: { + primitiveId: createdPrimitiveId ?? verifiedPort?.primitiveId ?? "created_port", + name: op.name, + portType: op.portType, + x: op.x, + y: op.y, + rotation: op.rotation, + verified: Boolean(verifiedPort || createdPrimitiveId), + port: verifiedPort + } + }; + } + + if (op.action === "modifyPort") { + if (eda.sch_PrimitiveNetPort?.modify) { + await eda.sch_PrimitiveNetPort.modify(op.portId, op.properties); + } else if (eda.sch_PrimitivePort?.modify) { + await eda.sch_PrimitivePort.modify(op.portId, op.properties); + } else { + throw apiError( + "capability_unavailable", + "Schematic port modification (sch_PrimitiveNetPort.modify / sch_PrimitivePort.modify) is not available." + ); + } + + const report = await fetchSchematicPortsBusesReport(api, { includeBuses: false, includeBusEntries: false }); + const modifiedPort = report.ports.find((p) => p.primitiveId === op.portId); + + return { + executed: true, + readback: { + portId: op.portId, + properties: op.properties, + verified: Boolean(modifiedPort), + port: modifiedPort + } + }; + } + + if (op.action === "deletePort") { + if (eda.sch_PrimitiveNetPort?.delete) { + await eda.sch_PrimitiveNetPort.delete([op.portId]); + } else if (eda.sch_PrimitivePort?.delete) { + await eda.sch_PrimitivePort.delete([op.portId]); + } else { + throw apiError( + "capability_unavailable", + "Schematic port deletion (sch_PrimitiveNetPort.delete / sch_PrimitivePort.delete) is not available." + ); + } + + const report = await fetchSchematicPortsBusesReport(api, { includeBuses: false, includeBusEntries: false }); + const stillExists = report.ports.some((p) => p.primitiveId === op.portId); + + if (stillExists) { + throw apiError("readback_verification_failed", `Port ${op.portId} still exists after delete call.`); + } + + return { + executed: true, + readback: { + portId: op.portId, + deleted: true, + verified: true + } + }; + } + + throw apiError("unsupported_action", `Unsupported schematic port mutation action "${op.action}".`); +} + +export async function executeSchematicBusMutation( + record: MutationRecord, + api: () => EasyEdaApi +): Promise<{ executed: boolean; readback: Record }> { + const eda = api(); + const op = record.operation as Record; + + if (op.action === "createBus") { + ensureApi("sch_PrimitiveBus", "create", eda); + const created = await eda.sch_PrimitiveBus.create(op.coordinates, { + name: op.name, + strokeWidth: op.lineWidth, + color: op.color + }); + + const createdPrimitiveId = + created?.primitiveId ?? created?.id ?? created?.uuid ?? (typeof created === "string" ? created : undefined); + + const report = await fetchSchematicPortsBusesReport(api, { includePorts: false, includeBusEntries: false }); + const verifiedBus = report.buses.find((b) => b.name === op.name || b.primitiveId === createdPrimitiveId); + + return { + executed: true, + readback: { + primitiveId: createdPrimitiveId ?? verifiedBus?.primitiveId ?? "created_bus", + name: op.name, + signalsCount: op.signals?.length ?? 0, + coordinates: op.coordinates, + verified: Boolean(verifiedBus || createdPrimitiveId), + bus: verifiedBus + } + }; + } + + if (op.action === "modifyBus") { + ensureApi("sch_PrimitiveBus", "modify", eda); + await eda.sch_PrimitiveBus.modify(op.busId, op.properties); + + const report = await fetchSchematicPortsBusesReport(api, { includePorts: false, includeBusEntries: false }); + const modifiedBus = report.buses.find((b) => b.primitiveId === op.busId); + + return { + executed: true, + readback: { + busId: op.busId, + properties: op.properties, + verified: Boolean(modifiedBus), + bus: modifiedBus + } + }; + } + + if (op.action === "deleteBus") { + ensureApi("sch_PrimitiveBus", "delete", eda); + await eda.sch_PrimitiveBus.delete([op.busId]); + + const report = await fetchSchematicPortsBusesReport(api, { includePorts: false, includeBusEntries: false }); + const stillExists = report.buses.some((b) => b.primitiveId === op.busId); + + if (stillExists) { + throw apiError("readback_verification_failed", `Bus ${op.busId} still exists after delete call.`); + } + + return { + executed: true, + readback: { + busId: op.busId, + deleted: true, + verified: true + } + }; + } + + if (op.action === "createBusEntry") { + ensureApi("sch_PrimitiveBusEntry", "create", eda); + const created = await eda.sch_PrimitiveBusEntry.create({ + startX: op.startX, + startY: op.startY, + endX: op.endX, + endY: op.endY, + rotation: op.rotation, + busId: op.busId, + wireId: op.wireId, + net: op.net + }); + + const createdPrimitiveId = + created?.primitiveId ?? created?.id ?? created?.uuid ?? (typeof created === "string" ? created : undefined); + + const report = await fetchSchematicPortsBusesReport(api, { includePorts: false, includeBuses: false }); + const verifiedEntry = report.busEntries.find((e) => e.primitiveId === createdPrimitiveId); + + return { + executed: true, + readback: { + primitiveId: createdPrimitiveId ?? "created_bus_entry", + startX: op.startX, + startY: op.startY, + endX: op.endX, + endY: op.endY, + net: op.net, + verified: Boolean(verifiedEntry || createdPrimitiveId), + busEntry: verifiedEntry + } + }; + } + + if (op.action === "deleteBusEntry") { + ensureApi("sch_PrimitiveBusEntry", "delete", eda); + await eda.sch_PrimitiveBusEntry.delete([op.entryId]); + + const report = await fetchSchematicPortsBusesReport(api, { includePorts: false, includeBuses: false }); + const stillExists = report.busEntries.some((e) => e.primitiveId === op.entryId); + + if (stillExists) { + throw apiError("readback_verification_failed", `Bus entry ${op.entryId} still exists after delete call.`); + } + + return { + executed: true, + readback: { + entryId: op.entryId, + deleted: true, + verified: true + } + }; + } + + throw apiError("unsupported_action", `Unsupported schematic bus mutation action "${op.action}".`); +} diff --git a/src/mcp/server.test.ts b/src/mcp/server.test.ts index 59a99f4..adb3a69 100644 --- a/src/mcp/server.test.ts +++ b/src/mcp/server.test.ts @@ -32,7 +32,7 @@ describe("EasyEDA MCP server", () => { const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]); - expect((await client.listTools()).tools).toHaveLength(65); + expect((await client.listTools()).tools).toHaveLength(68); const live = await client.callTool({ name: "easyeda_live_status", arguments: {} }); expect(live.structuredContent).toEqual({ status, bridgeEndpoint: editor.endpoint }); const doctor = await client.callTool({ name: "easyeda_doctor", arguments: {} }); @@ -83,6 +83,9 @@ describe("EasyEDA MCP server", () => { expect(toolNames).toContain("easyeda_highlight_net"); expect(toolNames).toContain("easyeda_get_selection"); expect(toolNames).toContain("easyeda_search_library"); + expect(toolNames).toContain("easyeda_get_schematic_ports_buses"); + expect(toolNames).toContain("easyeda_prepare_schematic_port"); + expect(toolNames).toContain("easyeda_prepare_schematic_bus"); const result = await client.callTool({ name: "easyeda_get_context", diff --git a/src/mcp/tools/schematicMutationTools.test.ts b/src/mcp/tools/schematicMutationTools.test.ts index c0a1a08..9af755f 100644 --- a/src/mcp/tools/schematicMutationTools.test.ts +++ b/src/mcp/tools/schematicMutationTools.test.ts @@ -28,6 +28,8 @@ describe("Schematic Mutation MCP Tools", () => { expect(names).toContain("easyeda_prepare_schematic_component"); expect(names).toContain("easyeda_prepare_schematic_wire"); + expect(names).toContain("easyeda_prepare_schematic_port"); + expect(names).toContain("easyeda_prepare_schematic_bus"); expect(names).toContain("easyeda_get_mutation_result"); }); @@ -258,4 +260,99 @@ describe("Schematic Mutation MCP Tools", () => { confirmation }); }); + + it("prepares a net port mutation via easyeda_prepare_schematic_port", async () => { + const mutationId = "mut-sch-createPort-123"; + const confirmation = `CONFIRM sch:createPort ${mutationId}`; + const bridge = { + endpoint: "ws://127.0.0.1:8765", + getStatus: (): EditorStatus => ({ connected: true, updatedAt: new Date().toISOString() }), + call: vi.fn(async () => ({ + mutationId, + confirmation, + action: "createPort", + preview: { + impact: "Creates net port 'TXD' (type: output) at (100, 200).", + scope: "port:TXD" + }, + expiresAt: new Date(Date.now() + 300_000).toISOString() + })) + }; + const client = await makeClient(bridge); + + const result = await client.callTool({ + name: "easyeda_prepare_schematic_port", + arguments: { + action: "createPort", + name: "TXD", + portType: "output", + x: 100, + y: 200, + rotation: 0 + } + }); + + expect(result.isError).toBeFalsy(); + expect(bridge.call).toHaveBeenCalledWith( + "prepareSchematicPort", + expect.objectContaining({ + action: "createPort", + name: "TXD", + portType: "output", + x: 100, + y: 200 + }), + 30_000 + ); + expect(result.structuredContent).toMatchObject({ + mutationId, + confirmation + }); + }); + + it("prepares a bus mutation via easyeda_prepare_schematic_bus", async () => { + const mutationId = "mut-sch-createBus-456"; + const confirmation = `CONFIRM sch:createBus ${mutationId}`; + const bridge = { + endpoint: "ws://127.0.0.1:8765", + getStatus: (): EditorStatus => ({ connected: true, updatedAt: new Date().toISOString() }), + call: vi.fn(async () => ({ + mutationId, + confirmation, + action: "createBus", + preview: { + impact: "Creates bus 'DATA[0..7]' with 4 points.", + scope: "bus:DATA[0..7]" + }, + expiresAt: new Date(Date.now() + 300_000).toISOString() + })) + }; + const client = await makeClient(bridge); + + const result = await client.callTool({ + name: "easyeda_prepare_schematic_bus", + arguments: { + action: "createBus", + name: "DATA[0..7]", + coordinates: [100, 200, 300, 200], + lineWidth: 3 + } + }); + + expect(result.isError).toBeFalsy(); + expect(bridge.call).toHaveBeenCalledWith( + "prepareSchematicBus", + expect.objectContaining({ + action: "createBus", + name: "DATA[0..7]", + coordinates: [100, 200, 300, 200], + lineWidth: 3 + }), + 30_000 + ); + expect(result.structuredContent).toMatchObject({ + mutationId, + confirmation + }); + }); }); diff --git a/src/mcp/tools/schematicMutationTools.ts b/src/mcp/tools/schematicMutationTools.ts index 2f16c4c..aa0a9e7 100644 --- a/src/mcp/tools/schematicMutationTools.ts +++ b/src/mcp/tools/schematicMutationTools.ts @@ -196,6 +196,165 @@ export function registerSchematicMutationTools(server: McpServer, bridge: Editor } ); + server.registerTool( + "easyeda_prepare_schematic_port", + { + title: "Prepare Schematic Port Mutation", + description: + "Prepares a create, modify, or delete operation on a schematic net port (hierarchical/sheet connector) with preview, validation, and exact confirmation phrase. Does not write until confirmed via easyeda_confirmed_action.", + inputSchema: { + action: z.enum(["createPort", "modifyPort", "deletePort"]).describe("Port action to perform"), + name: z.string().optional().describe("Net name for the port (e.g. 'TXD', 'CLK')"), + portType: z + .enum(["input", "output", "bidirectional", "unspecified"]) + .optional() + .describe("Port direction / type"), + x: z.number().optional().describe("X coordinate for port placement"), + y: z.number().optional().describe("Y coordinate for port placement"), + rotation: z.number().optional().describe("Rotation angle in degrees (0, 90, 180, 270)"), + color: z.string().optional().describe("Port color string"), + portId: z.string().optional().describe("Target port primitiveId for modify or delete"), + target: DocumentTargetSchema.optional().describe("Expected active schematic target"), + timeoutMs: DefaultTimeoutSchema.default(30_000) + }, + annotations: { + readOnlyHint: true, + destructiveHint: false, + idempotentHint: false, + openWorldHint: false + } + }, + async ({ action, name, portType, x, y, rotation, color, portId, target, timeoutMs }) => { + try { + const result = (await bridge.call( + "prepareSchematicPort", + { + action, + name, + portType, + x, + y, + rotation, + color, + portId, + target + }, + timeoutMs + )) as Record; + + const mutationId = String(result.mutationId ?? ""); + const confirmation = String(result.confirmation ?? ""); + const preview = (result.preview as { impact?: string; scope?: string }) ?? {}; + const summary = [ + `Prepared schematic port mutation '${action}':`, + `Impact: ${preview.impact ?? "none"}`, + `Scope: ${preview.scope ?? "active document"}`, + `Confirmation phrase required: "${confirmation}"`, + `Review the preview and run easyeda_confirmed_action with action="mutation", params={ mutationId: "${mutationId}" }, and the exact confirmation string.` + ].join("\n"); + + return ok(summary, result); + } catch (error) { + return fail(error); + } + } + ); + + server.registerTool( + "easyeda_prepare_schematic_bus", + { + title: "Prepare Schematic Bus Mutation", + description: + "Prepares a create, modify, or delete operation on schematic multi-bit buses or diagonal bus entries with syntax parsing, coordinate validation, preview, and exact confirmation phrase. Does not write until confirmed via easyeda_confirmed_action.", + inputSchema: { + action: z + .enum(["createBus", "modifyBus", "deleteBus", "createBusEntry", "deleteBusEntry"]) + .describe("Bus or bus entry action to perform"), + name: z.string().optional().describe("Bus name with syntax, e.g. 'DATA[0..7]' or 'ADDR[15:0]'"), + coordinates: z + .array(z.number()) + .optional() + .describe("Flat array of coordinates [x1, y1, x2, y2, ...] for bus polyline (min 4 numbers / 2 points)"), + lineWidth: z.number().optional().describe("Bus stroke width"), + color: z.string().optional().describe("Bus color string"), + busId: z.string().optional().describe("Target bus primitive ID for modify, delete, or attaching bus entry"), + entryId: z.string().optional().describe("Target bus entry primitive ID for delete"), + startX: z.number().optional().describe("Start X for bus entry tap"), + startY: z.number().optional().describe("Start Y for bus entry tap"), + endX: z.number().optional().describe("End X for bus entry tap"), + endY: z.number().optional().describe("End Y for bus entry tap"), + rotation: z.number().optional().describe("Rotation angle for bus entry"), + net: z.string().optional().describe("Net name for tapped signal (e.g. 'DATA0')"), + wireId: z.string().optional().describe("Primitive ID of wire connected by bus entry"), + target: DocumentTargetSchema.optional().describe("Expected active schematic target"), + timeoutMs: DefaultTimeoutSchema.default(30_000) + }, + annotations: { + readOnlyHint: true, + destructiveHint: false, + idempotentHint: false, + openWorldHint: false + } + }, + async ({ + action, + name, + coordinates, + lineWidth, + color, + busId, + entryId, + startX, + startY, + endX, + endY, + rotation, + net, + wireId, + target, + timeoutMs + }) => { + try { + const result = (await bridge.call( + "prepareSchematicBus", + { + action, + name, + coordinates, + lineWidth, + color, + busId, + entryId, + startX, + startY, + endX, + endY, + rotation, + net, + wireId, + target + }, + timeoutMs + )) as Record; + + const mutationId = String(result.mutationId ?? ""); + const confirmation = String(result.confirmation ?? ""); + const preview = (result.preview as { impact?: string; scope?: string }) ?? {}; + const summary = [ + `Prepared schematic bus mutation '${action}':`, + `Impact: ${preview.impact ?? "none"}`, + `Scope: ${preview.scope ?? "active document"}`, + `Confirmation phrase required: "${confirmation}"`, + `Review the preview and run easyeda_confirmed_action with action="mutation", params={ mutationId: "${mutationId}" }, and the exact confirmation string.` + ].join("\n"); + + return ok(summary, result); + } catch (error) { + return fail(error); + } + } + ); + server.registerTool( "easyeda_get_mutation_result", { diff --git a/src/mcp/tools/schematicTools.test.ts b/src/mcp/tools/schematicTools.test.ts index 6988477..6f4b16a 100644 --- a/src/mcp/tools/schematicTools.test.ts +++ b/src/mcp/tools/schematicTools.test.ts @@ -40,7 +40,8 @@ describe("schematicTools MCP registration and invocation", () => { "easyeda_find_unconnected_pins", "easyeda_run_schematic_erc", "easyeda_validate_schematic_area", - "easyeda_verify_connections" + "easyeda_verify_connections", + "easyeda_get_schematic_ports_buses" ]); }); @@ -128,4 +129,43 @@ describe("schematicTools MCP registration and invocation", () => { } }); }); + + it("invokes easyeda_get_schematic_ports_buses and returns ports, buses, and diagnostics", async () => { + const bridge = { + endpoint: "ws://127.0.0.1:8765", + getStatus: (): EditorStatus => ({ connected: true, updatedAt: new Date().toISOString() }), + call: vi.fn(async () => ({ + target: { documentType: "schematic" }, + summary: { portCount: 1, busCount: 1, busEntryCount: 1, totalSignalsInBuses: 8, warningsCount: 0 }, + ports: [{ primitiveId: "p1", name: "TXD", portType: "output", x: 10, y: 20, rotation: 0 }], + buses: [{ primitiveId: "b1", name: "DATA[0..7]", prefix: "DATA", signals: ["DATA0", "DATA1"] }], + busEntries: [{ primitiveId: "e1", startX: 10, startY: 20, endX: 20, endY: 30, net: "DATA0" }], + diagnostics: [] + })) + }; + const client = await makeClient(bridge); + + const result = await client.callTool({ + name: "easyeda_get_schematic_ports_buses", + arguments: { + includePorts: true, + includeBuses: true + } + }); + + expect(result.isError).toBeFalsy(); + expect(bridge.call).toHaveBeenCalledWith( + "getSchematicPortsBuses", + expect.objectContaining({ + includePorts: true, + includeBuses: true + }), + 15_000 + ); + expect(result.structuredContent).toMatchObject({ + result: { + summary: { portCount: 1, busCount: 1, totalSignalsInBuses: 8 } + } + }); + }); }); diff --git a/src/mcp/tools/schematicTools.ts b/src/mcp/tools/schematicTools.ts index b741be3..a52014a 100644 --- a/src/mcp/tools/schematicTools.ts +++ b/src/mcp/tools/schematicTools.ts @@ -277,4 +277,23 @@ export function registerSchematicTools(server: McpServer, bridge: EditorClient): }, summary: "Verified EasyEDA Pro schematic connections." }); + + registerReadTool(server, bridge, { + name: "easyeda_get_schematic_ports_buses", + title: "Get schematic ports and buses", + description: + "Inspects net ports (hierarchical/global sheet connectors), multi-bit buses, and bus entry taps in the active schematic with connection validation and signal range diagnostics.", + method: "getSchematicPortsBuses", + inputSchema: { + target: DocumentTargetSchema.optional().describe( + "Expected active schematic target to guard against document drift" + ), + includePorts: z.boolean().default(true).describe("Whether to include net ports"), + includeBuses: z.boolean().default(true).describe("Whether to include multi-bit buses"), + includeBusEntries: z.boolean().default(true).describe("Whether to include bus entry taps"), + includeRaw: z.boolean().default(false).describe("Whether to include raw primitive records from the editor"), + timeoutMs: DefaultTimeoutSchema.default(15_000) + }, + summary: "Fetched EasyEDA Pro schematic net ports and buses." + }); }