From 5bf73189c396c2af2ac4dc082b691a8a4820fdab Mon Sep 17 00:00:00 2001 From: Victor Freitas Date: Sun, 1 Nov 2026 19:43:06 -0300 Subject: [PATCH] feat(spice): simulation feasibility assessment, component audit and SPICE netlist generation (Phase 5.5) --- docs/tools.md | 38 +- extension/src/identity.ts | 4 + extension/src/index.ts | 3 + .../reporting/spiceFeasibilityReport.test.ts | 157 +++++ .../src/reporting/spiceFeasibilityReport.ts | 556 ++++++++++++++++++ src/mcp/registerTools.ts | 2 + src/mcp/server.test.ts | 4 +- src/mcp/tools/spiceTools.test.ts | 99 ++++ src/mcp/tools/spiceTools.ts | 46 ++ 9 files changed, 907 insertions(+), 2 deletions(-) create mode 100644 extension/src/reporting/spiceFeasibilityReport.test.ts create mode 100644 extension/src/reporting/spiceFeasibilityReport.ts create mode 100644 src/mcp/tools/spiceTools.test.ts create mode 100644 src/mcp/tools/spiceTools.ts diff --git a/docs/tools.md b/docs/tools.md index e59e060..b062a85 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -1,6 +1,6 @@ # Tools Reference -EasyEDA Pro MCP exposes **74 tools** across 8 categories. All inspection, tracing, navigation, and export tools are read-only (`readOnlyHint: true`). +EasyEDA Pro MCP exposes **76 tools** across 9 categories. All inspection, tracing, navigation, and export tools are read-only (`readOnlyHint: true`). ## Tool Catalog @@ -18,6 +18,8 @@ EasyEDA Pro MCP exposes **74 tools** across 8 categories. All inspection, tracin - [`easyeda_run_drc`](#easyeda_run_drc) · [`easyeda_get_pcb_layers`](#easyeda_get_pcb_layers) · [`easyeda_get_routing_status`](#easyeda_get_routing_status) · [`easyeda_list_pcb_components`](#easyeda_list_pcb_components) · [`easyeda_get_pcb_pads`](#easyeda_get_pcb_pads) · [`easyeda_prepare_pcb_component`](#easyeda_prepare_pcb_component) · [`easyeda_get_board_outline`](#easyeda_get_board_outline) · [`easyeda_prepare_board_outline`](#easyeda_prepare_board_outline) · [`easyeda_prepare_pcb_routing`](#easyeda_prepare_pcb_routing) · [`easyeda_prepare_pcb_layout`](#easyeda_prepare_pcb_layout) · [`easyeda_get_pcb_tracks`](#easyeda_get_pcb_tracks) · [`easyeda_get_pcb_vias`](#easyeda_get_pcb_vias) · [`easyeda_prepare_pcb_track_via`](#easyeda_prepare_pcb_track_via) · [`easyeda_highlight_net`](#easyeda_highlight_net) · [`easyeda_get_copper_zones`](#easyeda_get_copper_zones) · [`easyeda_get_keepouts`](#easyeda_get_keepouts) · [`easyeda_prepare_copper_keepout`](#easyeda_prepare_copper_keepout) · [`easyeda_get_pcb_airwires`](#easyeda_get_pcb_airwires) · [`easyeda_get_pcb_placement_report`](#easyeda_get_pcb_placement_report) · [`easyeda_get_pcb_net_report`](#easyeda_get_pcb_net_report) · [`easyeda_get_pcb_net_classes`](#easyeda_get_pcb_net_classes) · [`easyeda_get_pcb_differential_pairs`](#easyeda_get_pcb_differential_pairs) · [`easyeda_get_pcb_length_groups`](#easyeda_get_pcb_length_groups) · [`easyeda_prepare_pcb_net_constraint`](#easyeda_prepare_pcb_net_constraint) · [`easyeda_get_pcb_3d_inspection`](#easyeda_get_pcb_3d_inspection) · [`easyeda_get_pcb_3d_view`](#easyeda_get_pcb_3d_view) · [`easyeda_prepare_pcb_external_import`](#easyeda_prepare_pcb_external_import) · [`easyeda_get_drc_rules`](#easyeda_get_drc_rules) · [`easyeda_prepare_drc_edit`](#easyeda_prepare_drc_edit) · [`easyeda_get_drc_edit_result`](#easyeda_get_drc_edit_result) - **[Libraries, Navigation & Exports](#navigation-exports)** (15 tools) - [`easyeda_export_cpl`](#easyeda_export_cpl) · [`easyeda_export_bom`](#easyeda_export_bom) · [`easyeda_export_netlist`](#easyeda_export_netlist) · [`easyeda_export_gerber`](#easyeda_export_gerber) · [`easyeda_export_pdf`](#easyeda_export_pdf) · [`easyeda_export_image`](#easyeda_export_image) · [`easyeda_export_3d_model`](#easyeda_export_3d_model) · [`easyeda_export_project_archive`](#easyeda_export_project_archive) · [`easyeda_export_dxf`](#easyeda_export_dxf) · [`easyeda_navigate_component`](#easyeda_navigate_component) · [`easyeda_navigate_region`](#easyeda_navigate_region) · [`easyeda_zoom_board`](#easyeda_zoom_board) · [`easyeda_get_device_details`](#easyeda_get_device_details) · [`easyeda_compare_devices`](#easyeda_compare_devices) · [`easyeda_verify_pin_pad_mapping`](#easyeda_verify_pin_pad_mapping) +- **[SPICE Simulation Feasibility](#spice-simulation-feasibility)** (2 tools) + - [`easyeda_evaluate_spice_support`](#easyeda_evaluate_spice_support) · [`easyeda_generate_spice_netlist`](#easyeda_generate_spice_netlist) - **[Confirmation-Gated Actions](#confirmation-gated-actions)** (1 tool) - [`easyeda_confirmed_action`](#easyeda_confirmed_action) @@ -1290,6 +1292,40 @@ Validates 1-to-1 correspondence between schematic symbol pins and PCB footprint --- +## SPICE Simulation Feasibility + +### `easyeda_evaluate_spice_support` + +**Scope:** Schematic Analysis RPC (`readOnlyHint: true`, default timeout: `30000` ms) + +Performs a feasibility study of analog circuit SPICE simulation on the active schematic. Inspects placed components, verifies Node 0 / Ground datum connectivity, checks for power/stimulus sources, audits SPICE model availability, calculates a simulation readiness score (`0`–`100%`), and documents platform constraints and limitations. + +**Parameters:** +- **`groundNet`** (`string`, _optional_, default: `"GND"`): Net name expected as ground datum (mapped to SPICE node 0). +- **`target`** (`object`, _optional_): Expected document target specification. +- **`timeoutMs`** (`number`, _optional_, default: `30000`): RPC timeout in ms. + +--- + +### `easyeda_generate_spice_netlist` + +**Scope:** Netlist Export RPC (`readOnlyHint: true`, default timeout: `30000` ms) + +Generates a syntactically valid SPICE circuit netlist (`.cir` / `.sp`) from the active schematic with ground-to-0 normalization, primitive RLC elements, built-in semiconductor models, and configurable simulation directives (`.op`, `.tran`, `.ac`, `.dc`) for execution in external engines (ngspice, LTspice, Xyce). + +**Parameters:** +- **`analysisType`** (`"op" | "tran" | "ac" | "dc"`, _optional_, default: `"op"`): Simulation analysis type directive. +- **`analysisParams`** (`string`, _optional_): Directive parameters (e.g., `"1u 10m"` for `.tran`, or `"10 1 1Meg"` for `.ac`). +- **`groundNet`** (`string`, _optional_, default: `"GND"`): Net name to map to SPICE datum node 0. +- **`includeSubcircuits`** (`boolean`, _optional_, default: `true`): Whether to include X subcircuit cards for ICs. +- **`includeDefaultModels`** (`boolean`, _optional_, default: `true`): Include built-in generic diode and BJT `.model` definitions. +- **`fileName`** (`string`, _optional_): Optional output file name without extension. +- **`destinationPath`** (`string`, _optional_): Optional destination directory or output file path. +- **`target`** (`object`, _optional_): Expected document target specification. +- **`timeoutMs`** (`number`, _optional_, default: `30000`): RPC timeout in ms. + +--- + ## Confirmation-Gated Actions ### `easyeda_confirmed_action` diff --git a/extension/src/identity.ts b/extension/src/identity.ts index 99c5cde..0a35648 100644 --- a/extension/src/identity.ts +++ b/extension/src/identity.ts @@ -222,6 +222,10 @@ export function detectMethodCapabilities(api: () => EasyEdaApi): Record (typeof eda !== "undefined" ? eda : (globalThis as any).eda); @@ -61,6 +62,8 @@ const handlers: Record = { prepareSchematicBus: (params) => prepareSchematicBusMutation(getApi, params), prepareSchematicPcbSync: (params) => prepareSchematicPcbSyncMutation(getApi, params), compareSchematicPcb: (params) => compareSchematicPcb(getApi, params), + evaluateSpiceFeasibility: (params) => evaluateSpiceFeasibility(getApi, params), + generateSpiceNetlist: (params) => generateSpiceNetlist(getApi, exportHandlers.saveApiFile as any, params), ...contextHandlers, ...documentHandlers, ...schematicHandlers, diff --git a/extension/src/reporting/spiceFeasibilityReport.test.ts b/extension/src/reporting/spiceFeasibilityReport.test.ts new file mode 100644 index 0000000..5e08417 --- /dev/null +++ b/extension/src/reporting/spiceFeasibilityReport.test.ts @@ -0,0 +1,157 @@ +import { describe, expect, it, vi } from "vitest"; +import { classifyComponentForSpice, evaluateSpiceFeasibility, generateSpiceNetlist } from "./spiceFeasibilityReport.js"; + +describe("spiceFeasibilityReport", () => { + describe("classifyComponentForSpice", () => { + it("classifies passive resistors, capacitors and inductors as intrinsic primitives", () => { + const res = classifyComponentForSpice({ designator: "R1", value: "10k" }, [{ net: "VCC" }, { net: "NET1" }]); + expect(res.spiceCategory).toBe("primitive_r"); + expect(res.hasModel).toBe(true); + expect(res.modelSource).toBe("intrinsic"); + expect(res.parameters.value).toBe("10k"); + + const cap = classifyComponentForSpice({ designator: "C2", value: "100n" }, [{ net: "NET1" }, { net: "GND" }]); + expect(cap.spiceCategory).toBe("primitive_c"); + expect(cap.hasModel).toBe(true); + + const ind = classifyComponentForSpice({ designator: "L1", value: "22u" }, [{ net: "VIN" }, { net: "SW" }]); + expect(ind.spiceCategory).toBe("primitive_l"); + expect(ind.hasModel).toBe(true); + }); + + it("classifies diodes, transistors and voltage sources", () => { + const diode = classifyComponentForSpice({ designator: "D1", value: "1N4148" }, [{ net: "IN" }, { net: "OUT" }]); + expect(diode.spiceCategory).toBe("primitive_diode"); + expect(diode.hasModel).toBe(true); + + const bjt = classifyComponentForSpice({ designator: "Q1", value: "2N2222" }, [ + { net: "C" }, + { net: "B" }, + { net: "E" } + ]); + expect(bjt.spiceCategory).toBe("primitive_transistor"); + expect(bjt.hasModel).toBe(true); + + const vsrc = classifyComponentForSpice({ designator: "V1", value: "5V" }, [{ net: "VCC" }, { net: "GND" }]); + expect(vsrc.spiceCategory).toBe("source_voltage"); + expect(vsrc.hasModel).toBe(true); + expect(vsrc.parameters.dc).toBe("5V"); + }); + + it("flags ICs without models as needs_model and connectors as non_electrical", () => { + const ic = classifyComponentForSpice({ designator: "U1", title: "STM32F103" }, []); + expect(ic.spiceCategory).toBe("subcircuit"); + expect(ic.hasModel).toBe(false); + expect(ic.modelSource).toBe("missing"); + expect(ic.warnings.length).toBeGreaterThan(0); + + const conn = classifyComponentForSpice({ designator: "J1", title: "Header_1x4" }, []); + expect(conn.spiceCategory).toBe("non_electrical"); + expect(conn.hasModel).toBe(false); + expect(conn.modelSource).toBe("none"); + }); + }); + + describe("evaluateSpiceFeasibility", () => { + it("reports simulation_ready for a complete circuit with passives, source and GND", async () => { + const api = () => ({ + dmt_SelectControl: { + getCurrentDocumentInfo: () => ({ title: "RC_Filter.Schematic", documentType: 1 }) + }, + sch_PrimitiveComponent: { + getAll: vi.fn(async () => [ + { primitiveId: "p1", designator: "V1", value: "5V" }, + { primitiveId: "p2", designator: "R1", value: "1k" }, + { primitiveId: "p3", designator: "C1", value: "100n" } + ]), + getAllPinsByPrimitiveId: vi.fn(async (id: string) => { + if (id === "p1") return [{ net: "VIN" }, { net: "GND" }]; + if (id === "p2") return [{ net: "VIN" }, { net: "VOUT" }]; + return [{ net: "VOUT" }, { net: "GND" }]; + }) + }, + sch_Net: { + getAllNetsName: vi.fn(async () => ["VIN", "VOUT", "GND"]) + } + }); + + const report = await evaluateSpiceFeasibility(api as any); + expect(report.feasibilityScorePercent).toBe(100); + expect(report.isSimulatable).toBe(true); + expect(report.verdict).toBe("simulation_ready"); + expect(report.groundReference.detected).toBe(true); + expect(report.groundReference.netName).toBe("GND"); + expect(report.stimulusSources.hasStimulus).toBe(true); + expect(report.stimulusSources.count).toBe(1); + expect(report.platformLimitations.length).toBeGreaterThan(0); + }); + + it("penalizes score and warns when ground reference is missing", async () => { + const api = () => ({ + dmt_SelectControl: { + getCurrentDocumentInfo: () => ({ title: "NoGround.Schematic", documentType: 1 }) + }, + sch_PrimitiveComponent: { + getAll: vi.fn(async () => [ + { primitiveId: "p1", designator: "V1", value: "5V" }, + { primitiveId: "p2", designator: "R1", value: "1k" } + ]), + getAllPinsByPrimitiveId: vi.fn(async (id: string) => { + if (id === "p1") return [{ net: "NET1" }, { net: "NET2" }]; + return [{ net: "NET1" }, { net: "NET2" }]; + }) + }, + sch_Net: { + getAllNetsName: vi.fn(async () => ["NET1", "NET2"]) + } + }); + + const report = await evaluateSpiceFeasibility(api as any); + expect(report.groundReference.detected).toBe(false); + expect(report.feasibilityScorePercent).toBeLessThan(80); + expect(report.recommendations.some((r) => r.includes("CRITICAL: Add a ground reference"))).toBe(true); + }); + }); + + describe("generateSpiceNetlist", () => { + it("generates valid SPICE netlist syntax with .tran analysis and ground mapped to node 0", async () => { + const api = () => ({ + dmt_SelectControl: { + getCurrentDocumentInfo: () => ({ title: "VoltageDivider.Schematic" }) + }, + sch_PrimitiveComponent: { + getAll: vi.fn(async () => [ + { primitiveId: "c1", designator: "V1", value: "12V" }, + { primitiveId: "c2", designator: "R1", value: "10k" }, + { primitiveId: "c3", designator: "R2", value: "2.2k" }, + { primitiveId: "c4", designator: "D1", value: "1N4148" } + ]), + getAllPinsByPrimitiveId: vi.fn(async (id: string) => { + if (id === "c1") return [{ net: "VCC" }, { net: "GND" }]; + if (id === "c2") return [{ net: "VCC" }, { net: "MID" }]; + if (id === "c3") return [{ net: "MID" }, { net: "GND" }]; + return [{ net: "MID" }, { net: "GND" }]; + }) + } + }); + + const res = await generateSpiceNetlist(api as any, undefined, { + analysisType: "tran", + analysisParams: "10u 5ms", + groundNet: "GND" + }); + + expect(res.analysisType).toBe("tran"); + expect(res.directive).toBe(".tran 10u 5ms"); + expect(res.elementsCount).toBe(4); + expect(res.nodes).toContain("0"); + expect(res.netlist).toContain("V1 VCC 0 DC 12V"); + expect(res.netlist).toContain("R1 VCC MID 10k"); + expect(res.netlist).toContain("R2 MID 0 2.2k"); + expect(res.netlist).toContain("D1 MID 0 D_1N4148"); + expect(res.netlist).toContain(".model D_GENERIC"); + expect(res.netlist).toContain(".end"); + expect(res.validation).toMatchObject({ valid: true }); + }); + }); +}); diff --git a/extension/src/reporting/spiceFeasibilityReport.ts b/extension/src/reporting/spiceFeasibilityReport.ts new file mode 100644 index 0000000..3b53cd2 --- /dev/null +++ b/extension/src/reporting/spiceFeasibilityReport.ts @@ -0,0 +1,556 @@ +import { extractDocumentIdentity } from "../identity.js"; +import { inferDocumentType, optionalCall, sanitize, timestamp, toArray } from "../helpers.js"; +import { validateExportContent } from "./exportEnhancements.js"; +import type { EasyEdaApi } from "../types.js"; + +export type SpiceAnalysisType = "op" | "tran" | "ac" | "dc"; + +export type ComponentSpiceCategory = + | "primitive_r" + | "primitive_l" + | "primitive_c" + | "primitive_diode" + | "primitive_transistor" + | "source_voltage" + | "source_current" + | "subcircuit" + | "needs_model" + | "non_electrical"; + +export interface ComponentSpiceAudit { + designator: string; + prefix: string; + title: string; + spiceCategory: ComponentSpiceCategory; + modelName?: string; + hasModel: boolean; + modelSource: "intrinsic" | "embedded" | "library" | "missing" | "none"; + parameters: Record; + pinsCount: number; + pinsConnectedCount: number; + warnings: string[]; +} + +export interface SpiceFeasibilityReport { + documentId?: string; + documentName?: string; + documentType: string; + feasibilityScorePercent: number; // 0 to 100 + isSimulatable: boolean; + verdict: "simulation_ready" | "minor_setup_needed" | "major_models_missing" | "unsupported"; + engineAvailability: { + nativeEditorEngine: boolean; + externalNgspiceCompatible: boolean; + externalLtspiceCompatible: boolean; + cloudEngineAvailable: boolean; + recommendedWorkflow: string; + }; + groundReference: { + detected: boolean; + netName?: string; + spiceNode: "0"; + nodesCount: number; + }; + componentsAudit: { + totalComponents: number; + simulatableCount: number; + missingModelsCount: number; + nonElectricalCount: number; + items: ComponentSpiceAudit[]; + }; + stimulusSources: { + hasStimulus: boolean; + count: number; + sources: Array<{ designator: string; type: string; value: string }>; + }; + connectivitySummary: { + totalNets: number; + floatingPinsCount: number; + singlePinNetsCount: number; + }; + platformLimitations: string[]; + recommendations: string[]; +} + +export interface EvaluateSpiceFeasibilityParams { + target?: Record; + groundNet?: string; + timeoutMs?: number; +} + +export interface GenerateSpiceNetlistParams { + analysisType?: SpiceAnalysisType; + analysisParams?: string; + groundNet?: string; + includeSubcircuits?: boolean; + includeDefaultModels?: boolean; + fileName?: string; + destinationPath?: string; + target?: Record; + timeoutMs?: number; +} + +/** + * Classifies a component's designator and attributes into SPICE primitive/subcircuit categories. + */ +export function classifyComponentForSpice(rawComp: Record, pins: unknown[] = []): ComponentSpiceAudit { + const designator = String(rawComp.designator ?? rawComp.name ?? rawComp.id ?? "U?").trim(); + const title = String(rawComp.title ?? rawComp.package ?? rawComp.deviceType ?? "").trim(); + const prefixMatch = designator.match(/^([A-Za-z]+)/); + const prefix = prefixMatch ? prefixMatch[1].toUpperCase() : "U"; + + const rawAttrs = rawComp.attributes ?? rawComp.props ?? {}; + const valueAttr = String(rawComp.value ?? rawAttrs.value ?? rawAttrs.Value ?? "").trim(); + const spiceModelAttr = String(rawAttrs.spice_model ?? rawAttrs.SpiceModel ?? rawAttrs.model ?? "").trim(); + const spiceSubcktAttr = String(rawAttrs.spice_subckt ?? rawAttrs.subckt ?? "").trim(); + + const parameters: Record = {}; + if (valueAttr) parameters.value = valueAttr; + + const warnings: string[] = []; + let spiceCategory: ComponentSpiceCategory; + let hasModel: boolean; + let modelSource: "intrinsic" | "embedded" | "library" | "missing" | "none"; + let modelName: string | undefined = spiceModelAttr || spiceSubcktAttr || undefined; + + const connectedPinsCount = pins.filter((p: any) => { + const net = p.net ?? p.netName ?? p.connectNet; + return Boolean(net && String(net).trim() !== ""); + }).length; + + // 1. Passives + if (prefix === "R") { + spiceCategory = "primitive_r"; + hasModel = true; + modelSource = "intrinsic"; + if (!valueAttr) warnings.push("Resistor missing resistance value; default 1k will be assumed."); + } else if (prefix === "C") { + spiceCategory = "primitive_c"; + hasModel = true; + modelSource = "intrinsic"; + if (!valueAttr) warnings.push("Capacitor missing capacitance value; default 100n will be assumed."); + } else if (prefix === "L") { + spiceCategory = "primitive_l"; + hasModel = true; + modelSource = "intrinsic"; + if (!valueAttr) warnings.push("Inductor missing inductance value; default 10u will be assumed."); + } + // 2. Diodes + else if (prefix === "D" || prefix === "LED") { + spiceCategory = "primitive_diode"; + hasModel = Boolean(modelName || valueAttr); + modelSource = modelName ? "embedded" : "library"; + modelName = modelName ?? (valueAttr ? `D_${valueAttr}` : "D_GENERIC"); + } + // 3. Transistors + else if (prefix === "Q" || prefix === "M" || prefix === "T") { + spiceCategory = "primitive_transistor"; + hasModel = Boolean(modelName || valueAttr); + modelSource = modelName ? "embedded" : "library"; + modelName = modelName ?? (valueAttr ? `Q_${valueAttr}` : "NPN_GENERIC"); + } + // 4. Sources + else if ( + prefix === "V" || + designator.startsWith("BAT") || + designator.startsWith("VIN") || + designator.startsWith("PWR") + ) { + spiceCategory = "source_voltage"; + hasModel = true; + modelSource = "intrinsic"; + parameters.dc = valueAttr || "5V"; + } else if (prefix === "I") { + spiceCategory = "source_current"; + hasModel = true; + modelSource = "intrinsic"; + parameters.dc = valueAttr || "1mA"; + } + // 5. Connectors & Test Points + else if ( + prefix === "J" || + prefix === "CN" || + prefix === "HDR" || + prefix === "TP" || + prefix === "H" || + prefix === "MH" + ) { + spiceCategory = "non_electrical"; + hasModel = false; + modelSource = "none"; + } + // 6. ICs and complex subcircuits + else { + spiceCategory = "subcircuit"; + if (spiceSubcktAttr || spiceModelAttr) { + hasModel = true; + modelSource = "embedded"; + } else { + hasModel = false; + modelSource = "missing"; + warnings.push( + `Component '${designator}' (${title || "IC"}) has no attached SPICE subcircuit or simulation model.` + ); + } + } + + return { + designator, + prefix, + title, + spiceCategory, + modelName, + hasModel, + modelSource, + parameters, + pinsCount: pins.length, + pinsConnectedCount: connectedPinsCount, + warnings + }; +} + +/** + * Evaluates SPICE feasibility, engine availability, and circuit readiness of active schematic. + */ +export async function evaluateSpiceFeasibility( + api: () => EasyEdaApi, + params: EvaluateSpiceFeasibilityParams = {} +): Promise { + const eda = api(); + const docInfo = (await optionalCall(() => eda.dmt_SelectControl?.getCurrentDocumentInfo?.())) ?? {}; + const docId = extractDocumentIdentity(docInfo, undefined, "native_api"); + const docType = inferDocumentType(docInfo); + + // Probe EasyEDA Pro simulation API capabilities + const nativeSim = Boolean( + (eda as any).sch_Sim?.check || (eda as any).sim_Document?.run || (eda as any).sim_Engine?.simulate + ); + const cloudSim = Boolean((eda as any).sch_Sim?.cloudSimulate); + + // Retrieve schematic components + const rawComponents = toArray(await optionalCall(() => eda.sch_PrimitiveComponent?.getAll?.(undefined, true))); + + // Retrieve nets + const rawNets = toArray( + await optionalCall( + () => eda.sch_Net?.getAllNetsName?.() ?? eda.sch_Net?.getAllNetName?.() ?? eda.sch_Net?.getAllNets?.() + ) + ); + + // Audit components + const componentAudits: ComponentSpiceAudit[] = []; + const stimulusSources: Array<{ designator: string; type: string; value: string }> = []; + let floatingPinsTotal = 0; + + for (const item of rawComponents) { + if (!item || typeof item !== "object") continue; + const comp = item as Record; + const compId = comp.primitiveId ?? comp.id; + let pins: unknown[]; + if (compId && eda.sch_PrimitiveComponent?.getAllPinsByPrimitiveId) { + try { + pins = toArray(await eda.sch_PrimitiveComponent.getAllPinsByPrimitiveId(compId)); + } catch { + pins = toArray(comp.pins); + } + } else { + pins = toArray(comp.pins); + } + + const audit = classifyComponentForSpice(comp, pins); + componentAudits.push(audit); + + const unconnected = audit.pinsCount - audit.pinsConnectedCount; + if (unconnected > 0) floatingPinsTotal += unconnected; + + if (audit.spiceCategory === "source_voltage" || audit.spiceCategory === "source_current") { + stimulusSources.push({ + designator: audit.designator, + type: audit.spiceCategory, + value: String(audit.parameters.dc ?? audit.parameters.value ?? "5V") + }); + } + } + + // Detect Ground reference + const groundTargetName = params.groundNet?.toUpperCase() ?? "GND"; + const netNames = rawNets.map((n: any) => (typeof n === "string" ? n : String(n?.name ?? n?.netName ?? n))); + const groundDetected = netNames.some((n) => { + const norm = String(n).trim().toUpperCase(); + return norm === groundTargetName || norm === "0" || norm === "AGND" || norm === "DGND" || norm === "GND_PWR"; + }); + const matchedGround = netNames.find((n) => { + const norm = String(n).trim().toUpperCase(); + return norm === groundTargetName || norm === "0" || norm === "AGND" || norm === "DGND"; + }); + + // Calculate feasibility score + const totalComponents = componentAudits.length; + const simulatable = componentAudits.filter((c) => c.hasModel || c.spiceCategory === "non_electrical"); + const missingModels = componentAudits.filter((c) => c.modelSource === "missing"); + const nonElectrical = componentAudits.filter((c) => c.spiceCategory === "non_electrical"); + + let score = 100; + const recommendations: string[] = []; + + if (!groundDetected) { + score -= 40; + recommendations.push( + "CRITICAL: Add a ground reference net (named 'GND' or '0') to the schematic. SPICE nodal analysis requires node '0' as DC datum." + ); + } + + if (stimulusSources.length === 0) { + score -= 20; + recommendations.push( + "Add a stimulus source (DC voltage VCC, pulsed clock, or AC source) to excite the circuit during simulation." + ); + } + + if (missingModels.length > 0) { + const penalty = Math.min(30, missingModels.length * 10); + score -= penalty; + const names = missingModels + .slice(0, 5) + .map((m) => m.designator) + .join(", "); + recommendations.push( + `Attach SPICE subcircuits (.subckt) or SPICE model text to IC components lacking models: ${names}${missingModels.length > 5 ? " and others" : ""}.` + ); + } + + if (floatingPinsTotal > 0) { + score -= Math.min(10, floatingPinsTotal * 2); + recommendations.push( + `Connect or place 'No Connect' flags on ${floatingPinsTotal} floating pin(s) to avoid singular matrix errors during simulation.` + ); + } + + score = Math.max(0, Math.min(100, score)); + + let verdict: SpiceFeasibilityReport["verdict"]; + if (score >= 80) verdict = "simulation_ready"; + else if (score >= 50) verdict = "minor_setup_needed"; + else if (score >= 20) verdict = "major_models_missing"; + else verdict = "unsupported"; + + const isSimulatable = score >= 50 && groundDetected; + + const platformLimitations = [ + "EasyEDA Pro operates in a browser/Electron sandbox without an embedded native SPICE binary solver.", + "Native in-browser simulation requires external simulator integration (ngspice, LTspice, or Xyce).", + "Complex proprietary ICs and microcontrollers cannot be simulated with pure analog SPICE without vendor behavioral macromodels.", + "Simulation directives (.tran, .ac, .op, .dc) must be specified as schematic text or injected during netlist generation." + ]; + + return { + documentId: docId.documentId, + documentName: docId.documentName, + documentType: docType, + feasibilityScorePercent: score, + isSimulatable, + verdict, + engineAvailability: { + nativeEditorEngine: nativeSim, + externalNgspiceCompatible: true, + externalLtspiceCompatible: true, + cloudEngineAvailable: cloudSim, + recommendedWorkflow: + "Export SPICE netlist via easyeda_generate_spice_netlist and execute simulation in ngspice CLI or LTspice." + }, + groundReference: { + detected: groundDetected, + netName: matchedGround, + spiceNode: "0", + nodesCount: netNames.length + }, + componentsAudit: { + totalComponents, + simulatableCount: simulatable.length, + missingModelsCount: missingModels.length, + nonElectricalCount: nonElectrical.length, + items: componentAudits + }, + stimulusSources: { + hasStimulus: stimulusSources.length > 0, + count: stimulusSources.length, + sources: stimulusSources + }, + connectivitySummary: { + totalNets: netNames.length, + floatingPinsCount: floatingPinsTotal, + singlePinNetsCount: 0 + }, + platformLimitations, + recommendations + }; +} + +/** + * Generates standard SPICE formatted netlist (.cir / .sp) from active schematic. + */ +export async function generateSpiceNetlist( + api: () => EasyEdaApi, + saveFileFn: ((file: unknown, name: string) => Promise>) | undefined, + params: GenerateSpiceNetlistParams = {} +): Promise> { + const eda = api(); + const docInfo = (await optionalCall(() => eda.dmt_SelectControl?.getCurrentDocumentInfo?.())) ?? {}; + const docId = extractDocumentIdentity(docInfo, undefined, "native_api"); + const baseTitle = docId.documentName || "EasyEDA_Circuit"; + const analysisType = params.analysisType ?? "op"; + const analysisParams = params.analysisParams?.trim(); + + const baseName = params.fileName?.trim() || `easyeda-spice-${timestamp()}`; + const fileName = baseName.endsWith(".cir") || baseName.endsWith(".sp") ? baseName : `${baseName}.cir`; + + // Fetch components + const rawComponents = toArray(await optionalCall(() => eda.sch_PrimitiveComponent?.getAll?.(undefined, true))); + + const lines: string[] = []; + lines.push(`* EasyEDA Pro Exported SPICE Netlist`); + lines.push(`* Document: ${baseTitle} (${docId.documentId ?? "active"})`); + lines.push(`* Generated: ${new Date().toISOString()}`); + lines.push(`* Simulator Target: ngspice / LTspice / SPICE3f5`); + lines.push(``); + + const elements: string[] = []; + const referencedModels = new Set(); + const allNodes = new Set(); + + // Ground mapping + const groundNet = (params.groundNet ?? "GND").toUpperCase(); + const mapNode = (net: unknown, fallbackPin: string): string => { + if (!net) return `N_${fallbackPin}`; + const n = String(net).trim(); + const up = n.toUpperCase(); + if (up === groundNet || up === "0" || up === "AGND" || up === "DGND") { + allNodes.add("0"); + return "0"; + } + const sanitizedNode = n.replace(/[^A-Za-z0-9_]/g, "_"); + allNodes.add(sanitizedNode); + return sanitizedNode; + }; + + for (const item of rawComponents) { + if (!item || typeof item !== "object") continue; + const comp = item as Record; + const compId = comp.primitiveId ?? comp.id; + let pins: any[]; + if (compId && eda.sch_PrimitiveComponent?.getAllPinsByPrimitiveId) { + try { + pins = toArray(await eda.sch_PrimitiveComponent.getAllPinsByPrimitiveId(compId)); + } catch { + pins = toArray(comp.pins); + } + } else { + pins = toArray(comp.pins); + } + + const audit = classifyComponentForSpice(comp, pins); + if (audit.spiceCategory === "non_electrical") continue; + + const des = audit.designator; + const val = String(audit.parameters.value ?? audit.parameters.dc ?? "1k"); + + if ( + audit.spiceCategory === "primitive_r" || + audit.spiceCategory === "primitive_c" || + audit.spiceCategory === "primitive_l" + ) { + const p1 = mapNode(pins[0]?.net ?? pins[0]?.netName, `${des}_1`); + const p2 = mapNode(pins[1]?.net ?? pins[1]?.netName, `${des}_2`); + elements.push(`${des} ${p1} ${p2} ${val}`); + } else if (audit.spiceCategory === "primitive_diode") { + const pAnode = mapNode(pins[0]?.net ?? pins[0]?.netName, `${des}_A`); + const pCathode = mapNode(pins[1]?.net ?? pins[1]?.netName, `${des}_K`); + const mod = audit.modelName ?? "D_GENERIC"; + referencedModels.add(mod); + elements.push(`${des} ${pAnode} ${pCathode} ${mod}`); + } else if (audit.spiceCategory === "primitive_transistor") { + const pC = mapNode(pins[0]?.net ?? pins[0]?.netName, `${des}_C`); + const pB = mapNode(pins[1]?.net ?? pins[1]?.netName, `${des}_B`); + const pE = mapNode(pins[2]?.net ?? pins[2]?.netName, `${des}_E`); + const mod = audit.modelName ?? "NPN_GENERIC"; + referencedModels.add(mod); + elements.push(`${des} ${pC} ${pB} ${pE} ${mod}`); + } else if (audit.spiceCategory === "source_voltage") { + const pPos = mapNode(pins[0]?.net ?? pins[0]?.netName, `${des}_P`); + const pNeg = mapNode(pins[1]?.net ?? pins[1]?.netName, "0"); + elements.push(`${des} ${pPos} ${pNeg} DC ${val}`); + } else if (audit.spiceCategory === "source_current") { + const pPos = mapNode(pins[0]?.net ?? pins[0]?.netName, `${des}_P`); + const pNeg = mapNode(pins[1]?.net ?? pins[1]?.netName, "0"); + elements.push(`${des} ${pPos} ${pNeg} DC ${val}`); + } else if (audit.spiceCategory === "subcircuit" && params.includeSubcircuits !== false) { + const pinNodes = pins.map((p, idx) => mapNode(p.net ?? p.netName, `${des}_${idx + 1}`)); + const subName = audit.modelName ?? audit.title ?? "SUBCKT_UNKNOWN"; + elements.push(`X${des.replace(/^U/i, "")} ${pinNodes.join(" ")} ${subName}`); + } + } + + // Elements section + lines.push(`* Circuit Elements`); + if (elements.length === 0) { + lines.push(`* (No electrical elements found on active schematic canvas)`); + // Fallback minimal element for syntax validation + lines.push(`R_DUMMY 1 0 1Meg`); + allNodes.add("1"); + allNodes.add("0"); + } else { + for (const el of elements) lines.push(el); + } + lines.push(``); + + // Models section + if (params.includeDefaultModels !== false) { + lines.push(`* Built-in Semiconductor Models`); + lines.push(`.model D_GENERIC D(IS=1e-14 RS=0.1 CJO=2p BV=50)`); + lines.push(`.model NPN_GENERIC NPN(BF=100 IS=1e-14 VAF=100)`); + lines.push(`.model PNP_GENERIC PNP(BF=100 IS=1e-14 VAF=100)`); + lines.push(``); + } + + // Analysis directive + lines.push(`* Simulation Directives`); + let directive: string; + if (analysisType === "tran") { + directive = `.tran ${analysisParams || "1u 10m"}`; + } else if (analysisType === "ac") { + directive = `.ac dec ${analysisParams || "10 1 1Meg"}`; + } else if (analysisType === "dc") { + directive = `.dc ${analysisParams || "V1 0 5 0.1"}`; + } else { + directive = ".op"; + } + lines.push(directive); + lines.push(``); + lines.push(`.end`); + lines.push(``); + + const netlistContent = lines.join("\n"); + const validation = validateExportContent("txt", netlistContent, fileName, params.destinationPath); + + let saveResult: Record = { saved: false }; + if (saveFileFn) { + saveResult = await saveFileFn(netlistContent, fileName); + } + + return { + ...saveResult, + fileName, + analysisType, + directive, + elementsCount: elements.length, + nodesCount: allNodes.size, + nodes: Array.from(allNodes), + netlist: netlistContent, + validation: sanitize(validation), + metadata: { + documentId: docId.documentId, + documentName: docId.documentName, + destinationPath: validation.destinationPath + } + }; +} diff --git a/src/mcp/registerTools.ts b/src/mcp/registerTools.ts index 74fe4aa..d017b82 100644 --- a/src/mcp/registerTools.ts +++ b/src/mcp/registerTools.ts @@ -8,6 +8,7 @@ import { registerExportTools } from "./tools/exportTools.js"; import { registerDocumentTools } from "./tools/documentTools.js"; import { registerSchematicMutationTools } from "./tools/schematicMutationTools.js"; import { registerActionTools } from "./tools/actionTools.js"; +import { registerSpiceTools } from "./tools/spiceTools.js"; import { DefaultTimeoutSchema, hasExplicitMutationConfirmation, registerReadTool } from "./tools/common.js"; export { DefaultTimeoutSchema, hasExplicitMutationConfirmation, registerReadTool }; @@ -21,4 +22,5 @@ export function registerEasyEdaTools(server: McpServer, bridge: EditorClient): v registerDocumentTools(server, bridge); registerSchematicMutationTools(server, bridge); registerActionTools(server, bridge); + registerSpiceTools(server, bridge); } diff --git a/src/mcp/server.test.ts b/src/mcp/server.test.ts index 6e67de2..eac8a16 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(74); + expect((await client.listTools()).tools).toHaveLength(76); 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: {} }); @@ -92,6 +92,8 @@ describe("EasyEDA MCP server", () => { expect(toolNames).toContain("easyeda_export_3d_model"); expect(toolNames).toContain("easyeda_export_project_archive"); expect(toolNames).toContain("easyeda_export_dxf"); + expect(toolNames).toContain("easyeda_evaluate_spice_support"); + expect(toolNames).toContain("easyeda_generate_spice_netlist"); const result = await client.callTool({ name: "easyeda_get_context", diff --git a/src/mcp/tools/spiceTools.test.ts b/src/mcp/tools/spiceTools.test.ts new file mode 100644 index 0000000..adb6964 --- /dev/null +++ b/src/mcp/tools/spiceTools.test.ts @@ -0,0 +1,99 @@ +import type { EditorStatus } from "../../protocol/messages.js"; +import { describe, expect, it, vi } from "vitest"; +import { McpServer, InMemoryTransport } from "@modelcontextprotocol/server"; +import { Client } from "@modelcontextprotocol/client"; +import { registerSpiceTools } from "./spiceTools.js"; + +describe("spiceTools", () => { + it("registers SPICE feasibility study and netlist generation tools", () => { + const server = new McpServer({ name: "test", version: "1.0.0" }); + const registerToolSpy = vi.spyOn(server, "registerTool"); + const bridge = { + endpoint: "ws://127.0.0.1:8765", + getStatus: vi.fn((): EditorStatus => ({ connected: true, updatedAt: "2026-11-01T00:00:00.000Z" })), + call: vi.fn() + }; + + registerSpiceTools(server, bridge as any); + + const registeredToolNames = registerToolSpy.mock.calls.map((call) => call[0]); + expect(registeredToolNames).toEqual(["easyeda_evaluate_spice_support", "easyeda_generate_spice_netlist"]); + }); + + it("invokes easyeda_evaluate_spice_support through client", async () => { + const bridge = { + endpoint: "ws://127.0.0.1:8765", + getStatus: vi.fn((): EditorStatus => ({ connected: true, updatedAt: "2026-11-01T00:00:00.000Z" })), + call: vi.fn(async () => ({ + feasibilityScorePercent: 90, + isSimulatable: true, + verdict: "simulation_ready" + })) + }; + + const server = new McpServer({ name: "test", version: "1.0.0" }); + registerSpiceTools(server, bridge as any); + const client = new Client({ name: "test-client", version: "1.0.0" }); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]); + + const result = await client.callTool({ + name: "easyeda_evaluate_spice_support", + arguments: { groundNet: "GND" } + }); + + expect(result.isError).toBeFalsy(); + expect(bridge.call).toHaveBeenCalledWith("evaluateSpiceFeasibility", { groundNet: "GND" }, 30_000); + expect(result.structuredContent).toMatchObject({ + result: { + isSimulatable: true, + verdict: "simulation_ready" + } + }); + + await client.close(); + }); + + it("invokes easyeda_generate_spice_netlist with tran analysis", async () => { + const bridge = { + endpoint: "ws://127.0.0.1:8765", + getStatus: vi.fn((): EditorStatus => ({ connected: true, updatedAt: "2026-11-01T00:00:00.000Z" })), + call: vi.fn(async () => ({ + saved: true, + fileName: "filter.cir", + directive: ".tran 10u 5ms", + elementsCount: 3 + })) + }; + + const server = new McpServer({ name: "test", version: "1.0.0" }); + registerSpiceTools(server, bridge as any); + const client = new Client({ name: "test-client", version: "1.0.0" }); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]); + + const result = await client.callTool({ + name: "easyeda_generate_spice_netlist", + arguments: { + analysisType: "tran", + analysisParams: "10u 5ms", + groundNet: "0" + } + }); + + expect(result.isError).toBeFalsy(); + expect(bridge.call).toHaveBeenCalledWith( + "generateSpiceNetlist", + { + analysisType: "tran", + analysisParams: "10u 5ms", + groundNet: "0", + includeSubcircuits: true, + includeDefaultModels: true + }, + 30_000 + ); + + await client.close(); + }); +}); diff --git a/src/mcp/tools/spiceTools.ts b/src/mcp/tools/spiceTools.ts new file mode 100644 index 0000000..f204af2 --- /dev/null +++ b/src/mcp/tools/spiceTools.ts @@ -0,0 +1,46 @@ +import * as z from "zod/v4"; +import type { McpServer } from "@modelcontextprotocol/server"; +import type { EditorClient } from "../../editor/EditorClient.js"; +import { DefaultTimeoutSchema, DocumentTargetSchema, registerReadTool } from "./common.js"; + +export function registerSpiceTools(server: McpServer, bridge: EditorClient): void { + registerReadTool(server, bridge, { + name: "easyeda_evaluate_spice_support", + title: "Evaluate SPICE simulation feasibility and readiness", + description: + "Performs feasibility evaluation of analog SPICE simulation on the active schematic: audits component SPICE model availability, verifies Node 0 / GND reference, checks stimulus sources, and documents engine limits and platform boundaries.", + method: "evaluateSpiceFeasibility", + inputSchema: { + groundNet: z.string().default("GND").describe("Net name expected as ground datum (mapped to SPICE node 0)."), + target: DocumentTargetSchema.optional(), + timeoutMs: DefaultTimeoutSchema.default(30_000) + }, + summary: "Evaluated SPICE simulation feasibility and readiness." + }); + + registerReadTool(server, bridge, { + name: "easyeda_generate_spice_netlist", + title: "Generate standard SPICE netlist", + description: + "Generates a syntactically valid SPICE circuit netlist (.cir / .sp) with ground-to-0 normalization, primitive RLC elements, semiconductor models, and configurable analysis directives (.op, .tran, .ac, .dc) for simulation in ngspice, LTspice, or Xyce.", + method: "generateSpiceNetlist", + inputSchema: { + analysisType: z + .enum(["op", "tran", "ac", "dc"]) + .default("op") + .describe("Simulation analysis type (.op, .tran, .ac, .dc)."), + analysisParams: z + .string() + .optional() + .describe("Custom analysis directive arguments (e.g. '1u 10m' for .tran, or '10 1 1Meg' for .ac)."), + groundNet: z.string().default("GND").describe("Net name to map to SPICE datum node 0."), + includeSubcircuits: z.boolean().default(true).describe("Whether to include X subcircuit cards for ICs."), + includeDefaultModels: z.boolean().default(true).describe("Include built-in generic diode and BJT .model cards."), + fileName: z.string().min(1).optional().describe("Optional output file name without extension."), + destinationPath: z.string().min(1).optional().describe("Optional destination directory / target path."), + target: DocumentTargetSchema.optional(), + timeoutMs: DefaultTimeoutSchema.default(30_000) + }, + summary: "Generated SPICE circuit netlist." + }); +}