Skip to content

solidworks_mcp.server

solidworks_mcp.server

Main SolidWorks MCP Server implementation using FastMCP and PydanticAI.

This server provides 88+ tools for comprehensive SolidWorks automation with configurable deployment (local/remote) and security options.

Attributes

AGENT_SYSTEM_PROMPT module-attribute

AGENT_SYSTEM_PROMPT = 'You are a SolidWorks automation expert. You have access to comprehensive SolidWorks tools for CAD automation, modeling, drawing creation, analysis, and file management. Always prioritize safety, accuracy, and user intent. For complex operations, break them down into manageable steps.'

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)

Bases: Generic[T]

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.

CachePolicy dataclass

CachePolicy(enabled: bool = True, default_ttl_seconds: int = 60, max_entries: int = 512)

Cache policy options for adapter responses.

Attributes:

Name Type Description
default_ttl_seconds int

The default ttl seconds value.

enabled bool

The enabled value.

max_entries int

The max entries value.

ComplexityAnalyzer

ComplexityAnalyzer(parameter_threshold: int = 12, score_threshold: float = 0.6)

Analyze operation complexity and recommend COM or VBA execution path.

Parameters:

Name Type Description Default
parameter_threshold int

The parameter threshold value. Defaults to 12.

12
score_threshold float

The score threshold value. Defaults to 0.6.

0.6

Attributes:

Name Type Description
_parameter_threshold Any

The parameter threshold value.

_score_threshold Any

The score threshold value.

Initialize analyzer state.

Parameters:

Name Type Description Default
parameter_threshold int

The parameter threshold value. Defaults to 12.

12
score_threshold float

The score threshold value. Defaults to 0.6.

0.6

Returns:

Name Type Description
None None

None.

Source code in src/solidworks_mcp/adapters/complexity_analyzer.py
def __init__(
    self,
    parameter_threshold: int = 12,
    score_threshold: float = 0.6,
) -> None:
    """Initialize analyzer state.

    Args:
        parameter_threshold (int): The parameter threshold value. Defaults to 12.
        score_threshold (float): The score threshold value. Defaults to 0.6.

    Returns:
        None: None.
    """
    self._parameter_threshold = max(parameter_threshold, 1)
    self._score_threshold = max(min(score_threshold, 1.0), 0.1)
    self._profiles: dict[str, OperationProfile] = self._default_profiles()
    self._history: dict[str, dict[str, int]] = {}
Functions
analyze
analyze(operation: str, payload: object) -> RoutingDecision

Produce a routing recommendation for an operation call.

Parameters:

Name Type Description Default
operation str

Callable object executed by the helper.

required
payload object

The payload value.

required

Returns:

Name Type Description
RoutingDecision RoutingDecision

The result produced by the operation.

Source code in src/solidworks_mcp/adapters/complexity_analyzer.py
def analyze(self, operation: str, payload: object) -> RoutingDecision:
    """Produce a routing recommendation for an operation call.

    Args:
        operation (str): Callable object executed by the helper.
        payload (object): The payload value.

    Returns:
        RoutingDecision: The result produced by the operation.
    """
    profile = self._profiles.get(
        operation,
        OperationProfile(name=operation, base_complexity=0.2, vba_preferred=False),
    )
    parameter_count = self._count_parameters(payload)

    parameter_component = min(
        parameter_count / float(self._parameter_threshold), 1.0
    )
    history_component = self._history_bias(operation)
    complexity_score = min(
        1.0,
        (parameter_component * 0.45)
        + (profile.base_complexity * 0.40)
        + (history_component * 0.15),
    )

    prefer_vba = (
        parameter_count > self._parameter_threshold
        or profile.vba_preferred
        or complexity_score >= self._score_threshold
    )

    reason = (
        "parameter threshold exceeded"
        if parameter_count > self._parameter_threshold
        else "profile prefers VBA"
        if profile.vba_preferred
        else "complexity score exceeded threshold"
        if complexity_score >= self._score_threshold
        else "COM path preferred"
    )

    return RoutingDecision(
        operation=operation,
        parameter_count=parameter_count,
        complexity_score=complexity_score,
        prefer_vba=prefer_vba,
        reason=reason,
    )
record_result
record_result(operation: str, route: str, success: bool) -> None

Record operation outcome for future routing influence.

Parameters:

Name Type Description Default
operation str

Callable object executed by the helper.

required
route str

The route value.

required
success bool

The success value.

required

Returns:

Name Type Description
None None

None.

Source code in src/solidworks_mcp/adapters/complexity_analyzer.py
def record_result(self, operation: str, route: str, success: bool) -> None:
    """Record operation outcome for future routing influence.

    Args:
        operation (str): Callable object executed by the helper.
        route (str): The route value.
        success (bool): The success value.

    Returns:
        None: None.
    """
    history = self._history.setdefault(
        operation,
        {
            "com_success": 0,
            "com_failure": 0,
            "vba_success": 0,
            "vba_failure": 0,
        },
    )
    key = f"{route}_{'success' if success else 'failure'}"
    if key in history:
        history[key] += 1

DeploymentMode

Bases: StrEnum

Deployment mode options.

Attributes:

Name Type Description
HYBRID Any

The hybrid value.

LOCAL Any

The local value.

REMOTE Any

The remote value.

IntelligentRouter

IntelligentRouter(analyzer: ComplexityAnalyzer, cache: ResponseCache, cacheable_operations: set[str] | None = None)

Route operations between COM and VBA paths using complexity analysis.

Parameters:

Name Type Description Default
analyzer ComplexityAnalyzer

The analyzer value.

required
cache ResponseCache

The cache value.

required
cacheable_operations set[str] | None

The cacheable operations value. Defaults to None.

None

Attributes:

Name Type Description
_analyzer Any

The analyzer value.

_cache Any

The cache value.

_cacheable_operations Any

The cacheable operations value.

Initialize router dependencies.

Parameters:

Name Type Description Default
analyzer ComplexityAnalyzer

The analyzer value.

required
cache ResponseCache

The cache value.

required
cacheable_operations set[str] | None

The cacheable operations value. Defaults to None.

None

Returns:

Name Type Description
None None

None.

Source code in src/solidworks_mcp/adapters/intelligent_router.py
def __init__(
    self,
    analyzer: ComplexityAnalyzer,
    cache: ResponseCache,
    cacheable_operations: set[str] | None = None,
) -> None:
    """Initialize router dependencies.

    Args:
        analyzer (ComplexityAnalyzer): The analyzer value.
        cache (ResponseCache): The cache value.
        cacheable_operations (set[str] | None): The cacheable operations value. Defaults to
                                                None.

    Returns:
        None: None.
    """
    self._analyzer = analyzer
    self._cache = cache
    self._cacheable_operations = cacheable_operations or {
        # Lightweight metadata operations
        "get_model_info",
        "list_features",
        "list_configurations",
        "get_file_properties",
        "get_dimension",
        # Analysis operations — NOT cached: model state changes with
        # every feature-creation tool call and the router has no
        # automatic invalidation. Caching these produced stale
        # volumes mid-build.
        # "get_mass_properties",
        # "calculate_mass_properties",
        "get_material_properties",
        "analyze_geometry",
        "check_interference",
        # Drawing analysis operations
        "analyze_drawing_comprehensive",
        "analyze_drawing_dimensions",
        "analyze_drawing_views",
        "analyze_drawing_annotations",
        "check_drawing_compliance",
        "check_drawing_standards",
        "compare_drawing_versions",
        # Classification and indexing
        "classify_feature_tree",
        "discover_solidworks_docs",
    }
Functions
execute async
execute(operation: str, payload: object, call_args: tuple[Any, ...], call_kwargs: dict[str, Any], com_operation: OperationCallable, vba_operation: OperationCallable | None, cache_ttl_seconds: int | None = None) -> tuple[AdapterResult[Any], RouteResult]

Provide execute support for the intelligent router.

Parameters:

Name Type Description Default
operation str

Callable object executed by the helper.

required
payload object

The payload value.

required
call_args tuple[Any, ...]

The call args value.

required
call_kwargs dict[str, Any]

The call kwargs value.

required
com_operation OperationCallable

The com operation value.

required
vba_operation OperationCallable | None

The vba operation value.

required
cache_ttl_seconds int | None

The cache ttl seconds value. Defaults to None.

None

Returns:

Type Description
tuple[AdapterResult[Any], RouteResult]

tuple[AdapterResult[Any], RouteResult]: A tuple containing the resulting values.

Source code in src/solidworks_mcp/adapters/intelligent_router.py
async def execute(
    self,
    operation: str,
    payload: object,
    call_args: tuple[Any, ...],
    call_kwargs: dict[str, Any],
    com_operation: OperationCallable,
    vba_operation: OperationCallable | None,
    cache_ttl_seconds: int | None = None,
) -> tuple[AdapterResult[Any], RouteResult]:
    """Provide execute support for the intelligent router.

    Args:
        operation (str): Callable object executed by the helper.
        payload (object): The payload value.
        call_args (tuple[Any, ...]): The call args value.
        call_kwargs (dict[str, Any]): The call kwargs value.
        com_operation (OperationCallable): The com operation value.
        vba_operation (OperationCallable | None): The vba operation value.
        cache_ttl_seconds (int | None): The cache ttl seconds value. Defaults to None.

    Returns:
        tuple[AdapterResult[Any], RouteResult]: A tuple containing the resulting values.
    """
    if operation in self._cacheable_operations and self._cache.enabled:
        key = self._cache.make_key(operation, payload)
        cached = self._cache.get(key)
        if isinstance(cached, AdapterResult):
            return cached, RouteResult(route="cache", used_cache=True)

    decision = self._analyzer.analyze(operation=operation, payload=payload)

    if decision.prefer_vba and vba_operation is not None:
        vba_result = await self._safe_call(vba_operation, call_args, call_kwargs)
        self._analyzer.record_result(
            operation=operation,
            route="vba",
            success=vba_result.is_success,
        )
        if vba_result.is_success:
            self._cache_result(operation, payload, vba_result, cache_ttl_seconds)
            return vba_result, RouteResult(route="vba", used_cache=False)

    com_result = await self._safe_call(com_operation, call_args, call_kwargs)
    self._analyzer.record_result(
        operation=operation,
        route="com",
        success=com_result.is_success,
    )

    if com_result.is_success:
        self._cache_result(operation, payload, com_result, cache_ttl_seconds)
        return com_result, RouteResult(route="com", used_cache=False)

    if not decision.prefer_vba and vba_operation is not None:
        fallback_result = await self._safe_call(
            vba_operation,
            call_args,
            call_kwargs,
        )
        self._analyzer.record_result(
            operation=operation,
            route="vba",
            success=fallback_result.is_success,
        )
        if fallback_result.is_success:
            self._cache_result(
                operation,
                payload,
                fallback_result,
                cache_ttl_seconds,
            )
            return fallback_result, RouteResult(
                route="vba-fallback", used_cache=False
            )

    return com_result, RouteResult(route="com-error", used_cache=False)

MCPServerState

Bases: BaseModel

Server state management - serializable fields only.

Attributes:

Name Type Description
adapter Any | None

The adapter value.

agent Any | None

The agent value.

config SolidWorksMCPConfig

The config value.

is_connected bool

The is connected value.

startup_time str | None

The startup time value.

tool_count int

The tool count value.

ResponseCache

ResponseCache(policy: CachePolicy)

Thread-safe in-memory cache for adapter response objects.

Parameters:

Name Type Description Default
policy CachePolicy

The policy value.

required

Attributes:

Name Type Description
_lock Any

The lock value.

_policy Any

The policy value.

Initialize this cache.

Parameters:

Name Type Description Default
policy CachePolicy

The policy value.

required

Returns:

Name Type Description
None None

None.

Source code in src/solidworks_mcp/cache/response_cache.py
def __init__(self, policy: CachePolicy) -> None:
    """Initialize this cache.

    Args:
        policy (CachePolicy): The policy value.

    Returns:
        None: None.
    """
    self._policy = policy
    self._entries: dict[str, _CacheEntry[object]] = {}
    self._lock = RLock()
Attributes
enabled property
enabled: bool

Return whether caching is enabled.

Returns:

Name Type Description
bool bool

True if enabled, otherwise False.

Functions
get
get(key: str) -> object | None

Fetch a cached value when present and unexpired.

Parameters:

Name Type Description Default
key str

The key value.

required

Returns:

Type Description
object | None

object | None: The result produced by the operation.

Source code in src/solidworks_mcp/cache/response_cache.py
def get(self, key: str) -> object | None:
    """Fetch a cached value when present and unexpired.

    Args:
        key (str): The key value.

    Returns:
        object | None: The result produced by the operation.
    """
    if not self._policy.enabled:
        return None

    now = time.time()
    with self._lock:
        entry = self._entries.get(key)
        if entry is None:
            return None
        if entry.expires_at <= now:
            self._entries.pop(key, None)
            return None
        return entry.value
make_key
make_key(operation: str, payload: object) -> str

Build a deterministic cache key from an operation payload.

Parameters:

Name Type Description Default
operation str

Callable object executed by the helper.

required
payload object

The payload value.

required

Returns:

Name Type Description
str str

The resulting text value.

Source code in src/solidworks_mcp/cache/response_cache.py
def make_key(self, operation: str, payload: object) -> str:
    """Build a deterministic cache key from an operation payload.

    Args:
        operation (str): Callable object executed by the helper.
        payload (object): The payload value.

    Returns:
        str: The resulting text value.
    """
    normalized = self._normalize_payload(payload)
    raw = f"{operation}:{normalized}".encode()
    return hashlib.sha256(raw).hexdigest()
set
set(key: str, value: object, ttl_seconds: int | None = None) -> None

Store a cache value with expiration.

Parameters:

Name Type Description Default
key str

The key value.

required
value object

The value value.

required
ttl_seconds int | None

The ttl seconds value. Defaults to None.

None

Returns:

Name Type Description
None None

None.

Source code in src/solidworks_mcp/cache/response_cache.py
def set(self, key: str, value: object, ttl_seconds: int | None = None) -> None:
    """Store a cache value with expiration.

    Args:
        key (str): The key value.
        value (object): The value value.
        ttl_seconds (int | None): The ttl seconds value. Defaults to None.

    Returns:
        None: None.
    """
    if not self._policy.enabled:
        return

    ttl = (
        ttl_seconds if ttl_seconds is not None else self._policy.default_ttl_seconds
    )
    now = time.time()
    entry = _CacheEntry(value=value, created_at=now, expires_at=now + max(ttl, 1))

    with self._lock:
        if len(self._entries) >= self._policy.max_entries:
            self._evict_oldest_unlocked()
        self._entries[key] = entry

SolidWorksMCPConfig

Bases: BaseModel

Main configuration for SolidWorks MCP Server.

Attributes:

Name Type Description
adapter_type AdapterType

The adapter type value.

allowed_hosts list[str]

The allowed hosts value.

allowed_origins list[str]

The allowed origins value.

api_key SecretStr | None

The api key value.

api_key_required bool

The api key required value.

api_keys list[str]

The api keys value.

cache_dir Path | None

The cache dir value.

circuit_breaker_enabled bool

The circuit breaker enabled value.

circuit_breaker_threshold int

The circuit breaker threshold value.

circuit_breaker_timeout int

The circuit breaker timeout value.

complexity_parameter_threshold int

The complexity parameter threshold value.

complexity_score_threshold float

The complexity score threshold value.

connection_pool_size int

The connection pool size value.

connection_pooling bool

The connection pooling value.

cors_origins list[str]

The cors origins value.

data_dir Path

The data dir value.

database_url str

The database url value.

debug bool

The debug value.

deployment_mode DeploymentMode

The deployment mode value.

enable_analysis_tools bool

The enable analysis tools value.

enable_audit_logging bool

The enable audit logging value.

enable_circuit_breaker bool

The enable circuit breaker value.

enable_connection_pooling bool

The enable connection pooling value.

enable_cors bool

The enable cors value.

enable_design_tables bool

The enable design tables value.

enable_intelligent_routing bool

The enable intelligent routing value.

enable_macro_recording bool

The enable macro recording value.

enable_pdm bool

The enable pdm value.

enable_rate_limiting bool

The enable rate limiting value.

enable_response_cache bool

The enable response cache value.

enable_sql_integration bool

The enable sql integration value.

enable_windows_validation bool

The enable windows validation value.

host str

The host value.

log_file Path | None

The log file value.

log_level str

The log level value.

max_connections int

The max connections value.

max_retries int

The max retries value.

mock_solidworks bool

The mock solidworks value.

model_config Any

The model config value.

pdm_server str | None

The pdm server value.

pdm_vault str | None

The pdm vault value.

port int

The port value.

rate_limit_enabled bool

The rate limit enabled value.

rate_limit_per_minute int

The rate limit per minute value.

response_cache_max_entries int

The response cache max entries value.

response_cache_ttl_seconds int

The response cache ttl seconds value.

security_level SecurityLevel

The security level value.

solidworks_path str | None

The solidworks path value.

solidworks_year int | None

The solidworks year value.

sql_connection str | None

The sql connection value.

state_file str | None

The state file value.

testing bool

The testing value.

timeout_seconds float

The timeout seconds value.

worker_processes int

The worker processes value.

Attributes
can_use_solidworks property
can_use_solidworks: bool

Check if SolidWorks integration is possible.

Returns:

Name Type Description
bool bool

True if use solidworks, otherwise False.

is_windows property
is_windows: bool

Check if running on Windows.

Returns:

Name Type Description
bool bool

True if windows, otherwise False.

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

Build configuration from environment variables.

Parameters:

Name Type Description Default
env_file str | None

The env file value. Defaults to None.

None

Returns:

Name Type Description
SolidWorksMCPConfig SolidWorksMCPConfig

The result produced by the operation.

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

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

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

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

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

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

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

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

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

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

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

Get database configuration.

Returns:

Type Description
dict[str, Any]

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

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

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

Get security configuration.

Returns:

Type Description
dict[str, Any]

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

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

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

Post-initialization setup.

Parameters:

Name Type Description Default
__context Any

The context value.

required

Returns:

Name Type Description
None None

None.

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

    Args:
        __context (Any): The context value.

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

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

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

Set default cache directory.

Parameters:

Name Type Description Default
v Path | None

The v value.

required
info ValidationInfo

The info value.

required

Returns:

Name Type Description
Path Path

The result produced by the operation.

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

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

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

Set default log file path.

Parameters:

Name Type Description Default
v Path | None

The v value.

required
info ValidationInfo

The info value.

required

Returns:

Name Type Description
Path Path

The result produced by the operation.

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

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

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

Sync test/developer alias fields into canonical runtime fields.

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

Returns:

Name Type Description
SolidWorksMCPConfig SolidWorksMCPConfig

The result produced by the operation.

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

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

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

Validate adapter type based on platform.

Parameters:

Name Type Description Default
v AdapterType

The v value.

required
info ValidationInfo

The info value.

required

Returns:

Name Type Description
AdapterType AdapterType

The result produced by the operation.

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

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

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

Validate the complexity parameter threshold.

Parameters:

Name Type Description Default
v int

The v value.

required

Returns:

Name Type Description
int int

The computed numeric result.

Raises:

Type Description
ValueError

Complexity_parameter_threshold must be >= 1.

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

    Args:
        v (int): The v value.

    Returns:
        int: The computed numeric result.

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

Validate the complexity score threshold.

Parameters:

Name Type Description Default
v float

The v value.

required

Returns:

Name Type Description
float float

The computed numeric result.

Raises:

Type Description
ValueError

Complexity_score_threshold must be in (0, 1].

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

    Args:
        v (float): The v value.

    Returns:
        float: The computed numeric result.

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

Validate the port.

Parameters:

Name Type Description Default
v int

The v value.

required

Returns:

Name Type Description
int int

The computed numeric result.

Raises:

Type Description
ValueError

Port must be between 1 and 65535.

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

    Args:
        v (int): The v value.

    Returns:
        int: The computed numeric result.

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

Validate response cache size.

Parameters:

Name Type Description Default
v int

The v value.

required

Returns:

Name Type Description
int int

The computed numeric result.

Raises:

Type Description
ValueError

Response_cache_max_entries must be >= 1.

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

    Args:
        v (int): The v value.

    Returns:
        int: The computed numeric result.

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

Validate default response cache TTL.

Parameters:

Name Type Description Default
v int

The v value.

required

Returns:

Name Type Description
int int

The computed numeric result.

Raises:

Type Description
ValueError

Response_cache_ttl_seconds must be >= 1.

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

    Args:
        v (int): The v value.

    Returns:
        int: The computed numeric result.

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

Validate the timeout.

Parameters:

Name Type Description Default
v float

The v value.

required

Returns:

Name Type Description
float float

The computed numeric result.

Raises:

Type Description
ValueError

Timeout_seconds must be > 0.

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

    Args:
        v (float): The v value.

    Returns:
        float: The computed numeric result.

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

SolidWorksMCPError

Bases: Exception

Base exception for SolidWorks MCP Server errors.

SolidWorksMCPServer

SolidWorksMCPServer(config: SolidWorksMCPConfig)

Main SolidWorks MCP Server class.

Parameters:

Name Type Description Default
config SolidWorksMCPConfig

Configuration values for the operation.

required

Attributes:

Name Type Description
_db_logging_enabled Any

The db logging enabled value.

_db_path Any

The db path value.

_db_run_id Any

The db run id value.

_setup_complete Any

The setup complete value.

config Any

The config value.

mcp Any

The mcp value.

server Any

The server value.

state Any

The state value.

Initialize the solid works mcpserver.

Parameters:

Name Type Description Default
config SolidWorksMCPConfig

Configuration values for the operation.

required
Source code in src/solidworks_mcp/server.py
def __init__(self, config: SolidWorksMCPConfig):
    """Initialize the solid works mcpserver.

    Args:
        config (SolidWorksMCPConfig): Configuration values for the operation.
    """
    self.config = config
    self.state = MCPServerState(config=config)
    self.mcp = FastMCP("SolidWorks MCP Server")
    self.server = None
    self._setup_complete = False
    self._db_logging_enabled = self._env_truthy(
        os.getenv("SOLIDWORKS_MCP_DB_LOGGING", "0")
    )
    self._db_run_id = os.getenv("SOLIDWORKS_MCP_CONVERSATION_ID") or str(
        uuid.uuid4()
    )
    self._db_path = (
        os.getenv("SOLIDWORKS_MCP_DB_PATH")
        if os.getenv("SOLIDWORKS_MCP_DB_PATH")
        else None
    )

    # Runtime objects (not serializable)
    self.adapter: Any | None = None
    self.agent: Any | None = None
    self._router: IntelligentRouter | None = None
    self._vba_adapter: VbaGeneratorAdapter | None = None
Functions
health_check async
health_check() -> dict[str, Any]

Get server health status.

Returns:

Type Description
dict[str, Any]

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

Source code in src/solidworks_mcp/server.py
async def health_check(self) -> dict[str, Any]:
    """Get server health status.

    Returns:
        dict[str, Any]: A dictionary containing the resulting values.
    """
    adapter_health = None
    if self.adapter:
        adapter_health = await self.adapter.health_check()

    return {
        "status": "healthy" if self.state.is_connected else "warning",
        "config": {
            "deployment_mode": self.config.deployment_mode,
            "adapter_type": self.config.adapter_type,
            "security_level": self.config.security_level,
            "platform": platform.system(),
        },
        "state": {
            "connected": self.state.is_connected,
            "startup_time": self.state.startup_time,
            "tool_count": self.state.tool_count,
        },
        "adapter": adapter_health,
    }
setup async
setup() -> None

Initialize the server components.

Returns:

Name Type Description
None None

None.

Source code in src/solidworks_mcp/server.py
async def setup(self) -> None:
    """Initialize the server components.

    Returns:
        None: None.
    """
    if self._setup_complete:
        return

    logger.info("Setting up SolidWorks MCP Server...")

    # Validate environment
    await utils.validate_environment(self.config)

    # Setup security
    await security.setup_security(self.mcp, self.config)

    # Create SolidWorks adapter
    self.adapter = await adapters.create_adapter(self.config)
    self._configure_runtime_services()
    self.state.adapter = self.adapter

    # Register tools and derive canonical count from FastMCP runtime
    await tools.register_tools(self.mcp, self.adapter, self.config)
    self.state.tool_count = len(await self.mcp.list_tools())
    self.server = self.mcp

    # Setup PydanticAI agent after tools are registered so the agent can bind
    # directly to the in-process FastMCP server without a transport hop.
    await self._setup_agent()
    self.state.agent = self.agent

    self._setup_complete = True
    logger.info(f"Server setup complete with {self.state.tool_count} tools")
start async
start() -> None

Start the MCP server.

Returns:

Name Type Description
None None

None.

Source code in src/solidworks_mcp/server.py
async def start(self) -> None:
    """Start the MCP server.

    Returns:
        None: None.
    """
    await self.setup()

    if self.adapter:
        try:
            await self.adapter.connect()
            self.state.is_connected = True
            logger.info("Connected to SolidWorks")
        except Exception as e:
            logger.warning(f"Could not connect to SolidWorks: {e}")
            if not self.config.mock_solidworks:
                logger.warning("Continuing with mock adapter for testing")

    # Record startup time
    from datetime import datetime

    self.state.startup_time = datetime.now().isoformat()

    if self.config.deployment_mode == DeploymentMode.LOCAL:
        # Local stdio mode for MCP
        logger.info("Starting in local MCP mode (stdio)")
        await self._run_local_stdio()
    else:
        # Remote HTTP mode
        logger.info(
            f"Starting in remote mode on {self.config.host}:{self.config.port}"
        )
        await self._start_http_server()
stop async
stop() -> None

Gracefully stop the server.

Returns:

Name Type Description
None None

None.

Source code in src/solidworks_mcp/server.py
async def stop(self) -> None:
    """Gracefully stop the server.

    Returns:
        None: None.
    """
    logger.info("Stopping SolidWorks MCP Server...")

    if self.adapter:
        await self.adapter.disconnect()
        self.state.is_connected = False

    self._setup_complete = False
    self.server = None
    logger.info("Server stopped")

VbaGeneratorAdapter

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

Adapter that executes complex operations through VBA-oriented flow.

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

Parameters:

Name Type Description Default
backing_adapter Any

The backing adapter value.

required
macro_executor VbaMacroExecutor | None

The macro executor value. Defaults to None.

None

Attributes:

Name Type Description
_backing_adapter Any

The backing adapter value.

_macro_executor Any

The macro executor value.

config Any

The config value.

Initialize the vba generator adapter.

Parameters:

Name Type Description Default
backing_adapter Any

The backing adapter value.

required
macro_executor VbaMacroExecutor | None

The macro executor value. Defaults to None.

None

Returns:

Name Type Description
None None

None.

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

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

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

Delegate unknown members to backing adapter.

Parameters:

Name Type Description Default
item str

The item value.

required

Returns:

Name Type Description
Any Any

The result produced by the operation.

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

    Args:
        item (str): The item value.

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

Connect to SolidWorks using wrapped adapter.

Returns:

Name Type Description
None None

None.

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

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

Create the extrusion.

Parameters:

Name Type Description Default
params ExtrusionParameters

The params value.

required

Returns:

Type Description
AdapterResult[Any]

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

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

    Args:
        params (ExtrusionParameters): The params value.

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

Create the loft.

Parameters:

Name Type Description Default
params LoftParameters

The params value.

required

Returns:

Type Description
AdapterResult[Any]

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

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

    Args:
        params (LoftParameters): The params value.

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

Create the revolve.

Parameters:

Name Type Description Default
params RevolveParameters

The params value.

required

Returns:

Type Description
AdapterResult[Any]

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

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

    Args:
        params (RevolveParameters): The params value.

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

Create the sweep.

Parameters:

Name Type Description Default
params SweepParameters

The params value.

required

Returns:

Type Description
AdapterResult[Any]

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

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

    Args:
        params (SweepParameters): The params value.

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

Disconnect wrapped adapter.

Returns:

Name Type Description
None None

None.

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

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

Provide execute macro support for the vba generator adapter.

Parameters:

Name Type Description Default
macro_code str

The macro code value.

required
macro_name str

The macro name value. Defaults to "GeneratedMacro".

'GeneratedMacro'
subroutine str

The subroutine value. Defaults to "Main".

'Main'

Returns:

Type Description
AdapterResult[Any]

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

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

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

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

Retrieve VBA macro execution history.

Parameters:

Name Type Description Default
macro_name str | None

The macro name value. Defaults to None.

None

Returns:

Type Description
dict[str, Any]

dict[ str, Any,

dict[str, Any]

]: A dictionary containing the resulting values.

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

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

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

Return wrapped adapter health with VBA route marker.

Returns:

Name Type Description
Any Any

The result produced by the operation.

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

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

Return wrapped adapter connection state.

Returns:

Name Type Description
bool bool

True if connected, otherwise False.

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

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

Functions

_run_server async

_run_server(server: SolidWorksMCPServer) -> None

Run server lifecycle with graceful shutdown.

Parameters:

Name Type Description Default
server SolidWorksMCPServer

The server value.

required

Returns:

Name Type Description
None None

None.

Source code in src/solidworks_mcp/server.py
async def _run_server(server: SolidWorksMCPServer) -> None:
    """Run server lifecycle with graceful shutdown.

    Args:
        server (SolidWorksMCPServer): The server value.

    Returns:
        None: None.
    """
    try:
        await server.start()
    except KeyboardInterrupt:
        logger.info("Received interrupt signal")
    except Exception as e:
        logger.error(f"Server error: {e}")
        raise
    finally:
        await server.stop()

_run_with_config async

_run_with_config(config: SolidWorksMCPConfig) -> None

Run the server from a fully prepared config object.

Parameters:

Name Type Description Default
config SolidWorksMCPConfig

Configuration values for the operation.

required

Returns:

Name Type Description
None None

None.

Source code in src/solidworks_mcp/server.py
async def _run_with_config(config: SolidWorksMCPConfig) -> None:
    """Run the server from a fully prepared config object.

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

    Returns:
        None: None.
    """
    utils.setup_logging(config)

    logger.info("Starting SolidWorks MCP Server...")
    logger.info(f"Platform: {platform.system()}")
    logger.info(f"Python version: {sys.version}")
    logger.info(f"Deployment mode: {config.deployment_mode}")
    logger.info(f"Security level: {config.security_level}")

    server = SolidWorksMCPServer(config)
    await _run_server(server)

cli

cli(config: str | None = typer.Option(None, '--config', help='Configuration file path'), mode: str | None = typer.Option(None, '--mode', help='Deployment mode (local/remote/hybrid)'), host: str = typer.Option('localhost', '--host', help='Server host for remote mode'), port: int = typer.Option(8000, '--port', help='Server port for remote mode'), debug: bool = typer.Option(False, '--debug', help='Enable debug mode'), mock: bool = typer.Option(False, '--mock', help='Use mock SolidWorks for testing')) -> None

Start the SolidWorks MCP Server.

Parameters:

Name Type Description Default
config str | None

Configuration values for the operation. Defaults to typer.Option( None, "--config", help="Configuration file path", ).

Option(None, '--config', help='Configuration file path')
mode str | None

The mode value. Defaults to typer.Option( None, " --mode", help="Deployment mode (local/remote/hybrid)", ).

Option(None, '--mode', help='Deployment mode (local/remote/hybrid)')
host str

The host value. Defaults to typer.Option( "localhost", " --host", help="Server host for remote mode", ).

Option('localhost', '--host', help='Server host for remote mode')
port int

The port value. Defaults to typer.Option( 8000, "-- port", help="Server port for remote mode", ).

Option(8000, '--port', help='Server port for remote mode')
debug bool

The debug value. Defaults to typer.Option( False, "-- debug", help="Enable debug mode", ).

Option(False, '--debug', help='Enable debug mode')
mock bool

The mock value. Defaults to typer.Option( False, "-- mock", help="Use mock SolidWorks for testing", ).

Option(False, '--mock', help='Use mock SolidWorks for testing')

Returns:

Name Type Description
None None

None.

Source code in src/solidworks_mcp/server.py
def cli(
    config: str | None = typer.Option(
        None,
        "--config",
        help="Configuration file path",
    ),
    mode: str | None = typer.Option(
        None,
        "--mode",
        help="Deployment mode (local/remote/hybrid)",
    ),
    host: str = typer.Option(
        "localhost",
        "--host",
        help="Server host for remote mode",
    ),
    port: int = typer.Option(
        8000,
        "--port",
        help="Server port for remote mode",
    ),
    debug: bool = typer.Option(
        False,
        "--debug",
        help="Enable debug mode",
    ),
    mock: bool = typer.Option(
        False,
        "--mock",
        help="Use mock SolidWorks for testing",
    ),
) -> None:
    """Start the SolidWorks MCP Server.

    Args:
        config (str | None): Configuration values for the operation. Defaults to
                             typer.Option(         None,         "--config",
                             help="Configuration file path",     ).
        mode (str | None): The mode value. Defaults to typer.Option(         None,         "
                           --mode",         help="Deployment mode (local/remote/hybrid)",
                           ).
        host (str): The host value. Defaults to typer.Option(         "localhost",         "
                    --host",         help="Server host for remote mode",     ).
        port (int): The port value. Defaults to typer.Option(         8000,         "--
                    port",         help="Server port for remote mode",     ).
        debug (bool): The debug value. Defaults to typer.Option(         False,         "--
                      debug",         help="Enable debug mode",     ).
        mock (bool): The mock value. Defaults to typer.Option(         False,         "--
                     mock",         help="Use mock SolidWorks for testing",     ).

    Returns:
        None: None.
    """
    loaded_config = load_config(config)

    if mode:
        loaded_config.deployment_mode = DeploymentMode(mode)
    if host:
        loaded_config.host = host
    if port:
        loaded_config.port = port
    if debug:
        loaded_config.debug = True
        loaded_config.log_level = "DEBUG"
    if mock:
        loaded_config.mock_solidworks = True

    asyncio.run(_run_with_config(loaded_config))

cli_main

cli_main() -> None

Console script entry point using Typer CLI.

Returns:

Name Type Description
None None

None.

Source code in src/solidworks_mcp/server.py
def cli_main() -> None:
    """Console script entry point using Typer CLI.

    Returns:
        None: None.
    """
    typer.run(cli)

create_server

create_server(config: SolidWorksMCPConfig | None = None) -> SolidWorksMCPServer

Create a SolidWorks MCP Server instance.

Parameters:

Name Type Description Default
config SolidWorksMCPConfig | None

Configuration values for the operation. Defaults to None.

None

Returns:

Name Type Description
SolidWorksMCPServer SolidWorksMCPServer

The result produced by the operation.

Source code in src/solidworks_mcp/server.py
def create_server(config: SolidWorksMCPConfig | None = None) -> SolidWorksMCPServer:
    """Create a SolidWorks MCP Server instance.

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

    Returns:
        SolidWorksMCPServer: The result produced by the operation.
    """
    if config is None:
        config = load_config()

    return SolidWorksMCPServer(config)

insert_tool_event

insert_tool_event(*, run_id: str, tool_name: str, phase: str, payload_json: str | None, db_path: Path | None = None) -> None

Store lifecycle events around MCP tool usage to aid troubleshooting.

Parameters:

Name Type Description Default
run_id str

The run id value.

required
tool_name str

The tool name value.

required
phase str

The phase value.

required
payload_json str | None

The payload json value.

required
db_path Path | None

The db path value. Defaults to None.

None

Returns:

Name Type Description
None None

None.

Source code in src/solidworks_mcp/agents/history_db.py
def insert_tool_event(
    *,
    run_id: str,
    tool_name: str,
    phase: str,
    payload_json: str | None,
    db_path: Path | None = None,
) -> None:
    """Store lifecycle events around MCP tool usage to aid troubleshooting.

    Args:
        run_id (str): The run id value.
        tool_name (str): The tool name value.
        phase (str): The phase value.
        payload_json (str | None): The payload json value.
        db_path (Path | None): The db path value. Defaults to None.

    Returns:
        None: None.
    """
    resolved = init_db(db_path)
    engine = _build_engine(resolved)
    with Session(engine) as session:
        session.add(
            ToolEvent(
                run_id=run_id,
                tool_name=tool_name,
                phase=phase,
                payload_json=payload_json,
                created_at=_utc_now_iso(),
            )
        )
        session.commit()

list_capabilities async

list_capabilities() -> dict[str, list[str]]

List all available SolidWorks capabilities and tool categories.

Returns:

Type Description
dict[str, list[str]]

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

Source code in src/solidworks_mcp/server.py
async def list_capabilities() -> dict[str, list[str]]:
    """List all available SolidWorks capabilities and tool categories.

    Returns:
        dict[str, list[str]]: A dictionary containing the resulting values.
    """
    return {
        "modeling": [
            "create_part",
            "create_assembly",
            "create_drawing",
            "create_extrusion",
            "create_revolve",
            "create_sweep",
            "create_loft",
            "create_cut",
            "create_fillet",
            "create_chamfer",
        ],
        "sketching": [
            "create_sketch",
            "add_line",
            "add_circle",
            "add_rectangle",
            "add_arc",
            "add_spline",
            "add_dimension",
            "add_relation",
        ],
        "drawing": [
            "create_drawing_view",
            "add_section_view",
            "add_detail_view",
            "add_dimension_to_view",
            "add_annotation",
            "create_drawing_template",
        ],
        "analysis": [
            "get_mass_properties",
            "perform_fea_analysis",
            "check_interference",
            "analyze_geometry",
            "get_material_properties",
        ],
        "export": [
            "export_step",
            "export_iges",
            "export_stl",
            "export_pdf",
            "export_dwg",
            "export_images",
            "batch_export",
        ],
        "automation": [
            "generate_vba_macro",
            "record_macro",
            "batch_process",
            "create_design_table",
            "manage_configurations",
        ],
        "file_management": [
            "open_file",
            "save_file",
            "save_as",
            "close_file",
            "get_file_properties",
            "manage_references",
        ],
    }

load_config

load_config(config_file: str | None = None) -> SolidWorksMCPConfig

Load configuration from file and environment variables.

Parameters:

Name Type Description Default
config_file str | None

The config file value. Defaults to None.

None

Returns:

Name Type Description
SolidWorksMCPConfig SolidWorksMCPConfig

The result produced by the operation.

Source code in src/solidworks_mcp/config.py
def load_config(config_file: str | None = None) -> SolidWorksMCPConfig:
    """Load configuration from file and environment variables.

    Args:
        config_file (str | None): The config file value. Defaults to None.

    Returns:
        SolidWorksMCPConfig: The result produced by the operation.
    """
    if config_file:
        config_path = Path(config_file)
        if config_path.exists() and config_path.suffix.lower() == ".json":
            import json

            with config_path.open("r", encoding="utf-8") as f:
                data = json.load(f)
            return SolidWorksMCPConfig(**data)
        return SolidWorksMCPConfig.from_env(str(config_path))

    return SolidWorksMCPConfig.from_env()

main async

main() -> None

Legacy async entry point retained for tests and internal callers.

Returns:

Name Type Description
None None

None.

Source code in src/solidworks_mcp/server.py
async def main() -> None:
    """Legacy async entry point retained for tests and internal callers.

    Returns:
        None: None.
    """
    import argparse

    parser = argparse.ArgumentParser(description="SolidWorks MCP Server")
    parser.add_argument(
        "--config", help="Configuration file path", type=str, default=None
    )
    parser.add_argument(
        "--mode",
        help="Deployment mode (local/remote/hybrid)",
        choices=["local", "remote", "hybrid"],
        default=None,
    )
    parser.add_argument(
        "--host", help="Server host for remote mode", default="localhost"
    )
    parser.add_argument(
        "--port", help="Server port for remote mode", type=int, default=8000
    )
    parser.add_argument("--debug", help="Enable debug mode", action="store_true")
    parser.add_argument(
        "--mock", help="Use mock SolidWorks for testing", action="store_true"
    )

    args = parser.parse_args()

    config = load_config(args.config)

    if args.mode:
        config.deployment_mode = DeploymentMode(args.mode)
    if args.host:
        config.host = args.host
    if args.port:
        config.port = args.port
    if args.debug:
        config.debug = True
        config.log_level = "DEBUG"
    if args.mock:
        config.mock_solidworks = True

    await _run_with_config(config)

run_server

run_server() -> None

Synchronous entry point for the server.

Returns:

Name Type Description
None None

None.

Source code in src/solidworks_mcp/server.py
def run_server() -> None:
    """Synchronous entry point for the server.

    Returns:
        None: None.
    """
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        logger.info("Server stopped by user")
    except Exception as e:
        logger.error(f"Fatal error: {e}")
        sys.exit(1)

server_status async

server_status() -> dict[str, Any]

Get comprehensive server status information.

Returns:

Type Description
dict[str, Any]

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

Source code in src/solidworks_mcp/server.py
async def server_status() -> dict[str, Any]:
    """Get comprehensive server status information.

    Returns:
        dict[str, Any]: A dictionary containing the resulting values.
    """
    # This will be properly implemented when the server instance is available
    return {
        "status": "Server status endpoint - to be implemented with server state",
        "message": "Use the main server health_check method for detailed status",
    }