Skip to content

solidworks_mcp.adapters.solidworks.drawing_pack

solidworks_mcp.adapters.solidworks.drawing_pack

The drawing pack (queue item 12): section and detail views, title block and sheet format edits, drawing dimensions, and the facts check_drawing reads.

Every position is in sheet millimetres, as in the other drawing tools. COM calls (argument lists from the installed type library):

  • IDrawingDoc.ActivateView(Name); ISketchManager.CreateLine and CreateCircleByRadius in the active view's sketch;
  • IDrawingDoc.CreateSectionViewAt5(X, Y, Z, SectionLabel, Options, ExcludedComponents, SectionDepth) and CreateDetailViewAt4(X, Y, Z, Style, Scale1, Scale2, LabelIn, Showtype, FullOutline, JaggedOutline, NoOutline, ShapeIntensity) on the selected line or circle;
  • IModelDoc2.AddHorizontalDimension2 / AddVerticalDimension2 / AddDimension2 / AddRadialDimension2 / AddDiameterDimension2 after picking edges by sheet point (SelectByID2 with the null callout);
  • IDrawingDoc.AutoDimension(Entities, HScheme, HPlacement, VScheme, VPlacement) on the active view;
  • IDrawingDoc.SetupSheet5 for a new format and paper size (the call generate_drawing_package already makes);
  • IView.GetSketch().ModelToSketchTransform (sheet to view sketch space);
  • IView.GetOutline, GetDisplayDimensionCount, IAnnotation.IsDangling for the drawing report.

Enum values were read from swconst.tlb (SolidWorks 2026).

Attributes

ANNOTATION_TABLE module-attribute

ANNOTATION_TABLE = 14

AUTODIM_ENTITIES_ALL module-attribute

AUTODIM_ENTITIES_ALL = 1

AUTODIM_SCHEMES module-attribute

AUTODIM_SCHEMES = {'baseline': 1, 'chain': 3}

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)}

TABLE_BOM module-attribute

TABLE_BOM = 2

TEMPLATE_CUSTOM module-attribute

TEMPLATE_CUSTOM = 12

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')}

VIEW_TYPES module-attribute

VIEW_TYPES = {1: 'sheet', 2: 'section', 3: 'detail', 4: 'projected', 5: 'auxiliary', 6: 'standard', 7: 'named', 8: 'relative', 9: 'detached', 10: 'alternate position'}

_PLACE_TOLERANCE_MM module-attribute

_PLACE_TOLERANCE_MM = 1.0

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.

InputRefused

Bases: ValueError

The adapter checked an input against the document and refused it.

An expected answer, not a fault: a section line that misses its view, a point with nothing to dimension. It is logged as one line, without a traceback, and the tools classify it as invalid_input.

SolidWorksDrawingPackMixin

Section and detail views, title block and format, dimensions, 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]]

One dimension on the entities picked at sheet points.

Parameters:

Name Type Description Default
dimension_type str

horizontal, vertical, aligned, radial, diameter or angular.

required
entity1_point list[float]

[x, y] sheet mm on the first edge or vertex.

required
position list[float]

[x, y] sheet mm for the dimension's text.

required
entity2_point list[float] | None

The second entity, for linear and angular types.

None

Returns:

Type Description
AdapterResult[dict[str, Any]]

The dimension's name and value (mm, degrees for angular).

Source code in src/solidworks_mcp/adapters/solidworks/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]]:
    """One dimension on the entities picked at sheet points.

    Args:
        dimension_type: horizontal, vertical, aligned, radial, diameter
            or angular.
        entity1_point: ``[x, y]`` sheet mm on the first edge or vertex.
        position: ``[x, y]`` sheet mm for the dimension's text.
        entity2_point: The second entity, for linear and angular types.

    Returns:
        The dimension's name and value (mm, degrees for angular).
    """
    adapter: Any = self

    def build() -> dict[str, Any]:
        model = adapter.currentModel
        self._pack_on_sheet(self._pack_drawing(), position)
        adapter._attempt(lambda: model.ClearSelection2(True), None)
        for index, point in enumerate([entity1_point, entity2_point]):
            if point is None:
                continue
            if not self._pack_pick(point, append=index > 0):
                raise InputRefused(
                    f"Nothing to dimension at {list(point)} mm on the sheet; "
                    "give a point on a view's edge or vertex."
                )
        x, y = position[0] / 1000.0, position[1] / 1000.0
        create = {
            "horizontal": model.AddHorizontalDimension2,
            "vertical": model.AddVerticalDimension2,
            "aligned": model.AddDimension2,
            "angular": model.AddDimension2,
            "radial": model.AddRadialDimension2,
            "diameter": model.AddDiameterDimension2,
        }[dimension_type]
        display = create(x, y, 0.0)
        adapter._attempt(lambda: model.ClearSelection2(True), None)
        if display is None:
            raise RuntimeError(
                f"SolidWorks added no {dimension_type} dimension to the picked "
                "entities; check they suit that type."
            )
        disp = sw_type_info.flagged(display, "IDisplayDimension")
        dimension = sw_type_info.flagged(disp.GetDimension2(0), "IDimension")
        raw = float(dimension.SystemValue)
        angular = dimension_type == "angular"
        value = raw * 180.0 / math.pi if angular else raw * 1000.0
        return {
            "name": adapter._attempt(lambda: dimension.FullName, default=None),
            "dimension_type": dimension_type,
            "value": round(value, 4),
            "units": "deg" if angular else "mm",
        }

    return self._pack_run("add_dimension", build)
auto_dimension_view async
auto_dimension_view(view: str, scheme: str = 'baseline') -> AdapterResult[dict[str, Any]]

SolidWorks' auto-dimension on one view, counted before and after.

Parameters:

Name Type Description Default
view str

The view's name.

required
scheme str

baseline or chain, both directions.

'baseline'

Returns:

Type Description
AdapterResult[dict[str, Any]]

The view, the scheme, and the dimensions before, after and added.

Source code in src/solidworks_mcp/adapters/solidworks/drawing_pack.py
async def auto_dimension_view(
    self, view: str, scheme: str = "baseline"
) -> AdapterResult[dict[str, Any]]:
    """SolidWorks' auto-dimension on one view, counted before and after.

    Args:
        view: The view's name.
        scheme: ``baseline`` or ``chain``, both directions.

    Returns:
        The view, the scheme, and the dimensions before, after and added.
    """
    adapter: Any = self

    def build() -> dict[str, Any]:
        drawing = self._pack_drawing()
        target = self._pack_view(drawing, view)
        before = adapter._view_dimension_count(target)
        drawing.ActivateView(view)
        model = adapter.currentModel
        adapter._attempt(lambda: model.ClearSelection2(True), None)
        adapter._attempt(
            lambda: model.Extension.SelectByID2(
                view, "DRAWINGVIEW", 0.0, 0.0, 0.0, False, 0, _null_callout(), 0
            ),
            None,
        )
        code = AUTODIM_SCHEMES[scheme]
        status = drawing.AutoDimension(
            AUTODIM_ENTITIES_ALL, code, AUTODIM_ABOVE, code, AUTODIM_RIGHT
        )
        adapter._attempt(lambda: adapter.currentModel.EditRebuild3(), None)
        after = adapter._view_dimension_count(self._pack_view(drawing, view))
        if after <= before:
            raise RuntimeError(
                f"AutoDimension added no dimension to '{view}' (status {status})."
            )
        return {
            "view": view,
            "scheme": scheme,
            "dimensions_before": before,
            "dimensions_after": after,
            "added": after - before,
        }

    return self._pack_run("auto_dimension_view", build)
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]]

A detail view of the circle at center in view.

Parameters:

Name Type Description Default
view str

The parent view's name.

required
center list[float]

[x, y] sheet mm, inside the view.

required
radius float

The circle's radius on the sheet, mm.

required
position list[float]

[x, y] sheet mm for the new view's centre.

required
scale str

The detail's scale, e.g. "3:1".

'2:1'
label str | None

The detail's letter; the next free one when None.

None

Returns:

Type Description
AdapterResult[dict[str, Any]]

The new view's name, label, scale and outline.

Source code in src/solidworks_mcp/adapters/solidworks/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]]:
    """A detail view of the circle at ``center`` in ``view``.

    Args:
        view: The parent view's name.
        center: ``[x, y]`` sheet mm, inside the view.
        radius: The circle's radius on the sheet, mm.
        position: ``[x, y]`` sheet mm for the new view's centre.
        scale: The detail's scale, e.g. ``"3:1"``.
        label: The detail's letter; the next free one when ``None``.

    Returns:
        The new view's name, label, scale and outline.
    """
    adapter: Any = self
    top, bottom = parse_scale(scale)

    def build() -> dict[str, Any]:
        drawing = self._pack_drawing()
        parent = self._pack_view(drawing, view)
        outline = self._pack_outline(parent)
        if outline is not None and not inside(center, outline):
            raise InputRefused(
                f"The detail centre {list(center)} mm isn't inside view "
                f"'{view}' (its outline is {list(outline)} mm)."
            )
        self._pack_on_sheet(drawing, position)
        before = _view_names(adapter, drawing)
        letter = label or next_label(before)
        drawing.ActivateView(view)
        cx, cy = self._pack_to_view(parent, center)
        r = self._pack_radius(parent, center, radius)
        circle = adapter.currentModel.SketchManager.CreateCircleByRadius(
            cx, cy, 0.0, r
        )
        if circle is None:
            raise RuntimeError(f"The detail circle couldn't be drawn in '{view}'.")
        adapter._attempt(lambda: adapter.currentModel.ClearSelection2(True), None)
        adapter._select_sketch_entity(circle, append=False)
        created = drawing.CreateDetailViewAt4(
            position[0] / 1000.0,
            position[1] / 1000.0,
            0.0,
            DETAIL_STANDARD,
            top,
            bottom,
            letter,
            DETAIL_SHOW_CIRCLE,
            False,
            False,
            False,
            0,
        )
        if created is None:
            self._pack_discard(circle)
            raise RuntimeError(f"CreateDetailViewAt4 made no detail of '{view}'.")
        return {
            "label": letter,
            "parent": view,
            "scale": f"{top:g}:{bottom:g}",
            **self._pack_new_view(created, before),
        }

    return self._pack_run("create_detail_view", build)
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]]

A section view cut along a line across view.

Parameters:

Name Type Description Default
view str

The parent view's name.

required
line_start list[float]

[x, y] sheet mm where the section line starts.

required
line_end list[float]

[x, y] sheet mm where it ends.

required
position list[float]

[x, y] sheet mm for the new view's centre.

required
label str | None

The section's letter; the next free one when None.

None

Returns:

Type Description
AdapterResult[dict[str, Any]]

The new view's name, label and outline.

Source code in src/solidworks_mcp/adapters/solidworks/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]]:
    """A section view cut along a line across ``view``.

    Args:
        view: The parent view's name.
        line_start: ``[x, y]`` sheet mm where the section line starts.
        line_end: ``[x, y]`` sheet mm where it ends.
        position: ``[x, y]`` sheet mm for the new view's centre.
        label: The section's letter; the next free one when ``None``.

    Returns:
        The new view's name, label and outline.
    """
    adapter: Any = self

    def build() -> dict[str, Any]:
        drawing = self._pack_drawing()
        parent = self._pack_view(drawing, view)
        outline = self._pack_outline(parent)
        if outline is not None and not segment_crosses_box(
            line_start, line_end, outline
        ):
            raise InputRefused(
                f"The section line {list(line_start)} - {list(line_end)} mm "
                f"doesn't cross view '{view}' (its outline is {list(outline)} mm)."
            )
        self._pack_on_sheet(drawing, position)
        before = _view_names(adapter, drawing)
        letter = label or next_label(before)
        drawing.ActivateView(view)
        start = self._pack_to_view(parent, line_start)
        end = self._pack_to_view(parent, line_end)
        line = adapter.currentModel.SketchManager.CreateLine(*start, 0.0, *end, 0.0)
        if line is None:
            raise RuntimeError(f"The section line couldn't be drawn in '{view}'.")
        adapter._attempt(lambda: adapter.currentModel.ClearSelection2(True), None)
        adapter._select_sketch_entity(line, append=False)
        created = drawing.CreateSectionViewAt5(
            position[0] / 1000.0, position[1] / 1000.0, 0.0, letter, 0, None, 0.0
        )
        if created is None:
            self._pack_discard(line)
            raise RuntimeError(
                f"CreateSectionViewAt5 made no section view of '{view}'."
            )
        at_position = self._pack_place(created, position)
        return {
            "label": letter,
            "parent": view,
            "at_position": at_position,
            **self._pack_new_view(created, before),
        }

    return self._pack_run("create_section_view", build)
drawing_report async
drawing_report() -> AdapterResult[dict[str, Any]]

What check_drawing judges: views, sheet, title block, BOM, dangling.

Returns:

Type Description
AdapterResult[dict[str, Any]]

sheet_mm; views (name, type, outline, dimensions);

AdapterResult[dict[str, Any]]

title_block (title, drawn_by, revision); model_type;

AdapterResult[dict[str, Any]]

bom; dangling.

Source code in src/solidworks_mcp/adapters/solidworks/drawing_pack.py
async def drawing_report(self) -> AdapterResult[dict[str, Any]]:
    """What ``check_drawing`` judges: views, sheet, title block, BOM, dangling.

    Returns:
        ``sheet_mm``; ``views`` (name, type, outline, dimensions);
        ``title_block`` (title, drawn_by, revision); ``model_type``;
        ``bom``; ``dangling``.
    """
    adapter: Any = self

    def build() -> dict[str, Any]:
        drawing = self._pack_drawing()
        views = []
        for name in _view_names(adapter, drawing):
            view = _resolve_drawing_view(adapter, drawing, name)
            kind = adapter._attempt(lambda v=view: v.Type, default=None)
            views.append(
                {
                    "name": name,
                    "type": VIEW_TYPES.get(kind, "unknown"),
                    "pictorial": adapter._pictorial(view),
                    "outline_mm": self._pack_outline(view),
                    "dimensions": adapter._view_dimension_count(view),
                }
            )
        bom, dangling = self._pack_annotations(drawing)
        model = adapter._attempt(lambda: self._pack_model(drawing), default=None)
        model_type = adapter._attempt(lambda: model.GetType(), default=None)
        return {
            "sheet_mm": self._pack_sheet_mm(drawing),
            "views": views,
            "title_block": self._pack_title_values(model),
            "model_type": {1: "part", 2: "assembly"}.get(model_type),
            "bom": bom,
            "dangling": dangling,
        }

    return self._pack_run("drawing_report", build)
update_sheet_format async
update_sheet_format(sheet_format: str, paper_size: str | None = None) -> AdapterResult[dict[str, Any]]

Change the active sheet's format and paper size, keeping its views.

Parameters:

Name Type Description Default
sheet_format str

A format name (a2 - iso) or a .slddrt path.

required
paper_size str | None

a4 to a0; read from the format name when None.

None

Returns:

Type Description
AdapterResult[dict[str, Any]]

The format's path, the paper size and the views before and after.

Source code in src/solidworks_mcp/adapters/solidworks/drawing_pack.py
async def update_sheet_format(
    self, sheet_format: str, paper_size: str | None = None
) -> AdapterResult[dict[str, Any]]:
    """Change the active sheet's format and paper size, keeping its views.

    Args:
        sheet_format: A format name (``a2 - iso``) or a ``.slddrt`` path.
        paper_size: a4 to a0; read from the format name when ``None``.

    Returns:
        The format's path, the paper size and the views before and after.
    """
    adapter: Any = self

    def build() -> dict[str, Any]:
        size = paper_for(sheet_format, paper_size)
        path = self._pack_format_path(sheet_format)
        drawing = self._pack_drawing()
        before = _view_names(adapter, drawing)
        sheet = _as_com(adapter, drawing.GetCurrentSheet(), "ISheet")
        props = as_list(adapter._attempt(lambda: sheet.GetProperties2(), None))
        scale = (props[2], props[3]) if len(props) >= 5 else (1.0, 1.0)
        first_angle = bool(props[4]) if len(props) >= 5 else False
        name = adapter._attempt(lambda: sheet.GetName(), default="Sheet1")
        code, width, height = PAPER_SIZES[size]
        if not drawing.SetupSheet5(
            name,
            code,
            TEMPLATE_CUSTOM,
            scale[0],
            scale[1],
            first_angle,
            path,
            width / 1000.0,
            height / 1000.0,
            "Default",
            True,
        ):
            raise RuntimeError(f"SetupSheet5 refused the sheet format {path}.")
        adapter._attempt(lambda: adapter.currentModel.EditRebuild3(), None)
        after = _view_names(adapter, drawing)
        if sorted(after) != sorted(before):
            raise RuntimeError(
                f"The views changed with the format: {before} became {after}."
            )
        return {
            "sheet_format": path,
            "paper_size": size,
            "sheet_mm": self._pack_sheet_mm(drawing),
            "views": after,
        }

    return self._pack_run("update_sheet_format", build)
update_title_block async
update_title_block(fields: dict[str, str]) -> AdapterResult[dict[str, Any]]

Write title-block fields to the properties the sheet format reads.

title goes to the drawn model's Description (the ISO format reads it with $PRPSHEET); the rest are the drawing's own properties. Fields not given keep their values.

Parameters:

Name Type Description Default
fields dict[str, str]

Field name (a key of :data:TITLE_BLOCK_FIELDS) -> value.

required

Returns:

Type Description
AdapterResult[dict[str, Any]]

Each field with the property it was written to.

Source code in src/solidworks_mcp/adapters/solidworks/drawing_pack.py
async def update_title_block(
    self, fields: dict[str, str]
) -> AdapterResult[dict[str, Any]]:
    """Write title-block fields to the properties the sheet format reads.

    ``title`` goes to the drawn model's Description (the ISO format reads
    it with ``$PRPSHEET``); the rest are the drawing's own properties.
    Fields not given keep their values.

    Args:
        fields: Field name (a key of :data:`TITLE_BLOCK_FIELDS`) -> value.

    Returns:
        Each field with the property it was written to.
    """
    adapter: Any = self

    def build() -> dict[str, Any]:
        drawing = self._pack_drawing()
        written: dict[str, dict[str, str]] = {}
        for field, value in fields.items():
            owner, prop = TITLE_BLOCK_FIELDS[field]
            doc = (
                adapter.currentModel
                if owner == "drawing"
                else self._pack_model(drawing)
            )
            manager = doc.Extension.CustomPropertyManager("")
            manager.Add3(prop, 30, value, 2)  # text, replace the value
            written[field] = {"property": prop, "on": owner, "value": value}
        adapter._attempt(lambda: adapter.currentModel.ForceRebuild3(False), None)
        return {"fields": written}

    return self._pack_run("update_title_block", build)

Functions:

_as_com

_as_com(adapter: Any, obj: Any, interface: str) -> Any

Wrap a raw dispatch and flag its methods for an interface.

Objects handed back inside arrays (GetViews and friends) arrive as raw PyIDispatch. Method flagging is a no-op on those, so every call against them raises until they are wrapped through dynamic.Dispatch.

Parameters:

Name Type Description Default
adapter Any

A connected PyWin32Adapter.

required
obj Any

The raw dispatch.

required
interface str

Interface name, e.g. "IView".

required

Returns:

Name Type Description
Any Any

The wrapped, flagged object, or None.

Source code in src/solidworks_mcp/adapters/solidworks/io.py
def _as_com(adapter: Any, obj: Any, interface: str) -> Any:
    """Wrap a raw dispatch and flag its methods for an interface.

    Objects handed back inside arrays (``GetViews`` and friends) arrive as raw
    ``PyIDispatch``.  Method flagging is a no-op on those, so every call
    against them raises until they are wrapped through ``dynamic.Dispatch``.

    Args:
        adapter: A connected ``PyWin32Adapter``.
        obj: The raw dispatch.
        interface: Interface name, e.g. ``"IView"``.

    Returns:
        Any: The wrapped, flagged object, or ``None``.
    """
    wrapped = adapter._attempt(lambda: _dynamic.Dispatch(obj), default=None)
    if wrapped is None:
        return None
    adapter._attempt(
        lambda: _sw_type_info.flag_methods(wrapped, interface), default=None
    )
    return wrapped

_mm

_mm(box: Any) -> Box | None

A COM outline in metres -> mm, or None when unreadable.

Source code in src/solidworks_mcp/adapters/solidworks/drawing_pack.py
def _mm(box: Any) -> Box | None:
    """A COM outline in metres -> mm, or ``None`` when unreadable."""
    values = as_list(box)
    if len(values) < 4 or not all(isinstance(v, (int, float)) for v in values[:4]):
        return None
    return cast(Box, tuple(round(float(v) * 1000.0, 3) for v in values[:4]))

_null_callout

_null_callout() -> Any

Return a VT_DISPATCH null for SelectByID2's Callout parameter.

A plain Python None marshals as VT_NULL, which SolidWorks rejects with DISP_E_TYPEMISMATCH - measured as (-2147352571, 'Type mismatch.', None, 8). See runbook item 11.

Returns:

Name Type Description
Any Any

A VARIANT(VT_DISPATCH, None), or a non-None sentinel

Any

when pywin32 is unavailable (mock/Linux runs, where no real COM call

Any

will be made anyway, but the value must still never be bare None).

Source code in src/solidworks_mcp/adapters/solidworks/features.py
def _null_callout() -> Any:
    """Return a VT_DISPATCH null for ``SelectByID2``'s ``Callout`` parameter.

    A plain Python ``None`` marshals as ``VT_NULL``, which SolidWorks rejects
    with ``DISP_E_TYPEMISMATCH`` - measured as
    ``(-2147352571, 'Type mismatch.', None, 8)``. See runbook item 11.

    Returns:
        Any: A ``VARIANT(VT_DISPATCH, None)``, or a non-``None`` sentinel
        when pywin32 is unavailable (mock/Linux runs, where no real COM call
        will be made anyway, but the value must still never be bare ``None``).
    """
    try:
        import pythoncom
        import win32com.client as _win32com
    except ImportError:
        return _NULL_CALLOUT_SENTINEL
    return _win32com.VARIANT(pythoncom.VT_DISPATCH, None)

_read_custom_property

_read_custom_property(adapter: Any, manager: Any, name: str) -> tuple[str, str]

Read one custom property's (value, resolved value).

Tries Get6 (value and resolved value) first; under late binding on SW 2025 its out-parameters raise Parameter not optional, so it falls back to Get(name), which returns the stored text only.

Parameters:

Name Type Description Default
adapter Any

The adapter, for its _attempt helper.

required
manager Any

The document's ICustomPropertyManager.

required
name str

Property name.

required

Returns:

Type Description
str

tuple[str, str]: The stored value and the resolved value; empty

str

strings when the property cannot be read.

Source code in src/solidworks_mcp/adapters/solidworks/documentation.py
def _read_custom_property(adapter: Any, manager: Any, name: str) -> tuple[str, str]:
    """Read one custom property's (value, resolved value).

    Tries ``Get6`` (value and resolved value) first; under late binding on
    SW 2025 its out-parameters raise ``Parameter not optional``, so it falls
    back to ``Get(name)``, which returns the stored text only.

    Args:
        adapter: The adapter, for its ``_attempt`` helper.
        manager: The document's ``ICustomPropertyManager``.
        name: Property name.

    Returns:
        tuple[str, str]: The stored value and the resolved value; empty
        strings when the property cannot be read.
    """
    value, resolved = _unpack_custom_property(
        adapter._attempt(lambda: manager.Get6(name, False), default=None)
    )
    if value:
        return value, resolved
    plain = adapter._attempt(lambda: manager.Get(name), default=None)
    text = str(plain) if isinstance(plain, str) else ""
    return text, text

_resolve_drawing_view

_resolve_drawing_view(adapter: Any, drawing: Any, view_name: str) -> Any

Return the IView on the active drawing whose name matches.

Walks IDrawingDoc::GetViews (a list of sheets, each shaped (sheet, view, view, ...)) the same way :func:_view_names does. The match is case-insensitive.

Parameters:

Name Type Description Default
adapter Any

A connected PyWin32Adapter.

required
drawing Any

The drawing document, flagged for IDrawingDoc.

required
view_name str

The drawing-view name to look for.

required

Returns:

Name Type Description
Any Any

The flagged IView dispatch, or None when nothing matches.

Source code in src/solidworks_mcp/adapters/solidworks/io.py
def _resolve_drawing_view(adapter: Any, drawing: Any, view_name: str) -> Any:
    """Return the ``IView`` on the active drawing whose name matches.

    Walks ``IDrawingDoc::GetViews`` (a list of sheets, each shaped
    ``(sheet, view, view, ...)``) the same way :func:`_view_names` does. The
    match is case-insensitive.

    Args:
        adapter: A connected ``PyWin32Adapter``.
        drawing: The drawing document, flagged for ``IDrawingDoc``.
        view_name: The drawing-view name to look for.

    Returns:
        Any: The flagged ``IView`` dispatch, or ``None`` when nothing matches.
    """
    target = str(view_name or "").strip().lower()
    if not target:
        return None
    sheets = adapter._attempt(lambda: drawing.GetViews(), default=None)
    if not isinstance(sheets, (list, tuple)):
        return None
    for sheet in sheets:
        views = sheet if isinstance(sheet, (list, tuple)) else [sheet]
        for index, view in enumerate(views):
            if index == 0 and isinstance(sheet, (list, tuple)):
                continue
            wrapped = _as_com(adapter, view, "IView")
            if wrapped is None:
                continue
            name = adapter._attempt(lambda w=wrapped: w.GetName2(), default=None)
            if name and str(name).lower() == target:
                return wrapped
    return None

_to_sketch

_to_sketch(adapter: Any, sketch: Any, point_m: list[float]) -> list[float]

A model point (metres) in sketch's coordinates.

Parameters:

Name Type Description Default
adapter Any

The connected adapter (its swApp gives the math utility).

required
sketch Any

An ISketch.

required
point_m list[float]

[x, y, z] in metres, model space.

required

Returns:

Type Description
list[float]

[x, y, z] in the sketch's space; z is 0 on the sketch plane.

Source code in src/solidworks_mcp/adapters/solidworks/part_features.py
def _to_sketch(adapter: Any, sketch: Any, point_m: list[float]) -> list[float]:
    """A model point (metres) in ``sketch``'s coordinates.

    Args:
        adapter: The connected adapter (its ``swApp`` gives the math utility).
        sketch: An ``ISketch``.
        point_m: ``[x, y, z]`` in metres, model space.

    Returns:
        ``[x, y, z]`` in the sketch's space; ``z`` is 0 on the sketch plane.
    """
    app = sw_type_info.flagged(adapter.swApp, "ISldWorks")
    math_utility = sw_type_info.flagged(app.GetMathUtility(), "IMathUtility")
    point = sw_type_info.flagged(
        math_utility.CreatePoint(double_array(point_m)), "IMathPoint"
    )
    moved = sw_type_info.flagged(
        point.MultiplyTransform(sketch.ModelToSketchTransform), "IMathPoint"
    )
    return [float(v) for v in as_list(moved.ArrayData)[:3]]

_view_names

_view_names(adapter: Any, drawing: Any) -> list[str]

Return the drawing's view names, excluding sheet formats.

CreateDrawViewFromModelView3 returns None for a model SolidWorks could not resolve, and Create3rdAngleViews2 returns a bare boolean, so the view list is the ground truth for whether views were really added.

Parameters:

Name Type Description Default
adapter Any

A connected PyWin32Adapter.

required
drawing Any

The drawing document, flagged for IDrawingDoc.

required

Returns:

Type Description
list[str]

list[str]: View names in sheet order.

Source code in src/solidworks_mcp/adapters/solidworks/io.py
def _view_names(adapter: Any, drawing: Any) -> list[str]:
    """Return the drawing's view names, excluding sheet formats.

    ``CreateDrawViewFromModelView3`` returns ``None`` for a model SolidWorks
    could not resolve, and ``Create3rdAngleViews2`` returns a bare boolean, so
    the view list is the ground truth for whether views were really added.

    Args:
        adapter: A connected ``PyWin32Adapter``.
        drawing: The drawing document, flagged for ``IDrawingDoc``.

    Returns:
        list[str]: View names in sheet order.
    """
    sheets = adapter._attempt(lambda: drawing.GetViews(), default=None)
    if not isinstance(sheets, (list, tuple)):
        return []

    names: list[str] = []
    for sheet in sheets:
        views = sheet if isinstance(sheet, (list, tuple)) else [sheet]
        for index, view in enumerate(views):
            # GetViews returns (sheet, view, view, ...) per sheet; entry 0 is
            # the sheet itself, not a drawing view.
            if index == 0 and isinstance(sheet, (list, tuple)):
                continue
            wrapped = _as_com(adapter, view, "IView")
            if wrapped is None:
                continue
            name = adapter._attempt(lambda w=wrapped: w.GetName2(), default=None)
            if name:
                names.append(str(name))
    return names

as_list

as_list(value: Any) -> list[Any]

Normalise a COM array/scalar/None return into a list.

Source code in src/solidworks_mcp/adapters/solidworks/com_utils.py
def as_list(value: Any) -> list[Any]:
    """Normalise a COM array/scalar/None return into a list."""
    if value is None:
        return []
    if isinstance(value, (list, tuple)):
        return list(value)
    return [value]

double_array

double_array(values: list[float]) -> Any

VARIANT(VT_ARRAY | VT_R8) for array-valued COM properties (tuple when pywin32 is absent).

Source code in src/solidworks_mcp/adapters/solidworks/com_utils.py
def double_array(values: list[float]) -> Any:
    """``VARIANT(VT_ARRAY | VT_R8)`` for array-valued COM properties (tuple when pywin32 is absent)."""
    try:
        import pythoncom
        import win32com.client as w32

        return w32.VARIANT(
            pythoncom.VT_ARRAY | pythoncom.VT_R8, [float(v) for v in values]
        )
    except ImportError:  # non-Windows
        return tuple(values)

find_sheet_format

find_sheet_format(adapter: Any, name: str = 'a3 - iso.slddrt') -> str | None

Locate a sheet format file: SolidWorks' configured folder, then ProgramData.

Source code in src/solidworks_mcp/adapters/solidworks/drawing_standard.py
def find_sheet_format(adapter: Any, name: str = "a3 - iso.slddrt") -> str | None:
    """Locate a sheet format file: SolidWorks' configured folder, then ProgramData."""
    app = getattr(adapter, "swApp", None)
    folders: list[str] = []
    if app is not None:
        raw = adapter._attempt(
            lambda: app.GetUserPreferenceStringValue(_SW_PREF_SHEET_FORMAT_FOLDER),
            default="",
        )
        folders.extend(f.strip() for f in str(raw or "").split(";") if f.strip())
    folders.extend(
        sorted(
            glob.glob(r"C:\ProgramData\SOLIDWORKS\SOLIDWORKS *\lang\*\sheetformat"),
            reverse=True,
        )
    )
    for folder in folders:
        candidate = os.path.join(folder, name)
        if os.path.isfile(candidate):
            return candidate
    return None

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