Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@ All notable changes to the EasyEDA Pro MCP server and browser extension are docu

For packaged `.eext` and `.mcpb` downloads and checksums, see [GitHub Releases](https://github.com/VLab-Software/easyeda_mcp/releases).

## `1.4.1` (Extension `0.5.1`)

- feat: reconcile single-page snapshots with native Protel2 netlists
- fix: serialize native wire readback as plain JSON
- fix: track mutation deadlines and reconcile late completion
- fix: decode native wire segment groups without artificial diagonals
- fix: preserve schematic wire geometry and net identity

## `1.4.0` (Extension `0.5.0`)

- feat(spice): simulation feasibility assessment, component audit and SPICE netlist generation (Phase 5.5)
Expand Down
35 changes: 35 additions & 0 deletions docs/tools.md
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,23 @@ Builds a normalized snapshot of the active schematic: components, pins, wires, l

---

**Native connectivity:** with `allPages: false`, the extension attempts
`sch_ManufactureData.getNetlistFile("mcp-native-connectivity", "Protel2")` and reads the returned
File in memory. It does not save an export or modify the schematic. The read has a 3-second budget
and a 2 MB limit. Only supported Protel2 component and net records are parsed.

The `nativeNetlist` result reports `status`, `format`, `matchedPins`, `conflicts`, and an optional
`reason`. Pins matched by an exact, project-unique designator and pin number use
`netSource: "native_netlist"`. Native membership takes precedence over geometric inference;
disagreements produce warnings. Conflicting native memberships remain unknown.

An absent member does not prove disconnection: exports may omit components. Missing APIs,
unsupported files, timeouts, duplicate designators, and unmatched pins retain explicit geometric
fallback. Multi-page snapshots currently do not apply native membership because page-local IDs
and duplicate references need a separate scoped reconciliation. This integration requires a real
editor check after reloading the rebuilt extension; parsing tests alone do not establish export
compatibility with every EasyEDA version.

### `easyeda_get_schematic_nets`

**Scope:** Schematic RPC (`readOnlyHint: true`, `idempotentHint: true`, default timeout: `30000` ms)
Expand Down Expand Up @@ -1346,6 +1363,24 @@ Executes a mutating EasyEDA Pro action only after human confirmation is verified
- **`params`** (`object`, _optional_): Required for `editDrcRules` (`{ "editId": "<UUID>" }`) and `mutation` (`{ "mutationId": "<UUID>" }`).
- **`timeoutMs`** (`number`, _optional_, default: `60000`): RPC timeout in ms.

For staged mutations (`action: "mutation"`), the extension also tracks a 45-second execution deadline,
independent of the RPC timeout. A deadline returns `status: "unknown"`, not proof of cancellation.
Query `easyeda_get_mutation_result` with the same mutation ID; never replay an uncertain write.
The result includes `phase`, execution timestamps, and `execution` diagnostics (`timeoutMs`,
`elapsedMs`, `lockHeld`, and recovery guidance). Busy errors include the active mutation record.

The original operation remains observed after the deadline. Late completion runs readback and
updates the retained result; late rejection preserves uncertainty and releases the lock. A completed write whose readback fails validation or serialization remains `unknown`, with the
original error and mutation ID available for inspection; it is not evidence that the write failed.
Wire rename readback stores explicit plain state fields and verifies the returned net name.
A pending
executor retains its lock because the native SDK write cannot be cancelled by a JavaScript timeout.
If it never settles, reload the extension and inspect the document before preparing another write.
A stalled read-only lifecycle readback releases its lock at the deadline; its eventual completion
cannot unlock another mutation. Executors that perform their own writes and readback internally
are conservatively treated as pending writes until the entire executor settles.


::: code-group

```json [Apply Prepared DRC Edit]
Expand Down
2 changes: 1 addition & 1 deletion extension/extension.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"uuid": "easyedamcpbridge202605240001abcd",
"displayName": "EasyEDA MCP Bridge",
"description": "Independent local WebSocket bridge that lets an MCP server inspect and assist the active EasyEDA Pro project.",
"version": "0.5.0",
"version": "0.5.1",
"publisher": "vlabsoft",
"engines": {
"eda": "^2.3.0"
Expand Down
80 changes: 80 additions & 0 deletions extension/src/handlers/nativeNetlist.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { collectSchematicSnapshot } from "./schematicHandlers.js";
import { describe, expect, it, vi } from "vitest";
import { collectNativeNetlist } from "./nativeNetlist.js";

describe("native netlist collection", () => {
it("reads the File in memory, requests Protel2 and detects duplicate project references", async () => {
const getNetlistFile = vi.fn(async () => ({ size: 12, text: async () => "(\nGND\nU1-1\n)" }));
const result = await collectNativeNetlist(
{
sch_ManufactureData: { getNetlistFile },
sch_PrimitiveComponent: {
getAll: async () => [
{ componentType: "part", designator: "U1" },
{ componentType: "part", designator: "U1" }
]
}
},
false
);
expect(getNetlistFile).toHaveBeenCalledWith("mcp-native-connectivity", "Protel2");
expect(result).toMatchObject({ status: "available", ambiguousDesignators: ["U1"] });
});
it("does not claim support when the API or page scope is unavailable", async () => {
expect((await collectNativeNetlist({}, false)).status).toBe("unavailable");
const getNetlistFile = vi.fn();
expect((await collectNativeNetlist({ sch_ManufactureData: { getNetlistFile } }, true)).status).toBe("unavailable");
expect(getNetlistFile).not.toHaveBeenCalled();
});
it("reports a read failure without changing the editor", async () => {
const result = await collectNativeNetlist(
{
sch_ManufactureData: {
getNetlistFile: async () => {
throw new Error("export failed");
}
}
},
false
);
expect(result).toMatchObject({ status: "error", reason: "export failed" });
});
it("integrates native membership into the current-page snapshot", async () => {
const component = { primitiveId: "u", componentType: "part", designator: "U15" };
const api = () => ({
dmt_SelectControl: { getCurrentDocumentInfo: async () => ({ uuid: "sheet", documentType: 1 }) },
sch_PrimitiveComponent: {
getAll: async () => [component],
getAllPinsByPrimitiveId: async () => [{ pinNumber: "5", pinName: "V+" }]
},
sch_ManufactureData: { getNetlistFile: async () => ({ text: async () => "(\n3V3_LAB\nU15-5\n)" }) }
});
const snapshot = await collectSchematicSnapshot(api, { allPages: false, includeRaw: false });
expect(snapshot.pins[0]).toMatchObject({ net: "3V3_LAB", netSource: "native_netlist" });
expect(snapshot.nativeNetlist).toMatchObject({ status: "available", matchedPins: 1 });
});

it("bounds a hung native read and observes late rejection", async () => {
vi.useFakeTimers();
try {
let reject!: (error: Error) => void;
const pending = collectNativeNetlist(
{
sch_ManufactureData: {
getNetlistFile: () =>
new Promise((_, fail) => {
reject = fail;
})
}
},
false
);
await vi.advanceTimersByTimeAsync(3000);
expect((await pending).status).toBe("error");
reject(new Error("late SDK rejection"));
await vi.advanceTimersByTimeAsync(0);
} finally {
vi.useRealTimers();
}
});
});
55 changes: 55 additions & 0 deletions extension/src/handlers/nativeNetlist.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import type { NativeNetlistData } from "../../../src/schematic/nativeNetlist.js";
import type { EasyEdaApi } from "../types.js";

export async function collectNativeNetlist(eda: EasyEdaApi, allPages: boolean): Promise<NativeNetlistData> {
const base = { format: "Protel2" as const };
if (allPages)
return {
...base,
status: "unavailable",
reason: "Native mapping currently requires a single-page snapshot to avoid page-local ID collisions"
};
if (!eda.sch_ManufactureData?.getNetlistFile)
return { ...base, status: "unavailable", reason: "sch_ManufactureData.getNetlistFile is unavailable" };
let timer: ReturnType<typeof setTimeout> | undefined;
try {
const read = (async (): Promise<NativeNetlistData> => {
const file = await eda.sch_ManufactureData.getNetlistFile("mcp-native-connectivity", "Protel2");
if (!file || typeof file.text !== "function")
return { ...base, status: "unsupported", reason: "Native API did not return a readable File" };
if (typeof file.size === "number" && file.size > 2_000_000)
return { ...base, status: "unsupported", reason: "Native netlist exceeds 2 MB" };
const text: unknown = await file.text();
if (typeof text !== "string") return { ...base, status: "unsupported", reason: "Netlist content is not text" };
// Establish uniqueness across the project before matching references from an export.
const components = await eda.sch_PrimitiveComponent.getAll(undefined, true);
if (!Array.isArray(components)) throw new Error("Cannot establish project designator uniqueness");
const counts = new Map<string, number>();
for (const c of components)
if (c.componentType === "part" && typeof c.designator === "string")
counts.set(c.designator, (counts.get(c.designator) ?? 0) + 1);
return {
...base,
status: "available",
text,
ambiguousDesignators: [...counts].filter(([, count]) => count > 1).map(([name]) => name)
};
})();
const timeout = new Promise<NativeNetlistData>((resolve) => {
timer = setTimeout(
() =>
resolve({
...base,
status: "error",
reason: "Native netlist read timed out after 3000 ms; geometric fallback used"
}),
3000
);
});
return await Promise.race([read, timeout]);
} catch (error) {
return { ...base, status: "error", reason: error instanceof Error ? error.message : String(error) };
} finally {
if (timer !== undefined) clearTimeout(timer);
}
}
6 changes: 5 additions & 1 deletion extension/src/handlers/schematicHandlers.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { collectNativeNetlist } from "./nativeNetlist.js";
import {
assertSnapshotFresh,
buildSchematicSnapshot,
Expand Down Expand Up @@ -66,8 +67,11 @@ export async function collectSchematicSnapshot(
pinsByComponent,
wires: await optionalCall(() => (eda.sch_PrimitiveWire?.getAll ? eda.sch_PrimitiveWire.getAll() : [])),
texts: await optionalCall(() => (eda.sch_PrimitiveText?.getAll ? eda.sch_PrimitiveText.getAll() : [])),
includeRaw: options.includeRaw
includeRaw: options.includeRaw,
nativeNetlist: await collectNativeNetlist(eda, options.allPages)
};
const afterInfo = await eda.dmt_SelectControl.getCurrentDocumentInfo();
assertDocumentTargetMatch(target, extractDocumentIdentity(afterInfo, undefined, "native_api"));
return buildSchematicSnapshot(rawData);
}

Expand Down
72 changes: 72 additions & 0 deletions extension/src/mutation/schematicWireMutations.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -335,3 +335,75 @@ describe("Schematic Wire & Net Label Mutations", () => {
});
});
});

describe("native wire rename readback", () => {
function fixture(options: { ignoreWrite?: boolean; invalidReadback?: boolean } = {}) {
class NativeWire {
primitiveId = "native-wire";
net = "TEST_USB_GND";
line = [240, 620, 300, 620];
// These native members must never be copied into the lifecycle record.
nativeMetadata = new Map([["editor", "native"]]);
getState_PrimitiveId() {
return this.primitiveId;
}
getState_Net() {
return this.net;
}
getState_Line() {
return options.invalidReadback && this.net === "GND" ? [NaN] : this.line;
}
}
const wire = new NativeWire();
const modify = vi.fn(async (_id: string, properties: Record<string, unknown>) => {
if (!options.ignoreWrite) wire.net = String(properties.net);
});
const api = () => ({
dmt_SelectControl: { getCurrentDocumentInfo: async () => ({ uuid: "rename-sheet", documentType: 1 }) },
sch_PrimitiveWire: { get: async () => wire, getAll: async () => [wire], modify }
});
return { api, wire, modify };
}

it("confirms a native class instance as plain JSON after renaming once", async () => {
const { api, modify } = fixture();
const prepared = await prepareSchematicWireMutation(api, {
action: "modifyWire",
wireId: "native-wire",
net: "GND"
});
const result: any = await createActionHandlers(api, new DrcRules(api)).confirmedAction({
action: "mutation",
confirmation: prepared.confirmation,
params: { mutationId: prepared.mutationId }
});
expect(result.status).toBe("applied");
expect(result.after).toMatchObject({
wire: { primitiveId: "native-wire", net: "GND", line: [240, 620, 300, 620] },
verified: true
});
expect((result.after as any).wire.nativeMetadata).toBeUndefined();
expect(modify).toHaveBeenCalledTimes(1);
});

it.each([{ ignoreWrite: true }, { invalidReadback: true }])(
"preserves uncertainty when native readback fails: %j",
async (options) => {
const { api, modify } = fixture(options);
const prepared = await prepareSchematicWireMutation(api, {
action: "modifyWire",
wireId: "native-wire",
net: "GND"
});
const result: any = await createActionHandlers(api, new DrcRules(api)).confirmedAction({
action: "mutation",
confirmation: prepared.confirmation,
params: { mutationId: prepared.mutationId }
});
expect(result.status).toBe("unknown");
expect(result.error).toMatch(/readback/);
expect(result.execution).toMatchObject({ lockHeld: false });
expect(modify).toHaveBeenCalledTimes(1);
}
);
});
63 changes: 47 additions & 16 deletions extension/src/mutation/schematicWireMutations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { apiError, ensureApi, isNumber, isRecord, numeric, optionalCall, toArray
import { assertDocumentTargetMatch, extractDocumentIdentity } from "../identity.js";
import { extensionMutations } from "./mutationManager.js";
import type { EasyEdaApi } from "../types.js";
import type { MutationRecord } from "../../../src/mutation/contracts.js";
import { canonicalJson, type MutationRecord } from "../../../src/mutation/contracts.js";

export type NormalizedPoint = { x: number; y: number };

Expand Down Expand Up @@ -94,17 +94,35 @@ export async function findTouchingConnections(
return touching;
}

// SDK primitives are class instances. Only explicit state belongs in a mutation record.
export function wireReadbackData(wire: Record<string, unknown>): Record<string, unknown> {
const state = (method: string, field: string): unknown => {
const getter = wire[method];
return typeof getter === "function" ? getter.call(wire) : wire[field];
};
return JSON.parse(
canonicalJson({
primitiveId: state("getState_PrimitiveId", "primitiveId") ?? wire.id ?? wire.uuid,
line: state("getState_Line", "line"),
net: state("getState_Net", "net"),
color: state("getState_Color", "color"),
lineWidth: state("getState_LineWidth", "lineWidth"),
lineType: state("getState_LineType", "lineType")
})
);
}

export async function findWireById(api: () => EasyEdaApi, wireId: string): Promise<Record<string, unknown>> {
const eda = api();
if (eda.sch_PrimitiveWire?.get) {
const wire = await optionalCall(() => eda.sch_PrimitiveWire.get(wireId));
if (isRecord(wire)) return wire;
if (isRecord(wire)) return wireReadbackData(wire);
}
ensureApi("sch_PrimitiveWire", "getAll", eda);
const all = toArray(await eda.sch_PrimitiveWire.getAll());
for (const w of all) {
if (isRecord(w) && String(w.primitiveId ?? w.id ?? w.uuid ?? "") === wireId) {
return w;
return wireReadbackData(w);
}
}
throw apiError("wire_not_found", `Schematic wire with id "${wireId}" was not found.`);
Expand Down Expand Up @@ -422,20 +440,33 @@ export async function executeSchematicWireMutation(
ensureApi("sch_PrimitiveWire", "modify", eda);
await eda.sch_PrimitiveWire.modify(op.wireId, op.properties);

const wire = await findWireById(api, op.wireId);
const points = op.properties.coordinates ? extractPointsFromFlat(op.properties.coordinates) : [];
const affectedConnections = points.length > 0 ? await findTouchingConnections(api, points) : [];

return {
executed: true,
readback: {
wireId: op.wireId,
properties: op.properties,
wire,
affectedConnections,
verified: true
try {
const wire = await findWireById(api, op.wireId);
if (op.properties.net !== undefined && wire.net !== op.properties.net) {
throw apiError("readback_verification_failed", `Wire ${op.wireId} net does not match the requested name.`, {
expected: op.properties.net,
actual: wire.net
});
}
};
const points = op.properties.coordinates ? extractPointsFromFlat(op.properties.coordinates) : [];
const affectedConnections = points.length > 0 ? await findTouchingConnections(api, points) : [];

return {
executed: true,
readback: {
wireId: op.wireId,
properties: op.properties,
wire,
affectedConnections,
verified: true
}
};
} catch (error) {
throw apiError(
"write_readback_unknown",
`Wire modification completed but readback failed: ${error instanceof Error ? error.message : String(error)}`
);
}
}

if (op.action === "deleteWire") {
Expand Down
Loading
Loading