yimo-kit 0.1.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 (70) hide show
  1. yimo/__init__.py +26 -0
  2. yimo/kit/__init__.py +98 -0
  3. yimo/kit/ai/__init__.py +110 -0
  4. yimo/kit/ai/_internal/__init__.py +27 -0
  5. yimo/kit/ai/_internal/failover.py +535 -0
  6. yimo/kit/ai/_internal/pool.py +526 -0
  7. yimo/kit/ai/_internal/rerank_transport.py +137 -0
  8. yimo/kit/ai/_internal/retry_after.py +51 -0
  9. yimo/kit/ai/_internal/sdk_client.py +463 -0
  10. yimo/kit/ai/_internal/service_base.py +115 -0
  11. yimo/kit/ai/_internal/types.py +28 -0
  12. yimo/kit/ai/agent/__init__.py +127 -0
  13. yimo/kit/ai/agent/approval.py +66 -0
  14. yimo/kit/ai/agent/errors.py +128 -0
  15. yimo/kit/ai/agent/loop.py +643 -0
  16. yimo/kit/ai/agent/mcp.py +278 -0
  17. yimo/kit/ai/agent/registry.py +203 -0
  18. yimo/kit/ai/agent/session.py +150 -0
  19. yimo/kit/ai/agent/skill.py +370 -0
  20. yimo/kit/ai/agent/types.py +161 -0
  21. yimo/kit/ai/chat_service.py +724 -0
  22. yimo/kit/ai/decision/__init__.py +57 -0
  23. yimo/kit/ai/decision/decima.py +853 -0
  24. yimo/kit/ai/decision/laya.py +552 -0
  25. yimo/kit/ai/embedding_service.py +198 -0
  26. yimo/kit/ai/exceptions.py +109 -0
  27. yimo/kit/ai/image_service.py +84 -0
  28. yimo/kit/ai/messages.py +105 -0
  29. yimo/kit/ai/model_builder.py +121 -0
  30. yimo/kit/ai/model_client.py +62 -0
  31. yimo/kit/ai/profiles.py +577 -0
  32. yimo/kit/ai/rerank_service.py +136 -0
  33. yimo/kit/ai/runner.py +1127 -0
  34. yimo/kit/common_kit.py +221 -0
  35. yimo/kit/config/__init__.py +44 -0
  36. yimo/kit/config/kit_config.py +210 -0
  37. yimo/kit/config/log_config.py +171 -0
  38. yimo/kit/crawl/__init__.py +71 -0
  39. yimo/kit/crawl/article_io.py +325 -0
  40. yimo/kit/crawl/article_models.py +172 -0
  41. yimo/kit/crawl/deepseek_kit.py +673 -0
  42. yimo/kit/crawl/web_article_kit.py +638 -0
  43. yimo/kit/crawl/wx_article_kit.py +692 -0
  44. yimo/kit/db/__init__.py +101 -0
  45. yimo/kit/db/audit.py +625 -0
  46. yimo/kit/db/base_db_kit.py +1265 -0
  47. yimo/kit/db/crud.py +423 -0
  48. yimo/kit/db/engine.py +235 -0
  49. yimo/kit/db/exceptions.py +45 -0
  50. yimo/kit/db/models/__init__.py +33 -0
  51. yimo/kit/db/models/base.py +56 -0
  52. yimo/kit/db/mysql_kit.py +348 -0
  53. yimo/kit/db/pg_kit.py +442 -0
  54. yimo/kit/db/query.py +338 -0
  55. yimo/kit/db/session.py +85 -0
  56. yimo/kit/db/sqlite_kit.py +462 -0
  57. yimo/kit/db/transaction.py +109 -0
  58. yimo/kit/docs/__init__.py +34 -0
  59. yimo/kit/docs/anydoc_kit.py +490 -0
  60. yimo/kit/docs/docx_kit.py +895 -0
  61. yimo/kit/docs/md2doc_kit.py +1801 -0
  62. yimo/kit/docs/mineru_kit.py +1497 -0
  63. yimo/kit/docs/rc_docparser_kit.py +654 -0
  64. yimo/kit/file_kit.py +518 -0
  65. yimo/kit/license_kit.py +533 -0
  66. yimo/kit/redis_kit.py +392 -0
  67. yimo_kit-0.1.0.dist-info/METADATA +1673 -0
  68. yimo_kit-0.1.0.dist-info/RECORD +70 -0
  69. yimo_kit-0.1.0.dist-info/WHEEL +4 -0
  70. yimo_kit-0.1.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,370 @@
1
+ """
2
+ Copyright (c) 2021-2026 溢墨修心(Yimo). All Rights Reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+
16
+ Project: yimo
17
+ Author: 溢墨修心(Yimo)
18
+ """
19
+
20
+ # date: 2026-11-10
21
+ """Skill 包加载与只读工具。
22
+
23
+ 包结构::
24
+
25
+ <skills-root>/<skill-name>/
26
+ ├── SKILL.md # 必需(frontmatter + 正文)
27
+ ├── scripts/ # 可选(v1 只解析声明,不执行)
28
+ ├── references/ # 可选
29
+ └── assets/ # 可选
30
+
31
+ v1 只暴露三个只读工具:``read_skill`` / ``list_skill_files`` /
32
+ ``read_skill_file``;脚本执行属 v2。
33
+ """
34
+
35
+ import os
36
+ from collections.abc import Awaitable, Callable
37
+ from dataclasses import dataclass
38
+ from pathlib import Path
39
+ from typing import Any
40
+
41
+ try:
42
+ import yaml
43
+ except ImportError as exc: # pragma: no cover - 仅缺依赖环境触发
44
+ raise ImportError(
45
+ "yimo.kit.ai.agent 需要可选依赖,请安装:pip install yimo-kit[agent]"
46
+ ) from exc
47
+
48
+ from yimo.kit.ai.agent.errors import (
49
+ DuplicateSkillError,
50
+ SkillNotFoundError,
51
+ SkillValidationError,
52
+ ToolExecutionError,
53
+ )
54
+ from yimo.kit.ai.agent.types import ToolResult, ToolSpec
55
+ from yimo.kit.config.log_config import get_default_logger
56
+
57
+ __all__ = ["SkillPackage", "SkillRegistry", "SkillScript"]
58
+
59
+ logger = get_default_logger(__name__)
60
+
61
+ # 单文件读取上限:防止 references/ 里的大文件撑爆上下文
62
+ _MAX_FILE_CHARS = 256 * 1024
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class SkillScript:
67
+ """SKILL.md frontmatter 中声明的一个脚本(v1 不执行)。"""
68
+
69
+ name: str
70
+ description: str
71
+ path: str
72
+ args: dict[str, Any]
73
+
74
+
75
+ @dataclass(frozen=True)
76
+ class SkillPackage:
77
+ """一个已加载的技能包。"""
78
+
79
+ name: str
80
+ version: str
81
+ description: str
82
+ root: Path
83
+ body: str
84
+ scripts: tuple[SkillScript, ...] = ()
85
+
86
+
87
+ class SkillRegistry:
88
+ """多根目录技能注册表(非线程安全)。"""
89
+
90
+ def __init__(self) -> None:
91
+ self._packages: dict[str, SkillPackage] = {}
92
+
93
+ # ------------------------------------------------------------------
94
+ # 加载
95
+ # ------------------------------------------------------------------
96
+
97
+ def load(self, *roots: str | Path) -> int:
98
+ """扫描多个根目录的一级子目录,返回新增技能数。
99
+
100
+ Raises:
101
+ DuplicateSkillError: 两个根目录存在同名技能。
102
+ SkillValidationError: SKILL.md 结构非法。
103
+ """
104
+ added = 0
105
+ for raw_root in roots:
106
+ root = Path(raw_root).expanduser()
107
+ if not root.is_dir():
108
+ logger.warning(f"技能根目录不存在,已跳过: {root}")
109
+ continue
110
+ for child in sorted(root.iterdir()):
111
+ if not child.is_dir() or child.name.startswith("."):
112
+ continue
113
+ skill_file = child / "SKILL.md"
114
+ if not skill_file.is_file():
115
+ continue
116
+ package = _parse_package(child, skill_file)
117
+ existing = self._packages.get(package.name)
118
+ if existing is not None:
119
+ if existing.root.resolve() == package.root.resolve():
120
+ # 同一目录重复 load:幂等跳过,便于配置热重载
121
+ continue
122
+ raise DuplicateSkillError(
123
+ f"技能重名: {package.name}"
124
+ f"(已加载 {existing.root},本次 {package.root})"
125
+ )
126
+ self._packages[package.name] = package
127
+ added += 1
128
+ logger.info(f"已加载技能: {package.name}({package.root})")
129
+ return added
130
+
131
+ def load_from_env(self, var: str = "YIMO_SKILLS_PATH") -> int:
132
+ """从环境变量读取多路径(``os.pathsep`` 分隔)并加载。"""
133
+ raw = os.environ.get(var, "")
134
+ paths = [part for part in raw.split(os.pathsep) if part.strip()]
135
+ if not paths:
136
+ return 0
137
+ return self.load(*paths)
138
+
139
+ # ------------------------------------------------------------------
140
+ # 查询
141
+ # ------------------------------------------------------------------
142
+
143
+ def get(self, name: str) -> SkillPackage:
144
+ """按名取技能包。
145
+
146
+ Raises:
147
+ SkillNotFoundError: 技能未加载。
148
+ """
149
+ package = self._packages.get(name)
150
+ if package is None:
151
+ raise SkillNotFoundError(f"技能不存在: {name}")
152
+ return package
153
+
154
+ def names(self) -> list[str]:
155
+ """按名排序返回全部技能名。"""
156
+ return sorted(self._packages)
157
+
158
+ def index_block(self) -> str:
159
+ """生成注入 system 消息的技能索引;无技能时返回空串。"""
160
+ if not self._packages:
161
+ return ""
162
+ lines = ["# 可用技能"]
163
+ for name in self.names():
164
+ lines.append(f"- {name}: {self._packages[name].description}")
165
+ return "\n".join(lines)
166
+
167
+ def tools(
168
+ self,
169
+ ) -> list[tuple[ToolSpec, Callable[[dict[str, Any]], Awaitable[ToolResult]]]]:
170
+ """返回三个只读工具;无技能时返回空列表。"""
171
+ if not self._packages:
172
+ return []
173
+ return [
174
+ (
175
+ ToolSpec(
176
+ name="read_skill",
177
+ description=(
178
+ "读取指定技能的完整说明。name 必须取自「可用技能」列表。"
179
+ ),
180
+ input_schema={
181
+ "type": "object",
182
+ "properties": {
183
+ "name": {"type": "string", "description": "技能名"}
184
+ },
185
+ "required": ["name"],
186
+ },
187
+ ),
188
+ self._read_skill,
189
+ ),
190
+ (
191
+ ToolSpec(
192
+ name="list_skill_files",
193
+ description=(
194
+ "列出指定技能的 references/ 与 assets/ 文件(相对路径)。"
195
+ ),
196
+ input_schema={
197
+ "type": "object",
198
+ "properties": {
199
+ "name": {"type": "string", "description": "技能名"}
200
+ },
201
+ "required": ["name"],
202
+ },
203
+ ),
204
+ self._list_skill_files,
205
+ ),
206
+ (
207
+ ToolSpec(
208
+ name="read_skill_file",
209
+ description=(
210
+ "读取指定技能包内的文件内容(relpath 为包内相对路径)。"
211
+ ),
212
+ input_schema={
213
+ "type": "object",
214
+ "properties": {
215
+ "name": {"type": "string", "description": "技能名"},
216
+ "relpath": {
217
+ "type": "string",
218
+ "description": "包内相对路径,如 references/guide.md",
219
+ },
220
+ },
221
+ "required": ["name", "relpath"],
222
+ },
223
+ ),
224
+ self._read_skill_file,
225
+ ),
226
+ ]
227
+
228
+ def __len__(self) -> int:
229
+ return len(self._packages)
230
+
231
+ # ------------------------------------------------------------------
232
+ # 只读工具实现
233
+ # ------------------------------------------------------------------
234
+
235
+ async def _read_skill(self, arguments: dict[str, Any]) -> ToolResult:
236
+ package = self.get(_require_str(arguments, "name"))
237
+ return ToolResult(content=package.body)
238
+
239
+ async def _list_skill_files(self, arguments: dict[str, Any]) -> ToolResult:
240
+ package = self.get(_require_str(arguments, "name"))
241
+ files: list[str] = []
242
+ for sub in ("references", "assets"):
243
+ base = package.root / sub
244
+ if not base.is_dir():
245
+ continue
246
+ for path in sorted(base.rglob("*")):
247
+ if path.is_file():
248
+ files.append(path.relative_to(package.root).as_posix())
249
+ return ToolResult(content="\n".join(files) if files else "(空)")
250
+
251
+ async def _read_skill_file(self, arguments: dict[str, Any]) -> ToolResult:
252
+ package = self.get(_require_str(arguments, "name"))
253
+ relpath = _require_str(arguments, "relpath")
254
+ target = _resolve_within(package.root, relpath)
255
+ if not target.is_file():
256
+ raise ToolExecutionError(f"文件不存在: {relpath}")
257
+ try:
258
+ text = target.read_text(encoding="utf-8", errors="replace")
259
+ except OSError as exc:
260
+ raise ToolExecutionError(f"文件读取失败: {relpath}: {exc}") from exc
261
+ if len(text) > _MAX_FILE_CHARS:
262
+ text = text[:_MAX_FILE_CHARS] + "\n[truncated]"
263
+ return ToolResult(content=text)
264
+
265
+
266
+ def _require_str(arguments: dict[str, Any], key: str) -> str:
267
+ value = arguments.get(key)
268
+ if not isinstance(value, str) or not value.strip():
269
+ raise ToolExecutionError(f"参数 {key} 必须是非空字符串")
270
+ return value
271
+
272
+
273
+ def _resolve_within(root: Path, relpath: str) -> Path:
274
+ """把相对路径解析到包内;拒绝绝对路径与越界(含符号链接逃逸)。"""
275
+ candidate = Path(relpath)
276
+ if candidate.is_absolute():
277
+ raise ToolExecutionError(f"拒绝绝对路径: {relpath}")
278
+ root_resolved = root.resolve()
279
+ target = (root_resolved / candidate).resolve()
280
+ if not target.is_relative_to(root_resolved):
281
+ raise ToolExecutionError(f"路径越界: {relpath}")
282
+ return target
283
+
284
+
285
+ def _parse_package(root: Path, skill_file: Path) -> SkillPackage:
286
+ """解析并校验一个 SKILL.md。"""
287
+ try:
288
+ text = skill_file.read_text(encoding="utf-8")
289
+ except OSError as exc:
290
+ raise SkillValidationError(f"SKILL.md 读取失败: {skill_file}: {exc}") from exc
291
+ frontmatter, body = _split_frontmatter(text, skill_file)
292
+ name = frontmatter.get("name")
293
+ description = frontmatter.get("description")
294
+ if not isinstance(name, str) or not name.strip():
295
+ raise SkillValidationError(f"{skill_file} 缺少 name")
296
+ if name != root.name:
297
+ raise SkillValidationError(
298
+ f"{skill_file} 的 name={name!r} 与目录名 {root.name!r} 不一致"
299
+ )
300
+ if not isinstance(description, str) or not description.strip():
301
+ raise SkillValidationError(f"{skill_file} 缺少 description")
302
+ version = frontmatter.get("version", "0.0.0")
303
+ if not isinstance(version, str):
304
+ version = str(version)
305
+ scripts = tuple(
306
+ _parse_script(item, root, skill_file, index)
307
+ for index, item in enumerate(frontmatter.get("scripts") or [])
308
+ )
309
+ return SkillPackage(
310
+ name=name,
311
+ version=version,
312
+ description=description.strip(),
313
+ root=root,
314
+ body=body,
315
+ scripts=scripts,
316
+ )
317
+
318
+
319
+ def _split_frontmatter(text: str, skill_file: Path) -> tuple[dict[str, Any], str]:
320
+ """拆分 YAML frontmatter 与正文。"""
321
+ content = text.lstrip("\ufeff")
322
+ lines = content.splitlines()
323
+ if not lines or lines[0].strip() != "---":
324
+ raise SkillValidationError(f"{skill_file} 缺少 YAML frontmatter")
325
+ end: int | None = None
326
+ for index in range(1, len(lines)):
327
+ if lines[index].strip() == "---":
328
+ end = index
329
+ break
330
+ if end is None:
331
+ raise SkillValidationError(f"{skill_file} 的 frontmatter 未闭合")
332
+ raw = "\n".join(lines[1:end])
333
+ try:
334
+ parsed = yaml.safe_load(raw) or {}
335
+ except yaml.YAMLError as exc:
336
+ raise SkillValidationError(f"{skill_file} 的 frontmatter 非法: {exc}") from exc
337
+ if not isinstance(parsed, dict):
338
+ raise SkillValidationError(f"{skill_file} 的 frontmatter 必须是对象")
339
+ body = "\n".join(lines[end + 1 :]).lstrip("\n")
340
+ return parsed, body
341
+
342
+
343
+ def _parse_script(
344
+ item: Any, root: Path, skill_file: Path, index: int
345
+ ) -> SkillScript:
346
+ """校验 frontmatter 中的一个脚本声明。"""
347
+ if not isinstance(item, dict):
348
+ raise SkillValidationError(f"{skill_file} 的 scripts[{index}] 必须是对象")
349
+ name = item.get("name")
350
+ path = item.get("path")
351
+ args = item.get("args")
352
+ if not isinstance(name, str) or not name.strip():
353
+ raise SkillValidationError(f"{skill_file} 的 scripts[{index}] 缺少 name")
354
+ if not isinstance(path, str) or not path.strip():
355
+ raise SkillValidationError(f"{skill_file} 的 scripts[{index}] 缺少 path")
356
+ if not isinstance(args, dict) or args.get("type") != "object":
357
+ raise SkillValidationError(
358
+ f"{skill_file} 的脚本 {name!r} 缺少合法 args"
359
+ "(必须是 type=object 的 JSON Schema)"
360
+ )
361
+ try:
362
+ _resolve_within(root, path)
363
+ except ToolExecutionError as exc:
364
+ raise SkillValidationError(
365
+ f"{skill_file} 的脚本 {name!r} 路径非法: {exc}"
366
+ ) from exc
367
+ description = item.get("description", "")
368
+ if not isinstance(description, str):
369
+ description = str(description)
370
+ return SkillScript(name=name, description=description, path=path, args=args)
@@ -0,0 +1,161 @@
1
+ """
2
+ Copyright (c) 2021-2026 溢墨修心(Yimo). All Rights Reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+
16
+ Project: yimo
17
+ Author: 溢墨修心(Yimo)
18
+ """
19
+
20
+ # date: 2026-11-10
21
+ """yimo.kit.ai.agent 的公共类型(零可选依赖,未装 fastmcp 也可导入)。"""
22
+
23
+ import json
24
+ from dataclasses import dataclass, field
25
+ from pathlib import Path
26
+ from typing import Any, Literal
27
+
28
+ from yimo.kit.ai.agent.errors import AgentConfigError
29
+ from yimo.kit.ai.messages import Message
30
+
31
+ __all__ = [
32
+ "AgentResult",
33
+ "McpServerConfig",
34
+ "ToolCallRecord",
35
+ "ToolResult",
36
+ "ToolSpec",
37
+ "load_servers",
38
+ ]
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class ToolSpec:
43
+ """工具的模型侧声明(可直接转换为 OpenAI function 结构)。"""
44
+
45
+ name: str
46
+ description: str
47
+ input_schema: dict[str, Any]
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class ToolResult:
52
+ """工具执行结果(回灌给模型的统一形态)。"""
53
+
54
+ content: str
55
+ is_error: bool = False
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class ToolCallRecord:
60
+ """一次工具调用的排障记录(``arguments`` 不写日志原文)。"""
61
+
62
+ name: str
63
+ arguments: dict[str, Any]
64
+ result: ToolResult
65
+ elapsed: float
66
+
67
+
68
+ @dataclass(frozen=True)
69
+ class AgentResult:
70
+ """一轮 Agent 运行的最终结果。"""
71
+
72
+ text: str
73
+ messages: list[Message]
74
+ turns: int
75
+ tool_calls: list[ToolCallRecord]
76
+ stop_reason: Literal["completed", "max_turns", "timeout"]
77
+ truncated: bool = False
78
+
79
+
80
+ @dataclass(frozen=True)
81
+ class McpServerConfig:
82
+ """单个 MCP server 的连接配置。
83
+
84
+ - ``transport="http"``:必须给 ``url``,可选 ``headers``;
85
+ - ``transport="stdio"``:必须给 ``command``,可选 ``args`` / ``env`` / ``cwd``;
86
+ - ``optional=True``:连接失败时跳过该 server 并告警,不阻断 Agent 启动。
87
+ """
88
+
89
+ name: str
90
+ transport: Literal["http", "stdio"] = "http"
91
+ url: str | None = None
92
+ headers: dict[str, str] | None = None
93
+ command: str | None = None
94
+ args: list[str] = field(default_factory=list)
95
+ env: dict[str, str] | None = None
96
+ cwd: str | None = None
97
+ connect_timeout: float = 30.0
98
+ call_timeout: float = 60.0
99
+ tool_prefix: bool = True
100
+ optional: bool = False
101
+ # stdio 子进程是否跨连接保活。默认 False:close() 即断开并终止直接子进程;
102
+ # 设为 True 可复用子进程,但 Agent 退出后可能残留,需调用方自行管理。
103
+ keep_alive: bool = False
104
+
105
+ def __post_init__(self) -> None:
106
+ if not self.name or not self.name.strip():
107
+ raise AgentConfigError("MCP server 配置缺少 name")
108
+ if self.transport == "http":
109
+ if not self.url:
110
+ raise AgentConfigError(f"MCP server {self.name!r} 使用 http 但缺少 url")
111
+ elif self.transport == "stdio":
112
+ if not self.command:
113
+ raise AgentConfigError(
114
+ f"MCP server {self.name!r} 使用 stdio 但缺少 command"
115
+ )
116
+ else:
117
+ raise AgentConfigError(
118
+ f"MCP server {self.name!r} 的 transport 非法: {self.transport!r}"
119
+ )
120
+
121
+ @classmethod
122
+ def from_dict(cls, data: dict[str, Any]) -> "McpServerConfig":
123
+ """从 dict 构造配置(未知键直接报错,避免静默拼错字段)。"""
124
+ allowed = {
125
+ "name",
126
+ "transport",
127
+ "url",
128
+ "headers",
129
+ "command",
130
+ "args",
131
+ "env",
132
+ "cwd",
133
+ "connect_timeout",
134
+ "call_timeout",
135
+ "tool_prefix",
136
+ "optional",
137
+ "keep_alive",
138
+ }
139
+ unknown = sorted(set(data) - allowed)
140
+ if unknown:
141
+ raise AgentConfigError(f"MCP server 配置含未知字段: {unknown}")
142
+ return cls(**data)
143
+
144
+
145
+ def load_servers(path: str | Path) -> list[McpServerConfig]:
146
+ """从 JSON 文件加载 MCP server 列表。
147
+
148
+ 支持两种结构:``[{"name": ...}, ...]`` 或 ``{"servers": [...]}``。
149
+ 配置解释权归调用方,kit 不提供默认路径与全局单例。
150
+ """
151
+ file_path = Path(path)
152
+ try:
153
+ payload = json.loads(file_path.read_text(encoding="utf-8"))
154
+ except (OSError, json.JSONDecodeError) as exc:
155
+ raise AgentConfigError(f"MCP 配置文件读取失败: {file_path}: {exc}") from exc
156
+ items = payload.get("servers") if isinstance(payload, dict) else payload
157
+ if not isinstance(items, list):
158
+ raise AgentConfigError(
159
+ f"MCP 配置文件格式非法(需要数组或 {{'servers': [...]}}): {file_path}"
160
+ )
161
+ return [McpServerConfig.from_dict(item) for item in items]