-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Expand file tree
/
Copy pathtools_service.py
More file actions
584 lines (504 loc) · 22.1 KB
/
Copy pathtools_service.py
File metadata and controls
584 lines (504 loc) · 22.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
from __future__ import annotations
import traceback
from typing import Any
from astrbot.core import logger, sp
from astrbot.core.agent.mcp_client import MCPTool, validate_mcp_stdio_config
from astrbot.core.core_lifecycle import AstrBotCoreLifecycle
from astrbot.core.star import star_map
from astrbot.core.tools.registry import get_builtin_tool_config_statuses
class ToolsServiceError(Exception):
pass
class EmptyMcpServersError(ValueError):
pass
def extract_mcp_server_config(mcp_servers_value: object) -> dict:
if not isinstance(mcp_servers_value, dict):
raise ValueError("mcpServers must be a JSON object")
if not mcp_servers_value:
raise EmptyMcpServersError("mcpServers configuration cannot be empty")
key_0 = next(iter(mcp_servers_value))
extracted = mcp_servers_value[key_0]
if not isinstance(extracted, dict):
raise ValueError(
"Invalid mcpServers format. Ensure each key in mcpServers is a server name, "
"and each value is an object containing fields like command/url."
)
return extracted
class ToolsService:
def __init__(self, core_lifecycle: AstrBotCoreLifecycle) -> None:
self.core_lifecycle = core_lifecycle
self.tool_mgr = core_lifecycle.provider_manager.llm_tools
def rollback_mcp_server(self, name: str) -> bool:
try:
rollback_config = self.tool_mgr.load_mcp_config()
if name in rollback_config["mcpServers"]:
rollback_config["mcpServers"].pop(name)
return self.tool_mgr.save_mcp_config(rollback_config)
return True
except Exception:
logger.error(traceback.format_exc())
return False
def get_mcp_servers(self) -> list[dict]:
try:
config = self.tool_mgr.load_mcp_config()
servers = []
mcp_servers = config.get("mcpServers", {})
if not isinstance(mcp_servers, dict):
logger.warning(
f"Invalid MCP server config type: {type(mcp_servers).__name__}. Expected object/dict; skipped all MCP servers."
)
mcp_servers = {}
for name, server_config in mcp_servers.items():
if not isinstance(server_config, dict):
logger.warning(
f"Invalid config for MCP server '{name}' (type: {type(server_config).__name__}); skipped."
)
continue
server_info = {
"name": name,
"active": server_config.get("active", True),
}
for key, value in server_config.items():
if key != "active":
server_info[key] = value
for name_key, runtime in self.tool_mgr.mcp_server_runtime_view.items():
if name_key == name:
mcp_client = runtime.client
server_info["tools"] = [tool.name for tool in mcp_client.tools]
server_info["errlogs"] = mcp_client.server_errlogs
break
else:
server_info["tools"] = []
servers.append(server_info)
return servers
except Exception as exc:
logger.error(traceback.format_exc())
raise ToolsServiceError(f"Failed to get MCP server list: {exc!s}") from exc
def get_mcp_server_config(self, name: str) -> dict | None:
config = self.tool_mgr.load_mcp_config()
mcp_servers = config.get("mcpServers", {})
if not isinstance(mcp_servers, dict):
return None
server_config = mcp_servers.get(name)
if not isinstance(server_config, dict):
return None
return dict(server_config)
async def add_mcp_server(self, server_data: Any) -> str:
try:
name = server_data.get("name", "")
if not name:
raise ToolsServiceError("Server name cannot be empty")
has_valid_config, server_config = self._build_server_config(server_data)
if not has_valid_config:
raise ToolsServiceError("A valid server configuration is required")
self._validate_server_config(server_config)
config = self.tool_mgr.load_mcp_config()
if name in config["mcpServers"]:
raise ToolsServiceError(f"Server {name} already exists")
try:
await self.tool_mgr.test_mcp_server_connection(server_config)
except Exception as exc:
logger.error(traceback.format_exc())
raise ToolsServiceError(f"MCP connection test failed: {exc!s}") from exc
config["mcpServers"][name] = server_config
if self.tool_mgr.save_mcp_config(config):
await self._enable_added_server(name, server_config)
return f"Successfully added MCP server {name}"
raise ToolsServiceError("Failed to save configuration")
except ToolsServiceError:
raise
except Exception as exc:
logger.error(traceback.format_exc())
raise ToolsServiceError(f"Failed to add MCP server: {exc!s}") from exc
async def update_mcp_server(self, server_data: Any) -> str:
try:
name = server_data.get("name", "")
old_name = server_data.get("oldName") or name
if not name:
raise ToolsServiceError("Server name cannot be empty")
config = self.tool_mgr.load_mcp_config()
if old_name not in config["mcpServers"]:
raise ToolsServiceError(f"Server {old_name} does not exist")
is_rename = name != old_name
if name in config["mcpServers"] and is_rename:
raise ToolsServiceError(f"Server {name} already exists")
old_config = config["mcpServers"][old_name]
old_active = (
old_config.get("active", True) if isinstance(old_config, dict) else True
)
active = server_data.get("active", old_active)
only_update_active, server_config = self._build_updated_server_config(
server_data,
old_config,
active,
)
self._validate_server_config(server_config)
if is_rename:
config["mcpServers"].pop(old_name)
config["mcpServers"][name] = server_config
else:
config["mcpServers"][name] = server_config
if self.tool_mgr.save_mcp_config(config):
await self._sync_updated_server_runtime(
name=name,
old_name=old_name,
active=active,
is_rename=is_rename,
only_update_active=only_update_active,
server_config=config["mcpServers"][name],
)
return f"Successfully updated MCP server {name}"
raise ToolsServiceError("Failed to save configuration")
except ToolsServiceError:
raise
except Exception as exc:
logger.error(traceback.format_exc())
raise ToolsServiceError(f"Failed to update MCP server: {exc!s}") from exc
async def delete_mcp_server(self, server_data: Any) -> str:
try:
name = server_data.get("name", "")
if not name:
raise ToolsServiceError("Server name cannot be empty")
config = self.tool_mgr.load_mcp_config()
if name not in config["mcpServers"]:
raise ToolsServiceError(f"Server {name} does not exist")
del config["mcpServers"][name]
if self.tool_mgr.save_mcp_config(config):
if name in self.tool_mgr.mcp_server_runtime_view:
await self._disable_server(name)
return f"Successfully deleted MCP server {name}"
raise ToolsServiceError("Failed to save configuration")
except ToolsServiceError:
raise
except Exception as exc:
logger.error(traceback.format_exc())
raise ToolsServiceError(f"Failed to delete MCP server: {exc!s}") from exc
async def test_mcp_connection(self, server_data: Any) -> list:
try:
config = server_data.get("mcp_server_config", None)
if not isinstance(config, dict) or not config:
raise ToolsServiceError("Invalid MCP server configuration")
if "mcpServers" in config:
mcp_servers = config["mcpServers"]
if isinstance(mcp_servers, dict) and len(mcp_servers) > 1:
raise ToolsServiceError(
"Only one MCP server configuration can be tested at a time"
)
try:
config = extract_mcp_server_config(mcp_servers)
except EmptyMcpServersError as exc:
raise ToolsServiceError(
"MCP server configuration cannot be empty"
) from exc
except ValueError as exc:
raise ToolsServiceError(f"{exc!s}") from exc
elif not config:
raise ToolsServiceError("MCP server configuration cannot be empty")
self._validate_server_config(config)
return await self.tool_mgr.test_mcp_server_connection(config)
except ToolsServiceError:
raise
except Exception as exc:
logger.error(traceback.format_exc())
raise ToolsServiceError(f"Failed to test MCP connection: {exc!s}") from exc
def get_tool_list(self) -> list[dict]:
try:
tools = list(self.tool_mgr.func_list)
existing_names = {tool.name for tool in tools}
for tool in self.tool_mgr.iter_builtin_tools():
if tool.name not in existing_names:
tools.append(tool)
config_entries = self._get_config_entries()
tools_dict = []
for tool in tools:
tools_dict.append(self._serialize_tool(tool, config_entries))
return tools_dict
except Exception as exc:
logger.error(traceback.format_exc())
raise ToolsServiceError(f"Failed to get tool list: {exc!s}") from exc
def update_tool_permission(self, data: Any) -> str:
"""Set a tool permission level.
Args:
data: Legacy dashboard payload with ``name`` and ``permission``.
Returns:
A success message for the response body.
Raises:
ToolsServiceError: If the payload is invalid, the tool is unknown,
or permission storage cannot be updated.
"""
try:
tool_name = data.get("name") if isinstance(data, dict) else None
permission = data.get("permission") if isinstance(data, dict) else None
if not tool_name or permission not in ("admin", "member"):
raise ToolsServiceError(
"name and permission (admin or member) are required"
)
if self.tool_mgr.is_builtin_tool(tool_name):
raise ToolsServiceError(
"Builtin tools do not support per-tool permission configuration."
)
if not any(t.name == tool_name for t in self.tool_mgr.func_list):
raise ToolsServiceError(f"Tool '{tool_name}' not found")
perms_store = sp.get(
"tool_permissions",
{},
scope="global",
scope_id="global",
)
if not isinstance(perms_store, dict):
perms_store = {}
defaults = perms_store.get("_default", {})
if not isinstance(defaults, dict):
defaults = {}
defaults[tool_name] = permission
perms_store["_default"] = defaults
sp.put(
"tool_permissions",
perms_store,
scope="global",
scope_id="global",
)
return f"Tool '{tool_name}' permission set to {permission}"
except ToolsServiceError:
raise
except Exception as exc:
logger.error(traceback.format_exc())
raise ToolsServiceError(
f"Failed to update tool permission: {exc!s}"
) from exc
def toggle_tool(self, data: Any) -> str:
try:
tool_name = data.get("name")
action = data.get("activate")
if not tool_name or action is None:
raise ToolsServiceError("Missing required parameters: name or activate")
if self.tool_mgr.is_builtin_tool(tool_name):
raise ToolsServiceError(
"Builtin tools are read-only and cannot be toggled."
)
if action:
try:
ok = self.tool_mgr.activate_llm_tool(tool_name, star_map=star_map)
except ValueError as exc:
raise ToolsServiceError(
f"Failed to activate tool: {exc!s}"
) from exc
else:
ok = self.tool_mgr.deactivate_llm_tool(tool_name)
if ok:
return "Operation successful."
raise ToolsServiceError(
f"Tool {tool_name} does not exist or the operation failed."
)
except ToolsServiceError:
raise
except Exception as exc:
logger.error(traceback.format_exc())
raise ToolsServiceError(f"Failed to operate tool: {exc!s}") from exc
async def sync_provider(self, data: Any) -> str:
try:
provider_name = data.get("name")
match provider_name:
case "modelscope":
access_token = data.get("access_token", "")
await self.tool_mgr.sync_modelscope_mcp_servers(access_token)
case _:
raise ToolsServiceError(f"Unknown provider: {provider_name}")
return "Sync completed"
except ToolsServiceError:
raise
except Exception as exc:
logger.error(traceback.format_exc())
raise ToolsServiceError(f"Sync failed: {exc!s}") from exc
@staticmethod
def _build_server_config(server_data: dict) -> tuple[bool, dict]:
has_valid_config = False
server_config = {"active": server_data.get("active", True)}
for key, value in server_data.items():
if key in ["name", "active", "tools", "errlogs"]:
continue
if key == "mcpServers":
try:
server_config = extract_mcp_server_config(server_data["mcpServers"])
except ValueError as exc:
raise ToolsServiceError(f"{exc!s}") from exc
else:
server_config[key] = value
has_valid_config = True
return has_valid_config, server_config
@staticmethod
def _build_updated_server_config(
server_data: dict,
old_config: object,
active: bool,
) -> tuple[bool, dict]:
server_config = {"active": active}
only_update_active = True
for key, value in server_data.items():
if key in ["name", "active", "tools", "errlogs", "oldName"]:
continue
if key == "mcpServers":
try:
server_config = extract_mcp_server_config(server_data["mcpServers"])
except ValueError as exc:
raise ToolsServiceError(f"{exc!s}") from exc
else:
server_config[key] = value
only_update_active = False
if only_update_active and isinstance(old_config, dict):
for key, value in old_config.items():
if key != "active":
server_config[key] = value
return only_update_active, server_config
@staticmethod
def _validate_server_config(server_config: dict) -> None:
try:
validate_mcp_stdio_config(server_config)
except ValueError as exc:
raise ToolsServiceError(f"{exc!s}") from exc
async def _enable_added_server(self, name: str, server_config: dict) -> None:
try:
await self.tool_mgr.enable_mcp_server(name, server_config, timeout=30)
except TimeoutError as exc:
rollback_ok = self.rollback_mcp_server(name)
err_msg = f"Timed out while enabling MCP server {name}."
if not rollback_ok:
err_msg += (
" Configuration rollback failed. Please check the config manually."
)
raise ToolsServiceError(err_msg) from exc
except Exception as exc:
logger.error(traceback.format_exc())
rollback_ok = self.rollback_mcp_server(name)
err_msg = f"Failed to enable MCP server {name}: {exc!s}"
if not rollback_ok:
err_msg += (
" Configuration rollback failed. Please check the config manually."
)
raise ToolsServiceError(err_msg) from exc
async def _sync_updated_server_runtime(
self,
*,
name: str,
old_name: str,
active: bool,
is_rename: bool,
only_update_active: bool,
server_config: dict,
) -> None:
if active:
if (
old_name in self.tool_mgr.mcp_server_runtime_view
or not only_update_active
or is_rename
):
await self._disable_server_before_enable(old_name)
await self._enable_updated_server(name, server_config)
elif old_name in self.tool_mgr.mcp_server_runtime_view:
await self._disable_server(old_name)
async def _disable_server_before_enable(self, old_name: str) -> None:
try:
await self.tool_mgr.disable_mcp_server(old_name, timeout=10)
except TimeoutError as exc:
raise ToolsServiceError(
f"Timed out while disabling MCP server {old_name} before enabling: {exc!s}"
) from exc
except Exception as exc:
logger.error(traceback.format_exc())
raise ToolsServiceError(
f"Failed to disable MCP server {old_name} before enabling: {exc!s}"
) from exc
async def _enable_updated_server(self, name: str, server_config: dict) -> None:
try:
await self.tool_mgr.enable_mcp_server(name, server_config, timeout=30)
except TimeoutError as exc:
raise ToolsServiceError(
f"Timed out while enabling MCP server {name}."
) from exc
except Exception as exc:
logger.error(traceback.format_exc())
raise ToolsServiceError(
f"Failed to enable MCP server {name}: {exc!s}"
) from exc
async def _disable_server(self, name: str) -> None:
try:
await self.tool_mgr.disable_mcp_server(name, timeout=10)
except TimeoutError as exc:
raise ToolsServiceError(
f"Timed out while disabling MCP server {name}."
) from exc
except Exception as exc:
logger.error(traceback.format_exc())
raise ToolsServiceError(
f"Failed to disable MCP server {name}: {exc!s}"
) from exc
def _get_config_entries(self) -> list[dict]:
conf_list = self.core_lifecycle.astrbot_config_mgr.get_conf_list()
conf_name_map = {conf["id"]: conf["name"] for conf in conf_list}
config_entries = []
for conf_id, conf in self.core_lifecycle.astrbot_config_mgr.confs.items():
config_entries.append(
{
"conf_id": conf_id,
"conf_name": conf_name_map.get(conf_id, conf_id),
"config": conf,
}
)
return config_entries
def _serialize_tool(self, tool, config_entries: list[dict]) -> dict:
readonly = False
builtin_config_statuses = []
builtin_config_tags = []
if self.tool_mgr.is_builtin_tool(tool.name):
origin = "builtin"
origin_name = "AstrBot Core"
readonly = True
builtin_config_statuses = get_builtin_tool_config_statuses(
tool.name,
config_entries,
)
builtin_config_tags = [
status for status in builtin_config_statuses if status["enabled"]
]
elif isinstance(tool, MCPTool):
origin = "mcp"
origin_name = tool.mcp_server_name
elif tool.handler_module_path and star_map.get(tool.handler_module_path):
star = star_map[tool.handler_module_path]
origin = "plugin"
origin_name = star.name
else:
origin = "unknown"
origin_name = "unknown"
tool_info = {
"name": tool.name,
"description": tool.description,
"parameters": tool.parameters,
"active": tool.active,
"origin": origin,
"origin_name": origin_name,
"readonly": readonly,
"builtin_config_statuses": builtin_config_statuses,
"builtin_config_tags": builtin_config_tags,
}
if not readonly:
perms_store = sp.get(
"tool_permissions",
{},
scope="global",
scope_id="global",
)
defaults = (
perms_store.get("_default", {}) if isinstance(perms_store, dict) else {}
)
configured = tool.name in defaults
permission = (
defaults[tool.name]
if configured
else self.tool_mgr._default_permission(tool.name)
)
tool_info["permission"] = permission
tool_info["permission_configured"] = configured
tool_info["declared_permission_type"] = getattr(
tool, "declared_permission_type", None
)
return tool_info