agent_plugins.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. """Compatibility helpers for Agent Plugins v1 portable directory packages."""
  2. from __future__ import annotations
  3. import ipaddress
  4. import json
  5. import os
  6. import re
  7. import threading
  8. from dataclasses import dataclass
  9. from pathlib import Path
  10. from typing import Any, Dict, Mapping, Tuple
  11. from urllib.parse import urlsplit
  12. from agent.skill_utils import yaml_load
  13. from hermes_platform.declaration import Declaration, parse_declaration
  14. _HERMES_EXTENSION = "com.nousresearch.hermes"
  15. _LIVENESS: dict[str, dict] = {}
  16. def liveness_for(server_name: str) -> dict | None:
  17. """Return a copy of the portable server's liveness declaration."""
  18. value = _LIVENESS.get(server_name)
  19. return dict(value) if value is not None else None
  20. def _set_liveness(server_name: str, value: object) -> None:
  21. if value is None:
  22. _LIVENESS.pop(server_name, None)
  23. elif isinstance(value, dict):
  24. _LIVENESS[server_name] = dict(value)
  25. else:
  26. raise AgentPluginError(f"server '{server_name}' liveness must be an object")
  27. def _clear_liveness(server_name: str) -> None:
  28. _LIVENESS.pop(server_name, None)
  29. @dataclass(frozen=True)
  30. class AgentPluginServerDeclaration:
  31. declaration: Declaration
  32. liveness: dict | None
  33. PLUGIN_SCHEMA_V1 = "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json"
  34. MCP_SCHEMA_V1 = "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json"
  35. _PLUGIN_FIELDS = {"$schema", "name", "version", "description", "author", "homepage", "repository",
  36. "license", "keywords", "extensions"}
  37. _AUTHOR_FIELDS = {"name", "email", "url"}
  38. _STDIO_FIELDS = {"type", "command", "args", "env", "cwd"}
  39. _REMOTE_FIELDS = {"type", "url", "headers"}
  40. _PLUGIN_NAME_RE = re.compile(r"^(?!.*(?:--|\.\.))[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$")
  41. _SKILL_NAME_RE = re.compile(r"^(?!.*--)[a-z0-9]+(?:-[a-z0-9]+)*$")
  42. _PLACEHOLDER_RE = re.compile(r"\$\{(PLUGIN_ROOT|PLUGIN_DATA)\}")
  43. _HEADER_NAME_RE = re.compile(r"^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$")
  44. class AgentPluginError(ValueError):
  45. """Fatal portable manifest validation failure."""
  46. @dataclass(frozen=True)
  47. class AgentPluginDiagnostic:
  48. scope: str
  49. message: str
  50. @dataclass(frozen=True)
  51. class AgentPluginSkill:
  52. name: str
  53. description: str
  54. root: Path
  55. skill_md: Path
  56. frontmatter: Mapping[str, Any]
  57. @dataclass(frozen=True)
  58. class AgentPluginPackage:
  59. name: str
  60. version: str
  61. description: str
  62. root: Path
  63. data_root: Path
  64. manifest: Mapping[str, Any]
  65. skills: tuple[AgentPluginSkill, ...]
  66. mcp_servers: Mapping[str, dict[str, Any]]
  67. server_declarations: Mapping[str, AgentPluginServerDeclaration]
  68. diagnostics: tuple[AgentPluginDiagnostic, ...]
  69. _SERVER_DECLARATION_KEYS = frozenset({"app", "requires", "liveness", "trust", "timeout", "costs", "spend_limit", "cost_unit"})
  70. # Hermes call-policy keys: alone they configure a server, they do not declare an application.
  71. _SERVER_POLICY_KEYS = frozenset({"trust", "timeout", "costs", "spend_limit", "cost_unit"})
  72. def _server_declarations(
  73. manifest: Mapping[str, Any], mcp_servers: Mapping[str, dict[str, Any]],
  74. diagnostics: list[AgentPluginDiagnostic] | None = None,
  75. ) -> dict[str, AgentPluginServerDeclaration]:
  76. namespace = manifest.get("extensions", {}).get(_HERMES_EXTENSION, {})
  77. raw_servers = namespace.get("servers", {})
  78. if not isinstance(raw_servers, dict):
  79. raise AgentPluginError(f"extension '{_HERMES_EXTENSION}'.servers must be an object")
  80. declarations: dict[str, AgentPluginServerDeclaration] = {}
  81. for name, raw in raw_servers.items():
  82. if name not in mcp_servers:
  83. raise AgentPluginError(f"server declaration '{name}' has no matching mcp.json server")
  84. if not isinstance(raw, dict):
  85. raise AgentPluginError(f"server declaration '{name}' must be an object")
  86. # A key added by a newer Hermes must not make the package uninstallable here: the older
  87. # release ignores it with a diagnostic, like unknown top-level fields. A key whose absence
  88. # would be unsafe needs the catalog entry's requires_hermes, not a hard failure on every release:
  89. # plugin.json has no version floor, and install/update by catalog name enforce the entry's
  90. # (plugins_cmd_catalog.refuse_incompatible_catalog_entry / repin_catalog_plugin).
  91. unknown = set(raw) - _SERVER_DECLARATION_KEYS
  92. if unknown:
  93. if diagnostics is not None:
  94. diagnostics.append(AgentPluginDiagnostic(
  95. f"server:{name}", f"ignored unknown keys {sorted(unknown)} (needs a newer Hermes)"))
  96. raw = {key: value for key, value in raw.items() if key not in unknown}
  97. if not raw:
  98. continue
  99. if "liveness" in raw and "app" not in raw and "requires" not in raw:
  100. raise AgentPluginError(f"server declaration '{name}' has liveness without app or requires")
  101. if raw and set(raw) <= _SERVER_POLICY_KEYS:
  102. continue # transport/policy settings alone do not declare an application
  103. try:
  104. declaration = parse_declaration(
  105. name, raw.get("app"), raw.get("requires"),
  106. where=f"plugin.json extension server {name!r}",
  107. )
  108. except ValueError as exc:
  109. raise AgentPluginError(str(exc)) from exc
  110. liveness = raw.get("liveness")
  111. if liveness is not None and not isinstance(liveness, dict):
  112. raise AgentPluginError(f"server declaration '{name}' liveness must be an object")
  113. declarations[name] = AgentPluginServerDeclaration(
  114. declaration=declaration,
  115. liveness=dict(liveness) if liveness is not None else None,
  116. )
  117. return declarations
  118. def _server_trust(manifest: Mapping[str, Any], mcp_servers: Mapping[str, dict[str, Any]]) -> dict[str, str]:
  119. """Servers the package asks Hermes to gate: ``extensions.com.nousresearch.hermes.servers.<name>.trust``.
  120. The package may only narrow access. ``untrusted`` makes every write-capable call to that server
  121. ask the user first (the native ``trust: untrusted`` gate); ``full`` is the default and so changes
  122. nothing. A package can never widen a server the user configured: a ``config.yaml`` server with
  123. the same name replaces the package's entry, trust included.
  124. """
  125. raw_servers = manifest.get("extensions", {}).get(_HERMES_EXTENSION, {}).get("servers", {})
  126. trust: dict[str, str] = {}
  127. for name, raw in (raw_servers.items() if isinstance(raw_servers, dict) else ()):
  128. if not isinstance(raw, dict) or "trust" not in raw or name not in mcp_servers:
  129. continue # shape errors are raised by _server_declarations
  130. value = raw["trust"]
  131. if value not in ("full", "untrusted"):
  132. raise AgentPluginError(f"server declaration '{name}' trust must be 'untrusted' or 'full', not {value!r}")
  133. if value == "untrusted":
  134. trust[name] = value
  135. return trust
  136. def _server_timeouts(manifest: Mapping[str, Any], mcp_servers: Mapping[str, dict[str, Any]]) -> dict[str, float]:
  137. """Translate optional Hermes call deadlines without changing other servers' defaults."""
  138. raw_servers = manifest.get("extensions", {}).get(_HERMES_EXTENSION, {}).get("servers", {})
  139. timeouts: dict[str, float] = {}
  140. for name, raw in (raw_servers.items() if isinstance(raw_servers, dict) else ()):
  141. if not isinstance(raw, dict) or "timeout" not in raw or name not in mcp_servers:
  142. continue
  143. value = raw["timeout"]
  144. if isinstance(value, bool) or not isinstance(value, (int, float)) or not 0 < value <= threading.TIMEOUT_MAX:
  145. raise AgentPluginError(f"server declaration '{name}' timeout must be positive seconds within the platform wait limit")
  146. timeouts[name] = float(value)
  147. return timeouts
  148. def _server_costs(manifest: Mapping[str, Any], mcp_servers: Mapping[str, dict[str, Any]]) -> dict[str, dict[str, Any]]:
  149. """Translate ``costs``/``spend_limit``/``cost_unit`` into the native ``tool_costs``/``spend_limit``/``cost_unit``
  150. keys (``tools.mcp_tool_costs``). A malformed table disables the package: a budget the author declared must
  151. never be dropped while the server still spends."""
  152. from tools.mcp_tool_costs import parse_cost_policy
  153. raw_servers = manifest.get("extensions", {}).get(_HERMES_EXTENSION, {}).get("servers", {})
  154. translated: dict[str, dict[str, Any]] = {}
  155. for name, raw in (raw_servers.items() if isinstance(raw_servers, dict) else ()):
  156. if not isinstance(raw, dict) or name not in mcp_servers:
  157. continue
  158. declared = {key: raw[key] for key in ("costs", "spend_limit", "cost_unit") if key in raw}
  159. if not declared:
  160. continue
  161. try:
  162. parse_cost_policy(declared.get("costs"), declared.get("spend_limit"), declared.get("cost_unit"),
  163. where=f"server declaration '{name}'")
  164. except ValueError as exc:
  165. raise AgentPluginError(str(exc)) from exc
  166. if "costs" in declared:
  167. declared["tool_costs"] = declared.pop("costs")
  168. translated[name] = declared
  169. return translated
  170. def _inside(path: Path, root: Path) -> bool:
  171. try:
  172. return path.resolve(strict=False).is_relative_to(root.resolve(strict=True))
  173. except (OSError, RuntimeError, ValueError):
  174. return False
  175. def _all_str(values) -> bool:
  176. return all(isinstance(v, str) for v in values)
  177. def _str_map(value: object) -> bool:
  178. return isinstance(value, dict) and _all_str(value) and _all_str(value.values())
  179. def _read_json_object(path: Path, *, label: str) -> dict:
  180. try:
  181. value = json.loads(path.read_text(encoding="utf-8-sig"))
  182. except (OSError, UnicodeError, json.JSONDecodeError) as exc:
  183. raise AgentPluginError(f"{label} is not valid readable JSON: {exc}") from exc
  184. if not isinstance(value, dict):
  185. raise AgentPluginError(f"{label} must contain a JSON object")
  186. return value
  187. def _validate_manifest(root: Path) -> tuple[dict, list[AgentPluginDiagnostic]]:
  188. manifest_path = root / "plugin.json"
  189. if not _inside(manifest_path, root) or not manifest_path.is_file():
  190. raise AgentPluginError("plugin.json must be a regular file within the plugin root")
  191. manifest = _read_json_object(manifest_path, label="plugin.json")
  192. diagnostics: list[AgentPluginDiagnostic] = []
  193. for field in sorted(set(manifest) - _PLUGIN_FIELDS):
  194. diagnostics.append(AgentPluginDiagnostic("manifest", f"ignored unknown top-level field: {field}"))
  195. manifest.pop(field)
  196. if manifest.get("$schema") != PLUGIN_SCHEMA_V1:
  197. raise AgentPluginError("plugin.json declares an unsupported or missing Agent Plugins schema")
  198. name = manifest.get("name")
  199. if not isinstance(name, str) or not 1 <= len(name) <= 64 or _PLUGIN_NAME_RE.fullmatch(name) is None:
  200. raise AgentPluginError("plugin.json name does not satisfy v1 constraints")
  201. for field in ("version", "description", "homepage", "repository", "license"):
  202. if field in manifest and not isinstance(manifest[field], str):
  203. raise AgentPluginError(f"plugin.json {field} must be a string")
  204. keywords = manifest.get("keywords", [])
  205. if not isinstance(keywords, list) or not _all_str(keywords):
  206. raise AgentPluginError("plugin.json keywords must be an array of strings")
  207. author = manifest.get("author", {})
  208. if not isinstance(author, dict):
  209. raise AgentPluginError("plugin.json author must be an object")
  210. if set(author) - _AUTHOR_FIELDS or not _all_str(author.values()):
  211. raise AgentPluginError("plugin.json author may contain only string name, email, and url fields")
  212. extensions = manifest.get("extensions", {})
  213. if not isinstance(extensions, dict):
  214. diagnostics.append(AgentPluginDiagnostic("manifest", "ignored non-object extensions field"))
  215. manifest.pop("extensions")
  216. elif any(not isinstance(value, dict) for value in extensions.values()):
  217. raise AgentPluginError("plugin.json extension namespace values must be objects")
  218. return manifest, diagnostics
  219. def _valid_skill_frontmatter(frontmatter: Mapping[str, Any], directory_name: str) -> str | None:
  220. name = frontmatter.get("name")
  221. if (not isinstance(name, str) or name != directory_name or not 1 <= len(name) <= 64
  222. or _SKILL_NAME_RE.fullmatch(name) is None):
  223. return "name must match the directory and satisfy Agent Skills constraints"
  224. description = frontmatter.get("description")
  225. if not isinstance(description, str) or not 1 <= len(description) <= 1024:
  226. return "description must be a non-empty string of at most 1024 characters"
  227. if "license" in frontmatter and not isinstance(frontmatter["license"], str):
  228. return "license must be a string"
  229. if "compatibility" in frontmatter:
  230. compatibility = frontmatter["compatibility"]
  231. if not isinstance(compatibility, str) or not 1 <= len(compatibility) <= 500:
  232. return "compatibility must be a string of 1 to 500 characters"
  233. if "metadata" in frontmatter and not _str_map(frontmatter["metadata"]):
  234. return "metadata must map string keys to string values"
  235. if "allowed-tools" in frontmatter and not isinstance(frontmatter["allowed-tools"], str):
  236. return "allowed-tools must be a string"
  237. return None
  238. def _parse_skill_frontmatter(skill_md: Path) -> dict:
  239. """Read SKILL.md and return its YAML frontmatter object; raises ValueError/OSError/UnicodeError."""
  240. content = skill_md.read_text(encoding="utf-8-sig").lstrip("\ufeff")
  241. if not content.startswith("---"):
  242. raise ValueError("missing YAML frontmatter")
  243. end_match = re.search(r"\n---\s*\n", content[3:])
  244. if end_match is None:
  245. raise ValueError("unterminated YAML frontmatter")
  246. try:
  247. parsed = yaml_load(content[3 : end_match.start() + 3])
  248. except Exception as exc:
  249. raise ValueError(f"invalid YAML frontmatter: {exc}") from exc
  250. if not isinstance(parsed, dict):
  251. raise ValueError("YAML frontmatter must be an object")
  252. return parsed
  253. def _discover_skills(root: Path, diagnostics: list[AgentPluginDiagnostic]) -> tuple[AgentPluginSkill, ...]:
  254. skills_root = root / "skills"
  255. if not skills_root.exists() and not skills_root.is_symlink():
  256. return ()
  257. if not _inside(skills_root, root) or not skills_root.is_dir():
  258. diagnostics.append(AgentPluginDiagnostic("skills", "skills must be an in-root directory"))
  259. return ()
  260. try:
  261. children = sorted(skills_root.iterdir(), key=lambda path: path.name)
  262. except OSError as exc:
  263. diagnostics.append(AgentPluginDiagnostic("skills", f"cannot list skills: {exc}"))
  264. return ()
  265. skills: list[AgentPluginSkill] = []
  266. for child in children:
  267. skill_md = child / "SKILL.md"
  268. if not child.is_dir() or not skill_md.exists():
  269. continue
  270. if not _inside(skill_md, root) or not skill_md.is_file():
  271. error = "SKILL.md must be a regular in-root file"
  272. else:
  273. try:
  274. frontmatter = _parse_skill_frontmatter(skill_md)
  275. except (OSError, UnicodeError, ValueError) as exc:
  276. error = f"invalid SKILL.md: {exc}"
  277. else:
  278. error = _valid_skill_frontmatter(frontmatter, child.name)
  279. if error:
  280. diagnostics.append(AgentPluginDiagnostic(f"skill:{child.name}", error))
  281. continue
  282. skills.append(AgentPluginSkill(
  283. name=child.name, description=frontmatter["description"],
  284. root=child.resolve(strict=True), skill_md=skill_md.resolve(strict=True),
  285. frontmatter=dict(frontmatter)))
  286. return tuple(skills)
  287. def _expand(value: str, plugin_root: Path, data_root: Path) -> str:
  288. replacements = {"PLUGIN_ROOT": str(plugin_root), "PLUGIN_DATA": str(data_root)}
  289. return _PLACEHOLDER_RE.sub(lambda match: replacements[match.group(1)], value)
  290. def _resolve_scoped_path(value: str, plugin_root: Path, data_root: Path, *,
  291. expand_placeholders: bool = True) -> Path:
  292. expanded = _expand(value, plugin_root, data_root) if expand_placeholders else value
  293. if value.startswith("./"):
  294. base, candidate = plugin_root, plugin_root / expanded[2:]
  295. elif value == "${PLUGIN_ROOT}" or value.startswith("${PLUGIN_ROOT}/"):
  296. base, candidate = plugin_root, Path(expanded)
  297. elif value == "${PLUGIN_DATA}" or value.startswith("${PLUGIN_DATA}/"):
  298. base, candidate = data_root, Path(expanded)
  299. else:
  300. raise ValueError("path must start with ./, ${PLUGIN_ROOT}, or ${PLUGIN_DATA}")
  301. resolved = candidate.resolve(strict=False)
  302. try:
  303. resolved.relative_to(base.resolve(strict=False))
  304. except (OSError, RuntimeError, ValueError) as exc:
  305. raise ValueError("path escapes its resolved root") from exc
  306. return resolved
  307. def _validate_headers(headers: object) -> bool:
  308. if not isinstance(headers, dict):
  309. return headers is None
  310. names = [name for name in headers if isinstance(name, str) and _HEADER_NAME_RE.fullmatch(name)]
  311. values = headers.values()
  312. return (len(names) == len(headers) and len({name.lower() for name in names}) == len(names)
  313. and all(isinstance(v, str) and "\r" not in v and "\n" not in v for v in values))
  314. def _validate_remote_url(url: object) -> str:
  315. """Validate a portable remote MCP URL per Agent Plugins v1 §7.2.1 and return it: absolute
  316. http(s), no user info, no fragment; HTTP only for ``localhost``/loopback IP. No expansion."""
  317. if not isinstance(url, str) or not url:
  318. raise ValueError("url must be a non-empty string")
  319. try:
  320. parsed = urlsplit(url)
  321. except ValueError as exc:
  322. raise ValueError(f"url is not parseable: {exc}") from exc
  323. scheme = parsed.scheme.lower()
  324. if scheme not in {"http", "https"}:
  325. raise ValueError("url scheme must be http or https")
  326. if parsed.username is not None or parsed.password is not None:
  327. raise ValueError("url must not contain user information")
  328. if parsed.fragment:
  329. raise ValueError("url must not contain a fragment")
  330. host = parsed.hostname
  331. if not host:
  332. raise ValueError("url must have a host")
  333. if scheme == "http" and host != "localhost":
  334. try:
  335. loopback = ipaddress.ip_address(host).is_loopback
  336. except ValueError:
  337. loopback = False
  338. if not loopback:
  339. raise ValueError("non-loopback url must use https")
  340. return url
  341. def _translate_remote(config: Mapping[str, Any]) -> dict[str, Any]:
  342. """Translate a portable ``streamable-http`` entry into native MCP config. The v1 spec requires
  343. ``strict_redirect_headers``: drop configured headers on any cross-origin redirect."""
  344. if set(config) - _REMOTE_FIELDS:
  345. raise ValueError("unknown remote field")
  346. url = _validate_remote_url(config.get("url"))
  347. if not _validate_headers(config.get("headers")):
  348. raise ValueError("invalid headers")
  349. translated: dict[str, Any] = {"url": url, "strict_redirect_headers": True}
  350. if config.get("headers"):
  351. translated["headers"] = dict(config["headers"])
  352. return translated
  353. def _translate_stdio(config: Mapping[str, Any], plugin_root: Path, data_root: Path,
  354. create_data: bool = False) -> dict[str, Any]:
  355. if set(config) - _STDIO_FIELDS:
  356. raise ValueError("unknown stdio field")
  357. command = config.get("command")
  358. if not isinstance(command, str) or not command or "\x00" in command:
  359. raise ValueError("command must be a non-empty executable token")
  360. if command.startswith("./"):
  361. command = str(_resolve_scoped_path(command, plugin_root, data_root,
  362. expand_placeholders=False))
  363. elif any(character.isspace() for character in command):
  364. raise ValueError("command must contain one executable token")
  365. elif "/" in command or "\\" in command or command in {".", ".."}:
  366. raise ValueError("command must be a bare executable or begin with ./")
  367. args = config.get("args", [])
  368. if not isinstance(args, list) or not _all_str(args):
  369. raise ValueError("args must be an array of strings")
  370. env = config.get("env", {})
  371. if not _str_map(env):
  372. raise ValueError("env must map string keys to string values")
  373. if {"PLUGIN_ROOT", "PLUGIN_DATA"} & {key.upper() if os.name == "nt" else key for key in env}:
  374. raise ValueError("PLUGIN_ROOT and PLUGIN_DATA are reserved")
  375. cwd = config.get("cwd")
  376. if cwd is not None and not isinstance(cwd, str):
  377. raise ValueError("cwd must be a string")
  378. cwd_path = plugin_root if cwd is None else _resolve_scoped_path(cwd, plugin_root, data_root)
  379. if create_data:
  380. data_root.mkdir(parents=True, exist_ok=True)
  381. # The MCP client starts stdio servers with this cwd. Create only data-root descendants;
  382. # plugin-root paths remain package-owned and are never made writable by discovery.
  383. if cwd_path.is_relative_to(data_root):
  384. cwd_path.mkdir(parents=True, exist_ok=True)
  385. translated_env = {**{key: _expand(value, plugin_root, data_root) for key, value in env.items()},
  386. "PLUGIN_ROOT": str(plugin_root), "PLUGIN_DATA": str(data_root)}
  387. return {"command": command, "args": [_expand(value, plugin_root, data_root) for value in args],
  388. "env": translated_env, "cwd": str(cwd_path)}
  389. def _reject_sse(server: Mapping[str, Any]) -> None:
  390. if (set(server) - _REMOTE_FIELDS or not isinstance(server.get("url"), str)
  391. or not server.get("url") or not _validate_headers(server.get("headers"))):
  392. raise ValueError("invalid remote entry")
  393. raise ValueError("portable sse transport is not supported")
  394. def _discover_mcp(root: Path, data_root: Path, diagnostics: list[AgentPluginDiagnostic], *,
  395. create_data: bool = True) -> dict[str, dict[str, Any]]:
  396. mcp_path = root / "mcp.json"
  397. if not mcp_path.exists() and not mcp_path.is_symlink():
  398. return {}
  399. try: # file-level problems (incl. AgentPluginError from the JSON read) -> one "mcp" diagnostic
  400. if not _inside(mcp_path, root) or not mcp_path.is_file():
  401. raise ValueError("mcp.json must be a regular in-root file")
  402. config = _read_json_object(mcp_path, label="mcp.json")
  403. if set(config) != {"$schema", "mcpServers"}:
  404. raise ValueError("mcp.json has an invalid top-level shape")
  405. if config.get("$schema") != MCP_SCHEMA_V1:
  406. raise ValueError("mcp.json declares an unsupported schema")
  407. servers = config.get("mcpServers")
  408. if not isinstance(servers, dict):
  409. raise ValueError("mcpServers must be an object")
  410. except ValueError as exc:
  411. diagnostics.append(AgentPluginDiagnostic("mcp", str(exc)))
  412. return {}
  413. translators = {"stdio": lambda server: _translate_stdio(server, root, data_root, create_data),
  414. "streamable-http": _translate_remote, "sse": _reject_sse}
  415. translated: dict[str, dict[str, Any]] = {}
  416. for name, server in servers.items():
  417. try:
  418. if not isinstance(name, str) or not name or not isinstance(server, dict):
  419. raise ValueError("invalid server entry")
  420. translate = translators.get(server.get("type"))
  421. if translate is None:
  422. raise ValueError("unknown MCP server type")
  423. translated[name] = translate(server)
  424. except (OSError, ValueError) as exc:
  425. diagnostics.append(AgentPluginDiagnostic(f"mcp:{name}", str(exc)))
  426. return translated
  427. def _validate_root(plugin_root: Path) -> tuple[Path, dict, list[AgentPluginDiagnostic]]:
  428. root = Path(plugin_root).resolve(strict=True)
  429. if not root.is_dir():
  430. raise AgentPluginError("plugin root must be a directory")
  431. return root, *_validate_manifest(root)
  432. def load_agent_plugin(plugin_root: Path, data_root: Path) -> AgentPluginPackage:
  433. """Validate and translate one installed Agent Plugins v1 package."""
  434. root, manifest, diagnostics = _validate_root(plugin_root)
  435. resolved_data = Path(data_root).resolve(strict=False)
  436. skills = _discover_skills(root, diagnostics)
  437. mcp_servers = _discover_mcp(root, resolved_data, diagnostics)
  438. for name, tier in _server_trust(manifest, mcp_servers).items():
  439. mcp_servers[name] = {**mcp_servers[name], "trust": tier}
  440. for name, timeout in _server_timeouts(manifest, mcp_servers).items():
  441. mcp_servers[name] = {**mcp_servers[name], "timeout": timeout}
  442. for name, costs in _server_costs(manifest, mcp_servers).items():
  443. mcp_servers[name] = {**mcp_servers[name], **costs}
  444. server_declarations = _server_declarations(manifest, mcp_servers, diagnostics)
  445. return AgentPluginPackage(
  446. name=manifest["name"], version=manifest.get("version", ""),
  447. description=manifest.get("description", ""), root=root, data_root=resolved_data,
  448. manifest=dict(manifest), skills=skills, mcp_servers=mcp_servers,
  449. server_declarations=server_declarations,
  450. diagnostics=tuple(diagnostics),
  451. )
  452. def manifest_hermes_extension(manifest: Any) -> dict:
  453. """``extensions.com.nousresearch.hermes`` of a parsed ``plugin.json`` (Agent Plugins v1 forbids
  454. unknown top-level fields, so Hermes-specific fields such as ``config_keys`` live here), else ``{}``."""
  455. extensions = manifest.get("extensions") if isinstance(manifest, dict) else None
  456. hermes = extensions.get(_HERMES_EXTENSION) if isinstance(extensions, dict) else None
  457. return hermes if isinstance(hermes, dict) else {}
  458. def manifest_config_schema(manifest: Any) -> Any:
  459. """Raw ``extensions.com.nousresearch.hermes.config_schema`` of a parsed ``plugin.json``, else
  460. ``None``. Unvalidated: the settings form filters it, the loader and ``plugins validate`` report
  461. what is malformed."""
  462. return manifest_hermes_extension(manifest).get("config_schema")
  463. def read_agent_plugin_manifest(plugin_root: Path) -> tuple[dict, tuple[AgentPluginDiagnostic, ...]]:
  464. """Validate only root ``plugin.json`` without discovering components."""
  465. _root, manifest, diagnostics = _validate_root(plugin_root)
  466. return manifest, tuple(diagnostics)
  467. def has_enabled_agent_plugin_mcp(raw_config: Mapping[str, Any]) -> bool:
  468. """Import-compatible wrapper for the shared PluginManager MCP probe; directory scanning lives
  469. in :mod:`hermes_cli.plugins` so startup gating and full plugin discovery cannot drift apart."""
  470. from hermes_cli.plugins import has_enabled_agent_plugin_mcp as _probe
  471. return _probe(raw_config)