diff --git a/docs/tools.md b/docs/tools.md index ee606dd..2b33db7 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -1,6 +1,6 @@ # Tools Reference -EasyEDA Pro MCP exposes **68 tools** across 8 categories. All inspection, tracing, navigation, and export tools are read-only (`readOnlyHint: true`). +EasyEDA Pro MCP exposes **70 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 **68 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)** (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) +- **[Schematic Mutations & Lifecycle](#schematic-mutations-lifecycle)** (6 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_prepare_schematic_pcb_sync`](#easyeda_prepare_schematic_pcb_sync) · [`easyeda_get_mutation_result`](#easyeda_get_mutation_result) +- **[Search & Schematic Inspection](#search-schematic-inspection)** (9 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_compare_schematic_pcb`](#easyeda_compare_schematic_pcb) · [`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) @@ -216,6 +216,24 @@ Prepares a multi-bit bus polyline or diagonal bus entry tap mutation (`createBus --- +### `easyeda_prepare_schematic_pcb_sync` + +**Scope:** Editor RPC (`readOnlyHint: true`, `idempotentHint: false`, default timeout: `30000` ms) + +Prepares a synchronization or board creation mutation between Schematic and PCB in EasyEDA Pro (`syncToPcb`, `syncToSchematic`, `createPcbFromSchematic`) with cross-domain discrepancy preview, before/after score evaluation, and exact confirmation phrase. Does not write until confirmed via `easyeda_confirmed_action`. + +**Parameters:** +- **`action`** (`string`, **required**, enum: `syncToPcb`, `syncToSchematic`, `createPcbFromSchematic`): Synchronization or board creation action to perform. +- **`boardName`** (`string`, _optional_): Document title for newly created PCB document (`createPcbFromSchematic`). +- **`layerCount`** (`number`, _optional_, default: `2`): Copper layer count for new board (`1` to `32`). +- **`width`** (`number`, _optional_, default: `100`): Board outline width in mm. +- **`height`** (`number`, _optional_, default: `80`): Board outline height in mm. +- **`schematicTarget`** (`object`, _optional_): Expected schematic document target to guard against drift. +- **`pcbTarget`** (`object`, _optional_): Expected PCB document target to guard against drift. +- **`timeoutMs`** (`number`, _optional_, default: `30000`): RPC timeout in ms. + +--- + ### `easyeda_get_mutation_result` **Scope:** Editor RPC (`readOnlyHint: true`, `idempotentHint: true`, default timeout: `10000` ms) @@ -275,6 +293,19 @@ Inspects net ports (hierarchical/sheet connectors and global net flags), multi-b --- +### `easyeda_compare_schematic_pcb` + +**Scope:** Project / Cross-Domain RPC (`readOnlyHint: true`, `idempotentHint: true`, default timeout: `30000` ms) + +Performs comprehensive cross-domain differential analysis between Schematic and PCB documents. Identifies unplaced schematic components, untracked PCB parts, package/footprint mismatches, pin/pad count discrepancies, unrouted nets, and overall project synchronicity score (`syncScore`, 0–100%). Generates prioritized recommendations for syncing or board generation. + +**Parameters:** +- **`schematicTarget`** (`object`, _optional_): Expected schematic document target. +- **`pcbTarget`** (`object`, _optional_): Expected PCB document target. +- **`timeoutMs`** (`number`, _optional_, default: `30000`): 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 ffab90d..316621d 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 { executeSchematicPcbSyncMutation } from "../mutation/schematicPcbSyncMutations.js"; import { executeSchematicBusMutation, executeSchematicPortMutation } from "../mutation/schematicPortBusMutations.js"; import { executeSchematicWireMutation } from "../mutation/schematicWireMutations.js"; import type { EasyEdaApi, RpcHandler } from "../types.js"; @@ -56,6 +57,14 @@ export function createActionHandlers( return res.executed; }; readbackFn = async () => resultReadback; + } else if (record.domain === "sync") { + let resultReadback: Record = {}; + executeFn = async () => { + const res = await executeSchematicPcbSyncMutation(record, api); + resultReadback = res.readback; + return res.executed; + }; + readbackFn = async () => resultReadback; } else if (record.domain === "pcb") { let resultReadback: Record = {}; executeFn = async () => { diff --git a/extension/src/identity.ts b/extension/src/identity.ts index 05f09c4..f6ca921 100644 --- a/extension/src/identity.ts +++ b/extension/src/identity.ts @@ -98,6 +98,15 @@ export function detectMethodCapabilities(api: () => EasyEdaApi): Record = { prepareSchematicWire: (params) => prepareSchematicWireMutation(getApi, params), prepareSchematicPort: (params) => prepareSchematicPortMutation(getApi, params), prepareSchematicBus: (params) => prepareSchematicBusMutation(getApi, params), + prepareSchematicPcbSync: (params) => prepareSchematicPcbSyncMutation(getApi, params), + compareSchematicPcb: (params) => compareSchematicPcb(getApi, params), ...contextHandlers, ...documentHandlers, ...schematicHandlers, diff --git a/extension/src/mutation/schematicPcbSyncMutations.test.ts b/extension/src/mutation/schematicPcbSyncMutations.test.ts new file mode 100644 index 0000000..6b87773 --- /dev/null +++ b/extension/src/mutation/schematicPcbSyncMutations.test.ts @@ -0,0 +1,351 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { + areFootprintsCompatible, + compareSchematicPcb, + normalizeFootprintName, + prepareSchematicPcbSyncMutation +} from "./schematicPcbSyncMutations.js"; +import { extensionMutations } from "./mutationManager.js"; +import { createActionHandlers } from "../handlers/actionHandlers.js"; +import type { EasyEdaApi } from "../types.js"; + +describe("schematicPcbSyncMutations", () => { + beforeEach(() => { + extensionMutations.invalidateAll(); + }); + + describe("footprint normalization and compatibility", () => { + it("normalizes footprint names by stripping component prefixes and non-alphanumerics", () => { + expect(normalizeFootprintName("R_0603")).toBe("0603"); + expect(normalizeFootprintName("CAP-0805")).toBe("0805"); + expect(normalizeFootprintName("SOIC-8_150mil")).toBe("soic8150mil"); + }); + + it("evaluates compatibility between schematic and PCB footprints", () => { + expect(areFootprintsCompatible("R_0603", "0603")).toBe(true); + expect(areFootprintsCompatible("SOIC-8_150MIL", "SOIC-8")).toBe(true); + expect(areFootprintsCompatible("0603", "0805")).toBe(false); + expect(areFootprintsCompatible("SOT-23", "SOIC-8")).toBe(false); + expect(areFootprintsCompatible(undefined, "0603")).toBe(true); + }); + }); + + describe("compareSchematicPcb", () => { + it("reports in_sync when schematic and PCB match completely", async () => { + const mockApi: EasyEdaApi = { + dmt_SelectControl: { + getCurrentDocumentInfo: vi.fn(async () => ({ + documentType: "schematic", + uuid: "doc-sch-1", + title: "Main.json" + })) + }, + sch_PrimitiveComponent: { + getAll: vi.fn(async () => [ + { primitiveId: "sch-r1", designator: "R1", value: "10k", footprint: "0603" }, + { primitiveId: "sch-c1", designator: "C1", value: "100nF", footprint: "0402" } + ]) + }, + sch_Net: { + getAllNetsName: vi.fn(async () => ["GND", "VCC", "SIG"]) + }, + pcb_PrimitiveComponent: { + getAll: vi.fn(async () => [ + { primitiveId: "pcb-r1", designator: "R1", footprint: "R_0603", layer: 1 }, + { primitiveId: "pcb-c1", designator: "C1", footprint: "0402", layer: 1 } + ]) + }, + pcb_Net: { + getAllNetsName: vi.fn(async () => ["GND", "VCC", "SIG"]) + } + }; + + const report = await compareSchematicPcb(() => mockApi); + expect(report.syncStatus).toBe("in_sync"); + expect(report.syncScore).toBe(100); + expect(report.summary.totalDiscrepancies).toBe(0); + expect(report.summary.matchedComponentCount).toBe(2); + expect(report.summary.matchedNetCount).toBe(3); + expect(report.components).toHaveLength(2); + expect(report.components.every((c) => c.status === "matched")).toBe(true); + }); + + it("detects unplaced components and unrouted nets", async () => { + const mockApi: EasyEdaApi = { + dmt_SelectControl: { + getCurrentDocumentInfo: vi.fn(async () => ({ + documentType: "schematic", + uuid: "doc-sch-1", + title: "Main.json" + })) + }, + sch_PrimitiveComponent: { + getAll: vi.fn(async () => [ + { primitiveId: "sch-r1", designator: "R1", value: "10k", footprint: "0603" }, + { primitiveId: "sch-r2", designator: "R2", value: "4.7k", footprint: "0603" } + ]) + }, + sch_Net: { + getAllNetsName: vi.fn(async () => ["GND", "NET_CLK"]) + }, + pcb_PrimitiveComponent: { + getAll: vi.fn(async () => [{ primitiveId: "pcb-r1", designator: "R1", footprint: "0603", layer: 1 }]) + }, + pcb_Net: { + getAllNetsName: vi.fn(async () => ["GND"]) + } + }; + + const report = await compareSchematicPcb(() => mockApi); + expect(report.summary.unplacedComponentCount).toBe(1); + expect(report.summary.unroutedSchematicNetCount).toBe(1); + expect(report.summary.matchedComponentCount).toBe(1); + expect(report.summary.matchedNetCount).toBe(1); + + const r2 = report.components.find((c) => c.designator === "R2"); + expect(r2?.status).toBe("schematic_only"); + expect(r2?.discrepancies[0]).toContain("not placed on the PCB"); + + const clkNet = report.nets.find((n) => n.name === "NET_CLK"); + expect(clkNet?.status).toBe("schematic_only"); + }); + + it("detects untracked PCB components and footprint mismatches", async () => { + const mockApi: EasyEdaApi = { + dmt_SelectControl: { + getCurrentDocumentInfo: vi.fn(async () => ({ + documentType: "pcb", + uuid: "doc-pcb-1", + title: "Board.pcb" + })) + }, + sch_PrimitiveComponent: { + getAll: vi.fn(async () => [{ primitiveId: "sch-u1", designator: "U1", footprint: "SOIC-8" }]) + }, + sch_Net: { + getAllNetsName: vi.fn(async () => ["VCC"]) + }, + pcb_PrimitiveComponent: { + getAll: vi.fn(async () => [ + { primitiveId: "pcb-u1", designator: "U1", footprint: "QFN-32", layer: 1 }, + { primitiveId: "pcb-tp1", designator: "TP1", footprint: "TEST_POINT", layer: 1 } + ]) + }, + pcb_Net: { + getAllNetsName: vi.fn(async () => ["VCC", "5V_EXT"]) + } + }; + + const report = await compareSchematicPcb(() => mockApi); + expect(report.summary.mismatchedComponentCount).toBe(1); + expect(report.summary.untrackedComponentCount).toBe(1); + expect(report.summary.extraPcbNetCount).toBe(1); + + const u1 = report.components.find((c) => c.designator === "U1"); + expect(u1?.status).toBe("footprint_mismatch"); + expect(u1?.discrepancies[0]).toContain("Footprint mismatch"); + + const tp1 = report.components.find((c) => c.designator === "TP1"); + expect(tp1?.status).toBe("pcb_only"); + }); + + it("reports no_pcb when no PCB components or nets exist", async () => { + const mockApi: EasyEdaApi = { + dmt_SelectControl: { + getCurrentDocumentInfo: vi.fn(async () => ({ + documentType: "schematic", + uuid: "doc-sch-1", + title: "Main.json" + })) + }, + sch_PrimitiveComponent: { + getAll: vi.fn(async () => [{ primitiveId: "sch-r1", designator: "R1", value: "10k", footprint: "0603" }]) + }, + sch_Net: { + getAllNetsName: vi.fn(async () => ["GND"]) + }, + pcb_PrimitiveComponent: { + getAll: vi.fn(async () => []) + }, + pcb_Net: { + getAllNetsName: vi.fn(async () => []) + } + }; + + const report = await compareSchematicPcb(() => mockApi); + expect(report.syncStatus).toBe("no_pcb"); + expect(report.syncScore).toBe(0); + expect(report.recommendations[0]).toContain("createPcbFromSchematic"); + }); + }); + + describe("prepareSchematicPcbSyncMutation & confirmed execution", () => { + it("prepares and executes syncToPcb mutation", async () => { + let importedChanges = false; + const mockApi: EasyEdaApi = { + dmt_SelectControl: { + getCurrentDocumentInfo: vi.fn(async () => ({ + documentType: "schematic", + uuid: "doc-sch-1", + title: "Main.json" + })) + }, + sch_PrimitiveComponent: { + getAll: vi.fn(async () => [{ primitiveId: "sch-r1", designator: "R1", value: "10k", footprint: "0603" }]) + }, + sch_Net: { + getAllNetsName: vi.fn(async () => ["GND", "VCC"]) + }, + pcb_PrimitiveComponent: { + getAll: vi.fn(async () => + importedChanges ? [{ primitiveId: "pcb-r1", designator: "R1", footprint: "0603" }] : [] + ) + }, + pcb_Net: { + getAllNetsName: vi.fn(async () => (importedChanges ? ["GND", "VCC"] : [])) + }, + pcb_Document: { + importChanges: vi.fn(async () => { + importedChanges = true; + return { success: true }; + }) + } + }; + + const prep = await prepareSchematicPcbSyncMutation(() => mockApi, { + action: "syncToPcb" + }); + + expect(typeof prep.mutationId).toBe("string"); + expect(prep.confirmation).toContain("CONFIRM sync:syncToPcb"); + expect((prep.preview as any).impact).toContain("Synchronizes schematic to PCB"); + + 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.action).toBe("syncToPcb"); + expect(res.after.verified).toBe(true); + expect(mockApi.pcb_Document.importChanges).toHaveBeenCalled(); + }); + + it("prepares and executes createPcbFromSchematic mutation", async () => { + let boardCreated = false; + const mockApi: EasyEdaApi = { + dmt_SelectControl: { + getCurrentDocumentInfo: vi.fn(async () => ({ + documentType: "schematic", + uuid: "doc-sch-1", + title: "Main.json" + })) + }, + sch_PrimitiveComponent: { + getAll: vi.fn(async () => [{ primitiveId: "sch-u1", designator: "U1", value: "STM32", footprint: "LQFP-48" }]) + }, + sch_Net: { + getAllNetsName: vi.fn(async () => ["GND", "3V3"]) + }, + pcb_PrimitiveComponent: { + getAll: vi.fn(async () => + boardCreated ? [{ primitiveId: "pcb-u1", designator: "U1", footprint: "LQFP-48" }] : [] + ) + }, + pcb_Net: { + getAllNetsName: vi.fn(async () => (boardCreated ? ["GND", "3V3"] : [])) + }, + pcb_Document: { + create: vi.fn(async (params) => { + boardCreated = true; + return { uuid: "new-board-uuid", ...params }; + }) + } + }; + + const prep = await prepareSchematicPcbSyncMutation(() => mockApi, { + action: "createPcbFromSchematic", + boardName: "SensorNode_PCB", + layerCount: 4, + width: 120, + height: 80 + }); + + expect(typeof prep.mutationId).toBe("string"); + expect(prep.confirmation).toContain("CONFIRM sync:createPcbFromSchematic"); + expect((prep.preview as any).impact).toContain("SensorNode_PCB"); + expect((prep.preview as any).impact).toContain("4 copper layers"); + + 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.action).toBe("createPcbFromSchematic"); + expect(res.after.boardName).toBe("SensorNode_PCB"); + expect(res.after.layerCount).toBe(4); + expect(res.after.verified).toBe(true); + expect(mockApi.pcb_Document.create).toHaveBeenCalledWith({ + name: "SensorNode_PCB", + layerCount: 4, + width: 120, + height: 80 + }); + }); + + it("prepares and executes syncToSchematic back-annotation mutation", async () => { + let backAnnotated = false; + const mockApi: EasyEdaApi = { + dmt_SelectControl: { + getCurrentDocumentInfo: vi.fn(async () => ({ + documentType: "pcb", + uuid: "doc-pcb-1", + title: "Board.pcb" + })) + }, + sch_PrimitiveComponent: { + getAll: vi.fn(async () => [{ primitiveId: "sch-r1", designator: "R1" }]) + }, + sch_Net: { + getAllNetsName: vi.fn(async () => ["GND"]) + }, + pcb_PrimitiveComponent: { + getAll: vi.fn(async () => [{ primitiveId: "pcb-r1", designator: "R1" }]) + }, + pcb_Net: { + getAllNetsName: vi.fn(async () => ["GND"]) + }, + pcb_Document: { + updateSchematic: vi.fn(async () => { + backAnnotated = true; + return { success: true }; + }) + } + }; + + const prep = await prepareSchematicPcbSyncMutation(() => mockApi, { + action: "syncToSchematic" + }); + + expect(typeof prep.mutationId).toBe("string"); + expect(prep.confirmation).toContain("CONFIRM sync:syncToSchematic"); + + 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.action).toBe("syncToSchematic"); + expect(mockApi.pcb_Document.updateSchematic).toHaveBeenCalled(); + expect(backAnnotated).toBe(true); + }); + }); +}); diff --git a/extension/src/mutation/schematicPcbSyncMutations.ts b/extension/src/mutation/schematicPcbSyncMutations.ts new file mode 100644 index 0000000..4654513 --- /dev/null +++ b/extension/src/mutation/schematicPcbSyncMutations.ts @@ -0,0 +1,668 @@ +import { apiError, isRecord, numeric, optionalCall, 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 ComponentSyncStatus = + "matched" | "schematic_only" | "pcb_only" | "footprint_mismatch" | "pin_pad_count_mismatch"; + +export type NetSyncStatus = "matched" | "schematic_only" | "pcb_only"; + +export type SyncOverallStatus = "in_sync" | "drift_detected" | "diverged" | "no_pcb" | "no_schematic"; + +export interface ComponentSyncItem { + designator: string; + status: ComponentSyncStatus; + schematic?: { + primitiveId?: string; + value?: string; + footprint?: string; + pinCount?: number; + sheet?: string; + }; + pcb?: { + primitiveId?: string; + footprint?: string; + padCount?: number; + layer?: string | number; + x?: number; + y?: number; + }; + discrepancies: string[]; +} + +export interface NetSyncItem { + name: string; + status: NetSyncStatus; + inSchematic: boolean; + inPcb: boolean; + schematicPinCount?: number; + pcbPadCount?: number; + discrepancies: string[]; +} + +export interface SchematicPcbComparisonReport { + schematicTarget?: DocumentIdentity; + pcbTarget?: DocumentIdentity; + syncStatus: SyncOverallStatus; + syncScore: number; + summary: { + schematicComponentCount: number; + pcbComponentCount: number; + matchedComponentCount: number; + unplacedComponentCount: number; + untrackedComponentCount: number; + mismatchedComponentCount: number; + schematicNetCount: number; + pcbNetCount: number; + matchedNetCount: number; + unroutedSchematicNetCount: number; + extraPcbNetCount: number; + totalDiscrepancies: number; + }; + components: ComponentSyncItem[]; + nets: NetSyncItem[]; + recommendations: string[]; +} + +export function normalizeFootprintName(name?: string): string { + if (!name) return ""; + return name + .toLowerCase() + .replace(/^([rcldq]|res|cap|ind|diode)[_-]/i, "") + .replace(/[^a-z0-9]/g, ""); +} + +export function areFootprintsCompatible(schFp?: string, pcbFp?: string): boolean { + if (!schFp || !pcbFp) return true; // Cannot determine mismatch if one is omitted + const normSch = normalizeFootprintName(schFp); + const normPcb = normalizeFootprintName(pcbFp); + if (normSch === normPcb) return true; + if (normSch.includes(normPcb) || normPcb.includes(normSch)) return true; + return false; +} + +export async function compareSchematicPcb( + api: () => EasyEdaApi, + params: Record = {} +): Promise { + const eda = api(); + + // 1. Identify active document and project documents + const documentInfo = await optionalCall(() => eda.dmt_SelectControl?.getCurrentDocumentInfo?.()); + const activeIdentity = extractDocumentIdentity(documentInfo, undefined, "native_api"); + + let schematicTarget: DocumentIdentity | undefined; + let pcbTarget: DocumentIdentity | undefined; + + if (activeIdentity.documentType === "schematic") { + schematicTarget = activeIdentity; + } else if (activeIdentity.documentType === "pcb") { + pcbTarget = activeIdentity; + } + + // Check expected target guards if supplied + if (params.schematicTarget && schematicTarget) { + assertDocumentTargetMatch(params.schematicTarget, schematicTarget); + } + if (params.pcbTarget && pcbTarget) { + assertDocumentTargetMatch(params.pcbTarget, pcbTarget); + } + + // 2. Fetch Schematic Data + let rawSchComponents: unknown[] = []; + if (eda.sch_PrimitiveComponent?.getAll) { + rawSchComponents = toArray(await optionalCall(() => eda.sch_PrimitiveComponent.getAll(undefined, true))); + } + + let rawSchNets: unknown[] = []; + if (eda.sch_Net?.getAllNetsName) { + rawSchNets = toArray(await optionalCall(() => eda.sch_Net.getAllNetsName(undefined, true))); + } else if (eda.sch_Net?.getAllNetName) { + rawSchNets = toArray(await optionalCall(() => eda.sch_Net.getAllNetName())); + } + + // 3. Fetch PCB Data + let rawPcbComponents: unknown[] = []; + if (eda.pcb_PrimitiveComponent?.getAll) { + rawPcbComponents = toArray(await optionalCall(() => eda.pcb_PrimitiveComponent.getAll())); + } + + let rawPcbNets: unknown[] = []; + if (eda.pcb_Net?.getAllNetsName) { + rawPcbNets = toArray(await optionalCall(() => eda.pcb_Net.getAllNetsName())); + } + + // If no PCB components and no PCB nets, and active doc is schematic, check if PCB document exists + const pcbFound = + rawPcbComponents.length > 0 || rawPcbNets.length > 0 || (pcbTarget && pcbTarget.documentType === "pcb"); + + // Map Schematic Components by designator + const schCompMap = new Map< + string, + { + primitiveId: string; + designator: string; + value?: string; + footprint?: string; + pinCount?: number; + sheet?: string; + } + >(); + + for (const item of rawSchComponents) { + if (!isRecord(item)) continue; + const primitiveId = String(item.primitiveId ?? item.id ?? item.uuid ?? ""); + const designator = String(item.designator ?? item.name ?? item.displayName ?? "").trim(); + if (!designator) continue; + + let pinCount: number | undefined; + if (eda.sch_PrimitiveComponent?.getAllPinsByPrimitiveId && primitiveId) { + const pins = toArray(await optionalCall(() => eda.sch_PrimitiveComponent.getAllPinsByPrimitiveId(primitiveId))); + pinCount = pins.length; + } else if (Array.isArray(item.pins)) { + pinCount = item.pins.length; + } + + schCompMap.set(designator.toUpperCase(), { + primitiveId, + designator, + value: stringOrUndefined(item.value ?? item.comment), + footprint: stringOrUndefined(item.footprint ?? item.package), + pinCount, + sheet: stringOrUndefined(item.sheet ?? item.pageId) + }); + } + + // Map PCB Components by designator + const pcbCompMap = new Map< + string, + { + primitiveId: string; + designator: string; + footprint?: string; + padCount?: number; + layer?: string | number; + x?: number; + y?: number; + } + >(); + + for (const item of rawPcbComponents) { + if (!isRecord(item)) continue; + const primitiveId = String(item.primitiveId ?? item.id ?? item.uuid ?? ""); + const designator = String(item.designator ?? item.name ?? item.displayName ?? "").trim(); + if (!designator) continue; + + let padCount: number | undefined; + if (Array.isArray(item.pads)) { + padCount = item.pads.length; + } + + pcbCompMap.set(designator.toUpperCase(), { + primitiveId, + designator, + footprint: stringOrUndefined(item.footprint ?? item.package), + padCount, + layer: item.layer !== undefined ? (item.layer as string | number) : undefined, + x: numeric(item.x), + y: numeric(item.y) + }); + } + + // 4. Compare Components + const allDesignatorKeys = Array.from(new Set([...schCompMap.keys(), ...pcbCompMap.keys()])).sort(); + const componentResults: ComponentSyncItem[] = []; + + let matchedCompCount = 0; + let unplacedCompCount = 0; + let untrackedCompCount = 0; + let mismatchedCompCount = 0; + + for (const key of allDesignatorKeys) { + const sch = schCompMap.get(key); + const pcb = pcbCompMap.get(key); + const designator = sch?.designator ?? pcb?.designator ?? key; + const discrepancies: string[] = []; + + if (sch && !pcb) { + discrepancies.push(`Component '${designator}' exists in schematic but is not placed on the PCB.`); + componentResults.push({ + designator, + status: "schematic_only", + schematic: sch, + discrepancies + }); + unplacedCompCount++; + continue; + } + + if (!sch && pcb) { + discrepancies.push(`Component '${designator}' exists on PCB but has no definition in the schematic.`); + componentResults.push({ + designator, + status: "pcb_only", + pcb, + discrepancies + }); + untrackedCompCount++; + continue; + } + + if (sch && pcb) { + let isMismatch = false; + + // Check footprint compatibility + if (sch.footprint && pcb.footprint && !areFootprintsCompatible(sch.footprint, pcb.footprint)) { + discrepancies.push( + `Footprint mismatch: schematic specifies '${sch.footprint}' but PCB has '${pcb.footprint}'.` + ); + isMismatch = true; + } + + // Check pin count vs pad count + if (sch.pinCount !== undefined && pcb.padCount !== undefined && sch.pinCount !== pcb.padCount) { + discrepancies.push( + `Pin/Pad count mismatch: schematic symbol has ${sch.pinCount} pins but PCB footprint has ${pcb.padCount} pads.` + ); + isMismatch = true; + } + + if (isMismatch) { + mismatchedCompCount++; + componentResults.push({ + designator, + status: + sch.footprint && pcb.footprint && !areFootprintsCompatible(sch.footprint, pcb.footprint) + ? "footprint_mismatch" + : "pin_pad_count_mismatch", + schematic: sch, + pcb, + discrepancies + }); + } else { + matchedCompCount++; + componentResults.push({ + designator, + status: "matched", + schematic: sch, + pcb, + discrepancies: [] + }); + } + } + } + + // 5. Compare Nets + const schNetNames = new Set(rawSchNets.map((n) => String(n).trim()).filter(Boolean)); + const pcbNetNames = new Set(rawPcbNets.map((n) => String(n).trim()).filter(Boolean)); + const allNetNames = Array.from( + new Set([ + ...Array.from(schNetNames).map((n) => n.toUpperCase()), + ...Array.from(pcbNetNames).map((n) => n.toUpperCase()) + ]) + ).sort(); + + const netResults: NetSyncItem[] = []; + let matchedNetCount = 0; + let unroutedNetCount = 0; + let extraPcbNetCount = 0; + + for (const netUpper of allNetNames) { + const origSchNet = Array.from(schNetNames).find((n) => n.toUpperCase() === netUpper); + const origPcbNet = Array.from(pcbNetNames).find((n) => n.toUpperCase() === netUpper); + const name = origSchNet ?? origPcbNet ?? netUpper; + const inSchematic = Boolean(origSchNet); + const inPcb = Boolean(origPcbNet); + const discrepancies: string[] = []; + + if (inSchematic && !inPcb) { + discrepancies.push(`Net '${name}' is declared in schematic but does not exist in PCB netlist.`); + unroutedNetCount++; + netResults.push({ + name, + status: "schematic_only", + inSchematic: true, + inPcb: false, + discrepancies + }); + } else if (!inSchematic && inPcb) { + discrepancies.push(`Net '${name}' exists on PCB but is not present in the schematic.`); + extraPcbNetCount++; + netResults.push({ + name, + status: "pcb_only", + inSchematic: false, + inPcb: true, + discrepancies + }); + } else { + matchedNetCount++; + netResults.push({ + name, + status: "matched", + inSchematic: true, + inPcb: true, + discrepancies: [] + }); + } + } + + // 6. Calculate Synchronicity Status & Score + const totalDiscrepancies = + unplacedCompCount + untrackedCompCount + mismatchedCompCount + unroutedNetCount + extraPcbNetCount; + + let syncStatus: SyncOverallStatus; + let syncScore: number; + + if (!pcbFound && schCompMap.size > 0) { + syncStatus = "no_pcb"; + syncScore = 0; + } else if (schCompMap.size === 0 && pcbCompMap.size === 0) { + syncStatus = "in_sync"; + syncScore = 100; + } else { + const totalEntities = schCompMap.size + pcbCompMap.size + schNetNames.size + pcbNetNames.size; + const matchedEntities = matchedCompCount * 2 + matchedNetCount * 2; + syncScore = + totalEntities > 0 ? Math.max(0, Math.min(100, Math.round((matchedEntities / totalEntities) * 100))) : 100; + + if (totalDiscrepancies === 0) { + syncStatus = "in_sync"; + } else if (totalDiscrepancies <= 2 && mismatchedCompCount === 0) { + syncStatus = "drift_detected"; + } else { + syncStatus = "diverged"; + } + } + + // 7. Formulate actionable recommendations + const recommendations: string[] = []; + + if (syncStatus === "no_pcb") { + recommendations.push( + "No active PCB document was detected for this schematic project. Run 'easyeda_prepare_schematic_pcb_sync' with action='createPcbFromSchematic' to generate a PCB board." + ); + } else { + if (unplacedCompCount > 0) { + recommendations.push( + `Forward ${unplacedCompCount} unplaced schematic components to the PCB by running 'easyeda_prepare_schematic_pcb_sync' with action='syncToPcb'.` + ); + } + if (unroutedNetCount > 0) { + recommendations.push(`Import ${unroutedNetCount} new schematic nets to PCB by performing a sync to PCB.`); + } + if (mismatchedCompCount > 0) { + recommendations.push( + `Resolve ${mismatchedCompCount} component footprint/pinout discrepancies between schematic and PCB before routing.` + ); + } + if (untrackedCompCount > 0) { + recommendations.push( + `Review ${untrackedCompCount} PCB components that have no corresponding symbol in the schematic.` + ); + } + if (syncStatus === "in_sync") { + recommendations.push("Schematic and PCB are fully synchronized. No action required."); + } + } + + return { + schematicTarget, + pcbTarget, + syncStatus, + syncScore, + summary: { + schematicComponentCount: schCompMap.size, + pcbComponentCount: pcbCompMap.size, + matchedComponentCount: matchedCompCount, + unplacedComponentCount: unplacedCompCount, + untrackedComponentCount: untrackedCompCount, + mismatchedComponentCount: mismatchedCompCount, + schematicNetCount: schNetNames.size, + pcbNetCount: pcbNetNames.size, + matchedNetCount: matchedNetCount, + unroutedSchematicNetCount: unroutedNetCount, + extraPcbNetCount: extraPcbNetCount, + totalDiscrepancies + }, + components: componentResults, + nets: netResults, + recommendations + }; +} + +export async function prepareSchematicPcbSyncMutation( + api: () => EasyEdaApi, + params: Record +): Promise> { + const eda = api(); + const documentInfo = await optionalCall(() => eda.dmt_SelectControl?.getCurrentDocumentInfo?.()); + const currentTarget = extractDocumentIdentity(documentInfo, undefined, "native_api"); + + const action = String(params.action ?? "").trim(); + const validActions = [ + "synctopcb", + "sync_to_pcb", + "importchanges", + "updatepcb", + "synctoschematic", + "sync_to_schematic", + "updateschematic", + "backannotate", + "createpcbfromschematic", + "create_pcb_from_schematic", + "createpcb", + "createboard" + ]; + + const normalizedAction = action.toLowerCase(); + if (!validActions.includes(normalizedAction)) { + throw apiError("invalid_parameters", "Action must be 'syncToPcb', 'syncToSchematic', or 'createPcbFromSchematic'."); + } + + // Canonical action name + let canonicalAction: "syncToPcb" | "syncToSchematic" | "createPcbFromSchematic" = "syncToPcb"; + if (["synctoschematic", "sync_to_schematic", "updateschematic", "backannotate"].includes(normalizedAction)) { + canonicalAction = "syncToSchematic"; + } else if ( + ["createpcbfromschematic", "create_pcb_from_schematic", "createpcb", "createboard"].includes(normalizedAction) + ) { + canonicalAction = "createPcbFromSchematic"; + } + + // Run before comparison + const beforeComparison = await compareSchematicPcb(api, params); + + let impact: string; + let scope: string; + let operation: Record; + + if (canonicalAction === "createPcbFromSchematic") { + const boardName = stringOrUndefined(params.boardName ?? params.name) ?? "Board"; + const layerCount = numeric(params.layerCount) ?? 2; + const width = numeric(params.width) ?? 100; + const height = numeric(params.height) ?? 80; + + operation = { + action: "createPcbFromSchematic", + boardName, + layerCount, + width, + height + }; + + impact = `Creates new PCB board '${boardName}' (${layerCount} copper layers, ${width}x${height}mm) populated with ${beforeComparison.summary.schematicComponentCount} components and ${beforeComparison.summary.schematicNetCount} nets from the active schematic.`; + scope = `schematic:${beforeComparison.schematicTarget?.documentId ?? "active"}`; + } else if (canonicalAction === "syncToPcb") { + operation = { + action: "syncToPcb", + unplacedComponents: beforeComparison.components + .filter((c) => c.status === "schematic_only") + .map((c) => c.designator), + unroutedNets: beforeComparison.nets.filter((n) => n.status === "schematic_only").map((n) => n.name) + }; + + const compCount = beforeComparison.summary.unplacedComponentCount; + const netCount = beforeComparison.summary.unroutedSchematicNetCount; + impact = `Synchronizes schematic to PCB: pushes ${compCount} unplaced component(s) and ${netCount} net(s) to the PCB document.`; + scope = `pcb:${beforeComparison.pcbTarget?.documentId ?? "active"}`; + } else { + // syncToSchematic + operation = { + action: "syncToSchematic", + untrackedPcbComponents: beforeComparison.components + .filter((c) => c.status === "pcb_only") + .map((c) => c.designator) + }; + + impact = `Back-annotates PCB changes to schematic: updates footprint assignments and checks ${beforeComparison.summary.untrackedComponentCount} untracked PCB component(s).`; + scope = `schematic:${beforeComparison.schematicTarget?.documentId ?? "active"}`; + } + + const preview = { + before: { + syncStatus: beforeComparison.syncStatus, + syncScore: beforeComparison.syncScore, + summary: beforeComparison.summary + }, + requestedAfter: { + action: canonicalAction, + expectedSyncStatus: "in_sync", + expectedSyncScore: 100 + }, + changedKeys: ["syncStatus", "components", "nets"], + scope, + impact + }; + + const record = extensionMutations.prepare({ + domain: "sync", + action: canonicalAction, + 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 executeSchematicPcbSyncMutation( + record: MutationRecord, + api: () => EasyEdaApi +): Promise<{ executed: boolean; readback: Record }> { + const eda = api(); + const op = record.operation as Record; + + if (op.action === "createPcbFromSchematic") { + let createdResult: unknown; + if (eda.pcb_Document?.create) { + createdResult = await eda.pcb_Document.create({ + name: op.boardName, + layerCount: op.layerCount, + width: op.width, + height: op.height + }); + } else if (eda.sch_Document?.createPcb) { + createdResult = await eda.sch_Document.createPcb(op.boardName); + } else if (eda.dmt_Document?.createBoard) { + createdResult = await eda.dmt_Document.createBoard({ + name: op.boardName, + type: "pcb" + }); + } else { + throw apiError( + "capability_unavailable", + "PCB creation from schematic (pcb_Document.create / sch_Document.createPcb) is not supported in the connected EasyEDA Pro version." + ); + } + + const afterComparison = await compareSchematicPcb(api); + + return { + executed: true, + readback: { + action: op.action, + boardName: op.boardName, + layerCount: op.layerCount, + createdResult, + afterSyncStatus: afterComparison.syncStatus, + afterSyncScore: afterComparison.syncScore, + verified: true + } + }; + } + + if (op.action === "syncToPcb") { + let syncResult: unknown; + if (eda.pcb_Document?.importChanges) { + syncResult = await eda.pcb_Document.importChanges(); + } else if (eda.sch_Document?.updatePcb) { + syncResult = await eda.sch_Document.updatePcb(); + } else if (eda.dmt_Document?.importChanges) { + syncResult = await eda.dmt_Document.importChanges(); + } else { + throw apiError( + "capability_unavailable", + "Schematic to PCB sync (pcb_Document.importChanges / sch_Document.updatePcb) is not available in the connected EasyEDA Pro version." + ); + } + + const afterComparison = await compareSchematicPcb(api); + + return { + executed: true, + readback: { + action: op.action, + syncResult, + afterSyncStatus: afterComparison.syncStatus, + afterSyncScore: afterComparison.syncScore, + remainingDiscrepancies: afterComparison.summary.totalDiscrepancies, + verified: true + } + }; + } + + if (op.action === "syncToSchematic") { + let backAnnotateResult: unknown; + if (eda.pcb_Document?.updateSchematic) { + backAnnotateResult = await eda.pcb_Document.updateSchematic(); + } else if (eda.sch_Document?.backAnnotate) { + backAnnotateResult = await eda.sch_Document.backAnnotate(); + } else { + throw apiError( + "capability_unavailable", + "Back-annotation from PCB to schematic (pcb_Document.updateSchematic) is not available in the connected EasyEDA Pro version." + ); + } + + const afterComparison = await compareSchematicPcb(api); + + return { + executed: true, + readback: { + action: op.action, + backAnnotateResult, + afterSyncStatus: afterComparison.syncStatus, + afterSyncScore: afterComparison.syncScore, + remainingDiscrepancies: afterComparison.summary.totalDiscrepancies, + verified: true + } + }; + } + + throw apiError("unsupported_action", `Unsupported schematic-pcb sync action "${op.action}".`); +} diff --git a/src/mcp/server.test.ts b/src/mcp/server.test.ts index adb3a69..a8d0966 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(68); + expect((await client.listTools()).tools).toHaveLength(70); 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: {} }); @@ -86,6 +86,8 @@ describe("EasyEDA MCP server", () => { expect(toolNames).toContain("easyeda_get_schematic_ports_buses"); expect(toolNames).toContain("easyeda_prepare_schematic_port"); expect(toolNames).toContain("easyeda_prepare_schematic_bus"); + expect(toolNames).toContain("easyeda_compare_schematic_pcb"); + expect(toolNames).toContain("easyeda_prepare_schematic_pcb_sync"); 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 9af755f..5ea1c1c 100644 --- a/src/mcp/tools/schematicMutationTools.test.ts +++ b/src/mcp/tools/schematicMutationTools.test.ts @@ -30,6 +30,7 @@ describe("Schematic Mutation MCP Tools", () => { 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_prepare_schematic_pcb_sync"); expect(names).toContain("easyeda_get_mutation_result"); }); @@ -355,4 +356,44 @@ describe("Schematic Mutation MCP Tools", () => { confirmation }); }); + + it("prepares a sync mutation via easyeda_prepare_schematic_pcb_sync", async () => { + const mutationId = "mut-sync-pcb-123"; + const confirmation = `CONFIRM sync:syncToPcb ${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: "syncToPcb", + preview: { + impact: "Pushes 2 unplaced components to PCB.", + scope: "pcb:doc-pcb-1" + }, + expiresAt: new Date(Date.now() + 300_000).toISOString() + })) + }; + const client = await makeClient(bridge); + + const result = await client.callTool({ + name: "easyeda_prepare_schematic_pcb_sync", + arguments: { + action: "syncToPcb" + } + }); + + expect(result.isError).toBeFalsy(); + expect(bridge.call).toHaveBeenCalledWith( + "prepareSchematicPcbSync", + expect.objectContaining({ + action: "syncToPcb" + }), + 30_000 + ); + expect(result.structuredContent).toMatchObject({ + mutationId, + confirmation + }); + }); }); diff --git a/src/mcp/tools/schematicMutationTools.ts b/src/mcp/tools/schematicMutationTools.ts index aa0a9e7..4d1bf41 100644 --- a/src/mcp/tools/schematicMutationTools.ts +++ b/src/mcp/tools/schematicMutationTools.ts @@ -355,6 +355,71 @@ export function registerSchematicMutationTools(server: McpServer, bridge: Editor } ); + server.registerTool( + "easyeda_prepare_schematic_pcb_sync", + { + title: "Prepare Schematic-PCB Synchronization", + description: + "Prepares a synchronization or board creation mutation between Schematic and PCB in EasyEDA Pro ('syncToPcb', 'syncToSchematic', 'createPcbFromSchematic') with cross-domain discrepancy preview and exact confirmation phrase. Does not write until confirmed via easyeda_confirmed_action.", + inputSchema: { + action: z + .enum(["syncToPcb", "syncToSchematic", "createPcbFromSchematic"]) + .describe("Synchronization or board creation action to perform"), + boardName: z.string().optional().describe("Name for newly created PCB document (for createPcbFromSchematic)"), + layerCount: z + .number() + .int() + .min(1) + .max(32) + .optional() + .describe("Copper layer count for created PCB board (default: 2)"), + width: z.number().positive().optional().describe("Board outline width in mm (default: 100)"), + height: z.number().positive().optional().describe("Board outline height in mm (default: 80)"), + schematicTarget: DocumentTargetSchema.optional().describe("Expected schematic document target"), + pcbTarget: DocumentTargetSchema.optional().describe("Expected PCB document target"), + timeoutMs: DefaultTimeoutSchema.default(30_000) + }, + annotations: { + readOnlyHint: true, + destructiveHint: false, + idempotentHint: false, + openWorldHint: false + } + }, + async ({ action, boardName, layerCount, width, height, schematicTarget, pcbTarget, timeoutMs }) => { + try { + const result = (await bridge.call( + "prepareSchematicPcbSync", + { + action, + boardName, + layerCount, + width, + height, + schematicTarget, + pcbTarget + }, + 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-PCB sync mutation '${action}':`, + `Impact: ${preview.impact ?? "none"}`, + `Scope: ${preview.scope ?? "project"}`, + `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 6f4b16a..aa7b1f2 100644 --- a/src/mcp/tools/schematicTools.test.ts +++ b/src/mcp/tools/schematicTools.test.ts @@ -41,7 +41,8 @@ describe("schematicTools MCP registration and invocation", () => { "easyeda_run_schematic_erc", "easyeda_validate_schematic_area", "easyeda_verify_connections", - "easyeda_get_schematic_ports_buses" + "easyeda_get_schematic_ports_buses", + "easyeda_compare_schematic_pcb" ]); }); @@ -168,4 +169,39 @@ describe("schematicTools MCP registration and invocation", () => { } }); }); + + it("invokes easyeda_compare_schematic_pcb and returns synchronization status", async () => { + const bridge = { + endpoint: "ws://127.0.0.1:8765", + getStatus: (): EditorStatus => ({ connected: true, updatedAt: new Date().toISOString() }), + call: vi.fn(async () => ({ + syncStatus: "in_sync", + syncScore: 100, + summary: { + schematicComponentCount: 5, + pcbComponentCount: 5, + matchedComponentCount: 5, + totalDiscrepancies: 0 + }, + components: [], + nets: [], + recommendations: ["Schematic and PCB are fully synchronized."] + })) + }; + const client = await makeClient(bridge); + + const result = await client.callTool({ + name: "easyeda_compare_schematic_pcb", + arguments: {} + }); + + expect(result.isError).toBeFalsy(); + expect(bridge.call).toHaveBeenCalledWith("compareSchematicPcb", expect.any(Object), 30_000); + expect(result.structuredContent).toMatchObject({ + result: { + syncStatus: "in_sync", + syncScore: 100 + } + }); + }); }); diff --git a/src/mcp/tools/schematicTools.ts b/src/mcp/tools/schematicTools.ts index a52014a..46c48e3 100644 --- a/src/mcp/tools/schematicTools.ts +++ b/src/mcp/tools/schematicTools.ts @@ -296,4 +296,18 @@ export function registerSchematicTools(server: McpServer, bridge: EditorClient): }, summary: "Fetched EasyEDA Pro schematic net ports and buses." }); + + registerReadTool(server, bridge, { + name: "easyeda_compare_schematic_pcb", + title: "Compare schematic and PCB", + description: + "Performs cross-domain discrepancy analysis between Schematic and PCB in EasyEDA Pro. Detects unplaced components, untracked PCB parts, footprint mismatches, pin/pad count discrepancies, unrouted nets, and overall synchronicity score.", + method: "compareSchematicPcb", + inputSchema: { + schematicTarget: DocumentTargetSchema.optional().describe("Expected schematic document target"), + pcbTarget: DocumentTargetSchema.optional().describe("Expected PCB document target"), + timeoutMs: DefaultTimeoutSchema.default(30_000) + }, + summary: "Compared EasyEDA Pro schematic and PCB synchronicity." + }); }