Skip to content

solidworks_mcp.adapters.solidworks.part_features

solidworks_mcp.adapters.solidworks.part_features

Part features beyond extrude and revolve: holes, threads, patterns, shell, draft, rib.

Also sketch_convert_entities, which copies model edges into the open sketch. Every face and edge is picked by a point in millimetres, through the same helpers the chamfer and fillet tools use (rebuild first, then the nearest face or edge on the body; runbook #11 and #13).

The solid features share one rule (spec tools/measured-feature-change): the volume is read before and after through get_mass_properties, and a feature that left the volume unchanged is deleted again and reported as a failure, so a no-op never stays in the tree. A cosmetic thread is the exception: it must leave the volume alone.

COM argument lists and enum values come from the installed type libraries (sldworks.tlb and swconst.tlb, SolidWorks 2026).

Attributes

HOLE_END_CONDITIONS module-attribute

HOLE_END_CONDITIONS: dict[str, int] = {'blind': 0, 'through_all': 1}

HOLE_STANDARDS module-attribute

HOLE_STANDARDS: dict[str, int] = {'ansi_inch': 0, 'ansi_metric': 1, 'din': 4, 'iso': 8, 'jis': 9}

HOLE_TYPES module-attribute

HOLE_TYPES: dict[str, int] = {'counterbore': 0, 'countersink': 1, 'simple': 2, 'tapped': 4}

ISO_COARSE_PITCH module-attribute

ISO_COARSE_PITCH: dict[float, float] = {1.0: 0.25, 1.2: 0.25, 1.4: 0.3, 1.6: 0.35, 2.0: 0.4, 2.5: 0.45, 3.0: 0.5, 3.5: 0.6, 4.0: 0.7, 5.0: 0.8, 6.0: 1.0, 7.0: 1.0, 8.0: 1.25, 10.0: 1.5, 12.0: 1.75, 14.0: 2.0, 16.0: 2.0, 18.0: 2.5, 20.0: 2.5, 22.0: 2.5, 24.0: 3.0, 27.0: 3.0, 30.0: 3.5, 33.0: 3.5, 36.0: 4.0, 39.0: 4.0, 42.0: 4.5, 45.0: 4.5, 48.0: 5.0, 52.0: 5.0, 56.0: 5.5, 60.0: 5.5, 64.0: 6.0}

THREAD_END_TYPES module-attribute

THREAD_END_TYPES: dict[str, int] = {'blind': 0, 'up_to_next': 1, 'through': 2}

_HOLE_AT_POINT_M module-attribute

_HOLE_AT_POINT_M = 1e-07

_MARK_DIR1 module-attribute

_MARK_DIR1 = 1

_MARK_DIR2 module-attribute

_MARK_DIR2 = 2

_MARK_DRAFT_FACES module-attribute

_MARK_DRAFT_FACES = 2

_MARK_FEATURES module-attribute

_MARK_FEATURES = 4

_MARK_NEUTRAL module-attribute

_MARK_NEUTRAL = 1

_METRIC_THREAD_STANDARDS module-attribute

_METRIC_THREAD_STANDARDS = {'iso', 'din'}

_NO_CHANGE module-attribute

_NO_CHANGE = 0.0001

_PICK_TOLERANCE_M module-attribute

_PICK_TOLERANCE_M = 0.0005

_THREAD_SHARE module-attribute

_THREAD_SHARE = 0.8

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.

HoleLibraryError

Bases: Exception

The library can't be found or read; the message says where it looked.

HoleSizeError

Bases: InputRefused

A hole type or size the library doesn't have; names the nearest ones.

ResolvedHole dataclass

ResolvedHole(fastener: str, code: int, size: str, warning: str | None = None)

What create_hole asks SolidWorks for.

Attributes:

Name Type Description
fastener str

The hole type's name.

code int

Its HoleWizard5 fastener index.

size str

The size exactly as the library writes it.

warning str | None

Set when the size couldn't be checked.

SolidWorksPartFeaturesMixin

Holes, threads, linear patterns, shell, draft, rib and convert entities.

Methods:
add_cosmetic_thread async
add_cosmetic_thread(edge_point: list[float], size: str, diameter: float, end_type: str = 'blind', depth: float | None = None, standard: str = 'iso') -> AdapterResult[dict[str, Any]]

A cosmetic thread on a circular edge (InsertCosmeticThread3).

Parameters:

Name Type Description Default
edge_point list[float]

A point (mm) on the circular edge.

required
size str

The thread size, e.g. M10x1.5.

required
diameter float

The major diameter, mm.

required
end_type str

A key of :data:THREAD_END_TYPES.

'blind'
depth float | None

Thread length for a blind thread, mm.

None
standard str

A key of :data:HOLE_STANDARDS.

'iso'

Returns:

Type Description
AdapterResult[dict[str, Any]]

The thread's name; the volume is unchanged.

Source code in src/solidworks_mcp/adapters/solidworks/part_features.py
async def add_cosmetic_thread(
    self,
    edge_point: list[float],
    size: str,
    diameter: float,
    end_type: str = "blind",
    depth: float | None = None,
    standard: str = "iso",
) -> AdapterResult[dict[str, Any]]:
    """A cosmetic thread on a circular edge (``InsertCosmeticThread3``).

    Args:
        edge_point: A point (mm) on the circular edge.
        size: The thread size, e.g. ``M10x1.5``.
        diameter: The major diameter, mm.
        end_type: A key of :data:`THREAD_END_TYPES`.
        depth: Thread length for a blind thread, mm.
        standard: A key of :data:`HOLE_STANDARDS`.

    Returns:
        The thread's name; the volume is unchanged.
    """
    adapter: Any = self

    table_size = thread_table_size(size, standard)

    def build() -> dict[str, Any]:
        model = adapter.currentModel
        model.ClearSelection2(True)
        _Picks(adapter).pick(edge_point, "EDGE", 0)
        manager = sw_type_info.flagged(model.FeatureManager, "IFeatureManager")
        feature = manager.InsertCosmeticThread3(
            HOLE_STANDARDS[standard],  # Standard
            "Machine Threads",  # StandardType
            table_size,  # Size, as the thread table spells it
            _mm(diameter),  # Diameter
            THREAD_END_TYPES[end_type],  # EndType
            _mm(depth) if depth is not None else 0.0,  # Depth
            table_size,  # Note
        )
        if feature is None:
            raise RuntimeError(
                "InsertCosmeticThread3 made no thread; pick a point on a "
                "circular edge of a hole or shaft."
            )
        data: dict[str, Any] = {
            "name": _feature_name(adapter, feature),
            "size": size,
            "diameter_mm": float(diameter),
            "end_type": end_type,
            "depth_mm": depth,
            **_stored_thread(adapter, feature),
        }
        stored = data["stored_size"]
        if (
            stored
            and stored.replace(" ", "").lower()
            != table_size.replace(" ", "").lower()
        ):
            data["warning"] = (
                f"SolidWorks stored the thread as {stored}, not {size}; its "
                "thread table has no such size. Check the size against the "
                f"{standard} table."
            )
        return data

    return await self._measured("add_cosmetic_thread", build, must_change=False)
add_draft async
add_draft(angle: float, faces: list[list[float]], neutral_face: list[float], reverse: bool = False) -> AdapterResult[dict[str, Any]]

Draft faces by an angle against a neutral face (InsertMultiFaceDraft).

Parameters:

Name Type Description Default
angle float

Draft angle, degrees.

required
faces list[list[float]]

A point (mm) on each face to draft.

required
neutral_face list[float]

A point (mm) on the neutral face.

required
reverse bool

Draft the other way.

False

Returns:

Type Description
AdapterResult[dict[str, Any]]

The draft's name and volume change.

Source code in src/solidworks_mcp/adapters/solidworks/part_features.py
async def add_draft(
    self,
    angle: float,
    faces: list[list[float]],
    neutral_face: list[float],
    reverse: bool = False,
) -> AdapterResult[dict[str, Any]]:
    """Draft faces by an angle against a neutral face (``InsertMultiFaceDraft``).

    Args:
        angle: Draft angle, degrees.
        faces: A point (mm) on each face to draft.
        neutral_face: A point (mm) on the neutral face.
        reverse: Draft the other way.

    Returns:
        The draft's name and volume change.
    """
    adapter: Any = self

    def build() -> dict[str, Any]:
        model = adapter.currentModel
        model.ClearSelection2(True)
        picks = _Picks(adapter)
        picks.pick(neutral_face, "FACE", _MARK_NEUTRAL)
        for point in faces:
            picks.pick(point, "FACE", _MARK_DRAFT_FACES)
        manager = sw_type_info.flagged(model.FeatureManager, "IFeatureManager")
        feature = manager.InsertMultiFaceDraft(
            math.radians(float(angle)),  # Angle
            bool(reverse),  # FlipDir
            False,  # EdgeDraft
            0,  # PropType (swNeutralPlaneDraft... propagation: none)
            False,  # IsStepDraft
            False,  # IsBodyDraft
        )
        if feature is None:
            raise RuntimeError(
                "InsertMultiFaceDraft returned nothing; check that the faces "
                "meet the neutral face and that the angle is small enough."
            )
        return {
            "name": _feature_name(adapter, feature),
            "angle": float(angle),
            "faces_drafted": len(faces),
        }

    return await self._measured("add_draft", build)
create_hole async
create_hole(face_point: list[float], hole_type: str, standard: str, size: str, end_condition: str = 'through_all', depth: float | None = None, positions: list[list[float]] | None = None, fastener: str | None = None) -> AdapterResult[dict[str, Any]]

Hole Wizard holes at points on a flat face (HoleWizard5).

The face is selected at face_point with SelectByID2, and SolidWorks puts the hole where the pick landed, about 0.04 mm off; the hole's position sketch point is then moved exactly onto face_point. Dimensions not given are -1, which leaves them to the standard's table for the size. Each point of positions is added to the same position sketch, so one feature holds every hole (:func:_place_holes). A simple hole that SolidWorks won't make through all is made blind through the part (:func:_through_depth_m).

Parameters:

Name Type Description Default
face_point list[float]

[x, y, z] mm on the face, where the first hole goes.

required
hole_type str

A key of :data:HOLE_TYPES.

required
standard str

A key of :data:HOLE_STANDARDS.

required
size str

The size as the library lists it (M6, #10); a bare diameter or a pitch is matched to the table's spelling.

required
end_condition str

A key of :data:HOLE_END_CONDITIONS.

'through_all'
depth float | None

Hole depth for a blind hole, mm.

None
positions list[list[float]] | None

Further [x, y, z] mm points on the same face.

None
fastener str | None

The hole type's name from list_hole_sizes; the default for the kind and size when None.

None

Returns:

Type Description
AdapterResult[dict[str, Any]]

The hole's name, inputs, fastener, hole_count,

AdapterResult[dict[str, Any]]

end_condition_used and volume change. A size the library

AdapterResult[dict[str, Any]]

lacks is refused before any COM call, with the nearest sizes.

AdapterResult[dict[str, Any]]

When adding the positions fails, the hole is removed again and

AdapterResult[dict[str, Any]]

the error says why.

Source code in src/solidworks_mcp/adapters/solidworks/part_features.py
async def create_hole(
    self,
    face_point: list[float],
    hole_type: str,
    standard: str,
    size: str,
    end_condition: str = "through_all",
    depth: float | None = None,
    positions: list[list[float]] | None = None,
    fastener: str | None = None,
) -> AdapterResult[dict[str, Any]]:
    """Hole Wizard holes at points on a flat face (``HoleWizard5``).

    The face is selected at ``face_point`` with ``SelectByID2``, and
    SolidWorks puts the hole where the pick landed, about 0.04 mm off; the
    hole's position sketch point is then moved exactly onto
    ``face_point``. Dimensions not given are -1, which leaves them to the
    standard's table for the size. Each point of ``positions`` is added to
    the same position sketch, so one feature holds every hole
    (:func:`_place_holes`). A simple hole that
    SolidWorks won't make through all is made blind through the part
    (:func:`_through_depth_m`).

    Args:
        face_point: ``[x, y, z]`` mm on the face, where the first hole goes.
        hole_type: A key of :data:`HOLE_TYPES`.
        standard: A key of :data:`HOLE_STANDARDS`.
        size: The size as the library lists it (``M6``, ``#10``); a bare
            diameter or a pitch is matched to the table's spelling.
        end_condition: A key of :data:`HOLE_END_CONDITIONS`.
        depth: Hole depth for a blind hole, mm.
        positions: Further ``[x, y, z]`` mm points on the same face.
        fastener: The hole type's name from ``list_hole_sizes``; the
            default for the kind and size when ``None``.

    Returns:
        The hole's name, inputs, ``fastener``, ``hole_count``,
        ``end_condition_used`` and volume change. A size the library
        lacks is refused before any COM call, with the nearest sizes.
        When adding the positions fails, the hole is removed again and
        the error says why.
    """
    adapter: Any = self
    try:
        chosen = _resolve_hole(standard, hole_type, size, fastener)
    except HoleSizeError as exc:
        return AdapterResult(status=AdapterResultStatus.ERROR, error=str(exc))
    extra = [list(p) for p in positions or []]
    made: dict[str, str | None] = {}

    def build() -> dict[str, Any]:
        model = adapter.currentModel
        model.ClearSelection2(True)
        adapter._attempt(lambda: model.ForceRebuild3(True), default=None)
        x, y, z = (_mm(v) for v in face_point)
        manager = sw_type_info.flagged(model.FeatureManager, "IFeatureManager")

        def make(end: str, depth_m: float) -> Any:
            model.ClearSelection2(True)
            if not model.Extension.SelectByID2(
                "", "FACE", x, y, z, False, 0, _null_callout(), 0
            ):
                raise LookupError(
                    f"No face at {list(face_point)} mm to put the hole on."
                )
            return manager.HoleWizard5(
                HOLE_TYPES[hole_type],  # GenericHoleType
                HOLE_STANDARDS[standard],  # StandardIndex
                chosen.code,  # FastenerTypeIndex
                chosen.size,  # SSize
                HOLE_END_CONDITIONS[end],  # EndType
                -1.0,  # Diameter (from the size table)
                depth_m,  # Depth
                -1.0,  # Length
                *([-1.0] * 12),  # Value1..Value12 (from the size table)
                "",  # ThreadClass
                False,  # RevDir
                True,  # FeatureScope
                True,  # AutoSelect
                True,  # AssemblyFeatureScope
                True,  # AutoSelectComponents
                False,  # PropagateFeatureToParts
            )

        blind_depth = _mm(depth) if depth is not None else -1.0
        end_used = end_condition
        warnings = [chosen.warning] if chosen.warning else []
        feature = make(end_condition, blind_depth)
        if feature is None and hole_type == "simple" and end_condition != "blind":
            blind_depth = _through_depth_m(adapter, model)
            end_used = "blind"
            feature = make("blind", blind_depth)
            warnings.append(
                "SolidWorks makes no simple hole through all, so this one is "
                f"blind, {blind_depth * 1000:.1f} mm deep (through the part). "
                "If the part is made thicker, deepen the hole."
            )
        if feature is None:
            raise RuntimeError(
                f"HoleWizard5 made no hole ({hole_type}, {standard}, "
                f'"{chosen.fastener}" {chosen.size}); check the face is flat '
                "and the hole fits on it."
            )
        name = _feature_name(adapter, feature)
        made["name"] = name
        thread_m = (
            _cap_thread_depth(adapter, model, feature, blind_depth)
            if hole_type == "tapped" and end_condition == "blind" and depth
            else None
        )
        count = _place_holes(adapter, model, feature, list(face_point), extra)
        made["name"] = None  # finished: nothing to clean up
        data: dict[str, Any] = {
            "name": name,
            "hole_count": count,
            "thread_depth_mm": None if thread_m is None else thread_m * 1000,
            "hole_type": hole_type,
            "standard": standard,
            "fastener": chosen.fastener,
            "size": chosen.size,
            "end_condition": end_condition,
            "end_condition_used": end_used,
            "depth_mm": depth if end_used == end_condition else blind_depth * 1000,
            "at_mm": list(face_point),
            "positions_mm": extra,
        }
        if warnings:
            data["warnings"] = warnings
        return data

    result = await self._measured("create_hole", build)
    orphan = made.get("name")
    if not result.is_success and orphan:
        await adapter.delete_feature(orphan)
        return AdapterResult(
            status=AdapterResultStatus.ERROR,
            error=f"{result.error} The hole {orphan} was removed again.",
        )
    return result
create_rib async
create_rib(sketch: str, thickness: float, both_sides: bool = True, flip_material: bool = False, normal_to_sketch: bool = False) -> AdapterResult[dict[str, Any]]

A rib from an open sketch (InsertRib).

Parameters:

Name Type Description Default
sketch str

The rib sketch's name.

required
thickness float

Rib thickness, mm.

required
both_sides bool

Add the thickness to both sides of the sketch.

True
flip_material bool

Extend the rib the other way.

False
normal_to_sketch bool

Extrude normal to the sketch instead of parallel.

False

Returns:

Type Description
AdapterResult[dict[str, Any]]

The rib's name and volume change.

Source code in src/solidworks_mcp/adapters/solidworks/part_features.py
async def create_rib(
    self,
    sketch: str,
    thickness: float,
    both_sides: bool = True,
    flip_material: bool = False,
    normal_to_sketch: bool = False,
) -> AdapterResult[dict[str, Any]]:
    """A rib from an open sketch (``InsertRib``).

    Args:
        sketch: The rib sketch's name.
        thickness: Rib thickness, mm.
        both_sides: Add the thickness to both sides of the sketch.
        flip_material: Extend the rib the other way.
        normal_to_sketch: Extrude normal to the sketch instead of parallel.

    Returns:
        The rib's name and volume change.
    """
    adapter: Any = self

    def build() -> dict[str, Any]:
        model = adapter.currentModel
        model.ClearSelection2(True)
        if not _select_named_feature(adapter, sketch, 0, append=False):
            raise LookupError(f"Couldn't select the sketch '{sketch}' for the rib.")
        manager = sw_type_info.flagged(model.FeatureManager, "IFeatureManager")
        manager.InsertRib(
            bool(both_sides),  # Is2Sided
            False,  # ReverseThicknessDir
            _mm(thickness),  # Thickness
            0,  # ReferenceEdgeIndex
            bool(flip_material),  # ReverseMaterialDir
            False,  # IsDrafted
            False,  # DraftOutward
            0.0,  # DraftAngle
            bool(normal_to_sketch),  # IsNormToSketch
            False,  # IsDraftedFromWall
        )
        return {
            "name": _last_feature_name(adapter),
            "sketch": sketch,
            "thickness_mm": float(thickness),
            "both_sides": bool(both_sides),
        }

    return await self._measured("create_rib", build)
create_shell async
create_shell(thickness: float, faces: list[list[float]], outward: bool = False) -> AdapterResult[dict[str, Any]]

Hollow the body to a wall thickness, removing the faces picked.

Parameters:

Name Type Description Default
thickness float

Wall thickness, mm.

required
faces list[list[float]]

A point (mm) on each face to remove; empty for a closed shell.

required
outward bool

Add the wall outside the body instead of inside.

False

Returns:

Type Description
AdapterResult[dict[str, Any]]

The shell's name and volume change.

Source code in src/solidworks_mcp/adapters/solidworks/part_features.py
async def create_shell(
    self, thickness: float, faces: list[list[float]], outward: bool = False
) -> AdapterResult[dict[str, Any]]:
    """Hollow the body to a wall thickness, removing the faces picked.

    Args:
        thickness: Wall thickness, mm.
        faces: A point (mm) on each face to remove; empty for a closed shell.
        outward: Add the wall outside the body instead of inside.

    Returns:
        The shell's name and volume change.
    """
    adapter: Any = self

    def build() -> dict[str, Any]:
        model = adapter.currentModel
        model.ClearSelection2(True)
        picks = _Picks(adapter)
        for point in faces:
            picks.pick(point, "FACE", 0)
        doc = sw_type_info.flagged(model, "IModelDoc2")
        doc.InsertFeatureShell(_mm(thickness), bool(outward))
        return {
            "name": _last_feature_name(adapter),
            "thickness_mm": float(thickness),
            "faces_removed": len(faces),
            "outward": bool(outward),
        }

    return await self._measured("create_shell", build)
list_hole_sizes async
list_hole_sizes(standard: str, hole_type: str, fastener: str | None = None, size: str | None = None) -> AdapterResult[dict[str, Any]]

The Hole Wizard hole types and sizes, read from the installed library.

A file read (:mod:.hole_library), no COM: it works whether or not SolidWorks is running.

Parameters:

Name Type Description Default
standard str

A key of :data:HOLE_STANDARDS.

required
hole_type str

simple, counterbore, countersink or tapped.

required
fastener str | None

One hole type's name, to list only its sizes.

None
size str | None

One size, to read its dimensions.

None

Returns:

Type Description
AdapterResult[dict[str, Any]]

The hole types with their sizes, or one size's dimensions; an

AdapterResult[dict[str, Any]]

error naming where the library was looked for, or the nearest

AdapterResult[dict[str, Any]]

sizes.

Source code in src/solidworks_mcp/adapters/solidworks/part_features.py
async def list_hole_sizes(
    self,
    standard: str,
    hole_type: str,
    fastener: str | None = None,
    size: str | None = None,
) -> AdapterResult[dict[str, Any]]:
    """The Hole Wizard hole types and sizes, read from the installed library.

    A file read (:mod:`.hole_library`), no COM: it works whether or not
    SolidWorks is running.

    Args:
        standard: A key of :data:`HOLE_STANDARDS`.
        hole_type: ``simple``, ``counterbore``, ``countersink`` or ``tapped``.
        fastener: One hole type's name, to list only its sizes.
        size: One size, to read its dimensions.

    Returns:
        The hole types with their sizes, or one size's dimensions; an
        error naming where the library was looked for, or the nearest
        sizes.
    """
    try:
        data = describe(find_library(), standard, hole_type, fastener, size)
    except (HoleLibraryError, HoleSizeError) as exc:
        return AdapterResult(status=AdapterResultStatus.ERROR, error=str(exc))
    return AdapterResult(status=AdapterResultStatus.SUCCESS, data=data)
pattern_linear async
pattern_linear(features: list[str], direction: list[float] | str, count: int, spacing: float, direction2: list[float] | str | None = None, count2: int = 1, spacing2: float = 0.0, reverse: bool = False, reverse2: bool = False) -> AdapterResult[dict[str, Any]]

Repeat features along one or two directions (FeatureLinearPattern5).

A direction is a point (mm) on a straight edge, or the name of an axis or edge.

Parameters:

Name Type Description Default
features list[str]

Names of the features to repeat.

required
direction list[float] | str

The first direction.

required
count int

Instances along it, the original included.

required
spacing float

Distance between instances, mm.

required
direction2 list[float] | str | None

The second direction, or None for one direction.

None
count2 int

Instances along the second direction.

1
spacing2 float

Spacing along the second direction, mm.

0.0
reverse bool

Flip the first direction.

False
reverse2 bool

Flip the second direction.

False

Returns:

Type Description
AdapterResult[dict[str, Any]]

The pattern's name, inputs and volume change.

Source code in src/solidworks_mcp/adapters/solidworks/part_features.py
async def pattern_linear(
    self,
    features: list[str],
    direction: list[float] | str,
    count: int,
    spacing: float,
    direction2: list[float] | str | None = None,
    count2: int = 1,
    spacing2: float = 0.0,
    reverse: bool = False,
    reverse2: bool = False,
) -> AdapterResult[dict[str, Any]]:
    """Repeat features along one or two directions (``FeatureLinearPattern5``).

    A direction is a point (mm) on a straight edge, or the name of an
    axis or edge.

    Args:
        features: Names of the features to repeat.
        direction: The first direction.
        count: Instances along it, the original included.
        spacing: Distance between instances, mm.
        direction2: The second direction, or None for one direction.
        count2: Instances along the second direction.
        spacing2: Spacing along the second direction, mm.
        reverse: Flip the first direction.
        reverse2: Flip the second direction.

    Returns:
        The pattern's name, inputs and volume change.
    """
    adapter: Any = self

    def build() -> dict[str, Any]:
        model = adapter.currentModel
        model.ClearSelection2(True)
        picks = _Picks(adapter)
        names = ["", ""]
        for index, (where, mark) in enumerate(
            ((direction, _MARK_DIR1), (direction2, _MARK_DIR2))
        ):
            if where is None:
                continue
            if isinstance(where, str):
                names[index] = where
                if not _select_named_feature(
                    adapter, where, mark, append=index > 0
                ):
                    raise LookupError(f"Couldn't select the direction '{where}'.")
                picks._first = False
            else:
                picks.pick(where, "EDGE", mark)
        for name in features:
            if not _select_named_feature(
                adapter, name, _MARK_FEATURES, append=True
            ):
                raise LookupError(
                    f"Couldn't select the feature '{name}' to pattern."
                )
        manager = sw_type_info.flagged(model.FeatureManager, "IFeatureManager")
        two = direction2 is not None
        feature = manager.FeatureLinearPattern5(
            int(count),  # Num1
            _mm(spacing),  # Spacing1
            int(count2) if two else 1,  # Num2
            _mm(spacing2) if two else 0.0,  # Spacing2
            bool(reverse),  # FlipDir1
            bool(reverse2),  # FlipDir2
            names[0],  # DName1
            names[1],  # DName2
            False,  # GeometryPattern
            False,  # VaryInstance
            False,  # HasOffset1
            False,  # HasOffset2
            False,  # CtrlByNum1
            False,  # CtrlByNum2
            False,  # FromCentroid1
            False,  # FromCentroid2
            False,  # RevOffset1
            False,  # RevOffset2
            0.0,  # Offset1
            0.0,  # Offset2
            False,  # D2PatternSeedOnly
            False,  # SyncSubAssemblies
        )
        if feature is None:
            raise RuntimeError(
                "FeatureLinearPattern5 returned nothing. SolidWorks picks "
                "which way an edge points, so an instance may have landed "
                "off the part: try reverse (or reverse2). Also check the "
                "features, and that each direction is a straight edge or an "
                "axis."
            )
        return {
            "name": _feature_name(adapter, feature),
            "patterned": list(features),
            "count": int(count),
            "spacing_mm": float(spacing),
            "count2": int(count2) if two else None,
            "spacing2_mm": float(spacing2) if two else None,
        }

    return await self._measured("pattern_linear", build)
sketch_convert_entities async
sketch_convert_entities(edge_points: list[list[float]] | None = None, face_point: list[float] | None = None, construction: bool = False) -> AdapterResult[dict[str, Any]]

Copy model edges, or a face's outline, into the open sketch.

SketchUseEdge3 returns only a Boolean, so the sketch's segments are read before and after and the new ones registered under ids the other sketch tools accept.

Parameters:

Name Type Description Default
edge_points list[list[float]] | None

A point (mm) on each edge to copy.

None
face_point list[float] | None

A point (mm) on a face whose outline to copy.

None
construction bool

Make the copies construction geometry.

False

Returns:

Type Description
AdapterResult[dict[str, Any]]

The new entities' ids.

Source code in src/solidworks_mcp/adapters/solidworks/part_features.py
async def sketch_convert_entities(
    self,
    edge_points: list[list[float]] | None = None,
    face_point: list[float] | None = None,
    construction: bool = False,
) -> AdapterResult[dict[str, Any]]:
    """Copy model edges, or a face's outline, into the open sketch.

    ``SketchUseEdge3`` returns only a Boolean, so the sketch's segments
    are read before and after and the new ones registered under ids the
    other sketch tools accept.

    Args:
        edge_points: A point (mm) on each edge to copy.
        face_point: A point (mm) on a face whose outline to copy.
        construction: Make the copies construction geometry.

    Returns:
        The new entities' ids.
    """
    adapter: Any = self
    if not adapter.currentSketchManager:
        return AdapterResult(
            status=AdapterResultStatus.ERROR, error="No active sketch"
        )

    def segments() -> list[Any]:
        # Flagged, or GetSketchSegments reads as a property and calling
        # its tuple fails, so every count is 0 (seen live).
        sketch = sw_type_info.flagged(
            adapter.currentSketchManager.ActiveSketch, "ISketch"
        )
        return as_list(
            adapter._attempt(lambda: sketch.GetSketchSegments(), default=None)
        )

    def build() -> dict[str, Any]:
        before = len(segments())
        adapter.currentModel.ClearSelection2(True)
        # No rebuild: it would close the sketch being copied into.
        picks = _Picks(adapter, rebuild=False)
        for point in edge_points or []:
            picks.pick(point, "EDGE", 0)
        if face_point is not None:
            picks.pick(face_point, "FACE", 0)
        manager = sw_type_info.flagged(
            adapter.currentSketchManager, "ISketchManager"
        )
        if not manager.SketchUseEdge3(False, False):
            raise RuntimeError(
                "SketchUseEdge3 copied nothing; the picked edges may already "
                "be in the sketch."
            )
        new = segments()[before:]
        ids: list[str] = []
        for segment in new:
            if construction:
                segment.ConstructionGeometry = True
            entity_id = f"Converted_{len(adapter._sketch_entities) + 1}"
            adapter._sketch_entities[entity_id] = segment
            ids.append(entity_id)
        return {"entities": ids, "count": len(ids), "construction": construction}

    return cast(
        AdapterResult[dict[str, Any]],
        adapter._handle_com_operation("sketch_convert_entities", build),
    )

_BodyEntityPicker

_BodyEntityPicker(adapter: Any)

Find the body edge or face nearest a point, by true closest distance.

SelectByID2("", "EDGE", x, y, z, ...) picks along the view direction through the point, so on a 12 mm plate seen from the front an edge at z=-6 is hidden behind the matching edge at z=+6 and the front one is selected instead - silently. This walks every solid body's edges (or faces) and measures the distance from the point to the closest point on each (IEdge / IFace2.GetClosestPointOn), which does not depend on the view, vertices or midpoints.

The entity lists are read once per picker, so one fillet over many edges costs one body walk, not one per edge.

Parameters:

Name Type Description Default
adapter Any

A connected adapter with a valid currentModel.

required
Source code in src/solidworks_mcp/adapters/solidworks/features.py
def __init__(self, adapter: Any) -> None:
    self._adapter = adapter
    self._cache: dict[str, list[Any]] = {}
Methods:
entities
entities(getter: str) -> list[Any]

Return every solid body's GetEdges() or GetFaces().

Source code in src/solidworks_mcp/adapters/solidworks/features.py
def entities(self, getter: str) -> list[Any]:
    """Return every solid body's ``GetEdges()`` or ``GetFaces()``."""
    if getter not in self._cache:
        model = self._adapter.currentModel
        _flag(self._adapter, model, "GetBodies2")
        bodies = as_list(
            _attempt(self._adapter, lambda: model.GetBodies2(0, False))
        )
        found: list[Any] = []
        for body in bodies:
            _flag(self._adapter, body, getter)
            found.extend(
                as_list(
                    _attempt(self._adapter, lambda b=body: getattr(b, getter)())
                )
            )
        self._cache[getter] = found
    return self._cache[getter]
nearest
nearest(getter: str, point: tuple[float, float, float]) -> tuple[Any, float] | None

Return (entity, distance_m) for the closest entity, or None.

Source code in src/solidworks_mcp/adapters/solidworks/features.py
def nearest(
    self, getter: str, point: tuple[float, float, float]
) -> tuple[Any, float] | None:
    """Return ``(entity, distance_m)`` for the closest entity, or ``None``."""
    best: tuple[Any, float] | None = None
    for entity in self.entities(getter):
        _flag(self._adapter, entity, "GetClosestPointOn")
        closest = _attempt(
            self._adapter, lambda e=entity: list(e.GetClosestPointOn(*point))
        )
        if not closest or len(closest) < 3:
            continue
        distance = math.dist([float(c) for c in closest[:3]], point)
        if best is None or distance < best[1]:
            best = (entity, distance)
    return best
select
select(entity: Any, append: bool, mark: int = 0) -> bool

Select entity with IEntity.Select4 under mark.

Source code in src/solidworks_mcp/adapters/solidworks/features.py
def select(self, entity: Any, append: bool, mark: int = 0) -> bool:
    """Select ``entity`` with ``IEntity.Select4`` under ``mark``."""
    model = self._adapter.currentModel
    sel_mgr = _attempt(self._adapter, lambda: model.SelectionManager)
    _flag(self._adapter, sel_mgr, "CreateSelectData")
    select_data = _attempt(self._adapter, lambda: sel_mgr.CreateSelectData())
    if select_data is None:
        return False
    if mark:
        _attempt(self._adapter, lambda: setattr(select_data, "Mark", mark))
    _flag(self._adapter, entity, "Select4")
    return bool(
        _attempt(self._adapter, lambda: entity.Select4(append, select_data), False)
    )

_Picks

_Picks(adapter: Any, *, rebuild: bool = True)

Picks faces and edges by points (mm), sharing one body walk.

Start a pick set.

Parameters:

Name Type Description Default
adapter Any

The connected adapter.

required
rebuild bool

Rebuild before the first pick; False inside an open sketch, which a rebuild would close.

True
Source code in src/solidworks_mcp/adapters/solidworks/part_features.py
def __init__(self, adapter: Any, *, rebuild: bool = True) -> None:
    """Start a pick set.

    Args:
        adapter: The connected adapter.
        rebuild: Rebuild before the first pick; False inside an open
            sketch, which a rebuild would close.
    """
    self._adapter = adapter
    self._picker = _BodyEntityPicker(adapter)
    self._first = True
    self._rebuild = rebuild
Methods:
pick
pick(point: list[float], kind: str, mark: int) -> None

Select the kind ("FACE" or "EDGE") at point under mark.

Raises:

Type Description
LookupError

When nothing of that kind lies at the point.

Source code in src/solidworks_mcp/adapters/solidworks/part_features.py
def pick(self, point: list[float], kind: str, mark: int) -> None:
    """Select the ``kind`` ("FACE" or "EDGE") at ``point`` under ``mark``.

    Raises:
        LookupError: When nothing of that kind lies at the point.
    """
    x, y, z = (_mm(v) for v in point)
    selected = _select_edge_by_coord(
        self._adapter,
        x,
        y,
        z,
        append=not self._first,
        mark=mark,
        entity_type=kind,
        picker=self._picker,
        rebuild=self._rebuild,
    )
    self._first = False
    if not selected:
        raise LookupError(
            f"Couldn't select the {kind.lower()} at {list(point)} mm; give a "
            f"point on the {kind.lower()} itself."
        )

Functions:

_cap_thread_depth

_cap_thread_depth(adapter: Any, model: Any, feature: Any, depth_m: float) -> float | None

Keep a blind tapped hole's thread inside the hole, in metres.

HoleWizard5 takes the thread depth from the size table (about twice the diameter), which SolidWorks then refuses when the blind hole is shallower: "The Tap Thread Depth cannot be larger than Blind Hole Depth" (seen live on SolidWorks 2026). A thread exactly as deep as the hole is refused too (a zero-length line in the hole's sketch), so the thread is capped at :data:_THREAD_SHARE of the hole depth: the hole's IWizardHoleFeatureData2 is opened, ThreadDepth lowered, and the definition saved.

Parameters:

Name Type Description Default
adapter Any

The connected adapter.

required
model Any

The active IModelDoc2.

required
feature Any

The new hole feature.

required
depth_m float

The blind hole's depth, metres.

required

Returns:

Type Description
float | None

The thread depth in metres after the call, or None when the

float | None

definition couldn't be read (the rebuild check then reports why).

Source code in src/solidworks_mcp/adapters/solidworks/part_features.py
def _cap_thread_depth(
    adapter: Any, model: Any, feature: Any, depth_m: float
) -> float | None:
    """Keep a blind tapped hole's thread inside the hole, in metres.

    ``HoleWizard5`` takes the thread depth from the size table (about twice
    the diameter), which SolidWorks then refuses when the blind hole is
    shallower: "The Tap Thread Depth cannot be larger than Blind Hole Depth"
    (seen live on SolidWorks 2026). A thread exactly as deep as the hole is
    refused too (a zero-length line in the hole's sketch), so the thread is
    capped at :data:`_THREAD_SHARE` of the hole depth: the hole's
    ``IWizardHoleFeatureData2`` is opened, ``ThreadDepth`` lowered, and the
    definition saved.

    Args:
        adapter: The connected adapter.
        model: The active ``IModelDoc2``.
        feature: The new hole feature.
        depth_m: The blind hole's depth, metres.

    Returns:
        The thread depth in metres after the call, or ``None`` when the
        definition couldn't be read (the rebuild check then reports why).
    """
    hole = sw_type_info.flagged(feature, "IFeature")
    data = adapter._attempt(lambda: hole.GetDefinition(), None)
    if data is None:
        return None
    data = sw_type_info.flagged(data, "IWizardHoleFeatureData2")
    thread: float | None = adapter._attempt(lambda: float(data.ThreadDepth), None)
    cap = depth_m * _THREAD_SHARE
    if thread is None or thread <= cap:
        return thread
    adapter._attempt(lambda: data.AccessSelections(model, _null_callout()), None)
    data.ThreadDepth = cap
    saved = adapter._attempt(
        lambda: hole.ModifyDefinition(data, model, _null_callout()), False
    )
    if not saved:
        adapter._attempt(lambda: data.ReleaseSelectionAccess(), None)
        return thread
    return cap

_coords

_coords(point: Any) -> list[float]

An ISketchPoint's [x, y, z], sketch metres.

Source code in src/solidworks_mcp/adapters/solidworks/part_features.py
def _coords(point: Any) -> list[float]:
    """An ``ISketchPoint``'s ``[x, y, z]``, sketch metres."""
    return [float(point.X), float(point.Y), float(point.Z)]

_feature_name

_feature_name(adapter: Any, feature: Any) -> str | None

A COM feature's name, or None.

Source code in src/solidworks_mcp/adapters/solidworks/part_features.py
def _feature_name(adapter: Any, feature: Any) -> str | None:
    """A COM feature's name, or ``None``."""
    name = adapter._attempt(
        lambda: adapter._get_attr_or_call(feature, "Name"), default=None
    )
    return str(name) if name else None

_last_feature_name

_last_feature_name(adapter: Any) -> str | None

The newest feature's name, for calls that return nothing (rib, shell).

Source code in src/solidworks_mcp/adapters/solidworks/part_features.py
def _last_feature_name(adapter: Any) -> str | None:
    """The newest feature's name, for calls that return nothing (rib, shell)."""
    model = adapter.currentModel
    feature = adapter._attempt(lambda: model.FeatureByPositionReverse(0), default=None)
    return _feature_name(adapter, feature) if feature is not None else None

_mm

_mm(value: float) -> float

Millimetres to metres.

Source code in src/solidworks_mcp/adapters/solidworks/part_features.py
def _mm(value: float) -> float:
    """Millimetres to metres."""
    return float(value) / 1000.0

_nearest_point

_nearest_point(adapter: Any, sketch: Any, at: list[float]) -> Any

The ISketchPoint of sketch nearest at (sketch metres).

_position_sketch already found a point within the pick tolerance, so the sketch has at least one point.

Source code in src/solidworks_mcp/adapters/solidworks/part_features.py
def _nearest_point(adapter: Any, sketch: Any, at: list[float]) -> Any:
    """The ``ISketchPoint`` of ``sketch`` nearest ``at`` (sketch metres).

    ``_position_sketch`` already found a point within the pick tolerance, so
    the sketch has at least one point.
    """
    points = as_list(adapter._attempt(lambda: sketch.GetSketchPoints2(), default=None))
    return min(points, key=lambda p: math.dist(_coords(p), [at[0], at[1], 0.0]))

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

_place_holes

_place_holes(adapter: Any, model: Any, feature: Any, first_mm: list[float], positions_mm: list[list[float]]) -> int

Put the first hole exactly at first_mm and one at each position.

HoleWizard5 puts the hole where SelectByID2 picked the face, which lands about 0.04 mm from the point asked for. So the hole's position sketch is edited: its first point is moved onto the exact point (ISketchPoint.SetCoords), and each further point is added, as clicking points on the Hole Wizard's Positions tab does. Closing the sketch rebuilds the hole at every point. With nothing to move or add the sketch isn't opened.

Parameters:

Name Type Description Default
adapter Any

The connected adapter.

required
model Any

The active part.

required
feature Any

The new Hole Wizard feature.

required
first_mm list[float]

The first hole's point, mm.

required
positions_mm list[list[float]]

The further points, mm, on the same face.

required

Returns:

Type Description
int

The number of points in the position sketch afterwards.

Raises:

Type Description
ValueError

A point that is off the face's plane.

RuntimeError

When the first point didn't move or the sketch didn't take every point.

Source code in src/solidworks_mcp/adapters/solidworks/part_features.py
def _place_holes(
    adapter: Any,
    model: Any,
    feature: Any,
    first_mm: list[float],
    positions_mm: list[list[float]],
) -> int:
    """Put the first hole exactly at ``first_mm`` and one at each position.

    ``HoleWizard5`` puts the hole where ``SelectByID2`` picked the face, which
    lands about 0.04 mm from the point asked for. So the hole's position
    sketch is edited: its first point is moved onto the exact point
    (``ISketchPoint.SetCoords``), and each further point is added, as
    clicking points on the Hole Wizard's Positions tab does. Closing the
    sketch rebuilds the hole at every point. With nothing to move or add the
    sketch isn't opened.

    Args:
        adapter: The connected adapter.
        model: The active part.
        feature: The new Hole Wizard feature.
        first_mm: The first hole's point, mm.
        positions_mm: The further points, mm, on the same face.

    Returns:
        The number of points in the position sketch afterwards.

    Raises:
        ValueError: A point that is off the face's plane.
        RuntimeError: When the first point didn't move or the sketch didn't
            take every point.
    """
    first_m = [_mm(v) for v in first_mm]
    sketch_feature, sketch = _position_sketch(adapter, feature, first_m)
    target = _to_sketch(adapter, sketch, first_m)
    local = [_to_sketch(adapter, sketch, [_mm(v) for v in p]) for p in positions_mm]
    for point, at in zip(positions_mm, local, strict=True):
        if abs(at[2]) > _PICK_TOLERANCE_M:
            raise ValueError(
                f"Position {list(point)} mm is {abs(at[2]) * 1000:.3f} mm off the "
                "face the hole is on; give points on that face."
            )
    first = _nearest_point(adapter, sketch, target)
    off = math.dist(_coords(first), [target[0], target[1], 0.0])
    if off <= _HOLE_AT_POINT_M and not local:
        return len(_sketch_points(adapter, sketch))
    model.ClearSelection2(True)
    sw_type_info.flagged(sketch_feature, "IFeature").Select2(False, 0)
    model.EditSketch()
    manager = sw_type_info.flagged(model.SketchManager, "ISketchManager")
    manager.AddToDB = True  # no snapping onto the first hole
    try:
        if off > _HOLE_AT_POINT_M:
            sw_type_info.flagged(first, "ISketchPoint").SetCoords(
                target[0], target[1], 0.0
            )
        for x, y, _z in local:
            manager.CreatePoint(x, y, 0.0)
    finally:
        manager.AddToDB = False
        manager.InsertSketch(True)
    moved_off = math.dist(
        _coords(_nearest_point(adapter, sketch, target)), [target[0], target[1], 0.0]
    )
    if moved_off > _HOLE_AT_POINT_M:
        raise RuntimeError(
            f"The hole is {moved_off * 1000:.3f} mm from {list(first_mm)} mm and "
            "couldn't be moved onto it."
        )
    count = len(_sketch_points(adapter, sketch))
    expected = 1 + len(positions_mm)
    if count != expected:
        raise RuntimeError(
            f"The hole's position sketch has {count} points after adding "
            f"{len(positions_mm)}; expected {expected}."
        )
    return count

_position_sketch

_position_sketch(adapter: Any, feature: Any, first_m: list[float]) -> Any

The hole's position sketch feature: its sketch has a point at first_m.

Parameters:

Name Type Description Default
adapter Any

The connected adapter.

required
feature Any

The new Hole Wizard feature.

required
first_m list[float]

The first hole's point, metres, model space.

required

Returns:

Type Description
Any

(sketch_feature, sketch).

Raises:

Type Description
LookupError

When no sub-feature sketch holds that point.

Source code in src/solidworks_mcp/adapters/solidworks/part_features.py
def _position_sketch(adapter: Any, feature: Any, first_m: list[float]) -> Any:
    """The hole's position sketch feature: its sketch has a point at ``first_m``.

    Args:
        adapter: The connected adapter.
        feature: The new Hole Wizard feature.
        first_m: The first hole's point, metres, model space.

    Returns:
        ``(sketch_feature, sketch)``.

    Raises:
        LookupError: When no sub-feature sketch holds that point.
    """
    hole = sw_type_info.flagged(feature, "IFeature")
    sub = adapter._attempt(lambda: hole.GetFirstSubFeature(), default=None)
    while sub is not None:
        sub = sw_type_info.flagged(sub, "IFeature")
        kind = adapter._attempt(lambda s=sub: s.GetTypeName2(), default="")
        if kind in ("ProfileFeature", "3DProfileFeature"):
            sketch = sw_type_info.flagged(
                adapter._attempt(lambda s=sub: s.GetSpecificFeature2(), None),
                "ISketch",
            )
            if sketch is not None:
                at = _to_sketch(adapter, sketch, first_m)
                if any(
                    math.dist(at, p) <= _PICK_TOLERANCE_M
                    for p in _sketch_points(adapter, sketch)
                ):
                    return sub, sketch
        sub = adapter._attempt(lambda s=sub: s.GetNextSubFeature(), default=None)
    raise LookupError("The hole's position sketch couldn't be found.")

_resolve_hole

_resolve_hole(standard: str, hole_type: str, size: str, fastener: str | None) -> ResolvedHole

The hole type, index and size to ask HoleWizard5 for.

Checked against the installed library; when it can't be read, the default hole type is tried with a warning (design decision 7).

Raises:

Type Description
HoleSizeError

For a size or hole type the library lacks.

Source code in src/solidworks_mcp/adapters/solidworks/part_features.py
def _resolve_hole(
    standard: str, hole_type: str, size: str, fastener: str | None
) -> ResolvedHole:
    """The hole type, index and size to ask ``HoleWizard5`` for.

    Checked against the installed library; when it can't be read, the
    default hole type is tried with a warning (design decision 7).

    Raises:
        HoleSizeError: For a size or hole type the library lacks.
    """
    try:
        library = find_library()
    except HoleLibraryError as exc:
        return unchecked(standard, hole_type, size, fastener, str(exc))
    return library.resolve(standard, hole_type, size, fastener)

_select_edge_by_coord

_select_edge_by_coord(adapter: Any, x: float, y: float, z: float, append: bool, mark: int = 0, entity_type: str = 'EDGE', picker: _BodyEntityPicker | None = None, rebuild: bool = True) -> bool

Select the edge (or face) nearest to (x, y, z) in metres.

Calls ForceRebuild3 on the first entity in the selection set so that recent features are fully tessellated and selectable, then resolves the point with :class:_BodyEntityPicker - the entity whose closest point is nearest, independent of the view. Only when no body edge/face can be read at all does it fall back to the view-dependent SelectByID2 pick.

entity_type is normally "EDGE", but pass "FACE" to select a whole face instead. Any other type ("VERTEX" from measure_entities) goes straight to the SelectByID2 pick: a vertex lies on its edges at distance 0, so the edge walk would select an edge in its place.

Parameters:

Name Type Description Default
adapter Any

A connected adapter with a valid currentModel.

required
x float

X in metres.

required
y float

Y in metres.

required
z float

Z in metres.

required
append bool

Add to the current selection instead of replacing it.

required
mark int

Selection mark.

0
entity_type str

"EDGE", "FACE", or another SelectByID2 type such as "VERTEX".

'EDGE'
picker _BodyEntityPicker | None

Reuse a picker (and its body walk) across several picks.

None
rebuild bool

Rebuild before the first pick. Pass False inside an open sketch: a rebuild there closes the sketch (seen live).

True

Returns:

Name Type Description
bool bool

True if an entity was selected; False otherwise.

Raises:

Type Description
LookupError

When the nearest entity is further than _PICK_TOLERANCE_M from the point - picking it anyway would silently act on the wrong edge.

Source code in src/solidworks_mcp/adapters/solidworks/features.py
def _select_edge_by_coord(
    adapter: Any,
    x: float,
    y: float,
    z: float,
    append: bool,
    mark: int = 0,
    entity_type: str = "EDGE",
    picker: _BodyEntityPicker | None = None,
    rebuild: bool = True,
) -> bool:
    """Select the edge (or face) nearest to (x, y, z) in metres.

    Calls ``ForceRebuild3`` on the first entity in the selection set so that
    recent features are fully tessellated and selectable, then resolves the
    point with :class:`_BodyEntityPicker` - the entity whose closest point is
    nearest, independent of the view. Only when no body edge/face can be read
    at all does it fall back to the view-dependent ``SelectByID2`` pick.

    ``entity_type`` is normally ``"EDGE"``, but pass ``"FACE"`` to select a
    whole face instead. Any other type (``"VERTEX"`` from
    ``measure_entities``) goes straight to the ``SelectByID2`` pick: a vertex
    lies on its edges at distance 0, so the edge walk would select an edge
    in its place.

    Args:
        adapter: A connected adapter with a valid ``currentModel``.
        x: X in metres.
        y: Y in metres.
        z: Z in metres.
        append: Add to the current selection instead of replacing it.
        mark: Selection mark.
        entity_type: ``"EDGE"``, ``"FACE"``, or another ``SelectByID2``
            type such as ``"VERTEX"``.
        picker: Reuse a picker (and its body walk) across several picks.
        rebuild: Rebuild before the first pick. Pass False inside an open
            sketch: a rebuild there closes the sketch (seen live).

    Returns:
        bool: True if an entity was selected; False otherwise.

    Raises:
        LookupError: When the nearest entity is further than
            ``_PICK_TOLERANCE_M`` from the point - picking it anyway would
            silently act on the wrong edge.
    """
    model = adapter.currentModel

    # Rebuild to tessellate geometry from recent features before the first
    # entity in the selection set (when append=False this is the first one).
    if not append and rebuild:
        adapter._attempt(lambda: model.ForceRebuild3(True), default=None)

    # Only edges and faces are walked on the body; anything else (a vertex)
    # keeps the SelectByID2 pick, which honours the requested type.
    if entity_type not in ("EDGE", "FACE"):
        return _select_by_view_pick(adapter, x, y, z, append, mark, entity_type)

    picker = picker or _BodyEntityPicker(adapter)
    getter = "GetFaces" if entity_type == "FACE" else "GetEdges"
    nearest = picker.nearest(getter, (x, y, z))
    if nearest is None:
        return _select_by_view_pick(adapter, x, y, z, append, mark, entity_type)

    entity, distance = nearest
    if distance > _PICK_TOLERANCE_M:
        kind = entity_type.lower()
        raise LookupError(
            f"No {kind} passes through ({x * 1000:g}, {y * 1000:g}, "
            f"{z * 1000:g}) mm; the nearest is {distance * 1000:.3f} mm away. "
            f"Give a point on the {kind} itself."
        )
    return picker.select(entity, append, mark)

_select_named_feature

_select_named_feature(adapter: Any, name: str, mark: int, append: bool) -> bool

Select a named feature under a specific selection mark via Select2.

Sweep and loft rely on selection marks to tell SolidWorks which selection is the profile (1), guide curve (2), or sweep path (4). We resolve the feature with IModelDoc2::FeatureByName and select it with IFeature::Select2(append, mark) — the same proven path the rest of the adapter uses for plane/sketch selection. IModelDocExtension::SelectByID2 is avoided deliberately: late-bound SelectByID2 raises Type mismatch on some SolidWorks builds, whereas FeatureByName + Select2 is reliable, works for sketches and reference curves such as a helix, and needs no entity-type string.

Parameters:

Name Type Description Default
adapter Any

A connected adapter with a valid currentModel.

required
name str

Feature name (e.g. "Sketch1" or "Helix/Spiral1"). Any @document qualifier is stripped before lookup. A default plane ("Top Plane", "Right"...) or the origin is found by its place in the tree, in any language (#262, fixed in 2.2.0).

required
mark int

Selection mark — 1=profile, 2=guide curve, 4=sweep path.

required
append bool

True to add to the current selection set, False to replace it.

required

Returns:

Name Type Description
bool bool

True when the feature was found and selected.

Source code in src/solidworks_mcp/adapters/solidworks/features.py
def _select_named_feature(
    adapter: Any,
    name: str,
    mark: int,
    append: bool,
) -> bool:
    """Select a named feature under a specific selection mark via ``Select2``.

    Sweep and loft rely on selection marks to tell SolidWorks which selection
    is the profile (1), guide curve (2), or sweep path (4).  We resolve the
    feature with ``IModelDoc2::FeatureByName`` and select it with
    ``IFeature::Select2(append, mark)`` — the same proven path the rest of the
    adapter uses for plane/sketch selection.  ``IModelDocExtension::SelectByID2``
    is avoided deliberately: late-bound ``SelectByID2`` raises
    ``Type mismatch`` on some SolidWorks builds, whereas ``FeatureByName`` +
    ``Select2`` is reliable, works for sketches *and* reference curves such as
    a helix, and needs no entity-type string.

    Args:
        adapter: A connected adapter with a valid ``currentModel``.
        name: Feature name (e.g. ``"Sketch1"`` or ``"Helix/Spiral1"``).  Any
            ``@document`` qualifier is stripped before lookup. A default
            plane (``"Top Plane"``, ``"Right"``...) or the origin is found by
            its place in the tree, in any language (#262, fixed in 2.2.0).
        mark: Selection mark — 1=profile, 2=guide curve, 4=sweep path.
        append: ``True`` to add to the current selection set, ``False`` to
            replace it.

    Returns:
        bool: ``True`` when the feature was found and selected.
    """
    bare = entity_name(adapter, name.split("@", 1)[0])
    feature = adapter._attempt(
        lambda: adapter.currentModel.FeatureByName(bare), default=None
    )
    if not feature:
        return False
    return bool(adapter._attempt(lambda: feature.Select2(append, mark), default=False))

_sketch_points

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

The points of an ISketch, [x, y, z] in sketch metres.

Source code in src/solidworks_mcp/adapters/solidworks/part_features.py
def _sketch_points(adapter: Any, sketch: Any) -> list[list[float]]:
    """The points of an ``ISketch``, ``[x, y, z]`` in sketch metres."""
    points = as_list(adapter._attempt(lambda: sketch.GetSketchPoints2(), default=None))
    return [[float(p.X), float(p.Y), float(p.Z)] for p in points]

_stored_thread

_stored_thread(adapter: Any, feature: Any) -> dict[str, str | None]

The size and callout SolidWorks stored for a cosmetic thread.

Source code in src/solidworks_mcp/adapters/solidworks/part_features.py
def _stored_thread(adapter: Any, feature: Any) -> dict[str, str | None]:
    """The size and callout SolidWorks stored for a cosmetic thread."""
    data = adapter._attempt(
        lambda: sw_type_info.flagged(
            sw_type_info.flagged(feature, "IFeature").GetDefinition(),
            "ICosmeticThreadFeatureData",
        ),
        default=None,
    )
    size = adapter._attempt(lambda: data.Size, default=None) if data else None
    callout = (
        adapter._attempt(lambda: data.ThreadCallout, default=None) if data else None
    )
    return {
        "stored_size": str(size) if size else None,
        "callout": str(callout) if callout else None,
    }

_through_depth_m

_through_depth_m(adapter: Any, model: Any) -> float

A blind depth that passes through the part: its box diagonal + 1 mm.

SolidWorks refuses through_all for a simple Hole Wizard hole (seen live, every argument variant), so such a hole is made blind this deep.

Parameters:

Name Type Description Default
adapter Any

The connected adapter.

required
model Any

The active part.

required

Returns:

Type Description
float

The depth in metres; 1 m when the part box can't be read.

Source code in src/solidworks_mcp/adapters/solidworks/part_features.py
def _through_depth_m(adapter: Any, model: Any) -> float:
    """A blind depth that passes through the part: its box diagonal + 1 mm.

    SolidWorks refuses ``through_all`` for a simple Hole Wizard hole (seen
    live, every argument variant), so such a hole is made blind this deep.

    Args:
        adapter: The connected adapter.
        model: The active part.

    Returns:
        The depth in metres; 1 m when the part box can't be read.
    """
    part = sw_type_info.flagged(model, "IPartDoc")
    box = as_list(adapter._attempt(lambda: part.GetPartBox(True), default=None))
    if len(box) < 6:
        return 1.0
    corners = [float(v) for v in box[:6]]
    return math.dist(corners[:3], corners[3:]) + 0.001

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

_with_volume_change

_with_volume_change(result: AdapterResult[dict[str, Any]], before: float, after: float) -> AdapterResult[dict[str, Any]]

A pattern or mirror's result, with the volume it changed.

Parameters:

Name Type Description Default
result AdapterResult[dict[str, Any]]

The feature call's successful result.

required
before float

The part's volume before, in mm³.

required
after float

The part's volume after, in mm³.

required

Returns:

Type Description
AdapterResult[dict[str, Any]]

AdapterResult[dict[str, Any]]: result's data plus

AdapterResult[dict[str, Any]]

volume_before, volume_after, volume_change (negative for a

AdapterResult[dict[str, Any]]

cut) and volume_ratio.

Source code in src/solidworks_mcp/adapters/solidworks/features.py
def _with_volume_change(
    result: AdapterResult[dict[str, Any]], before: float, after: float
) -> AdapterResult[dict[str, Any]]:
    """A pattern or mirror's result, with the volume it changed.

    Args:
        result: The feature call's successful result.
        before: The part's volume before, in mm³.
        after: The part's volume after, in mm³.

    Returns:
        AdapterResult[dict[str, Any]]: ``result``'s data plus
        ``volume_before``, ``volume_after``, ``volume_change`` (negative for a
        cut) and ``volume_ratio``.
    """
    data = dict(result.data or {})
    data["volume_before"] = before
    data["volume_after"] = after
    data["volume_change"] = after - before
    # A first feature (a base flange) starts from nothing: no ratio.
    data["volume_ratio"] = round(after / before, 6) if before else None
    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data=data,
        execution_time=result.execution_time,
    )

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]

collect_rebuild_issues

collect_rebuild_issues(adapter: Any, model: Any) -> list[RawRebuildIssue]

Return every rebuild error/warning on model after a rebuild.

Parameters:

Name Type Description Default
adapter Any

A connected adapter (for _attempt).

required
model Any

The active IModelDoc2.

required

Returns:

Type Description
list[RawRebuildIssue]

list[RawRebuildIssue]: Empty when the model is clean.

Source code in src/solidworks_mcp/adapters/solidworks/rebuild_inspector.py
def collect_rebuild_issues(adapter: Any, model: Any) -> list[RawRebuildIssue]:
    """Return every rebuild error/warning on ``model`` after a rebuild.

    Args:
        adapter: A connected adapter (for ``_attempt``).
        model: The active ``IModelDoc2``.

    Returns:
        list[RawRebuildIssue]: Empty when the model is clean.
    """
    issues = _from_whats_wrong(adapter, model)
    if issues is None:
        issues = _from_tree_walk(adapter, model)
    return issues

describe

describe(library: HoleLibrary, standard: str, hole_type: str, fastener: str | None = None, size: str | None = None) -> dict[str, Any]

What list_hole_sizes returns.

No size: the hole types of the kind (only fastener's when given), each with its enabled sizes. With size: that size's dimensions, in the hole type fastener names or the default one for the kind.

Raises:

Type Description
HoleSizeError

For an unknown hole type or size.

Source code in src/solidworks_mcp/adapters/solidworks/hole_library.py
def describe(
    library: HoleLibrary,
    standard: str,
    hole_type: str,
    fastener: str | None = None,
    size: str | None = None,
) -> dict[str, Any]:
    """What ``list_hole_sizes`` returns.

    No ``size``: the hole types of the kind (only ``fastener``'s when given),
    each with its enabled sizes. With ``size``: that size's dimensions, in
    the hole type ``fastener`` names or the default one for the kind.

    Raises:
        HoleSizeError: For an unknown hole type or size.
    """
    if size is not None:
        name = fastener or default_fastener(standard, hole_type, size)[0]
        entry = library.find_type(standard, hole_type, name)
        return {
            "standard": standard,
            "hole_type": hole_type,
            "fastener": entry.name,
            "units": "in" if standard == "ansi_inch" else "mm",
            "dimensions": library.dimensions(standard, entry, size),
        }
    types = (
        [library.find_type(standard, hole_type, fastener)]
        if fastener
        else library.hole_types(standard, hole_type)
    )
    return {
        "standard": standard,
        "hole_type": hole_type,
        "units": "in" if standard == "ansi_inch" else "mm",
        "hole_types": [
            {"name": t.name, "sizes": library.sizes(standard, t)} for t in types
        ],
    }

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)

explain

explain(issue: RawRebuildIssue) -> dict[str, Any]

Build the caller-facing diagnostic entry for one rebuild issue.

Parameters:

Name Type Description Default
issue RawRebuildIssue

The raw entry collected from SolidWorks.

required

Returns:

Type Description
dict[str, Any]

dict[str, Any]: feature, type, code, code_name,

dict[str, Any]

severity, description, parents and hint.

Source code in src/solidworks_mcp/adapters/solidworks/rebuild_diagnostics.py
def explain(issue: RawRebuildIssue) -> dict[str, Any]:
    """Build the caller-facing diagnostic entry for one rebuild issue.

    Args:
        issue: The raw entry collected from SolidWorks.

    Returns:
        dict[str, Any]: ``feature``, ``type``, ``code``, ``code_name``,
        ``severity``, ``description``, ``parents`` and ``hint``.
    """
    description, hint = _CODE_HINTS.get(issue.code, ("", ""))
    empty_parent = next(
        (
            p
            for p in issue.parents
            if p.type == "ProfileFeature" and p.segment_count == 0
        ),
        None,
    )
    if empty_parent is not None:
        hint = _EMPTY_SKETCH_HINT.format(name=empty_parent.name)
    elif not hint:
        hint = _TYPE_HINTS.get(issue.type, GENERIC_HINT)
    if not description:
        description = (
            f"{_TYPE_LABELS.get(issue.type, issue.type or 'Feature')} "
            f"'{issue.feature}' failed to rebuild "
            f"({code_name(issue.code)})."
        )
    return {
        "feature": issue.feature,
        "type": issue.type,
        "code": issue.code,
        "code_name": code_name(issue.code),
        "severity": "warning" if issue.is_warning else "error",
        "description": description,
        "parents": [
            {"name": p.name, "type": p.type}
            | (
                {"segment_count": p.segment_count}
                if p.segment_count is not None
                else {}
            )
            for p in issue.parents
        ],
        "hint": hint,
    }

find_library

find_library() -> SqliteHoleLibrary

The installed library.

Raises:

Type Description
HoleLibraryError

Naming every place looked and the setting.

Source code in src/solidworks_mcp/adapters/solidworks/hole_library.py
def find_library() -> SqliteHoleLibrary:
    """The installed library.

    Raises:
        HoleLibraryError: Naming every place looked and the setting.
    """
    tried = candidate_paths()
    for path in tried:
        if path.is_file():
            return load(path)
    where = "; ".join(str(p) for p in tried) or "no SolidWorks install in the registry"
    raise HoleLibraryError(
        f"No Hole Wizard library ({_FILE_NAME}) found. Looked in: {where}. "
        f"Set {LIBRARY_SETTING} to the file's path."
    )

thread_table_size

thread_table_size(size: str, standard: str) -> str

The spelling SolidWorks' thread table has for size.

M8x1.25 is the ISO coarse M8, which the ISO and DIN tables list as M8; any other size (a fine pitch, an inch size) is kept.

Source code in src/solidworks_mcp/adapters/solidworks/part_features.py
def thread_table_size(size: str, standard: str) -> str:
    """The spelling SolidWorks' thread table has for ``size``.

    ``M8x1.25`` is the ISO coarse M8, which the ISO and DIN tables list as
    ``M8``; any other size (a fine pitch, an inch size) is kept.
    """
    if standard not in _METRIC_THREAD_STANDARDS:
        return size
    pitched = re.fullmatch(
        r"\s*[Mm]\s*(\d+(?:\.\d+)?)\s*[xX]\s*(\d+(?:\.\d+)?)\s*", size
    )
    if not pitched:
        return size
    diameter, pitch = float(pitched.group(1)), float(pitched.group(2))
    if ISO_COARSE_PITCH.get(diameter) == pitch:
        return f"M{pitched.group(1)}"
    return size

unchecked

unchecked(standard: str, hole_type: str, size: str, fastener: str | None, reason: str) -> ResolvedHole

The defaults to try when the library can't be read, with a warning.

A named fastener is used only when it is the default for the kind, as its index is otherwise unknown.

Raises:

Type Description
HoleSizeError

For a fastener whose index can't be known.

Source code in src/solidworks_mcp/adapters/solidworks/hole_library.py
def unchecked(
    standard: str, hole_type: str, size: str, fastener: str | None, reason: str
) -> ResolvedHole:
    """The defaults to try when the library can't be read, with a warning.

    A named ``fastener`` is used only when it is the default for the kind,
    as its index is otherwise unknown.

    Raises:
        HoleSizeError: For a ``fastener`` whose index can't be known.
    """
    name, code = default_fastener(standard, hole_type, size)
    if fastener and _fold(fastener) != _fold(name):
        raise HoleSizeError(
            f'The hole type "{fastener}" can\'t be used: {reason} Leave '
            f'`fastener` out to use "{name}".'
        )
    diameter = _bare_diameter(size)
    spelled = (
        f"Ø{diameter:.1f}" if diameter is not None and standard != "ansi_inch" else size
    )
    return ResolvedHole(
        name,
        code,
        spelled,
        f"The size wasn't checked: {reason} The hole was attempted as "
        f'"{name}" {spelled}.',
    )