Skip to content

solidworks_mcp.adapters.mock_drawing_pack

solidworks_mcp.adapters.mock_drawing_pack

The mock adapter's drawing pack: the real adapter's refusals and replies.

Views get an outline on an A3 sheet, so positions, section lines and picks are checked the way the real adapter checks them; the rules themselves come from :mod:.solidworks.drawing_pack.

Attributes

Box module-attribute

Box = tuple[float, float, float, float]

PAPER_SIZES module-attribute

PAPER_SIZES: dict[str, tuple[int, float, float]] = {'a4': (6, 297.0, 210.0), 'a3': (8, 420.0, 297.0), 'a2': (9, 594.0, 420.0), 'a1': (10, 841.0, 594.0), 'a0': (11, 1189.0, 841.0)}

TITLE_BLOCK_FIELDS module-attribute

TITLE_BLOCK_FIELDS: dict[str, tuple[str, str]] = {'title': ('model', 'Description'), 'drawing_number': ('drawing', 'DrawingNo'), 'drawn_by': ('drawing', 'DrawnBy'), 'drawn_date': ('drawing', 'DrawnDate'), 'revision': ('drawing', 'Revision'), 'company': ('drawing', 'COMPANYNAME')}

Classes

AdapterResult dataclass

AdapterResult(status: AdapterResultStatus, data: T | None = None, error: str | None = None, execution_time: float | None = None, metadata: dict[str, Any] | None = None)

Result wrapper for adapter operations.

Attributes:

Name Type Description
data T | None

The data value.

error str | None

The error value.

execution_time float | None

The execution time value.

metadata dict[str, Any] | None

The metadata value.

status AdapterResultStatus

The status value.

Attributes
is_error property
is_error: bool

Check if operation had an error.

Returns:

Name Type Description
bool bool

True if error, otherwise False.

is_success property
is_success: bool

Check if operation was successful.

Returns:

Name Type Description
bool bool

True if success, otherwise False.

AdapterResultStatus

Bases: StrEnum

Result status for adapter operations.

Attributes:

Name Type Description
ERROR Any

The error value.

SUCCESS Any

The success value.

TIMEOUT Any

The timeout value.

WARNING Any

The warning value.

MockDrawingPackMixin

Section and detail views, dimensions, format, title block, report.

Methods:
add_dimension async
add_dimension(dimension_type: str, entity1_point: list[float], position: list[float], entity2_point: list[float] | None = None) -> AdapterResult[dict[str, Any]]

Mock dimension, measured between the points (fixed for circles).

Source code in src/solidworks_mcp/adapters/mock_drawing_pack.py
async def add_dimension(
    self,
    dimension_type: str,
    entity1_point: list[float],
    position: list[float],
    entity2_point: list[float] | None = None,
) -> AdapterResult[dict[str, Any]]:
    """Mock dimension, measured between the points (fixed for circles)."""
    refused = self._pack_guard("add_dimension") or self._pack_off_sheet(position)
    if refused:
        return refused
    points = [p for p in (entity1_point, entity2_point) if p is not None]
    owner = None
    for point in points:
        owner = next(
            (
                v
                for v in self._drawing_views
                if inside(point, self._pack_outline(v))
            ),
            None,
        )
        if owner is None:
            return _error(
                f"Nothing to dimension at {list(point)} mm on the sheet; "
                "give a point on a view's edge or vertex."
            )
    first, second = points[0], points[-1]
    values = {
        "horizontal": abs(second[0] - first[0]),
        "vertical": abs(second[1] - first[1]),
        "aligned": math.dist(first, second),
        "angular": 90.0,
        "radial": 3.0,
        "diameter": 6.0,
    }
    counts = self.__dict__.setdefault("_view_dimensions", {})
    counts[owner] = counts.get(owner, 0) + 1
    return _ok(
        {
            "name": f"RD{sum(counts.values())}@{owner}",
            "dimension_type": dimension_type,
            "value": round(values[dimension_type], 4),
            "units": "deg" if dimension_type == "angular" else "mm",
        }
    )
auto_dimension_view async
auto_dimension_view(view: str, scheme: str = 'baseline') -> AdapterResult[dict[str, Any]]

Mock auto-dimension: two more dimensions on the view.

Source code in src/solidworks_mcp/adapters/mock_drawing_pack.py
async def auto_dimension_view(
    self, view: str, scheme: str = "baseline"
) -> AdapterResult[dict[str, Any]]:
    """Mock auto-dimension: two more dimensions on the view."""
    refused = self._pack_guard("auto_dimension_view") or self._pack_unknown(view)
    if refused:
        return refused
    counts = self.__dict__.setdefault("_view_dimensions", {})
    before = counts.get(view, 0)
    counts[view] = before + 2
    return _ok(
        {
            "view": view,
            "scheme": scheme,
            "dimensions_before": before,
            "dimensions_after": before + 2,
            "added": 2,
        }
    )
create_detail_view async
create_detail_view(view: str, center: list[float], radius: float, position: list[float], scale: str = '2:1', label: str | None = None) -> AdapterResult[dict[str, Any]]

Mock detail view: a new view named Detail View X (s:s).

Source code in src/solidworks_mcp/adapters/mock_drawing_pack.py
async def create_detail_view(
    self,
    view: str,
    center: list[float],
    radius: float,
    position: list[float],
    scale: str = "2:1",
    label: str | None = None,
) -> AdapterResult[dict[str, Any]]:
    """Mock detail view: a new view named ``Detail View X (s:s)``."""
    top, bottom = parse_scale(scale)
    refused = self._pack_guard("create_detail_view") or self._pack_unknown(view)
    if refused:
        return refused
    outline = self._pack_outline(view)
    if not inside(center, outline):
        return _error(
            f"The detail centre {list(center)} mm isn't inside view "
            f"'{view}' (its outline is {list(outline)} mm)."
        )
    off = self._pack_off_sheet(position)
    if off:
        return off
    before = len(self._drawing_views)
    letter = label or next_label(self._drawing_views)
    ratio = f"{top:g}:{bottom:g}"
    name = f"Detail View {letter} ({ratio})"
    box = self._pack_add_view(name, position)
    return _ok(
        {
            "label": letter,
            "parent": view,
            "scale": ratio,
            "name": name,
            "outline_mm": box,
            "views_before": before,
            "views_after": len(self._drawing_views),
        }
    )
create_section_view async
create_section_view(view: str, line_start: list[float], line_end: list[float], position: list[float], label: str | None = None) -> AdapterResult[dict[str, Any]]

Mock section view: a new view named Section View X-X.

Source code in src/solidworks_mcp/adapters/mock_drawing_pack.py
async def create_section_view(
    self,
    view: str,
    line_start: list[float],
    line_end: list[float],
    position: list[float],
    label: str | None = None,
) -> AdapterResult[dict[str, Any]]:
    """Mock section view: a new view named ``Section View X-X``."""
    refused = self._pack_guard("create_section_view") or self._pack_unknown(view)
    if refused:
        return refused
    outline = self._pack_outline(view)
    if not segment_crosses_box(line_start, line_end, outline):
        return _error(
            f"The section line {list(line_start)} - {list(line_end)} mm "
            f"doesn't cross view '{view}' (its outline is {list(outline)} mm)."
        )
    off = self._pack_off_sheet(position)
    if off:
        return off
    before = len(self._drawing_views)
    letter = label or next_label(self._drawing_views)
    name = f"Section View {letter}-{letter}"
    box = self._pack_add_view(name, position)
    return _ok(
        {
            "label": letter,
            "parent": view,
            "name": name,
            "outline_mm": box,
            "views_before": before,
            "views_after": len(self._drawing_views),
        }
    )
drawing_report async
drawing_report() -> AdapterResult[dict[str, Any]]

Mock report from the drawing's state.

Source code in src/solidworks_mcp/adapters/mock_drawing_pack.py
async def drawing_report(self) -> AdapterResult[dict[str, Any]]:
    """Mock report from the drawing's state."""
    refused = self._pack_guard("drawing_report")
    if refused:
        return refused
    counts = self.__dict__.get("_view_dimensions", {})
    title = self._pack_state()["title_block"]
    return _ok(
        {
            "sheet_mm": self._pack_sheet(),
            "views": [
                {
                    "name": name,
                    "type": "detail" if name.startswith("Detail") else "standard",
                    "pictorial": "iso" in name.lower(),
                    "outline_mm": self._pack_outline(name),
                    "dimensions": counts.get(name, 0),
                }
                for name in self._drawing_views
            ],
            "title_block": {
                key: title.get(key) for key in ("title", "drawn_by", "revision")
            },
            "model_type": "part",
            "bom": False,
            "dangling": 0,
        }
    )
update_sheet_format async
update_sheet_format(sheet_format: str, paper_size: str | None = None) -> AdapterResult[dict[str, Any]]

Mock format change: a0 to a4 ISO or ANSI names exist.

Source code in src/solidworks_mcp/adapters/mock_drawing_pack.py
async def update_sheet_format(
    self, sheet_format: str, paper_size: str | None = None
) -> AdapterResult[dict[str, Any]]:
    """Mock format change: ``a0`` to ``a4`` ISO or ANSI names exist."""
    refused = self._pack_guard("update_sheet_format")
    if refused:
        return refused
    try:
        size = paper_for(sheet_format, paper_size)
    except ValueError as exc:
        return _error(str(exc))
    name = (
        sheet_format
        if sheet_format.endswith(".slddrt")
        else (f"{sheet_format}.slddrt")
    )
    if not re.fullmatch(r"a[0-4] - (iso|ansi)\.slddrt", name.lower()):
        return _error(
            f"No sheet format '{name}' in SolidWorks' sheet format folders "
            r"or under C:\ProgramData\SOLIDWORKS; give a .slddrt path."
        )
    state = self._pack_state()
    state.update(paper=size, format=name)
    return _ok(
        {
            "sheet_format": name,
            "paper_size": size,
            "sheet_mm": self._pack_sheet(),
            "views": list(self._drawing_views),
        }
    )
update_title_block async
update_title_block(fields: dict[str, str]) -> AdapterResult[dict[str, Any]]

Mock title block: the fields are kept for drawing_report.

Source code in src/solidworks_mcp/adapters/mock_drawing_pack.py
async def update_title_block(
    self, fields: dict[str, str]
) -> AdapterResult[dict[str, Any]]:
    """Mock title block: the fields are kept for ``drawing_report``."""
    refused = self._pack_guard("update_title_block")
    if refused:
        return refused
    self._pack_state()["title_block"].update(fields)
    return _ok(
        {
            "fields": {
                field: {
                    "property": TITLE_BLOCK_FIELDS[field][1],
                    "on": TITLE_BLOCK_FIELDS[field][0],
                    "value": value,
                }
                for field, value in fields.items()
            }
        }
    )

Functions:

_error

_error(message: str) -> AdapterResult[dict[str, Any]]

An error result.

Source code in src/solidworks_mcp/adapters/mock_drawing_pack.py
def _error(message: str) -> AdapterResult[dict[str, Any]]:
    """An error result."""
    return AdapterResult(status=AdapterResultStatus.ERROR, error=message)

_ok

_ok(data: dict[str, Any]) -> AdapterResult[dict[str, Any]]

A success result.

Source code in src/solidworks_mcp/adapters/mock_drawing_pack.py
def _ok(data: dict[str, Any]) -> AdapterResult[dict[str, Any]]:
    """A success result."""
    return AdapterResult(status=AdapterResultStatus.SUCCESS, data=data)

inside

inside(point: list[float], box: Box) -> bool

Whether point lies in box (edges included).

Source code in src/solidworks_mcp/adapters/solidworks/drawing_pack.py
def inside(point: list[float], box: Box) -> bool:
    """Whether ``point`` lies in ``box`` (edges included)."""
    return box[0] <= point[0] <= box[2] and box[1] <= point[1] <= box[3]

next_label

next_label(view_names: list[str]) -> str

The first letter no section or detail view uses yet ("A" when none).

Source code in src/solidworks_mcp/adapters/solidworks/drawing_pack.py
def next_label(view_names: list[str]) -> str:
    """The first letter no section or detail view uses yet ("A" when none)."""
    used = {
        m.group(1)
        for name in view_names
        if (m := re.search(r"(?:Section|Detail) View ([A-Z])\b", name))
    }
    return next(c for c in "ABCDEFGHJKLMNPRSTUVWXYZ" if c not in used)

paper_for

paper_for(sheet_format: str, paper_size: str | None) -> str

The paper size: given, else the format name's (a2 - iso -> a2).

Raises:

Type Description
ValueError

When neither names one of :data:PAPER_SIZES.

Source code in src/solidworks_mcp/adapters/solidworks/drawing_pack.py
def paper_for(sheet_format: str, paper_size: str | None) -> str:
    """The paper size: given, else the format name's (``a2 - iso`` -> ``a2``).

    Raises:
        ValueError: When neither names one of :data:`PAPER_SIZES`.
    """
    if paper_size:
        size = paper_size.strip().lower()
    else:
        stem = ntpath.basename(sheet_format).lower()  # a Windows path, on any OS
        size = next((s for s in PAPER_SIZES if stem.startswith(s)), "")
    if size not in PAPER_SIZES:
        raise InputRefused(
            f"paper_size must be one of {', '.join(PAPER_SIZES)}; it can't be "
            f"read from the format name '{sheet_format}'."
        )
    return size

parse_scale

parse_scale(scale: str) -> tuple[float, float]

"3:1" -> (3.0, 1.0).

Raises:

Type Description
ValueError

For anything but two positive numbers around a colon.

Source code in src/solidworks_mcp/adapters/solidworks/drawing_pack.py
def parse_scale(scale: str) -> tuple[float, float]:
    """``"3:1"`` -> ``(3.0, 1.0)``.

    Raises:
        ValueError: For anything but two positive numbers around a colon.
    """
    match = re.fullmatch(r"\s*(\d+(?:\.\d+)?)\s*:\s*(\d+(?:\.\d+)?)\s*", scale)
    if not match or float(match.group(1)) <= 0 or float(match.group(2)) <= 0:
        raise ValueError(f"scale '{scale}' must look like '2:1' or '1:2'.")
    return float(match.group(1)), float(match.group(2))

segment_crosses_box

segment_crosses_box(start: list[float], end: list[float], box: Box) -> bool

Whether the segment from start to end touches the box (Liang-Barsky).

Source code in src/solidworks_mcp/adapters/solidworks/drawing_pack.py
def segment_crosses_box(start: list[float], end: list[float], box: Box) -> bool:
    """Whether the segment from ``start`` to ``end`` touches the box (Liang-Barsky)."""
    (x0, y0), (x1, y1) = start[:2], end[:2]
    dx, dy = x1 - x0, y1 - y0
    low, high = 0.0, 1.0
    for p, q in (
        (-dx, x0 - box[0]),
        (dx, box[2] - x0),
        (-dy, y0 - box[1]),
        (dy, box[3] - y0),
    ):
        if p == 0:
            if q < 0:
                return False
            continue
        t = q / p
        if p < 0:
            low = max(low, t)
        else:
            high = min(high, t)
        if low > high:
            return False
    return True