release: v1.5.0 — discovery layer, honesty debt closed, Wave A

Tool count 131 -> 154; 474 -> 1242 collected tests.

The release exists for two measured reasons. A 149-tool catalog costs a client
~40,300 tokens before it has asked for anything, and a drafter searching the way
drafters think -- FILLET, BPOLY, QSELECT, WBLOCK -- scored df=0 against the stock
index, because those words were simply not in the data.

Discovery and batching
- DISCOVERY_MODE=search replaces the catalog with search_tools + call_tool,
  ranked over an AutoCAD command and synonym corpus (discovery/aliases.py) on
  top of fastmcp's BM25 index. Measured: 40,305 -> 356 tokens advertised.
- cad_batch runs a step list in one round trip; fields= projects result-heavy
  responses. The `core` profile is gone -- discovery replaced it.

Honesty debt (Tier 0)
- OCS/ECS: `extrusion` appeared nowhere in this codebase, so mirrored and
  rotated geometry reported coordinates that were quietly wrong. backends/ocs.py
  translates at the backend boundary; every tool coordinate is WCS on both
  engines, and a tilted plane refuses rather than answering with a number that
  looks fine.
- drawing_save_as(fmt="dwg") wrote DXF bytes to a .dwg path. drawing_audit never
  repaired. analysis_measure_area shoelaced points the caller typed in.
- ezdxf calls gained a per-call timeout, so one hung call can no longer wedge a
  server whose document lock is a single asyncio.Lock.

Architecture
- The 1854-line backend ABC is 19 contract modules; @capability(key, reason=)
  makes optional methods declarative and a gate fails on undeclared holes.
- 8 layout/viewport tools, CHSPACE, CAD_PROGID escape hatch.
- Wave A: selection filters, boundary tracing, hatch depth, annotation objects,
  measurement -- 13 tools of a planned 39. The REGION and 2D-boolean family was
  cut on evidence: add_region() yields zero ACIS bytes and the greiner_hormann
  substitute loses 28.2% of the area on a square with one semicircular edge.

Verified against a live AutoCAD 2026, which found four COM defects no amount of
reading would have caught -- AcadPViewport has no ViewCenter, and the line that
set it had been swallowed by a bare except since v1.4.

Benchmark v3 (15 tasks) and what it caught
- v2 scored this server 10/10, which carried no information: every task in it
  exercised something the server was built around. Five tasks were added because
  they can fail, and three did while being written -- a hatch could not be
  measured though the refusal listed HATCH as measurable, the boundary tools and
  the measure tool disagreed about the same shape (139.2177 vs 139.2699), and a
  circle stored as two bulged vertices measured 0.0.
- Competitor reports are NOT re-scored. They are pinned v1.4 runs against v2 and
  were never asked these five questions; the chart shows those rows `not run`.
- Correctness A/B: 21/24 -> 24/24, zero regressions.

Performance, stated plainly
The published v1.4 perf report was recorded on CPython 3.14 and the new one on
3.11.15, so the apparent 2-6x speedup is the interpreter, not this release.
Re-measured on one interpreter, v1.5.0 is 28% slower creating entities and 22%
slower on the 10k roundtrip. Fully attributed: EZDXF_CALL_TIMEOUT=0 restores
v1.4.0's exact numbers. That is the deadlock fix being paid for, the knob is
documented, and winning it back is on the 1.6 roadmap.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Umut CAN
2026-08-06 09:45:20 +03:00
co-authored by Claude Opus 5
parent d5a0ff5109
commit b03a7615b1
107 changed files with 32640 additions and 4810 deletions
+155 -51
View File
@@ -6,6 +6,7 @@ Path traversal protection and command injection prevention.
from __future__ import annotations
import logging
import os
import re
from pathlib import Path
@@ -29,6 +30,38 @@ _BLOCKED_PATH_PATTERNS = re.compile(
)
_DRIVE_ANCHOR = re.compile(r"^[A-Za-z]:$")
def _reject_non_local_anchor(original: str, resolved: Path) -> None:
r"""Every guard below compares against plain ``X:\`` paths.
Windows accepts three other anchors that name the same files but compare
unequal: the extended-length prefix (``\\?\C:\...``), UNC (``\\host\share``)
and the admin shares (``\\localhost\C$``). The backslash spellings are
already rejected by ``_BLOCKED_PATH_PATTERNS``, but ``pathlib`` normalises
the *forward-slash* spellings into them only after ``.resolve()`` — so they
slipped past the pattern check and then failed to match ``C:/Windows`` in
the system-directory loop. Proven: ``//?/C:/Windows/win.ini`` handed back a
working handle to ``C:\Windows\win.ini``.
A hard input rejection, so a plain ``ToolError`` like its siblings — not a
capability refusal, which means "this backend cannot" and would wrongly
suggest another engine would accept it.
"""
drive = resolved.drive
if _DRIVE_ANCHOR.match(drive):
return
log.warning("Blocked non-local path anchor: %s -> %s", original, resolved)
raise ToolError(
f"Path rejected: '{original}' resolves to '{resolved}', which is not a "
f"plain local drive path (anchor '{drive}'). Extended-length (\\\\?\\), "
"device and UNC (\\\\host\\share, \\\\localhost\\C$) paths bypass the "
"system-directory and allowed-root checks and are not accepted. Use a "
"normal 'X:\\folder\\file.dxf' path."
)
def validate_path(path: str, *, allow_write: bool = False) -> Path:
"""Resolve and validate a file path against security rules.
@@ -49,6 +82,12 @@ def validate_path(path: str, *, allow_write: bool = False) -> Path:
resolved = Path(path).resolve()
# After .resolve() (drive is only meaningful once resolved) and before the
# system-directory loop, whose comparisons this is protecting. POSIX has no
# drive component at all, so the check is Windows-only by construction.
if os.name == "nt":
_reject_non_local_anchor(path, resolved)
_SYSTEM_DIRS = [
Path("C:/Windows").resolve(),
Path("C:/Program Files").resolve(),
@@ -103,56 +142,107 @@ def validate_path(path: str, *, allow_write: bool = False) -> Path:
# ---------------------------------------------------------------------------
# Command / LISP sanitization
#
# Why it is NOT incoherent to block INSERT/SAVEAS/NEW/OPEN/PURGE/ERASE here
# while `block_insert` / `drawing_save_as` / `drawing_new` / `drawing_open` /
# `drawing_purge` / `entity_delete` are tools — this gets re-raised, so it is
# recorded once:
#
# `sanitize_command` and `sanitize_lisp` each have exactly ONE caller, both of
# them the COM-only free-text escape hatch into SendCommand. The policy is
# scoped to the CHANNEL, not to the operation, which is capability narrowing
# rather than a contradiction:
#
# * `block_insert(name, x, y, ...)` takes a block ALREADY in the drawing plus
# typed geometry. The INSERT *command* takes a file path and pulls in an
# external DWG, which can carry an attached VBA/LISP payload. Same name,
# different capability.
# * `entity_delete(handle)` deletes one named entity. `ERASE ALL` does not.
# * `drawing_save_as` / `_open` / `_new` route their path through
# validate_path. A free-text `SAVEAS C:\...` routes through nothing.
# ---------------------------------------------------------------------------
_DANGEROUS_COMMANDS = [
"ERASE",
"_ERASE",
"DELETE",
"_DELETE",
"PURGE",
"_PURGE",
"QUIT",
"_QUIT",
"CLOSE",
"_CLOSE",
"QSAVE",
"_QSAVE",
"SAVEAS",
"_SAVEAS",
"NEW",
"_NEW",
"OPEN",
"_OPEN",
"RECOVER",
"_RECOVER",
"WBLOCK",
"_WBLOCK",
"INSERT",
"_INSERT",
"XREF",
"_XREF",
"SHELL",
"_SHELL",
"SCRIPT",
"_SCRIPT",
"APPLOAD",
"_APPLOAD",
"NETLOAD",
"_NETLOAD",
"VBARUN",
"_VBARUN",
"VBALOAD",
"_VBALOAD",
"SECURITYOPTIONS",
"_SECURITYOPTIONS",
]
_DANGEROUS_COMMAND_PATTERNS = re.compile(
r"\b(" + "|".join(re.escape(cmd) for cmd in _DANGEROUS_COMMANDS) + r")\b",
re.IGNORECASE,
# Matched against the extracted VERB, so the "_XXX" duplicates the old list
# carried are gone — command_verbs() strips every decorator AutoCAD accepts.
#
# Single-letter aliases are deliberately absent. `E` is the ERASE alias, but it
# is also the Extents *option* of ZOOM, so blocking it refuses `_ZOOM\nE\n` —
# the canonical zoom-extents macro, and this repo's own safe-command fixture.
# A guardrail that blocks the most common harmless macro gets switched off, and
# then it guards nothing.
_DANGEROUS_COMMANDS = frozenset(
{
# destructive to the drawing
"ERASE",
"DELETE",
"PURGE",
"WBLOCK",
"INSERT",
"XREF",
# ends or overwrites the session / file
"QUIT",
"EXIT",
"CLOSE",
"CLOSEALL",
"QSAVE",
"SAVE",
"SAVEAS",
"NEW",
"OPEN",
"RECOVER",
"RECOVERALL",
# loads or runs code — every channel found while probing
"SHELL",
"SCRIPT",
"SCR",
"APPLOAD",
"NETLOAD",
"ARX",
"VBARUN",
"VBALOAD",
"VBASTMT",
"VBAIDE",
"VBAMAN",
"CUILOAD",
"MENULOAD",
"MENU",
"CUI",
# writes files outside the tool layer's path validation
"EXPORT",
"ETRANSMIT",
"PUBLISH",
"SECURITYOPTIONS",
}
)
# AutoCAD accepts a command with any mix of these leading decorators:
# _ international (locale-independent) form
# . suppress a redefined command
# - the command-line (no dialog) variant
# ' transparent
_COMMAND_DECORATORS = "_.-*'"
def command_verbs(command: str) -> list[str]:
"""Every command verb in a SendCommand string.
SendCommand takes a whole macro, not one command: segments are separated by
a newline or ``;``, and only the FIRST token of a segment is a verb — the
rest is argument data. Scanning the raw string with a word-boundary regex is
what refused ``MTEXT 0,0 10,10 Do not erase this part``, which is annotation
text, while still missing spellings AutoCAD accepts.
"""
verbs: list[str] = []
for segment in re.split(r"[\n;]+", command):
segment = segment.strip()
if not segment:
continue
token = segment.split()[0].split(",")[0].lstrip(_COMMAND_DECORATORS)
if token:
verbs.append(token.upper())
return verbs
# Dangerous LISP symbols. We match these as **bare tokens anywhere** in the
# expression — not only when they appear right after `(` — because aliasing
# tricks like `(setq f command)(f "ERASE")` reference the symbol as a value.
@@ -191,6 +281,12 @@ _DANGEROUS_LISP_PATTERNS = [
r"\*push-error-using-stack\*",
]
# A double-quoted literal is DATA — drawing text, a layer name, a note. The
# symbol denylist must not read it. Without this, an engineering CAD server
# refused its own vocabulary: '(setq desc "Max load 500 kg")' matched
# r"(?:auto)?load" and '(setq layer "C:CENTER")' matched r"c:[\w-]+".
_LISP_STRING_LITERAL = re.compile(r'"(?:[^"\\]|\\.)*"')
_DANGEROUS_LISP_PATTERN = re.compile(
r"(?:(?<![\w-])|^)(?:" + "|".join(_DANGEROUS_LISP_PATTERNS) + r")(?![\w-])",
re.IGNORECASE,
@@ -210,12 +306,17 @@ def sanitize_command(command: str) -> str:
log.info("Dangerous commands enabled — bypassing sanitization for: %s", command[:80])
return command
if _DANGEROUS_COMMAND_PATTERNS.search(command):
blocked = {verb for verb in command_verbs(command) if verb in _DANGEROUS_COMMANDS}
if blocked:
log.warning("Blocked dangerous command: %s", command[:120])
raise ToolError(
f"Command rejected: '{command[:80]}' contains a restricted command. "
"Restricted commands include ERASE, DELETE, PURGE, QUIT, SHELL, SCRIPT, etc. "
"Set DANGEROUS_COMMANDS_ENABLED=true to allow all commands."
f"Command rejected: {', '.join(sorted(blocked))} "
f"{'is a restricted command' if len(blocked) == 1 else 'are restricted commands'}. "
"This denylist is a guardrail against accidental destruction, not a "
"security boundary — "
"prefer the typed tools (entity_delete, drawing_save_as, block_insert, "
"drawing_purge), which validate their arguments. Set "
"DANGEROUS_COMMANDS_ENABLED=true to allow all commands."
)
return command
@@ -236,7 +337,10 @@ def sanitize_lisp(expression: str) -> str:
)
return expression
if _DANGEROUS_LISP_PATTERN.search(expression):
# Blank the literals, then scan. The ORIGINAL expression is returned:
# this decides whether to run it, it does not rewrite it.
code_only = _LISP_STRING_LITERAL.sub('""', expression)
if _DANGEROUS_LISP_PATTERN.search(code_only):
log.warning("Blocked dangerous LISP expression: %s", expression[:120])
raise ToolError(
"LISP expression rejected: contains a restricted function. "