Skip to content

solidworks_mcp.tools.file_management

solidworks_mcp.tools.file_management

File management tools for SolidWorks MCP Server.

Provides tools for managing SolidWorks files including save, save as, file properties, and reference management.

Classes

ClassifyFeatureTreeInput

Bases: CompatInput

Input schema for feature-family classification.

Attributes:

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

The features value.

include_suppressed bool

The include suppressed value.

model_info dict[str, Any] | None

The model info value.

CompatInput

Bases: BaseModel

Base schema allowing legacy/extra fields used by existing tests.

Attributes:

Name Type Description
model_config Any

The model config value.

FileOperationInput

Bases: CompatInput

Input schema for file operations.

Attributes:

Name Type Description
file_path str | None

The file path value.

include_system bool

The include system value.

operation str

The operation value.

parameters dict[str, Any] | None

The parameters value.

properties dict[str, Any] | None

The properties value.

source_path str | None

The source path value.

target_path str | None

The target path value.

FormatConversionInput

Bases: CompatInput

Input schema for format conversion.

Attributes:

Name Type Description
conversion_options dict[str, Any] | None

The conversion options value.

invalid_format str | None

The invalid format value.

output_path str | None

The output path value.

quality str

The quality value.

source_file str

The source file value.

source_format str | None

The source format value.

target_file str | None

The target file value.

target_format str

The target format value.

units str

The units value.

ListFeaturesInput

Bases: CompatInput

Input schema for feature tree listing.

Attributes:

Name Type Description
include_suppressed bool

The include suppressed value.

LoadAssemblyInput

Bases: CompatInput

Input schema for loading an assembly file.

Attributes:

Name Type Description
file_path str

The file path value.

LoadPartInput

Bases: CompatInput

Input schema for loading a part file.

Attributes:

Name Type Description
file_path str

The file path value.

SaveAsInput

Bases: CompatInput

Input schema for save as operation.

Attributes:

Name Type Description
file_path str

The file path value.

format_type str

The format type value.

overwrite bool

The overwrite value.

SaveAssemblyInput

Bases: CompatInput

Input schema for saving an assembly file.

Attributes:

Name Type Description
file_path str | None

The file path value.

overwrite bool

The overwrite value.

SaveFileInput

Bases: CompatInput

Input schema for saving a file.

Attributes:

Name Type Description
file_path str | None

The file path value.

force_save bool

The force save value.

SavePartInput

Bases: CompatInput

Input schema for saving a part file.

Attributes:

Name Type Description
file_path str | None

The file path value.

overwrite bool

The overwrite value.

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,
    }
Functions
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_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
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_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) -> AdapterResult[list[dict[str, Any]]]

List model features from the feature tree.

Parameters:

Name Type Description Default
include_suppressed bool

The include suppressed value. Defaults to False.

False

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
) -> AdapterResult[list[dict[str, Any]]]:
    """List model features from the feature tree.

    Args:
        include_suppressed (bool): The include suppressed value. Defaults to False.

    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

Functions

classify_feature_tree_snapshot

classify_feature_tree_snapshot(model_info: Mapping[str, Any] | None, features: list[Mapping[str, Any]] | None) -> dict[str, Any]

Classify a model family from model-info and feature-tree snapshots.

The output is intentionally simple and explainable so agents can use it as a planning primitive rather than as a black-box prediction.

Parameters:

Name Type Description Default
model_info Mapping[str, Any] | None

The model info value.

required
features list[Mapping[str, Any]] | None

The features value.

required

Returns:

Type Description
dict[str, Any]

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

Source code in src/solidworks_mcp/utils/feature_tree_classifier.py
def classify_feature_tree_snapshot(
    model_info: Mapping[str, Any] | None,
    features: list[Mapping[str, Any]] | None,
) -> dict[str, Any]:
    """Classify a model family from model-info and feature-tree snapshots.

    The output is intentionally simple and explainable so agents can use it as a planning
    primitive rather than as a black-box prediction.

    Args:
        model_info (Mapping[str, Any] | None): The model info value.
        features (list[Mapping[str, Any]] | None): The features value.

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

    feature_list = list(features or [])
    feature_texts = [_feature_text(feature) for feature in feature_list]
    document_type = _as_lower_text((model_info or {}).get("type")) or "unknown"

    evidence: list[str] = []
    warnings: list[str] = []
    next_actions: list[str] = []

    family = "unknown"
    workflow = "inspect-more"
    confidence = "low"
    needs_vba = False

    if document_type == "assembly" or _has_any(feature_texts, _ASSEMBLY_TOKENS):
        family = "assembly"
        workflow = "assembly-planning"
        confidence = "high" if document_type == "assembly" else "medium"
        evidence.append("Assembly document or mate/component evidence detected")
        next_actions.extend(
            [
                "List components and mates before planning inserts or edits",
                "Delegate part-level reconstruction for each component separately",
            ]
        )
    elif document_type == "drawing" or _has_any(feature_texts, _DRAWING_TOKENS):
        family = "drawing"
        workflow = "drawing-review"
        confidence = "high" if document_type == "drawing" else "medium"
        evidence.append("Drawing document or drawing-view evidence detected")
        next_actions.append("Use drawing tools instead of part-modeling tools")
    elif _has_any(feature_texts, _SHEET_METAL_TOKENS):
        family = "sheet_metal"
        workflow = "vba-sheet-metal"
        confidence = "high"
        needs_vba = True
        evidence.extend(
            _match_examples(feature_texts, _SHEET_METAL_TOKENS)
            or ["Sheet metal features detected in the tree"]
        )
        next_actions.extend(
            [
                "Preserve base-flange and bend dependency order",
                "If cuts appear between Unfold and Fold, keep them in flat-pattern state",
                "Prefer a VBA-aware reconstruction plan until direct sheet metal tools exist",
            ]
        )
    elif _has_any(feature_texts, _ADVANCED_SOLID_TOKENS):
        family = "advanced_solid"
        workflow = "vba-advanced-solid"
        confidence = "medium"
        needs_vba = True
        evidence.extend(
            _match_examples(feature_texts, _ADVANCED_SOLID_TOKENS)
            or ["Advanced solid or surface features detected"]
        )
        next_actions.extend(
            [
                "Plan around loft/sweep/shell boundaries before issuing build commands",
                "Prefer macro-backed execution for unsupported direct-MCP features",
            ]
        )
    elif _has_any(feature_texts, _REVOLVE_TOKENS):
        family = "revolve"
        workflow = "direct-mcp-revolve"
        confidence = "high"
        evidence.extend(
            _match_examples(feature_texts, _REVOLVE_TOKENS)
            or ["Revolve features detected"]
        )
        next_actions.extend(
            [
                "Locate the axis sketch or centerline before recreating the profile",
                "Verify the half-profile closes on the revolve axis",
            ]
        )
    elif _has_any(feature_texts, _EXTRUDE_TOKENS):
        family = "extrude"
        workflow = "direct-mcp-extrude"
        confidence = "high"
        evidence.extend(
            _match_examples(feature_texts, _EXTRUDE_TOKENS)
            or ["Extrude features detected"]
        )
        next_actions.extend(
            [
                "Read the driving sketch before recreating downstream cuts or fillets",
                "Verify closed-loop profiles before extrusion",
            ]
        )
    else:
        non_reference_count = 0
        sketch_like_count = 0
        for feature in feature_list:
            feature_type = _as_lower_text(feature.get("type"))
            if feature_type and feature_type not in {
                "refplane",
                "originprofilefeature",
            }:
                non_reference_count += 1
            if feature_type in {"profilefeature", "3dprofilefeature", "sketch"}:
                sketch_like_count += 1

        if sketch_like_count > 0 and sketch_like_count == non_reference_count:
            family = "sketch_only"
            workflow = "inspect-more"
            confidence = "low"
            evidence.append("Only sketch-like features were found in the tree snapshot")
            warnings.append(
                "Feature tree may be incomplete for this adapter/runtime; do not infer the 3D family from sketches alone"
            )
            next_actions.extend(
                [
                    "Combine feature-tree output with mass properties and exported images",
                    "Prefer reading the original file in SolidWorks before planning a rebuild",
                ]
            )
        else:
            warnings.append(
                "No strong feature-family evidence found; keep planning provisional"
            )
            next_actions.extend(
                [
                    "Inspect more of the model state before building",
                    "Avoid committing to direct-MCP or VBA-only paths until evidence improves",
                ]
            )

    return {
        "document_type": document_type or "unknown",
        "family": family,
        "recommended_workflow": workflow,
        "confidence": confidence,
        "needs_vba": needs_vba,
        "evidence": evidence,
        "warnings": warnings,
        "next_actions": next_actions,
        "feature_count": len(feature_list),
    }

register_file_management_tools async

register_file_management_tools(mcp: FastMCP, adapter: SolidWorksAdapter, config: dict[str, Any]) -> int

Register file management tools with FastMCP.

Registers essential file operations for SolidWorks document management including save operations, file format conversions, and file property access. These tools provide fundamental document lifecycle management capabilities.

Parameters:

Name Type Description Default
mcp FastMCP

The mcp value.

required
adapter SolidWorksAdapter

Adapter instance used for the operation.

required
config dict[str, Any]

Configuration values for the operation.

required

Returns:

Name Type Description
int int

The computed numeric result.

Example
from solidworks_mcp.tools.file_management import register_file_management_tools

tool_count = await register_file_management_tools(mcp, adapter, config)
print(f"Registered {tool_count} file management tools")
            Note:
                File management tools require an active SolidWorks document.
                Save operations preserve the current document state and metadata.
Source code in src/solidworks_mcp/tools/file_management.py
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
async def register_file_management_tools(
    mcp: FastMCP, adapter: SolidWorksAdapter, config: dict[str, Any]
) -> int:
    """Register file management tools with FastMCP.

    Registers essential file operations for SolidWorks document management including save
    operations, file format conversions, and file property access. These tools provide
    fundamental document lifecycle management capabilities.

    Args:
        mcp (FastMCP): The mcp value.
        adapter (SolidWorksAdapter): Adapter instance used for the operation.
        config (dict[str, Any]): Configuration values for the operation.

    Returns:
        int: The computed numeric result.

    Example:
                        ```python
                        from solidworks_mcp.tools.file_management import register_file_management_tools

                        tool_count = await register_file_management_tools(mcp, adapter, config)
                        print(f"Registered {tool_count} file management tools")
                        ```

                    Note:
                        File management tools require an active SolidWorks document.
                        Save operations preserve the current document state and metadata.
    """
    tool_count = 0

    def _coerce_input(model_cls, payload):
        """Accept legacy dict payloads from compatibility wrapper as well as model instances.

        Args:
            model_cls (Any): The model cls value.
            payload (Any): The payload value.

        Returns:
            Any: The result produced by the operation.
        """
        return (
            payload
            if isinstance(payload, model_cls)
            else model_cls.model_validate(payload)
        )

    def _result_value(payload: Any, *keys: str, default: Any = None) -> Any:
        """Read a value from adapter result payloads that may be dicts or model objects.

        Args:
            payload (Any): The payload value.
            *keys (str): Additional positional arguments forwarded to the call.
            default (Any): Fallback value returned when the operation fails. Defaults to None.

        Returns:
            Any: The result produced by the operation.
        """
        if payload is None:
            return default

        if isinstance(payload, dict):
            for key in keys:
                if key in payload and payload[key] is not None:
                    return payload[key]
            return default

        for key in keys:
            value = getattr(payload, key, None)
            if value is not None:
                return value
        return default

    @mcp.tool()
    async def save_file(input_data: SaveFileInput) -> dict[str, Any]:
        """Save the current SolidWorks model.

        Saves the currently active SolidWorks document to its existing file location. Essential
        for preserving work and maintaining document version control. Handles both modified and
        unmodified documents based on force_save setting.

        Args:
            input_data (SaveFileInput): The input data value.

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

        Example:
                            ```python
                            # Force save current model
                            result = await save_file({"force_save": True})

                            # Save only if modified
                            result = await save_file({"force_save": False})

                            if result["status"] == "success":
                                print(f"File saved at {result['timestamp']}")
                            ```

                        Note:
                            - Requires an open SolidWorks document
                            - Preserves original file location and format
                            - Updates document timestamp and metadata
                            - No effect if document is read-only
        """
        try:
            input_data = _coerce_input(SaveFileInput, input_data)
            if hasattr(adapter, "save_file"):
                result = await adapter.save_file(input_data.file_path)
                if result.is_success:
                    return {
                        "status": "success",
                        "message": "File saved successfully",
                        "data": result.data,
                        "execution_time": result.execution_time,
                    }
                return {
                    "status": "error",
                    "message": result.error or "Failed to save file",
                }

            return {
                "status": "success",
                "message": "File saved successfully",
                "timestamp": "2024-03-14T00:00:00Z",  # Would be actual timestamp
            }

        except Exception as e:
            logger.error(f"Error in save_file tool: {e}")
            return {
                "status": "error",
                "message": f"Unexpected error: {str(e)}",
            }

    @mcp.tool()
    async def save_as(input_data: SaveAsInput) -> dict[str, Any]:
        """Save the current model to a new location or format.

        Saves the currently active SolidWorks document with a new filename, location, or file
        format. Supports multiple export formats for interoperability with other CAD systems and
        manufacturing workflows.

        Args:
            input_data (SaveAsInput): The input data value.

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

        Example:
                            ```python
                            # Save as new SolidWorks file
                            result = await save_as({
                                "file_path": "C:/Projects/bracket_v2.sldprt",
                                "format_type": "solidworks",
                                "overwrite": False
                            })

                            # Export to STEP format
                            result = await save_as({
                                "file_path": "C:/Exports/bracket.step",
                                "format_type": "step",
                                "overwrite": True
                            })

                            # Export for 3D printing
                            result = await save_as({
                                "file_path": "C:/3DPrint/bracket.stl",
                                "format_type": "stl"
                            })
                            ```
        """
        try:
            input_data = _coerce_input(SaveAsInput, input_data)
            if hasattr(adapter, "save_file") and input_data.format_type.lower() in {
                "solidworks",
                "sldprt",
                "sldasm",
                "slddrw",
            }:
                result = await adapter.save_file(input_data.file_path)
                if result.is_success:
                    return {
                        "status": "success",
                        "message": f"File saved as: {input_data.file_path}",
                        "file_path": input_data.file_path,
                        "format": input_data.format_type,
                        "execution_time": result.execution_time,
                    }
                return {
                    "status": "error",
                    "message": result.error or "Failed to save file",
                }

            if hasattr(adapter, "export_file"):
                result = await adapter.export_file(
                    input_data.file_path,
                    input_data.format_type,
                )
                if result.is_success:
                    return {
                        "status": "success",
                        "message": f"File exported as: {input_data.file_path}",
                        "file_path": input_data.file_path,
                        "format": input_data.format_type,
                        "execution_time": result.execution_time,
                    }
                return {
                    "status": "error",
                    "message": result.error or "Failed to export file",
                }

            # Fallback for adapters without save/export support.
            return {
                "status": "success",
                "message": f"File saved as: {input_data.file_path}",
                "file_path": input_data.file_path,
                "format": input_data.format_type,
            }

        except Exception as e:
            logger.error(f"Error in save_as tool: {e}")
            return {
                "status": "error",
                "message": f"Unexpected error: {str(e)}",
            }

    @mcp.tool()
    async def get_file_properties() -> dict[str, Any]:
        """Get properties of the current SolidWorks file.

        Retrieves comprehensive metadata and properties of the currently active SolidWorks
        document. Provides essential file information for document management, version control,
        and project organization.

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

        Example:
                            ```python
                            result = await get_file_properties()

                            if result["status"] == "success":
                                props = result["properties"]

                                # Basic file info
                                file_info = props["file_info"]
                                print(f"File: {file_info['file_name']}")
                                print(f"Size: {file_info['file_size']}")
                                print(f"Type: {file_info['file_type']}")

                                # Technical properties
                                tech = props["technical_properties"]
                                print(f"Material: {tech['material']}")
                                print(f"Units: {tech['units']}")

                                # Document info
                                doc = props["document_info"]
                                print(f"Author: {doc['author']}")
                                print(f"Description: {doc['description']}")
                            ```

                        Note:
                            - Requires an active SolidWorks document
                            - Properties may vary based on document type
                            - Some properties may be empty if not set
                            - Technical properties depend on document configuration
        """
        # Simulated file properties - would get from adapter
        return {
            "status": "success",
            "properties": {
                "file_name": "Example.sldprt",
                "file_size": "2.5 MB",
                "created_date": "2024-03-14T00:00:00Z",
                "modified_date": "2024-03-14T12:00:00Z",
                "author": "User",
                "description": "SolidWorks part file",
                "material": "Default",
                "units": "millimeters",
            },
        }

    @mcp.tool()
    async def get_model_info() -> dict[str, Any]:
        """Get metadata for the active SolidWorks document.

        Returns a compact summary of the current model context that is useful for read-before-
        write LLM flows (document type, active configuration, and feature count).

        Returns:
            dict[str, Any]: A dictionary containing the resulting values.
        """
        try:
            if hasattr(adapter, "get_model_info"):
                result = await adapter.get_model_info()
                if result.is_success:
                    return {
                        "status": "success",
                        "model_info": result.data,
                        "execution_time": result.execution_time,
                    }
                return {
                    "status": "error",
                    "message": result.error or "Failed to get model info",
                }

            return {
                "status": "error",
                "message": "Active adapter does not support get_model_info",
            }
        except Exception as e:
            logger.error(f"Error in get_model_info tool: {e}")
            return {
                "status": "error",
                "message": f"Unexpected error: {str(e)}",
            }

    @mcp.tool()
    async def list_features(input_data: ListFeaturesInput) -> dict[str, Any]:
        """List feature-tree entries for the active SolidWorks document.

        Useful for read-before-write workflows where the agent must inspect existing model
        structure before adding or editing downstream features.

        Args:
            input_data (ListFeaturesInput): The input data value.

        Returns:
            dict[str, Any]: A dictionary containing the resulting values.
        """
        try:
            input_data = _coerce_input(ListFeaturesInput, input_data)
            if hasattr(adapter, "list_features"):
                result = await adapter.list_features(
                    include_suppressed=input_data.include_suppressed
                )
                if result.is_success:
                    return {
                        "status": "success",
                        "features": result.data or [],
                        "count": len(result.data or []),
                        "execution_time": result.execution_time,
                    }
                return {
                    "status": "error",
                    "message": result.error or "Failed to list features",
                }

            return {
                "status": "error",
                "message": "Active adapter does not support list_features",
            }
        except Exception as e:
            logger.error(f"Error in list_features tool: {e}")
            return {
                "status": "error",
                "message": f"Unexpected error: {str(e)}",
            }

    @mcp.tool()
    async def classify_feature_tree(
        input_data: ClassifyFeatureTreeInput,
    ) -> dict[str, Any]:
        """Classify the active model into a feature family from model-info and tree data.

        This is a read-before-write helper for delegation. It summarizes whether the current
        document looks like a direct-MCP solid, sheet metal workflow, advanced VBA-backed part,
        assembly, drawing, or an insufficient-evidence case.

        Args:
            input_data (ClassifyFeatureTreeInput): The input data value.

        Returns:
            dict[str, Any]: A dictionary containing the resulting values.
        """
        try:
            input_data = _coerce_input(ClassifyFeatureTreeInput, input_data)
            model_info = input_data.model_info
            features = input_data.features
            execution_time = 0.0

            if model_info is None and hasattr(adapter, "get_model_info"):
                model_result = await adapter.get_model_info()
                if model_result.is_success:
                    model_info = model_result.data
                    execution_time = max(
                        execution_time, model_result.execution_time or 0.0
                    )

            if features is None:
                if hasattr(adapter, "list_features"):
                    feature_result = await adapter.list_features(
                        include_suppressed=input_data.include_suppressed
                    )
                    if feature_result.is_success:
                        features = feature_result.data or []
                        execution_time = max(
                            execution_time, feature_result.execution_time or 0.0
                        )
                    else:
                        return {
                            "status": "error",
                            "message": feature_result.error
                            or "Failed to list features for classification",
                        }
                else:
                    return {
                        "status": "error",
                        "message": "Active adapter does not support list_features",
                    }

            classification = classify_feature_tree_snapshot(model_info, features or [])
            return {
                "status": "success",
                "classification": classification,
                "model_info": model_info or {},
                "features": features or [],
                "execution_time": execution_time,
            }
        except Exception as e:
            logger.error(f"Error in classify_feature_tree tool: {e}")
            return {
                "status": "error",
                "message": f"Unexpected error: {str(e)}",
            }

    @mcp.tool()
    async def list_configurations() -> dict[str, Any]:
        """List configuration names for the active SolidWorks document.

        Returns all available configuration names so callers can select a stable target before
        invoking feature or export operations.

        Returns:
            dict[str, Any]: A dictionary containing the resulting values.
        """
        try:
            if hasattr(adapter, "list_configurations"):
                result = await adapter.list_configurations()
                if result.is_success:
                    return {
                        "status": "success",
                        "configurations": result.data or [],
                        "count": len(result.data or []),
                        "execution_time": result.execution_time,
                    }
                return {
                    "status": "error",
                    "message": result.error or "Failed to list configurations",
                }

            return {
                "status": "error",
                "message": "Active adapter does not support list_configurations",
            }
        except Exception as e:
            logger.error(f"Error in list_configurations tool: {e}")
            return {
                "status": "error",
                "message": f"Unexpected error: {str(e)}",
            }

    @mcp.tool()
    async def manage_file_properties(input_data: FileOperationInput) -> dict[str, Any]:
        """Read, update, copy, move, rename, or delete file-related properties.

        Uses the requested operation and file paths to manage SolidWorks file metadata or
        related file lifecycle tasks through the active adapter.

        Args:
            input_data (FileOperationInput): The input data value.

        Returns:
            dict[str, Any]: A dictionary containing the resulting values.
        """
        try:
            input_data = _coerce_input(FileOperationInput, input_data)
            if hasattr(adapter, "manage_file_properties"):
                result = await adapter.manage_file_properties(input_data.model_dump())
                if result.is_success:
                    return {
                        "status": "success",
                        "message": "File properties managed successfully",
                        "data": result.data,
                        "execution_time": result.execution_time,
                    }
                return {
                    "status": "error",
                    "message": result.error or "Failed to manage file properties",
                }
            return {
                "status": "success",
                "message": "File properties managed successfully",
                "data": {
                    "file_path": input_data.file_path,
                    "operation": input_data.operation,
                },
            }
        except Exception as e:
            logger.error(f"Error in manage_file_properties tool: {e}")
            return {"status": "error", "message": f"Unexpected error: {str(e)}"}

    @mcp.tool()
    async def convert_file_format(input_data: FormatConversionInput) -> dict[str, Any]:
        """Convert a SolidWorks file from one format to another.

        Supports exporting source files to target formats such as STEP, IGES, STL, PDF, or other
        adapter-supported conversion outputs.

        Args:
            input_data (FormatConversionInput): The input data value.

        Returns:
            dict[str, Any]: A dictionary containing the resulting values.
        """
        try:
            input_data = _coerce_input(FormatConversionInput, input_data)
            if hasattr(adapter, "convert_file_format"):
                result = await adapter.convert_file_format(input_data.model_dump())
                if result.is_success:
                    return {
                        "status": "success",
                        "message": "File converted successfully",
                        "data": result.data,
                        "execution_time": result.execution_time,
                    }
                return {
                    "status": "error",
                    "message": result.error or "Failed to convert file format",
                }
            return {
                "status": "success",
                "message": "File converted successfully",
                "data": {
                    "source_file": input_data.source_file,
                    "target_file": input_data.target_file or input_data.output_path,
                    "format_to": input_data.target_format,
                },
            }
        except Exception as e:
            logger.error(f"Error in convert_file_format tool: {e}")
            return {"status": "error", "message": f"Unexpected error: {str(e)}"}

    @mcp.tool()
    async def batch_file_operations(input_data: FileOperationInput) -> dict[str, Any]:
        """Run a file operation across multiple files as a batch workflow.

        Intended for repetitive file management tasks such as copying, moving, renaming, or
        deleting groups of SolidWorks documents.

        Args:
            input_data (FileOperationInput): The input data value.

        Returns:
            dict[str, Any]: A dictionary containing the resulting values.
        """
        try:
            input_data = _coerce_input(FileOperationInput, input_data)
            if hasattr(adapter, "batch_file_operations"):
                result = await adapter.batch_file_operations(input_data.model_dump())
                if result.is_success:
                    return {
                        "status": "success",
                        "message": "Batch file operations completed successfully",
                        "data": result.data,
                        "execution_time": result.execution_time,
                    }
                return {
                    "status": "error",
                    "message": result.error or "Failed to run batch file operations",
                }
            return {
                "status": "success",
                "message": "Batch file operations completed successfully",
                "data": {
                    "file_path": input_data.file_path,
                    "operation": input_data.operation,
                },
            }
        except Exception as e:
            logger.error(f"Error in batch_file_operations tool: {e}")
            return {"status": "error", "message": f"Unexpected error: {str(e)}"}

    @mcp.tool()
    async def load_part(input_data: LoadPartInput) -> dict[str, Any]:
        """Load (open) a SolidWorks part file.

        Convenience wrapper that opens a .sldprt file and makes it the active document. Provides
        a simpler alternative to open_model for parts.

        Args:
            input_data (LoadPartInput): The input data value.

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

        Example:
                            ```python
                            result = await load_part({
                                "file_path": "C:/Projects/bracket.sldprt"
                            })

                            if result["status"] == "success":
                                print(f"Loaded: {result['model']['name']}")
                            ```

                        Note:
                            - File must be a valid .sldprt (part) file
                            - Path must be absolute and accessible
        """
        try:
            input_data = _coerce_input(LoadPartInput, input_data)
            # Ensure file path ends with .sldprt
            file_path = input_data.file_path
            if not file_path.lower().endswith(".sldprt"):
                return {
                    "status": "error",
                    "message": f"File must be a .sldprt part file: {file_path}",
                }

            result = await adapter.open_model(file_path)
            if result.is_success:
                model = result.data
                title = _result_value(model, "title", "name", default=file_path)
                path = _result_value(model, "path", "file_path", default=file_path)
                configuration = _result_value(model, "configuration", default="Default")
                return {
                    "status": "success",
                    "message": f"Loaded part: {title}",
                    "model": {
                        "name": title,
                        "type": "Part",
                        "path": path,
                        "configuration": configuration,
                    },
                    "execution_time": result.execution_time,
                }
            return {
                "status": "error",
                "message": f"Failed to load part: {result.error}",
            }
        except Exception as e:
            logger.error(f"Error in load_part tool: {e}")
            return {
                "status": "error",
                "message": f"Unexpected error: {str(e)}",
            }

    @mcp.tool()
    async def load_assembly(input_data: LoadAssemblyInput) -> dict[str, Any]:
        """Load (open) a SolidWorks assembly file.

        Convenience wrapper that opens a .sldasm file and makes it the active document. Provides
        a simpler alternative to open_model for assemblies.

        Args:
            input_data (LoadAssemblyInput): The input data value.

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

        Example:
                            ```python
                            result = await load_assembly({
                                "file_path": "C:/Projects/machine_assembly.sldasm"
                            })

                            if result["status"] == "success":
                                print(f"Loaded: {result['model']['name']}")
                            ```

                        Note:
                            - File must be a valid .sldasm (assembly) file
                            - Path must be absolute and accessible
        """
        try:
            input_data = _coerce_input(LoadAssemblyInput, input_data)
            # Ensure file path ends with .sldasm
            file_path = input_data.file_path
            if not file_path.lower().endswith(".sldasm"):
                return {
                    "status": "error",
                    "message": f"File must be a .sldasm assembly file: {file_path}",
                }

            result = await adapter.open_model(file_path)
            if result.is_success:
                model = result.data
                title = _result_value(model, "title", "name", default=file_path)
                path = _result_value(model, "path", "file_path", default=file_path)
                configuration = _result_value(model, "configuration", default="Default")
                return {
                    "status": "success",
                    "message": f"Loaded assembly: {title}",
                    "model": {
                        "name": title,
                        "type": "Assembly",
                        "path": path,
                        "configuration": configuration,
                    },
                    "execution_time": result.execution_time,
                }
            return {
                "status": "error",
                "message": f"Failed to load assembly: {result.error}",
            }
        except Exception as e:
            logger.error(f"Error in load_assembly tool: {e}")
            return {
                "status": "error",
                "message": f"Unexpected error: {str(e)}",
            }

    @mcp.tool()
    async def save_part(input_data: SavePartInput | None = None) -> dict[str, Any]:
        """Save the active SolidWorks part document.

        Convenience wrapper that saves the currently active part. If no file_path is provided,
        saves to the existing location. Otherwise, saves as a new file.

        Args:
            input_data (SavePartInput | None): The input data value. Defaults to None.

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

        Example:
                            ```python
                            # Save to current location
                            result = await save_part()

                            # Save as new file
                            result = await save_part({
                                "file_path": "C:/Projects/bracket_v2.sldprt",
                                "overwrite": False
                            })

                            if result["status"] == "success":
                                print(f"Part saved to {result['file_path']}")
                            ```

                        Note:
                            - Active document must be a part file
                            - When saving to new location, ensure path ends with .sldprt
        """
        try:
            if input_data is None:
                input_data = SavePartInput()
            else:
                input_data = _coerce_input(SavePartInput, input_data)

            # If file_path provided, use save_as; otherwise use regular save
            if input_data.file_path:
                # Normalize and validate provided path
                file_path = input_data.file_path.strip()
                if not file_path:
                    return {
                        "status": "error",
                        "message": "Invalid file_path: path is empty or whitespace.",
                    }
                # Detect paths that are effectively just the extension (e.g., ".sldprt")
                cleaned = file_path.strip()
                if (
                    cleaned.count(".") == 1
                    and cleaned.startswith(".")
                    and cleaned[1:].lower() == "sldprt"
                ):
                    return {
                        "status": "error",
                        "message": "Invalid file_path: missing base filename before extension.",
                    }
                # Ensure path ends with .sldprt for parts
                if not file_path.lower().endswith(".sldprt"):
                    file_path = file_path.rsplit(".", 1)[0] + ".sldprt"

                result = await adapter.save_file(file_path)
                if result.is_success:
                    return {
                        "status": "success",
                        "message": f"Part saved as: {file_path}",
                        "file_path": file_path,
                        "execution_time": result.execution_time,
                    }
                return {
                    "status": "error",
                    "message": f"Failed to save part: {result.error}",
                }
            else:
                # Save to current location
                result = await adapter.save_file(None)
                if result.is_success:
                    return {
                        "status": "success",
                        "message": "Part saved successfully",
                        "execution_time": result.execution_time,
                    }
                return {
                    "status": "error",
                    "message": f"Failed to save part: {result.error}",
                }
        except Exception as e:
            logger.error(f"Error in save_part tool: {e}")
            return {
                "status": "error",
                "message": f"Unexpected error: {str(e)}",
            }

    @mcp.tool()
    async def save_assembly(
        input_data: SaveAssemblyInput | None = None,
    ) -> dict[str, Any]:
        """Save the active SolidWorks assembly document.

        Convenience wrapper that saves the currently active assembly. If no file_path is
        provided, saves to the existing location. Otherwise, saves as a new file.

        Args:
            input_data (SaveAssemblyInput | None): The input data value. Defaults to None.

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

        Example:
                            ```python
                            # Save to current location
                            result = await save_assembly()

                            # Save as new file
                            result = await save_assembly({
                                "file_path": "C:/Projects/machine_v2.sldasm",
                                "overwrite": False
                            })

                            if result["status"] == "success":
                                print(f"Assembly saved to {result['file_path']}")
                            ```

                        Note:
                            - Active document must be an assembly file
                            - When saving to new location, ensure path ends with .sldasm
        """
        try:
            if input_data is None:
                input_data = SaveAssemblyInput()
            else:
                input_data = _coerce_input(SaveAssemblyInput, input_data)

            # If file_path provided, use save_as; otherwise use regular save
            if input_data.file_path:
                # Ensure path ends with .sldasm for assemblies
                file_path = input_data.file_path
                if not file_path.lower().endswith(".sldasm"):
                    file_path = file_path.rsplit(".", 1)[0] + ".sldasm"

                result = await adapter.save_file(file_path)
                if result.is_success:
                    return {
                        "status": "success",
                        "message": f"Assembly saved as: {file_path}",
                        "file_path": file_path,
                        "execution_time": result.execution_time,
                    }
                return {
                    "status": "error",
                    "message": f"Failed to save assembly: {result.error}",
                }
            else:
                # Save to current location
                result = await adapter.save_file(None)
                if result.is_success:
                    return {
                        "status": "success",
                        "message": "Assembly saved successfully",
                        "execution_time": result.execution_time,
                    }
                return {
                    "status": "error",
                    "message": f"Failed to save assembly: {result.error}",
                }
        except Exception as e:
            logger.error(f"Error in save_assembly tool: {e}")
            return {
                "status": "error",
                "message": f"Unexpected error: {str(e)}",
            }

    tool_count = 14  # Total number of registered tools in this module
    return tool_count