discord_tool.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. """Discord server introspection and management tool (REST API + bot token).
  2. The model-visible schema is filtered by two gates: privileged intents from GET /applications/@me
  3. (search_members / member_info need GUILD_MEMBERS; fetch_messages / list_pins are annotated when
  4. MESSAGE_CONTENT is missing) and the ``discord.server_actions`` config allowlist. Per-guild
  5. permissions are NOT pre-checked — a call-time 403 is mapped to guidance by :func:`_enrich_403`.
  6. """
  7. import functools
  8. import hashlib
  9. import json
  10. import logging
  11. import threading
  12. import time
  13. import urllib.error
  14. import urllib.parse
  15. import urllib.request
  16. from pathlib import Path
  17. from typing import Any, Dict, List, Optional
  18. from agent.secret_scope import get_secret
  19. from tools.registry import registry, tool_error
  20. logger = logging.getLogger(__name__)
  21. DISCORD_API_BASE = "https://discord.com/api/v10"
  22. _DISCORD_RESPONSE_BODY_MAX_BYTES = 4 * 1024 * 1024
  23. _DISCORD_ERROR_BODY_MAX_BYTES = 64 * 1024
  24. # Application flag bits (GET /applications/@me → "flags"); the *_LIMITED bit is the
  25. # <100-guild variant of the same intent.
  26. _FLAGS_GUILD_MEMBERS = (1 << 14) | (1 << 15)
  27. _FLAGS_MESSAGE_CONTENT = (1 << 18) | (1 << 19)
  28. class DiscordAPIError(Exception):
  29. def __init__(self, status: int, body: str):
  30. self.status = status
  31. self.body = body
  32. super().__init__(f"Discord API error {status}: {body}")
  33. def _read_limited_response_body(source: Any, limit: int, *, label: str) -> bytes:
  34. body = source.read(limit + 1)
  35. if len(body) > limit:
  36. raise DiscordAPIError(502, f"Discord API {label} exceeded {limit} bytes.")
  37. return body
  38. def _get_bot_token() -> Optional[str]:
  39. """Resolve the Discord bot token under the active profile secret scope."""
  40. return (get_secret("DISCORD_BOT_TOKEN", "") or "").strip() or None
  41. def _discord_request(
  42. method: str, path: str, token: str, params: Optional[dict[str, str]] = None,
  43. body: Optional[dict[str, Any]] = None, timeout: int = 15) -> Any:
  44. """Make a request to the Discord REST API."""
  45. url = f"{DISCORD_API_BASE}{path}"
  46. if params:
  47. url += "?" + urllib.parse.urlencode(params)
  48. req = urllib.request.Request(
  49. url, data=None if body is None else json.dumps(body).encode("utf-8"), method=method,
  50. headers={
  51. "Authorization": f"Bot {token}", "Content-Type": "application/json",
  52. "User-Agent": "Hermes-Agent (https://github.com/NousResearch/hermes-agent)"})
  53. try:
  54. with urllib.request.urlopen(req, timeout=timeout) as resp:
  55. if resp.status == 204:
  56. return None
  57. body = _read_limited_response_body(resp, _DISCORD_RESPONSE_BODY_MAX_BYTES, label="response body")
  58. return json.loads(body.decode("utf-8"))
  59. except urllib.error.HTTPError as e:
  60. try:
  61. error_body = _read_limited_response_body(
  62. e, _DISCORD_ERROR_BODY_MAX_BYTES, label="error body").decode("utf-8", errors="replace")
  63. except DiscordAPIError as too_large:
  64. error_body = too_large.body
  65. except Exception:
  66. error_body = ""
  67. raise DiscordAPIError(e.code, error_body) from e
  68. _CHANNEL_TYPE_NAMES = {
  69. 0: "text", 2: "voice", 4: "category", 5: "announcement", 10: "announcement_thread",
  70. 11: "public_thread", 12: "private_thread", 13: "stage", 15: "forum", 16: "media"}
  71. def _channel_type_name(type_id: int) -> str:
  72. return _CHANNEL_TYPE_NAMES.get(type_id, f"unknown({type_id})")
  73. # ── capability detection (application intents) ──────────────────────────────
  74. # Per-token in-process cache: the app/me endpoint is hit at most once per process.
  75. _capability_cache: dict[str, dict[str, Any]] = {}
  76. # Privileged intents change only when the user flips them in the Developer Portal, so
  77. # 24h disk staleness is harmless: a hidden action re-appears on the next refresh; an
  78. # exposed action the bot lost fails at call time with an enriched 403.
  79. _CAPABILITY_DISK_TTL_SECONDS = 24 * 3600
  80. # One background detection per (process, token) at most.
  81. _capability_bg_started: set = set()
  82. _capability_bg_lock = threading.Lock()
  83. # Permissive default (``detected`` False = detection failed/pending): all actions
  84. # exposed, call-time 403s mapped to guidance by ``_enrich_403``.
  85. _PERMISSIVE_CAPS = {"has_members_intent": True, "has_message_content": True, "detected": False}
  86. def _capability_disk_cache_path() -> Path:
  87. from hermes_constants import get_hermes_home
  88. return get_hermes_home() / "cache" / "discord_capabilities.json"
  89. def _token_cache_key(token: str) -> str:
  90. """Stable non-reversible cache key for a bot token."""
  91. return hashlib.sha256(token.encode("utf-8")).hexdigest()[:16]
  92. def _read_caps_file(path: Path) -> dict[str, Any]:
  93. """Disk cache contents ({token_key: {"caps", "ts"}}); {} when missing/corrupt."""
  94. try:
  95. with path.open("r", encoding="utf-8-sig") as f:
  96. data = json.load(f)
  97. return data if isinstance(data, dict) else {}
  98. except Exception:
  99. return {}
  100. def _load_caps_from_disk(token: str) -> Optional[dict[str, Any]]:
  101. """Return fresh disk-cached capabilities for *token*, or None."""
  102. try:
  103. entry = _read_caps_file(_capability_disk_cache_path()).get(_token_cache_key(token))
  104. if not isinstance(entry, dict) or time.time() - float(entry.get("ts", 0)) > _CAPABILITY_DISK_TTL_SECONDS:
  105. return None
  106. caps = entry.get("caps")
  107. return caps if isinstance(caps, dict) and "has_members_intent" in caps else None
  108. except Exception:
  109. return None
  110. def _save_caps_to_disk(token: str, caps: dict[str, Any]) -> None:
  111. try:
  112. path = _capability_disk_cache_path()
  113. path.parent.mkdir(parents=True, exist_ok=True)
  114. data = _read_caps_file(path)
  115. data[_token_cache_key(token)] = {"caps": caps, "ts": time.time()}
  116. tmp = path.with_suffix(".json.tmp")
  117. with tmp.open("w", encoding="utf-8") as f:
  118. json.dump(data, f)
  119. tmp.replace(path)
  120. except Exception:
  121. logger.debug("discord capability disk-cache write failed", exc_info=True)
  122. def _detect_capabilities_nonblocking(token: str) -> dict[str, Any]:
  123. """Schema-build lookup: in-process cache → fresh disk cache → permissive default plus a
  124. fire-and-forget background detection that fills the disk cache for the NEXT process
  125. (the ~2-5s blocking HTTPS call must stay off the cold-start critical path)."""
  126. cached = _capability_cache.get(token)
  127. if cached is not None:
  128. return cached
  129. disk = _load_caps_from_disk(token)
  130. if disk is not None:
  131. _capability_cache[token] = disk
  132. return disk
  133. # Cold start — pin the permissive default for THIS process: schemas must not change
  134. # between agent inits within a live process or the per-conversation prompt cache breaks.
  135. caps_default = dict(_PERMISSIVE_CAPS)
  136. _capability_cache[token] = caps_default
  137. with _capability_bg_lock:
  138. if token not in _capability_bg_started:
  139. _capability_bg_started.add(token)
  140. def _bg_detect() -> None:
  141. try:
  142. caps = _fetch_capabilities(token)
  143. if caps.get("detected"):
  144. _save_caps_to_disk(token, caps)
  145. except Exception:
  146. logger.debug("background discord capability detection failed", exc_info=True)
  147. threading.Thread(target=_bg_detect, name="discord-caps-detect", daemon=True).start()
  148. return caps_default
  149. def _fetch_capabilities(token: str) -> dict[str, Any]:
  150. """Fetch capabilities from GET /applications/@me. Pure network fetch — never touches
  151. the in-process cache (background detection must not mutate schemas mid-process).
  152. Detection failure is permissive."""
  153. caps: dict[str, Any] = dict(_PERMISSIVE_CAPS)
  154. try:
  155. app = _discord_request("GET", "/applications/@me", token, timeout=5)
  156. flags = int(app.get("flags", 0) or 0)
  157. caps["has_members_intent"] = bool(flags & _FLAGS_GUILD_MEMBERS)
  158. caps["has_message_content"] = bool(flags & _FLAGS_MESSAGE_CONTENT)
  159. caps["detected"] = True
  160. except Exception as exc: # nosec — detection is best-effort
  161. logger.info("Discord capability detection failed (%s); exposing all actions.", exc)
  162. return caps
  163. def _detect_capabilities(token: str, *, force: bool = False) -> dict[str, Any]:
  164. """Blocking detection via GET /applications/@me, cached per token (the warm-up path;
  165. schema builds use the non-blocking variant). ``force`` re-fetches."""
  166. if token in _capability_cache and not force:
  167. return _capability_cache[token]
  168. caps = _fetch_capabilities(token)
  169. _capability_cache[token] = caps
  170. return caps
  171. def _reset_capability_cache() -> None:
  172. """Test hook: clear the detection cache."""
  173. global _capability_cache, _capability_bg_started
  174. _capability_cache = {}
  175. with _capability_bg_lock:
  176. _capability_bg_started = set()
  177. # ── action implementations ───────────────────────────────────────────────────
  178. def _listing(key: str, items: list[dict[str, Any]]) -> str:
  179. return json.dumps({key: items, "count": len(items)})
  180. def _member_summary(m: dict[str, Any], *, full: bool) -> dict[str, Any]:
  181. """Member row; ``full`` adds the avatar/join fields member_info exposes
  182. (key order is part of the result text, so the two shapes stay explicit)."""
  183. user = m.get("user", {})
  184. row = {
  185. "user_id": user.get("id"), "username": user.get("username"), "display_name": user.get("global_name"),
  186. "nickname": m.get("nick"), "avatar": user.get("avatar"), "bot": user.get("bot", False),
  187. "roles": m.get("roles", []), "joined_at": m.get("joined_at"), "premium_since": m.get("premium_since")}
  188. return row if full else {k: v for k, v in row.items() if k not in ("avatar", "joined_at", "premium_since")}
  189. def _message_summary(msg: dict[str, Any]) -> dict[str, Any]:
  190. author = msg.get("author", {})
  191. return {
  192. "id": msg["id"], "content": msg.get("content", ""),
  193. "author": {
  194. "id": author.get("id"), "username": author.get("username"),
  195. "display_name": author.get("global_name"), "bot": author.get("bot", False)},
  196. "timestamp": msg.get("timestamp"), "edited_timestamp": msg.get("edited_timestamp"),
  197. "attachments": [
  198. {"filename": a.get("filename"), "url": a.get("url"), "size": a.get("size")}
  199. for a in msg.get("attachments", [])],
  200. "reactions": [
  201. {"emoji": r.get("emoji", {}).get("name"), "count": r.get("count", 0)}
  202. for r in msg.get("reactions", [])] if msg.get("reactions") else [],
  203. "pinned": msg.get("pinned", False)}
  204. def _limit_param(limit: Any, default: int) -> str:
  205. """Discord caps list endpoints at 100 per page."""
  206. try:
  207. return str(min(int(limit), 100))
  208. except (TypeError, ValueError):
  209. return str(min(default, 100))
  210. def _list_guilds(token: str, **_kwargs: Any) -> str:
  211. guilds = _discord_request("GET", "/users/@me/guilds", token)
  212. return _listing("guilds", [
  213. {
  214. "id": g["id"], "name": g["name"], "icon": g.get("icon"),
  215. "owner": g.get("owner", False), "permissions": g.get("permissions")}
  216. for g in guilds])
  217. def _server_info(token: str, guild_id: str, **_kwargs: Any) -> str:
  218. g = _discord_request("GET", f"/guilds/{guild_id}", token, params={"with_counts": "true"})
  219. return json.dumps({
  220. "id": g["id"], "name": g["name"], "description": g.get("description"), "icon": g.get("icon"),
  221. "owner_id": g.get("owner_id"), "member_count": g.get("approximate_member_count"),
  222. "online_count": g.get("approximate_presence_count"), "features": g.get("features", []),
  223. "premium_tier": g.get("premium_tier"), "premium_subscription_count": g.get("premium_subscription_count"),
  224. "verification_level": g.get("verification_level")})
  225. def _list_channels(token: str, guild_id: str, **_kwargs: Any) -> str:
  226. """All channels grouped by category (uncategorized first), each sorted by position."""
  227. channels = _discord_request("GET", f"/guilds/{guild_id}/channels", token)
  228. cats = sorted((ch for ch in channels if ch["type"] == 4), key=lambda c: c.get("position", 0))
  229. groups: dict[Optional[str], list[dict[str, Any]]] = {None: [], **{c["id"]: [] for c in cats}}
  230. for ch in channels:
  231. if ch["type"] == 4: # category
  232. continue
  233. parent = ch.get("parent_id")
  234. groups[parent if parent in groups else None].append({
  235. "id": ch["id"], "name": ch.get("name", ""), "type": _channel_type_name(ch["type"]),
  236. "position": ch.get("position", 0), "topic": ch.get("topic"), "nsfw": ch.get("nsfw", False)})
  237. for group in groups.values():
  238. group.sort(key=lambda c: c["position"])
  239. result = [{"category": None, "channels": groups[None]}] if groups[None] else []
  240. result += [{"category": {"id": c["id"], "name": c["name"]}, "channels": groups[c["id"]]} for c in cats]
  241. return json.dumps({"channel_groups": result, "total_channels": sum(len(g["channels"]) for g in result)})
  242. def _channel_info(token: str, channel_id: str, **_kwargs: Any) -> str:
  243. ch = _discord_request("GET", f"/channels/{channel_id}", token)
  244. return json.dumps({
  245. "id": ch["id"], "name": ch.get("name"), "type": _channel_type_name(ch["type"]),
  246. "guild_id": ch.get("guild_id"), "topic": ch.get("topic"), "nsfw": ch.get("nsfw", False),
  247. "position": ch.get("position"), "parent_id": ch.get("parent_id"),
  248. "rate_limit_per_user": ch.get("rate_limit_per_user", 0), "last_message_id": ch.get("last_message_id")})
  249. def _list_roles(token: str, guild_id: str, **_kwargs: Any) -> str:
  250. roles = _discord_request("GET", f"/guilds/{guild_id}/roles", token)
  251. return _listing("roles", [
  252. {
  253. "id": r["id"], "name": r["name"],
  254. "color": f"#{r.get('color', 0):06x}" if r.get("color") else None,
  255. "position": r.get("position", 0), "mentionable": r.get("mentionable", False),
  256. "managed": r.get("managed", False), "member_count": r.get("member_count"),
  257. "hoist": r.get("hoist", False)}
  258. for r in sorted(roles, key=lambda r: r.get("position", 0), reverse=True)])
  259. def _member_info(token: str, guild_id: str, user_id: str, **_kwargs: Any) -> str:
  260. m = _discord_request("GET", f"/guilds/{guild_id}/members/{user_id}", token)
  261. return json.dumps(_member_summary(m, full=True))
  262. def _search_members(token: str, guild_id: str, query: str, limit: int = 20, **_kwargs: Any) -> str:
  263. """Name-prefix member search (requires the GUILD_MEMBERS intent)."""
  264. params = {"query": query, "limit": _limit_param(limit, 20)}
  265. members = _discord_request("GET", f"/guilds/{guild_id}/members/search", token, params=params)
  266. return _listing("members", [_member_summary(m, full=False) for m in members])
  267. def _fetch_messages(
  268. token: str, channel_id: str, limit: int = 50,
  269. before: Optional[str] = None, after: Optional[str] = None, **_kwargs: Any) -> str:
  270. """``before``/``after`` are message snowflakes for reverse/forward pagination."""
  271. params: dict[str, str] = {"limit": _limit_param(limit, 50)}
  272. if before:
  273. params["before"] = before
  274. if after:
  275. params["after"] = after
  276. messages = _discord_request("GET", f"/channels/{channel_id}/messages", token, params=params)
  277. return _listing("messages", [_message_summary(msg) for msg in messages])
  278. def _list_pins(token: str, channel_id: str, **_kwargs: Any) -> str:
  279. """Pinned messages (content truncated for overview)."""
  280. messages = _discord_request("GET", f"/channels/{channel_id}/pins", token)
  281. return _listing("pinned_messages", [
  282. {
  283. "id": msg["id"], "content": msg.get("content", "")[:200],
  284. "author": msg.get("author", {}).get("username"), "timestamp": msg.get("timestamp")}
  285. for msg in messages])
  286. def _create_thread(
  287. token: str, channel_id: str, name: str, message_id: Optional[str] = None,
  288. auto_archive_duration: int = 1440, **_kwargs: Any) -> str:
  289. """Create a thread — anchored to ``message_id`` when given, else standalone public."""
  290. body: dict[str, Any] = {"name": name, "auto_archive_duration": auto_archive_duration}
  291. path = f"/channels/{channel_id}/threads"
  292. if message_id:
  293. path = f"/channels/{channel_id}/messages/{message_id}/threads"
  294. else:
  295. body["type"] = 11 # PUBLIC_THREAD
  296. thread = _discord_request("POST", path, token, body=body)
  297. return json.dumps({"success": True, "thread_id": thread["id"], "name": thread.get("name")})
  298. def _mutation(method: str, path: str, message: str):
  299. """Body-less write action: ``path``/``message`` are format templates over the action kwargs."""
  300. def _action(token: str, **kw: Any) -> str:
  301. _discord_request(method, path.format(**kw), token)
  302. return json.dumps({"success": True, "message": message.format(**kw)})
  303. return _action
  304. _pin_message = _mutation("PUT", "/channels/{channel_id}/pins/{message_id}", "Message {message_id} pinned.")
  305. _unpin_message = _mutation("DELETE", "/channels/{channel_id}/pins/{message_id}", "Message {message_id} unpinned.")
  306. _delete_message = _mutation(
  307. "DELETE", "/channels/{channel_id}/messages/{message_id}", "Message {message_id} deleted.")
  308. _add_role = _mutation(
  309. "PUT", "/guilds/{guild_id}/members/{user_id}/roles/{role_id}", "Role {role_id} added to user {user_id}.")
  310. _remove_role = _mutation(
  311. "DELETE", "/guilds/{guild_id}/members/{user_id}/roles/{role_id}",
  312. "Role {role_id} removed from user {user_id}.")
  313. # ── action dispatch + metadata ───────────────────────────────────────────────
  314. # Single source of truth: (action, handler, required-param signature, description). Order is
  315. # the schema/enum order; the signature drives runtime required-param validation.
  316. _ACTION_MANIFEST = [
  317. ("list_guilds", _list_guilds, "()", "list servers the bot is in"),
  318. ("server_info", _server_info, "(guild_id)", "server details + member counts"),
  319. ("list_channels", _list_channels, "(guild_id)", "all channels grouped by category"),
  320. ("channel_info", _channel_info, "(channel_id)", "single channel details"),
  321. ("list_roles", _list_roles, "(guild_id)", "roles sorted by position"),
  322. ("member_info", _member_info, "(guild_id, user_id)", "lookup a specific member"),
  323. ("search_members", _search_members, "(guild_id, query)", "find members by name prefix"),
  324. ("fetch_messages", _fetch_messages, "(channel_id)", "recent messages; optional before/after snowflakes"),
  325. ("list_pins", _list_pins, "(channel_id)", "pinned messages in a channel"),
  326. ("pin_message", _pin_message, "(channel_id, message_id)", "pin a message"),
  327. ("unpin_message", _unpin_message, "(channel_id, message_id)", "unpin a message"),
  328. ("delete_message", _delete_message, "(channel_id, message_id)", "delete a message"),
  329. ("create_thread", _create_thread, "(channel_id, name)", "create a public thread; optional message_id anchor"),
  330. ("add_role", _add_role, "(guild_id, user_id, role_id)", "assign a role"),
  331. ("remove_role", _remove_role, "(guild_id, user_id, role_id)", "remove a role"),
  332. ]
  333. _ACTIONS = {name: fn for name, fn, _sig, _desc in _ACTION_MANIFEST}
  334. _REQUIRED_PARAMS: dict[str, list[str]] = {
  335. name: [p.strip() for p in sig.strip("()").split(",") if p.strip()]
  336. for name, _fn, sig, _desc in _ACTION_MANIFEST}
  337. # Two tools share one action table: ``discord`` (core, the participation trio every bot
  338. # user wants) and ``discord_admin`` (everything else).
  339. _CORE_ACTION_NAMES = frozenset({"fetch_messages", "search_members", "create_thread"})
  340. _CORE_ACTIONS = {k: v for k, v in _ACTIONS.items() if k in _CORE_ACTION_NAMES}
  341. _ADMIN_ACTIONS = {k: v for k, v in _ACTIONS.items() if k not in _CORE_ACTION_NAMES}
  342. # Actions that require the GUILD_MEMBERS privileged intent.
  343. _INTENT_GATED_MEMBERS = frozenset({"member_info", "search_members"})
  344. def _load_allowed_actions_config() -> Optional[list[str]]:
  345. """``discord.server_actions`` allowlist (comma string or YAML list), or ``None`` when
  346. unrestricted. Unknown names are dropped with a warning."""
  347. try:
  348. from hermes_cli.config import load_config
  349. cfg = load_config()
  350. except Exception as exc:
  351. logger.debug("discord: could not load config (%s); allowing all actions.", exc)
  352. return None
  353. raw = (cfg.get("discord") or {}).get("server_actions")
  354. if raw is None or raw == "":
  355. return None
  356. if isinstance(raw, str):
  357. raw = raw.split(",")
  358. elif not isinstance(raw, (list, tuple)):
  359. logger.warning("discord.server_actions: unexpected type %s; ignoring.", type(raw).__name__)
  360. return None
  361. names = [str(n).strip() for n in raw if str(n).strip()]
  362. invalid = [n for n in names if n not in _ACTIONS]
  363. if invalid:
  364. logger.warning(
  365. "discord.server_actions: unknown action(s) ignored: %s. Known: %s",
  366. ", ".join(invalid), ", ".join(_ACTIONS.keys()))
  367. return [n for n in names if n in _ACTIONS]
  368. def _available_actions(caps: dict[str, Any], allowlist: Optional[list[str]]) -> list[str]:
  369. """Visible actions from intents + config allowlist, in :data:`_ACTIONS` order."""
  370. members_ok = caps.get("has_members_intent", True)
  371. return [
  372. name for name in _ACTIONS
  373. if (members_ok or name not in _INTENT_GATED_MEMBERS) and (allowlist is None or name in allowlist)]
  374. # ── schema construction ──────────────────────────────────────────────────────
  375. _TOOL_DESCRIPTIONS = {
  376. "discord_admin": (
  377. "Manage a Discord server via the REST API.",
  378. "Call list_guilds first to discover guild_ids, then list_channels for "
  379. "channel_ids. Runtime errors will tell you if the bot lacks a specific "
  380. "per-guild permission (e.g. MANAGE_ROLES for add_role).",
  381. ),
  382. "discord": (
  383. "Read and participate in a Discord server.",
  384. "Use the channel_id from the current conversation context. "
  385. "Use search_members to look up user IDs by name prefix.",
  386. ),
  387. }
  388. _SCHEMA_PROPERTIES: dict[str, Any] = {
  389. "guild_id": {"type": "string", "description": "Discord server (guild) ID."},
  390. "channel_id": {"type": "string", "description": "Discord channel ID."},
  391. "user_id": {"type": "string", "description": "Discord user ID."},
  392. "role_id": {"type": "string", "description": "Discord role ID."},
  393. "message_id": {"type": "string", "description": "Discord message ID."},
  394. "query": {"type": "string", "description": "Member name prefix to search for (search_members)."},
  395. "name": {"type": "string", "description": "New thread name (create_thread)."},
  396. "limit": {
  397. "type": "integer",
  398. "minimum": 1,
  399. "maximum": 100,
  400. "description": "Max results (default 50). Applies to fetch_messages, search_members.",
  401. },
  402. "before": {"type": "string", "description": "Snowflake ID for reverse pagination (fetch_messages)."},
  403. "after": {"type": "string", "description": "Snowflake ID for forward pagination (fetch_messages)."},
  404. "auto_archive_duration": {
  405. "type": "integer",
  406. "enum": [60, 1440, 4320, 10080],
  407. "description": "Thread archive duration in minutes (create_thread, default 1440).",
  408. },
  409. }
  410. _CONTENT_NOTE = (
  411. "\n\nNOTE: Bot does NOT have the MESSAGE_CONTENT privileged intent. "
  412. "{names} will return message metadata (author, "
  413. "timestamps, attachments, reactions, pin state) but `content` will be "
  414. "empty for messages not sent as a direct mention to the bot or in DMs. "
  415. "Enable the intent in the Discord Developer Portal to see all content."
  416. )
  417. def _build_schema(
  418. actions: list[str], caps: Optional[dict[str, Any]] = None, tool_name: str = "discord",
  419. ) -> Optional[dict[str, Any]]:
  420. """Tool schema for the filtered action list; ``None`` when empty (drop the tool)."""
  421. caps = caps or {}
  422. if not actions:
  423. return None
  424. manifest_block = "\n".join(
  425. f" {name}{sig} — {desc}" for name, _fn, sig, desc in _ACTION_MANIFEST if name in actions)
  426. content_note = ""
  427. affected_actions = {"fetch_messages", "list_pins"} & set(actions)
  428. if affected_actions and caps.get("detected") and caps.get("has_message_content") is False:
  429. content_note = _CONTENT_NOTE.format(names=" and ".join(sorted(affected_actions)))
  430. lead, guidance = _TOOL_DESCRIPTIONS.get(tool_name, _TOOL_DESCRIPTIONS["discord"])
  431. return {
  432. "name": tool_name,
  433. "description": f"{lead}\n\nAvailable actions:\n{manifest_block}\n\n{guidance}{content_note}",
  434. "parameters": {
  435. "type": "object",
  436. "properties": {"action": {"type": "string", "enum": actions}, **_SCHEMA_PROPERTIES},
  437. "required": ["action"]}}
  438. def _get_dynamic_schema(action_subset: dict[str, Any], tool_name: str) -> Optional[dict[str, Any]]:
  439. """Build a dynamic schema for *action_subset* filtered by intents + config."""
  440. token = _get_bot_token()
  441. if not token:
  442. return None
  443. caps = _detect_capabilities_nonblocking(token)
  444. actions = [a for a in _available_actions(caps, _load_allowed_actions_config()) if a in action_subset]
  445. return _build_schema(actions, caps, tool_name=tool_name) if actions else None
  446. get_dynamic_schema_core = functools.partial(_get_dynamic_schema, _CORE_ACTIONS, "discord")
  447. get_dynamic_schema_admin = functools.partial(_get_dynamic_schema, _ADMIN_ACTIONS, "discord_admin")
  448. # ── 403 error enrichment ─────────────────────────────────────────────────────
  449. _NO_MANAGE_MESSAGES = "Bot lacks MANAGE_MESSAGES permission in this channel"
  450. _VIEW_HISTORY = "Bot cannot view this channel (missing VIEW_CHANNEL or READ_MESSAGE_HISTORY)."
  451. _ROLE_HIERARCHY = "Either the bot lacks MANAGE_ROLES, or the target role sits higher than the bot's highest role."
  452. # Per-action guidance for a call-time 403 (per-guild permissions are never pre-checked).
  453. _ACTION_403_HINT = {
  454. "pin_message": (
  455. f"{_NO_MANAGE_MESSAGES}. "
  456. "Ask the server admin to grant the bot a role that has MANAGE_MESSAGES, or a per-channel overwrite."),
  457. "unpin_message": f"{_NO_MANAGE_MESSAGES}.",
  458. "delete_message": f"{_NO_MANAGE_MESSAGES}, or cannot view the channel/message.",
  459. "create_thread": "Bot lacks CREATE_PUBLIC_THREADS in this channel, or cannot view it.",
  460. "add_role": (
  461. f"{_ROLE_HIERARCHY} Roles can only be assigned below the bot's own position in the role hierarchy."),
  462. "remove_role": _ROLE_HIERARCHY,
  463. "fetch_messages": _VIEW_HISTORY,
  464. "list_pins": _VIEW_HISTORY,
  465. "channel_info": "Bot cannot view this channel (missing VIEW_CHANNEL).",
  466. "search_members": (
  467. "Likely missing the Server Members privileged intent — enable it in the Discord Developer Portal "
  468. "under your bot's settings."),
  469. "member_info": "Bot cannot see this guild member (missing Server Members intent or insufficient permissions)."}
  470. def _enrich_403(action: str, body: str) -> str:
  471. """Return a user-friendly guidance string for a 403 on ``action``."""
  472. hint = _ACTION_403_HINT.get(action)
  473. base = f"Discord API 403 (forbidden) on '{action}'."
  474. return f"{base} {hint} (Raw: {body})" if hint else f"{base} (Raw: {body})"
  475. def check_discord_tool_requirements() -> bool:
  476. """Tool is available only when a Discord bot token is configured."""
  477. return bool(_get_bot_token())
  478. # ── handlers ─────────────────────────────────────────────────────────────────
  479. _HANDLER_DEFAULTS = {
  480. "guild_id": "", "channel_id": "", "user_id": "", "role_id": "", "message_id": "", "query": "",
  481. "name": "", "limit": 50, "before": "", "after": "", "auto_archive_duration": 1440}
  482. def _run_discord_action(action: str, valid_actions: dict[str, Any], tool_label: str, **params: Any) -> str:
  483. """Shared handler logic for both discord tools (``params`` default per :data:`_HANDLER_DEFAULTS`)."""
  484. token = _get_bot_token()
  485. if not token:
  486. return tool_error("DISCORD_BOT_TOKEN not configured.")
  487. action_fn = valid_actions.get(action)
  488. if not action_fn:
  489. return tool_error(f"Unknown action: {action}", available_actions=list(valid_actions.keys()))
  490. # Config-level allowlist gate (defense in depth): a stale cached schema from a prior
  491. # config must not let denied actions through.
  492. allowlist = _load_allowed_actions_config()
  493. if allowlist is not None and action not in allowlist:
  494. return tool_error(
  495. f"Action '{action}' is disabled by config (discord.server_actions). "
  496. f"Allowed: {', '.join(allowlist) if allowlist else '<none>'}")
  497. kwargs = {k: params.get(k, v) for k, v in _HANDLER_DEFAULTS.items()}
  498. missing = [p for p in _REQUIRED_PARAMS.get(action, []) if not kwargs.get(p)]
  499. if missing:
  500. return tool_error(f"Missing required parameters for '{action}': {', '.join(missing)}")
  501. try:
  502. return action_fn(token=token, **kwargs)
  503. except DiscordAPIError as e:
  504. logger.warning("Discord API error in %s action '%s': %s", tool_label, action, e)
  505. return tool_error(_enrich_403(action, e.body) if e.status == 403 else str(e))
  506. except Exception as e:
  507. logger.exception("Unexpected error in %s action '%s'", tool_label, action)
  508. return tool_error(f"Unexpected error: {e}")
  509. # ``discord`` = core participation trio; ``discord_admin`` = server management.
  510. discord_core = functools.partial(_run_discord_action, valid_actions=_CORE_ACTIONS, tool_label="discord")
  511. discord_admin_handler = functools.partial(
  512. _run_discord_action, valid_actions=_ADMIN_ACTIONS, tool_label="discord_admin")
  513. # Static (un-detected) schemas at import; the intent/config-filtered ones come from
  514. # get_dynamic_schema_core/admin via model_tools' dynamic schema overrides.
  515. for _name, _actions, _handler in (
  516. ("discord", _CORE_ACTIONS, discord_core), ("discord_admin", _ADMIN_ACTIONS, discord_admin_handler),
  517. ):
  518. registry.register(
  519. name=_name,
  520. toolset=_name,
  521. schema=_build_schema(list(_actions), caps={"detected": False}, tool_name=_name),
  522. handler=lambda args, _h=_handler, **kw: _h(**{"action": "", **args}),
  523. check_fn=check_discord_tool_requirements,
  524. requires_env=["DISCORD_BOT_TOKEN"])