Skip to content

solidworks_mcp.adapters.factory

solidworks_mcp.adapters.factory

Adapter factory for creating SolidWorks adapters.

Provides centralized adapter creation with configuration-based selection and automatic fallback strategies.

Classes

AdapterFactory

Factory-pattern adapter creator with singleton and fallback strategies.

Manages adapter registration and creation with configuration-based selection. Automatically wraps adapters with decorators (circuit breaker, connection pool) based on configuration. Implements singleton pattern for consistency.

Attributes:

Name Type Description
_adapter_registry dict[AdapterType, type[SolidWorksAdapter]]

The adapter registry value.

_adapters dict[AdapterType, type[SolidWorksAdapter]]

The adapters value.

_instance AdapterFactory | None

The instance value.

Example

factory = AdapterFactory() config = SolidWorksMCPConfig(adapter_type=AdapterType.PYWIN32) adapter = factory.create_adapter(config) await adapter.connect()

Methods:
__new__
__new__() -> AdapterFactory

Initialize or return singleton AdapterFactory instance.

Enforces singleton pattern to ensure single adapter registry and consistent factory behavior across application lifetime.

Returns:

Name Type Description
AdapterFactory AdapterFactory

The result produced by the operation.

Example

factory1 = AdapterFactory() factory2 = AdapterFactory() factory1 is factory2 True

Source code in src/solidworks_mcp/adapters/factory.py
def __new__(cls) -> AdapterFactory:
    """Initialize or return singleton AdapterFactory instance.

    Enforces singleton pattern to ensure single adapter registry and consistent factory
    behavior across application lifetime.

    Returns:
        AdapterFactory: The result produced by the operation.

    Example:
                        >>> factory1 = AdapterFactory()
                        >>> factory2 = AdapterFactory()
                        >>> factory1 is factory2
                        True
    """
    if cls._instance is None:
        cls._instance = super().__new__(cls)
    return cls._instance
create_adapter classmethod
create_adapter(config: SolidWorksMCPConfig) -> SolidWorksAdapter

Create and configure a SolidWorks adapter instance.

Determines the best adapter type based on configuration and environment. Selects implementation, applies wrappers (circuit breaker, connection pool), and returns a fully-initialized adapter ready for connection.

The adapter is automatically downgraded to Mock on non-Windows platforms or when testing is enabled, with fallback to configured type otherwise.

Parameters:

Name Type Description Default
config SolidWorksMCPConfig

Configuration values for the operation.

required

Returns:

Name Type Description
SolidWorksAdapter SolidWorksAdapter

The result produced by the operation.

Example

config = SolidWorksMCPConfig(mock_solidworks=True) adapter = AdapterFactory.create_adapter(config) isinstance(adapter, MockSolidWorksAdapter) True

Source code in src/solidworks_mcp/adapters/factory.py
@classmethod
def create_adapter(cls, config: SolidWorksMCPConfig) -> SolidWorksAdapter:
    """Create and configure a SolidWorks adapter instance.

    Determines the best adapter type based on configuration and environment. Selects
    implementation, applies wrappers (circuit breaker, connection pool), and returns a
    fully-initialized adapter ready for connection.

    The adapter is automatically downgraded to Mock on non-Windows platforms or when testing
    is enabled, with fallback to configured type otherwise.

    Args:
        config (SolidWorksMCPConfig): Configuration values for the operation.

    Returns:
        SolidWorksAdapter: The result produced by the operation.

    Example:
                        >>> config = SolidWorksMCPConfig(mock_solidworks=True)
                        >>> adapter = AdapterFactory.create_adapter(config)
                        >>> isinstance(adapter, MockSolidWorksAdapter)
                        True
    """
    factory = cls()
    return factory._create_adapter_impl(config)
register_adapter classmethod
register_adapter(adapter_type: AdapterType, adapter_class: type[SolidWorksAdapter]) -> None

Register an adapter class for a given adapter type.

Updates the adapter registry to map a specific AdapterType enum value to a SolidWorksAdapter implementation class. Called during initialization to register built- in adapters (PyWin32, Mock, etc.).

Parameters:

Name Type Description Default
adapter_type AdapterType

The adapter type value.

required
adapter_class type[SolidWorksAdapter]

The adapter class value.

required

Returns:

Name Type Description
None None

None.

Example

from adapters.pywin32_adapter import PyWin32Adapter AdapterFactory.register_adapter( ... AdapterType.PYWIN32, PyWin32Adapter ... )

Source code in src/solidworks_mcp/adapters/factory.py
@classmethod
def register_adapter(
    cls, adapter_type: AdapterType, adapter_class: type[SolidWorksAdapter]
) -> None:
    """Register an adapter class for a given adapter type.

    Updates the adapter registry to map a specific AdapterType enum value to a
    SolidWorksAdapter implementation class. Called during initialization to register built-
    in adapters (PyWin32, Mock, etc.).

    Args:
        adapter_type (AdapterType): The adapter type value.
        adapter_class (type[SolidWorksAdapter]): The adapter class value.

    Returns:
        None: None.

    Example:
                        >>> from adapters.pywin32_adapter import PyWin32Adapter
                        >>> AdapterFactory.register_adapter(
                        ...     AdapterType.PYWIN32, PyWin32Adapter
                        ... )
    """
    cls._adapter_registry[adapter_type] = adapter_class

AdapterType

Bases: StrEnum

SolidWorks adapter implementation options.

Attributes:

Name Type Description
EDGE_DOTNET Any

The edge dotnet value.

MOCK Any

The mock value.

POWERSHELL Any

The powershell value.

PYWIN32 Any

The pywin32 value.

VBA Any

The vba value.

MockSolidWorksAdapter

MockSolidWorksAdapter(config: object | None = None)

Bases: SolidWorksAdapter

Mock adapter that simulates SolidWorks operations.

Parameters:

Name Type Description Default
config object | None

Configuration values for the operation. Defaults to None.

None

Attributes:

Name Type Description
_connected Any

The connected value.

_delays Any

The delays value.

_is_connected_proxy Any

The is connected proxy value.

_operation_count Any

The operation count value.

_simulate_errors Any

The simulate errors value.

Initialize the mock solid works adapter.

Parameters:

Name Type Description Default
config object | None

Configuration values for the operation. Defaults to None.

None

Returns:

Name Type Description
None None

None.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
def __init__(self, config: object | None = None) -> None:
    """Initialize the mock solid works adapter.

    Args:
        config (object | None): Configuration values for the operation. Defaults to None.

    Returns:
        None: None.
    """
    super().__init__(config)
    cfg: dict[str, Any] = dict(self.config_dict)
    self._connected = False
    self._current_model: SolidWorksModel | None = None
    self._models: dict[str, SolidWorksModel] = {}
    self._features: dict[str, SolidWorksFeature] = {}
    # Component tree for an Assembly-type current model, keyed by
    # component name. See ``_flatten_assembly_components`` for shape.
    # Empty means "use the canned default fixture" (see list_features).
    self._assembly_components: dict[str, dict[str, Any]] = {}
    self._sketches: dict[str, str] = {}
    self._current_sketch: str | None = None
    # Tracks IDs returned by add_line/add_arc/add_circle/add_centerline/
    # add_rectangle/add_spline so add_sketch_constraint can validate
    # entity1/entity2 the same way the real adapter validates against
    # its sketch-entity registry.
    self._sketch_entity_ids: set[str] = set()
    self._dimensions: dict[str, float] = {}
    # Assembly components inserted via insert_component, keyed by
    # insertion order. See insert_component/list_components/add_mate.
    self._components: list[str] = []
    self._operation_count = 0

    # Configurable simulation delays (in seconds)
    self._delays = {
        "connect": cfg.get("mock_connect_delay", 0.1),
        "model_operation": cfg.get("mock_model_delay", 0.02),
        "feature_operation": cfg.get("mock_feature_delay", 0.03) if cfg else 0.03,
        "sketch_operation": cfg.get("mock_sketch_delay", 0.1),
    }
    self._is_connected_proxy = _BoolCallable(lambda: self._connected)
    self._simulate_errors = bool(cfg.get("simulate_errors", False))
Methods:
__getattribute__
__getattribute__(name: str) -> Any

Build internal getattribute.

Parameters:

Name Type Description Default
name str

The name value.

required

Returns:

Name Type Description
Any Any

The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
def __getattribute__(self, name: str) -> Any:
    """Build internal getattribute.

    Args:
        name (str): The name value.

    Returns:
        Any: The result produced by the operation.
    """
    if name == "is_connected":
        return object.__getattribute__(self, "_is_connected_proxy")
    return object.__getattribute__(self, name)
add_arc async
add_arc(center_x: float, center_y: float, start_x: float, start_y: float, end_x: float, end_y: float) -> AdapterResult[str]

Mock adding a circular arc to sketch.

Parameters:

Name Type Description Default
center_x float

Arc centre X.

required
center_y float

Arc centre Y.

required
start_x float

Arc start point X.

required
start_y float

Arc start point Y.

required
end_x float

Arc end point X.

required
end_y float

Arc end point Y.

required

Returns:

Type Description
AdapterResult[str]

AdapterResult[str]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def add_arc(
    self,
    center_x: float,
    center_y: float,
    start_x: float,
    start_y: float,
    end_x: float,
    end_y: float,
) -> AdapterResult[str]:
    """Mock adding a circular arc to sketch.

    Args:
        center_x (float): Arc centre X.
        center_y (float): Arc centre Y.
        start_x (float): Arc start point X.
        start_y (float): Arc start point Y.
        end_x (float): Arc end point X.
        end_y (float): Arc end point Y.

    Returns:
        AdapterResult[str]: The result produced by the operation.
    """
    if not self._current_sketch:
        return AdapterResult(
            status=AdapterResultStatus.ERROR, error="No active sketch"
        )

    await asyncio.sleep(self._delays["sketch_operation"] / 2)
    self._operation_count += 1

    arc_id = f"Arc_{random.randint(1000, 9999)}"
    self._sketch_entity_ids.add(arc_id)

    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data=arc_id,
        execution_time=self._delays["sketch_operation"] / 2,
    )
add_centerline async
add_centerline(x1: float, y1: float, x2: float, y2: float) -> AdapterResult[str]

Mock adding a construction centerline to sketch.

Parameters:

Name Type Description Default
x1 float

The x1 value.

required
y1 float

The y1 value.

required
x2 float

The x2 value.

required
y2 float

The y2 value.

required

Returns:

Type Description
AdapterResult[str]

AdapterResult[str]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def add_centerline(
    self, x1: float, y1: float, x2: float, y2: float
) -> AdapterResult[str]:
    """Mock adding a construction centerline to sketch.

    Args:
        x1 (float): The x1 value.
        y1 (float): The y1 value.
        x2 (float): The x2 value.
        y2 (float): The y2 value.

    Returns:
        AdapterResult[str]: The result produced by the operation.
    """
    if not self._current_sketch:
        return AdapterResult(
            status=AdapterResultStatus.ERROR, error="No active sketch"
        )

    await asyncio.sleep(self._delays["sketch_operation"] / 2)
    self._operation_count += 1

    centerline_id = f"Centerline_{random.randint(1000, 9999)}"
    self._sketch_entity_ids.add(centerline_id)

    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data=centerline_id,
        execution_time=self._delays["sketch_operation"] / 2,
    )
add_circle async
add_circle(center_x: float, center_y: float, radius: float) -> AdapterResult[str]

Mock adding a circle to sketch.

Parameters:

Name Type Description Default
center_x float

The center x value.

required
center_y float

The center y value.

required
radius float

The radius value.

required

Returns:

Type Description
AdapterResult[str]

AdapterResult[str]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def add_circle(
    self, center_x: float, center_y: float, radius: float
) -> AdapterResult[str]:
    """Mock adding a circle to sketch.

    Args:
        center_x (float): The center x value.
        center_y (float): The center y value.
        radius (float): The radius value.

    Returns:
        AdapterResult[str]: The result produced by the operation.
    """
    if not self._current_sketch:
        return AdapterResult(
            status=AdapterResultStatus.ERROR, error="No active sketch"
        )

    await asyncio.sleep(self._delays["sketch_operation"] / 2)
    self._operation_count += 1

    circle_id = f"Circle{random.randint(1000, 9999)}"
    self._sketch_entity_ids.add(circle_id)

    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data=circle_id,
        execution_time=self._delays["sketch_operation"] / 2,
    )
add_ellipse async
add_ellipse(center_x: float, center_y: float, major_axis: float, minor_axis: float) -> AdapterResult[str]

Mock adding an axis-aligned ellipse to sketch.

Parameters:

Name Type Description Default
center_x float

Ellipse centre X in millimetres.

required
center_y float

Ellipse centre Y in millimetres.

required
major_axis float

Full major-axis length in millimetres.

required
minor_axis float

Full minor-axis length in millimetres.

required

Returns:

Type Description
AdapterResult[str]

AdapterResult[str]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def add_ellipse(
    self,
    center_x: float,
    center_y: float,
    major_axis: float,
    minor_axis: float,
) -> AdapterResult[str]:
    """Mock adding an axis-aligned ellipse to sketch.

    Args:
        center_x (float): Ellipse centre X in millimetres.
        center_y (float): Ellipse centre Y in millimetres.
        major_axis (float): Full major-axis length in millimetres.
        minor_axis (float): Full minor-axis length in millimetres.

    Returns:
        AdapterResult[str]: The result produced by the operation.
    """
    if not self._current_sketch:
        return AdapterResult(
            status=AdapterResultStatus.ERROR, error="No active sketch"
        )

    await asyncio.sleep(self._delays["sketch_operation"] / 2)
    self._operation_count += 1

    ellipse_id = f"Ellipse_{random.randint(1000, 9999)}"
    self._sketch_entity_ids.add(ellipse_id)

    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data=ellipse_id,
        execution_time=self._delays["sketch_operation"] / 2,
    )
add_line async
add_line(x1: float, y1: float, x2: float, y2: float) -> AdapterResult[str]

Mock adding a line to sketch.

Parameters:

Name Type Description Default
x1 float

The x1 value.

required
y1 float

The y1 value.

required
x2 float

The x2 value.

required
y2 float

The y2 value.

required

Returns:

Type Description
AdapterResult[str]

AdapterResult[str]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def add_line(
    self, x1: float, y1: float, x2: float, y2: float
) -> AdapterResult[str]:
    """Mock adding a line to sketch.

    Args:
        x1 (float): The x1 value.
        y1 (float): The y1 value.
        x2 (float): The x2 value.
        y2 (float): The y2 value.

    Returns:
        AdapterResult[str]: The result produced by the operation.
    """
    if not self._current_sketch:
        return AdapterResult(
            status=AdapterResultStatus.ERROR, error="No active sketch"
        )

    await asyncio.sleep(self._delays["sketch_operation"] / 2)
    self._operation_count += 1

    line_id = f"Line{random.randint(1000, 9999)}"
    self._sketch_entity_ids.add(line_id)

    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data=line_id,
        execution_time=self._delays["sketch_operation"] / 2,
    )
add_mate async
add_mate(component_a: str, component_b: str, entity_a: str = 'Front Plane', entity_b: str = 'Front Plane', mate_type: str = 'coincident', alignment: str = 'aligned', distance: float = 0.0, angle: float = 0.0) -> AdapterResult[dict[str, Any]]

Mock mating two components in the active assembly.

Parameters:

Name Type Description Default
component_a str

First component instance name.

required
component_b str

Second component instance name.

required
entity_a str

Named feature on the first component. Defaults to "Front Plane".

'Front Plane'
entity_b str

Named feature on the second component. Defaults to "Front Plane".

'Front Plane'
mate_type str

Mate type. Defaults to "coincident".

'coincident'
alignment str

Mate alignment. Defaults to "aligned".

'aligned'
distance float

Distance in millimetres, for a distance mate. Defaults to 0.0.

0.0
angle float

Angle in degrees, for an angle mate. Defaults to 0.0.

0.0

Returns:

Type Description
AdapterResult[dict[str, Any]]

AdapterResult[dict[str, Any]]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def add_mate(
    self,
    component_a: str,
    component_b: str,
    entity_a: str = "Front Plane",
    entity_b: str = "Front Plane",
    mate_type: str = "coincident",
    alignment: str = "aligned",
    distance: float = 0.0,
    angle: float = 0.0,
) -> AdapterResult[dict[str, Any]]:
    """Mock mating two components in the active assembly.

    Args:
        component_a (str): First component instance name.
        component_b (str): Second component instance name.
        entity_a (str): Named feature on the first component. Defaults to
            "Front Plane".
        entity_b (str): Named feature on the second component. Defaults to
            "Front Plane".
        mate_type (str): Mate type. Defaults to "coincident".
        alignment (str): Mate alignment. Defaults to "aligned".
        distance (float): Distance in millimetres, for a distance mate.
            Defaults to 0.0.
        angle (float): Angle in degrees, for an angle mate. Defaults to 0.0.

    Returns:
        AdapterResult[dict[str, Any]]: The result produced by the operation.
    """
    known_mate_types = {
        "coincident",
        "concentric",
        "perpendicular",
        "parallel",
        "tangent",
        "distance",
        "angle",
    }
    if mate_type not in known_mate_types:
        return AdapterResult(
            status=AdapterResultStatus.ERROR,
            error=(
                f"Unknown mate type '{mate_type}'. "
                f"Use one of: {', '.join(sorted(known_mate_types))}."
            ),
        )

    await asyncio.sleep(self._delays["model_operation"])
    self._operation_count += 1

    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data={
            "mate_type": mate_type,
            "alignment": alignment,
            "components": [component_a, component_b],
            "entities": [entity_a, entity_b],
            "distance": distance or None,
            "angle": angle or None,
            # The real adapter fills these by comparing every component's
            # Transform2 before and after the mate. The mock has no
            # geometry to move, so it reports "not determinable" rather
            # than True: this field exists precisely so a caller can tell
            # a mate that positioned something from one SolidWorks
            # accepted and ignored, and a mock that always answers True
            # would make that check useless wherever mock mode is used.
            "moved_components": [],
            "geometry_moved": None,
        },
        execution_time=self._delays["model_operation"],
    )
add_polygon async
add_polygon(center_x: float, center_y: float, radius: float, sides: int) -> AdapterResult[str]

Mock adding a regular polygon to sketch.

Parameters:

Name Type Description Default
center_x float

Polygon centre X in millimetres.

required
center_y float

Polygon centre Y in millimetres.

required
radius float

Circumradius in millimetres (distance from centre to each vertex; matches the real adapter's CreatePolygon(..., Inscribed=True) semantics).

required
sides int

Number of polygon sides.

required

Returns:

Type Description
AdapterResult[str]

AdapterResult[str]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def add_polygon(
    self, center_x: float, center_y: float, radius: float, sides: int
) -> AdapterResult[str]:
    """Mock adding a regular polygon to sketch.

    Args:
        center_x (float): Polygon centre X in millimetres.
        center_y (float): Polygon centre Y in millimetres.
        radius (float): Circumradius in millimetres (distance from centre
            to each vertex; matches the real adapter's
            ``CreatePolygon(..., Inscribed=True)`` semantics).
        sides (int): Number of polygon sides.

    Returns:
        AdapterResult[str]: The result produced by the operation.
    """
    if not self._current_sketch:
        return AdapterResult(
            status=AdapterResultStatus.ERROR, error="No active sketch"
        )

    await asyncio.sleep(self._delays["sketch_operation"] / 2)
    self._operation_count += 1

    # ID format mirrors the real PyWin32 adapter, which uses
    # ``_register_sketch_entity("Polygon", ...)`` (counter-based) so the
    # returned ID is a valid input to downstream sketch_linear_pattern /
    # sketch_circular_pattern / sketch_mirror / sketch_offset calls.
    polygon_id = f"Polygon_{len(self._sketch_entity_ids) + 1}"
    self._sketch_entity_ids.add(polygon_id)
    _ = sides  # informational only; the sides count is no longer part of the ID

    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data=polygon_id,
        execution_time=self._delays["sketch_operation"] / 2,
    )
add_rectangle async
add_rectangle(x1: float, y1: float, x2: float, y2: float) -> AdapterResult[str]

Mock adding a rectangle to sketch.

Parameters:

Name Type Description Default
x1 float

The x1 value.

required
y1 float

The y1 value.

required
x2 float

The x2 value.

required
y2 float

The y2 value.

required

Returns:

Type Description
AdapterResult[str]

AdapterResult[str]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def add_rectangle(
    self, x1: float, y1: float, x2: float, y2: float
) -> AdapterResult[str]:
    """Mock adding a rectangle to sketch.

    Args:
        x1 (float): The x1 value.
        y1 (float): The y1 value.
        x2 (float): The x2 value.
        y2 (float): The y2 value.

    Returns:
        AdapterResult[str]: The result produced by the operation.
    """
    if not self._current_sketch:
        return AdapterResult(
            status=AdapterResultStatus.ERROR, error="No active sketch"
        )

    await asyncio.sleep(self._delays["sketch_operation"])
    self._operation_count += 1

    rect_id = f"Rectangle{random.randint(1000, 9999)}"
    self._sketch_entity_ids.add(rect_id)

    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data=rect_id,
        execution_time=self._delays["sketch_operation"],
    )
add_sketch_constraint async
add_sketch_constraint(entity1: str, entity2: str | None, relation_type: str, entity3: str | None = None) -> AdapterResult[str]

Mock adding a geometric constraint between sketch entities.

Parameters:

Name Type Description Default
entity1 str

Primary sketch-entity ID.

required
entity2 str | None

Secondary sketch-entity ID, or None for single-entity relations (horizontal, vertical, fix).

required
relation_type str

Constraint name (see RELATION_NAME_MAP).

required
entity3 str | None

Third entity ID — only used by the symmetric relation (the centerline of symmetry). All other relation types reject a non-null entity3.

None

Returns:

Type Description
AdapterResult[str]

AdapterResult[str]: SUCCESS with a placeholder constraint ID, or ERROR if no active sketch, the relation_type is unsupported, arity is wrong, or an entity ID is unknown.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def add_sketch_constraint(
    self,
    entity1: str,
    entity2: str | None,
    relation_type: str,
    entity3: str | None = None,
) -> AdapterResult[str]:
    """Mock adding a geometric constraint between sketch entities.

    Args:
        entity1 (str): Primary sketch-entity ID.
        entity2 (str | None): Secondary sketch-entity ID, or None for
            single-entity relations (horizontal, vertical, fix).
        relation_type (str): Constraint name (see RELATION_NAME_MAP).
        entity3 (str | None): Third entity ID — only used by the
            ``symmetric`` relation (the centerline of symmetry). All
            other relation types reject a non-null ``entity3``.

    Returns:
        AdapterResult[str]: SUCCESS with a placeholder constraint ID, or
            ERROR if no active sketch, the relation_type is unsupported,
            arity is wrong, or an entity ID is unknown.
    """
    if not self._current_sketch:
        return AdapterResult(
            status=AdapterResultStatus.ERROR, error="No active sketch"
        )

    rt_norm = (relation_type or "").strip().lower()
    if rt_norm not in RELATION_NAME_MAP:
        supported = ", ".join(sorted(RELATION_NAME_MAP))
        return AdapterResult(
            status=AdapterResultStatus.ERROR,
            error=(
                f"Unsupported relation type '{relation_type}'. "
                f"Supported: {supported}"
            ),
        )

    # Arity validation — mirror the real adapter
    if rt_norm == "symmetric":
        if entity2 is None or entity3 is None:
            return AdapterResult(
                status=AdapterResultStatus.ERROR,
                error=(
                    f"Relation '{relation_type}' requires entity1, "
                    "entity2, and entity3 (the centerline of symmetry)"
                ),
            )
    elif entity3 is not None:
        return AdapterResult(
            status=AdapterResultStatus.ERROR,
            error=(
                f"Relation '{relation_type}' does not accept entity3 — "
                "only 'symmetric' takes a third entity (the centerline)"
            ),
        )

    # Validate entity IDs against the in-process sketch-entity registry
    # so the mock surfaces the same "Unknown sketch entity" error as the
    # real adapter (which checks adapter._sketch_entities).
    for ent in (entity1, entity2, entity3):
        if ent is not None and ent not in self._sketch_entity_ids:
            return AdapterResult(
                status=AdapterResultStatus.ERROR,
                error=(
                    f"Unknown sketch entity '{ent}'. Use IDs returned by "
                    "add_line/add_arc/add_circle/add_spline/add_centerline."
                ),
            )

    await asyncio.sleep(self._delays["sketch_operation"] / 2)
    self._operation_count += 1

    constraint_id = f"Constraint_{relation_type}_{random.randint(1000, 9999)}"

    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data=constraint_id,
        execution_time=self._delays["sketch_operation"] / 2,
    )
add_sketch_line async
add_sketch_line(x1: float, y1: float, x2: float, y2: float, construction: bool = False) -> AdapterResult[dict[str, Any]]

Legacy compatibility wrapper around add_line.

Parameters:

Name Type Description Default
x1 float

The x1 value.

required
y1 float

The y1 value.

required
x2 float

The x2 value.

required
y2 float

The y2 value.

required
construction bool

The construction value. Defaults to False.

False

Returns:

Type Description
AdapterResult[dict[str, Any]]

AdapterResult[dict[str, Any]]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def add_sketch_line(
    self,
    x1: float,
    y1: float,
    x2: float,
    y2: float,
    construction: bool = False,
) -> AdapterResult[dict[str, Any]]:
    """Legacy compatibility wrapper around add_line.

    Args:
        x1 (float): The x1 value.
        y1 (float): The y1 value.
        x2 (float): The x2 value.
        y2 (float): The y2 value.
        construction (bool): The construction value. Defaults to False.

    Returns:
        AdapterResult[dict[str, Any]]: The result produced by the operation.
    """
    result = await self.add_line(x1, y1, x2, y2)
    if not result.is_success:
        return AdapterResult(
            status=result.status,
            error=result.error,
            execution_time=result.execution_time,
        )
    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data={
            "id": result.data,
            "start": {"x": x1, "y": y1},
            "end": {"x": x2, "y": y2},
            "construction": construction,
        },
        execution_time=result.execution_time,
    )
add_spline async
add_spline(points: list[dict[str, float]]) -> AdapterResult[str]

Mock adding a NURBS spline through the supplied points.

Parameters:

Name Type Description Default
points list[dict[str, float]]

Ordered control points with "x" / "y" keys. Minimum 2 points.

required

Returns:

Type Description
AdapterResult[str]

AdapterResult[str]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def add_spline(self, points: list[dict[str, float]]) -> AdapterResult[str]:
    """Mock adding a NURBS spline through the supplied points.

    Args:
        points (list[dict[str, float]]): Ordered control points with
            ``"x"`` / ``"y"`` keys. Minimum 2 points.

    Returns:
        AdapterResult[str]: The result produced by the operation.
    """
    if not self._current_sketch:
        return AdapterResult(
            status=AdapterResultStatus.ERROR, error="No active sketch"
        )
    if len(points) < 2:
        return AdapterResult(
            status=AdapterResultStatus.ERROR,
            error="add_spline requires at least 2 points",
        )
    # Match the real adapter's point contract: each dict must carry
    # both ``x`` and ``y`` keys, or the live impl raises KeyError on
    # ``point["x"]``. Validating here keeps mock/live parity so tests
    # that pass against the mock won't fail live on malformed input.
    for index, point in enumerate(points):
        if not isinstance(point, dict) or "x" not in point or "y" not in point:
            return AdapterResult(
                status=AdapterResultStatus.ERROR,
                error=(
                    f"add_spline point at index {index} is missing "
                    "required 'x' and/or 'y' keys"
                ),
            )

    await asyncio.sleep(self._delays["sketch_operation"] / 2)
    self._operation_count += 1

    spline_id = f"Spline_{random.randint(1000, 9999)}"
    self._sketch_entity_ids.add(spline_id)

    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data=spline_id,
        execution_time=self._delays["sketch_operation"] / 2,
    )
check_sketch_fully_defined async
check_sketch_fully_defined(sketch_name: str | None = None) -> AdapterResult[dict[str, Any]]

Mock check for sketch definition status.

Parameters:

Name Type Description Default
sketch_name str | None

Optional sketch name to inspect. Defaults to None.

None

Returns:

Type Description
AdapterResult[dict[str, Any]]

AdapterResult[dict[str, Any]]: Definition status payload.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def check_sketch_fully_defined(
    self, sketch_name: str | None = None
) -> AdapterResult[dict[str, Any]]:
    """Mock check for sketch definition status.

    Args:
        sketch_name (str | None): Optional sketch name to inspect. Defaults to None.

    Returns:
        AdapterResult[dict[str, Any]]: Definition status payload.
    """
    if not self._current_model:
        return AdapterResult(
            status=AdapterResultStatus.ERROR,
            error="No active model",
        )

    await asyncio.sleep(self._delays["sketch_operation"] / 3)
    self._operation_count += 1

    resolved_name = sketch_name or self._current_sketch or "Sketch1"
    if sketch_name and sketch_name not in self._sketches:
        return AdapterResult(
            status=AdapterResultStatus.ERROR,
            error=f"Sketch not found: {sketch_name}",
        )

    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data={
            "sketch_name": resolved_name,
            "is_fully_defined": True,
            "definition_state": "fully_defined",
            "source": "mock",
            "raw_status": True,
        },
        execution_time=self._delays["sketch_operation"] / 3,
    )
close_model async
close_model(save: bool = False) -> AdapterResult[None]

Mock closing the current model.

Parameters:

Name Type Description Default
save bool

The save value. Defaults to False.

False

Returns:

Type Description
AdapterResult[None]

AdapterResult[None]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def close_model(self, save: bool = False) -> AdapterResult[None]:
    """Mock closing the current model.

    Args:
        save (bool): The save value. Defaults to False.

    Returns:
        AdapterResult[None]: The result produced by the operation.
    """
    if not self._current_model:
        return AdapterResult(
            status=AdapterResultStatus.WARNING, error="No active model to close"
        )

    await asyncio.sleep(self._delays["model_operation"] / 2)
    self._operation_count += 1

    if save:
        # Simulate save operation
        await asyncio.sleep(self._delays["model_operation"])

    self._current_model = None

    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data=None,
        execution_time=self._delays["model_operation"],
    )
connect async
connect() -> None

Mock connection to SolidWorks.

Returns:

Name Type Description
None None

None.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def connect(self) -> None:
    """Mock connection to SolidWorks.

    Returns:
        None: None.
    """
    await asyncio.sleep(self._delays["connect"])
    self._connected = True

    # Initialize some sample data
    self._dimensions = {
        "D1@Sketch1": 10.0,
        "D2@Sketch1": 20.0,
        "D1@Boss-Extrude1": 50.0,
    }
create_assembly async
create_assembly(name: str | None = None) -> AdapterResult[SolidWorksModel]

Mock creating a new assembly.

Parameters:

Name Type Description Default
name str | None

The name value. Defaults to None.

None

Returns:

Type Description
AdapterResult[SolidWorksModel]

AdapterResult[SolidWorksModel]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def create_assembly(
    self, name: str | None = None
) -> AdapterResult[SolidWorksModel]:
    """Mock creating a new assembly.

    Args:
        name (str | None): The name value. Defaults to None.

    Returns:
        AdapterResult[SolidWorksModel]: The result produced by the operation.
    """
    if not self._connected:
        return AdapterResult(
            status=AdapterResultStatus.ERROR, error="Not connected to SolidWorks"
        )

    await asyncio.sleep(self._delays["model_operation"])
    self._operation_count += 1

    model_id = name or f"Assembly{len(self._models) + 1}"
    model = SolidWorksModel(
        path=f"Mock://{model_id}.sldasm",
        name=f"{model_id}",
        type="Assembly",
        is_active=True,
        configuration="Default",
        properties={"created": datetime.now().isoformat(), "mock": True},
    )

    self._current_model = model
    self._models[model.path] = model

    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data=model,
        execution_time=self._delays["model_operation"],
    )
create_drawing async
create_drawing(name: str | None = None) -> AdapterResult[SolidWorksModel]

Mock creating a new drawing.

Parameters:

Name Type Description Default
name str | None

The name value. Defaults to None.

None

Returns:

Type Description
AdapterResult[SolidWorksModel]

AdapterResult[SolidWorksModel]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def create_drawing(
    self, name: str | None = None
) -> AdapterResult[SolidWorksModel]:
    """Mock creating a new drawing.

    Args:
        name (str | None): The name value. Defaults to None.

    Returns:
        AdapterResult[SolidWorksModel]: The result produced by the operation.
    """
    if not self._connected:
        return AdapterResult(
            status=AdapterResultStatus.ERROR, error="Not connected to SolidWorks"
        )

    await asyncio.sleep(self._delays["model_operation"])
    self._operation_count += 1

    model_id = name or f"Drawing{len(self._models) + 1}"
    model = SolidWorksModel(
        path=f"Mock://{model_id}.slddrw",
        name=f"{model_id}",
        type="Drawing",
        is_active=True,
        configuration="Default",
        properties={"created": datetime.now().isoformat(), "mock": True},
    )

    self._current_model = model
    self._models[model.path] = model

    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data=model,
        execution_time=self._delays["model_operation"],
    )
create_extrusion async
create_extrusion(params: ExtrusionParameters | str, depth: float | None = None, direction: str | None = None) -> AdapterResult[SolidWorksFeature]

Mock creating an extrusion feature.

Parameters:

Name Type Description Default
params ExtrusionParameters | str

The params value.

required
depth float | None

The depth value. Defaults to None.

None
direction str | None

The direction value. Defaults to None.

None

Returns:

Type Description
AdapterResult[SolidWorksFeature]

AdapterResult[SolidWorksFeature]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def create_extrusion(
    self,
    params: ExtrusionParameters | str,
    depth: float | None = None,
    direction: str | None = None,
) -> AdapterResult[SolidWorksFeature]:
    """Mock creating an extrusion feature.

    Args:
        params (ExtrusionParameters | str): The params value.
        depth (float | None): The depth value. Defaults to None.
        direction (str | None): The direction value. Defaults to None.

    Returns:
        AdapterResult[SolidWorksFeature]: The result produced by the operation.
    """
    if not self._current_model:
        return AdapterResult(
            status=AdapterResultStatus.ERROR, error="No active model"
        )

    if isinstance(params, str):
        params = ExtrusionParameters(depth=depth or 0.0)

    await asyncio.sleep(self._delays["feature_operation"])
    self._operation_count += 1

    feature_id = f"Boss-Extrude{len(self._features) + 1}"
    feature = SolidWorksFeature(
        name=feature_id,
        type="Extrusion",
        id=str(uuid.uuid4()),
        parameters={
            "depth": params.depth,
            "direction": direction or "blind",
            "draft_angle": params.draft_angle,
            "reverse_direction": params.reverse_direction,
            "both_directions": params.both_directions,
            "thin_feature": params.thin_feature,
            "thin_thickness": params.thin_thickness,
        },
        properties={"created": datetime.now().isoformat(), "mock": True},
    )

    feature_key = feature.id or feature.name
    self._features[feature_key] = feature

    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data=feature,
        execution_time=self._delays["feature_operation"],
    )
create_loft async
create_loft(params: LoftParameters) -> AdapterResult[SolidWorksFeature]

Mock creating a loft feature.

Parameters:

Name Type Description Default
params LoftParameters

The params value.

required

Returns:

Type Description
AdapterResult[SolidWorksFeature]

AdapterResult[SolidWorksFeature]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def create_loft(
    self, params: LoftParameters
) -> AdapterResult[SolidWorksFeature]:
    """Mock creating a loft feature.

    Args:
        params (LoftParameters): The params value.

    Returns:
        AdapterResult[SolidWorksFeature]: The result produced by the operation.
    """
    if not self._current_model:
        return AdapterResult(
            status=AdapterResultStatus.ERROR, error="No active model"
        )

    await asyncio.sleep(self._delays["feature_operation"])
    self._operation_count += 1

    feature_id = f"Boss-Loft{len(self._features) + 1}"
    feature = SolidWorksFeature(
        name=feature_id,
        type="Loft",
        id=str(uuid.uuid4()),
        parameters={
            "profiles": params.profiles,
            "guide_curves": params.guide_curves,
            "start_tangent": params.start_tangent,
            "end_tangent": params.end_tangent,
        },
        properties={"created": datetime.now().isoformat(), "mock": True},
    )

    feature_key = feature.id or feature.name
    self._features[feature_key] = feature

    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data=feature,
        execution_time=self._delays["feature_operation"],
    )
create_part async
create_part(name: str | None = None, units: str | None = None) -> AdapterResult[SolidWorksModel]

Mock creating a new part.

Parameters:

Name Type Description Default
name str | None

The name value. Defaults to None.

None
units str | None

The units value. Defaults to None.

None

Returns:

Type Description
AdapterResult[SolidWorksModel]

AdapterResult[SolidWorksModel]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def create_part(
    self, name: str | None = None, units: str | None = None
) -> AdapterResult[SolidWorksModel]:
    """Mock creating a new part.

    Args:
        name (str | None): The name value. Defaults to None.
        units (str | None): The units value. Defaults to None.

    Returns:
        AdapterResult[SolidWorksModel]: The result produced by the operation.
    """
    if not self._connected:
        return AdapterResult(
            status=AdapterResultStatus.ERROR, error="Not connected to SolidWorks"
        )

    await asyncio.sleep(self._delays["model_operation"])
    self._operation_count += 1

    model_id = name or f"Part{len(self._models) + 1}"
    model = SolidWorksModel(
        path=f"Mock://{model_id}.sldprt",
        name=f"{model_id}",
        type="Part",
        is_active=True,
        configuration="Default",
        properties={
            "created": datetime.now().isoformat(),
            "mock": True,
            "units": units or "mm",
        },
    )

    self._current_model = model
    self._models[model.path] = model

    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data=model,
        execution_time=self._delays["model_operation"],
    )
create_revolve async
create_revolve(params: RevolveParameters) -> AdapterResult[SolidWorksFeature]

Mock creating a revolve feature.

Parameters:

Name Type Description Default
params RevolveParameters

The params value.

required

Returns:

Type Description
AdapterResult[SolidWorksFeature]

AdapterResult[SolidWorksFeature]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def create_revolve(
    self, params: RevolveParameters
) -> AdapterResult[SolidWorksFeature]:
    """Mock creating a revolve feature.

    Args:
        params (RevolveParameters): The params value.

    Returns:
        AdapterResult[SolidWorksFeature]: The result produced by the operation.
    """
    if not self._current_model:
        return AdapterResult(
            status=AdapterResultStatus.ERROR, error="No active model"
        )

    await asyncio.sleep(self._delays["feature_operation"])
    self._operation_count += 1

    feature_id = f"Boss-Revolve{len(self._features) + 1}"
    feature = SolidWorksFeature(
        name=feature_id,
        type="Revolve",
        id=str(uuid.uuid4()),
        parameters={
            "angle": params.angle,
            "reverse_direction": params.reverse_direction,
            "both_directions": params.both_directions,
            "thin_feature": params.thin_feature,
            "thin_thickness": params.thin_thickness,
        },
        properties={"created": datetime.now().isoformat(), "mock": True},
    )

    feature_key = feature.id or feature.name
    self._features[feature_key] = feature

    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data=feature,
        execution_time=self._delays["feature_operation"],
    )
create_sketch async
create_sketch(plane: str) -> AdapterResult[dict[str, Any]]

Mock creating a sketch.

Parameters:

Name Type Description Default
plane str

The plane value.

required

Returns:

Type Description
AdapterResult[dict[str, Any]]

AdapterResult[dict[str, Any]]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def create_sketch(self, plane: str) -> AdapterResult[dict[str, Any]]:  # type: ignore[override]
    """Mock creating a sketch.

    Args:
        plane (str): The plane value.

    Returns:
        AdapterResult[dict[str, Any]]: The result produced by the operation.
    """
    if not self._current_model:
        # Legacy tests start sketching immediately after connect.
        await self.create_part()

    await asyncio.sleep(self._delays["sketch_operation"])
    self._operation_count += 1

    sketch_id = f"Sketch{len(self._sketches) + 1}"
    self._sketches[sketch_id] = plane
    self._current_sketch = sketch_id

    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data={
            "id": sketch_id,
            "name": sketch_id,
            "sketch_name": sketch_id,
            "plane": plane,
        },
        execution_time=self._delays["sketch_operation"],
    )
create_sweep async
create_sweep(params: SweepParameters) -> AdapterResult[SolidWorksFeature]

Mock creating a sweep feature.

Parameters:

Name Type Description Default
params SweepParameters

The params value.

required

Returns:

Type Description
AdapterResult[SolidWorksFeature]

AdapterResult[SolidWorksFeature]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def create_sweep(
    self, params: SweepParameters
) -> AdapterResult[SolidWorksFeature]:
    """Mock creating a sweep feature.

    Args:
        params (SweepParameters): The params value.

    Returns:
        AdapterResult[SolidWorksFeature]: The result produced by the operation.
    """
    if not self._current_model:
        return AdapterResult(
            status=AdapterResultStatus.ERROR, error="No active model"
        )

    await asyncio.sleep(self._delays["feature_operation"])
    self._operation_count += 1

    feature_id = f"Boss-Sweep{len(self._features) + 1}"
    feature = SolidWorksFeature(
        name=feature_id,
        type="Sweep",
        id=str(uuid.uuid4()),
        parameters={
            "path": params.path,
            "twist_along_path": params.twist_along_path,
            "twist_angle": params.twist_angle,
        },
        properties={"created": datetime.now().isoformat(), "mock": True},
    )

    feature_key = feature.id or feature.name
    self._features[feature_key] = feature

    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data=feature,
        execution_time=self._delays["feature_operation"],
    )
disconnect async
disconnect() -> None

Mock disconnection from SolidWorks.

Returns:

Name Type Description
None None

None.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def disconnect(self) -> None:
    """Mock disconnection from SolidWorks.

    Returns:
        None: None.
    """
    self._connected = False
    self._current_model = None
    self._models.clear()
    self._features.clear()
    self._sketches.clear()
    self._current_sketch = None
exit_sketch async
exit_sketch() -> AdapterResult[None]

Mock exiting sketch mode.

Returns:

Type Description
AdapterResult[None]

AdapterResult[None]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def exit_sketch(self) -> AdapterResult[None]:
    """Mock exiting sketch mode.

    Returns:
        AdapterResult[None]: The result produced by the operation.
    """
    if not self._current_sketch:
        return AdapterResult(
            status=AdapterResultStatus.WARNING, error="No active sketch to exit"
        )

    await asyncio.sleep(self._delays["sketch_operation"] / 2)
    self._current_sketch = None

    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data=None,
        execution_time=self._delays["sketch_operation"] / 2,
    )
export_file async
export_file(file_path: str, format_type: str) -> AdapterResult[None]

Mock exporting a file.

Parameters:

Name Type Description Default
file_path str

Path to the target file.

required
format_type str

The format type value.

required

Returns:

Type Description
AdapterResult[None]

AdapterResult[None]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def export_file(
    self, file_path: str, format_type: str
) -> AdapterResult[None]:
    """Mock exporting a file.

    Args:
        file_path (str): Path to the target file.
        format_type (str): The format type value.

    Returns:
        AdapterResult[None]: The result produced by the operation.
    """
    if not self._current_model:
        return AdapterResult(
            status=AdapterResultStatus.ERROR, error="No active model"
        )

    # Simulate export time based on format
    export_times = {
        "step": 2.0,
        "iges": 1.5,
        "stl": 1.0,
        "pdf": 0.5,
        "jpg": 0.3,
        "glb": 1.2,
        "gltf": 1.2,
    }

    format_lower = format_type.lower()
    delay = export_times.get(format_lower, 1.0)

    await asyncio.sleep(delay)
    self._operation_count += 1

    # Write a minimal placeholder file so callers that check existence get a valid result
    if format_lower == "stl":
        import pathlib

        out = pathlib.Path(file_path)
        out.parent.mkdir(parents=True, exist_ok=True)
        # Minimal ASCII STL — a single unit triangle (mock geometry placeholder)
        out.write_text(
            "solid mock\n"
            "  facet normal 0 0 1\n"
            "    outer loop\n"
            "      vertex 0 0 0\n"
            "      vertex 10 0 0\n"
            "      vertex 5 10 0\n"
            "    endloop\n"
            "  endfacet\n"
            "  facet normal 0 0 1\n"
            "    outer loop\n"
            "      vertex 0 0 0\n"
            "      vertex 10 0 0\n"
            "      vertex 5 0 10\n"
            "    endloop\n"
            "  endfacet\n"
            "endsolid mock\n",
            encoding="utf-8",
        )

    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data=None,
        execution_time=delay,
        metadata={"exported_format": format_type, "file_path": file_path},
    )
export_image async
export_image(payload: dict) -> AdapterResult[dict]

Mock export of a PNG/JPG viewport screenshot.

Parameters:

Name Type Description Default
payload dict

The payload value.

required

Returns:

Type Description
AdapterResult[dict]

AdapterResult[dict]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def export_image(self, payload: dict) -> AdapterResult[dict]:
    """Mock export of a PNG/JPG viewport screenshot.

    Args:
        payload (dict): The payload value.

    Returns:
        AdapterResult[dict]: The result produced by the operation.
    """
    if not self._current_model:
        return AdapterResult(
            status=AdapterResultStatus.ERROR, error="No active model"
        )

    import pathlib

    file_path = payload.get("file_path", "")
    width = int(payload.get("width", 1280))
    height = int(payload.get("height", 720))
    orientation = str(payload.get("view_orientation", "current"))

    await asyncio.sleep(0.3)
    self._operation_count += 1

    out = pathlib.Path(file_path)
    out.parent.mkdir(parents=True, exist_ok=True)

    # Write a valid 1×1 white PNG binary so UI image tags don't break
    _PNG_1X1_WHITE = (
        b"\x89PNG\r\n\x1a\n"  # PNG signature
        b"\x00\x00\x00\rIHDR"  # IHDR chunk length+type
        b"\x00\x00\x00\x01\x00\x00\x00\x01"  # 1x1
        b"\x08\x02\x00\x00\x00\x90wS\xde"  # 8-bit RGB + CRC
        b"\x00\x00\x00\x0cIDATx\x9cc\xf8\xff\xff\xff\x00\x05\xfe\x02\xfe\xdc\xcaY\xe7"  # IDAT
        b"\x00\x00\x00\x00IEND\xaeB`\x82"  # IEND
    )
    out.write_bytes(_PNG_1X1_WHITE)

    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data={
            "file_path": file_path,
            "format": "PNG",
            "dimensions": f"{width}x{height}",
            "view": orientation,
        },
        execution_time=0.3,
        metadata={"mock": True, "orientation": orientation},
    )
get_dimension async
get_dimension(name: str) -> AdapterResult[float]

Mock getting a dimension value.

Parameters:

Name Type Description Default
name str

The name value.

required

Returns:

Type Description
AdapterResult[float]

AdapterResult[float]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def get_dimension(self, name: str) -> AdapterResult[float]:
    """Mock getting a dimension value.

    Args:
        name (str): The name value.

    Returns:
        AdapterResult[float]: The result produced by the operation.
    """
    await asyncio.sleep(0.05)  # Very fast operation
    self._operation_count += 1

    if name in self._dimensions:
        return AdapterResult(
            status=AdapterResultStatus.SUCCESS,
            data=self._dimensions[name],
            execution_time=0.05,
        )
    else:
        return AdapterResult(
            status=AdapterResultStatus.ERROR, error=f"Dimension '{name}' not found"
        )
get_mass_properties async
get_mass_properties() -> AdapterResult[MassProperties]

Mock getting mass properties.

Returns:

Type Description
AdapterResult[MassProperties]

AdapterResult[MassProperties]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def get_mass_properties(self) -> AdapterResult[MassProperties]:
    """Mock getting mass properties.

    Returns:
        AdapterResult[MassProperties]: The result produced by the operation.
    """
    if not self._current_model:
        return AdapterResult(
            status=AdapterResultStatus.ERROR, error="No active model"
        )

    await asyncio.sleep(self._delays["feature_operation"])
    self._operation_count += 1

    # Generate realistic mock data
    properties = MassProperties(
        volume=random.uniform(1000, 100000),  # mm³
        surface_area=random.uniform(1000, 50000),  # mm²
        mass=random.uniform(0.1, 50.0),  # kg (assuming typical density)
        center_of_mass=[
            random.uniform(-100, 100),
            random.uniform(-100, 100),
            random.uniform(-100, 100),
        ],
        moments_of_inertia={
            "Ixx": random.uniform(1e6, 1e9),
            "Iyy": random.uniform(1e6, 1e9),
            "Izz": random.uniform(1e6, 1e9),
            "Ixy": random.uniform(-1e8, 1e8),
            "Ixz": random.uniform(-1e8, 1e8),
            "Iyz": random.uniform(-1e8, 1e8),
        },
    )

    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data=properties,
        execution_time=self._delays["feature_operation"],
    )
get_model_info async
get_model_info() -> AdapterResult[dict[str, Any]]

Mock metadata for the currently active model.

Returns:

Type Description
AdapterResult[dict[str, Any]]

AdapterResult[dict[str, Any]]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def get_model_info(self) -> AdapterResult[dict[str, Any]]:
    """Mock metadata for the currently active model.

    Returns:
        AdapterResult[dict[str, Any]]: The result produced by the operation.
    """
    if not self._current_model:
        return AdapterResult(
            status=AdapterResultStatus.ERROR,
            error="No active model",
        )

    await asyncio.sleep(self._delays["model_operation"] / 2)
    self._operation_count += 1

    model = self._current_model
    feature_count = len(self._features)
    info = {
        "title": model.name,
        "path": model.path,
        "type": model.type,
        "configuration": model.configuration or "Default",
        "is_dirty": False,
        "feature_count": feature_count,
        "rebuild_status": 0,
    }

    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data=info,
        execution_time=self._delays["model_operation"] / 2,
    )
health_check async
health_check() -> AdapterHealth

Get mock health status.

Returns:

Name Type Description
AdapterHealth AdapterHealth

The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def health_check(self) -> AdapterHealth:
    """Get mock health status.

    Returns:
        AdapterHealth: The result produced by the operation.
    """
    error_count = int(self._metrics["errors_count"])
    success_count = int(
        self._metrics["operations_count"] - self._metrics["errors_count"]
    )
    return AdapterHealth(
        healthy=self._connected,
        last_check=datetime.now(),
        error_count=error_count,
        success_count=success_count,
        average_response_time=self._metrics["average_response_time"],
        connection_status="connected" if self._connected else "disconnected",
        metrics={
            "adapter_type": "mock",
            "operations_count": self._operation_count,
            "models_count": len(self._models),
            "features_count": len(self._features),
            "sketches_count": len(self._sketches),
        },
    )
insert_component async
insert_component(file_path: str, x: float = 0.0, y: float = 0.0, z: float = 0.0) -> AdapterResult[dict[str, Any]]

Mock inserting a component into the active assembly.

Records the component in self._components so repeated inserts accumulate and list_components reflects them.

Parameters:

Name Type Description Default
file_path str

Path to the part or sub-assembly to insert.

required
x float

X position in millimetres. Defaults to 0.0.

0.0
y float

Y position in millimetres. Defaults to 0.0.

0.0
z float

Z position in millimetres. Defaults to 0.0.

0.0

Returns:

Type Description
AdapterResult[dict[str, Any]]

AdapterResult[dict[str, Any]]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def insert_component(
    self, file_path: str, x: float = 0.0, y: float = 0.0, z: float = 0.0
) -> AdapterResult[dict[str, Any]]:
    """Mock inserting a component into the active assembly.

    Records the component in ``self._components`` so repeated inserts
    accumulate and ``list_components`` reflects them.

    Args:
        file_path (str): Path to the part or sub-assembly to insert.
        x (float): X position in millimetres. Defaults to 0.0.
        y (float): Y position in millimetres. Defaults to 0.0.
        z (float): Z position in millimetres. Defaults to 0.0.

    Returns:
        AdapterResult[dict[str, Any]]: The result produced by the operation.
    """
    await asyncio.sleep(self._delays["model_operation"])
    self._operation_count += 1

    self._components.append(f"component-{len(self._components) + 1}")

    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data={
            "component": self._components[-1],
            "file_path": file_path,
            "position": {"x": x, "y": y, "z": z},
            "components_before": len(self._components) - 1,
            "components_after": len(self._components),
        },
        execution_time=self._delays["model_operation"],
    )
is_connected
is_connected() -> bool

Check if mock connection is active.

Returns:

Name Type Description
bool bool

True if connected, otherwise False.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
def is_connected(self) -> bool:
    """Check if mock connection is active.

    Returns:
        bool: True if connected, otherwise False.
    """
    return self._connected
list_components async
list_components() -> AdapterResult[list[str]]

Mock listing the top-level components of the active assembly.

Returns:

Type Description
AdapterResult[list[str]]

AdapterResult[list[str]]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def list_components(self) -> AdapterResult[list[str]]:
    """Mock listing the top-level components of the active assembly.

    Returns:
        AdapterResult[list[str]]: The result produced by the operation.
    """
    await asyncio.sleep(self._delays["model_operation"] / 2)
    self._operation_count += 1

    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data=list(self._components),
        execution_time=self._delays["model_operation"] / 2,
    )
list_configurations async
list_configurations() -> AdapterResult[list[str]]

Mock configuration listing for the active model.

Returns:

Type Description
AdapterResult[list[str]]

AdapterResult[list[str]]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def list_configurations(self) -> AdapterResult[list[str]]:
    """Mock configuration listing for the active model.

    Returns:
        AdapterResult[list[str]]: The result produced by the operation.
    """
    if not self._current_model:
        return AdapterResult(
            status=AdapterResultStatus.ERROR,
            error="No active model",
        )

    await asyncio.sleep(self._delays["model_operation"] / 2)
    self._operation_count += 1

    active = self._current_model.configuration or "Default"
    configs = [active] if active == "Default" else ["Default", active]

    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data=configs,
        execution_time=self._delays["model_operation"] / 2,
    )
list_features async
list_features(include_suppressed: bool = False, max_assembly_depth: int = 2) -> AdapterResult[list[dict[str, Any]]]

Mock feature tree listing for the active model.

For an Assembly model, flattens in every configured component's features (see _assembly_components) alongside the document's own features, tagged with component/component_path the same way the real adapter does. Falls back to a small canned two-component fixture (plus one nested sub-assembly) when no components have been configured, mirroring the existing "seed realistic feature names" behavior for an empty Part.

Parameters:

Name Type Description Default
include_suppressed bool

The include suppressed value. Defaults to False.

False
max_assembly_depth int

Sub-assembly recursion budget. Ignored for non-Assembly models. Defaults to 2.

2

Returns:

Type Description
AdapterResult[list[dict[str, Any]]]

AdapterResult[list[dict[str, Any]]]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def list_features(
    self, include_suppressed: bool = False, max_assembly_depth: int = 2
) -> AdapterResult[list[dict[str, Any]]]:
    """Mock feature tree listing for the active model.

    For an Assembly model, flattens in every configured component's
    features (see ``_assembly_components``) alongside the document's own
    features, tagged with ``component``/``component_path`` the same way
    the real adapter does. Falls back to a small canned two-component
    fixture (plus one nested sub-assembly) when no components have been
    configured, mirroring the existing "seed realistic feature names"
    behavior for an empty Part.

    Args:
        include_suppressed (bool): The include suppressed value. Defaults to False.
        max_assembly_depth (int): Sub-assembly recursion budget. Ignored
            for non-Assembly models. Defaults to 2.

    Returns:
        AdapterResult[list[dict[str, Any]]]: The result produced by the operation.
    """
    if not self._current_model:
        return AdapterResult(
            status=AdapterResultStatus.ERROR,
            error="No active model",
        )

    await asyncio.sleep(self._delays["feature_operation"] / 2)
    self._operation_count += 1

    is_assembly = self._current_model.type == "Assembly"

    # Seed realistic feature names for empty mock state.
    if not self._features:
        seeded: list[dict[str, Any]] = [
            {
                "name": "Origin",
                "type": "OriginProfileFeature",
                "suppressed": False,
                "component": None,
                "component_path": None,
                "component_parent": None,
            },
            {
                "name": "Front Plane",
                "type": "RefPlane",
                "suppressed": False,
                "component": None,
                "component_path": None,
                "component_parent": None,
            },
            {
                "name": "Right Plane",
                "type": "RefPlane",
                "suppressed": False,
                "component": None,
                "component_path": None,
                "component_parent": None,
            },
            {
                "name": "Top Plane",
                "type": "RefPlane",
                "suppressed": False,
                "component": None,
                "component_path": None,
                "component_parent": None,
            },
            {
                "name": "Sketch1",
                "type": "ProfileFeature",
                "suppressed": False,
                "component": None,
                "component_path": None,
                "component_parent": None,
            },
        ]
        if is_assembly:
            components = self._assembly_components or _DEFAULT_ASSEMBLY_COMPONENTS
            seeded.extend(
                self._flatten_assembly_components(
                    components, include_suppressed, max_assembly_depth - 1, None
                )
            )
        return AdapterResult(
            status=AdapterResultStatus.SUCCESS,
            data=seeded,
            execution_time=self._delays["feature_operation"] / 2,
        )

    feature_rows: list[dict[str, Any]] = []
    for i, feature in enumerate(self._features.values()):
        row = {
            "name": feature.name,
            "type": feature.type,
            "suppressed": bool((feature.properties or {}).get("suppressed", False)),
            "position": i,
            "component": None,
            "component_path": None,
            "component_parent": None,
        }
        if include_suppressed or not row["suppressed"]:
            feature_rows.append(row)

    if is_assembly:
        components = self._assembly_components or _DEFAULT_ASSEMBLY_COMPONENTS
        feature_rows.extend(
            self._flatten_assembly_components(
                components,
                include_suppressed,
                max_assembly_depth - 1,
                None,
            )
        )

    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data=feature_rows,
        execution_time=self._delays["feature_operation"] / 2,
    )
open_model async
open_model(file_path: str) -> AdapterResult[SolidWorksModel]

Mock opening a SolidWorks model.

Parameters:

Name Type Description Default
file_path str

Path to the target file.

required

Returns:

Type Description
AdapterResult[SolidWorksModel]

AdapterResult[SolidWorksModel]: The result produced by the operation.

Raises:

Type Description
SolidWorksOperationError

Simulated adapter failure.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def open_model(self, file_path: str) -> AdapterResult[SolidWorksModel]:
    """Mock opening a SolidWorks model.

    Args:
        file_path (str): Path to the target file.

    Returns:
        AdapterResult[SolidWorksModel]: The result produced by the operation.

    Raises:
        SolidWorksOperationError: Simulated adapter failure.
    """
    if not self._connected:
        return AdapterResult(
            status=AdapterResultStatus.ERROR, error="Not connected to SolidWorks"
        )

    if self._simulate_errors:
        raise SolidWorksOperationError("Simulated adapter failure")

    await asyncio.sleep(self._delays["model_operation"])
    self._operation_count += 1

    # Determine model type from file extension
    file_path_lower = file_path.lower()
    if file_path_lower.endswith(".sldprt"):
        model_type = "Part"
    elif file_path_lower.endswith(".sldasm"):
        model_type = "Assembly"
    elif file_path_lower.endswith(".slddrw"):
        model_type = "Drawing"
    else:
        return AdapterResult(
            status=AdapterResultStatus.ERROR,
            error=f"Unsupported file type: {file_path}",
        )

    # Create mock model
    model_name = file_path.split("/")[-1].split("\\")[-1]
    model = SolidWorksModel(
        path=file_path,
        name=model_name,
        type=model_type,
        is_active=True,
        configuration="Default",
        properties={
            "created": datetime.now().isoformat(),
            "model_id": model_name or f"Part{len(self._models) + 1}",
            "file_size": random.randint(100000, 5000000),
        },
    )

    self._current_model = model
    self._models[file_path] = model

    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data=model,
        execution_time=self._delays["model_operation"],
    )
pack_and_go_assembly async
pack_and_go_assembly(source_path: str, target_dir: str) -> AdapterResult[dict]

Mock Pack-and-Go: simulate copying an assembly to a target directory.

Parameters:

Name Type Description Default
source_path str

Path to the source .sldasm file.

required
target_dir str

Directory to copy files into.

required

Returns:

Type Description
AdapterResult[dict]

AdapterResult[dict]: Simulated pack-and-go result.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def pack_and_go_assembly(
    self,
    source_path: str,
    target_dir: str,
) -> AdapterResult[dict]:
    """Mock Pack-and-Go: simulate copying an assembly to a target directory.

    Args:
        source_path (str): Path to the source .sldasm file.
        target_dir (str): Directory to copy files into.

    Returns:
        AdapterResult[dict]: Simulated pack-and-go result.
    """
    import pathlib

    await asyncio.sleep(0.05)
    self._operation_count += 1

    source = pathlib.Path(source_path)
    out_dir = pathlib.Path(target_dir)
    mock_parts = [f"MockPart{i}.SLDPRT" for i in range(1, 3)]
    source_files = [str(source)] + [str(source.parent / p) for p in mock_parts]
    copied_files = [str(out_dir / source.name)] + [
        str(out_dir / p) for p in mock_parts
    ]
    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data={
            "source_assembly": str(source),
            "target_dir": str(out_dir),
            "copied_files": copied_files,
            "source_files": source_files,
            "save_statuses": [0] * (len(mock_parts) + 1),
            "all_files_saved": True,
        },
        execution_time=0.05,
        metadata={"mock": True},
    )
save_file async
save_file(file_path: str | None = None) -> AdapterResult[dict[str, Any]]

Legacy compatibility save operation for tests.

Parameters:

Name Type Description Default
file_path str | None

Path to the target file. Defaults to None.

None

Returns:

Type Description
AdapterResult[dict[str, Any]]

AdapterResult[dict[str, Any]]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def save_file(
    self, file_path: str | None = None
) -> AdapterResult[dict[str, Any]]:
    """Legacy compatibility save operation for tests.

    Args:
        file_path (str | None): Path to the target file. Defaults to None.

    Returns:
        AdapterResult[dict[str, Any]]: The result produced by the operation.
    """
    if not self._current_model:
        return AdapterResult(
            status=AdapterResultStatus.ERROR,
            error="No active model",
        )
    await asyncio.sleep(0.02)
    self._operation_count += 1
    resolved_path = file_path or self._current_model.path
    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data={"file_path": resolved_path, "saved": True},
        execution_time=0.02,
    )
select_feature async
select_feature(feature_name: str) -> AdapterResult[dict[str, Any]]

Mock feature selection/highlight — succeeds without COM side-effects.

Parameters:

Name Type Description Default
feature_name str

The feature name value.

required

Returns:

Type Description
AdapterResult[dict[str, Any]]

AdapterResult[dict[str, Any]]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def select_feature(self, feature_name: str) -> AdapterResult[dict[str, Any]]:
    """Mock feature selection/highlight — succeeds without COM side-effects.

    Args:
        feature_name (str): The feature name value.

    Returns:
        AdapterResult[dict[str, Any]]: The result produced by the operation.
    """
    if not self._current_model:
        return AdapterResult(
            status=AdapterResultStatus.ERROR,
            error="No active model",
        )
    await asyncio.sleep(self._delays["feature_operation"] / 4)
    self._operation_count += 1
    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data={
            "selected": True,
            "feature_name": feature_name,
            "entity_type": "mock",
        },
        execution_time=self._delays["feature_operation"] / 4,
    )
set_dimension async
set_dimension(name: str, value: float) -> AdapterResult[None]

Mock setting a dimension value.

Parameters:

Name Type Description Default
name str

The name value.

required
value float

The value value.

required

Returns:

Type Description
AdapterResult[None]

AdapterResult[None]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def set_dimension(self, name: str, value: float) -> AdapterResult[None]:
    """Mock setting a dimension value.

    Args:
        name (str): The name value.
        value (float): The value value.

    Returns:
        AdapterResult[None]: The result produced by the operation.
    """
    await asyncio.sleep(0.1)  # Fast operation
    self._operation_count += 1

    self._dimensions[name] = value

    return AdapterResult(
        status=AdapterResultStatus.SUCCESS, data=None, execution_time=0.1
    )
sketch_circular_pattern async
sketch_circular_pattern(entities: list[str], angle: float, count: int) -> AdapterResult[str]

Mock creating a circular sketch pattern around the sketch origin.

Parameters:

Name Type Description Default
entities list[str]

Seed entity IDs.

required
angle float

Total swept angle in degrees.

required
count int

Total number of instances (including the seed).

required

Returns:

Type Description
AdapterResult[str]

AdapterResult[str]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def sketch_circular_pattern(
    self,
    entities: list[str],
    angle: float,
    count: int,
) -> AdapterResult[str]:
    """Mock creating a circular sketch pattern around the sketch origin.

    Args:
        entities (list[str]): Seed entity IDs.
        angle (float): Total swept angle in degrees.
        count (int): Total number of instances (including the seed).

    Returns:
        AdapterResult[str]: The result produced by the operation.
    """
    if not self._current_sketch:
        return AdapterResult(
            status=AdapterResultStatus.ERROR, error="No active sketch"
        )
    if not entities:
        return AdapterResult(
            status=AdapterResultStatus.ERROR,
            error="sketch_circular_pattern requires at least one entity",
        )
    if count < 2:
        return AdapterResult(
            status=AdapterResultStatus.ERROR,
            error="sketch_circular_pattern requires count >= 2",
        )
    if angle <= 0:
        return AdapterResult(
            status=AdapterResultStatus.ERROR,
            error="sketch_circular_pattern requires angle > 0",
        )
    for ent in entities:
        if ent not in self._sketch_entity_ids:
            return AdapterResult(
                status=AdapterResultStatus.ERROR,
                error=(
                    f"Unknown sketch entity '{ent}'. Use IDs returned by "
                    "add_line/add_arc/add_circle/add_spline/add_centerline."
                ),
            )

    await asyncio.sleep(self._delays["sketch_operation"] / 2)
    self._operation_count += 1

    pattern_id = f"CircularPattern_{count}x{angle}deg_{random.randint(1000, 9999)}"
    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data=pattern_id,
        execution_time=self._delays["sketch_operation"] / 2,
    )
sketch_linear_pattern async
sketch_linear_pattern(entities: list[str], direction_x: float, direction_y: float, spacing: float, count: int) -> AdapterResult[str]

Mock creating a linear sketch pattern.

Mirrors the real adapter's validation rules — empty entities, count < 2, non-positive spacing, and a zero direction vector each produce a clear error without "creating" a pattern.

Parameters:

Name Type Description Default
entities list[str]

Seed entity IDs.

required
direction_x float

Pattern direction X component.

required
direction_y float

Pattern direction Y component.

required
spacing float

Distance between instances in millimetres.

required
count int

Total number of instances (including the seed).

required

Returns:

Type Description
AdapterResult[str]

AdapterResult[str]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def sketch_linear_pattern(
    self,
    entities: list[str],
    direction_x: float,
    direction_y: float,
    spacing: float,
    count: int,
) -> AdapterResult[str]:
    """Mock creating a linear sketch pattern.

    Mirrors the real adapter's validation rules — empty entities,
    count < 2, non-positive spacing, and a zero direction vector each
    produce a clear error without "creating" a pattern.

    Args:
        entities (list[str]): Seed entity IDs.
        direction_x (float): Pattern direction X component.
        direction_y (float): Pattern direction Y component.
        spacing (float): Distance between instances in millimetres.
        count (int): Total number of instances (including the seed).

    Returns:
        AdapterResult[str]: The result produced by the operation.
    """
    if not self._current_sketch:
        return AdapterResult(
            status=AdapterResultStatus.ERROR, error="No active sketch"
        )
    if not entities:
        return AdapterResult(
            status=AdapterResultStatus.ERROR,
            error="sketch_linear_pattern requires at least one entity",
        )
    if count < 2:
        return AdapterResult(
            status=AdapterResultStatus.ERROR,
            error="sketch_linear_pattern requires count >= 2",
        )
    if spacing <= 0:
        return AdapterResult(
            status=AdapterResultStatus.ERROR,
            error="sketch_linear_pattern requires spacing > 0",
        )
    if math.hypot(direction_x, direction_y) < 1e-9:
        return AdapterResult(
            status=AdapterResultStatus.ERROR,
            error=("sketch_linear_pattern requires a non-zero direction vector"),
        )
    for ent in entities:
        if ent not in self._sketch_entity_ids:
            return AdapterResult(
                status=AdapterResultStatus.ERROR,
                error=(
                    f"Unknown sketch entity '{ent}'. Use IDs returned by "
                    "add_line/add_arc/add_circle/add_spline/add_centerline."
                ),
            )

    await asyncio.sleep(self._delays["sketch_operation"] / 2)
    self._operation_count += 1

    pattern_id = f"LinearPattern_{count}x{spacing}_{random.randint(1000, 9999)}"
    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data=pattern_id,
        execution_time=self._delays["sketch_operation"] / 2,
    )
sketch_mirror async
sketch_mirror(entities: list[str], mirror_line: str) -> AdapterResult[str]

Mock mirroring sketch entities about a centerline.

Parameters:

Name Type Description Default
entities list[str]

IDs of segments to mirror.

required
mirror_line str

ID of the centerline to mirror across.

required

Returns:

Type Description
AdapterResult[str]

AdapterResult[str]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def sketch_mirror(
    self, entities: list[str], mirror_line: str
) -> AdapterResult[str]:
    """Mock mirroring sketch entities about a centerline.

    Args:
        entities (list[str]): IDs of segments to mirror.
        mirror_line (str): ID of the centerline to mirror across.

    Returns:
        AdapterResult[str]: The result produced by the operation.
    """
    if not self._current_sketch:
        return AdapterResult(
            status=AdapterResultStatus.ERROR, error="No active sketch"
        )
    if not entities:
        return AdapterResult(
            status=AdapterResultStatus.ERROR,
            error="sketch_mirror requires at least one entity",
        )
    if not mirror_line:
        return AdapterResult(
            status=AdapterResultStatus.ERROR,
            error=(
                "sketch_mirror requires a mirror_line entity ID (add_centerline)"
            ),
        )
    if mirror_line not in self._sketch_entity_ids:
        return AdapterResult(
            status=AdapterResultStatus.ERROR,
            error=(
                f"Unknown mirror_line entity '{mirror_line}'. Use the "
                "ID returned by add_centerline."
            ),
        )
    # Mirror the real adapter — IModelDoc2::SketchMirror needs a
    # centreline as the mirror axis; other segments silently no-op.
    if not mirror_line.startswith("Centerline_"):
        return AdapterResult(
            status=AdapterResultStatus.ERROR,
            error=(
                f"mirror_line must be a centerline (from add_centerline), "
                f"got '{mirror_line}'"
            ),
        )
    for ent in entities:
        if ent not in self._sketch_entity_ids:
            return AdapterResult(
                status=AdapterResultStatus.ERROR,
                error=(
                    f"Unknown sketch entity '{ent}'. Use IDs returned by "
                    "add_line/add_arc/add_circle/add_spline/add_centerline."
                ),
            )

    await asyncio.sleep(self._delays["sketch_operation"] / 2)
    self._operation_count += 1

    mirror_id = f"Mirror_{mirror_line}_{random.randint(1000, 9999)}"
    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data=mirror_id,
        execution_time=self._delays["sketch_operation"] / 2,
    )
sketch_offset async
sketch_offset(entities: list[str], offset_distance: float, reverse_direction: bool) -> AdapterResult[str]

Mock offsetting sketch entities by a fixed distance.

Parameters:

Name Type Description Default
entities list[str]

IDs of segments to offset.

required
offset_distance float

Distance in millimetres. Must be > 0.

required
reverse_direction bool

Flip the offset direction.

required

Returns:

Type Description
AdapterResult[str]

AdapterResult[str]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/mock_adapter.py
async def sketch_offset(
    self,
    entities: list[str],
    offset_distance: float,
    reverse_direction: bool,
) -> AdapterResult[str]:
    """Mock offsetting sketch entities by a fixed distance.

    Args:
        entities (list[str]): IDs of segments to offset.
        offset_distance (float): Distance in millimetres. Must be > 0.
        reverse_direction (bool): Flip the offset direction.

    Returns:
        AdapterResult[str]: The result produced by the operation.
    """
    if not self._current_sketch:
        return AdapterResult(
            status=AdapterResultStatus.ERROR, error="No active sketch"
        )
    if not entities:
        return AdapterResult(
            status=AdapterResultStatus.ERROR,
            error="sketch_offset requires at least one entity",
        )
    if offset_distance <= 0:
        return AdapterResult(
            status=AdapterResultStatus.ERROR,
            error=(
                "sketch_offset requires offset_distance > 0 — use "
                "reverse_direction to flip the side"
            ),
        )
    for ent in entities:
        if ent not in self._sketch_entity_ids:
            return AdapterResult(
                status=AdapterResultStatus.ERROR,
                error=(
                    f"Unknown sketch entity '{ent}'. Use IDs returned by "
                    "add_line/add_arc/add_circle/add_spline/add_centerline."
                ),
            )

    await asyncio.sleep(self._delays["sketch_operation"] / 2)
    self._operation_count += 1

    direction = "inward" if reverse_direction else "outward"
    offset_id = f"Offset_{offset_distance}_{direction}_{random.randint(1000, 9999)}"
    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data=offset_id,
        execution_time=self._delays["sketch_operation"] / 2,
    )

SolidWorksAdapter

SolidWorksAdapter(config: object | None = None)

Bases: ABC

Base adapter interface for SolidWorks integration.

Parameters:

Name Type Description Default
config object | None

Configuration values for the operation. Defaults to None.

None

Attributes:

Name Type Description
_metrics Any

The metrics value.

config Any

The config value.

config_dict Any

The config dict value.

Initialize adapter with configuration.

Parameters:

Name Type Description Default
config object | None

Configuration values for the operation. Defaults to None.

None
Source code in src/solidworks_mcp/adapters/base.py
def __init__(self, config: object | None = None):
    """Initialize adapter with configuration.

    Args:
        config (object | None): Configuration values for the operation. Defaults to None.
    """
    if config is None:
        normalized_config: dict[str, Any] = {}
    elif isinstance(config, Mapping):
        normalized_config = dict(config)
    elif hasattr(config, "model_dump"):
        normalized_config = dict(config.model_dump())
    else:
        normalized_config = {}

    # Preserve original config object for compatibility with tests and
    # call sites that compare object identity/equality.
    self.config = config
    # Keep a normalized mapping for adapter internals.
    self.config_dict = normalized_config
    self._metrics = {
        "operations_count": 0,
        "errors_count": 0,
        "average_response_time": 0.0,
    }
    # SolidWorks-as-Code session logging. Set soc_session_id to enable
    # automatic ToolCallRecord writes for every adapter operation.
    self.soc_session_id: str | None = None
    self.soc_db_path: Path | None = None
Methods:
add_arc async
add_arc(center_x: float, center_y: float, start_x: float, start_y: float, end_x: float, end_y: float) -> AdapterResult[str]

Add an arc to the current sketch.

Parameters:

Name Type Description Default
center_x float

The center x value.

required
center_y float

The center y value.

required
start_x float

The start x value.

required
start_y float

The start y value.

required
end_x float

The end x value.

required
end_y float

The end y value.

required

Returns:

Type Description
AdapterResult[str]

AdapterResult[str]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
async def add_arc(
    self,
    center_x: float,
    center_y: float,
    start_x: float,
    start_y: float,
    end_x: float,
    end_y: float,
) -> AdapterResult[str]:
    """Add an arc to the current sketch.

    Args:
        center_x (float): The center x value.
        center_y (float): The center y value.
        start_x (float): The start x value.
        start_y (float): The start y value.
        end_x (float): The end x value.
        end_y (float): The end y value.

    Returns:
        AdapterResult[str]: The result produced by the operation.
    """
    return AdapterResult(
        status=AdapterResultStatus.ERROR,
        error="add_arc is not implemented by this adapter",
    )
add_centerline async
add_centerline(x1: float, y1: float, x2: float, y2: float) -> AdapterResult[str]

Add a centerline to the current sketch.

Parameters:

Name Type Description Default
x1 float

The x1 value.

required
y1 float

The y1 value.

required
x2 float

The x2 value.

required
y2 float

The y2 value.

required

Returns:

Type Description
AdapterResult[str]

AdapterResult[str]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
async def add_centerline(
    self, x1: float, y1: float, x2: float, y2: float
) -> AdapterResult[str]:
    """Add a centerline to the current sketch.

    Args:
        x1 (float): The x1 value.
        y1 (float): The y1 value.
        x2 (float): The x2 value.
        y2 (float): The y2 value.

    Returns:
        AdapterResult[str]: The result produced by the operation.
    """
    return AdapterResult(
        status=AdapterResultStatus.ERROR,
        error="add_centerline is not implemented by this adapter",
    )
add_circle abstractmethod async
add_circle(center_x: float, center_y: float, radius: float) -> AdapterResult[str]

Add a circle to the current sketch.

Parameters:

Name Type Description Default
center_x float

The center x value.

required
center_y float

The center y value.

required
radius float

The radius value.

required

Returns:

Type Description
AdapterResult[str]

AdapterResult[str]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
@abstractmethod
async def add_circle(
    self, center_x: float, center_y: float, radius: float
) -> AdapterResult[str]:
    """Add a circle to the current sketch.

    Args:
        center_x (float): The center x value.
        center_y (float): The center y value.
        radius (float): The radius value.

    Returns:
        AdapterResult[str]: The result produced by the operation.
    """
    pass
add_ellipse async
add_ellipse(center_x: float, center_y: float, major_axis: float, minor_axis: float) -> AdapterResult[str]

Add an ellipse to the current sketch.

Parameters:

Name Type Description Default
center_x float

The center x value.

required
center_y float

The center y value.

required
major_axis float

The major axis value.

required
minor_axis float

The minor axis value.

required

Returns:

Type Description
AdapterResult[str]

AdapterResult[str]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
async def add_ellipse(
    self,
    center_x: float,
    center_y: float,
    major_axis: float,
    minor_axis: float,
) -> AdapterResult[str]:
    """Add an ellipse to the current sketch.

    Args:
        center_x (float): The center x value.
        center_y (float): The center y value.
        major_axis (float): The major axis value.
        minor_axis (float): The minor axis value.

    Returns:
        AdapterResult[str]: The result produced by the operation.
    """
    return AdapterResult(
        status=AdapterResultStatus.ERROR,
        error="add_ellipse is not implemented by this adapter",
    )
add_fillet async
add_fillet(radius: float, edge_names: list[str]) -> AdapterResult[Any]

Add a fillet feature to selected edges.

Rounds the selected edges of the current solid body with the given radius.

Parameters:

Name Type Description Default
radius float

Fillet radius in millimeters.

required
edge_names list[str]

List of edge names to fillet.

required

Returns:

Name Type Description
AdapterResult AdapterResult[Any]

Feature result or error.

Source code in src/solidworks_mcp/adapters/base.py
async def add_fillet(
    self, radius: float, edge_names: list[str]
) -> AdapterResult[Any]:
    """Add a fillet feature to selected edges.

    Rounds the selected edges of the current solid body with the given radius.

    Args:
        radius (float): Fillet radius in millimeters.
        edge_names (list[str]): List of edge names to fillet.

    Returns:
        AdapterResult: Feature result or error.
    """
    return AdapterResult(
        status=AdapterResultStatus.ERROR,
        error="add_fillet is not implemented by this adapter",
    )
add_line abstractmethod async
add_line(x1: float, y1: float, x2: float, y2: float) -> AdapterResult[str]

Add a line to the current sketch.

Parameters:

Name Type Description Default
x1 float

The x1 value.

required
y1 float

The y1 value.

required
x2 float

The x2 value.

required
y2 float

The y2 value.

required

Returns:

Type Description
AdapterResult[str]

AdapterResult[str]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
@abstractmethod
async def add_line(
    self, x1: float, y1: float, x2: float, y2: float
) -> AdapterResult[str]:
    """Add a line to the current sketch.

    Args:
        x1 (float): The x1 value.
        y1 (float): The y1 value.
        x2 (float): The x2 value.
        y2 (float): The y2 value.

    Returns:
        AdapterResult[str]: The result produced by the operation.
    """
    pass
add_mate async
add_mate(component_a: str, component_b: str, entity_a: str = 'Front Plane', entity_b: str = 'Front Plane', mate_type: str = 'coincident', alignment: str = 'aligned', distance: float = 0.0, angle: float = 0.0) -> AdapterResult[dict[str, Any]]

Mate two components together in the active assembly.

Parameters:

Name Type Description Default
component_a str

First component instance name.

required
component_b str

Second component instance name.

required
entity_a str

Named feature on the first component. Defaults to "Front Plane".

'Front Plane'
entity_b str

Named feature on the second component. Defaults to "Front Plane".

'Front Plane'
mate_type str

Mate type, e.g. coincident. Defaults to "coincident".

'coincident'
alignment str

aligned, anti_aligned or closest. Defaults to "aligned".

'aligned'
distance float

Distance in millimetres, for a distance mate. Defaults to 0.0.

0.0
angle float

Angle in degrees, for an angle mate. Defaults to 0.0.

0.0

Returns:

Type Description
AdapterResult[dict[str, Any]]

AdapterResult[dict[str, Any]]: Mate details, or error.

Source code in src/solidworks_mcp/adapters/base.py
async def add_mate(
    self,
    component_a: str,
    component_b: str,
    entity_a: str = "Front Plane",
    entity_b: str = "Front Plane",
    mate_type: str = "coincident",
    alignment: str = "aligned",
    distance: float = 0.0,
    angle: float = 0.0,
) -> AdapterResult[dict[str, Any]]:
    """Mate two components together in the active assembly.

    Args:
        component_a (str): First component instance name.
        component_b (str): Second component instance name.
        entity_a (str): Named feature on the first component. Defaults to
            "Front Plane".
        entity_b (str): Named feature on the second component. Defaults to
            "Front Plane".
        mate_type (str): Mate type, e.g. ``coincident``. Defaults to
            "coincident".
        alignment (str): ``aligned``, ``anti_aligned`` or ``closest``.
            Defaults to "aligned".
        distance (float): Distance in millimetres, for a distance mate.
            Defaults to 0.0.
        angle (float): Angle in degrees, for an angle mate. Defaults to 0.0.

    Returns:
        AdapterResult[dict[str, Any]]: Mate details, or error.
    """
    return AdapterResult(
        status=AdapterResultStatus.ERROR,
        error="add_mate is not implemented by this adapter",
    )
add_polygon async
add_polygon(center_x: float, center_y: float, radius: float, sides: int) -> AdapterResult[str]

Add a regular polygon to the current sketch.

Parameters:

Name Type Description Default
center_x float

The center x value.

required
center_y float

The center y value.

required
radius float

The radius value.

required
sides int

The sides value.

required

Returns:

Type Description
AdapterResult[str]

AdapterResult[str]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
async def add_polygon(
    self, center_x: float, center_y: float, radius: float, sides: int
) -> AdapterResult[str]:
    """Add a regular polygon to the current sketch.

    Args:
        center_x (float): The center x value.
        center_y (float): The center y value.
        radius (float): The radius value.
        sides (int): The sides value.

    Returns:
        AdapterResult[str]: The result produced by the operation.
    """
    return AdapterResult(
        status=AdapterResultStatus.ERROR,
        error="add_polygon is not implemented by this adapter",
    )
add_rectangle abstractmethod async
add_rectangle(x1: float, y1: float, x2: float, y2: float) -> AdapterResult[str]

Add a rectangle to the current sketch.

Parameters:

Name Type Description Default
x1 float

The x1 value.

required
y1 float

The y1 value.

required
x2 float

The x2 value.

required
y2 float

The y2 value.

required

Returns:

Type Description
AdapterResult[str]

AdapterResult[str]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
@abstractmethod
async def add_rectangle(
    self, x1: float, y1: float, x2: float, y2: float
) -> AdapterResult[str]:
    """Add a rectangle to the current sketch.

    Args:
        x1 (float): The x1 value.
        y1 (float): The y1 value.
        x2 (float): The x2 value.
        y2 (float): The y2 value.

    Returns:
        AdapterResult[str]: The result produced by the operation.
    """
    pass
add_sketch_circle async
add_sketch_circle(center_x: float, center_y: float, radius: float, construction: bool = False) -> AdapterResult[str]

Alias for add_circle used by some tool flows.

Parameters:

Name Type Description Default
center_x float

The center x value.

required
center_y float

The center y value.

required
radius float

The radius value.

required
construction bool

The construction value. Defaults to False.

False

Returns:

Type Description
AdapterResult[str]

AdapterResult[str]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
async def add_sketch_circle(
    self,
    center_x: float,
    center_y: float,
    radius: float,
    construction: bool = False,
) -> AdapterResult[str]:
    """Alias for add_circle used by some tool flows.

    Args:
        center_x (float): The center x value.
        center_y (float): The center y value.
        radius (float): The radius value.
        construction (bool): The construction value. Defaults to False.

    Returns:
        AdapterResult[str]: The result produced by the operation.
    """
    return await self.add_circle(center_x, center_y, radius)
add_sketch_constraint async
add_sketch_constraint(entity1: str, entity2: str | None, relation_type: str, entity3: str | None = None) -> AdapterResult[str]

Apply a geometric constraint between sketch entities.

Parameters:

Name Type Description Default
entity1 str

The entity1 value.

required
entity2 str | None

The entity2 value.

required
relation_type str

The relation type value.

required
entity3 str | None

Third entity ID — only used by the symmetric relation (the centerline of symmetry). All other relation types reject a non-null entity3.

None

Returns:

Type Description
AdapterResult[str]

AdapterResult[str]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
async def add_sketch_constraint(
    self,
    entity1: str,
    entity2: str | None,
    relation_type: str,
    entity3: str | None = None,
) -> AdapterResult[str]:
    """Apply a geometric constraint between sketch entities.

    Args:
        entity1 (str): The entity1 value.
        entity2 (str | None): The entity2 value.
        relation_type (str): The relation type value.
        entity3 (str | None): Third entity ID — only used by the
            ``symmetric`` relation (the centerline of symmetry). All
            other relation types reject a non-null ``entity3``.

    Returns:
        AdapterResult[str]: The result produced by the operation.
    """
    return AdapterResult(
        status=AdapterResultStatus.ERROR,
        error="add_sketch_constraint is not implemented by this adapter",
    )
add_sketch_dimension async
add_sketch_dimension(entity1: str, entity2: str | None, dimension_type: str, value: float) -> AdapterResult[str]

Add a sketch dimension.

Parameters:

Name Type Description Default
entity1 str

The entity1 value.

required
entity2 str | None

The entity2 value.

required
dimension_type str

The dimension type value.

required
value float

The value value.

required

Returns:

Type Description
AdapterResult[str]

AdapterResult[str]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
async def add_sketch_dimension(
    self,
    entity1: str,
    entity2: str | None,
    dimension_type: str,
    value: float,
) -> AdapterResult[str]:
    """Add a sketch dimension.

    Args:
        entity1 (str): The entity1 value.
        entity2 (str | None): The entity2 value.
        dimension_type (str): The dimension type value.
        value (float): The value value.

    Returns:
        AdapterResult[str]: The result produced by the operation.
    """
    return AdapterResult(
        status=AdapterResultStatus.ERROR,
        error="add_sketch_dimension is not implemented by this adapter",
    )
add_spline async
add_spline(points: list[dict[str, float]]) -> AdapterResult[str]

Add a spline through the provided points.

Parameters:

Name Type Description Default
points list[dict[str, float]]

The points value.

required

Returns:

Type Description
AdapterResult[str]

AdapterResult[str]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
async def add_spline(self, points: list[dict[str, float]]) -> AdapterResult[str]:
    """Add a spline through the provided points.

    Args:
        points (list[dict[str, float]]): The points value.

    Returns:
        AdapterResult[str]: The result produced by the operation.
    """
    return AdapterResult(
        status=AdapterResultStatus.ERROR,
        error="add_spline is not implemented by this adapter",
    )
check_sketch_fully_defined async
check_sketch_fully_defined(sketch_name: str | None = None) -> AdapterResult[dict[str, Any]]

Check whether a sketch is fully defined.

Parameters:

Name Type Description Default
sketch_name str | None

Optional sketch name to inspect. Defaults to None.

None

Returns:

Type Description
AdapterResult[dict[str, Any]]

AdapterResult[dict[str, Any]]: Definition status payload.

Source code in src/solidworks_mcp/adapters/base.py
async def check_sketch_fully_defined(
    self, sketch_name: str | None = None
) -> AdapterResult[dict[str, Any]]:
    """Check whether a sketch is fully defined.

    Args:
        sketch_name (str | None): Optional sketch name to inspect. Defaults to None.

    Returns:
        AdapterResult[dict[str, Any]]: Definition status payload.
    """
    return AdapterResult(
        status=AdapterResultStatus.ERROR,
        error="check_sketch_fully_defined is not implemented by this adapter",
    )
close_model abstractmethod async
close_model(save: bool = False) -> AdapterResult[None]

Close the current model.

Parameters:

Name Type Description Default
save bool

The save value. Defaults to False.

False

Returns:

Type Description
AdapterResult[None]

AdapterResult[None]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
@abstractmethod
async def close_model(self, save: bool = False) -> AdapterResult[None]:
    """Close the current model.

    Args:
        save (bool): The save value. Defaults to False.

    Returns:
        AdapterResult[None]: The result produced by the operation.
    """
    pass
connect abstractmethod async
connect() -> None

Connect to SolidWorks application.

Returns:

Name Type Description
None None

None.

Source code in src/solidworks_mcp/adapters/base.py
@abstractmethod
async def connect(self) -> None:
    """Connect to SolidWorks application.

    Returns:
        None: None.
    """
    pass
create_assembly abstractmethod async
create_assembly(name: str | None = None) -> AdapterResult[SolidWorksModel]

Create a new assembly document.

Parameters:

Name Type Description Default
name str | None

The name value. Defaults to None.

None

Returns:

Type Description
AdapterResult[SolidWorksModel]

AdapterResult[SolidWorksModel]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
@abstractmethod
async def create_assembly(
    self, name: str | None = None
) -> AdapterResult[SolidWorksModel]:
    """Create a new assembly document.

    Args:
        name (str | None): The name value. Defaults to None.

    Returns:
        AdapterResult[SolidWorksModel]: The result produced by the operation.
    """
    pass
create_cut async
create_cut(sketch_name: str, depth: float) -> AdapterResult[str]

Create a cut feature from an existing sketch.

Parameters:

Name Type Description Default
sketch_name str

The sketch name value.

required
depth float

The depth value.

required

Returns:

Type Description
AdapterResult[str]

AdapterResult[str]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
async def create_cut(self, sketch_name: str, depth: float) -> AdapterResult[str]:
    """Create a cut feature from an existing sketch.

    Args:
        sketch_name (str): The sketch name value.
        depth (float): The depth value.

    Returns:
        AdapterResult[str]: The result produced by the operation.
    """
    return AdapterResult(
        status=AdapterResultStatus.ERROR,
        error="create_cut is not implemented by this adapter",
    )
create_cut_extrude async
create_cut_extrude(params: ExtrusionParameters) -> AdapterResult[Any]

Create a cut-extrude feature from the active sketch.

Cuts material from the current solid body using the active sketch profile. Equivalent to SolidWorks Insert > Cut > Extrude.

Parameters:

Name Type Description Default
params ExtrusionParameters

Depth and direction parameters.

required

Returns:

Name Type Description
AdapterResult AdapterResult[Any]

Feature result or error.

Source code in src/solidworks_mcp/adapters/base.py
async def create_cut_extrude(
    self, params: ExtrusionParameters
) -> AdapterResult[Any]:
    """Create a cut-extrude feature from the active sketch.

    Cuts material from the current solid body using the active sketch profile.
    Equivalent to SolidWorks Insert > Cut > Extrude.

    Args:
        params (ExtrusionParameters): Depth and direction parameters.

    Returns:
        AdapterResult: Feature result or error.
    """
    return AdapterResult(
        status=AdapterResultStatus.ERROR,
        error="create_cut_extrude is not implemented by this adapter",
    )
create_drawing abstractmethod async
create_drawing(name: str | None = None) -> AdapterResult[SolidWorksModel]

Create a new drawing document.

Parameters:

Name Type Description Default
name str | None

The name value. Defaults to None.

None

Returns:

Type Description
AdapterResult[SolidWorksModel]

AdapterResult[SolidWorksModel]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
@abstractmethod
async def create_drawing(
    self, name: str | None = None
) -> AdapterResult[SolidWorksModel]:
    """Create a new drawing document.

    Args:
        name (str | None): The name value. Defaults to None.

    Returns:
        AdapterResult[SolidWorksModel]: The result produced by the operation.
    """
    pass
create_extrusion abstractmethod async
create_extrusion(params: ExtrusionParameters) -> AdapterResult[SolidWorksFeature]

Create an extrusion feature.

Parameters:

Name Type Description Default
params ExtrusionParameters

The params value.

required

Returns:

Type Description
AdapterResult[SolidWorksFeature]

AdapterResult[SolidWorksFeature]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
@abstractmethod
async def create_extrusion(
    self, params: ExtrusionParameters
) -> AdapterResult[SolidWorksFeature]:
    """Create an extrusion feature.

    Args:
        params (ExtrusionParameters): The params value.

    Returns:
        AdapterResult[SolidWorksFeature]: The result produced by the operation.
    """
    pass
create_loft abstractmethod async
create_loft(params: LoftParameters) -> AdapterResult[SolidWorksFeature]

Create a loft feature.

Parameters:

Name Type Description Default
params LoftParameters

The params value.

required

Returns:

Type Description
AdapterResult[SolidWorksFeature]

AdapterResult[SolidWorksFeature]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
@abstractmethod
async def create_loft(
    self, params: LoftParameters
) -> AdapterResult[SolidWorksFeature]:
    """Create a loft feature.

    Args:
        params (LoftParameters): The params value.

    Returns:
        AdapterResult[SolidWorksFeature]: The result produced by the operation.
    """
    pass
create_part abstractmethod async
create_part(name: str | None = None, units: str | None = None) -> AdapterResult[SolidWorksModel]

Create a new part document.

Parameters:

Name Type Description Default
name str | None

The name value. Defaults to None.

None
units str | None

The units value. Defaults to None.

None

Returns:

Type Description
AdapterResult[SolidWorksModel]

AdapterResult[SolidWorksModel]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
@abstractmethod
async def create_part(
    self, name: str | None = None, units: str | None = None
) -> AdapterResult[SolidWorksModel]:
    """Create a new part document.

    Args:
        name (str | None): The name value. Defaults to None.
        units (str | None): The units value. Defaults to None.

    Returns:
        AdapterResult[SolidWorksModel]: The result produced by the operation.
    """
    pass
create_revolve abstractmethod async
create_revolve(params: RevolveParameters) -> AdapterResult[SolidWorksFeature]

Create a revolve feature.

Parameters:

Name Type Description Default
params RevolveParameters

The params value.

required

Returns:

Type Description
AdapterResult[SolidWorksFeature]

AdapterResult[SolidWorksFeature]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
@abstractmethod
async def create_revolve(
    self, params: RevolveParameters
) -> AdapterResult[SolidWorksFeature]:
    """Create a revolve feature.

    Args:
        params (RevolveParameters): The params value.

    Returns:
        AdapterResult[SolidWorksFeature]: The result produced by the operation.
    """
    pass
create_sketch abstractmethod async
create_sketch(plane: str) -> AdapterResult[str]

Create a new sketch on the specified plane.

Parameters:

Name Type Description Default
plane str

The plane value.

required

Returns:

Type Description
AdapterResult[str]

AdapterResult[str]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
@abstractmethod
async def create_sketch(self, plane: str) -> AdapterResult[str]:
    """Create a new sketch on the specified plane.

    Args:
        plane (str): The plane value.

    Returns:
        AdapterResult[str]: The result produced by the operation.
    """
    pass
create_sweep abstractmethod async
create_sweep(params: SweepParameters) -> AdapterResult[SolidWorksFeature]

Create a sweep feature.

Parameters:

Name Type Description Default
params SweepParameters

The params value.

required

Returns:

Type Description
AdapterResult[SolidWorksFeature]

AdapterResult[SolidWorksFeature]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
@abstractmethod
async def create_sweep(
    self, params: SweepParameters
) -> AdapterResult[SolidWorksFeature]:
    """Create a sweep feature.

    Args:
        params (SweepParameters): The params value.

    Returns:
        AdapterResult[SolidWorksFeature]: The result produced by the operation.
    """
    pass
disconnect abstractmethod async
disconnect() -> None

Disconnect from SolidWorks application.

Returns:

Name Type Description
None None

None.

Source code in src/solidworks_mcp/adapters/base.py
@abstractmethod
async def disconnect(self) -> None:
    """Disconnect from SolidWorks application.

    Returns:
        None: None.
    """
    pass
exit_sketch abstractmethod async
exit_sketch() -> AdapterResult[None]

Exit sketch editing mode.

Returns:

Type Description
AdapterResult[None]

AdapterResult[None]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
@abstractmethod
async def exit_sketch(self) -> AdapterResult[None]:
    """Exit sketch editing mode.

    Returns:
        AdapterResult[None]: The result produced by the operation.
    """
    pass
export_file abstractmethod async
export_file(file_path: str, format_type: str) -> AdapterResult[None]

Export the current model to a file.

Parameters:

Name Type Description Default
file_path str

Path to the target file.

required
format_type str

The format type value.

required

Returns:

Type Description
AdapterResult[None]

AdapterResult[None]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
@abstractmethod
async def export_file(
    self, file_path: str, format_type: str
) -> AdapterResult[None]:
    """Export the current model to a file.

    Args:
        file_path (str): Path to the target file.
        format_type (str): The format type value.

    Returns:
        AdapterResult[None]: The result produced by the operation.
    """
    pass
export_image abstractmethod async
export_image(payload: dict) -> AdapterResult[dict]

Export a viewport screenshot (PNG/JPG) of the current model.

Payload keys: file_path (str): Absolute output path. width (int): Image width in pixels. height (int): Image height in pixels. view_orientation (str): One of "isometric", "front", "top", "right", "back", "bottom", "current".

Parameters:

Name Type Description Default
payload dict

The payload value.

required

Returns:

Type Description
AdapterResult[dict]

AdapterResult[dict]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
@abstractmethod
async def export_image(self, payload: dict) -> AdapterResult[dict]:
    """Export a viewport screenshot (PNG/JPG) of the current model.

    Payload keys: file_path (str): Absolute output path. width (int): Image width in pixels.
    height (int): Image height in pixels. view_orientation (str): One of "isometric",
    "front", "top", "right", "back", "bottom", "current".

    Args:
        payload (dict): The payload value.

    Returns:
        AdapterResult[dict]: The result produced by the operation.
    """
    pass
get_dimension abstractmethod async
get_dimension(name: str) -> AdapterResult[float]

Get the value of a dimension.

Parameters:

Name Type Description Default
name str

The name value.

required

Returns:

Type Description
AdapterResult[float]

AdapterResult[float]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
@abstractmethod
async def get_dimension(self, name: str) -> AdapterResult[float]:
    """Get the value of a dimension.

    Args:
        name (str): The name value.

    Returns:
        AdapterResult[float]: The result produced by the operation.
    """
    pass
get_mass_properties abstractmethod async
get_mass_properties() -> AdapterResult[MassProperties]

Get mass properties of the current model.

Returns:

Type Description
AdapterResult[MassProperties]

AdapterResult[MassProperties]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
@abstractmethod
async def get_mass_properties(self) -> AdapterResult[MassProperties]:
    """Get mass properties of the current model.

    Returns:
        AdapterResult[MassProperties]: The result produced by the operation.
    """
    pass
get_metrics
get_metrics() -> dict[str, Any]

Get adapter metrics.

Returns:

Type Description
dict[str, Any]

dict[str, Any]: A dictionary containing the resulting values.

Source code in src/solidworks_mcp/adapters/base.py
def get_metrics(self) -> dict[str, Any]:
    """Get adapter metrics.

    Returns:
        dict[str, Any]: A dictionary containing the resulting values.
    """
    return self._metrics.copy()
get_model_info abstractmethod async
get_model_info() -> AdapterResult[dict[str, Any]]

Get metadata for the active model.

Returns:

Type Description
AdapterResult[dict[str, Any]]

AdapterResult[dict[str, Any]]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
@abstractmethod
async def get_model_info(self) -> AdapterResult[dict[str, Any]]:
    """Get metadata for the active model.

    Returns:
        AdapterResult[dict[str, Any]]: The result produced by the operation.
    """
    pass
health_check abstractmethod async
health_check() -> AdapterHealth

Get adapter health status.

Returns:

Name Type Description
AdapterHealth AdapterHealth

The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
@abstractmethod
async def health_check(self) -> AdapterHealth:
    """Get adapter health status.

    Returns:
        AdapterHealth: The result produced by the operation.
    """
    pass
insert_component async
insert_component(file_path: str, x: float = 0.0, y: float = 0.0, z: float = 0.0) -> AdapterResult[dict[str, Any]]

Insert a part or sub-assembly into the active assembly.

Parameters:

Name Type Description Default
file_path str

Absolute path to the .sldprt or .sldasm.

required
x float

X position in millimetres. Defaults to 0.0.

0.0
y float

Y position in millimetres. Defaults to 0.0.

0.0
z float

Z position in millimetres. Defaults to 0.0.

0.0

Returns:

Type Description
AdapterResult[dict[str, Any]]

AdapterResult[dict[str, Any]]: Component name and counts, or error.

Source code in src/solidworks_mcp/adapters/base.py
async def insert_component(
    self, file_path: str, x: float = 0.0, y: float = 0.0, z: float = 0.0
) -> AdapterResult[dict[str, Any]]:
    """Insert a part or sub-assembly into the active assembly.

    Args:
        file_path (str): Absolute path to the ``.sldprt`` or ``.sldasm``.
        x (float): X position in millimetres. Defaults to 0.0.
        y (float): Y position in millimetres. Defaults to 0.0.
        z (float): Z position in millimetres. Defaults to 0.0.

    Returns:
        AdapterResult[dict[str, Any]]: Component name and counts, or error.
    """
    return AdapterResult(
        status=AdapterResultStatus.ERROR,
        error="insert_component is not implemented by this adapter",
    )
is_connected abstractmethod
is_connected() -> bool

Check if connected to SolidWorks.

Returns:

Name Type Description
bool bool

True if connected, otherwise False.

Source code in src/solidworks_mcp/adapters/base.py
@abstractmethod
def is_connected(self) -> bool:
    """Check if connected to SolidWorks.

    Returns:
        bool: True if connected, otherwise False.
    """
    pass
list_components async
list_components() -> AdapterResult[list[str]]

List the top-level components of the active assembly.

Returns:

Type Description
AdapterResult[list[str]]

AdapterResult[list[str]]: Component instance names, or error.

Source code in src/solidworks_mcp/adapters/base.py
async def list_components(self) -> AdapterResult[list[str]]:
    """List the top-level components of the active assembly.

    Returns:
        AdapterResult[list[str]]: Component instance names, or error.
    """
    return AdapterResult(
        status=AdapterResultStatus.ERROR,
        error="list_components is not implemented by this adapter",
    )
list_configurations abstractmethod async
list_configurations() -> AdapterResult[list[str]]

List configuration names for the active model.

Returns:

Type Description
AdapterResult[list[str]]

AdapterResult[list[str]]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
@abstractmethod
async def list_configurations(self) -> AdapterResult[list[str]]:
    """List configuration names for the active model.

    Returns:
        AdapterResult[list[str]]: The result produced by the operation.
    """
    pass
list_features abstractmethod async
list_features(include_suppressed: bool = False, max_assembly_depth: int = 2) -> AdapterResult[list[dict[str, Any]]]

List model features from the feature tree.

For a Part document, returns that document's own feature list, unchanged from prior behavior. For an Assembly document, returns a single flat list containing the assembly's own top-level features plus every resolved component's features, recursing into sub-assemblies up to max_assembly_depth. Every descriptor gains component, component_path, and component_parent keys: None for a document's own features (Part features, or an Assembly's top-level features), or the owning component's name/path for a component-derived feature. component_parent is the immediate parent component name when the component is nested inside a sub-assembly, otherwise None. A component that cannot be resolved (suppressed, lightweight-and-unloaded, missing file) is represented by one descriptor with type: "UnresolvedComponent" instead of being silently dropped.

Parameters:

Name Type Description Default
include_suppressed bool

The include suppressed value. Defaults to False. Applied independently to the assembly's own features and to each component's features.

False
max_assembly_depth int

How many levels of sub-assembly to recurse into. Defaults to 2. Ignored for Part documents. A component beyond the configured depth still appears in the result as a single descriptor (name + path), not expanded.

2

Returns:

Type Description
AdapterResult[list[dict[str, Any]]]

AdapterResult[list[dict[str, Any]]]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
@abstractmethod
async def list_features(
    self, include_suppressed: bool = False, max_assembly_depth: int = 2
) -> AdapterResult[list[dict[str, Any]]]:
    """List model features from the feature tree.

    For a Part document, returns that document's own feature list,
    unchanged from prior behavior. For an Assembly document, returns a
    single flat list containing the assembly's own top-level features
    plus every resolved component's features, recursing into
    sub-assemblies up to ``max_assembly_depth``. Every descriptor gains
    ``component``, ``component_path``, and ``component_parent`` keys:
    ``None`` for a document's own features (Part features, or an Assembly's
    top-level features), or the owning component's name/path for a
    component-derived feature. ``component_parent`` is the immediate parent
    component name when the component is nested inside a sub-assembly,
    otherwise ``None``. A component that cannot be resolved (suppressed,
    lightweight-and-unloaded, missing file) is represented by one descriptor
    with ``type: "UnresolvedComponent"`` instead of being silently dropped.

    Args:
        include_suppressed (bool): The include suppressed value. Defaults to False.
            Applied independently to the assembly's own features and to
            each component's features.
        max_assembly_depth (int): How many levels of sub-assembly to
            recurse into. Defaults to 2. Ignored for Part documents. A
            component beyond the configured depth still appears in the
            result as a single descriptor (name + path), not expanded.

    Returns:
        AdapterResult[list[dict[str, Any]]]: The result produced by the operation.
    """
    pass
open_model abstractmethod async
open_model(file_path: str) -> AdapterResult[SolidWorksModel]

Open a SolidWorks model (part, assembly, or drawing).

Parameters:

Name Type Description Default
file_path str

Path to the target file.

required

Returns:

Type Description
AdapterResult[SolidWorksModel]

AdapterResult[SolidWorksModel]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
@abstractmethod
async def open_model(self, file_path: str) -> AdapterResult[SolidWorksModel]:
    """Open a SolidWorks model (part, assembly, or drawing).

    Args:
        file_path (str): Path to the target file.

    Returns:
        AdapterResult[SolidWorksModel]: The result produced by the operation.
    """
    pass
save_file async
save_file(file_path: str | None = None) -> AdapterResult[Any]

Save the active model to the existing path or the provided path.

Parameters:

Name Type Description Default
file_path str | None

Path to the target file. Defaults to None.

None

Returns:

Type Description
AdapterResult[Any]

AdapterResult[Any]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
async def save_file(self, file_path: str | None = None) -> AdapterResult[Any]:
    """Save the active model to the existing path or the provided path.

    Args:
        file_path (str | None): Path to the target file. Defaults to None.

    Returns:
        AdapterResult[Any]: The result produced by the operation.
    """
    return AdapterResult(
        status=AdapterResultStatus.ERROR,
        error="save_file is not implemented by this adapter",
    )
set_dimension abstractmethod async
set_dimension(name: str, value: float) -> AdapterResult[None]

Set the value of a dimension.

Parameters:

Name Type Description Default
name str

The name value.

required
value float

The value value.

required

Returns:

Type Description
AdapterResult[None]

AdapterResult[None]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
@abstractmethod
async def set_dimension(self, name: str, value: float) -> AdapterResult[None]:
    """Set the value of a dimension.

    Args:
        name (str): The name value.
        value (float): The value value.

    Returns:
        AdapterResult[None]: The result produced by the operation.
    """
    pass
sketch_circular_pattern async
sketch_circular_pattern(entities: list[str], angle: float, count: int) -> AdapterResult[str]

Create a circular pattern of sketch entities around the sketch origin.

The rotation axis is always the sketch origin — SW's CreateCircularSketchStepAndRepeat has no pattern-centre parameter and derives the axis from the seed's geometry. Place the seed entity at the desired radius from the origin.

Parameters:

Name Type Description Default
entities list[str]

The entities value.

required
angle float

The angle value.

required
count int

The count value.

required

Returns:

Type Description
AdapterResult[str]

AdapterResult[str]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
async def sketch_circular_pattern(
    self,
    entities: list[str],
    angle: float,
    count: int,
) -> AdapterResult[str]:
    """Create a circular pattern of sketch entities around the sketch origin.

    The rotation axis is always the sketch origin — SW's
    ``CreateCircularSketchStepAndRepeat`` has no pattern-centre
    parameter and derives the axis from the seed's geometry. Place
    the seed entity at the desired radius from the origin.

    Args:
        entities (list[str]): The entities value.
        angle (float): The angle value.
        count (int): The count value.

    Returns:
        AdapterResult[str]: The result produced by the operation.
    """
    return AdapterResult(
        status=AdapterResultStatus.ERROR,
        error="sketch_circular_pattern is not implemented by this adapter",
    )
sketch_linear_pattern async
sketch_linear_pattern(entities: list[str], direction_x: float, direction_y: float, spacing: float, count: int) -> AdapterResult[str]

Create a linear pattern of sketch entities.

Parameters:

Name Type Description Default
entities list[str]

The entities value.

required
direction_x float

The direction x value.

required
direction_y float

The direction y value.

required
spacing float

The spacing value.

required
count int

The count value.

required

Returns:

Type Description
AdapterResult[str]

AdapterResult[str]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
async def sketch_linear_pattern(
    self,
    entities: list[str],
    direction_x: float,
    direction_y: float,
    spacing: float,
    count: int,
) -> AdapterResult[str]:
    """Create a linear pattern of sketch entities.

    Args:
        entities (list[str]): The entities value.
        direction_x (float): The direction x value.
        direction_y (float): The direction y value.
        spacing (float): The spacing value.
        count (int): The count value.

    Returns:
        AdapterResult[str]: The result produced by the operation.
    """
    return AdapterResult(
        status=AdapterResultStatus.ERROR,
        error="sketch_linear_pattern is not implemented by this adapter",
    )
sketch_mirror async
sketch_mirror(entities: list[str], mirror_line: str) -> AdapterResult[str]

Mirror sketch entities about a mirror line.

Parameters:

Name Type Description Default
entities list[str]

The entities value.

required
mirror_line str

The mirror line value.

required

Returns:

Type Description
AdapterResult[str]

AdapterResult[str]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
async def sketch_mirror(
    self, entities: list[str], mirror_line: str
) -> AdapterResult[str]:
    """Mirror sketch entities about a mirror line.

    Args:
        entities (list[str]): The entities value.
        mirror_line (str): The mirror line value.

    Returns:
        AdapterResult[str]: The result produced by the operation.
    """
    return AdapterResult(
        status=AdapterResultStatus.ERROR,
        error="sketch_mirror is not implemented by this adapter",
    )
sketch_offset async
sketch_offset(entities: list[str], offset_distance: float, reverse_direction: bool) -> AdapterResult[str]

Offset sketch entities.

Parameters:

Name Type Description Default
entities list[str]

The entities value.

required
offset_distance float

The offset distance value.

required
reverse_direction bool

The reverse direction value.

required

Returns:

Type Description
AdapterResult[str]

AdapterResult[str]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/base.py
async def sketch_offset(
    self,
    entities: list[str],
    offset_distance: float,
    reverse_direction: bool,
) -> AdapterResult[str]:
    """Offset sketch entities.

    Args:
        entities (list[str]): The entities value.
        offset_distance (float): The offset distance value.
        reverse_direction (bool): The reverse direction value.

    Returns:
        AdapterResult[str]: The result produced by the operation.
    """
    return AdapterResult(
        status=AdapterResultStatus.ERROR,
        error="sketch_offset is not implemented by this adapter",
    )
update_metrics
update_metrics(operation_time: float, success: bool) -> None

Update adapter metrics.

Parameters:

Name Type Description Default
operation_time float

The operation time value.

required
success bool

The success value.

required

Returns:

Name Type Description
None None

None.

Source code in src/solidworks_mcp/adapters/base.py
def update_metrics(self, operation_time: float, success: bool) -> None:
    """Update adapter metrics.

    Args:
        operation_time (float): The operation time value.
        success (bool): The success value.

    Returns:
        None: None.
    """
    self._metrics["operations_count"] += 1
    if not success:
        self._metrics["errors_count"] += 1

    # Update average response time
    current_avg = self._metrics["average_response_time"]
    count = self._metrics["operations_count"]
    self._metrics["average_response_time"] = (
        current_avg * (count - 1) + operation_time
    ) / count

SolidWorksMCPConfig

Bases: BaseModel

Main configuration for SolidWorks MCP Server.

Attributes:

Name Type Description
adapter_type AdapterType

The adapter type value.

allowed_hosts list[str]

The allowed hosts value.

allowed_origins list[str]

The allowed origins value.

api_key SecretStr | None

The api key value.

api_key_required bool

The api key required value.

api_keys list[str]

The api keys value.

cache_dir Path | None

The cache dir value.

circuit_breaker_enabled bool

The circuit breaker enabled value.

circuit_breaker_threshold int

The circuit breaker threshold value.

circuit_breaker_timeout int

The circuit breaker timeout value.

complexity_parameter_threshold int

The complexity parameter threshold value.

complexity_score_threshold float

The complexity score threshold value.

connection_pool_size int

The connection pool size value.

connection_pooling bool

The connection pooling value.

cors_origins list[str]

The cors origins value.

data_dir Path

The data dir value.

database_url str

The database url value.

debug bool

The debug value.

deployment_mode DeploymentMode

The deployment mode value.

enable_analysis_tools bool

The enable analysis tools value.

enable_audit_logging bool

The enable audit logging value.

enable_circuit_breaker bool

The enable circuit breaker value.

enable_connection_pooling bool

The enable connection pooling value.

enable_cors bool

The enable cors value.

enable_design_tables bool

The enable design tables value.

enable_intelligent_routing bool

The enable intelligent routing value.

enable_macro_recording bool

The enable macro recording value.

enable_pdm bool

The enable pdm value.

enable_rate_limiting bool

The enable rate limiting value.

enable_response_cache bool

The enable response cache value.

enable_sql_integration bool

The enable sql integration value.

enable_windows_validation bool

The enable windows validation value.

host str

The host value.

log_file Path | None

The log file value.

log_level str

The log level value.

max_connections int

The max connections value.

max_retries int

The max retries value.

mock_solidworks bool

The mock solidworks value.

model_config Any

The model config value.

pdm_server str | None

The pdm server value.

pdm_vault str | None

The pdm vault value.

port int

The port value.

rate_limit_enabled bool

The rate limit enabled value.

rate_limit_per_minute int

The rate limit per minute value.

response_cache_max_entries int

The response cache max entries value.

response_cache_ttl_seconds int

The response cache ttl seconds value.

security_level SecurityLevel

The security level value.

solidworks_path str | None

The solidworks path value.

solidworks_year int | None

The solidworks year value.

sql_connection str | None

The sql connection value.

state_file str | None

The state file value.

testing bool

The testing value.

timeout_seconds float

The timeout seconds value.

worker_processes int

The worker processes value.

Attributes
can_use_solidworks property
can_use_solidworks: bool

Check if SolidWorks integration is possible.

Returns:

Name Type Description
bool bool

True if use solidworks, otherwise False.

is_windows property
is_windows: bool

Check if running on Windows.

Returns:

Name Type Description
bool bool

True if windows, otherwise False.

Methods:
from_env classmethod
from_env(env_file: str | None = None) -> SolidWorksMCPConfig

Build configuration from environment variables.

Parameters:

Name Type Description Default
env_file str | None

The env file value. Defaults to None.

None

Returns:

Name Type Description
SolidWorksMCPConfig SolidWorksMCPConfig

The result produced by the operation.

Source code in src/solidworks_mcp/config.py
@classmethod
def from_env(cls, env_file: str | None = None) -> SolidWorksMCPConfig:
    """Build configuration from environment variables.

    Args:
        env_file (str | None): The env file value. Defaults to None.

    Returns:
        SolidWorksMCPConfig: The result produced by the operation.
    """
    import json

    env_prefix = "SOLIDWORKS_MCP_"
    raw_values: dict[str, Any] = {}

    list_like_fields = {"cors_origins", "allowed_hosts", "api_keys"}

    def _coerce_env_value(key: str, value: Any) -> Any:
        """Build internal coerce env value.

        Args:
            key (str): The key value.
            value (Any): The value value.

        Returns:
            Any: The result produced by the operation.
        """
        if not isinstance(value, str):
            return value
        if key in list_like_fields:
            stripped = value.strip()
            if stripped.startswith("[") and stripped.endswith("]"):
                try:
                    parsed = json.loads(stripped)
                    if isinstance(parsed, list):
                        return parsed
                except Exception:
                    # Leave original value for Pydantic to validate/report.
                    return value
        return value

    if env_file and Path(env_file).exists():
        for key, value in dotenv_values(env_file).items():
            if key and key.startswith(env_prefix) and value is not None:
                field_name = key[len(env_prefix) :].lower()
                raw_values[field_name] = _coerce_env_value(field_name, value)

    for key, value in os.environ.items():
        if key.startswith(env_prefix):
            field_name = key[len(env_prefix) :].lower()
            raw_values[field_name] = _coerce_env_value(field_name, value)

    return cls(**raw_values)
get_database_config
get_database_config() -> dict[str, Any]

Get database configuration.

Returns:

Type Description
dict[str, Any]

dict[str, Any]: A dictionary containing the resulting values.

Source code in src/solidworks_mcp/config.py
def get_database_config(self) -> dict[str, Any]:
    """Get database configuration.

    Returns:
        dict[str, Any]: A dictionary containing the resulting values.
    """
    return {
        "url": self.database_url,
        "echo": self.debug,
    }
get_security_config
get_security_config() -> dict[str, Any]

Get security configuration.

Returns:

Type Description
dict[str, Any]

dict[str, Any]: A dictionary containing the resulting values.

Source code in src/solidworks_mcp/config.py
def get_security_config(self) -> dict[str, Any]:
    """Get security configuration.

    Returns:
        dict[str, Any]: A dictionary containing the resulting values.
    """
    return {
        "api_key": self.api_key.get_secret_value() if self.api_key else None,
        "allowed_hosts": self.allowed_hosts,
        "enable_cors": self.enable_cors,
        "cors_origins": self.cors_origins,
        "enable_rate_limiting": self.enable_rate_limiting,
        "rate_limit_per_minute": self.rate_limit_per_minute,
        "security_level": self.security_level,
    }
model_post_init
model_post_init(__context: Any) -> None

Post-initialization setup.

Parameters:

Name Type Description Default
__context Any

The context value.

required

Returns:

Name Type Description
None None

None.

Source code in src/solidworks_mcp/config.py
def model_post_init(self, __context: Any) -> None:
    """Post-initialization setup.

    Args:
        __context (Any): The context value.

    Returns:
        None: None.
    """
    if self.cache_dir is None:
        self.cache_dir = self.data_dir / "cache"
    if self.log_file is None:
        self.log_file = self.data_dir / "logs" / "server.log"

    # Ensure data directories exist
    self.data_dir.mkdir(parents=True, exist_ok=True)
    self.cache_dir.mkdir(parents=True, exist_ok=True)
    self.log_file.parent.mkdir(parents=True, exist_ok=True)

    # Set testing defaults
    if self.testing:
        self.mock_solidworks = True
        self.adapter_type = AdapterType.MOCK
set_cache_dir classmethod
set_cache_dir(v: Path | None, info: ValidationInfo) -> Path

Set default cache directory.

Parameters:

Name Type Description Default
v Path | None

The v value.

required
info ValidationInfo

The info value.

required

Returns:

Name Type Description
Path Path

The result produced by the operation.

Source code in src/solidworks_mcp/config.py
@field_validator("cache_dir")
@classmethod
def set_cache_dir(cls, v: Path | None, info: ValidationInfo) -> Path:
    """Set default cache directory.

    Args:
        v (Path | None): The v value.
        info (ValidationInfo): The info value.

    Returns:
        Path: The result produced by the operation.
    """
    if v is None:
        data_dir = cast(
            Path,
            info.data.get("data_dir", Path.home() / ".solidworks_mcp"),
        )
        return data_dir / "cache"
    return v
set_log_file classmethod
set_log_file(v: Path | None, info: ValidationInfo) -> Path

Set default log file path.

Parameters:

Name Type Description Default
v Path | None

The v value.

required
info ValidationInfo

The info value.

required

Returns:

Name Type Description
Path Path

The result produced by the operation.

Source code in src/solidworks_mcp/config.py
@field_validator("log_file")
@classmethod
def set_log_file(cls, v: Path | None, info: ValidationInfo) -> Path:
    """Set default log file path.

    Args:
        v (Path | None): The v value.
        info (ValidationInfo): The info value.

    Returns:
        Path: The result produced by the operation.
    """
    if v is None:
        data_dir = cast(
            Path,
            info.data.get("data_dir", Path.home() / ".solidworks_mcp"),
        )
        return data_dir / "logs" / "server.log"
    return v
sync_legacy_alias_fields
sync_legacy_alias_fields() -> SolidWorksMCPConfig

Sync test/developer alias fields into canonical runtime fields.

Several fixtures and scripts still populate compatibility fields such as rate_limit_enabled and connection_pooling. Runtime code reads the canonical fields, so normalize them here after validation.

Returns:

Name Type Description
SolidWorksMCPConfig SolidWorksMCPConfig

The result produced by the operation.

Source code in src/solidworks_mcp/config.py
@model_validator(mode="after")
def sync_legacy_alias_fields(self) -> SolidWorksMCPConfig:
    """Sync test/developer alias fields into canonical runtime fields.

    Several fixtures and scripts still populate compatibility fields such as
    ``rate_limit_enabled`` and ``connection_pooling``. Runtime code reads the canonical
    fields, so normalize them here after validation.

    Returns:
        SolidWorksMCPConfig: The result produced by the operation.
    """
    self.enable_circuit_breaker = self.circuit_breaker_enabled
    self.enable_connection_pooling = self.connection_pooling
    self.connection_pool_size = self.max_connections
    self.enable_rate_limiting = self.rate_limit_enabled
    if self.allowed_origins and not self.cors_origins:
        self.cors_origins = list(self.allowed_origins)
    return self
validate_adapter_type classmethod
validate_adapter_type(v: AdapterType, info: ValidationInfo) -> AdapterType

Validate adapter type based on platform.

Parameters:

Name Type Description Default
v AdapterType

The v value.

required
info ValidationInfo

The info value.

required

Returns:

Name Type Description
AdapterType AdapterType

The result produced by the operation.

Source code in src/solidworks_mcp/config.py
@field_validator("adapter_type")
@classmethod
def validate_adapter_type(cls, v: AdapterType, info: ValidationInfo) -> AdapterType:
    """Validate adapter type based on platform.

    Args:
        v (AdapterType): The v value.
        info (ValidationInfo): The info value.

    Returns:
        AdapterType: The result produced by the operation.
    """
    return v
validate_complexity_parameter_threshold classmethod
validate_complexity_parameter_threshold(v: int) -> int

Validate the complexity parameter threshold.

Parameters:

Name Type Description Default
v int

The v value.

required

Returns:

Name Type Description
int int

The computed numeric result.

Raises:

Type Description
ValueError

Complexity_parameter_threshold must be >= 1.

Source code in src/solidworks_mcp/config.py
@field_validator("complexity_parameter_threshold")
@classmethod
def validate_complexity_parameter_threshold(cls, v: int) -> int:
    """Validate the complexity parameter threshold.

    Args:
        v (int): The v value.

    Returns:
        int: The computed numeric result.

    Raises:
        ValueError: Complexity_parameter_threshold must be >= 1.
    """
    if v < 1:
        raise ValueError("complexity_parameter_threshold must be >= 1")
    return v
validate_complexity_score_threshold classmethod
validate_complexity_score_threshold(v: float) -> float

Validate the complexity score threshold.

Parameters:

Name Type Description Default
v float

The v value.

required

Returns:

Name Type Description
float float

The computed numeric result.

Raises:

Type Description
ValueError

Complexity_score_threshold must be in (0, 1].

Source code in src/solidworks_mcp/config.py
@field_validator("complexity_score_threshold")
@classmethod
def validate_complexity_score_threshold(cls, v: float) -> float:
    """Validate the complexity score threshold.

    Args:
        v (float): The v value.

    Returns:
        float: The computed numeric result.

    Raises:
        ValueError: Complexity_score_threshold must be in (0, 1].
    """
    if v <= 0 or v > 1:
        raise ValueError("complexity_score_threshold must be in (0, 1]")
    return v
validate_port classmethod
validate_port(v: int) -> int

Validate the port.

Parameters:

Name Type Description Default
v int

The v value.

required

Returns:

Name Type Description
int int

The computed numeric result.

Raises:

Type Description
ValueError

Port must be between 1 and 65535.

Source code in src/solidworks_mcp/config.py
@field_validator("port")
@classmethod
def validate_port(cls, v: int) -> int:
    """Validate the port.

    Args:
        v (int): The v value.

    Returns:
        int: The computed numeric result.

    Raises:
        ValueError: Port must be between 1 and 65535.
    """
    if v < 1 or v > 65535:
        raise ValueError("Port must be between 1 and 65535")
    return v
validate_response_cache_max_entries classmethod
validate_response_cache_max_entries(v: int) -> int

Validate response cache size.

Parameters:

Name Type Description Default
v int

The v value.

required

Returns:

Name Type Description
int int

The computed numeric result.

Raises:

Type Description
ValueError

Response_cache_max_entries must be >= 1.

Source code in src/solidworks_mcp/config.py
@field_validator("response_cache_max_entries")
@classmethod
def validate_response_cache_max_entries(cls, v: int) -> int:
    """Validate response cache size.

    Args:
        v (int): The v value.

    Returns:
        int: The computed numeric result.

    Raises:
        ValueError: Response_cache_max_entries must be >= 1.
    """
    if v < 1:
        raise ValueError("response_cache_max_entries must be >= 1")
    return v
validate_response_cache_ttl_seconds classmethod
validate_response_cache_ttl_seconds(v: int) -> int

Validate default response cache TTL.

Parameters:

Name Type Description Default
v int

The v value.

required

Returns:

Name Type Description
int int

The computed numeric result.

Raises:

Type Description
ValueError

Response_cache_ttl_seconds must be >= 1.

Source code in src/solidworks_mcp/config.py
@field_validator("response_cache_ttl_seconds")
@classmethod
def validate_response_cache_ttl_seconds(cls, v: int) -> int:
    """Validate default response cache TTL.

    Args:
        v (int): The v value.

    Returns:
        int: The computed numeric result.

    Raises:
        ValueError: Response_cache_ttl_seconds must be >= 1.
    """
    if v < 1:
        raise ValueError("response_cache_ttl_seconds must be >= 1")
    return v
validate_timeout classmethod
validate_timeout(v: float) -> float

Validate the timeout.

Parameters:

Name Type Description Default
v float

The v value.

required

Returns:

Name Type Description
float float

The computed numeric result.

Raises:

Type Description
ValueError

Timeout_seconds must be > 0.

Source code in src/solidworks_mcp/config.py
@field_validator("timeout_seconds")
@classmethod
def validate_timeout(cls, v: float) -> float:
    """Validate the timeout.

    Args:
        v (float): The v value.

    Returns:
        float: The computed numeric result.

    Raises:
        ValueError: Timeout_seconds must be > 0.
    """
    if v <= 0:
        raise ValueError("timeout_seconds must be > 0")
    return v

VbaGeneratorAdapter

VbaGeneratorAdapter(backing_adapter: Any, macro_executor: VbaMacroExecutor | None = None)

Adapter that executes complex operations through VBA-oriented flow.

This adapter currently uses the wrapped COM adapter for final execution, but annotates responses as VBA-routed and can be extended to execute generated macros directly in future iterations.

Parameters:

Name Type Description Default
backing_adapter Any

The backing adapter value.

required
macro_executor VbaMacroExecutor | None

The macro executor value. Defaults to None.

None

Attributes:

Name Type Description
_backing_adapter Any

The backing adapter value.

_macro_executor Any

The macro executor value.

config Any

The config value.

Initialize the vba generator adapter.

Parameters:

Name Type Description Default
backing_adapter Any

The backing adapter value.

required
macro_executor VbaMacroExecutor | None

The macro executor value. Defaults to None.

None

Returns:

Name Type Description
None None

None.

Source code in src/solidworks_mcp/adapters/vba_adapter.py
def __init__(
    self,
    backing_adapter: Any,
    macro_executor: VbaMacroExecutor | None = None,
) -> None:
    """Initialize the vba generator adapter.

    Args:
        backing_adapter (Any): The backing adapter value.
        macro_executor (VbaMacroExecutor | None): The macro executor value. Defaults to
                                                  None.

    Returns:
        None: None.
    """
    self._backing_adapter = backing_adapter
    self._macro_executor = macro_executor or VbaMacroExecutor()
    self.config = getattr(backing_adapter, "config", None)
Methods:
__getattr__
__getattr__(item: str) -> Any

Delegate unknown members to backing adapter.

Parameters:

Name Type Description Default
item str

The item value.

required

Returns:

Name Type Description
Any Any

The result produced by the operation.

Source code in src/solidworks_mcp/adapters/vba_adapter.py
def __getattr__(self, item: str) -> Any:
    """Delegate unknown members to backing adapter.

    Args:
        item (str): The item value.

    Returns:
        Any: The result produced by the operation.
    """
    return getattr(self._backing_adapter, item)
connect async
connect() -> None

Connect to SolidWorks using wrapped adapter.

Returns:

Name Type Description
None None

None.

Source code in src/solidworks_mcp/adapters/vba_adapter.py
async def connect(self) -> None:
    """Connect to SolidWorks using wrapped adapter.

    Returns:
        None: None.
    """
    await self._backing_adapter.connect()
create_extrusion async
create_extrusion(params: ExtrusionParameters) -> AdapterResult[Any]

Create the extrusion.

Parameters:

Name Type Description Default
params ExtrusionParameters

The params value.

required

Returns:

Type Description
AdapterResult[Any]

AdapterResult[Any]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/vba_adapter.py
async def create_extrusion(
    self,
    params: ExtrusionParameters,
) -> AdapterResult[Any]:
    """Create the extrusion.

    Args:
        params (ExtrusionParameters): The params value.

    Returns:
        AdapterResult[Any]: The result produced by the operation.
    """
    return await self._run_with_vba_metadata(
        operation="create_extrusion",
        payload=params,
        com_call=self._backing_adapter.create_extrusion,
        vba_code=self._generate_extrusion_vba(params),
    )
create_loft async
create_loft(params: LoftParameters) -> AdapterResult[Any]

Create the loft.

Parameters:

Name Type Description Default
params LoftParameters

The params value.

required

Returns:

Type Description
AdapterResult[Any]

AdapterResult[Any]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/vba_adapter.py
async def create_loft(
    self,
    params: LoftParameters,
) -> AdapterResult[Any]:
    """Create the loft.

    Args:
        params (LoftParameters): The params value.

    Returns:
        AdapterResult[Any]: The result produced by the operation.
    """
    return await self._run_with_vba_metadata(
        operation="create_loft",
        payload=params,
        com_call=self._backing_adapter.create_loft,
        vba_code=self._generate_loft_vba(params),
    )
create_revolve async
create_revolve(params: RevolveParameters) -> AdapterResult[Any]

Create the revolve.

Parameters:

Name Type Description Default
params RevolveParameters

The params value.

required

Returns:

Type Description
AdapterResult[Any]

AdapterResult[Any]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/vba_adapter.py
async def create_revolve(
    self,
    params: RevolveParameters,
) -> AdapterResult[Any]:
    """Create the revolve.

    Args:
        params (RevolveParameters): The params value.

    Returns:
        AdapterResult[Any]: The result produced by the operation.
    """
    return await self._run_with_vba_metadata(
        operation="create_revolve",
        payload=params,
        com_call=self._backing_adapter.create_revolve,
        vba_code=self._generate_revolve_vba(params),
    )
create_sweep async
create_sweep(params: SweepParameters) -> AdapterResult[Any]

Create the sweep.

Parameters:

Name Type Description Default
params SweepParameters

The params value.

required

Returns:

Type Description
AdapterResult[Any]

AdapterResult[Any]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/vba_adapter.py
async def create_sweep(
    self,
    params: SweepParameters,
) -> AdapterResult[Any]:
    """Create the sweep.

    Args:
        params (SweepParameters): The params value.

    Returns:
        AdapterResult[Any]: The result produced by the operation.
    """
    return await self._run_with_vba_metadata(
        operation="create_sweep",
        payload=params,
        com_call=self._backing_adapter.create_sweep,
        vba_code=self._generate_sweep_vba(params),
    )
disconnect async
disconnect() -> None

Disconnect wrapped adapter.

Returns:

Name Type Description
None None

None.

Source code in src/solidworks_mcp/adapters/vba_adapter.py
async def disconnect(self) -> None:
    """Disconnect wrapped adapter.

    Returns:
        None: None.
    """
    await self._backing_adapter.disconnect()
execute_macro async
execute_macro(macro_code: str, macro_name: str = 'GeneratedMacro', subroutine: str = 'Main') -> AdapterResult[Any]

Provide execute macro support for the vba generator adapter.

Parameters:

Name Type Description Default
macro_code str

The macro code value.

required
macro_name str

The macro name value. Defaults to "GeneratedMacro".

'GeneratedMacro'
subroutine str

The subroutine value. Defaults to "Main".

'Main'

Returns:

Type Description
AdapterResult[Any]

AdapterResult[Any]: The result produced by the operation.

Source code in src/solidworks_mcp/adapters/vba_adapter.py
async def execute_macro(
    self,
    macro_code: str,
    macro_name: str = "GeneratedMacro",
    subroutine: str = "Main",
) -> AdapterResult[Any]:
    """Provide execute macro support for the vba generator adapter.

    Args:
        macro_code (str): The macro code value.
        macro_name (str): The macro name value. Defaults to "GeneratedMacro".
        subroutine (str): The subroutine value. Defaults to "Main".

    Returns:
        AdapterResult[Any]: The result produced by the operation.
    """
    request = MacroExecutionRequest(
        macro_code=macro_code,
        macro_name=macro_name,
        subroutine=subroutine,
    )
    return await self._macro_executor.execute_macro(
        request=request,
        backing_adapter=self._backing_adapter,
    )
get_macro_execution_history
get_macro_execution_history(macro_name: str | None = None) -> dict[str, Any]

Retrieve VBA macro execution history.

Parameters:

Name Type Description Default
macro_name str | None

The macro name value. Defaults to None.

None

Returns:

Type Description
dict[str, Any]

dict[ str, Any,

dict[str, Any]

]: A dictionary containing the resulting values.

Source code in src/solidworks_mcp/adapters/vba_adapter.py
def get_macro_execution_history(
    self, macro_name: str | None = None
) -> dict[
    str,
    Any,
]:
    """Retrieve VBA macro execution history.

    Args:
        macro_name (str | None): The macro name value. Defaults to None.

    Returns:
        dict[
            str,
            Any,
        ]: A dictionary containing the resulting values.
    """
    history = self._macro_executor.get_execution_history(macro_name)
    return {key: value.__dict__ for key, value in history.items()}
health_check async
health_check() -> Any

Return wrapped adapter health with VBA route marker.

Returns:

Name Type Description
Any Any

The result produced by the operation.

Source code in src/solidworks_mcp/adapters/vba_adapter.py
async def health_check(self) -> Any:
    """Return wrapped adapter health with VBA route marker.

    Returns:
        Any: The result produced by the operation.
    """
    health = await self._backing_adapter.health_check()
    if hasattr(health, "metrics"):
        metrics = dict(health.metrics or {})
        metrics["route"] = "vba"
        health.metrics = metrics
    return health
is_connected
is_connected() -> bool

Return wrapped adapter connection state.

Returns:

Name Type Description
bool bool

True if connected, otherwise False.

Source code in src/solidworks_mcp/adapters/vba_adapter.py
def is_connected(self) -> bool:
    """Return wrapped adapter connection state.

    Returns:
        bool: True if connected, otherwise False.
    """
    return bool(self._backing_adapter.is_connected())

Functions:

_register_default_adapters

_register_default_adapters() -> None

Register default adapter implementations.

Returns:

Name Type Description
None None

None.

Source code in src/solidworks_mcp/adapters/factory.py
def _register_default_adapters() -> None:
    """Register default adapter implementations.

    Returns:
        None: None.
    """
    # Always register mock adapter
    AdapterFactory.register_adapter(AdapterType.MOCK, MockSolidWorksAdapter)
    AdapterFactory.register_adapter(AdapterType.VBA, VbaGeneratorAdapter)  # type: ignore[arg-type]

    # Register pywin32 adapter if on Windows
    if platform.system() == "Windows":
        try:
            from .pywin32_adapter import PyWin32Adapter

            AdapterFactory.register_adapter(AdapterType.PYWIN32, PyWin32Adapter)
        except ImportError:
            # pywin32 not available, will fall back to mock
            pass

create_adapter async

create_adapter(config: SolidWorksMCPConfig) -> SolidWorksAdapter

Async factory function for creating SolidWorks adapters.

Parameters:

Name Type Description Default
config SolidWorksMCPConfig

Configuration values for the operation.

required

Returns:

Name Type Description
SolidWorksAdapter SolidWorksAdapter

The result produced by the operation.

Source code in src/solidworks_mcp/adapters/factory.py
async def create_adapter(config: SolidWorksMCPConfig) -> SolidWorksAdapter:
    """Async factory function for creating SolidWorks adapters.

    Args:
        config (SolidWorksMCPConfig): Configuration values for the operation.

    Returns:
        SolidWorksAdapter: The result produced by the operation.
    """
    # Register adapters if not already done
    _register_default_adapters()

    # Create adapter using factory
    adapter = AdapterFactory.create_adapter(config)

    return adapter