Skip to content

solidworks_mcp.adapters.solidworks.templates

solidworks_mcp.adapters.solidworks.templates

Save the active document as a template (queue item 21).

IModelDocExtension.SaveAs writes a .prtdot, .asmdot or .drwdot. SolidWorks then has the template open in place of the document, as File > Save As does: seen live on SolidWorks 2026 for a part never saved and for a saved one, and swSaveAsOptions_Copy doesn't change it. The template folders are SolidWorks' swFileLocationsDocumentTemplates preference, the folders File > New shows.

Attributes

DOCUMENT_TYPES module-attribute

DOCUMENT_TYPES: dict[int, str] = {1: 'part', 2: 'assembly', 3: 'drawing'}

TEMPLATE_EXTENSIONS module-attribute

TEMPLATE_EXTENSIONS: dict[int, str] = {1: '.prtdot', 2: '.asmdot', 3: '.drwdot'}

_SAVE_AS_CURRENT_VERSION module-attribute

_SAVE_AS_CURRENT_VERSION = 0

_SAVE_AS_SILENT module-attribute

_SAVE_AS_SILENT = 1

_SW_PREF_TEMPLATE_FOLDERS module-attribute

_SW_PREF_TEMPLATE_FOLDERS = 6

Classes

AdapterResult dataclass

AdapterResult(status: AdapterResultStatus, data: T | None = None, error: str | None = None, execution_time: float | None = None, metadata: dict[str, Any] | None = None)

Result wrapper for adapter operations.

Attributes:

Name Type Description
data T | None

The data value.

error str | None

The error value.

execution_time float | None

The execution time value.

metadata dict[str, Any] | None

The metadata value.

status AdapterResultStatus

The status value.

Attributes
is_error property
is_error: bool

Check if operation had an error.

Returns:

Name Type Description
bool bool

True if error, otherwise False.

is_success property
is_success: bool

Check if operation was successful.

Returns:

Name Type Description
bool bool

True if success, otherwise False.

AdapterResultStatus

Bases: StrEnum

Result status for adapter operations.

Attributes:

Name Type Description
ERROR Any

The error value.

SUCCESS Any

The success value.

TIMEOUT Any

The timeout value.

WARNING Any

The warning value.

SolidWorksTemplatesMixin

get_template_folders and save_as_template for the real adapter.

Methods:
get_template_folders async
get_template_folders() -> AdapterResult[dict[str, Any]]

The template folders, and the active document's template extension.

Returns:

Type Description
AdapterResult[dict[str, Any]]

AdapterResult[dict[str, Any]]: folders, and document_type

AdapterResult[dict[str, Any]]

and extension (both None with no document open).

Source code in src/solidworks_mcp/adapters/solidworks/templates.py
async def get_template_folders(self) -> AdapterResult[dict[str, Any]]:
    """The template folders, and the active document's template extension.

    Returns:
        AdapterResult[dict[str, Any]]: ``folders``, and ``document_type``
        and ``extension`` (both ``None`` with no document open).
    """
    adapter = cast("Any", self)
    kind = _doc_type(adapter) if adapter.currentModel is not None else None
    return AdapterResult(
        status=AdapterResultStatus.SUCCESS,
        data={
            "folders": self._template_folders(),
            "document_type": DOCUMENT_TYPES.get(kind or 0),
            "extension": TEMPLATE_EXTENSIONS.get(kind or 0),
        },
    )
save_as_template async
save_as_template(file_path: str) -> AdapterResult[dict[str, Any]]

Save the active document as a template at file_path.

SolidWorks then has the template open in place of the document (see the module docstring); the document's file, if it had one, is left as last saved. The title and path are read before and after, so the reply says what is open now.

Parameters:

Name Type Description Default
file_path str

The template's full path, with the document's template extension.

required

Returns:

Type Description
AdapterResult[dict[str, Any]]

AdapterResult[dict[str, Any]]: file_path, document_type,

AdapterResult[dict[str, Any]]

in_template_folder, template_folders, document_path

AdapterResult[dict[str, Any]]

(the open document's path before the save, None if never

AdapterResult[dict[str, Any]]

saved) and document_became_template.

Source code in src/solidworks_mcp/adapters/solidworks/templates.py
async def save_as_template(self, file_path: str) -> AdapterResult[dict[str, Any]]:
    """Save the active document as a template at ``file_path``.

    SolidWorks then has the template open in place of the document (see
    the module docstring); the document's file, if it had one, is left
    as last saved. The title and path are read before and after, so the
    reply says what is open now.

    Args:
        file_path: The template's full path, with the document's template
            extension.

    Returns:
        AdapterResult[dict[str, Any]]: ``file_path``, ``document_type``,
        ``in_template_folder``, ``template_folders``, ``document_path``
        (the open document's path before the save, ``None`` if never
        saved) and ``document_became_template``.
    """
    adapter = cast("Any", self)
    if adapter.currentModel is None:
        return _error("No active model")
    kind = _doc_type(adapter) or 0
    extension = TEMPLATE_EXTENSIONS.get(kind)
    if extension is None:
        return _error("save_as_template needs an active part, assembly or drawing")
    if not file_path.lower().endswith(extension):
        return _error(
            f"{DOCUMENT_TYPES[kind].capitalize()} templates are {extension}; "
            f"{file_path!r} isn't one."
        )

    def _read(model: Any, name: str) -> str:
        """A string member of the document; empty when unreadable."""
        value = adapter._attempt(
            lambda: adapter._get_attr_or_call(model, name), default=""
        )
        return str(value or "")

    def _identity(model: Any) -> tuple[str, str]:
        """The document's path and title."""
        return _read(model, "GetPathName"), _read(model, "GetTitle")

    def _save() -> dict[str, Any]:
        model = adapter.currentModel
        before = _identity(model)
        ext = _sw_type_info.flagged(model.Extension, "IModelDocExtension")
        errors, warnings = _byref_int(), _byref_int()
        ok = ext.SaveAs(
            file_path,
            _SAVE_AS_CURRENT_VERSION,
            _SAVE_AS_SILENT,
            _null_callout(),
            errors,
            warnings,
        )
        if not ok or not os.path.isfile(file_path):
            raise RuntimeError(
                f"SolidWorks didn't write the template {file_path!r} "
                f"(SaveAs returned {ok!r}, error code "
                f"{getattr(errors, 'value', errors)!r})."
            )
        folders = self._template_folders()
        return {
            "file_path": file_path,
            "document_type": DOCUMENT_TYPES[kind],
            "in_template_folder": in_folders(file_path, folders),
            "template_folders": folders,
            "document_path": before[0] or None,
            "document_became_template": _identity(model) != before,
        }

    return cast(
        "AdapterResult[dict[str, Any]]",
        adapter._handle_com_operation("save_as_template", _save),
    )

Functions:

_byref_int

_byref_int() -> Any

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

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

Returns:

Name Type Description
Any Any

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

Any

unavailable (test/mock environments).

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

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

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

_doc_type

_doc_type(adapter: Any) -> int | None

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

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

Parameters:

Name Type Description Default
adapter Any

A connected PyWin32Adapter.

required

Returns:

Type Description
int | None

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

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

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

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

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

_error

_error(message: str) -> AdapterResult[dict[str, Any]]

An error result.

Source code in src/solidworks_mcp/adapters/solidworks/templates.py
def _error(message: str) -> AdapterResult[dict[str, Any]]:
    """An error result."""
    return AdapterResult(status=AdapterResultStatus.ERROR, error=message)

_null_callout

_null_callout() -> Any

Return a VT_DISPATCH null for SelectByID2's Callout parameter.

A plain Python None marshals as VT_NULL, which SolidWorks rejects with DISP_E_TYPEMISMATCH - measured as (-2147352571, 'Type mismatch.', None, 8). See runbook item 11.

Returns:

Name Type Description
Any Any

A VARIANT(VT_DISPATCH, None), or a non-None sentinel

Any

when pywin32 is unavailable (mock/Linux runs, where no real COM call

Any

will be made anyway, but the value must still never be bare None).

Source code in src/solidworks_mcp/adapters/solidworks/features.py
def _null_callout() -> Any:
    """Return a VT_DISPATCH null for ``SelectByID2``'s ``Callout`` parameter.

    A plain Python ``None`` marshals as ``VT_NULL``, which SolidWorks rejects
    with ``DISP_E_TYPEMISMATCH`` - measured as
    ``(-2147352571, 'Type mismatch.', None, 8)``. See runbook item 11.

    Returns:
        Any: A ``VARIANT(VT_DISPATCH, None)``, or a non-``None`` sentinel
        when pywin32 is unavailable (mock/Linux runs, where no real COM call
        will be made anyway, but the value must still never be bare ``None``).
    """
    try:
        import pythoncom
        import win32com.client as _win32com
    except ImportError:
        return _NULL_CALLOUT_SENTINEL
    return _win32com.VARIANT(pythoncom.VT_DISPATCH, None)

in_folders

in_folders(path: str, folders: list[str]) -> bool

Whether path sits directly in one of folders.

Compared as Windows paths (case and separators ignored), on any OS.

Parameters:

Name Type Description Default
path str

A file path.

required
folders list[str]

Folder paths.

required

Returns:

Name Type Description
bool bool

True when the file's folder is one of them.

Source code in src/solidworks_mcp/adapters/solidworks/templates.py
def in_folders(path: str, folders: list[str]) -> bool:
    """Whether ``path`` sits directly in one of ``folders``.

    Compared as Windows paths (case and separators ignored), on any OS.

    Args:
        path: A file path.
        folders: Folder paths.

    Returns:
        bool: True when the file's folder is one of them.
    """
    parent = ntpath.normcase(ntpath.normpath(ntpath.dirname(path)))
    return any(ntpath.normcase(ntpath.normpath(folder)) == parent for folder in folders)

split_folders

split_folders(text: Any) -> list[str]

The folders in a ;-separated SolidWorks location preference.

Parameters:

Name Type Description Default
text Any

The preference's value; anything not a string means none.

required

Returns:

Type Description
list[str]

list[str]: The folders, in order, blanks dropped.

Source code in src/solidworks_mcp/adapters/solidworks/templates.py
def split_folders(text: Any) -> list[str]:
    """The folders in a ``;``-separated SolidWorks location preference.

    Args:
        text: The preference's value; anything not a string means none.

    Returns:
        list[str]: The folders, in order, blanks dropped.
    """
    if not isinstance(text, str):
        return []
    return [folder.strip() for folder in text.split(";") if folder.strip()]