solidworks-mcp-python 1.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. solidworks_mcp/__init__.py +57 -0
  2. solidworks_mcp/adapters/__init__.py +40 -0
  3. solidworks_mcp/adapters/base.py +1882 -0
  4. solidworks_mcp/adapters/circuit_breaker.py +2052 -0
  5. solidworks_mcp/adapters/com_executor.py +252 -0
  6. solidworks_mcp/adapters/complexity_analyzer.py +272 -0
  7. solidworks_mcp/adapters/connection_pool.py +1884 -0
  8. solidworks_mcp/adapters/factory.py +366 -0
  9. solidworks_mcp/adapters/intelligent_router.py +218 -0
  10. solidworks_mcp/adapters/mock_adapter.py +4016 -0
  11. solidworks_mcp/adapters/pywin32_adapter.py +2842 -0
  12. solidworks_mcp/adapters/solidworks/__init__.py +17 -0
  13. solidworks_mcp/adapters/solidworks/bitmap.py +180 -0
  14. solidworks_mcp/adapters/solidworks/com_utils.py +56 -0
  15. solidworks_mcp/adapters/solidworks/dimension_layout.py +753 -0
  16. solidworks_mcp/adapters/solidworks/documentation.py +1476 -0
  17. solidworks_mcp/adapters/solidworks/drawing_standard.py +1993 -0
  18. solidworks_mcp/adapters/solidworks/face_selection.py +392 -0
  19. solidworks_mcp/adapters/solidworks/features.py +3362 -0
  20. solidworks_mcp/adapters/solidworks/io.py +3649 -0
  21. solidworks_mcp/adapters/solidworks/rebuild_diagnostics.py +269 -0
  22. solidworks_mcp/adapters/solidworks/rebuild_inspector.py +146 -0
  23. solidworks_mcp/adapters/solidworks/selection.py +308 -0
  24. solidworks_mcp/adapters/solidworks/sketch.py +2545 -0
  25. solidworks_mcp/adapters/sw_feature_errors.py +66 -0
  26. solidworks_mcp/adapters/sw_type_info.py +317 -0
  27. solidworks_mcp/adapters/vba_adapter.py +318 -0
  28. solidworks_mcp/adapters/vba_macro_executor.py +215 -0
  29. solidworks_mcp/agents/__init__.py +68 -0
  30. solidworks_mcp/agents/design_knowledge/assembly_patterns.md +127 -0
  31. solidworks_mcp/agents/design_knowledge/hinges.md +118 -0
  32. solidworks_mcp/agents/design_knowledge/snap_fits.md +93 -0
  33. solidworks_mcp/agents/design_knowledge/solidworks_basics.md +3 -0
  34. solidworks_mcp/agents/design_knowledge/tolerancing.md +128 -0
  35. solidworks_mcp/agents/harness.py +216 -0
  36. solidworks_mcp/agents/history_db.py +1508 -0
  37. solidworks_mcp/agents/retrieval_index.py +164 -0
  38. solidworks_mcp/agents/schemas.py +165 -0
  39. solidworks_mcp/agents/smoke_test.py +285 -0
  40. solidworks_mcp/agents/soc_exporter.py +650 -0
  41. solidworks_mcp/agents/soc_pickup.py +332 -0
  42. solidworks_mcp/agents/soc_rewind.py +221 -0
  43. solidworks_mcp/agents/vector_rag.py +665 -0
  44. solidworks_mcp/cache/__init__.py +5 -0
  45. solidworks_mcp/cache/response_cache.py +164 -0
  46. solidworks_mcp/config.py +729 -0
  47. solidworks_mcp/exceptions.py +37 -0
  48. solidworks_mcp/security/__init__.py +68 -0
  49. solidworks_mcp/security/auth.py +128 -0
  50. solidworks_mcp/security/cors.py +27 -0
  51. solidworks_mcp/security/rate_limiting.py +90 -0
  52. solidworks_mcp/security/runtime.py +155 -0
  53. solidworks_mcp/server.py +777 -0
  54. solidworks_mcp/server_cli_fixed.py +120 -0
  55. solidworks_mcp/setup/__init__.py +1 -0
  56. solidworks_mcp/setup/cli.py +399 -0
  57. solidworks_mcp/setup/clients.py +157 -0
  58. solidworks_mcp/setup/config_file.py +230 -0
  59. solidworks_mcp/setup/handshake.py +202 -0
  60. solidworks_mcp/setup/launcher.py +102 -0
  61. solidworks_mcp/setup/legacy.py +100 -0
  62. solidworks_mcp/setup/registration.py +193 -0
  63. solidworks_mcp/setup/solidworks.py +49 -0
  64. solidworks_mcp/tools/__init__.py +64 -0
  65. solidworks_mcp/tools/analysis.py +723 -0
  66. solidworks_mcp/tools/automation.py +578 -0
  67. solidworks_mcp/tools/docs_discovery.py +1476 -0
  68. solidworks_mcp/tools/drawing.py +1015 -0
  69. solidworks_mcp/tools/drawing_analysis.py +456 -0
  70. solidworks_mcp/tools/drawing_automation.py +627 -0
  71. solidworks_mcp/tools/engineering_data.py +466 -0
  72. solidworks_mcp/tools/error_classifier.py +232 -0
  73. solidworks_mcp/tools/export.py +833 -0
  74. solidworks_mcp/tools/file_facts.py +40 -0
  75. solidworks_mcp/tools/file_management.py +1473 -0
  76. solidworks_mcp/tools/input_compat.py +17 -0
  77. solidworks_mcp/tools/macro_recording.py +464 -0
  78. solidworks_mcp/tools/modeling.py +2360 -0
  79. solidworks_mcp/tools/sketching.py +1422 -0
  80. solidworks_mcp/tools/template_management.py +367 -0
  81. solidworks_mcp/tools/tool_boundary.py +280 -0
  82. solidworks_mcp/tools/vba_generation.py +1145 -0
  83. solidworks_mcp/ui/__init__.py +9 -0
  84. solidworks_mcp/ui/local_llm.py +725 -0
  85. solidworks_mcp/ui/routers/__init__.py +10 -0
  86. solidworks_mcp/ui/routers/checkpoint.py +24 -0
  87. solidworks_mcp/ui/routers/docs.py +47 -0
  88. solidworks_mcp/ui/routers/llm.py +83 -0
  89. solidworks_mcp/ui/routers/local_model.py +69 -0
  90. solidworks_mcp/ui/routers/model.py +75 -0
  91. solidworks_mcp/ui/routers/preview.py +38 -0
  92. solidworks_mcp/ui/routers/session.py +161 -0
  93. solidworks_mcp/ui/routers/viewer.py +154 -0
  94. solidworks_mcp/ui/schemas.py +502 -0
  95. solidworks_mcp/ui/server.py +298 -0
  96. solidworks_mcp/ui/service.py +481 -0
  97. solidworks_mcp/ui/services/__init__.py +136 -0
  98. solidworks_mcp/ui/services/_utils.py +958 -0
  99. solidworks_mcp/ui/services/checkpoint_service.py +1110 -0
  100. solidworks_mcp/ui/services/docs_service.py +282 -0
  101. solidworks_mcp/ui/services/llm_service.py +956 -0
  102. solidworks_mcp/ui/services/model_service.py +459 -0
  103. solidworks_mcp/ui/services/parameter_repair_service.py +314 -0
  104. solidworks_mcp/ui/services/preview_service.py +489 -0
  105. solidworks_mcp/ui/services/session_service.py +1389 -0
  106. solidworks_mcp/utils/__init__.py +9 -0
  107. solidworks_mcp/utils/feature_tree_classifier.py +342 -0
  108. solidworks_mcp/utils/logging.py +76 -0
  109. solidworks_mcp/utils/validation.py +77 -0
  110. solidworks_mcp/version.py +8 -0
  111. solidworks_mcp_python-1.5.0.dist-info/METADATA +410 -0
  112. solidworks_mcp_python-1.5.0.dist-info/RECORD +115 -0
  113. solidworks_mcp_python-1.5.0.dist-info/WHEEL +4 -0
  114. solidworks_mcp_python-1.5.0.dist-info/entry_points.txt +3 -0
  115. solidworks_mcp_python-1.5.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,1145 @@
1
+ """VBA Code Generation tools for SolidWorks MCP Server.
2
+
3
+ Provides tools for generating VBA macros for complex SolidWorks operations, especially
4
+ useful for operations with 13+ parameters that exceed COM limits.
5
+ """
6
+
7
+ from typing import Any
8
+
9
+ from fastmcp import FastMCP
10
+ from pydantic import Field
11
+
12
+ from ..adapters.base import SolidWorksAdapter
13
+ from .input_compat import CompatInput
14
+ from .tool_boundary import (
15
+ InvalidInputError,
16
+ require_success,
17
+ with_tool_boundary,
18
+ )
19
+
20
+ # Input schemas for VBA generation
21
+
22
+
23
+ class VBAExtrusionInput(CompatInput):
24
+ """Input schema for generating VBA extrusion code.
25
+
26
+ Attributes:
27
+ advanced_options (dict[str, Any] | None): The advanced options value.
28
+ assembly_feature_scope (str | None): The assembly feature scope value.
29
+ auto_select (bool): The auto select value.
30
+ both_directions (bool): The both directions value.
31
+ cap_ends (bool): The cap ends value.
32
+ cap_thickness (float): The cap thickness value.
33
+ custom_properties (dict[str, Any] | None): The custom properties value.
34
+ depth (float): The depth value.
35
+ depth2 (float): The depth2 value.
36
+ direction (str | None): The direction value.
37
+ draft_angle (float): The draft angle value.
38
+ draft_outward (bool): The draft outward value.
39
+ end_condition (str | None): The end condition value.
40
+ end_condition_reference (str | None): The end condition reference value.
41
+ feature_scope (str | bool): The feature scope value.
42
+ merge_result (bool): The merge result value.
43
+ offset_parameters (dict[str, Any] | None): The offset parameters value.
44
+ sketch_name (str | None): The sketch name value.
45
+ start_condition (str | None): The start condition value.
46
+ thin_feature (bool): The thin feature value.
47
+ thin_thickness (float): The thin thickness value.
48
+ thin_thickness1 (float | None): The thin thickness1 value.
49
+ thin_thickness2 (float | None): The thin thickness2 value.
50
+ thin_type (str): The thin type value.
51
+ """
52
+
53
+ sketch_name: str | None = Field(default=None, description="Sketch name")
54
+ depth: float = Field(description="Extrusion depth in mm")
55
+ direction: str | None = Field(default=None, description="Direction")
56
+ both_directions: bool = Field(
57
+ default=False, description="Extrude in both directions"
58
+ )
59
+ depth2: float = Field(
60
+ default=0.0, description="Second direction depth if both_directions=True"
61
+ )
62
+ draft_angle: float = Field(default=0.0, description="Draft angle in degrees")
63
+ draft_outward: bool = Field(default=True, description="Draft direction")
64
+ thin_feature: bool = Field(default=False, description="Create thin feature")
65
+ thin_thickness: float = Field(
66
+ default=1.0, description="Thin feature thickness in mm"
67
+ )
68
+ thin_thickness1: float | None = Field(default=None, description="Alias thickness 1")
69
+ thin_thickness2: float | None = Field(default=None, description="Alias thickness 2")
70
+ thin_type: str = Field(default="OneDirection", description="Thin feature type")
71
+ cap_ends: bool = Field(default=False, description="Cap thin feature ends")
72
+ cap_thickness: float = Field(default=1.0, description="Cap thickness in mm")
73
+ merge_result: bool = Field(default=True, description="Merge with existing geometry")
74
+ feature_scope: str | bool = Field(default=False, description="Use feature scope")
75
+ auto_select: bool = Field(default=True, description="Auto select components")
76
+ assembly_feature_scope: str | None = Field(
77
+ default=None, description="Assembly feature scope"
78
+ )
79
+ start_condition: str | None = Field(default=None, description="Start condition")
80
+ end_condition: str | None = Field(default=None, description="End condition")
81
+ end_condition_reference: str | None = Field(
82
+ default=None, description="End condition reference"
83
+ )
84
+ offset_parameters: dict[str, Any] | None = Field(
85
+ default=None, description="Offset parameters"
86
+ )
87
+ custom_properties: dict[str, Any] | None = Field(
88
+ default=None, description="Custom properties"
89
+ )
90
+ advanced_options: dict[str, Any] | None = Field(
91
+ default=None, description="Advanced options"
92
+ )
93
+
94
+
95
+ class VBARevolveInput(CompatInput):
96
+ """Input schema for generating VBA revolve code.
97
+
98
+ Attributes:
99
+ angle (float | None): The angle value.
100
+ angle2 (float): The angle2 value.
101
+ angle_degrees (float | None): The angle degrees value.
102
+ axis_reference (str | None): The axis reference value.
103
+ both_directions (bool): The both directions value.
104
+ merge_result (bool): The merge result value.
105
+ sketch_name (str | None): The sketch name value.
106
+ thin_feature (bool): The thin feature value.
107
+ thin_thickness (float): The thin thickness value.
108
+ """
109
+
110
+ angle: float | None = Field(default=None, description="Revolve angle in degrees")
111
+ angle_degrees: float | None = Field(default=None, description="Angle alias")
112
+ sketch_name: str | None = Field(default=None, description="Sketch name")
113
+ axis_reference: str | None = Field(default=None, description="Axis reference")
114
+ both_directions: bool = Field(
115
+ default=False, description="Revolve in both directions"
116
+ )
117
+ angle2: float = Field(default=0.0, description="Second direction angle")
118
+ thin_feature: bool = Field(default=False, description="Create thin feature")
119
+ thin_thickness: float = Field(
120
+ default=1.0, description="Thin feature thickness in mm"
121
+ )
122
+ merge_result: bool = Field(default=True, description="Merge with existing geometry")
123
+
124
+ def model_post_init(self, __context: Any) -> None:
125
+ """Provide model post init support for the vbarevolve input.
126
+
127
+ Args:
128
+ __context (Any): The context value.
129
+
130
+ Returns:
131
+ None: None.
132
+ """
133
+ if self.angle is None:
134
+ self.angle = self.angle_degrees if self.angle_degrees is not None else 360.0
135
+
136
+
137
+ class VBAAssemblyInput(CompatInput):
138
+ """Input schema for generating VBA assembly operations.
139
+
140
+ Attributes:
141
+ assembly_file (str | None): The assembly file value.
142
+ component_file (str | None): The component file value.
143
+ component_path (str | None): The component path value.
144
+ insertion_point (list[float]): The insertion point value.
145
+ operation_type (str | None): The operation type value.
146
+ rotation (list[float]): The rotation value.
147
+ """
148
+
149
+ operation_type: str | None = Field(
150
+ default=None, description="Assembly operation (insert, mate, pattern, etc.)"
151
+ )
152
+ component_path: str | None = Field(
153
+ default=None, description="Path to component file"
154
+ )
155
+ assembly_file: str | None = Field(default=None, description="Assembly file")
156
+ component_file: str | None = Field(default=None, description="Component file alias")
157
+ insertion_point: list[float] = Field(
158
+ default=[0, 0, 0], description="Insertion coordinates [x,y,z]"
159
+ )
160
+ rotation: list[float] = Field(
161
+ default=[0, 0, 0], description="Rotation angles [rx,ry,rz]"
162
+ )
163
+
164
+
165
+ class VBADrawingInput(CompatInput):
166
+ """Input schema for generating VBA drawing operations.
167
+
168
+ Attributes:
169
+ advanced_options (dict[str, Any] | None): The advanced options value.
170
+ drawing_file (str | None): The drawing file value.
171
+ model_path (str | None): The model path value.
172
+ operation_type (str | None): The operation type value.
173
+ scale (float): The scale value.
174
+ sheet_format (str): The sheet format value.
175
+ view_layout (str | None): The view layout value.
176
+ view_scale (str | None): The view scale value.
177
+ """
178
+
179
+ operation_type: str | None = Field(
180
+ default=None,
181
+ description="Drawing operation (view, dimension, annotation, etc.)",
182
+ )
183
+ model_path: str | None = Field(default=None, description="Path to 3D model")
184
+ drawing_file: str | None = Field(default=None, description="Drawing file path")
185
+ view_layout: str | None = Field(default=None, description="View layout")
186
+ view_scale: str | None = Field(default=None, description="View scale")
187
+ advanced_options: dict[str, Any] | None = Field(
188
+ default=None, description="Advanced options"
189
+ )
190
+ sheet_format: str = Field(
191
+ default="A3", description="Sheet format (A4, A3, B, C, etc.)"
192
+ )
193
+ scale: float = Field(default=1.0, description="Drawing scale")
194
+
195
+
196
+ class VBABatchInput(CompatInput):
197
+ """Input schema for generating VBA batch operations.
198
+
199
+ Attributes:
200
+ exclude_list (list[str] | None): The exclude list value.
201
+ export_format (str | None): The export format value.
202
+ file_pattern (str | None): The file pattern value.
203
+ operation_type (str | None): The operation type value.
204
+ recursive (bool): The recursive value.
205
+ source_directory (str | None): The source directory value.
206
+ source_folder (str | None): The source folder value.
207
+ target_folder (str | None): The target folder value.
208
+ """
209
+
210
+ operation_type: str | None = Field(
211
+ default=None, description="Batch operation type (export, properties, etc.)"
212
+ )
213
+ file_pattern: str | None = Field(
214
+ default=None, description="File pattern to process (e.g., '*.sldprt')"
215
+ )
216
+ source_folder: str | None = Field(default=None, description="Source folder path")
217
+ target_folder: str | None = Field(default=None, description="Target folder path")
218
+ source_directory: str | None = Field(
219
+ default=None, description="Source directory alias"
220
+ )
221
+ export_format: str | None = Field(default=None, description="Export format alias")
222
+ exclude_list: list[str] | None = Field(default=None, description="Exclude list")
223
+ recursive: bool = Field(default=True, description="Process subfolders")
224
+
225
+
226
+ async def register_vba_generation_tools(
227
+ mcp: FastMCP, adapter: SolidWorksAdapter, config: Any
228
+ ) -> int:
229
+ """Register VBA generation tools with FastMCP.
230
+
231
+ Args:
232
+ mcp (FastMCP): The mcp value.
233
+ adapter (SolidWorksAdapter): Adapter instance used for the operation.
234
+ config (Any): Configuration values for the operation.
235
+
236
+ Returns:
237
+ int: The computed numeric result.
238
+
239
+ Example:
240
+ >>> tool_count = await register_vba_generation_tools(mcp, adapter, config)
241
+ """
242
+ mcp = with_tool_boundary(mcp)
243
+ tool_count = 0
244
+
245
+ @mcp.tool()
246
+ async def generate_vba_extrusion(input_data: VBAExtrusionInput) -> dict[str, Any]:
247
+ """Generate VBA code for complex extrusion operations.
248
+
249
+ Args:
250
+ input_data (VBAExtrusionInput): The input data value.
251
+
252
+ Returns:
253
+ dict[str, Any]: A dictionary containing the resulting values.
254
+
255
+ Example:
256
+ >>> result = await generate_vba_extrusion(extrusion_input)
257
+ """
258
+ if hasattr(adapter, "generate_vba_extrusion"):
259
+ result = await adapter.generate_vba_extrusion(input_data.model_dump())
260
+ require_success(result, "Failed to generate VBA code")
261
+ return {
262
+ "status": "success",
263
+ "message": "Generated VBA code for advanced extrusion",
264
+ "data": result.data,
265
+ "execution_time": result.execution_time,
266
+ }
267
+
268
+ vba_code = f"""Sub CreateAdvancedExtrusion()
269
+ Dim swApp As SldWorks.SldWorks
270
+ Dim swModel As SldWorks.ModelDoc2
271
+ Dim swFeatMgr As SldWorks.FeatureManager
272
+ Dim swFeat As SldWorks.Feature
273
+ Dim myFeature As Object
274
+
275
+ Set swApp = Application.SldWorks
276
+ Set swModel = swApp.ActiveDoc
277
+
278
+ If swModel Is Nothing Then
279
+ MsgBox "No active document"
280
+ Exit Sub
281
+ End If
282
+
283
+ Set swFeatMgr = swModel.FeatureManager
284
+
285
+ ' Advanced extrusion with full parameter control
286
+ myFeature = swFeatMgr.FeatureExtruThin2( _
287
+ {input_data.depth / 1000.0}, _ ' Depth (meters)
288
+ {input_data.depth2 / 1000.0}, _ ' Depth2 (meters)
289
+ {str(input_data.both_directions).lower()}, _ ' BothDirections
290
+ {input_data.draft_angle * 3.14159 / 180.0}, _ ' DraftAngle (radians)
291
+ {0}, _ ' DraftAngle2
292
+ {str(input_data.draft_outward).lower()}, _ ' DraftOutward
293
+ {str(input_data.draft_outward).lower()}, _ ' DraftOutward2
294
+ {str(input_data.merge_result).lower()}, _ ' MergeResult
295
+ {str(input_data.feature_scope).lower()}, _ ' FeatureScope
296
+ {str(input_data.auto_select).lower()}, _ ' AutoSelect
297
+ {input_data.thin_thickness / 1000.0}, _ ' Thickness (meters)
298
+ {input_data.thin_thickness / 1000.0}, _ ' Thickness2
299
+ False, _ ' ReverseOffset
300
+ {str(input_data.both_directions).lower()}, _ ' BothDirectionThin
301
+ {str(input_data.cap_ends).lower()}, _ ' CapEnds
302
+ 0, _ ' EndCondition
303
+ 0 _ ' EndCondition2
304
+ )
305
+
306
+ If myFeature Is Nothing Then
307
+ MsgBox "Failed to create extrusion"
308
+ Else
309
+ MsgBox "Advanced extrusion created successfully"
310
+ End If
311
+
312
+ End Sub"""
313
+
314
+ return {
315
+ "status": "success",
316
+ "message": "Generated VBA code for advanced extrusion",
317
+ "vba_code": vba_code,
318
+ "parameters": {
319
+ "depth": input_data.depth,
320
+ "both_directions": input_data.both_directions,
321
+ "thin_feature": input_data.thin_feature,
322
+ "parameter_count": 17,
323
+ "complexity": "complex",
324
+ },
325
+ "usage_instructions": [
326
+ "1. Open SolidWorks VBA editor (Tools > Macro > Edit)",
327
+ "2. Create new module and paste the generated code",
328
+ "3. Ensure you have an active sketch selected",
329
+ "4. Run the macro (F5)",
330
+ ],
331
+ }
332
+
333
+ @mcp.tool()
334
+ async def generate_vba_revolve(input_data: VBARevolveInput) -> dict[str, Any]:
335
+ """Generate VBA code for complex revolve operations.
336
+
337
+ Args:
338
+ input_data (VBARevolveInput): The input data value.
339
+
340
+ Returns:
341
+ dict[str, Any]: A dictionary containing the resulting values.
342
+
343
+ Example:
344
+ >>> result = await generate_vba_revolve(revolve_input)
345
+ """
346
+ """
347
+ Generate VBA code for complex revolve operations.
348
+
349
+ Creates VBA macro for revolve features with advanced thin-wall options.
350
+ """
351
+ if hasattr(adapter, "generate_vba_revolve"):
352
+ result = await adapter.generate_vba_revolve(input_data.model_dump())
353
+ require_success(result, "Failed to generate VBA code")
354
+ return {
355
+ "status": "success",
356
+ "message": "Generated VBA code for advanced revolve",
357
+ "data": result.data,
358
+ "execution_time": result.execution_time,
359
+ }
360
+
361
+ vba_code = f"""Sub CreateAdvancedRevolve()
362
+ Dim swApp As SldWorks.SldWorks
363
+ Dim swModel As SldWorks.ModelDoc2
364
+ Dim swFeatMgr As SldWorks.FeatureManager
365
+ Dim myFeature As Object
366
+
367
+ Set swApp = Application.SldWorks
368
+ Set swModel = swApp.ActiveDoc
369
+ Set swFeatMgr = swModel.FeatureManager
370
+
371
+ ' Advanced revolve with thin-wall options
372
+ myFeature = swFeatMgr.FeatureRevolve2( _
373
+ True, _ ' SingleDir
374
+ {str(input_data.both_directions).lower()}, _ ' IsSolid
375
+ False, _ ' IsThin
376
+ False, _ ' ReverseDir
377
+ 3, _ ' Type (swEndCondBlind)
378
+ 3, _ ' Type2
379
+ {(input_data.angle or 0.0) * 3.14159 / 180.0}, _ ' Angle (radians)
380
+ {(input_data.angle2 or 0.0) * 3.14159 / 180.0}, _ ' Angle2
381
+ {str(input_data.merge_result).lower()}, _ ' MergeResult
382
+ False, _ ' FeatureScope
383
+ False, _ ' Auto
384
+ True, _ ' AssemblyFeatureScope
385
+ 0, _ ' AutoSelectComponents
386
+ False, _ ' PropagateFeatureToParts
387
+ True, _ ' CreateSelectionSet
388
+ False, _ ' CurveToOrderUse
389
+ False _ ' UseMachinedSurface
390
+ )
391
+
392
+ If myFeature Is Nothing Then
393
+ MsgBox "Failed to create revolve"
394
+ Else
395
+ MsgBox "Advanced revolve created successfully"
396
+ End If
397
+
398
+ End Sub"""
399
+
400
+ return {
401
+ "status": "success",
402
+ "message": "Generated VBA code for advanced revolve",
403
+ "vba_code": vba_code,
404
+ "parameters": {
405
+ "angle": input_data.angle,
406
+ "both_directions": input_data.both_directions,
407
+ "thin_feature": input_data.thin_feature,
408
+ "parameter_count": 16,
409
+ "complexity": "complex",
410
+ },
411
+ "usage_instructions": [
412
+ "1. Create a sketch profile and axis of revolution",
413
+ "2. Select the sketch and axis",
414
+ "3. Run the generated VBA macro",
415
+ "4. Check the revolve feature in the feature tree",
416
+ ],
417
+ }
418
+
419
+ @mcp.tool()
420
+ async def generate_vba_assembly_insert(
421
+ input_data: VBAAssemblyInput,
422
+ ) -> dict[str, Any]:
423
+ """Generate VBA code for assembly component insertion.
424
+
425
+ Args:
426
+ input_data (VBAAssemblyInput): The input data value.
427
+
428
+ Returns:
429
+ dict[str, Any]: A dictionary containing the resulting values.
430
+
431
+ Example:
432
+ >>> result = await generate_vba_assembly_insert(assembly_input)
433
+
434
+ Generate VBA code for inserting components into assemblies.
435
+
436
+ Creates macro for component insertion with precise positioning.
437
+ """
438
+ if hasattr(adapter, "generate_vba_assembly_insert"):
439
+ result = await adapter.generate_vba_assembly_insert(input_data.model_dump())
440
+ require_success(result, "Failed to generate VBA code")
441
+ return {
442
+ "status": "success",
443
+ "message": "Generated VBA code for component insertion",
444
+ "data": result.data,
445
+ "execution_time": result.execution_time,
446
+ }
447
+
448
+ vba_code = f'''Sub InsertComponent()
449
+ Dim swApp As SldWorks.SldWorks
450
+ Dim swModel As SldWorks.ModelDoc2
451
+ Dim swAssy As SldWorks.AssemblyDoc
452
+ Dim swComp As SldWorks.Component2
453
+
454
+ Set swApp = Application.SldWorks
455
+ Set swModel = swApp.ActiveDoc
456
+ Set swAssy = swModel
457
+
458
+ ' Insert component at specified location
459
+ Set swComp = swAssy.AddComponent5( _
460
+ "{input_data.component_path}", _
461
+ 0, _ ' Configuration
462
+ "", _ ' Config name
463
+ False, _ ' LoadModel
464
+ "", _ ' ReferenceName
465
+ {input_data.insertion_point[0] / 1000.0}, _ ' X position (meters)
466
+ {input_data.insertion_point[1] / 1000.0}, _ ' Y position (meters)
467
+ {input_data.insertion_point[2] / 1000.0} _ ' Z position (meters)
468
+ )
469
+
470
+ If swComp Is Nothing Then
471
+ MsgBox "Failed to insert component"
472
+ Else
473
+ MsgBox "Component inserted successfully: " & swComp.Name2
474
+ End If
475
+
476
+ End Sub'''
477
+
478
+ return {
479
+ "status": "success",
480
+ "message": "Generated VBA code for component insertion",
481
+ "vba_code": vba_code,
482
+ "parameters": {
483
+ "component_path": input_data.component_path,
484
+ "insertion_point": input_data.insertion_point,
485
+ "operation_type": input_data.operation_type,
486
+ },
487
+ "usage_instructions": [
488
+ "1. Open the target assembly document",
489
+ "2. Ensure the component file path exists",
490
+ "3. Run the macro to insert the component",
491
+ "4. Add mates as needed for positioning",
492
+ ],
493
+ }
494
+
495
+ @mcp.tool()
496
+ async def generate_vba_drawing_views(input_data: VBADrawingInput) -> dict[str, Any]:
497
+ """Generate VBA code for drawing view creation.
498
+
499
+ Args:
500
+ input_data (VBADrawingInput): The input data value.
501
+
502
+ Returns:
503
+ dict[str, Any]: A dictionary containing the resulting values.
504
+
505
+ Example:
506
+ >>> result = await generate_vba_drawing_views(drawing_input)
507
+ """
508
+ """
509
+ Generate VBA code for creating drawing views.
510
+
511
+ Creates macro for standard drawing view setup.
512
+ """
513
+ if hasattr(adapter, "generate_vba_drawing_views"):
514
+ result = await adapter.generate_vba_drawing_views(input_data.model_dump())
515
+ require_success(result, "Failed to generate VBA code")
516
+ return {
517
+ "status": "success",
518
+ "message": "Generated VBA code for drawing views",
519
+ "data": result.data,
520
+ "execution_time": result.execution_time,
521
+ }
522
+
523
+ vba_code = f'''Sub CreateDrawingViews()
524
+ Dim swApp As SldWorks.SldWorks
525
+ Dim swModel As SldWorks.ModelDoc2
526
+ Dim swDraw As SldWorks.DrawingDoc
527
+ Dim swView As SldWorks.View
528
+ Dim swSheet As SldWorks.Sheet
529
+
530
+ Set swApp = Application.SldWorks
531
+ Set swModel = swApp.ActiveDoc
532
+ Set swDraw = swModel
533
+
534
+ If swDraw Is Nothing Then
535
+ MsgBox "No active drawing document"
536
+ Exit Sub
537
+ End If
538
+
539
+ Set swSheet = swDraw.GetCurrentSheet
540
+
541
+ ' Create standard 3 view drawing
542
+ ' Front view
543
+ Set swView = swDraw.CreateDrawViewFromModelView3( _
544
+ "{input_data.model_path}", _
545
+ "*Front", _
546
+ 0.1, _ ' X position
547
+ 0.15, _ ' Y position
548
+ 0 _ ' Z position
549
+ )
550
+
551
+ swView.ScaleRatio = Array({input_data.scale}, 1)
552
+
553
+ ' Top view
554
+ Set swView = swDraw.CreateDrawViewFromModelView3( _
555
+ "{input_data.model_path}", _
556
+ "*Top", _
557
+ 0.1, _
558
+ 0.25, _
559
+ 0 _
560
+ )
561
+
562
+ swView.ScaleRatio = Array({input_data.scale}, 1)
563
+
564
+ ' Right view
565
+ Set swView = swDraw.CreateDrawViewFromModelView3( _
566
+ "{input_data.model_path}", _
567
+ "*Right", _
568
+ 0.25, _
569
+ 0.15, _
570
+ 0 _
571
+ )
572
+
573
+ swView.ScaleRatio = Array({input_data.scale}, 1)
574
+
575
+ MsgBox "Drawing views created successfully"
576
+
577
+ End Sub'''
578
+
579
+ return {
580
+ "status": "success",
581
+ "message": "Generated VBA code for drawing views",
582
+ "vba_code": vba_code,
583
+ "parameters": {
584
+ "model_path": input_data.model_path,
585
+ "scale": input_data.scale,
586
+ "sheet_format": input_data.sheet_format,
587
+ },
588
+ "usage_instructions": [
589
+ "1. Create a new drawing document",
590
+ "2. Verify the 3D model path is correct",
591
+ "3. Run the macro to create standard views",
592
+ "4. Adjust view positions as needed",
593
+ ],
594
+ }
595
+
596
+ @mcp.tool()
597
+ async def generate_vba_batch_export(input_data: VBABatchInput) -> dict[str, Any]:
598
+ """Generate VBA code for batch file export operations.
599
+
600
+ Args:
601
+ input_data (VBABatchInput): The input data value.
602
+
603
+ Returns:
604
+ dict[str, Any]: A dictionary containing the resulting values.
605
+
606
+ Example:
607
+ >>> result = await generate_vba_batch_export(batch_input)
608
+ """
609
+ """
610
+ Generate VBA code for batch file operations.
611
+
612
+ Creates macro for processing multiple files automatically.
613
+ """
614
+ if hasattr(adapter, "generate_vba_batch_export"):
615
+ result = await adapter.generate_vba_batch_export(input_data.model_dump())
616
+ require_success(result, "Failed to generate VBA code")
617
+ return {
618
+ "status": "success",
619
+ "message": f"Generated VBA code for batch {input_data.operation_type}",
620
+ "data": result.data,
621
+ "execution_time": result.execution_time,
622
+ }
623
+
624
+ vba_code = f'''Sub BatchExport()
625
+ Dim swApp As SldWorks.SldWorks
626
+ Dim swModel As SldWorks.ModelDoc2
627
+ Dim fso As FileSystemObject
628
+ Dim folder As Folder
629
+ Dim file As file
630
+ Dim filePath As String
631
+ Dim exportPath As String
632
+ Dim processedCount As Integer
633
+
634
+ Set swApp = Application.SldWorks
635
+ Set fso = New FileSystemObject
636
+ Set folder = fso.GetFolder("{input_data.source_folder}")
637
+
638
+ processedCount = 0
639
+
640
+ ' Process all files matching pattern
641
+ For Each file In folder.Files
642
+ If LCase(file.Name) Like LCase("{input_data.file_pattern}") Then
643
+ filePath = file.Path
644
+
645
+ ' Open the file
646
+ Set swModel = swApp.OpenDoc6(filePath, 1, 1, "", 0, 0)
647
+
648
+ If Not swModel Is Nothing Then
649
+ ' Generate export path
650
+ exportPath = "{input_data.target_folder}" & "\\" & _
651
+ fso.GetBaseName(file.Name) & ".step"
652
+
653
+ ' Export as STEP
654
+ swModel.SaveAs2 exportPath, 0, True, False
655
+
656
+ ' Close the model
657
+ swApp.CloseDoc swModel.GetTitle
658
+
659
+ processedCount = processedCount + 1
660
+ End If
661
+ End If
662
+ Next file
663
+
664
+ MsgBox "Batch export completed. Processed " & processedCount & " files."
665
+
666
+ End Sub'''
667
+
668
+ return {
669
+ "status": "success",
670
+ "message": f"Generated VBA code for batch {input_data.operation_type}",
671
+ "vba_code": vba_code,
672
+ "parameters": {
673
+ "operation_type": input_data.operation_type,
674
+ "file_pattern": input_data.file_pattern,
675
+ "source_folder": input_data.source_folder,
676
+ "target_folder": input_data.target_folder,
677
+ "recursive": input_data.recursive,
678
+ },
679
+ "usage_instructions": [
680
+ "1. Verify source and target folder paths exist",
681
+ "2. Close any open documents to avoid conflicts",
682
+ "3. Run the macro - it will process all matching files",
683
+ "4. Check the target folder for exported files",
684
+ ],
685
+ }
686
+
687
+ @mcp.tool()
688
+ async def generate_vba_part_modeling(input_data: dict[str, Any]) -> dict[str, Any]:
689
+ """Generate VBA code for complex part modeling operations.
690
+
691
+ Args:
692
+ input_data (dict[str, Any]): The input data value.
693
+
694
+ Returns:
695
+ dict[str, Any]: A dictionary containing the resulting values.
696
+
697
+ Example:
698
+ >>> result = await generate_vba_part_modeling(part_input)
699
+ """
700
+ """
701
+ Generate VBA code for advanced part modeling operations.
702
+
703
+ Creates macro for complex part features like sweeps, lofts, shells.
704
+ """
705
+ operation = input_data.get("operation", "shell")
706
+ thickness = input_data.get("thickness", 2.0)
707
+
708
+ if operation == "shell":
709
+ vba_code = f"""Sub CreateShell()
710
+ Dim swApp As SldWorks.SldWorks
711
+ Dim swModel As SldWorks.ModelDoc2
712
+ Dim swFeatMgr As SldWorks.FeatureManager
713
+ Dim swFeat As SldWorks.Feature
714
+
715
+ Set swApp = Application.SldWorks
716
+ Set swModel = swApp.ActiveDoc
717
+ Set swFeatMgr = swModel.FeatureManager
718
+
719
+ ' Create shell feature
720
+ Set swFeat = swFeatMgr.FeatureShell2( _
721
+ {thickness / 1000.0}, _ ' Thickness (meters)
722
+ False, _ ' OutwardThickness
723
+ False, _ ' MultiThickness
724
+ False, _ ' ShowPreview
725
+ False, _ ' MultipleFaceDef
726
+ False _ ' MultipleThicknessDef
727
+ )
728
+
729
+ If swFeat Is Nothing Then
730
+ MsgBox "Failed to create shell"
731
+ Else
732
+ MsgBox "Shell created successfully with thickness: {thickness}mm"
733
+ End If
734
+
735
+ End Sub"""
736
+ elif operation == "fillet":
737
+ radius = input_data.get("radius", 5.0)
738
+ vba_code = f"""Sub CreateFillet()
739
+ Dim swApp As SldWorks.SldWorks
740
+ Dim swModel As SldWorks.ModelDoc2
741
+ Dim swFeatMgr As SldWorks.FeatureManager
742
+
743
+ Set swApp = Application.SldWorks
744
+ Set swModel = swApp.ActiveDoc
745
+ Set swFeatMgr = swModel.FeatureManager
746
+
747
+ ' Create fillet feature
748
+ swFeatMgr.FeatureFillet4( _
749
+ {radius / 1000.0}, _ ' Radius (meters)
750
+ 0, _ ' SecondRadius
751
+ 0, _ ' RollOnOff
752
+ 0, _ ' RollFirstRadius
753
+ 0, _ ' RollSecondRadius
754
+ 0, _ ' RollSmoothTransition
755
+ 0, _ ' ConicRho
756
+ 0, _ ' SetbackDistance
757
+ False, _ ' AssemblyFeatureScope
758
+ False, _ ' AutoSelectComponents
759
+ False, _ ' PropagateFeatureToParts
760
+ False, _ ' CreateSelectionSet
761
+ False, _ ' EnableSolidPreview
762
+ 0 _ ' CornerType
763
+ )
764
+
765
+ swModel.ClearSelection2 True
766
+ MsgBox "Fillet created with radius: {radius}mm"
767
+
768
+ End Sub"""
769
+ else:
770
+ raise InvalidInputError(f"Unsupported operation: {operation}")
771
+
772
+ return {
773
+ "status": "success",
774
+ "message": f"Generated VBA code for {operation} operation",
775
+ "vba_code": vba_code,
776
+ "parameters": input_data,
777
+ "usage_instructions": [
778
+ "1. Select the appropriate faces/edges",
779
+ "2. Run the generated VBA macro",
780
+ "3. Verify the feature was created correctly",
781
+ ],
782
+ }
783
+
784
+ @mcp.tool()
785
+ async def generate_vba_assembly_mates(input_data: dict[str, Any]) -> dict[str, Any]:
786
+ """Generate VBA code for assembly mate creation.
787
+
788
+ Args:
789
+ input_data (dict[str, Any]): The input data value.
790
+
791
+ Returns:
792
+ dict[str, Any]: A dictionary containing the resulting values.
793
+
794
+ Example:
795
+ >>> result = await generate_vba_assembly_mates(mate_input)
796
+ """
797
+ """
798
+ Generate VBA code for creating assembly mates.
799
+
800
+ Creates macro for various mate types (concentric, distance, parallel, etc).
801
+ """
802
+ mate_type = input_data.get("mate_type", "concentric")
803
+ component1 = input_data.get("component1", "Part1")
804
+ component2 = input_data.get("component2", "Part2")
805
+ distance = input_data.get("distance", 0.0)
806
+
807
+ mate_type_map = {
808
+ "concentric": "swMateType_CONCENTRIC",
809
+ "distance": "swMateType_DISTANCE",
810
+ "parallel": "swMateType_PARALLEL",
811
+ "perpendicular": "swMateType_PERPENDICULAR",
812
+ "coincident": "swMateType_COINCIDENT",
813
+ }
814
+
815
+ sw_mate_type = mate_type_map.get(mate_type, "swMateType_CONCENTRIC")
816
+
817
+ vba_code = f"""Sub CreateAssemblyMate()
818
+ Dim swApp As SldWorks.SldWorks
819
+ Dim swModel As SldWorks.ModelDoc2
820
+ Dim swAssy As SldWorks.AssemblyDoc
821
+ Dim swMateFeats As Variant
822
+ Dim swMate As SldWorks.Feature
823
+
824
+ Set swApp = Application.SldWorks
825
+ Set swModel = swApp.ActiveDoc
826
+ Set swAssy = swModel
827
+
828
+ ' Clear existing selections
829
+ swModel.ClearSelection2 True
830
+
831
+ ' Note: Entity selection needs to be done before running this macro
832
+ ' Select appropriate faces/edges on {component1} and {component2}
833
+
834
+ ' Create {mate_type} mate
835
+ swMateFeats = swAssy.AddMate5( _
836
+ {sw_mate_type}, _ ' Mate type
837
+ swMateAlign_ALIGNED, _ ' Alignment
838
+ False, _ ' Flip
839
+ {distance / 1000.0}, _ ' Distance (meters)
840
+ 0, _ ' Distance2
841
+ 0, _ ' Angle
842
+ 0, _ ' Angle2
843
+ False, _ ' LockRotation
844
+ 0, _ ' WidthMateOption
845
+ 0, _ ' For Positioning Only
846
+ 0 _ ' LockToSketch
847
+ )
848
+
849
+ If IsEmpty(swMateFeats) Then
850
+ MsgBox "Failed to create mate. Check entity selection."
851
+ Else
852
+ Set swMate = swMateFeats(0)
853
+ MsgBox "Mate created: " & swMate.Name
854
+ End If
855
+
856
+ End Sub"""
857
+
858
+ return {
859
+ "status": "success",
860
+ "message": f"Generated VBA code for {mate_type} mate",
861
+ "vba_code": vba_code,
862
+ "parameters": {
863
+ "mate_type": mate_type,
864
+ "component1": component1,
865
+ "component2": component2,
866
+ "distance": distance,
867
+ },
868
+ "usage_instructions": [
869
+ "1. Open the assembly document",
870
+ "2. Select the two faces/edges to mate",
871
+ "3. Run the generated macro",
872
+ "4. Verify the mate was created in the feature tree",
873
+ ],
874
+ }
875
+
876
+ @mcp.tool()
877
+ async def generate_vba_drawing_dimensions(
878
+ input_data: dict[str, Any],
879
+ ) -> dict[str, Any]:
880
+ """Generate VBA code for creating drawing dimensions.
881
+
882
+ Creates macro for various dimension types in drawings.
883
+
884
+ Args:
885
+ input_data (dict[str, Any]): The input data value.
886
+
887
+ Returns:
888
+ dict[str, Any]: A dictionary containing the resulting values.
889
+ """
890
+ dimension_type = input_data.get("dimension_type", "linear")
891
+ precision = input_data.get("precision", 2)
892
+
893
+ vba_code = f'''Sub CreateDrawingDimensions()
894
+ Dim swApp As SldWorks.SldWorks
895
+ Dim swModel As SldWorks.ModelDoc2
896
+ Dim swDraw As SldWorks.DrawingDoc
897
+ Dim swView As SldWorks.View
898
+ Dim swDisp As SldWorks.DisplayDimension
899
+ Dim swDim As SldWorks.Dimension
900
+
901
+ Set swApp = Application.SldWorks
902
+ Set swModel = swApp.ActiveDoc
903
+ Set swDraw = swModel
904
+
905
+ ' Get active drawing view
906
+ Set swView = swDraw.GetFirstView ' Sheet
907
+ Set swView = swView.GetNextView ' First drawing view
908
+
909
+ If swView Is Nothing Then
910
+ MsgBox "No drawing view found"
911
+ Exit Sub
912
+ End If
913
+
914
+ swModel.ClearSelection2 True
915
+
916
+ ' Note: Select appropriate entities before running
917
+ ' For linear dimensions: select two edges or points
918
+ ' For radial: select arc or circle
919
+ ' For angular: select two lines
920
+
921
+ Select Case "{dimension_type}"
922
+ Case "linear"
923
+ Set swDisp = swModel.AddDimension2(0.05, 0.05, 0)
924
+ Case "radial"
925
+ Set swDisp = swModel.AddDimension2(0.05, 0.05, 0)
926
+ Case "angular"
927
+ Set swDisp = swModel.AddDimension2(0.05, 0.05, 0)
928
+ Case "diameter"
929
+ Set swDisp = swModel.AddDimension2(0.05, 0.05, 0)
930
+ End Select
931
+
932
+ If Not swDisp Is Nothing Then
933
+ Set swDim = swDisp.GetDimension2(0)
934
+ ' Set precision
935
+ swDim.SetPrecision2 swLinear, {precision}
936
+ MsgBox "Dimension created with {precision} decimal places"
937
+ Else
938
+ MsgBox "Failed to create dimension. Check entity selection."
939
+ End If
940
+
941
+ End Sub'''
942
+
943
+ return {
944
+ "status": "success",
945
+ "message": f"Generated VBA code for {dimension_type} dimension",
946
+ "vba_code": vba_code,
947
+ "parameters": {
948
+ "dimension_type": dimension_type,
949
+ "precision": precision,
950
+ },
951
+ "usage_instructions": [
952
+ "1. Open a drawing with views",
953
+ "2. Select two edges, points, or appropriate entities",
954
+ "3. Run the macro to create dimension",
955
+ "4. Adjust dimension position as needed",
956
+ ],
957
+ }
958
+
959
+ @mcp.tool()
960
+ async def generate_vba_file_operations(
961
+ input_data: dict[str, Any],
962
+ ) -> dict[str, Any]:
963
+ """Generate VBA code for file management operations.
964
+
965
+ Args:
966
+ input_data (dict[str, Any]): The input data value.
967
+
968
+ Returns:
969
+ dict[str, Any]: A dictionary containing the resulting values.
970
+
971
+ Example:
972
+ >>> result = await generate_vba_file_operations(file_input)
973
+
974
+ Creates macro for custom properties, PDM operations, etc.
975
+ """
976
+ operation = input_data.get("operation", "custom_properties")
977
+
978
+ if operation == "custom_properties":
979
+ property_name = input_data.get("property_name", "Material")
980
+ property_value = input_data.get("property_value", "Steel")
981
+
982
+ vba_code = f'''Sub SetCustomProperties()
983
+ Dim swApp As SldWorks.SldWorks
984
+ Dim swModel As SldWorks.ModelDoc2
985
+ Dim swCustPropMgr As SldWorks.CustomPropertyManager
986
+ Dim configNames As Variant
987
+ Dim i As Integer
988
+
989
+ Set swApp = Application.SldWorks
990
+ Set swModel = swApp.ActiveDoc
991
+
992
+ ' Get configuration names
993
+ configNames = swModel.GetConfigurationNames
994
+
995
+ ' Set property for all configurations
996
+ For i = 0 To UBound(configNames)
997
+ Set swCustPropMgr = swModel.Extension.CustomPropertyManager(configNames(i))
998
+
999
+ swCustPropMgr.Add3 "{property_name}", swCustomInfoText, _
1000
+ "{property_value}", swCustomPropertyAddOption_ReplaceValue
1001
+ Next i
1002
+
1003
+ ' Also set at file level
1004
+ Set swCustPropMgr = swModel.Extension.CustomPropertyManager("")
1005
+ swCustPropMgr.Add3 "{property_name}", swCustomInfoText, _
1006
+ "{property_value}", swCustomPropertyAddOption_ReplaceValue
1007
+
1008
+ MsgBox "Custom property '{property_name}' set to '{property_value}'"
1009
+
1010
+ End Sub'''
1011
+
1012
+ elif operation == "pack_and_go":
1013
+ target_folder = input_data.get("target_folder", "C:\\PackAndGo")
1014
+
1015
+ vba_code = f'''Sub PackAndGo()
1016
+ Dim swApp As SldWorks.SldWorks
1017
+ Dim swModel As SldWorks.ModelDoc2
1018
+ Dim swPackAndGo As SldWorks.PackAndGo
1019
+ Dim pgStatus As Long
1020
+ Dim pgWarnings As Long
1021
+
1022
+ Set swApp = Application.SldWorks
1023
+ Set swModel = swApp.ActiveDoc
1024
+
1025
+ Set swPackAndGo = swApp.GetPackAndGo
1026
+
1027
+ ' Set Pack and Go settings
1028
+ swPackAndGo.IncludeDrawings = True
1029
+ swPackAndGo.IncludeSimulationResults = False
1030
+ swPackAndGo.IncludeToolboxComponents = False
1031
+ swPackAndGo.FlattenToSingleFolder = True
1032
+
1033
+ ' Set destination folder
1034
+ swPackAndGo.SetSaveToName swModel.GetTitle, "{target_folder}"
1035
+
1036
+ ' Execute Pack and Go
1037
+ swPackAndGo.PackAndGo2 pgStatus, pgWarnings
1038
+
1039
+ If pgStatus = 0 Then
1040
+ MsgBox "Pack and Go completed successfully"
1041
+ Else
1042
+ MsgBox "Pack and Go failed with status: " & pgStatus
1043
+ End If
1044
+
1045
+ End Sub'''
1046
+ else:
1047
+ raise InvalidInputError(f"Unsupported operation: {operation}")
1048
+
1049
+ return {
1050
+ "status": "success",
1051
+ "message": f"Generated VBA code for {operation}",
1052
+ "vba_code": vba_code,
1053
+ "parameters": input_data,
1054
+ "usage_instructions": [
1055
+ "1. Open the target document",
1056
+ "2. Run the generated macro",
1057
+ "3. Check results in properties or file system",
1058
+ ],
1059
+ }
1060
+
1061
+ @mcp.tool()
1062
+ async def generate_vba_macro_recorder(input_data: dict[str, Any]) -> dict[str, Any]:
1063
+ """Generate VBA code using macro recording patterns.
1064
+
1065
+ Args:
1066
+ input_data (dict[str, Any]): The input data value.
1067
+
1068
+ Returns:
1069
+ dict[str, Any]: A dictionary containing the resulting values.
1070
+
1071
+ Example:
1072
+ >>> result = await generate_vba_macro_recorder(recorder_input)
1073
+ """
1074
+ operation = input_data.get("operation", "start_recording")
1075
+
1076
+ if operation == "start_recording":
1077
+ vba_code = """Sub StartMacroRecording()
1078
+ Dim swApp As SldWorks.SldWorks
1079
+ Set swApp = Application.SldWorks
1080
+
1081
+ ' Enable macro recording
1082
+ swApp.UnloadAddIn "SldWorks.Addin.Utilities.MacroRecorder"
1083
+ swApp.LoadAddIn "SldWorks.Addin.Utilities.MacroRecorder"
1084
+
1085
+ ' Note: Use Tools > Macro > Record in SolidWorks interface
1086
+ ' This code prepares the environment for recording
1087
+
1088
+ MsgBox "Macro recording environment prepared. Use Tools > Macro > Record to start."
1089
+
1090
+ End Sub"""
1091
+
1092
+ elif operation == "stop_recording":
1093
+ vba_code = """Sub StopMacroRecording()
1094
+ Dim swApp As SldWorks.SldWorks
1095
+ Set swApp = Application.SldWorks
1096
+
1097
+ ' Note: Use Tools > Macro > Stop Record in SolidWorks interface
1098
+ ' This code helps manage the recording session
1099
+
1100
+ MsgBox "Stop recording using Tools > Macro > Stop Record"
1101
+
1102
+ End Sub"""
1103
+
1104
+ elif operation == "create_template":
1105
+ macro_name = input_data.get("macro_name", "CustomMacro")
1106
+ vba_code = f"""Sub {macro_name}Template()
1107
+ Dim swApp As SldWorks.SldWorks
1108
+ Dim swModel As SldWorks.ModelDoc2
1109
+ ' Add more variables as needed
1110
+
1111
+ Set swApp = Application.SldWorks
1112
+ Set swModel = swApp.ActiveDoc
1113
+
1114
+ ' TODO: Add your custom automation code here
1115
+ ' This template provides the basic SolidWorks API structure
1116
+
1117
+ ' Error handling
1118
+ If swModel Is Nothing Then
1119
+ MsgBox "No active document"
1120
+ Exit Sub
1121
+ End If
1122
+
1123
+ ' Your automation logic goes here...
1124
+
1125
+ MsgBox "Custom macro template ready for customization"
1126
+
1127
+ End Sub"""
1128
+ else:
1129
+ raise InvalidInputError(f"Unsupported operation: {operation}")
1130
+
1131
+ return {
1132
+ "status": "success",
1133
+ "message": f"Generated VBA code for macro {operation}",
1134
+ "vba_code": vba_code,
1135
+ "parameters": input_data,
1136
+ "usage_instructions": [
1137
+ "1. Open SolidWorks VBA editor (Alt+F11)",
1138
+ "2. Create new module and paste code",
1139
+ "3. Customize as needed for your workflow",
1140
+ ],
1141
+ }
1142
+
1143
+ # Core VBA generation tools
1144
+ tool_count = 10
1145
+ return tool_count