Skip to content

solidworks_mcp.adapters.solidworks.equations

solidworks_mcp.adapters.solidworks.equations

Equations and global variables: list, add or change, and delete them.

Since 2.2.0 every IEquationMgr call goes through compat (#265: they failed with "Member not found" on SolidWorks 2024).

One value ("Width" = 60mm) can drive several dimensions ("D1@Sketch1" = "Width" / 2), which is how a SolidWorks part becomes parametric.

COM calls (argument lists from the installed 2026 type library), all on IModelDoc2.GetEquationMgr(). What each returns was measured on SolidWorks 2026 (the equations live probe, 2026-11-18):

  • GetCount(), and the indexed properties Equation(i), Value(i) and GlobalVariable(i); Equation(i) reads the active configuration's text;
  • Add2(Index, Equation, Solve) returns the new index, or -1 when SolidWorks refuses the text. It adds to every configuration;
  • writing the Equation(i) property changes an equation in every configuration (its scope goes back to all). A text SolidWorks can't use is refused: Status becomes -1 and the stored text doesn't change;
  • SetEquationAndConfigurationOption(Index, Equation, 1, None) (this configuration) returns 0 when it worked. Named configurations are set one at a time, each made active in turn, then the active one is shown again. Given any array of configuration names it returns -1, and with option 2 (all) it returns -1 on a part with many equations (19 in the wrench demo), which is why "all" writes the property instead. Add3 takes names too and fails the same way, so it isn't used;
  • Delete(Index); EvaluateAll(), whose return value isn't used (it returned -1 on a part that solved);
  • Status, the last operation's result: -1 when it failed, so an added equation SolidWorks couldn't solve is deleted again.

IModelDoc2.Parameter(name) checks a dimension name before anything is written.

Attributes

_DISPATCH_PROPERTYPUT module-attribute

_DISPATCH_PROPERTYPUT = 4

_NAME module-attribute

_NAME = re.compile('^\\s*"([^"]*)"')

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.

SolidWorksEquationsMixin

List, add or change, and delete equations and global variables.

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

Delete the equation for name.

Parameters:

Name Type Description Default
name str

The equation's name (its left-hand side).

required

Returns:

Type Description
AdapterResult[dict[str, Any]]

The deleted name and the names left.

Source code in src/solidworks_mcp/adapters/solidworks/equations.py
async def delete_equation(self, name: str) -> AdapterResult[dict[str, Any]]:
    """Delete the equation for ``name``.

    Args:
        name: The equation's name (its left-hand side).

    Returns:
        The deleted name and the names left.
    """

    def build() -> dict[str, Any]:
        manager = self._equation_manager()
        rows = self._equations(manager)
        match = next((r for r in rows if r["name"].lower() == name.lower()), None)
        if match is None:
            known = ", ".join(r["name"] for r in rows) or "none"
            raise LookupError(f"No equation named '{name}'; the model has {known}.")
        compat.invoke(manager, "Delete", match["index"], interface="IEquationMgr")
        self._solve(manager)
        return {
            "deleted": match["name"],
            "equations": [r["name"] for r in self._equations(manager)],
        }

    return self._on_model("delete_equation", build)
list_equations async
list_equations() -> AdapterResult[list[dict[str, Any]]]

Every equation and global variable of the active model.

Returns:

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

Each with index, name, expression, kind and

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

value (in the document's units, or None).

Source code in src/solidworks_mcp/adapters/solidworks/equations.py
async def list_equations(self) -> AdapterResult[list[dict[str, Any]]]:
    """Every equation and global variable of the active model.

    Returns:
        Each with ``index``, ``name``, ``expression``, ``kind`` and
        ``value`` (in the document's units, or None).
    """

    def build() -> list[dict[str, Any]]:
        return self._equations(self._equation_manager())

    return self._on_model("list_equations", build)
set_equation async
set_equation(name: str, expression: str, configurations: str | list[str] = 'all') -> AdapterResult[dict[str, Any]]

Add an equation for name, or change the one there is.

Parameters:

Name Type Description Default
name str

A global variable, or a dimension such as D1@Sketch1.

required
expression str

The right-hand side, e.g. 60mm or "Width" / 2.

required
configurations str | list[str]

"all", "this" or configuration names.

'all'

Returns:

Type Description
AdapterResult[dict[str, Any]]

The stored equation, its value, action (added or

AdapterResult[dict[str, Any]]

changed) and the configurations it applies in; for named

AdapterResult[dict[str, Any]]

configurations, the expression set and values, its solved

AdapterResult[dict[str, Any]]

value in each of them.

Source code in src/solidworks_mcp/adapters/solidworks/equations.py
async def set_equation(
    self,
    name: str,
    expression: str,
    configurations: str | list[str] = "all",
) -> AdapterResult[dict[str, Any]]:
    """Add an equation for ``name``, or change the one there is.

    Args:
        name: A global variable, or a dimension such as ``D1@Sketch1``.
        expression: The right-hand side, e.g. ``60mm`` or ``"Width" / 2``.
        configurations: ``"all"``, ``"this"`` or configuration names.

    Returns:
        The stored equation, its value, ``action`` (``added`` or
        ``changed``) and the configurations it applies in; for named
        configurations, the expression set and ``values``, its solved
        value in each of them.
    """
    adapter: Any = self

    def build() -> dict[str, Any]:
        option, names, _array = configuration_scope(adapter, configurations)
        if "@" in name and not adapter.currentModel.Parameter(name):
            raise LookupError(
                f"No dimension named '{name}' in the active document; read "
                "the names with list_model_dimensions."
            )
        manager = self._equation_manager()
        text = equation_text(name, expression)
        values: dict[str, Any] = {}
        existing = next(
            (
                row
                for row in self._equations(manager)
                if row["name"].lower() == name.lower()
            ),
            None,
        )
        if existing is None:
            index = _add(manager, -1, text)
            if index < 0:
                raise ValueError(
                    f"SolidWorks refused the equation {text}; nothing was added."
                )
            if option != ALL_CONFIGURATIONS and not self._set(
                index, text, option, names, values
            ):
                compat.invoke(
                    self._equation_manager(),
                    "Delete",
                    index,
                    interface="IEquationMgr",
                )
                raise ValueError(
                    f"SolidWorks refused the equation {text} in "
                    f"{', '.join(names)}; nothing was added."
                )
            action = "added"
        else:
            index = existing["index"]
            previous = str(
                compat.invoke(manager, "Equation", index, interface="IEquationMgr")
            )
            if not self._set(index, text, option, names, values):
                self._set(index, previous, option, names)
                raise ValueError(
                    f"SolidWorks refused the equation {text}; the equation "
                    f"was left as {previous}."
                )
            action = "changed"
        manager = self._equation_manager()
        self._solve(manager)
        row = self._equations(manager)[index]
        if values:
            # The row is read in the active configuration; say what was
            # set instead: the expression, its value in the first named
            # configuration, and in each one it was set in.
            row = {
                **row,
                "expression": expression.strip(),
                "value": values[names[0]],
                "values": values,
            }
        return {**row, "action": action, "configurations": names}

    return self._on_model("set_equation", build)

Functions:

_active

_active(adapter: Any) -> str | None

The active configuration's name (IConfiguration.Name is a property).

Source code in src/solidworks_mcp/adapters/solidworks/configurations.py
def _active(adapter: Any) -> str | None:
    """The active configuration's name (``IConfiguration.Name`` is a property)."""
    config = adapter._attempt(
        lambda: adapter.currentModel.GetActiveConfiguration(), None
    )
    name = getattr(config, "Name", None) if config is not None else None
    return str(name) if name else None

_add

_add(manager: Any, index: int, text: str) -> int

Add text at index (-1: at the end); its index, or -1 if refused.

An equation Add2 accepts but can't solve leaves Status negative; it is deleted again so nothing half-made stays in the model.

Source code in src/solidworks_mcp/adapters/solidworks/equations.py
def _add(manager: Any, index: int, text: str) -> int:
    """Add ``text`` at ``index`` (-1: at the end); its index, or -1 if refused.

    An equation ``Add2`` accepts but can't solve leaves ``Status`` negative;
    it is deleted again so nothing half-made stays in the model.
    """
    added = int(
        compat.invoke(manager, "Add2", index, text, True, interface="IEquationMgr")
    )
    if added >= 0 and _failed(manager):
        compat.invoke(manager, "Delete", added, interface="IEquationMgr")
        return -1
    return added

_failed

_failed(manager: Any) -> bool

Whether the last operation failed: Status is negative then.

Source code in src/solidworks_mcp/adapters/solidworks/equations.py
def _failed(manager: Any) -> bool:
    """Whether the last operation failed: ``Status`` is negative then."""
    status = compat.read(manager, "Status", interface="IEquationMgr")
    return isinstance(status, int) and status < 0

_kind

_kind(name: str, is_global: bool) -> str

global_variable, dimension (a name with @) or other.

Source code in src/solidworks_mcp/adapters/solidworks/equations.py
def _kind(name: str, is_global: bool) -> str:
    """``global_variable``, ``dimension`` (a name with ``@``) or ``other``."""
    if is_global:
        return "global_variable"
    return "dimension" if "@" in name else "other"

_put_everywhere

_put_everywhere(manager: Any, index: int, text: str) -> bool

Write the Equation(index) property: the text in every configuration.

pywin32's late binding reads indexed properties but can't assign one, so the property put goes through IDispatch.Invoke.

Source code in src/solidworks_mcp/adapters/solidworks/equations.py
def _put_everywhere(manager: Any, index: int, text: str) -> bool:
    """Write the ``Equation(index)`` property: the text in every configuration.

    pywin32's late binding reads indexed properties but can't assign one, so
    the property put goes through ``IDispatch.Invoke``.
    """
    dispatch = manager._oleobj_
    dispid = dispatch.GetIDsOfNames("Equation")
    dispatch.Invoke(dispid, 0, _DISPATCH_PROPERTYPUT, False, index, text)
    return _took(manager, index, text)

_same

_same(a: str, b: str) -> bool

Whether two equation texts match, ignoring spaces and case.

Source code in src/solidworks_mcp/adapters/solidworks/equations.py
def _same(a: str, b: str) -> bool:
    """Whether two equation texts match, ignoring spaces and case."""
    return re.sub(r"\s+", "", a).lower() == re.sub(r"\s+", "", b).lower()

_set_here

_set_here(manager: Any, index: int, text: str) -> bool

Set equation index to text in the active configuration only.

Source code in src/solidworks_mcp/adapters/solidworks/equations.py
def _set_here(manager: Any, index: int, text: str) -> bool:
    """Set equation ``index`` to ``text`` in the active configuration only."""
    returned = compat.invoke(
        manager,
        "SetEquationAndConfigurationOption",
        index,
        text,
        THIS_CONFIGURATION,
        None,
        interface="IEquationMgr",
    )
    return returned == 0 and _took(manager, index, text)

_took

_took(manager: Any, index: int, text: str) -> bool

Whether SolidWorks kept text for equation index.

Status isn't negative and the stored text reads back the same (SolidWorks may respace it).

Source code in src/solidworks_mcp/adapters/solidworks/equations.py
def _took(manager: Any, index: int, text: str) -> bool:
    """Whether SolidWorks kept ``text`` for equation ``index``.

    ``Status`` isn't negative and the stored text reads back the same
    (SolidWorks may respace it).
    """
    return not _failed(manager) and _same(
        str(compat.invoke(manager, "Equation", index, interface="IEquationMgr")), text
    )

configuration_scope

configuration_scope(adapter: Any, configurations: str | list[str]) -> tuple[int, list[str], Any]

Where a change applies: the COM option, the names, and their array.

"this" is the active configuration, "all" every one, a list those named (each checked first).

Raises:

Type Description
LookupError

For a name the model doesn't have, listing the names.

Source code in src/solidworks_mcp/adapters/solidworks/configurations.py
def configuration_scope(
    adapter: Any, configurations: str | list[str]
) -> tuple[int, list[str], Any]:
    """Where a change applies: the COM option, the names, and their array.

    ``"this"`` is the active configuration, ``"all"`` every one, a list those
    named (each checked first).

    Raises:
        LookupError: For a name the model doesn't have, listing the names.
    """
    names = _names(adapter)
    if configurations == "this":
        active = _active(adapter)
        return THIS_CONFIGURATION, [active] if active else [], None
    if configurations == "all":
        return ALL_CONFIGURATIONS, names, string_array(names)
    unknown = [n for n in configurations if n not in names]
    if unknown:
        raise LookupError(
            f"No configuration named {', '.join(repr(n) for n in unknown)}; the "
            f"model has {', '.join(names) or 'none'}."
        )
    chosen = list(configurations)
    return SPECIFY_CONFIGURATION, chosen, string_array(chosen)

equation_text

equation_text(name: str, expression: str) -> str

The equation SolidWorks stores for name = expression.

Source code in src/solidworks_mcp/adapters/solidworks/equations.py
def equation_text(name: str, expression: str) -> str:
    """The equation SolidWorks stores for ``name`` = ``expression``."""
    return f'"{name}" = {expression.strip()}'

split_equation

split_equation(text: str) -> tuple[str, str]

An equation's name and expression, from its text.

Text with no quoted name (not one SolidWorks writes) gives an empty name and the whole text as the expression.

Source code in src/solidworks_mcp/adapters/solidworks/equations.py
def split_equation(text: str) -> tuple[str, str]:
    """An equation's name and expression, from its text.

    Text with no quoted name (not one SolidWorks writes) gives an empty name
    and the whole text as the expression.
    """
    match = _NAME.match(text)
    if not match:
        return "", text.strip()
    rest = text[match.end() :].lstrip()
    return match.group(1), rest[1:].strip() if rest.startswith("=") else rest