@atlisp/mcp 1.8.18 → 1.8.19

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.
@@ -13,19 +13,30 @@ const BUSY_DELAY = parseInt(process.env.BUSY_DELAY || '500', 10);
13
13
  const LISP_CACHE = new Map();
14
14
  const LISP_CACHE_MAX = parseInt(process.env.LISP_CACHE_MAX || '500', 10);
15
15
 
16
+ const CACHE_TTL = parseInt(process.env.LISP_CACHE_TTL || '300000', 10);
17
+
16
18
  function getCachedLisp(code) {
17
19
  const hash = crypto.createHash('sha256').update(code).digest('hex');
18
- if (LISP_CACHE.has(hash)) return LISP_CACHE.get(hash);
19
- return null;
20
+ const entry = LISP_CACHE.get(hash);
21
+ if (!entry) return null;
22
+ if (Date.now() - entry.ts > CACHE_TTL) {
23
+ LISP_CACHE.delete(hash);
24
+ return null;
25
+ }
26
+ entry.ts = Date.now();
27
+ return entry.compiled;
20
28
  }
21
29
 
22
30
  function setCachedLisp(code, compiled) {
23
31
  const hash = crypto.createHash('sha256').update(code).digest('hex');
24
32
  if (LISP_CACHE.size >= LISP_CACHE_MAX) {
25
- const firstKey = LISP_CACHE.keys().next().value;
26
- LISP_CACHE.delete(firstKey);
33
+ let oldest = null;
34
+ for (const [k, v] of LISP_CACHE) {
35
+ if (!oldest || v.ts < oldest.ts) oldest = { k, ts: v.ts };
36
+ }
37
+ if (oldest) LISP_CACHE.delete(oldest.k);
27
38
  }
28
- LISP_CACHE.set(hash, compiled);
39
+ LISP_CACHE.set(hash, { compiled, ts: Date.now() });
29
40
  return compiled;
30
41
  }
31
42
 
@@ -151,16 +162,34 @@ const cadSendWithResult = edge.func(function() {/*
151
162
  string code = d.code.ToString();
152
163
  string platform = d.platform.ToString();
153
164
  string encoding = d.encoding != null ? d.encoding.ToString() : "";
165
+ string codeHash = d.codeHash != null ? d.codeHash.ToString() : "";
166
+ bool cacheEnabled = d.cacheEnabled != null && d.cacheEnabled.ToString() == "True";
167
+ bool hasCacheKey = cacheEnabled && !string.IsNullOrEmpty(codeHash);
154
168
  string progId = platform == "BricsCAD" ? "BricscadApp.AcadApplication" : platform + ".Application";
155
169
  string tempDir = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "@lisp", "tmp");
156
170
  System.IO.Directory.CreateDirectory(tempDir);
157
171
 
172
+ // 结果文件始终使用 GUID 命名(每次调用唯一)
158
173
  tempFile = System.IO.Path.Combine(tempDir, "atlisp_result_" + System.Guid.NewGuid().ToString("N") + ".txt");
159
- lispFile = System.IO.Path.Combine(tempDir, "atlisp_code_" + System.Guid.NewGuid().ToString("N") + ".lsp");
160
- userCodeFile = System.IO.Path.Combine(tempDir, "atlisp_user_" + System.Guid.NewGuid().ToString("N") + ".lsp");
161
174
 
162
- // 用户代码单独写入文件,避免拼接注入风险
163
- System.IO.File.WriteAllText(userCodeFile, code, System.Text.Encoding.GetEncoding(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ANSICodePage));
175
+ // 代码文件:启用缓存时使用 hash 命名,否则使用 GUID 命名
176
+ string fileKey = hasCacheKey ? codeHash : System.Guid.NewGuid().ToString("N");
177
+ userCodeFile = System.IO.Path.Combine(tempDir, "atlisp_user_" + fileKey + ".lsp");
178
+ lispFile = System.IO.Path.Combine(tempDir, "atlisp_code_" + fileKey + ".lsp");
179
+
180
+ bool useCachedUserCode = false;
181
+ if (hasCacheKey) {
182
+ if (System.IO.File.Exists(userCodeFile)) {
183
+ var userFileInfo = new System.IO.FileInfo(userCodeFile);
184
+ if ((DateTime.Now - userFileInfo.LastWriteTime).TotalHours < 1) {
185
+ useCachedUserCode = true;
186
+ }
187
+ }
188
+ }
189
+
190
+ if (!useCachedUserCode) {
191
+ System.IO.File.WriteAllText(userCodeFile, code, System.Text.Encoding.GetEncoding(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ANSICodePage));
192
+ }
164
193
 
165
194
  string lispCode = "(progn"
166
195
  + "(setq f(open \"" + tempFile.Replace("\\", "\\\\") + "\" \"w\"))"
@@ -171,7 +200,6 @@ string encoding = d.encoding != null ? d.encoding.ToString() : "";
171
200
  + "(close f)"
172
201
  + "(princ))";
173
202
 
174
- // 使用系统 ANSI 编码以兼容 GstarCAD / ZWCAD
175
203
  System.IO.File.WriteAllText(lispFile, lispCode, System.Text.Encoding.GetEncoding(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ANSICodePage));
176
204
 
177
205
  dynamic cad = System.Runtime.InteropServices.Marshal.GetActiveObject(progId);
@@ -193,11 +221,9 @@ string encoding = d.encoding != null ? d.encoding.ToString() : "";
193
221
  byte[] bytes = System.IO.File.ReadAllBytes(tempFile);
194
222
  System.Text.Encoding enc;
195
223
 
196
- // 优先使用指定的编码
197
224
  if (!string.IsNullOrEmpty(encoding)) {
198
225
  enc = System.Text.Encoding.GetEncoding(encoding);
199
226
  } else {
200
- // 自动检测编码:先尝试 UTF-8,如果失败则使用 GBK
201
227
  try {
202
228
  string utf8Result = System.Text.Encoding.UTF8.GetString(bytes);
203
229
  if (!utf8Result.Contains("\ufffd")) {
@@ -216,14 +242,13 @@ string encoding = d.encoding != null ? d.encoding.ToString() : "";
216
242
 
217
243
  result = enc.GetString(bytes).Trim();
218
244
 
219
- // 检查是否有错误前缀
220
245
  if (result.StartsWith("ERROR:")) {
221
246
  return new { success = false, error = result.Substring(6).Trim() };
222
247
  }
223
248
 
224
249
  try { System.IO.File.Delete(tempFile); } catch {}
225
250
  try { System.IO.File.Delete(lispFile); } catch {}
226
- try { System.IO.File.Delete(userCodeFile); } catch {}
251
+ if (!hasCacheKey) { try { if (System.IO.File.Exists(userCodeFile)) System.IO.File.Delete(userCodeFile); } catch {} }
227
252
  break;
228
253
  } catch (System.IO.IOException) {
229
254
  System.Threading.Thread.Sleep(200);
@@ -482,6 +507,13 @@ async function connectToPlatform(targetPlatform) {
482
507
  });
483
508
  }
484
509
 
510
+ function computeCodeHash(code, cacheEnabled) {
511
+ if (cacheEnabled) {
512
+ return crypto.createHash('sha256').update(code).digest('hex');
513
+ }
514
+ return '';
515
+ }
516
+
485
517
  async function handleMessage(msg) {
486
518
  if (msg.type === 'ping') {
487
519
  return { pong: true };
@@ -554,9 +586,11 @@ async function handleMessage(msg) {
554
586
  return { success: false, error: `安全限制: ${injectionCheck.error}` };
555
587
  }
556
588
  if (msg.code.length > 255) {
557
- log(`send (long code ${msg.code.length} chars, fallback to sendResult): ${msg.code.substring(0, 80)}...`);
589
+ const cacheEnabled = process.env.LONG_CODE_CACHE === '1';
590
+ const codeHash = computeCodeHash(msg.code, cacheEnabled);
591
+ log(`send (long code ${msg.code.length} chars, fallback to sendResult, cache=${cacheEnabled}): ${msg.code.substring(0, 80)}...`);
558
592
  const r = await new Promise((resolve, reject) => {
559
- cadSendWithResult({ code: msg.code, platform: msg.platform || 'AutoCAD', encoding: '' }, (e, r) => {
593
+ cadSendWithResult({ code: msg.code, platform: msg.platform || 'AutoCAD', encoding: '', codeHash, cacheEnabled }, (e, r) => {
560
594
  if (e) reject(e);
561
595
  else resolve(r);
562
596
  });
@@ -606,6 +640,8 @@ async function handleMessage(msg) {
606
640
  if (!injectionCheck.valid) {
607
641
  return { success: false, error: `安全限制: ${injectionCheck.error}` };
608
642
  }
643
+ const cacheEnabled = process.env.LONG_CODE_CACHE === '1';
644
+ const codeHash = computeCodeHash(msg.code, cacheEnabled);
609
645
  const maxRetriesResult = 3;
610
646
  let lastErrorResult = null;
611
647
  for (let i = 0; i < maxRetriesResult; i++) {
@@ -614,7 +650,7 @@ async function handleMessage(msg) {
614
650
  log(`sendResult: ${msg.code}`);
615
651
  try {
616
652
  const r = await new Promise((resolve, reject) => {
617
- cadSendWithResult({ code: msg.code, platform: msg.platform, encoding: msg.encoding || '' }, (e, r) => {
653
+ cadSendWithResult({ code: msg.code, platform: msg.platform, encoding: msg.encoding || '', codeHash, cacheEnabled }, (e, r) => {
618
654
  if (e) reject(e);
619
655
  else resolve(r);
620
656
  });
package/dist/config.js CHANGED
@@ -33,6 +33,7 @@ const envSchema = z.object({
33
33
  LLM_MODEL: z.string().optional().default('gpt-4o-mini'),
34
34
  LLM_MAX_TOKENS: z.string().optional().default('4096'),
35
35
  LLM_TEMPERATURE: z.string().optional().default('0.7'),
36
+ WORKER_POOL_SIZE: z.string().optional().default('2'),
36
37
  });
37
38
 
38
39
  const configSchema = z.object({
@@ -71,6 +72,7 @@ const configSchema = z.object({
71
72
  llmMaxTokens: z.number().optional(),
72
73
  llmTemperature: z.number().optional(),
73
74
  maxPoolSize: z.number().optional(),
75
+ workerPoolSize: z.number().optional(),
74
76
  });
75
77
 
76
78
  function parseArgs() {
@@ -171,6 +173,7 @@ const config = {
171
173
  llmMaxTokens: fileConfig?.llmMaxTokens || parseInt(env.LLM_MAX_TOKENS, 10),
172
174
  llmTemperature: fileConfig?.llmTemperature || parseFloat(env.LLM_TEMPERATURE),
173
175
  maxPoolSize: fileConfig?.maxPoolSize || 3,
176
+ workerPoolSize: fileConfig?.workerPoolSize || parseInt(env.WORKER_POOL_SIZE, 10),
174
177
  };
175
178
 
176
179
  export function validateConfig() {
@@ -201,16 +204,20 @@ export function validateConfig() {
201
204
  }
202
205
 
203
206
  let configWatchers = [];
207
+ let configReloadLock = false;
204
208
 
205
209
  if (configFilePath && fs.existsSync(configFilePath)) {
206
210
  try {
207
211
  fs.watch(configFilePath, (eventType) => {
208
212
  if (eventType === 'change') {
213
+ if (configReloadLock) return;
214
+ configReloadLock = true;
209
215
  const newFileConfig = loadConfigFile(configFilePath);
210
216
  if (newFileConfig) {
211
217
  Object.assign(config, newFileConfig);
212
- configWatchers.forEach(fn => fn(config));
218
+ configWatchers.forEach(fn => { try { fn(config); } catch {} });
213
219
  }
220
+ configReloadLock = false;
214
221
  }
215
222
  });
216
223
  } catch (e) { console.error(`Config file watch error: ${e.message}`); }
@@ -225,12 +232,16 @@ export function getAllConfig() {
225
232
  }
226
233
 
227
234
  export function reloadConfig() {
235
+ if (configReloadLock) return false;
236
+ configReloadLock = true;
228
237
  const newFileConfig = loadConfigFile(config.configFile);
229
238
  if (newFileConfig) {
230
239
  Object.assign(config, newFileConfig);
231
- configWatchers.forEach(fn => fn(config));
240
+ configWatchers.forEach(fn => { try { fn(config); } catch {} });
241
+ configReloadLock = false;
232
242
  return true;
233
243
  }
244
+ configReloadLock = false;
234
245
  return false;
235
246
  }
236
247
 
@@ -0,0 +1,70 @@
1
+ import { cad } from '../cad.js';
2
+ import { log, error as logError } from '../logger.js';
3
+ import { mcpSuccess, mcpError, ensureCadConnected } from '../handler-utils.js';
4
+ import { handleToolCall } from '../mcp-tools.js';
5
+
6
+ export async function batchTransaction({ operations }) {
7
+ try {
8
+ await ensureCadConnected();
9
+
10
+ if (!operations || !Array.isArray(operations) || operations.length === 0) {
11
+ return mcpError('operations 必须是非空数组');
12
+ }
13
+
14
+ log(`batch_transaction: starting ${operations.length} operations`);
15
+
16
+ await cad.sendCommand('(command "_.UNDO" "_BEGIN")');
17
+
18
+ const results = [];
19
+ let hasError = false;
20
+
21
+ for (let i = 0; i < operations.length; i++) {
22
+ const op = operations[i];
23
+ log(`batch_transaction: step ${i + 1}/${operations.length} -> ${op.tool}`);
24
+
25
+ try {
26
+ const result = await handleToolCall(op.tool, op.args || {});
27
+ results.push({
28
+ step: i,
29
+ tool: op.tool,
30
+ success: !result.isError,
31
+ result,
32
+ });
33
+ if (result.isError) {
34
+ hasError = true;
35
+ }
36
+ } catch (e) {
37
+ logError(`batch_transaction: step ${i} (${op.tool}) threw: ${e.message}`);
38
+ results.push({
39
+ step: i,
40
+ tool: op.tool,
41
+ success: false,
42
+ error: e.message,
43
+ });
44
+ hasError = true;
45
+ }
46
+ }
47
+
48
+ try {
49
+ await cad.sendCommand('(command "_.UNDO" "_END")');
50
+ } catch (e) {
51
+ logError(`batch_transaction: UNDO _END failed: ${e.message}`);
52
+ }
53
+
54
+ if (hasError) {
55
+ try {
56
+ await cad.sendCommand('(command "_.UNDO" "1")');
57
+ log('batch_transaction: rolled back due to errors');
58
+ } catch (e) {
59
+ logError(`batch_transaction: UNDO rollback failed: ${e.message}`);
60
+ }
61
+ return mcpError(`批量事务部分操作失败,已回滚: ${JSON.stringify(results)}`);
62
+ }
63
+
64
+ log(`batch_transaction: all ${operations.length} operations succeeded`);
65
+ return mcpSuccess(JSON.stringify(results));
66
+ } catch (e) {
67
+ logError(`batch_transaction: outer error: ${e.message}`);
68
+ return mcpError(`批量事务错误: ${e.message}`);
69
+ }
70
+ }
@@ -1,6 +1,6 @@
1
1
  import { cad } from '../cad.js';
2
2
  import { log } from '../logger.js';
3
- import { escapeLispString } from '../handler-utils.js';
3
+ import { withCadConnection, mcpSuccess, mcpError, escapeLispString } from '../handler-utils.js';
4
4
 
5
5
  export async function connectCad(platform = null) {
6
6
  log(`connect_cad called${platform ? ` (target: ${platform})` : ''}, cad.connected before: ${cad.connected}`);
@@ -11,92 +11,68 @@ export async function connectCad(platform = null) {
11
11
  if (connected) {
12
12
  const messages = [`已连接到 ${cad.getPlatform()} ${cad.getVersion()}`];
13
13
  initAtlisp().catch(e => log(`connect_cad: initAtlisp failed: ${e.message}`));
14
- return { content: [{ type: 'text', text: messages.join(';') }] };
14
+ return mcpSuccess(messages.join(';'));
15
15
  }
16
- return { content: [{ type: 'text', text: '未能连接或启动 CAD,请确保 CAD 已安装' }], isError: true };
16
+ return mcpError('未能连接或启动 CAD,请确保 CAD 已安装');
17
17
  } catch (e) {
18
18
  log('connect_cad error: ' + e.message);
19
- return { content: [{ type: 'text', text: `连接 CAD 失败: ${e.message}` }], isError: true };
19
+ return mcpError(`连接 CAD 失败: ${e.message}`);
20
20
  }
21
21
  }
22
22
 
23
- export async function evalLisp(code, withResult = false, encoding = null) {
24
- if (!cad.connected) { await cad.connect(); }
25
- if (!cad.connected) {
26
- return { content: [{ type: 'text', text: '未连接 CAD' }], isError: true };
27
- }
23
+ export const evalLisp = withCadConnection(async (code, withResult = false, encoding = null) => {
28
24
  const trimmed = (code || '').trim();
29
- if (!trimmed) return { content: [{ type: 'text', text: '命令为空,未发送' }] };
30
- try {
31
- if (withResult) {
32
- const result = await cad.sendCommandWithResult(trimmed, encoding);
33
- if (result !== null) {
34
- return { content: [{ type: 'text', text: result }] };
35
- }
36
- return { content: [{ type: 'text', text: '执行失败或无返回值' }], isError: true };
37
- } else {
38
- await cad.sendCommand(trimmed + '\n');
39
- return { content: [{ type: 'text', text: `已发送命令` }] };
25
+ if (!trimmed) return mcpSuccess('命令为空,未发送');
26
+ if (withResult) {
27
+ const result = await cad.sendCommandWithResult(trimmed, encoding);
28
+ if (result !== null) {
29
+ return mcpSuccess(result);
40
30
  }
41
- } catch (e) {
42
- return { content: [{ type: 'text', text: `错误: ${e.message}` }], isError: true };
31
+ return mcpError('执行失败或无返回值');
43
32
  }
44
- }
33
+ await cad.sendCommand(trimmed + '\n');
34
+ return mcpSuccess('已发送命令');
35
+ });
45
36
 
46
- export async function getCadInfo() {
47
- if (!cad.connected) { await cad.connect(); }
48
- if (!cad.connected) return { content: [{ type: 'text', text: 'CAD 未连接' }] };
37
+ export const getCadInfo = withCadConnection(async () => {
49
38
  const info = await cad.getInfo();
50
- return { content: [{ type: 'text', text: info }] };
51
- }
39
+ return mcpSuccess(info);
40
+ });
52
41
 
53
- export async function atCommand(command) {
54
- if (!cad.connected) return { content: [{ type: 'text', text: '请先连接 CAD' }], isError: true };
42
+ export const atCommand = withCadConnection(async (command) => {
55
43
  const trimmed = (command || '').trim();
56
- if (!trimmed) return { content: [{ type: 'text', text: '命令为空,未发送' }] };
44
+ if (!trimmed) return mcpSuccess('命令为空,未发送');
57
45
  await cad.sendCommand(trimmed + '\n');
58
- return { content: [{ type: 'text', text: '已发送命令' }] };
59
- }
46
+ return mcpSuccess('已发送命令');
47
+ });
60
48
 
61
- export async function newDocument() {
62
- if (!cad.connected) { await cad.connect(); }
63
- if (!cad.connected) return { content: [{ type: 'text', text: '未连接 CAD' }], isError: true };
49
+ export const newDocument = withCadConnection(async () => {
64
50
  const result = await cad.newDoc();
65
51
  if (result) {
66
- return { content: [{ type: 'text', text: '已在 CAD 中新建空白文档' }] };
52
+ return mcpSuccess('已在 CAD 中新建空白文档');
67
53
  }
68
- return { content: [{ type: 'text', text: '新建文档失败' }], isError: true };
69
- }
54
+ return mcpError('新建文档失败');
55
+ });
70
56
 
71
- export async function bringToFront() {
72
- if (!cad.connected) { await cad.connect(); }
73
- if (!cad.connected) return { content: [{ type: 'text', text: '未连接 CAD' }], isError: true };
57
+ export const bringToFront = withCadConnection(async () => {
74
58
  const result = await cad.bringToFront();
75
59
  if (result) {
76
- return { content: [{ type: 'text', text: '已将 CAD 窗口切换到前台' }] };
60
+ return mcpSuccess('已将 CAD 窗口切换到前台');
77
61
  }
78
- return { content: [{ type: 'text', text: '切换前台失败' }], isError: true };
79
- }
62
+ return mcpError('切换前台失败');
63
+ });
80
64
 
81
- export async function installAtlisp() {
82
- if (!cad.connected) { await cad.connect(); }
83
- if (!cad.connected) return { content: [{ type: 'text', text: '未连接 CAD' }], isError: true };
65
+ export const installAtlisp = withCadConnection(async () => {
84
66
  const installCode = '(progn(vl-load-com)(setq s strcat h "http" o(vlax-create-object (s"win"h".win"h"request.5.1"))v vlax-invoke e eval r read)(v o\'open "get" (s h"://atlisp.""cn/@"):vlax-true)(v o\'send)(v o\'WaitforResponse 1000)(e(r(vlax-get-property o\'ResponseText))))';
85
67
  await cad.sendCommand(installCode + '\n');
86
- return { content: [{ type: 'text', text: '已发送 @lisp 安装代码到 CAD' }] };
87
- }
68
+ return mcpSuccess('已发送 @lisp 安装代码到 CAD');
69
+ });
88
70
 
89
- export async function listFunctionsInCad() {
90
- if (!cad.connected) { await cad.connect(); }
91
- if (!cad.connected) return { content: [{ type: 'text', text: '未连接 CAD' }], isError: true };
92
- try {
93
- const result = await cad.sendCommandWithResult('(atoms-family 0)', null);
94
- if (result) return { content: [{ type: 'text', text: result }] };
95
- return { content: [{ type: 'text', text: 'CAD 函数列表为空' }] };
96
- } catch (e) {
97
- return { content: [{ type: 'text', text: `错误: ${e.message}` }], isError: true };
98
- }
99
- }
71
+ export const listFunctionsInCad = withCadConnection(async () => {
72
+ const result = await cad.sendCommandWithResult('(atoms-family 0)', null);
73
+ if (result) return mcpSuccess(result);
74
+ return mcpError('CAD 函数列表为空');
75
+ });
100
76
 
101
77
  export async function getSystemStatus() {
102
78
  const status = {
@@ -140,9 +116,7 @@ export async function getSystemStatus() {
140
116
  return { content: [{ type: 'text', text: JSON.stringify(status, null, 2) }] };
141
117
  }
142
118
 
143
- export async function initAtlisp() {
144
- if (!cad.connected) { await cad.connect(); }
145
- if (!cad.connected) return { content: [{ type: 'text', text: '未连接 CAD' }], isError: true };
119
+ export const initAtlisp = withCadConnection(async () => {
146
120
  const code = `(if (null @::load-module)
147
121
  (progn
148
122
  (vl-load-com)
@@ -151,30 +125,16 @@ export async function initAtlisp() {
151
125
  (v o'send)
152
126
  (v o'WaitforResponse 1000)
153
127
  (e(r(vlax-get o'ResponseText)))))`;
154
- try {
155
- await cad.sendCommand(code + '\n');
156
- return { content: [{ type: 'text', text: '已发送 @lisp 函数库加载代码到 CAD' }] };
157
- } catch (e) {
158
- return { content: [{ type: 'text', text: `错误: ${e.message}` }], isError: true };
159
- }
160
- }
161
- export async function getSystemVariable(name) {
162
- if (!cad.connected) { await cad.connect(); }
163
- if (!cad.connected) return { content: [{ type: 'text', text: '未连接 CAD' }], isError: true };
164
- try {
165
- const result = await cad.sendCommandWithResult(`(vl-princ-to-string (getvar "${escapeLispString(name)}"))`);
166
- return { content: [{ type: 'text', text: result || 'nil' }] };
167
- } catch (e) {
168
- return { content: [{ type: 'text', text: `错误: ${e.message}` }], isError: true };
169
- }
170
- }
171
- export async function setSystemVariable(name, value) {
172
- if (!cad.connected) { await cad.connect(); }
173
- if (!cad.connected) return { content: [{ type: 'text', text: '未连接 CAD' }], isError: true };
174
- try {
175
- await cad.sendCommand(`(setvar "${escapeLispString(name)}" ${value})\n`);
176
- return { content: [{ type: 'text', text: `已设置 ${name} = ${value}` }] };
177
- } catch (e) {
178
- return { content: [{ type: 'text', text: `错误: ${e.message}` }], isError: true };
179
- }
180
- }
128
+ await cad.sendCommand(code + '\n');
129
+ return mcpSuccess('已发送 @lisp 函数库加载代码到 CAD');
130
+ });
131
+
132
+ export const getSystemVariable = withCadConnection(async (name) => {
133
+ const result = await cad.sendCommandWithResult(`(vl-princ-to-string (getvar "${escapeLispString(name)}"))`);
134
+ return mcpSuccess(result || 'nil');
135
+ });
136
+
137
+ export const setSystemVariable = withCadConnection(async (name, value) => {
138
+ await cad.sendCommand(`(setvar "${escapeLispString(name)}" ${value})\n`);
139
+ return mcpSuccess(`已设置 ${name} = ${value}`);
140
+ });