kicad-splitplane 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,172 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ kicad-splitplane-mcp - MCP server that lets AI agents split KiCad power planes.
4
+
5
+ A thin wrapper around the kicad_splitplane library with two tools:
6
+
7
+ list_power_nets(board_path) which supply nets the board has
8
+ split_plane(board_path, nets, ...) one zone per net, written to a NEW board
9
+
10
+ It never overwrites the input board. Run it over stdio:
11
+
12
+ pip install "kicad-splitplane[mcp]"
13
+ kicad-splitplane-mcp # or: uvx kicad-splitplane-mcp
14
+
15
+ Works with the MCP Python SDK 2.x (MCPServer) and 1.x (FastMCP).
16
+
17
+ Author: Aleksandar Tuzlak - MIT License
18
+ """
19
+ import os
20
+ import re
21
+ import sys
22
+ from typing import List, Optional
23
+
24
+ import kicad_splitplane as sp
25
+
26
+ try: # MCP Python SDK 2.x
27
+ from mcp.server.mcpserver import MCPServer as _Server
28
+ from mcp.server.mcpserver.exceptions import ToolError
29
+ except ImportError:
30
+ try: # MCP Python SDK 1.x
31
+ from mcp.server.fastmcp import FastMCP as _Server
32
+ from mcp.server.fastmcp.exceptions import ToolError
33
+ except ImportError:
34
+ _Server = None
35
+
36
+ class ToolError(Exception):
37
+ """Stand-in so the tool functions work without the MCP SDK."""
38
+
39
+ __version__ = sp.__version__
40
+
41
+ INSTRUCTIONS = """\
42
+ kicad-splitplane splits one copper layer of a KiCad board (.kicad_pcb) into
43
+ one continuous zone per supply net, computed from the nets' vias and
44
+ through-hole pads. Use it when several supply nets (e.g. +5V, +3V3, +1V8)
45
+ share one power-plane layer. Never put GND on a split plane; GND gets its own
46
+ solid plane.
47
+
48
+ Workflow: list_power_nets -> pick the supply nets with the user ->
49
+ split_plane -> handle the warnings -> the user opens the new board in KiCad,
50
+ fills all zones (B) and runs DRC. The input board is never modified."""
51
+
52
+ LIST_DESCRIPTION = """\
53
+ List the supply-like nets of a KiCad board (.kicad_pcb) and its copper layers.
54
+
55
+ Call this first, before split_plane, to find out which nets can share a
56
+ power-plane layer. For each net it returns the number of vias/through-hole
57
+ pads (the seeds split_plane uses) and SMD pads. A net with 0 vias/THT but SMD
58
+ pads has not been fanned out yet: preview it with split_plane(include_smd=True).
59
+ Supply-like means the name looks like a voltage or rail (+5V, 3V3, VCC, VDD,
60
+ VBUS, VIN, ...); set all_nets=True if the user's supply nets have other names.
61
+ GND and signal nets are not candidates. Read-only; changes nothing."""
62
+
63
+ SPLIT_DESCRIPTION = """\
64
+ Split one copper layer of a KiCad board into one continuous zone per supply
65
+ net and write the result to a NEW board file (the input is never overwritten).
66
+
67
+ Use it when two or more supply nets (e.g. +5V, +3V3, +1V8) share one plane
68
+ layer. Never include GND or signal nets. Get the net names and the layer from
69
+ list_power_nets first and confirm them with the user if unsure.
70
+
71
+ Writes <out_path> (default <board>_splitplane.kicad_pcb), a preview PNG next
72
+ to it and copies of the project files (.kicad_pro/.kicad_prl, nets coloured as
73
+ in the preview). Returns ok, per-net zones (parts, area_mm2, seeds), warnings,
74
+ the log and the written file paths.
75
+
76
+ Warnings and what to do:
77
+ - "via ... is trapped by other nets -> move it to ~(x, y)": move that via to
78
+ the suggested spot (or retry with a smaller res, e.g. 0.3).
79
+ - "split into N islands" / "cut the copper into N pieces": the net cannot be
80
+ one zone with the current vias; move or add vias, or try another layer.
81
+ - "has a neck narrower than ... mm": a thin spot; acceptable next to dense
82
+ connectors, otherwise move vias to give it room.
83
+ - "pad/via ... is not connected to its zone" / "zone runs over a ... pad/via":
84
+ move the named via, or reduce gap.
85
+ - No vias/THT pads for a net: the board is not fanned out yet. Run again with
86
+ include_smd=True for a PREVIEW only (SMD pads stand in for vias), place vias,
87
+ then run without include_smd for the real split.
88
+
89
+ ok=True means one connected zone per net. Afterwards tell the user to open the
90
+ new board in KiCad, fill all zones (B) and run DRC; the tool cannot do that.
91
+
92
+ Parameters (mm): gap between zones (0.5), edge clearance to the board edge
93
+ (0.5), min_neck warning width (1.0), res grid resolution (0.5; 0.3-0.6 if vias
94
+ get trapped). plain=True skips connecting the vias (faster, may give islands).
95
+ keep_old=True keeps existing zones of these nets on the layer (default: they
96
+ are replaced)."""
97
+
98
+
99
+ def _board(board_path: str) -> str:
100
+ path = os.path.abspath(os.path.expanduser(board_path))
101
+ if not path.endswith(".kicad_pcb"):
102
+ raise ToolError(f"Not a KiCad board (.kicad_pcb): {board_path}")
103
+ if not os.path.isfile(path):
104
+ raise ToolError(f"Board not found: {path}")
105
+ return path
106
+
107
+
108
+ def list_power_nets(board_path: str, all_nets: bool = False) -> dict:
109
+ path = _board(board_path)
110
+ text = open(path, encoding="utf-8").read()
111
+ try:
112
+ nets = sp.list_nets(text) if all_nets else sp.list_power_candidates(text)
113
+ layers = sp.copper_layers(sp.parse_sexpr(text))
114
+ except ValueError as e:
115
+ raise ToolError(str(e)) from e
116
+ return {"board": path, "copper_layers": layers,
117
+ "nets": [{"name": n, "vias_tht": t, "smd": s} for n, t, s in nets]}
118
+
119
+
120
+ def split_plane(board_path: str, nets: List[str], layer: str = "In2.Cu", gap: float = 0.5,
121
+ edge: float = 0.5, min_neck: float = 1.0, res: float = 0.5,
122
+ include_smd: bool = False, plain: bool = False, keep_old: bool = False,
123
+ out_path: Optional[str] = None) -> dict:
124
+ path = _board(board_path)
125
+ out = (os.path.abspath(os.path.expanduser(out_path)) if out_path
126
+ else re.sub(r"\.kicad_pcb$", "", path) + "_splitplane.kicad_pcb")
127
+ if not out.endswith(".kicad_pcb"):
128
+ raise ToolError(f"out_path must end in .kicad_pcb: {out_path}")
129
+ if os.path.realpath(out) == os.path.realpath(path):
130
+ raise ToolError("out_path must differ from board_path: the input board is never overwritten.")
131
+ if not os.path.isdir(os.path.dirname(out)):
132
+ raise ToolError(f"Output folder does not exist: {os.path.dirname(out)}")
133
+ text = open(path, encoding="utf-8").read()
134
+ try:
135
+ r = sp.process(text, layer, nets, gap, edge, min_neck, res, include_smd, plain, keep_old)
136
+ except ValueError as e:
137
+ raise ToolError(str(e)) from e
138
+ result = {**sp.summary(r), "files": sp.write_outputs(path, out, r)}
139
+ if include_smd:
140
+ result["note"] = ("Preview only: SMD pads stood in for vias. Place the vias, then run "
141
+ "again without include_smd.")
142
+ return result
143
+
144
+
145
+ def build_server():
146
+ """The MCP server with both tools registered (needs the MCP SDK)."""
147
+ if _Server is None:
148
+ raise ImportError("the MCP Python SDK is not installed")
149
+ server = _Server("kicad-splitplane", instructions=INSTRUCTIONS)
150
+ server.tool(description=LIST_DESCRIPTION)(list_power_nets)
151
+ server.tool(description=SPLIT_DESCRIPTION)(split_plane)
152
+ return server
153
+
154
+
155
+ def main(argv=None):
156
+ argv = sys.argv[1:] if argv is None else argv
157
+ if argv and argv[0] in ("-h", "--help"):
158
+ print(__doc__.strip())
159
+ return 0
160
+ if argv and argv[0] == "--version":
161
+ print(__version__)
162
+ return 0
163
+ if _Server is None:
164
+ sys.exit("kicad-splitplane-mcp needs the MCP Python SDK. Install it with\n"
165
+ ' pip install "kicad-splitplane[mcp]"\n'
166
+ "or run the server with: uvx kicad-splitplane-mcp")
167
+ build_server().run()
168
+ return 0
169
+
170
+
171
+ if __name__ == "__main__":
172
+ sys.exit(main())