Skip to content

solidworks_mcp.adapters.solidworks.assembly

solidworks_mcp.adapters.solidworks.assembly

Assembly-depth mixin for PyWin32 SolidWorks operations (queue item 33).

Exploded views, component patterns and mirrors, replacing a component, and balloons on a drawing view. Components are named by their instance name (pin-1), found with the helpers io.py already uses. COM signatures and enum values were read from SolidWorks 2026's type library.

Attributes

BALLOON_LAYOUTS module-attribute

BALLOON_LAYOUTS = {'square': 1, 'circle': 2, 'top': 3, 'bottom': 4, 'right': 5, 'left': 6}

_BALLOON_CIRCULAR module-attribute

_BALLOON_CIRCULAR = 1

_DIRECTION_PLANES module-attribute

_DIRECTION_PLANES = {'x': 'Right Plane', 'y': 'Top Plane', 'z': 'Front Plane'}

_EXPLODE_ALONG_NORMAL module-attribute

_EXPLODE_ALONG_NORMAL = 2

_LOCAL_CIRCULAR_PATTERN module-attribute

_LOCAL_CIRCULAR_PATTERN = 109

_LOCAL_LINEAR_PATTERN module-attribute

_LOCAL_LINEAR_PATTERN = 108

_MIRRORED_X_MIRRORED_Y module-attribute

_MIRRORED_X_MIRRORED_Y = 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.

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.

SolidWorksAssemblyMixin

Exploded views, component patterns, mirrors, replace and balloons.

Methods:
add_balloons async
add_balloons(view_name: str, layout: str = 'square') -> AdapterResult[dict[str, Any]]

Number a drawing view's parts with balloons, one per part.

Selects the view and calls IDrawingDoc.AutoBalloon5 with options from CreateAutoBalloonOptions: the layout, circular balloons, one per part (IgnoreMultiple).

Returns:

Type Description
AdapterResult[dict[str, Any]]

AdapterResult[dict[str, Any]]: The view, layout,

AdapterResult[dict[str, Any]]

balloon count and their items (the numbers shown).

Source code in src/solidworks_mcp/adapters/solidworks/assembly.py
async def add_balloons(
    self, view_name: str, layout: str = "square"
) -> AdapterResult[dict[str, Any]]:
    """Number a drawing view's parts with balloons, one per part.

    Selects the view and calls ``IDrawingDoc.AutoBalloon5`` with
    options from ``CreateAutoBalloonOptions``: the ``layout``,
    circular balloons, one per part (``IgnoreMultiple``).

    Returns:
        AdapterResult[dict[str, Any]]: The ``view``, ``layout``,
        balloon ``count`` and their ``items`` (the numbers shown).
    """
    adapter = self._adapter(self)
    if _doc_type(adapter) != 3:
        return AdapterResult(
            status=AdapterResultStatus.ERROR,
            error="add_balloons requires a drawing document",
        )

    def run() -> dict[str, Any]:
        drawing = _sw_type_info.flagged(adapter.currentModel, "IDrawingDoc")
        if _resolve_drawing_view(adapter, drawing, view_name) is None:
            raise Exception(
                f"No view named {view_name!r}. Views: "
                f"{', '.join(_view_names(adapter, drawing)) or 'none'}"
            )
        adapter.currentModel.ClearSelection2(True)
        _select_named(adapter, view_name, "DRAWINGVIEW", 0)
        options = drawing.CreateAutoBalloonOptions()
        options.Layout = BALLOON_LAYOUTS[layout]
        options.IgnoreMultiple = True
        options.Style = _BALLOON_CIRCULAR
        notes = as_list(drawing.AutoBalloon5(options))
        adapter.currentModel.ClearSelection2(True)
        if not notes:
            raise Exception(f"SolidWorks added no balloons to {view_name}")
        items = [
            str(_sw_type_info.flagged(note, "INote").GetText()) for note in notes
        ]
        return {
            "view": view_name,
            "layout": layout,
            "count": len(notes),
            "items": items,
        }

    return cast(
        AdapterResult[dict[str, Any]],
        adapter._handle_com_operation("add_balloons", run),
    )
create_exploded_view async
create_exploded_view(steps: list[dict[str, Any]] | None = None) -> AdapterResult[dict[str, Any]]

Explode the active assembly, automatically or step by step, and show it.

With no steps, IAssemblyDoc.AutoExplode. Each step moves its components distance mm along x, y or z (reverse for the other way): the components are selected under mark 1 and the default plane normal to the direction under mark 2, then IConfiguration.AddExplodeStep2.

Parameters:

Name Type Description Default
steps list[dict[str, Any]] | None

components, direction, distance, reverse.

None

Returns:

Type Description
AdapterResult[dict[str, Any]]

AdapterResult[dict[str, Any]]: The exploded view's view,

AdapterResult[dict[str, Any]]

steps added, and the bounding box size_before_mm and

AdapterResult[dict[str, Any]]

size_after_mm.

Source code in src/solidworks_mcp/adapters/solidworks/assembly.py
async def create_exploded_view(
    self, steps: list[dict[str, Any]] | None = None
) -> AdapterResult[dict[str, Any]]:
    """Explode the active assembly, automatically or step by step, and show it.

    With no ``steps``, ``IAssemblyDoc.AutoExplode``. Each step moves its
    ``components`` ``distance`` mm along ``x``, ``y`` or ``z``
    (``reverse`` for the other way): the components are selected under
    mark 1 and the default plane normal to the direction under mark 2,
    then ``IConfiguration.AddExplodeStep2``.

    Args:
        steps: ``components``, ``direction``, ``distance``, ``reverse``.

    Returns:
        AdapterResult[dict[str, Any]]: The exploded view's ``view``,
        ``steps`` added, and the bounding box ``size_before_mm`` and
        ``size_after_mm``.
    """
    adapter = self._adapter(self)
    if wrong := _need_assembly(adapter, "create_exploded_view"):
        return wrong

    def run() -> dict[str, Any]:
        model = adapter.currentModel
        assembly = _assembly(adapter)
        before = _box_size(adapter, assembly)
        if not steps:
            if not assembly.AutoExplode():
                raise Exception("SolidWorks didn't explode the assembly")
        else:
            names = sorted({n for step in steps for n in step["components"]})
            found = _find_components(adapter, assembly, names)
            config = _sw_type_info.flagged(
                model.GetActiveConfiguration(), "IConfiguration"
            )
            if not _exploded_views(adapter, assembly):
                assembly.CreateExplodedView()
            for number, step in enumerate(steps, start=1):
                model.ClearSelection2(True)
                _select_components(
                    adapter,
                    [found[n] for n in step["components"]],
                    _MARK_COMPONENTS,
                )
                _select_named(
                    adapter,
                    _DIRECTION_PLANES[step["direction"]],
                    "PLANE",
                    _MARK_DIRECTION,
                )
                made = config.AddExplodeStep2(
                    step["distance"] / 1000.0,
                    _EXPLODE_ALONG_NORMAL,
                    bool(step.get("reverse", False)),
                    0.0,
                    0,
                    False,
                    False,
                    False,
                    _byref_int(),
                )
                model.ClearSelection2(True)
                if made is None:
                    raise Exception(f"SolidWorks refused explode step {number}")
        views = _exploded_views(adapter, assembly)
        view = views[-1] if views else ""
        assembly.ShowExploded2(True, view)
        return {
            "view": view,
            "steps": len(steps or []),
            "automatic": not steps,
            "size_before_mm": before,
            "size_after_mm": _box_size(adapter, assembly),
        }

    return cast(
        AdapterResult[dict[str, Any]],
        adapter._handle_com_operation("create_exploded_view", run),
    )
mirror_components async
mirror_components(components: list[str], plane: str) -> AdapterResult[dict[str, Any]]

Mirror components about a plane, as instances of the same parts.

IAssemblyDoc.MirrorComponents3 with the components as ComponentsToInstance and nothing mirrored into new files.

Returns:

Type Description
AdapterResult[dict[str, Any]]

AdapterResult[dict[str, Any]]: The plane and the added

AdapterResult[dict[str, Any]]

instances' names.

Source code in src/solidworks_mcp/adapters/solidworks/assembly.py
async def mirror_components(
    self, components: list[str], plane: str
) -> AdapterResult[dict[str, Any]]:
    """Mirror components about a plane, as instances of the same parts.

    ``IAssemblyDoc.MirrorComponents3`` with the components as
    ``ComponentsToInstance`` and nothing mirrored into new files.

    Returns:
        AdapterResult[dict[str, Any]]: The ``plane`` and the ``added``
        instances' names.
    """
    adapter = self._adapter(self)
    if wrong := _need_assembly(adapter, "mirror_components"):
        return wrong

    def run() -> dict[str, Any]:
        model = adapter.currentModel
        assembly = _assembly(adapter)
        found = _find_components(adapter, assembly, components)
        before = _component_names(adapter, assembly)
        model.ClearSelection2(True)
        _select_named(adapter, plane, "PLANE", 0)
        plane_object = _selected(adapter)
        model.ClearSelection2(True)
        assembly.MirrorComponents3(
            plane_object,
            dispatch_array([found[name] for name in components]),
            long_array([_MIRRORED_X_MIRRORED_Y] * len(components)),
            False,
            dispatch_array([]),
            False,
            dispatch_array([]),
            0,
            "",
            "",
            0,
            False,
            False,
            False,
        )
        added = [n for n in _component_names(adapter, assembly) if n not in before]
        if len(added) != len(components):
            raise Exception(
                f"Mirroring about {plane} added {len(added)} components, "
                f"not {len(components)}"
            )
        return {"plane": plane, "added": added}

    return cast(
        AdapterResult[dict[str, Any]],
        adapter._handle_com_operation("mirror_components", run),
    )
pattern_components async
pattern_components(components: list[str], axis: str, count: int, kind: str = 'linear', spacing: float | None = None, angle: float | None = None) -> AdapterResult[dict[str, Any]]

Repeat components along or around a reference axis.

A component pattern feature from a definition (IFeatureManager.CreateDefinition, local linear or circular): the seeds, the axis, count (seeds included) and the spacing (mm) or the angle (degrees; 360 spaces them equally).

Returns:

Type Description
AdapterResult[dict[str, Any]]

AdapterResult[dict[str, Any]]: The feature, the component

AdapterResult[dict[str, Any]]

counts before and after, and the added instances.

Source code in src/solidworks_mcp/adapters/solidworks/assembly.py
async def pattern_components(
    self,
    components: list[str],
    axis: str,
    count: int,
    kind: str = "linear",
    spacing: float | None = None,
    angle: float | None = None,
) -> AdapterResult[dict[str, Any]]:
    """Repeat components along or around a reference axis.

    A component pattern feature from a definition
    (``IFeatureManager.CreateDefinition``, local linear or circular):
    the seeds, the axis, ``count`` (seeds included) and the spacing (mm)
    or the angle (degrees; 360 spaces them equally).

    Returns:
        AdapterResult[dict[str, Any]]: The ``feature``, the component
        counts before and after, and the ``added`` instances.
    """
    adapter = self._adapter(self)
    if wrong := _need_assembly(adapter, "pattern_components"):
        return wrong

    def run() -> dict[str, Any]:
        model = adapter.currentModel
        assembly = _assembly(adapter)
        found = _find_components(adapter, assembly, components)
        before = _component_names(adapter, assembly)
        # The definition takes its seeds and axis from the selection
        # (seeds under mark 1, the axis under mark 2): set as properties
        # instead, SolidWorks 2026 reads the axis as unset and refuses.
        model.ClearSelection2(True)
        _select_components(
            adapter, [found[name] for name in components], _MARK_COMPONENTS
        )
        _select_named(adapter, axis, "AXIS", _MARK_DIRECTION)
        manager = _sw_type_info.flagged(model.FeatureManager, "IFeatureManager")
        if kind == "circular":
            data = _sw_type_info.flagged(
                manager.CreateDefinition(_LOCAL_CIRCULAR_PATTERN),
                "ILocalCircularPatternFeatureData",
            )
            data.TotalInstances = count
            data.EqualSpacing = math.isclose(float(angle or 360.0), 360.0)
            data.Spacing = math.radians(float(angle or 360.0))
        else:
            data = _sw_type_info.flagged(
                manager.CreateDefinition(_LOCAL_LINEAR_PATTERN),
                "ILocalLinearPatternFeatureData",
            )
            data.D1TotalInstances = count
            data.D1Spacing = float(spacing or 0.0) / 1000.0
        feature = manager.CreateFeature(data)
        model.ClearSelection2(True)
        if feature is None:
            raise Exception("SolidWorks refused the component pattern")
        after = _component_names(adapter, assembly)
        added = [name for name in after if name not in before]
        expected = (count - 1) * len(components)
        if len(added) != expected:
            raise Exception(
                f"The component pattern added {len(added)} components, "
                f"not {expected}"
            )
        return {
            "feature": str(feature.Name),
            "components_before": len(before),
            "components_after": len(after),
            "added": added,
        }

    return cast(
        AdapterResult[dict[str, Any]],
        adapter._handle_com_operation("pattern_components", run),
    )
replace_component async
replace_component(component: str, file_path: str, all_instances: bool = False) -> AdapterResult[dict[str, Any]]

Swap a component for another part or assembly file.

Selects the component and calls IAssemblyDoc.ReplaceComponents2 (the file's active configuration, mates re-attached). The file must exist; names and files are read back afterwards.

Returns:

Type Description
AdapterResult[dict[str, Any]]

AdapterResult[dict[str, Any]]: component, file_path, the

AdapterResult[dict[str, Any]]

replaced instances with their files after, and the component

AdapterResult[dict[str, Any]]

names before and after.

Source code in src/solidworks_mcp/adapters/solidworks/assembly.py
async def replace_component(
    self, component: str, file_path: str, all_instances: bool = False
) -> AdapterResult[dict[str, Any]]:
    """Swap a component for another part or assembly file.

    Selects the component and calls ``IAssemblyDoc.ReplaceComponents2``
    (the file's active configuration, mates re-attached). The file must
    exist; names and files are read back afterwards.

    Returns:
        AdapterResult[dict[str, Any]]: ``component``, ``file_path``, the
        ``replaced`` instances with their files after, and the component
        names before and after.
    """
    adapter = self._adapter(self)
    if wrong := _need_assembly(adapter, "replace_component"):
        return wrong
    if not os.path.isfile(file_path):
        return AdapterResult(
            status=AdapterResultStatus.ERROR,
            error=f"No file at {file_path} to replace {component} with",
        )

    def run() -> dict[str, Any]:
        model = adapter.currentModel
        assembly = _assembly(adapter)
        target = _find_components(adapter, assembly, [component])[component]
        old_file = str(target.GetPathName())
        before = _component_names(adapter, assembly)
        model.ClearSelection2(True)
        _select_components(adapter, [target], 0)
        done = assembly.ReplaceComponents2(file_path, "", all_instances, 0, True)
        model.ClearSelection2(True)
        if not done:
            raise Exception(f"SolidWorks refused to replace {component}")
        after = _component_names(adapter, assembly)
        replaced = {
            name: str(found.GetPathName())
            for name, found in _find_components(adapter, assembly, after).items()
            if os.path.normcase(str(found.GetPathName()))
            == os.path.normcase(file_path)
        }
        if not replaced:
            raise Exception(f"{component} still uses {old_file}")
        return {
            "component": component,
            "file_path": file_path,
            "replaced": replaced,
            "components_before": before,
            "components_after": after,
        }

    return cast(
        AdapterResult[dict[str, Any]],
        adapter._handle_com_operation("replace_component", run),
    )
set_component_appearance async
set_component_appearance(component: str, visible: bool | None = None, transparent: bool | None = None) -> AdapterResult[dict[str, Any]]

Hide or show a component, and make it transparent or opaque.

Visibility is IComponent2.Visible (1 shown, 0 hidden); transparency selects the component and calls IAssemblyDoc.SetComponentTransparent. Both are read back.

Returns:

Type Description
AdapterResult[dict[str, Any]]

AdapterResult[dict[str, Any]]: visible and transparent

AdapterResult[dict[str, Any]]

after.

Source code in src/solidworks_mcp/adapters/solidworks/assembly.py
async def set_component_appearance(
    self,
    component: str,
    visible: bool | None = None,
    transparent: bool | None = None,
) -> AdapterResult[dict[str, Any]]:
    """Hide or show a component, and make it transparent or opaque.

    Visibility is ``IComponent2.Visible`` (1 shown, 0 hidden);
    transparency selects the component and calls
    ``IAssemblyDoc.SetComponentTransparent``. Both are read back.

    Returns:
        AdapterResult[dict[str, Any]]: ``visible`` and ``transparent``
        after.
    """
    adapter = self._adapter(self)
    if wrong := _need_assembly(adapter, "set_component_state"):
        return wrong

    def run() -> dict[str, Any]:
        model = adapter.currentModel
        assembly = _assembly(adapter)
        target = _find_components(adapter, assembly, [component])[component]
        if visible is not None:
            target.Visible = 1 if visible else 0
        if transparent is not None:
            model.ClearSelection2(True)
            _select_components(adapter, [target], 0)
            assembly.SetComponentTransparent(transparent)
            model.ClearSelection2(True)
        shown = int(target.Visible) == 1
        if visible is not None and shown is not visible:
            raise Exception(
                f"{component} is still {'hidden' if visible else 'shown'}"
            )
        return {
            "visible": shown,
            "transparent": transparent,
        }

    return cast(
        AdapterResult[dict[str, Any]],
        adapter._handle_com_operation("set_component_state", run),
    )
set_exploded_view async
set_exploded_view(exploded: bool) -> AdapterResult[dict[str, Any]]

Show the active configuration's exploded view, or collapse it.

Parameters:

Name Type Description Default
exploded bool

True to explode, False to collapse.

required

Returns:

Type Description
AdapterResult[dict[str, Any]]

AdapterResult[dict[str, Any]]: The view, exploded read back

AdapterResult[dict[str, Any]]

(IModelDoc2.IsExploded) and the bounding box size_mm.

Source code in src/solidworks_mcp/adapters/solidworks/assembly.py
async def set_exploded_view(self, exploded: bool) -> AdapterResult[dict[str, Any]]:
    """Show the active configuration's exploded view, or collapse it.

    Args:
        exploded: ``True`` to explode, ``False`` to collapse.

    Returns:
        AdapterResult[dict[str, Any]]: The ``view``, ``exploded`` read back
        (``IModelDoc2.IsExploded``) and the bounding box ``size_mm``.
    """
    adapter = self._adapter(self)
    if wrong := _need_assembly(adapter, "set_exploded_view"):
        return wrong

    def run() -> dict[str, Any]:
        assembly = _assembly(adapter)
        views = _exploded_views(adapter, assembly)
        if not views:
            raise Exception(
                "No exploded view found in the active configuration; "
                "make one with create_exploded_view"
            )
        assembly.ShowExploded2(exploded, views[0])
        model = _sw_type_info.flagged(adapter.currentModel, "IModelDoc2")
        return {
            "view": views[0],
            "exploded": bool(model.IsExploded()),
            "size_mm": _box_size(adapter, assembly),
        }

    return cast(
        AdapterResult[dict[str, Any]],
        adapter._handle_com_operation("set_exploded_view", run),
    )

Functions:

_assembly

_assembly(adapter: Any) -> Any

The active document as IAssemblyDoc.

Source code in src/solidworks_mcp/adapters/solidworks/assembly.py
def _assembly(adapter: Any) -> Any:
    """The active document as ``IAssemblyDoc``."""
    return _sw_type_info.flagged(adapter.currentModel, "IAssemblyDoc")

_box_from_metres

_box_from_metres(raw: Any, method: str) -> dict[str, Any] | None

Turn a SolidWorks [x1, y1, z1, x2, y2, z2] box in metres into mm.

Parameters:

Name Type Description Default
raw Any

The six-value box, or anything else.

required
method str

How the box was measured, reported back to the caller.

required

Returns:

Type Description
dict[str, Any] | None

dict[str, Any] | None: min, max, size (mm) and method,

dict[str, Any] | None

or None when raw is not a six-number box.

Source code in src/solidworks_mcp/adapters/solidworks/io.py
def _box_from_metres(raw: Any, method: str) -> dict[str, Any] | None:
    """Turn a SolidWorks ``[x1, y1, z1, x2, y2, z2]`` box in metres into mm.

    Args:
        raw: The six-value box, or anything else.
        method: How the box was measured, reported back to the caller.

    Returns:
        dict[str, Any] | None: ``min``, ``max``, ``size`` (mm) and ``method``,
        or ``None`` when ``raw`` is not a six-number box.
    """
    if not isinstance(raw, (list, tuple)) or len(raw) < 6:
        return None
    if not all(isinstance(v, (int, float)) for v in raw[:6]):
        return None
    values = [float(v) * 1000.0 for v in raw[:6]]
    low = [min(values[i], values[i + 3]) for i in range(3)]
    high = [max(values[i], values[i + 3]) for i in range(3)]
    return {
        "min": [round(v, 4) for v in low],
        "max": [round(v, 4) for v in high],
        "size": [round(high[i] - low[i], 4) for i in range(3)],
        "method": method,
    }

_box_size

_box_size(adapter: Any, assembly: Any) -> list[float] | None

The assembly's bounding box size [x, y, z] in mm.

Source code in src/solidworks_mcp/adapters/solidworks/assembly.py
def _box_size(adapter: Any, assembly: Any) -> list[float] | None:
    """The assembly's bounding box size ``[x, y, z]`` in mm."""
    box = _box_from_metres(
        adapter._attempt(lambda: assembly.GetBox(0), default=None), "assembly_box"
    )
    return None if box is None else [round(v, 4) for v in box["size"]]

_byref_int

_byref_int() -> Any

Return a byref long VARIANT for a SolidWorks out-parameter.

See :func:_byref_bstr for why pythoncom.Missing does not work.

Returns:

Name Type Description
Any Any

A VARIANT(VT_BYREF | VT_I4, 0), or 0 when pywin32 is

Any

unavailable (test/mock environments).

Source code in src/solidworks_mcp/adapters/solidworks/io.py
def _byref_int() -> Any:
    """Return a byref long VARIANT for a SolidWorks out-parameter.

    See :func:`_byref_bstr` for why ``pythoncom.Missing`` does not work.

    Returns:
        Any: A ``VARIANT(VT_BYREF | VT_I4, 0)``, or ``0`` when pywin32 is
        unavailable (test/mock environments).
    """
    variant_ctor = getattr(getattr(win32com, "client", None), "VARIANT", None)
    if not callable(variant_ctor):
        return _ByrefFallback(0)
    return variant_ctor(
        int(getattr(pythoncom, "VT_BYREF", 0)) | int(getattr(pythoncom, "VT_I4", 0)), 0
    )

_component_names

_component_names(adapter: Any, assembly: Any) -> list[str]

Return the names of an assembly's top-level components.

AddComponent* can return an object having added nothing, so the component list is the ground truth for whether an insert worked.

Parameters:

Name Type Description Default
adapter Any

A connected PyWin32Adapter.

required
assembly Any

The assembly document, flagged for IAssemblyDoc.

required

Returns:

Type Description
list[str]

list[str]: Component names, empty when the assembly holds none.

Source code in src/solidworks_mcp/adapters/solidworks/io.py
def _component_names(adapter: Any, assembly: Any) -> list[str]:
    """Return the names of an assembly's top-level components.

    ``AddComponent*`` can return an object having added nothing, so the
    component list is the ground truth for whether an insert worked.

    Args:
        adapter: A connected ``PyWin32Adapter``.
        assembly: The assembly document, flagged for ``IAssemblyDoc``.

    Returns:
        list[str]: Component names, empty when the assembly holds none.
    """
    return [name for name, _ in _component_pairs(adapter, assembly)]

_doc_type

_doc_type(adapter: Any) -> int | None

Return the active document's type: 1 part, 2 assembly, 3 drawing.

GetType is one of the members pywin32 late binding may expose as either a bound method or a plain value, so calling it directly returns None on some documents. _get_attr_or_call handles both shapes.

Parameters:

Name Type Description Default
adapter Any

A connected PyWin32Adapter.

required

Returns:

Type Description
int | None

int | None: The document type, or None when it cannot be read.

Source code in src/solidworks_mcp/adapters/solidworks/io.py
def _doc_type(adapter: Any) -> int | None:
    """Return the active document's type: 1 part, 2 assembly, 3 drawing.

    ``GetType`` is one of the members pywin32 late binding may expose as either
    a bound method or a plain value, so calling it directly returns ``None`` on
    some documents.  ``_get_attr_or_call`` handles both shapes.

    Args:
        adapter: A connected ``PyWin32Adapter``.

    Returns:
        int | None: The document type, or ``None`` when it cannot be read.
    """
    value = adapter._attempt(
        lambda: adapter._get_attr_or_call(adapter.currentModel, "GetType"),
        default=None,
    )
    return int(value) if isinstance(value, (int, float)) else None

_exploded_views

_exploded_views(adapter: Any, assembly: Any) -> list[str]

The active configuration's exploded views' names.

Source code in src/solidworks_mcp/adapters/solidworks/assembly.py
def _exploded_views(adapter: Any, assembly: Any) -> list[str]:
    """The active configuration's exploded views' names."""
    names = adapter._attempt(lambda: assembly.GetExplodedViewNames(), default=None)
    return [str(n) for n in as_list(names)]

_find_components

_find_components(adapter: Any, assembly: Any, names: list[str]) -> dict[str, Any]

The named top-level components of assembly, as IComponent2.

Parameters:

Name Type Description Default
adapter Any

The connected adapter.

required
assembly Any

The IAssemblyDoc dispatch.

required
names list[str]

Instance names, e.g. ["bracket-1", "pin-1"].

required

Returns:

Type Description
dict[str, Any]

dict[str, Any]: Name to wrapped component, one per name.

Raises:

Type Description
Exception

When the components can't be read, or a name isn't there (the message lists what the assembly holds).

Source code in src/solidworks_mcp/adapters/solidworks/io.py
def _find_components(adapter: Any, assembly: Any, names: list[str]) -> dict[str, Any]:
    """The named top-level components of ``assembly``, as ``IComponent2``.

    Args:
        adapter: The connected adapter.
        assembly: The ``IAssemblyDoc`` dispatch.
        names: Instance names, e.g. ``["bracket-1", "pin-1"]``.

    Returns:
        dict[str, Any]: Name to wrapped component, one per name.

    Raises:
        Exception: When the components can't be read, or a name isn't there
            (the message lists what the assembly holds).
    """
    components = adapter._attempt(lambda: assembly.GetComponents(True), default=None)
    if not isinstance(components, (list, tuple)):
        raise Exception("Could not read the assembly's components")

    found: dict[str, Any] = {}
    for component in components:
        wrapped = _as_com(adapter, component, "IComponent2")
        if wrapped is None:
            continue
        name = adapter._attempt(lambda w=wrapped: w.Name2, default=None)
        if name and str(name) in names:
            found[str(name)] = wrapped

    missing = [n for n in names if n not in found]
    if missing:
        available = [
            str(
                adapter._attempt(
                    lambda c=c: _as_com(adapter, c, "IComponent2").Name2,
                    default="?",
                )
            )
            for c in components
        ]
        raise Exception(
            f"Component(s) not found: {', '.join(missing)}. "
            f"The assembly holds: {', '.join(available)}."
        )
    return found

_need_assembly

_need_assembly(adapter: Any, operation: str) -> AdapterResult[Any] | None

The wrong-document error, or None when an assembly is active.

Source code in src/solidworks_mcp/adapters/solidworks/assembly.py
def _need_assembly(adapter: Any, operation: str) -> AdapterResult[Any] | None:
    """The wrong-document error, or ``None`` when an assembly is active."""
    if _doc_type(adapter) == 2:
        return None
    return AdapterResult(
        status=AdapterResultStatus.ERROR,
        error=f"{operation} requires an assembly document",
    )

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

_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

_select_components

_select_components(adapter: Any, components: list[Any], mark: int) -> None

Select each component, appending, under mark.

Source code in src/solidworks_mcp/adapters/solidworks/assembly.py
def _select_components(adapter: Any, components: list[Any], mark: int) -> None:
    """Select each component, appending, under ``mark``."""
    data = _select_data(adapter, mark)
    for component in components:
        if not component.Select4(True, data, False):
            raise Exception(f"Couldn't select {component.Name2}")

_select_data

_select_data(adapter: Any, mark: int) -> Any

An ISelectData carrying mark.

Source code in src/solidworks_mcp/adapters/solidworks/assembly.py
def _select_data(adapter: Any, mark: int) -> Any:
    """An ``ISelectData`` carrying ``mark``."""
    sel_mgr = _sw_type_info.flagged(
        adapter.currentModel.SelectionManager, "ISelectionMgr"
    )
    data = sel_mgr.CreateSelectData()
    data.Mark = mark
    return data

_select_named

_select_named(adapter: Any, name: str, kind: str, mark: int) -> None

Select a plane or axis by its name, appending, under mark.

A default plane (Top Plane, Right...) is found by its place in the assembly's tree, in any language (#262, fixed in 2.2.0).

Raises:

Type Description
Exception

<Kind> '<name>' not found, when nothing was selected.

Source code in src/solidworks_mcp/adapters/solidworks/assembly.py
def _select_named(adapter: Any, name: str, kind: str, mark: int) -> None:
    """Select a plane or axis by its name, appending, under ``mark``.

    A default plane (``Top Plane``, ``Right``...) is found by its place in
    the assembly's tree, in any language (#262, fixed in 2.2.0).

    Raises:
        Exception: ``<Kind> '<name>' not found``, when nothing was selected.
    """
    name = entity_name(adapter, name)
    picked = adapter.currentModel.Extension.SelectByID2(
        name, kind, 0, 0, 0, True, mark, _null_callout(), 0
    )
    if not picked:
        raise Exception(f"{kind.title()} '{name}' not found in the assembly")

_selected

_selected(adapter: Any, index: int = 1) -> Any

The index-th selected object (1-based).

Source code in src/solidworks_mcp/adapters/solidworks/assembly.py
def _selected(adapter: Any, index: int = 1) -> Any:
    """The ``index``-th selected object (1-based)."""
    sel_mgr = _sw_type_info.flagged(
        adapter.currentModel.SelectionManager, "ISelectionMgr"
    )
    return sel_mgr.GetSelectedObject6(index, -1)

_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]

dispatch_array

dispatch_array(values: list[Any]) -> Any

VARIANT(VT_ARRAY | VT_DISPATCH), e.g. edges for a flange (tuple when pywin32 is absent).

Source code in src/solidworks_mcp/adapters/solidworks/com_utils.py
def dispatch_array(values: list[Any]) -> Any:
    """``VARIANT(VT_ARRAY | VT_DISPATCH)``, e.g. edges for a flange (tuple when pywin32 is absent)."""
    try:
        import pythoncom
        import win32com.client as w32

        return w32.VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_DISPATCH, list(values))
    except ImportError:  # non-Windows
        return tuple(values)

entity_name

entity_name(adapter: Any, name: str, owner: Any = None) -> str

The document's own name for a default plane or the origin.

Front, Top, Right, XY, XZ, YZ, Front Plane... and Origin, in any case, are found by their place in the tree; a @component@assembly suffix reads that component's tree and is kept. Any other name is returned unchanged.

Parameters:

Name Type Description Default
adapter Any

A connected adapter with a document open.

required
name str

The name a tool was given.

required
owner Any

The document or component to read; by default the active document, or the component the suffix names.

None

Returns:

Name Type Description
str str

The name to pass to SolidWorks. When the tree can't be read, the

str

English name ("Top Plane"), as before this lookup existed.

Raises:

Type Description
LookupError

The tree reached its origin with fewer than three reference planes before it; the message lists them and the install's language.

Source code in src/solidworks_mcp/adapters/solidworks/default_entities.py
def entity_name(adapter: Any, name: str, owner: Any = None) -> str:
    """The document's own name for a default plane or the origin.

    ``Front``, ``Top``, ``Right``, ``XY``, ``XZ``, ``YZ``, ``Front Plane``...
    and ``Origin``, in any case, are found by their place in the tree; a
    ``@component@assembly`` suffix reads that component's tree and is kept.
    Any other name is returned unchanged.

    Args:
        adapter: A connected adapter with a document open.
        name: The name a tool was given.
        owner: The document or component to read; by default the active
            document, or the component the suffix names.

    Returns:
        str: The name to pass to SolidWorks. When the tree can't be read, the
        English name (``"Top Plane"``), as before this lookup existed.

    Raises:
        LookupError: The tree reached its origin with fewer than three
            reference planes before it; the message lists them and the
            install's language.
    """
    index = default_index(name)
    if index is None:
        return name
    base, sep, suffix = str(name).partition("@")
    target = owner if owner is not None else _owner_for(adapter, suffix)
    defaults = read_defaults(adapter, target)
    english = ORIGIN if index == _ORIGIN_INDEX else DEFAULT_PLANES[index]
    if not defaults.readable:
        return english + sep + suffix
    local = defaults.name_of(index)
    if local is None:
        planes = ", ".join(defaults.planes) or "none"
        raise LookupError(
            f"Default plane {base.strip()!r} not found: the document has "
            f"{len(defaults.planes)} reference plane(s) before its origin "
            f"({planes}), not the three default ones. SolidWorks language: "
            f"{install_language(adapter)}."
        )
    return local + sep + suffix

long_array

long_array(values: list[int]) -> Any

VARIANT(VT_ARRAY | VT_I4), e.g. one orientation per component (tuple when pywin32 is absent).

Source code in src/solidworks_mcp/adapters/solidworks/com_utils.py
def long_array(values: list[int]) -> Any:
    """``VARIANT(VT_ARRAY | VT_I4)``, e.g. one orientation per component (tuple when pywin32 is absent)."""
    try:
        import pythoncom
        import win32com.client as w32

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