Skip to main content
Glama
Mastercam MCP Server

Mastercam MCP Server

by FunSize77
README.md
# Mastercam MCP Server

A [Model Context Protocol](https://modelcontextprotocol.io) server that lets AI agents drive **Mastercam 2027**: open parts, inspect geometry, build tools and toolpaths, regenerate, post
G-code and produce setup sheets — in the Mastercam window in front of the user.

It is a standard MCP server, not tied to one AI vendor: it works with any MCP client (Claude Desktop, Claude Code,
Cursor, VS Code, Windsurf, OpenAI Codex CLI, Gemini CLI, LM Studio, ...) and any model that can call tools, including
local models (see `examples/ollama_agent.py`). Tested: Claude, and a 4B local Gemma model through Ollama.

Status: **1.0.2**. Verified live on Mastercam 2027 Update 1 (29.1.193.0). See [docs/FEATURES.md](docs/FEATURES.md)
for the full feature map and roadmap (machine/control definitions, simulation, post editing, ...).

## Architecture

```
MCP client ──stdio──> mastercam_mcp (Python, FastMCP)
                          │  JSON lines over a Windows named pipe
                          ▼
                Mastercam.exe ── McamMcp.dll (NET-Hook add-in, .NET 10)
                                  runs each command on Mastercam's UI thread
```

* **`plugin/McamMcp`** — C# NET-Hook loaded by Mastercam. It serves two pipes:
  `\\.\pipe\mastercam_mcp_<pid>` (always, one per Mastercam process) and the shared `\\.\pipe\mastercam_mcp`
  (owned by the first Mastercam to start; the others take it over when it exits).
  A dialog watcher answers Mastercam message boxes that appear during a command (so a "Toolpath regeneration
  failed" box never hangs the agent) and returns their text to the client.
* **`mastercam_mcp`** — the Python MCP server: tool definitions, path policy, launcher, setup-sheet generator and
  the `run_job` workflow.

## Install

### From the release package (testers)

Requirements: Windows, Mastercam 2027, Python 3.10+ (no .NET SDK). Unzip `mastercam-mcp-<version>.zip`, close
Mastercam, then from that folder:

```powershell
powershell -ExecutionPolicy Bypass -File .\install.ps1 -Startup -Client cursor,vscode
```

It installs the server, copies the prebuilt add-in (approve the UAC prompt, or run from an elevated PowerShell), sets the
add-in to load with Mastercam and registers the server with the clients you name (`claude-desktop`, `claude-code`,
`cursor`, `vscode`, `windsurf`, `codex`, `gemini`, `lmstudio`; each file is backed up first). `install.ps1 -Uninstall` removes it.
See [docs/TESTING.md](docs/TESTING.md) for a first session and what to report.

### From source

Requirements: Windows, Mastercam 2027, .NET 10 SDK, Python 3.10+. `.\scripts\make-release.ps1` builds the release zip.

```powershell
# 1. Python package
pip install -e .[test]

# 2. Build and install the add-in. Close Mastercam first (the DLL is locked while it runs).
#    Copying into C:\Program Files\mcam needs administrator rights: run from an elevated PowerShell,
#    or approve the UAC prompt. The script checks the installed DLL's hash and fails loudly if the copy did not happen.
.\scripts\install-plugin.ps1            # add -Startup to load the bridge every time Mastercam starts
.\scripts\install-plugin.ps1 -Uninstall

# 3. Check (with Mastercam running and the add-in loaded: Add-Ins > MCP Bridge)
python -m mastercam_mcp --check
```

Without `-Startup`, load the bridge per session from **Add-Ins > MCP Bridge**; `launch_mastercam` starts
Mastercam and waits for the bridge.

## MCP client configuration

The server is started by the client: command `python`, arguments `-m mastercam_mcp`. To register it:

```powershell
python -m mastercam_mcp --configure cursor,vscode       # any of: claude-desktop, claude-code, cursor, vscode,
                                                         # windsurf, codex, gemini, lmstudio (backs up each file)
python -m mastercam_mcp --print-config                   # the common "mcpServers" JSON block, for any other client
python -m mastercam_mcp --print-config codex             # the block in that client's format
```

The common block (Claude Desktop, Cursor, Windsurf, Gemini CLI, LM Studio and most others):

```json
{
  "mcpServers": {
    "mastercam": {
      "command": "python",
      "args": ["-m", "mastercam_mcp"],
      "env": { "MCAM_MCP_ALLOWED_DIRS": "C:\\CAM\\jobs" }
    }
  }
}
```

VS Code (`mcp.json`) uses `"servers"` with `"type": "stdio"`; Codex uses `[mcp_servers.mastercam]` in `config.toml`.

**Fewer tools.** Some clients cap the number of tools, and small models choose better from a short list. Set
`MCAM_MCP_TOOLS` (or `--tools`) to `core` (about 25 tools, enough for a 2D part end to end), or to groups and tool names:
`core,planes,wireframe`. Groups: session, files, part, wireframe, planes, setup, tools, toolpaths, edit, check, output,
scripting. `--configure ... --tools core` writes it into the client config.

**HTTP clients.** For a client that connects to a URL instead of starting a program:
`python -m mastercam_mcp --http` serves `http://127.0.0.1:8765/mcp` (`--port` to change). It listens on this PC only;
there is no authentication, so do not expose it with `--host` unless a firewall or tunnel you control is in front of it.

**Any model.** `examples/ollama_agent.py` is a 90-line agent loop that connects a local Ollama model to the server, as a
reference for other harnesses.

## Environment variables

| Variable | Default | Meaning |
| --- | --- | --- |
| `MCAM_MCP_PIPE` | `mastercam_mcp` | Base pipe name (must match the add-in). |
| `MCAM_MCP_PID` | — | Pin the server to one Mastercam process (`mastercam_mcp_<pid>`). `select_mastercam` does the same at runtime. |
| `MCAM_MCP_TIMEOUT` | `120` | Default seconds per bridge call (long tools such as post/regenerate use more). |
| `MCAM_MCP_ALLOWED_DIRS` | — | `;`-separated folders. When set, every path read or written must be inside one of them. |
| `MCAM_MCP_ALLOW_SCRIPTS` | off | `1` exposes `execute_csharp` (arbitrary C# inside Mastercam). Also `--allow-scripts`. The add-in accepts it only when Mastercam also runs with it set. |
| `MCAM_MCP_NC_EXTENSIONS` | — | Extra file extensions `read_nc_file` / `check_nc_file` may read (`;`-separated), if your post writes an unusual one. |
| `MCAM_MCP_TOOLS` | `all` | Tools to expose: `all`, `core`, or groups / tool names separated by commas (see above). Also `--tools`. |
| `MASTERCAM_EXE` | auto | Full path to `Mastercam.exe` if it is not in the standard location. |

## Tools

| Area | Tools |
| --- | --- |
| Session | `mastercam_status`, `select_mastercam`, `launch_mastercam`, `get_state` |
| Guidance | `knowledge` (master guide, topics, search) |
| Files | `open_file`, `new_file`, `save_file`, `export_file` (STEP, Parasolid, ACIS, STL, DXF), `screenshot` |
| Part | `get_part_info`, `get_extents`, `list_levels`, `list_geometry` |
| Wireframe | `create_geometry`, `delete_geometry`, `set_level` |
| Planes | `list_planes`, `create_plane`, `update_plane`, `set_planes` (WCS, tool and construction planes, work offsets) |
| Setup | `list_machine_groups`, `create_machine_group`, `set_output_folder`, `set_stock`, `create_toolpath_group`, `set_active_group` |
| Tools | `list_tools`, `list_library_tools`, `create_tool` (22 tool types) |
| Toolpaths | `create_facing`, `create_contour`, `create_pocket`, `create_drill`, `create_circle_mill`, `create_helix_bore`, `list_library_operations`, `import_operations` |
| Edit | `list_operations`, `update_operation`, `get_operation_parameters`, `set_operation_parameters`, `move_operations`, `copy_operations`, `delete_operations`, `regenerate_operations`, `get_cycle_time`, `operation_stats` |
| Output | `post_process`, `read_nc_file`, `check_nc_file`, `generate_setup_sheet`, `run_native_setup_sheet` |
| Workflow | `run_job` (open → library ops → regenerate → save → post → setup sheet), prompt `program_part` |
| Scripting | `execute_csharp` (opt-in) |

Notes for agents and integrators (the `knowledge` tool serves these and more to the agent):

* Heights in `linking` are **absolute** unless the matching `*_incremental` flag is set (Mastercam's own default for
  new operations is incremental). For drilling, `feed_plane` is the R plane.
* `chain` picks curves that lie flat in the operation's tool plane (`plane`, else the active one), at any depth. If they are
  at several depths the call is refused until you give `chain.depth` (a Z in that plane, or `"all"`) or `entity_ids`.
  Closed chains run clockwise seen from the plane, so `comp_side: left` is outside and `right` is inside.
* `plane` is the tool plane (`top`, `front`, ... or a plane name; on a horizontal machine `front` is usually B0). For holes,
  `positions` and `bolt_circle` are in that plane's coordinates.
* `bolt_circle` is `{diameter, count, start_angle, center, z}` or a list of them. `coolant` is `flood`, `mist`, `thru` or `off`.
* `create_circle_mill` plunges at the hole center: use it on pre-drilled holes. `create_helix_bore` cuts from solid.
* Taps need `threads` in `create_tool` (threads per inch, or pitch in mm), otherwise they post a zero feed.
* New operations take the tool's H/D numbers unless `length_offset` / `diameter_offset` are given.
* Every create_* starts from the machine's default settings: Mastercam itself would copy the last operation of the
  same type (a plain drill after a tap came out as a tap). Only what you pass changes them.
* Stock to leave is 0 unless given, and stepovers follow the tool (pocket 50%, facing 75%), so the depth asked for is the depth cut.
  Contour lead in/out lines and arcs are 100% of the tool diameter (`lead` to change them, `lead: false` for none).
* `post_errors: true` from `post_process` / `run_job`: the post reported errors; do not run that NC file until they are explained.
* `check_nc_file` reviews posted G-code (F0, spindle off while cutting, H/D vs tool, rapids into the stock zone, travel,
  program end) and lists each tool's Z range, feeds and speeds. `run_job` runs it on every NC file. It is not a simulation.
* Mastercam cannot move an operation into another group, so `move_operations` with `group_id` copies and deletes:
  the operation gets a new id (`new_ids` in the result).
* Facing `across_overlap` (default 50) / `along_overlap` (default 110) are percent of the tool diameter (Mastercam needs ≥ 50 to face a boundary).
  In `set_operation_parameters`, `CutParams.AcrossOverlap`/`AlongOverlap` are raw distances in part units.
* `get_operation_parameters` dumps every parameter group of an operation; `set_operation_parameters` writes any of
  them by path (`{"EntryHelix.MaxRadius": 0.05}`), so the structured tools are never a ceiling.
* Results may carry `mastercam_messages` — dialogs Mastercam showed and how the bridge answered them. A
  `regenerated: false` / `warning` result means the operation exists but has no toolpath; `post_process` reports such
  operations as `dirty_operations`.

## Safety

* **Every toolpath produced by automation must be verified (simulation, backplot, review) before it runs on a machine.**
* Save As and `run_job` keep an existing `.mcam` unless `overwrite` is true. Posted NC files in the output folder are replaced.
* With several Mastercam windows open, `mastercam_status` lists them and the agent must `select_mastercam` the right one.
* `execute_csharp` is off by default, in both the MCP server and the Mastercam add-in. It is on only when
  `MCAM_MCP_ALLOW_SCRIPTS=1` is set for both (as a user environment variable: `setx MCAM_MCP_ALLOW_SCRIPTS 1`, then restart
  Mastercam and the MCP client). Enable it only for trusted clients: it runs arbitrary code inside Mastercam.
* Use `MCAM_MCP_ALLOWED_DIRS` to fence file access to job folders.
* File tools only touch their own file types (Save As `.mcam`, exports, `.png`, `.html`; NC readers only NC extensions,
  extendable with `MCAM_MCP_NC_EXTENSIONS`). The add-in's pipe accepts only the same Windows user. `--http` listens on this
  PC only and rejects foreign Host headers and browser origins. See [SECURITY.md](SECURITY.md).

## Troubleshooting

| Symptom | Fix |
| --- | --- |
| `BridgeUnavailable: No bridge is listening` | Start Mastercam and load Add-Ins > MCP Bridge (or install with `-Startup`). |
| Install says "Elevated copy failed" | The UAC prompt was declined or hidden. Run the script from an elevated PowerShell. |
| Install says "Mastercam is running" | Close every Mastercam window; the add-in DLL is locked while it runs. |
| A call timed out | Mastercam may be busy or showing a non-standard dialog. Look at its window; the command still runs and later calls continue normally. |
| Commands go to the wrong Mastercam | `mastercam_status`, then `select_mastercam(pid)`, or set `MCAM_MCP_PID`. |
| `version_warning` in `mastercam_status` | The add-in and the server are different releases: close Mastercam and rerun `install-plugin.ps1`. |
| `AmbiguousDepth` from a create tool | Curves exist at several depths; pass `chain.depth` or `chain.entity_ids`. |
| Anything else | Bridge log: `%LOCALAPPDATA%\McamMcp\bridge.log`. |

## Development

```powershell
python -m pytest              # protocol, server and workflow tests against a fake bridge (no Mastercam needed)
dotnet build plugin\McamMcp -c Release
```

## License and trademarks

MIT (see [LICENSE](LICENSE)). Mastercam is a trademark of CNC Software, LLC. This project is independent and is not
affiliated with or endorsed by CNC Software. It needs a licensed copy of Mastercam to do anything.

TDQS

B3.2/5.0

Scored across 54 tools

Disambiguation4/5

Despite 54 tools, most have a clearly distinct resource+action target, and the descriptions actively disambiguate the risky pairs (create_circle_mill vs create_helix_bore, generate_setup_sheet vs run_native_setup_sheet, list_tools vs list_library_tools). There is residual overlap among the several 'what is the current state' tools (mastercam_status, get_state, get_part_info, list_operations) and between run_job and the individual step tools, but an agent can still choose correctly from the text.

Naming Consistency4/5

The dominant convention is snake_case verb_noun (create_contour, set_planes, list_geometry, delete_operations), applied across nearly the whole surface. Minor deviations exist: bare nouns (knowledge, screenshot, operation_stats), noun-first names (mastercam_status), and 'new_file' where create_* would be expected, plus launch_mastercam/select_mastercam placing the server name in different positions.

Tool Count2/5

54 tools is well past the point where an agent can reason about the surface at once, even though the CAD-to-CAM domain is genuinely broad and most tools are non-redundant. The set is sensibly grouped into lifecycle areas, but it would benefit from consolidation (e.g. run_job-style wrappers for common sequences).

Completeness4/5

Coverage is strong across the domain: session/file management, geometry, levels, planes, tools, toolpath operations, machine groups, stock, posting, NC verification, setup sheets and a one-shot job runner. Gaps remain around geometry modification/transforms (only create and delete), tool editing/library import, and machine-group removal, but these are workaroundable.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues