Skip to content

caidish/KlayoutClaw

Repository files navigation

KlayoutClaw

Python 3.10+ MCP License: MIT

AI-powered layout design platform for KLayout. Connects your agent (Claude Code, Codex, Cline, or any MCP client) to your desktop KLayout through the Model Context Protocol, and ships Claude Code skills for geometry creation, layer display, visual capture, and nanodevice fabrication pipelines.

Built for device physicists working on 2D material devices, superconducting qubits, photonics, and other micro/nanofabricated systems.

macOS only for now. Linux/Windows support is planned but untested. We need more help with Windows/Linux Native user and more benchmark test.

Demo

Real Sample Nanodevice Demo

Full nanodevice fabrication pipeline on a real van der Waals heterostructure sample: load a GDS template, overlay flake detection results from the flakedetect and gdsalign pipelines, generate a 8 pin Hall bar, and route 11 pins to bonding pads using multi-window routing.

Real Sample Demo

What's Inside

KlayoutClaw has three layers:

Layer What it does
MCP Server KLayout autorun macro — JSON-RPC 2.0 server on 127.0.0.1:8765. 6 tools: create layouts, run pya scripts, save GDS/OASIS, capture screenshots, autoroute pin pairs. Zero external dependencies.
Skills Claude Code plugin with 7 skills — geometry, display, visual, image, and 3 nanodevice pipelines (flakedetect, gdsalign, routing). Claude loads them automatically when relevant.
Tools Standalone utilities — GDS-to-PNG converter, subprocess routing engine. Used by the MCP server and skills internally.
┌─────────────┐       HTTP/JSON-RPC        ┌─────────────────┐
│  Claude /    │  ◄──────────────────────►  │  KLayout GUI    │
│  Codex /     │    127.0.0.1:8765/mcp      │  + KlayoutClaw  │
│  Any MCP     │                            │    plugin        │
│  client      │                            │                  │
└─────────────┘                            └─────────────────┘
       │
       │  Skills (Claude Code plugin)
       │  geometry, display, visual, image,
       │  nanodevice:{flakedetect, gdsalign, routing}
       ▼

Quick Start

# 1. Clone
git clone https://github.com/caidish/KlayoutClaw.git
cd KlayoutClaw

# 2. Install plugin into KLayout
python install.py

# 3. Launch KLayout
open /Applications/klayout.app

# 4. Test the connection
python tests/test_connection.py

MCP Tools

Tool Description
create_layout Create a new layout with a top cell
execute_script Run arbitrary Python/pya code in KLayout
save_layout Save layout as GDS2 or OASIS
get_layout_info Get layout summary (cells, layers, dbu)
screenshot Capture viewport as PNG (what the user sees)
auto_route Autoroute connections between pin pairs

execute_script is the power tool — it runs any Python code inside KLayout with access to pya, the current layout, and view. The other tools handle lifecycle and visualization. See docs/tools.md for full parameter schemas.

Autorouter

auto_route automatically connects pin pairs using Hungarian matching and cost-based pathfinding. It runs as a subprocess with numpy/scipy/scikit-image, supporting obstacle avoidance, configurable path spacing, and graduated damping cost fields. See docs/tools.md for tuning parameters.

Example: Create a rectangle via MCP

import json, urllib.request

def mcp(method, params=None, req_id=1):
    payload = {"jsonrpc": "2.0", "id": req_id, "method": method}
    if params: payload["params"] = params
    req = urllib.request.Request("http://127.0.0.1:8765/mcp",
        data=json.dumps(payload).encode(),
        headers={"Content-Type": "application/json"}, method="POST")
    return json.loads(urllib.request.urlopen(req).read())

# Initialize + create layout
mcp("initialize", {"protocolVersion": "2025-03-26", "capabilities": {},
    "clientInfo": {"name": "example", "version": "0.1"}})
mcp("tools/call", {"name": "create_layout", "arguments": {"name": "TOP"}}, 2)

# Draw a 100x50um rectangle on layer 1/0
mcp("tools/call", {"name": "execute_script", "arguments": {"code": """
dbu = _layout.dbu
li = _layout.layer(1, 0)
_top_cell.shapes(li).insert(pya.Box(int(-50/dbu), int(-25/dbu), int(50/dbu), int(25/dbu)))
result = {"status": "ok", "shape": "rectangle"}
"""}}, 3)

# Save
mcp("tools/call", {"name": "save_layout",
    "arguments": {"filepath": "/tmp/example.gds"}}, 4)

Using with Claude Code

# Add KlayoutClaw as an MCP server
claude mcp add --transport http klayoutclaw http://127.0.0.1:8765/mcp

# Or use the config file
claude --mcp-config mcp_config.json

Then just ask Claude to create layouts:

"Create a Hall bar device with a 100x25um graphene channel, 6 side probes, metal contacts, and bonding pads. Save it as hallbar.gds."

Skills (Claude Code Plugin)

KlayoutClaw is also a Claude Code plugin. Install it to get skills that Claude invokes automatically:

# Add the marketplace
/plugin marketplace add caidish/KlayoutClaw

# Install the plugin
/plugin install klayoutclaw@klayoutclaw

Or test locally during development:

claude --plugin-dir ./path/to/KlayoutClaw

Available Skills

Skill Slash Command Description
geometry /klayoutclaw:geometry Create rectangles, polygons, paths, cells, and instances
display /klayoutclaw:display Toggle layer visibility, show/hide layers
visual /klayoutclaw:visual Capture layout as PNG for visual inspection
image /klayoutclaw:image Load reference images (microscope, SEM) as background overlay
nanodevice:flakedetect -- Detect vdW heterostructure material boundaries (hBN, graphene, graphite) from optical images
nanodevice:gdsalign -- Align GDS templates to microscope images using lithographic marker detection
nanodevice:routing -- Place bonding pads and autoroute connections between device features

Claude loads these skills automatically when relevant (e.g., "draw a rectangle" triggers the geometry skill).

See docs/skills.md for full reference.

Nanodevice Skills

Agent-orchestrated pipelines for semiconductor/2D-material device fabrication workflows:

flakedetect -- Identifies material boundaries in van der Waals heterostructure stacks from optical microscope images. 5 stages: cross-substrate alignment (SIFT + Chamfer), per-material segmentation (graphite, graphene, top/bottom hBN), coordinate transforms + overlay, polygon commit to KLayout, and visual review.

gdsalign -- Aligns GDS lithography templates to microscope images. Extracts marker pairs from GDS, template-matches them in the image, computes a similarity transform, and warps contours into GDS coordinates.

routing -- Multi-window EBL routing. Places bonding pads around the field perimeter with pin markers, then runs two-pass routing (inner fine + outer coarse + boundary patches) to connect device features to pads.

UI Plugin

The UI plugin (klayoutclaw_ui.lym) adds a status indicator and command history panel to KLayout -- no source modifications needed.

  • Status bar: Shows MCP: Running ● :8765 in green when active
  • Dock panel: Scrollable command history with timestamps and pass/fail indicators

See docs/ui-plugin.md for details.

Project Structure

KlayoutClaw/
├── .claude-plugin/
│   ├── plugin.json               # Claude Code plugin manifest
│   └── marketplace.json          # Claude Code marketplace catalog
├── plugin/
│   ├── klayoutclaw_server.lym    # MCP server (v0.6)
│   └── klayoutclaw_ui.lym        # UI panel + status bar
├── skills/                       # Claude Code skills (auto-loaded)
│   ├── scripts/mcp_client.py     # Shared MCP client
│   ├── geometry/                 # Shape creation skills
│   ├── display/                  # Layer visibility skills
│   ├── image/                    # Background image overlay skill
│   ├── visual/                   # Layout capture skill
│   └── nanodevice/               # Device fabrication pipelines
│       ├── flakedetect/          # vdW heterostructure detection (5 sub-skills)
│       ├── gdsalign/             # GDS template alignment
│       └── routing/              # Pad placement + autorouting
├── tools/
│   ├── gds_to_image.py           # GDS → PNG converter (gdstk + matplotlib)
│   ├── capture_demo.py           # Simple Hall bar demo capture script
│   ├── capture_ml08_demo.py      # ML08 nanodevice demo
│   └── route_worker.py           # Subprocess routing engine
├── tests/
│   ├── test_connection.py        # Protocol-level MCP test
│   ├── test_connection.sh        # E2E connection test
│   ├── test_flakedetect.py       # Flakedetect pipeline tests
│   ├── test_gdsalign.py          # GDS alignment tests (12 tests)
│   ├── test_utf8_body_corruption.py  # UTF-8 body corruption regression test
│   ├── create_hallbar.py         # Hall bar creation test
│   ├── create_hallbar_unrouted.py # Unrouted Hall bar (autorouter input)
│   ├── evaluate_gds.py           # Hall bar structural evaluation
│   ├── evaluate_routing.py       # Routing structural validation
│   ├── test_hallbar.sh           # E2E Hall bar test
│   └── test_autoroute.sh         # E2E autoroute test
├── tests_resources/              # Test fixtures
│   ├── graphene_for_test.jpg     # Graphene microscope image
│   └── ml08/                     # ML08 sample data
├── docs/
│   ├── tools.md                  # MCP tool reference (6 tools)
│   ├── skills.md                 # Skills reference (7 skills)
│   ├── ui-plugin.md              # UI plugin docs
│   ├── plans/                    # Architecture design docs
│   └── superpowers/              # Design specs and implementation plans
├── install.py                    # KLayout plugin installer
├── mcp_config.json               # MCP client config (HTTP, port 8765)
└── pyproject.toml                # pytest configuration

Qiskit Quantum Simulation (Experimental)

KlayoutClaw can be paired with a Qiskit MCP server for quantum device simulation. The agent reads transmon geometry from KLayout, writes simulation code (scqubits, qiskit-aer) in JupyterLab notebook cells, and verifies device physics -- all visible in the notebook.

Claude Code ──┬── KLayout MCP (8765)    layout geometry
              ├── instrMCP (8123)        notebook cell manipulation
              └── Qiskit MCP (8124)      namespace queries + resources

See docs/qiskit_mcp.md for full setup, tool reference, and testing instructions.

Architecture

  • pya.QTcpServer on Qt main thread -- no Python threads, no GIL issues
  • No external dependencies for the server -- only Python stdlib + pya
  • JSON-RPC 2.0 over HTTP (plain JSON, no SSE)
  • auto_route spawns a subprocess for heavy computation (numpy/scipy/scikit-image)
  • All pya calls execute on the main thread directly

See docs/plans/ for design decisions and the threading problem that led to this architecture.

Tests

# Protocol-level connection test (requires KLayout running)
python tests/test_connection.py

# Create a Hall bar and verify structure
python tests/create_hallbar.py /tmp/hallbar.gds
python tests/evaluate_gds.py /tmp/hallbar.gds

# Autoroute test (needs conda env instrMCPdev)
bash tests/test_autoroute.sh

# Full E2E (installs plugin, launches KLayout, tests connection)
bash tests/test_connection.sh

# Nanodevice skill tests (requires test fixtures in tests_resources/)
pytest tests/test_flakedetect.py tests/test_gdsalign.py -v

Community

Built for the device physics community. Interested in contributing? See CONTRIBUTING.md or contact caidish1234@gmail.com.

Acknowledgments

The auto-routing engine (tools/route_worker.py) incorporates algorithmic techniques from Klayout-Router by Legendrexial -- including graduated damping cost fields, pin-aware routing with per-pair recovery, and sorted routing order. Klayout-Router is licensed under the MIT License.

License

MIT

About

No description, website, or topics provided.

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors