Skip to content

solidworks_mcp.tools.template_management

solidworks_mcp.tools.template_management

Template Management tools for SolidWorks MCP Server.

Provides tools for managing SolidWorks templates including extraction, application, comparison, and library management.

Classes

CompatInput

Bases: BaseModel

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

Attributes:

Name Type Description
model_config Any

The model config 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

TemplateApplicationInput

Bases: BaseModel

Input schema for applying template to model.

Attributes:

Name Type Description
apply_dimensions bool

The apply dimensions value.

apply_materials bool

The apply materials value.

overwrite_existing bool

The overwrite existing value.

target_model str

The target model value.

template_path str

The template path value.

TemplateBatchInput

Bases: BaseModel

Input schema for batch template operations.

Attributes:

Name Type Description
backup_originals bool

The backup originals value.

file_pattern str

The file pattern value.

recursive bool

The recursive value.

source_folder str

The source folder value.

template_path str

The template path value.

TemplateComparisonInput

Bases: CompatInput

Input schema for comparing templates.

Attributes:

Name Type Description
comparison_depth str

The comparison depth value.

comparison_type str

The comparison type value.

generate_report bool

The generate report value.

include_dimensions bool

The include dimensions value.

include_materials bool

The include materials value.

include_properties bool

The include properties value.

template1_path str

The template1 path value.

template2_path str

The template2 path value.

TemplateExtractionInput

Bases: BaseModel

Input schema for extracting template from model.

Attributes:

Name Type Description
include_custom_properties bool

The include custom properties value.

include_dimensions bool

The include dimensions value.

save_path str

The save path value.

source_model str

The source model value.

template_name str

The template name value.

template_type str

The template type value.

Functions

register_template_management_tools async

register_template_management_tools(mcp: FastMCP, adapter: SolidWorksAdapter, config) -> int

Register template management tools with FastMCP.

Parameters:

Name Type Description Default
mcp FastMCP

The mcp value.

required
adapter SolidWorksAdapter

Adapter instance used for the operation.

required
config Any

Configuration values for the operation.

required

Returns:

Name Type Description
int int

The computed numeric result.

Example

tool_count = await register_template_management_tools(mcp, adapter, config)

Source code in src/solidworks_mcp/tools/template_management.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
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
async def register_template_management_tools(
    mcp: FastMCP, adapter: SolidWorksAdapter, config
) -> int:
    """Register template management tools with FastMCP.

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

    Returns:
        int: The computed numeric result.

    Example:
                        >>> tool_count = await register_template_management_tools(mcp, adapter, config)
    """
    tool_count = 0

    @mcp.tool()
    async def extract_template(input_data: TemplateExtractionInput) -> dict[str, Any]:
        """Extract template from existing SolidWorks model.

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

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

        Example:
                            >>> result = await extract_template(extraction_input)
        """
        try:
            if hasattr(adapter, "extract_template"):
                result = await adapter.extract_template(input_data.model_dump())
                if result.is_success:
                    return {
                        "status": "success",
                        "message": f"Template '{input_data.template_name}' extracted from {input_data.source_model}",
                        "data": result.data,
                        "execution_time": result.execution_time,
                    }
                return {
                    "status": "error",
                    "message": result.error or "Failed to extract template",
                }

            # For now, return a structured response that describes what would be done
            # In full implementation, this would use the SolidWorks API to extract settings

            extracted_properties = {
                "document_properties": {
                    "units": "mm-kg-s",
                    "precision": 2,
                    "annotation_font": "Century Gothic",
                    "dimension_style": "ISO",
                },
                "custom_properties": [
                    {"name": "Material", "type": "text", "value": "Steel"},
                    {"name": "Weight", "type": "number", "expression": "SW-Mass"},
                    {"name": "DrawingNo", "type": "text", "value": ""},
                    {"name": "RevisionLevel", "type": "text", "value": "A"},
                ],
                "dimension_settings": {
                    "decimal_places": input_data.include_dimensions,
                    "trailing_zeros": True,
                    "units_display": True,
                },
            }

            return {
                "status": "success",
                "message": f"Template '{input_data.template_name}' extracted from {input_data.source_model}",
                "template": {
                    "name": input_data.template_name,
                    "type": input_data.template_type,
                    "save_path": input_data.save_path,
                    "extracted_properties": extracted_properties,
                    "property_count": len(extracted_properties["custom_properties"]),
                    "includes_dimensions": input_data.include_dimensions,
                    "includes_custom_properties": input_data.include_custom_properties,
                },
                "usage_instructions": [
                    "1. Template file saved to specified path",
                    "2. Use apply_template to apply to other models",
                    "3. Template includes document formatting and properties",
                    "4. Can be added to template library for reuse",
                ],
            }

        except Exception as e:
            logger.error(f"Error in extract_template tool: {e}")
            return {
                "status": "error",
                "message": f"Failed to extract template: {str(e)}",
            }

    @mcp.tool()
    async def apply_template(input_data: TemplateApplicationInput) -> dict[str, Any]:
        """Apply a template to an existing SolidWorks model.

        This tool applies saved template settings including properties, dimensions, and
        formatting to the target model.

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

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

        Example:
                            >>> result = await apply_template(application_input)
        """
        try:
            if hasattr(adapter, "apply_template"):
                result = await adapter.apply_template(input_data.model_dump())
                if result.is_success:
                    return {
                        "status": "success",
                        "message": f"Template applied to {input_data.target_model}",
                        "data": result.data,
                        "execution_time": result.execution_time,
                    }
                return {
                    "status": "error",
                    "message": result.error or "Failed to apply template",
                }

            # Simulate template application process
            applied_changes = {
                "properties_updated": [
                    "Material → Steel",
                    "DrawingNo → DRW-001",
                    "RevisionLevel → A",
                ],
                "dimension_formatting": {
                    "precision_updated": True,
                    "units_format_applied": True,
                    "font_updated": "Century Gothic",
                },
                "document_settings": {
                    "units_system": "mm-kg-s",
                    "drafting_standard": "ISO",
                },
            }

            return {
                "status": "success",
                "message": f"Template applied to {input_data.target_model}",
                "template_application": {
                    "template_path": input_data.template_path,
                    "target_model": input_data.target_model,
                    "changes_applied": applied_changes,
                    "overwrite_mode": input_data.overwrite_existing,
                    "material_applied": input_data.apply_materials,
                    "dimensions_applied": input_data.apply_dimensions,
                },
                "recommendations": [
                    "Rebuild the model to update all features",
                    "Check custom properties in File > Properties",
                    "Verify dimension formatting in drawings",
                    "Save the model to preserve changes",
                ],
            }

        except Exception as e:
            logger.error(f"Error in apply_template tool: {e}")
            return {
                "status": "error",
                "message": f"Failed to apply template: {str(e)}",
            }

    @mcp.tool()
    async def batch_apply_template(input_data: TemplateBatchInput) -> dict[str, Any]:
        """Apply template to multiple models in batch.

        This tool processes multiple SolidWorks files and applies the same template
        configuration to all matching files.

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

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

        Example:
                            >>> result = await batch_apply_template(batch_input)
        """
        try:
            if hasattr(adapter, "batch_apply_template"):
                result = await adapter.batch_apply_template(input_data.model_dump())
                if result.is_success:
                    return {
                        "status": "success",
                        "message": "Batch template application completed",
                        "data": result.data,
                        "execution_time": result.execution_time,
                    }
                return {
                    "status": "error",
                    "message": result.error or "Failed batch template application",
                }

            # Simulate batch processing
            processed_files = [
                {"file": "part001.sldprt", "status": "success", "changes": 5},
                {"file": "part002.sldprt", "status": "success", "changes": 4},
                {"file": "assembly001.sldasm", "status": "success", "changes": 3},
                {
                    "file": "drawing001.slddrw",
                    "status": "skipped",
                    "reason": "Wrong file type",
                },
            ]

            summary = {
                "total_processed": len(
                    [f for f in processed_files if f["status"] == "success"]
                ),
                "total_scanned": len(processed_files),
                "total_changes": sum(f.get("changes", 0) for f in processed_files),
                "backup_created": input_data.backup_originals,
            }

            return {
                "status": "success",
                "message": f"Batch template application completed on {summary['total_processed']} files",
                "batch_operation": {
                    "template_path": input_data.template_path,
                    "source_folder": input_data.source_folder,
                    "file_pattern": input_data.file_pattern,
                    "recursive": input_data.recursive,
                    "summary": summary,
                    "processed_files": processed_files,
                },
                "performance": {
                    "efficiency": f"{summary['total_changes']} changes across {summary['total_processed']} files",
                    "backup_status": "Created"
                    if input_data.backup_originals
                    else "Not created",
                },
            }

        except Exception as e:
            logger.error(f"Error in batch_apply_template tool: {e}")
            return {
                "status": "error",
                "message": f"Failed batch template application: {str(e)}",
            }

    @mcp.tool()
    async def compare_templates(input_data: TemplateComparisonInput) -> dict[str, Any]:
        """Compare two templates and generate difference report.

        This tool analyzes differences between templates to help understand variations in
        formatting and properties.

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

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

        Example:
                            >>> result = await compare_templates(comparison_input)
        """
        try:
            if hasattr(adapter, "compare_templates"):
                result = await adapter.compare_templates(input_data.model_dump())
                if result.is_success:
                    return {
                        "status": "success",
                        "message": "Template comparison completed",
                        "data": result.data,
                        "execution_time": result.execution_time,
                    }
                return {
                    "status": "error",
                    "message": result.error or "Failed to compare templates",
                }

            # Simulate template comparison
            differences = {
                "document_properties": {
                    "units": {
                        "template1": "mm-kg-s",
                        "template2": "in-lbm-s",
                        "different": True,
                    },
                    "precision": {"template1": 2, "template2": 3, "different": True},
                    "font": {
                        "template1": "Arial",
                        "template2": "Century Gothic",
                        "different": True,
                    },
                },
                "custom_properties": {
                    "added_in_template2": ["RevisionDate", "Designer"],
                    "removed_from_template1": ["OldProperty"],
                    "modified": [
                        {
                            "property": "Material",
                            "template1": "Steel",
                            "template2": "Aluminum",
                        }
                    ],
                },
                "dimension_formatting": {
                    "decimal_places": {
                        "template1": 2,
                        "template2": 2,
                        "different": False,
                    },
                    "units_display": {
                        "template1": True,
                        "template2": False,
                        "different": True,
                    },
                },
            }

            similarity_score = 85.5  # Simulated similarity percentage

            comparison_report = {
                "template1": input_data.template1_path,
                "template2": input_data.template2_path,
                "comparison_type": input_data.comparison_type,
                "similarity_score": similarity_score,
                "differences_found": differences,
                "recommendations": [
                    "Consider standardizing units system across templates",
                    "Review custom property naming conventions",
                    "Align dimension formatting for consistency",
                ],
            }

            return {
                "status": "success",
                "message": f"Template comparison completed - {similarity_score}% similar",
                "comparison": comparison_report,
                "analysis": {
                    "major_differences": 3,
                    "minor_differences": 2,
                    "compatibility": "High" if similarity_score > 80 else "Medium",
                },
            }

        except Exception as e:
            logger.error(f"Error in compare_templates tool: {e}")
            return {
                "status": "error",
                "message": f"Failed to compare templates: {str(e)}",
            }

    @mcp.tool()
    async def save_to_template_library(input_data: dict[str, Any]) -> dict[str, Any]:
        """Save template to the organization's template library.

        This tool manages a centralized template library with categorization and version
        control.

        Args:
            input_data (dict[str, Any]): The input data value.

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

        Example:
                            >>> result = await save_to_template_library(library_input)
        """

        try:
            if hasattr(adapter, "save_to_template_library"):
                result = await adapter.save_to_template_library(input_data)
                if result.is_success:
                    return {
                        "status": "success",
                        "message": "Template saved to library",
                        "data": result.data,
                        "execution_time": result.execution_time,
                    }
                return {
                    "status": "error",
                    "message": result.error or "Failed to save to library",
                }

            template_path = input_data.get("template_path", "")
            library_category = input_data.get("category", "uncategorized")
            version = input_data.get("version", "1.0")
            description = input_data.get("description", "")
            author = input_data.get("author", "Unknown")

            library_entry = {
                "template_id": f"TPL-{library_category.upper()}-{int(time.time()) % 10000}",
                "name": input_data.get("template_name", "Unnamed Template"),
                "category": library_category,
                "version": version,
                "author": author,
                "description": description,
                "created_date": "2024-01-15",  # Would be current date
                "file_path": template_path,
                "usage_count": 0,
                "tags": input_data.get("tags", []),
                "compatible_versions": [
                    "SW2020",
                    "SW2021",
                    "SW2022",
                    "SW2023",
                    "SW2024",
                ],
            }

            return {
                "status": "success",
                "message": f"Template saved to library as {library_entry['template_id']}",
                "library_entry": library_entry,
                "library_stats": {
                    "total_templates": 47,  # Simulated library stats
                    "category_count": {
                        "parts": 15,
                        "assemblies": 12,
                        "drawings": 8,
                        "custom": 12,
                    },
                    "most_popular": "STD-PART-001",
                    "latest_addition": library_entry["template_id"],
                },
                "usage_instructions": [
                    "Template is now available in library browser",
                    "Use template_id for quick access",
                    "Template will appear in category filters",
                    "Version control enabled for updates",
                ],
            }

        except Exception as e:
            logger.error(f"Error in save_to_template_library tool: {e}")
            return {
                "status": "error",
                "message": f"Failed to save to library: {str(e)}",
            }

    @mcp.tool()
    async def list_template_library(input_data: dict[str, Any]) -> dict[str, Any]:
        """List available templates from the template library.

        This tool provides browsing and searching capabilities for the organization's template
        library.

        Args:
            input_data (dict[str, Any]): The input data value.

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

        Example:
                            >>> result = await list_template_library(list_input)
        """
        try:
            if hasattr(adapter, "list_template_library"):
                result = await adapter.list_template_library(input_data)
                if result.is_success:
                    return {
                        "status": "success",
                        "message": "Template library listed successfully",
                        "data": result.data,
                        "execution_time": result.execution_time,
                    }
                return {
                    "status": "error",
                    "message": result.error or "Failed to list template library",
                }

            category_filter = input_data.get("category", "all")
            search_term = input_data.get("search_term", "")
            sort_by = input_data.get("sort_by", "name")  # name, date, usage

            # Simulated template library
            library_templates = [
                {
                    "template_id": "STD-PART-001",
                    "name": "Standard Part Template",
                    "category": "parts",
                    "version": "2.1",
                    "author": "Engineering Team",
                    "description": "Standard template for mechanical parts with ISO properties",
                    "usage_count": 145,
                    "last_updated": "2024-01-10",
                    "tags": ["standard", "mechanical", "iso"],
                },
                {
                    "template_id": "ASM-MAIN-002",
                    "name": "Main Assembly Template",
                    "category": "assemblies",
                    "version": "1.5",
                    "author": "Design Team",
                    "description": "Template for main assembly documentation and BOM",
                    "usage_count": 87,
                    "last_updated": "2024-01-08",
                    "tags": ["assembly", "bom", "documentation"],
                },
                {
                    "template_id": "DRW-ISO-003",
                    "name": "ISO Drawing Template",
                    "category": "drawings",
                    "version": "3.0",
                    "author": "Drafting Team",
                    "description": "ISO standard drawing template with title block",
                    "usage_count": 203,
                    "last_updated": "2024-01-12",
                    "tags": ["drawing", "iso", "title-block"],
                },
            ]

            # Apply filters
            filtered_templates = library_templates
            if category_filter != "all":
                filtered_templates = [
                    t for t in filtered_templates if t["category"] == category_filter
                ]

            if search_term:
                filtered_templates = [
                    t
                    for t in filtered_templates
                    if search_term.lower() in t["name"].lower()
                    or search_term.lower() in t["description"].lower()
                ]

            # Apply sorting
            if sort_by == "usage":
                filtered_templates.sort(key=lambda x: x["usage_count"], reverse=True)
            elif sort_by == "date":
                filtered_templates.sort(key=lambda x: x["last_updated"], reverse=True)
            else:  # name
                filtered_templates.sort(key=lambda x: x["name"])

            return {
                "status": "success",
                "message": f"Found {len(filtered_templates)} templates matching criteria",
                "library_search": {
                    "category_filter": category_filter,
                    "search_term": search_term,
                    "sort_by": sort_by,
                    "total_results": len(filtered_templates),
                },
                "templates": filtered_templates,
                "categories_available": ["parts", "assemblies", "drawings", "custom"],
                "library_summary": {
                    "total_templates": len(library_templates),
                    "most_used": max(library_templates, key=lambda x: x["usage_count"])[
                        "name"
                    ],
                    "newest": max(library_templates, key=lambda x: x["last_updated"])[
                        "name"
                    ],
                },
            }

        except Exception as e:
            logger.error(f"Error in list_template_library tool: {e}")
            return {
                "status": "error",
                "message": f"Failed to list library: {str(e)}",
            }

    tool_count = 6  # Template management tools
    return tool_count