The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(mcp): Hermes as an MCP server leaves core for the mcp-serve plugin
Tekniume3a962d087c5
diff --git a/gateway/slash_commands_model.py b/gateway/slash_commands_model.pyindex 5fc7b95e4d5..2803af17174 100644--- a/gateway/slash_commands_model.py+++ b/gateway/slash_commands_model.py@@ -598,7 +598,7 @@ class GatewayModelCommandsMixin:# that searches by the complete peer tuple when session_key doesn't match. origin_json and# display_name complete the identity (same shape as the reset path's db_create_kwargs in# gateway/session.py, #82633) so consumers that read routing/presentation data from state.db- # (mcp_serve, mirror, channel directory) see the branch row fully formed with zero backfill gap.+ # (the mcp-serve plugin, mirror, channel directory) see the branch row fully formed with zero backfill gap.session_key=session_key,source=source,config_path=(profile_home or _hermes_home) / "config.yaml",diff --git a/hermes_cli/_parser.py b/hermes_cli/_parser.pyindex ade6dd98b52..357d1eba59d 100644--- a/hermes_cli/_parser.py+++ b/hermes_cli/_parser.py@@ -343,7 +343,7 @@ def _plugin_command_install_hint(prog: str, value: str):def _moved_command_hint(prog: str, value: str) -> str:- """``hermes auth spotify`` / ``hermes spotify`` after Spotify left core: where the command went."""+ """Where a command that left core went (``hermes auth spotify``, ``hermes mcp serve``, ...)."""from hermes_cli.left_core_migration import moved_command_hintreturn moved_command_hint(prog, value)diff --git a/hermes_cli/console_engine.py b/hermes_cli/console_engine.pyindex 254660c95d2..d456f6408d4 100644--- a/hermes_cli/console_engine.py+++ b/hermes_cli/console_engine.py@@ -355,7 +355,6 @@ _BLOCKED_TOP = frozenset(_BLOCKED_PAIRS = {("config", "edit"): "`config edit` opens an editor and is not available in Hermes Console.",- ("mcp", "serve"): "`mcp serve` starts a server and is not available in Hermes Console.",("profile", "alias"): "`profile alias` creates shell wrappers and is not available in Hermes Console.",("skills", "config"): "`skills config` is interactive and is not available in Hermes Console.",("skills", "publish"): "`skills publish` is not available in Hermes Console.",diff --git a/hermes_cli/left_core_migration.py b/hermes_cli/left_core_migration.pyindex 4b66dc73e5f..4bb1c57c614 100644--- a/hermes_cli/left_core_migration.py+++ b/hermes_cli/left_core_migration.py@@ -177,6 +177,10 @@ class LeftCoreFeature:# Top-level command the plugin registers in place of core's ``hermes auth <cli>`` login# (``hermes <cli> login|status|logout``); :func:`moved_command_hint` points the old spelling at it.cli: str = ""+ # Top-level command the plugin registers in place of core's nested ``old_command``+ # (``hermes mcp serve`` -> ``hermes mcp-serve``); :func:`moved_command_hint` points the old spelling at it.+ command: str = ""+ old_command: str = ""# Key of the bundled plugin core shipped (``observability/langfuse``). It stays an alias of the# catalog plugin in ``plugins.enabled`` / ``plugins.disabled`` (the loader's gate, an# administrator's pinned list) and for every `hermes plugins <verb>` (:func:`legacy_plugin_alias`).@@ -205,6 +209,13 @@ LEFT_CORE: tuple[LeftCoreFeature, ...] = (private_env=("HERMES_LANGFUSE_PUBLIC_KEY", "HERMES_LANGFUSE_BASE_URL"),plugin_key="observability/langfuse",),+ LeftCoreFeature(+ # MCP clients that launch `hermes mcp serve` are configured outside Hermes, so no home shows the+ # feature in use: nothing installs automatically, and the old spelling prints where it went.+ plugin="mcp-serve", label="Hermes as an MCP server", in_use=lambda home, **_: False,+ unchanged="the conversation tools keep their names; MCP clients change their args to [\"mcp-serve\"]",+ command="mcp-serve", old_command="hermes mcp serve",+ ),)def _install_sentence(feature: LeftCoreFeature) -> str:@@ -233,13 +244,25 @@ def legacy_plugin_keys(plugin: str) -> set[str]:def moved_command_hint(prog: str, value: str, action: str = "") -> str:"""For a command a left-core plugin took over: ``hermes auth [<action>] <cli>`` (core's old login- spelling) or ``hermes <cli>`` while the plugin is not loaded, the line saying where it went and- how to get it for the active home, else ``""``."""+ spelling), core's old nested spelling (``hermes mcp serve``), or the plugin's own ``hermes <cli>`` /+ ``hermes <command>`` while the plugin is not loaded, the line saying where it went and how to get it+ for the active home, else ``""``."""from hermes_constants import get_hermes_home- feature = next((f for f in LEFT_CORE if f.cli and f.cli == value), None)- if feature is None or prog not in {"hermes", "hermes auth"}:- return ""home = Path(get_hermes_home())+ moved = next((f for f in LEFT_CORE if f.old_command and f.old_command == f"{prog} {value}"), None)+ if moved is not None:+ present = plugin_present(moved.plugin, home)+ get = "" if present else f" Install it with: `{_install_command(moved.plugin, home)}`."+ return (f"{moved.label} moved out of core into the '{moved.plugin}' plugin: `{moved.old_command}` is now "+ f"`hermes {moved.command}`.{get}")+ if prog == "hermes auth":+ feature = next((f for f in LEFT_CORE if f.cli and f.cli == value), None)+ elif prog == "hermes":+ feature = next((f for f in LEFT_CORE if value and value in (f.cli, f.command)), None)+ else:+ feature = None+ if feature is None:+ return ""install = _install_command(feature.plugin, home)if not plugin_present(feature.plugin, home):get = f" Install it with: `{install}`."diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex ab5bf578965..e597ce70aee 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -2836,7 +2836,6 @@ _AGENT_COMMANDS = {None, "chat", "acp", "rl"}_AGENT_SUBCOMMANDS = {"cron": ("cron_command", {"run", "tick"}),"gateway": ("gateway_command", {"run"}),- "mcp": ("mcp_action", {"serve"}),}@@ -2851,7 +2850,7 @@ def _is_tui_chat_launch(args) -> bool:# here, so the wrapper pre-warmed its own MCP discovery while the TUI# gateway (spawned moments later) ran a second one — an idle stdio MCP# server copy held dead for the whole session. Only chat commands can- # launch the TUI; other commands (mcp serve, gateway, acp, cron) keep+ # launch the TUI; other commands (gateway, acp, cron) keep# their own discovery behavior untouched.if getattr(args, "command", None) not in {None, "chat"}:return False@@ -2859,18 +2858,11 @@ def _is_tui_chat_launch(args) -> bool:def _agent_subcommand_selected(args) -> bool:- """True for ``cron run/tick``, ``gateway run``, ``mcp serve`` (see _AGENT_SUBCOMMANDS)."""+ """True for ``cron run/tick``, ``gateway run`` (see _AGENT_SUBCOMMANDS)."""_sub_attr, _sub_set = _AGENT_SUBCOMMANDS.get(args.command, (None, None))return bool(_sub_attr and getattr(args, _sub_attr, None) in _sub_set)-def _command_has_dedicated_mcp_startup(args) -> bool:- """acp / gateway run / cron run|tick own their MCP startup on the runtime path."""- return args.command == "acp" or (- args.command != "mcp" and _agent_subcommand_selected(args)- )--def _should_background_mcp_startup(args) -> bool:return not _is_tui_chat_launch(args) and args.command in {None, "chat", "rl"}@@ -2920,7 +2912,7 @@ def _prepare_agent_startup(args) -> None:exc_info=True,)# -t/--toolsets narrows which configured MCP servers get spawned, on- # every discovery path (inline below, background thread, TUI/desktop+ # every discovery path (background thread, TUI/desktop# deferred start). Built-in toolset names never match a server key, so# `-t terminal` simply spawns nothing; `-t all` keeps the full set.try:@@ -2935,8 +2927,7 @@ def _prepare_agent_startup(args) -> None:if _accept_hooks: # rides session.create (env_launch_flags) and the classic CLI's consent checkos.environ["HERMES_ACCEPT_HOOKS"] = "1"return- _run_inline_mcp_discovery = not (_is_tui_chat_launch(args) or _command_has_dedicated_mcp_startup(args))- if _run_inline_mcp_discovery and _should_background_mcp_startup(args):+ if _should_background_mcp_startup(args):try:from hermes_cli.mcp_startup import start_background_mcp_discovery@@ -2949,22 +2940,6 @@ def _prepare_agent_startup(args) -> None:"Background MCP tool discovery failed at CLI startup",exc_info=True,)- _run_inline_mcp_discovery = False- if _run_inline_mcp_discovery:- try: # synchronous for entrypoints without a later bounded startup path- from hermes_cli.mcp_startup import get_mcp_server_filter- from tools.mcp_tool_discovery import discover_mcp_tools-- _mcp_filter = get_mcp_server_filter()- if _mcp_filter is None:- discover_mcp_tools()- else:- discover_mcp_tools(allowed_mcp_names=_mcp_filter)- except Exception:- logger.debug(- "MCP tool discovery failed at CLI startup",- exc_info=True,- )try:from hermes_cli.config import load_configfrom agent.shell_hooks import register_from_configdiff --git a/hermes_cli/mcp_config.py b/hermes_cli/mcp_config.pyindex abb9cc337e8..3bb246863c3 100644--- a/hermes_cli/mcp_config.py+++ b/hermes_cli/mcp_config.py@@ -1124,7 +1124,6 @@ _MCP_USAGE = ("hermes mcp Open the catalog picker (default)","hermes mcp catalog List Nous-approved MCPs","hermes mcp install <name> Install a catalog MCP",- "hermes mcp serve Run as MCP server","hermes mcp add <name> --url <endpoint> Add a custom MCP server","hermes mcp add <name> --command <cmd> Add a stdio server","hermes mcp add <name> --preset <preset> Add from a known preset",@@ -1140,10 +1139,6 @@ _MCP_USAGE = (def mcp_command(args):"""Main dispatcher for ``hermes mcp`` subcommands."""action = getattr(args, "mcp_action", None)- if action == "serve":- from mcp_serve import run_mcp_server- run_mcp_server(verbose=getattr(args, "verbose", False))- returnif action in ("picker", "catalog", "install"):# Catalog subcommands live in mcp_picker / mcp_catalog; import lazily to keep this module cheap.from hermes_cli import mcp_pickerdiff --git a/hermes_cli/subcommands/mcp.py b/hermes_cli/subcommands/mcp.pyindex 9702d7be16b..5977969ba63 100644--- a/hermes_cli/subcommands/mcp.py+++ b/hermes_cli/subcommands/mcp.py@@ -5,25 +5,17 @@ from __future__ import annotationsimport argparsefrom typing import Callable-from hermes_cli.subcommands._shared import add_accept_hooks_flag-def build_mcp_parser(subparsers, *, cmd_mcp: Callable) -> None:"""Attach the ``mcp`` subcommand to ``subparsers``."""mcp_parser = subparsers.add_parser(- "mcp", help="Manage MCP servers and run Hermes as an MCP server",- description="Manage MCP server connections and run Hermes as an MCP server.\n\n"+ "mcp", help="Manage MCP server connections",+ description="Manage MCP server connections.\n\n""MCP servers provide additional tools via the Model Context Protocol.\n"- "Use 'hermes mcp add' to connect to a new server, or\n"- "'hermes mcp serve' to expose Hermes conversations over MCP.")+ "Use 'hermes mcp add' to connect to a new server. Running Hermes itself as an\n"+ "MCP server is the mcp-serve plugin: `hermes plugins install mcp-serve`.")mcp_sub = mcp_parser.add_subparsers(dest="mcp_action")- mcp_serve_p = mcp_sub.add_parser(- "serve", help="Run Hermes as an MCP server (expose conversations to other agents)")- mcp_serve_p.add_argument(- "-v", "--verbose", action="store_true", help="Enable verbose logging on stderr")- add_accept_hooks_flag(mcp_serve_p)-mcp_add_p = mcp_sub.add_parser("add", help="Add an MCP server (discovery-first install)")mcp_add_p.add_argument("name", help="Server name (used as config key)")mcp_add_p.add_argument("--url", help="HTTP/SSE endpoint URL")@@ -75,5 +67,4 @@ def build_mcp_parser(subparsers, *, cmd_mcp: Callable) -> None:"install", help="Install a catalog MCP by name (e.g. `hermes mcp install deepwiki`)")mcp_install_p.add_argument("identifier", help="Catalog entry name (or `official/<name>`)")- add_accept_hooks_flag(mcp_parser)mcp_parser.set_defaults(func=cmd_mcp)diff --git a/locales/af.yaml b/locales/af.yamlindex 40418466111..949b8febedb 100644--- a/locales/af.yaml+++ b/locales/af.yaml@@ -3604,7 +3604,7 @@ tips:t069: "hermes skills tap add myorg/skills-repo voeg 'n eie GitHub-vaardigheidsbron by."t070: "hermes skills snapshot export setup.json voer jou vaardigheidskonfigurasie uit vir rugsteun of deel."t071: "hermes mcp add github --command npx voeg MCP-bedieners vanaf die opdraglyn by."- t072: "hermes mcp serve laat Hermes self as 'n MCP-bediener vir ander agente loop."+ t072: "hermes mcp-serve laat Hermes self as 'n MCP-bediener vir ander agente loop."t073: "hermes auth add laat jou verskeie API-sleutels byvoeg vir rotasie van die geloofsbriewe-poel."t074: "hermes completion bash >> ~/.bashrc aktiveer tab-voltooiing vir alle opdragte en profiele."t075: "hermes logs -f volg agent.log intyds. --level WARNING --since 1h filter die uitvoer."diff --git a/locales/ar.yaml b/locales/ar.yamlindex 71423789bc2..3ed3446315e 100644--- a/locales/ar.yaml+++ b/locales/ar.yaml@@ -3604,7 +3604,7 @@ tips:t069: "hermes skills tap add myorg/skills-repo يضيف مصدر مهارات مخصصًا من GitHub."t070: "hermes skills snapshot export setup.json يصدّر إعدادات مهاراتك للنسخ الاحتياطي أو المشاركة."t071: "hermes mcp add github --command npx يضيف خوادم MCP من سطر الأوامر."- t072: "hermes mcp serve يشغّل Hermes نفسه كخادم MCP لوكلاء آخرين."+ t072: "hermes mcp-serve يشغّل Hermes نفسه كخادم MCP لوكلاء آخرين."t073: "hermes auth add يتيح لك إضافة عدة مفاتيح API للتناوب ضمن مجموعة بيانات الاعتماد."t074: "hermes completion bash >> ~/.bashrc يفعّل الإكمال بمفتاح Tab لجميع الأوامر والملفات التعريفية."t075: "hermes logs -f يتابع agent.log في الوقت الفعلي. و--level WARNING --since 1h يصفّي المخرجات."diff --git a/locales/de.yaml b/locales/de.yamlindex c1093f07c48..f1ebd5d14a1 100644--- a/locales/de.yaml+++ b/locales/de.yaml@@ -3604,7 +3604,7 @@ tips:t069: "hermes skills tap add myorg/skills-repo fügt eine eigene GitHub-Skill-Quelle hinzu."t070: "hermes skills snapshot export setup.json exportiert Ihre Skill-Konfiguration zur Sicherung oder Weitergabe."t071: "hermes mcp add github --command npx fügt MCP-Server über die Befehlszeile hinzu."- t072: "hermes mcp serve betreibt Hermes selbst als MCP-Server für andere Agenten."+ t072: "hermes mcp-serve betreibt Hermes selbst als MCP-Server für andere Agenten."t073: "hermes auth add lässt Sie mehrere API-Schlüssel für die Rotation im Zugangsdaten-Pool hinzufügen."t074: "hermes completion bash >> ~/.bashrc aktiviert die Tab-Vervollständigung für alle Befehle und Profile."t075: "hermes logs -f folgt agent.log in Echtzeit. --level WARNING --since 1h filtert die Ausgabe."diff --git a/locales/en.yaml b/locales/en.yamlindex 7400c308bb4..d760a0e7715 100644--- a/locales/en.yaml+++ b/locales/en.yaml@@ -3718,7 +3718,7 @@ tips:t069: "hermes skills tap add myorg/skills-repo adds a custom GitHub skill source."t070: "hermes skills snapshot export setup.json exports your skill configuration for backup or sharing."t071: "hermes mcp add github --command npx adds MCP servers from the command line."- t072: "hermes mcp serve runs Hermes itself as an MCP server for other agents."+ t072: "hermes mcp-serve runs Hermes itself as an MCP server for other agents."t073: "hermes auth add lets you add multiple API keys for credential pool rotation."t074: "hermes completion bash >> ~/.bashrc enables tab completion for all commands and profiles."t075: "hermes logs -f follows agent.log in real time. --level WARNING --since 1h filters output."diff --git a/locales/es.yaml b/locales/es.yamlindex 645bc9b1296..c49122067a3 100644--- a/locales/es.yaml+++ b/locales/es.yaml@@ -3604,7 +3604,7 @@ tips:t069: "hermes skills tap add myorg/skills-repo agrega una fuente de skills personalizada de GitHub."t070: "hermes skills snapshot export setup.json exporta tu configuración de skills para respaldarla o compartirla."t071: "hermes mcp add github --command npx agrega servidores MCP desde la línea de comandos."- t072: "hermes mcp serve ejecuta Hermes como servidor MCP para otros agentes."+ t072: "hermes mcp-serve ejecuta Hermes como servidor MCP para otros agentes."t073: "hermes auth add te permite agregar varias claves de API para rotar un grupo de credenciales."t074: "hermes completion bash >> ~/.bashrc activa el autocompletado con Tab para todos los comandos y perfiles."t075: "hermes logs -f sigue agent.log en tiempo real. --level WARNING --since 1h filtra la salida."diff --git a/locales/fr.yaml b/locales/fr.yamlindex 9c20ed82d0a..5b9776f3ffe 100644--- a/locales/fr.yaml+++ b/locales/fr.yaml@@ -3929,7 +3929,7 @@ tips:t069: "hermes skills tap add myorg/skills-repo ajoute une source de skills GitHub personnalisée."t070: "hermes skills snapshot export setup.json exporte votre configuration de skills pour sauvegarde ou partage."t071: "hermes mcp add github --command npx ajoute des serveurs MCP depuis la ligne de commande."- t072: "hermes mcp serve fait tourner Hermes lui-même comme serveur MCP pour d'autres agents."+ t072: "hermes mcp-serve fait tourner Hermes lui-même comme serveur MCP pour d'autres agents."t073: "hermes auth add permet d'ajouter plusieurs clés API pour la rotation d'un pool d'identifiants."t074: "hermes completion bash >> ~/.bashrc active la complétion par Tab pour toutes les commandes et tous les profils."t075: "hermes logs -f suit agent.log en temps réel. --level WARNING --since 1h filtre la sortie."diff --git a/locales/ga.yaml b/locales/ga.yamlindex 03d8cb74d6c..f47c648e812 100644--- a/locales/ga.yaml+++ b/locales/ga.yaml@@ -3604,7 +3604,7 @@ tips:t069: "Cuireann hermes skills tap add myorg/skills-repo foinse scileanna GitHub shaincheaptha leis."t070: "Easpórtálann hermes skills snapshot export setup.json do chumraíocht scileanna le haghaidh cúltaca nó roinnte."t071: "Cuireann hermes mcp add github --command npx freastalaithe MCP leis ón líne ordaithe."- t072: "Ritheann hermes mcp serve Hermes féin mar fhreastalaí MCP do ghníomhairí eile."+ t072: "Ritheann hermes mcp-serve Hermes féin mar fhreastalaí MCP do ghníomhairí eile."t073: "Ligeann hermes auth add duit eochracha API iolracha a chur leis le haghaidh rothlú linn dintiúr."t074: "Cumasaíonn hermes completion bash >> ~/.bashrc comhlánú táib do gach ordú agus próifíl."t075: "Leanann hermes logs -f agent.log i bhfíor-am. Scagann --level WARNING --since 1h an t-aschur."diff --git a/locales/hu.yaml b/locales/hu.yamlindex ca73de2869a..505e1edaca0 100644--- a/locales/hu.yaml+++ b/locales/hu.yaml@@ -3621,7 +3621,7 @@ tips:t069: "A hermes skills tap add myorg/skills-repo egyedi GitHub skill-forrást ad hozzá."t070: "A hermes skills snapshot export setup.json exportálja a skill-konfigurációdat biztonsági mentéshez vagy megosztáshoz."t071: "A hermes mcp add github --command npx parancssorból ad hozzá MCP-szervereket."- t072: "A hermes mcp serve magát a Hermest futtatja MCP-szerverként más ügynökök számára."+ t072: "A hermes mcp-serve magát a Hermest futtatja MCP-szerverként más ügynökök számára."t073: "A hermes auth add több API-kulcsot is felvehet a hitelesítőadat-készlet rotálásához."t074: "A hermes completion bash >> ~/.bashrc bekapcsolja a Tab-kiegészítést minden parancshoz és profilhoz."t075: "A hermes logs -f valós időben követi az agent.log fájlt. A --level WARNING --since 1h szűri a kimenetet."diff --git a/locales/it.yaml b/locales/it.yamlindex 7e362db7b78..ac41eeb6072 100644--- a/locales/it.yaml+++ b/locales/it.yaml@@ -3604,7 +3604,7 @@ tips:t069: "hermes skills tap add myorg/skills-repo aggiunge una sorgente GitHub personalizzata per le skill."t070: "hermes skills snapshot export setup.json esporta la configurazione delle tue skill per backup o condivisione."t071: "hermes mcp add github --command npx aggiunge server MCP dalla riga di comando."- t072: "hermes mcp serve esegue Hermes stesso come server MCP per altri agenti."+ t072: "hermes mcp-serve esegue Hermes stesso come server MCP per altri agenti."t073: "hermes auth add ti permette di aggiungere più chiavi API per la rotazione del pool di credenziali."t074: "hermes completion bash >> ~/.bashrc abilita il completamento con Tab per tutti i comandi e i profili."t075: "hermes logs -f segue agent.log in tempo reale. --level WARNING --since 1h filtra l'output."diff --git a/locales/ja.yaml b/locales/ja.yamlindex b26730d3ecf..7cd8c0f10b5 100644--- a/locales/ja.yaml+++ b/locales/ja.yaml@@ -3604,7 +3604,7 @@ tips:t069: "hermes skills tap add myorg/skills-repo はカスタムの GitHub スキルソースを追加します。"t070: "hermes skills snapshot export setup.json はバックアップや共有のためにスキル設定をエクスポートします。"t071: "hermes mcp add github --command npx はコマンドラインから MCP サーバーを追加します。"- t072: "hermes mcp serve は Hermes 自体を他のエージェント向けの MCP サーバーとして実行します。"+ t072: "hermes mcp-serve は Hermes 自体を他のエージェント向けの MCP サーバーとして実行します。"t073: "hermes auth add で認証情報プールのローテーション用に複数の API キーを追加できます。"t074: "hermes completion bash >> ~/.bashrc はすべてのコマンドとプロファイルの Tab 補完を有効にします。"t075: "hermes logs -f は agent.log をリアルタイムで追跡します。--level WARNING --since 1h で出力を絞り込めます。"diff --git a/locales/ko.yaml b/locales/ko.yamlindex d1f8d8afeb5..ebe9f64e7ad 100644--- a/locales/ko.yaml+++ b/locales/ko.yaml@@ -3604,7 +3604,7 @@ tips:t069: "hermes skills tap add myorg/skills-repo는 사용자 지정 GitHub 스킬 소스를 추가해요."t070: "hermes skills snapshot export setup.json은 백업이나 공유를 위해 스킬 설정을 내보내요."t071: "hermes mcp add github --command npx는 명령줄에서 MCP 서버를 추가해요."- t072: "hermes mcp serve는 Hermes 자체를 다른 에이전트를 위한 MCP 서버로 실행해요."+ t072: "hermes mcp-serve는 Hermes 자체를 다른 에이전트를 위한 MCP 서버로 실행해요."t073: "hermes auth add로 자격 증명 풀 순환을 위한 API 키를 여러 개 추가할 수 있어요."t074: "hermes completion bash >> ~/.bashrc는 모든 명령과 프로필에 대한 탭 자동 완성을 활성화해요."t075: "hermes logs -f는 agent.log를 실시간으로 따라가요. --level WARNING --since 1h로 출력을 필터링해요."diff --git a/locales/pt.yaml b/locales/pt.yamlindex 2f884def7f9..9b0cbcd7d49 100644--- a/locales/pt.yaml+++ b/locales/pt.yaml@@ -3604,7 +3604,7 @@ tips:t069: "hermes skills tap add myorg/skills-repo adiciona uma fonte personalizada de skills no GitHub."t070: "hermes skills snapshot export setup.json exporta sua configuração de skills para backup ou compartilhamento."t071: "hermes mcp add github --command npx adiciona servidores MCP pela linha de comando."- t072: "hermes mcp serve executa o próprio Hermes como um servidor MCP para outros agentes."+ t072: "hermes mcp-serve executa o próprio Hermes como um servidor MCP para outros agentes."t073: "hermes auth add permite adicionar várias chaves de API para rotação do pool de credenciais."t074: "hermes completion bash >> ~/.bashrc ativa o preenchimento com Tab para todos os comandos e perfis."t075: "hermes logs -f acompanha o agent.log em tempo real. --level WARNING --since 1h filtra a saída."diff --git a/locales/ru.yaml b/locales/ru.yamlindex 64d71267f1f..8aafd8d396f 100644--- a/locales/ru.yaml+++ b/locales/ru.yaml@@ -3604,7 +3604,7 @@ tips:t069: "hermes skills tap add myorg/skills-repo добавляет собственный источник навыков на GitHub."t070: "hermes skills snapshot export setup.json экспортирует конфигурацию навыков для резервной копии или обмена."t071: "hermes mcp add github --command npx добавляет MCP-серверы из командной строки."- t072: "hermes mcp serve запускает сам Hermes как MCP-сервер для других агентов."+ t072: "hermes mcp-serve запускает сам Hermes как MCP-сервер для других агентов."t073: "hermes auth add позволяет добавить несколько API-ключей для ротации пула учётных данных."t074: "hermes completion bash >> ~/.bashrc включает автодополнение по Tab для всех команд и профилей."t075: "hermes logs -f показывает agent.log в реальном времени. --level WARNING --since 1h фильтрует вывод."diff --git a/locales/tr.yaml b/locales/tr.yamlindex 39ad0963954..f36fe119976 100644--- a/locales/tr.yaml+++ b/locales/tr.yaml@@ -3604,7 +3604,7 @@ tips:t069: "hermes skills tap add myorg/skills-repo özel bir GitHub skill kaynağı ekler."t070: "hermes skills snapshot export setup.json skill yapılandırmanızı yedekleme veya paylaşım için dışa aktarır."t071: "hermes mcp add github --command npx komut satırından MCP sunucuları ekler."- t072: "hermes mcp serve Hermes'in kendisini diğer ajanlar için bir MCP sunucusu olarak çalıştırır."+ t072: "hermes mcp-serve Hermes'in kendisini diğer ajanlar için bir MCP sunucusu olarak çalıştırır."t073: "hermes auth add kimlik bilgisi havuzu rotasyonu için birden fazla API anahtarı eklemenizi sağlar."t074: "hermes completion bash >> ~/.bashrc tüm komutlar ve profiller için tab tamamlamayı etkinleştirir."t075: "hermes logs -f agent.log dosyasını gerçek zamanlı izler. --level WARNING --since 1h çıktıyı filtreler."diff --git a/locales/uk.yaml b/locales/uk.yamlindex f62c09e60c1..20fdcc8fc6f 100644--- a/locales/uk.yaml+++ b/locales/uk.yaml@@ -3604,7 +3604,7 @@ tips:t069: "hermes skills tap add myorg/skills-repo додає власне джерело навичок на GitHub."t070: "hermes skills snapshot export setup.json експортує вашу конфігурацію навичок для резервного копіювання або обміну."t071: "hermes mcp add github --command npx додає MCP-сервери з командного рядка."- t072: "hermes mcp serve запускає сам Hermes як MCP-сервер для інших агентів."+ t072: "hermes mcp-serve запускає сам Hermes як MCP-сервер для інших агентів."t073: "hermes auth add дозволяє додати кілька API-ключів для ротації пулу облікових даних."t074: "hermes completion bash >> ~/.bashrc вмикає автодоповнення через Tab для всіх команд і профілів."t075: "hermes logs -f стежить за agent.log у реальному часі. --level WARNING --since 1h фільтрує вивід."diff --git a/locales/zh-hant.yaml b/locales/zh-hant.yamlindex ae5f5d7a590..a52f7273971 100644--- a/locales/zh-hant.yaml+++ b/locales/zh-hant.yaml@@ -3604,7 +3604,7 @@ tips:t069: "hermes skills tap add myorg/skills-repo 會新增自訂的 GitHub 技能來源。"t070: "hermes skills snapshot export setup.json 會匯出你的技能設定,供備份或分享。"t071: "hermes mcp add github --command npx 可從命令列新增 MCP 伺服器。"- t072: "hermes mcp serve 會將 Hermes 本身作為 MCP 伺服器執行,供其他代理使用。"+ t072: "hermes mcp-serve 會將 Hermes 本身作為 MCP 伺服器執行,供其他代理使用。"t073: "hermes auth add 讓你新增多個 API 金鑰,用於憑證池輪替。"t074: "hermes completion bash >> ~/.bashrc 會為所有指令與設定檔啟用 Tab 自動完成。"t075: "hermes logs -f 會即時追蹤 agent.log。--level WARNING --since 1h 可篩選輸出。"diff --git a/locales/zh.yaml b/locales/zh.yamlindex c6f5543d90c..9e86a2563a8 100644--- a/locales/zh.yaml+++ b/locales/zh.yaml@@ -3604,7 +3604,7 @@ tips:t069: "hermes skills tap add myorg/skills-repo 添加自定义的 GitHub 技能源。"t070: "hermes skills snapshot export setup.json 导出你的技能配置,用于备份或分享。"t071: "hermes mcp add github --command npx 可从命令行添加 MCP 服务器。"- t072: "hermes mcp serve 把 Hermes 本身作为 MCP 服务器运行,供其他代理使用。"+ t072: "hermes mcp-serve 把 Hermes 本身作为 MCP 服务器运行,供其他代理使用。"t073: "hermes auth add 允许你添加多个 API 密钥,用于凭据池轮换。"t074: "hermes completion bash >> ~/.bashrc 为所有命令和配置档启用 Tab 补全。"t075: "hermes logs -f 实时跟踪 agent.log。--level WARNING --since 1h 可筛选输出。"diff --git a/mcp_serve.py b/mcp_serve.pydeleted file mode 100644index 1ced8c328d6..00000000000--- a/mcp_serve.py+++ /dev/null@@ -1,763 +0,0 @@-"""-Hermes MCP Server — expose messaging conversations as MCP tools (`hermes mcp serve`).--A stdio MCP server letting any MCP client (Claude Code, Cursor, Codex, ...) list-conversations, read history, send messages, poll live events, and manage approvals.-Matches OpenClaw's 9-tool channel bridge surface plus the Hermes-specific-channels_list. Client config: {"mcpServers": {"hermes": {"command": "hermes", "args": ["mcp", "serve"]}}}-"""--from __future__ import annotations--import json-import logging-import os-import re-import sqlite3-import sys-import threading-import time-from dataclasses import dataclass, field-from datetime import datetime-from pathlib import Path-from typing import Dict, List, Optional--logger = logging.getLogger("hermes.mcp_serve")--# mcp 2.0 removed `mcp.server.fastmcp`; `mcp.server.MCPServer` keeps the same-# `@server.tool()` / `run_stdio_async()` surface (docstring -> description,-# signature -> input schema).-_MCP_SERVER_AVAILABLE = False-try:- from mcp.server import MCPServer-- _MCP_SERVER_AVAILABLE = True-except ImportError:- MCPServer = None # type: ignore[assignment,misc]---# --- Helpers -------------------------------------------------------------------def _hermes_home() -> Path:- try:- from hermes_constants import get_hermes_home- return get_hermes_home()- except ImportError:- return Path(os.environ.get("HERMES_HOME", Path.home() / ".hermes"))---def _get_sessions_dir() -> Path:- return _hermes_home() / "sessions"---class _StateDbVersion:- """``PRAGMA data_version`` of state.db on a private read-only connection.-- The value changes whenever ANY other connection commits — WAL commits included, same mtime- tick included — and stays put otherwise, for about a microsecond per read. A stat signature- of state.db (+ WAL) misses same-tick commits unless every recent mtime forces a full poll,- which keeps a busy gateway's bridge in permanent full-poll mode. ``read`` returns None when- the database is absent or unreadable; the caller then polls unconditionally."""-- def __init__(self):- self._path: Optional[Path] = None- self._conn: Optional[sqlite3.Connection] = None-- def read(self) -> Optional[int]:- path = _hermes_home() / "state.db"- try:- conn = self._conn- if conn is None or self._path != path:- self.close()- if not path.exists():- return None- # Polled from the bridge thread, baselined from the starter's. read_only_db_uri:- # a raw f"file:{path}" URI breaks on '#', '?' or '%xx' in HERMES_HOME.- from hermes_state_holders import read_only_db_uri- conn = sqlite3.connect(read_only_db_uri(path), uri=True, check_same_thread=False)- self._conn = conn- self._path = path- return conn.execute("PRAGMA data_version").fetchone()[0]- except sqlite3.Error:- self.close()- return None-- def close(self) -> None:- if self._conn is not None:- self._conn.close()- self._conn = None- self._path = None---def _read_json(path: Path):- """Parsed JSON file, or {} when missing/unreadable."""- if not path.exists():- return {}- try:- with open(path, "r", encoding="utf-8") as f:- return json.load(f)- except Exception as e:- logger.debug("Failed to load %s: %s", path.name, e)- return {}---def _close_quietly(db, what: str) -> None:- try:- db.close()- except Exception:- logger.debug("Failed to close MCP %s SessionDB", what, exc_info=True)---def _get_session_db():- """SessionDB instance for reading message transcripts, or None."""- try:- from hermes_state_registry import acquire- return acquire()- except Exception as e:- logger.debug("SessionDB unavailable: %s", e)- return None---def _load_session_messages(session_id: str):- """(messages, error) for one session; closes the temporary database handle."""- db = _get_session_db()- if db is None:- return None, "Session database unavailable"- try:- return db.get_messages(session_id), None- except Exception as e:- return None, f"Failed to read messages: {e}"- finally:- try:- from hermes_state_registry import release_or_close- release_or_close(db)- except Exception:- logger.debug("Failed to close MCP SessionDB", exc_info=True)---def _load_sessions_index() -> dict:- """Gateway routing index: session_key -> entry dict.-- state.db is primary (gateway session rows carry session_key/origin metadata);- sessions.json is the fallback for pre-migration databases without session_keys.-- state.db is the primary source (#9006): gateway sessions persist their routing metadata (session_key,- chat/thread ids, display_name, origin) on the durable session row, so a single database read replaces- the old dual-file sessions.json dependency.- """- return _load_sessions_index_from_db() or _load_sessions_index_from_json()---def _iso(ts) -> str:- try:- return datetime.fromtimestamp(float(ts)).isoformat() if ts else ""- except (TypeError, ValueError, OSError):- return ""---def _row_to_index_entry(row: dict) -> dict:- """Convert a state.db gateway session row to the sessions.json entry shape."""- origin = {}- if row.get("origin_json"):- try:- parsed = json.loads(row["origin_json"])- if isinstance(parsed, dict):- origin = parsed- except (TypeError, ValueError):- pass- if not origin: # pre-origin_json rows: synthesize the minimal origin from columns- origin = {"platform": row.get("source", ""), **{k: row.get(k) for k in ("chat_id", "chat_type", "thread_id", "user_id")}}-- input_tokens = int(row.get("input_tokens") or 0)- output_tokens = int(row.get("output_tokens") or 0)- return {- "session_id": str(row.get("id", "")), "session_key": row.get("session_key", ""),- "platform": row.get("source", ""),- "chat_type": row.get("chat_type") or origin.get("chat_type", ""),- "display_name": row.get("display_name") or origin.get("chat_name") or "",- "origin": origin,- "created_at": _iso(row.get("started_at")),- "updated_at": _iso(row.get("last_active") or row.get("started_at")),- "input_tokens": input_tokens, "output_tokens": output_tokens,- "total_tokens": input_tokens + output_tokens,- }---def _load_sessions_index_from_db() -> dict:- """Build the routing index from state.db gateway session rows."""- db = _get_session_db()- if db is None:- return {}- try:- lister = getattr(db, "list_gateway_sessions", None)- if not callable(lister):- return {}- return {row["session_key"]: _row_to_index_entry(row) for row in lister(active_only=True) if row.get("session_key")}- except Exception as e:- logger.debug("Failed to load gateway sessions from state.db: %s", e)- return {}- finally:- try:- db.close()- except Exception:- pass---def _load_sessions_index_from_json() -> dict:- """Legacy fallback: read sessions.json directly (avoids importing SessionStore,- which needs GatewayConfig). Keys starting with "_" are metadata sentinels- (e.g. "_README"), not session entries."""- data = _read_json(_get_sessions_dir() / "sessions.json")- return {k: v for k, v in data.items() if not str(k).startswith("_")} if isinstance(data, dict) else {}---def _load_channel_directory() -> dict:- """Load the cached channel directory for available targets."""- return _read_json(_hermes_home() / "channel_directory.json")---def _coerce_int(value, *, default: int, minimum: int, maximum: int) -> int:- """Clamped int for MCP tool boundaries; *default* when the client sent an unconvertible value."""- try:- coerced = int(value)- except (TypeError, ValueError):- coerced = default- return max(minimum, min(coerced, maximum))---def _extract_message_content(msg: dict) -> str:- """Extract text content from a message, handling multi-part content."""- content = msg.get("content", "")- if isinstance(content, list):- return "\n".join(p.get("text", "") for p in content if isinstance(p, dict) and p.get("type") == "text")- return str(content) if content else ""---def _extract_attachments(msg: dict) -> list[dict]:- """Non-text attachments: image/file content blocks plus MEDIA: tags in the text."""- attachments = []- content = msg.get("content", "")- for part in content if isinstance(content, list) else ():- if not isinstance(part, dict):- continue- ptype = part.get("type", "")- if ptype == "image_url":- url = part.get("image_url", {}).get("url", "") if isinstance(part.get("image_url"), dict) else ""- elif ptype == "image":- url = part.get("url", part.get("source", {}).get("url", ""))- else:- if ptype != "text":- attachments.append({"type": ptype, "data": part})- continue- if url:- attachments.append({"type": "image", "url": url})- for match in re.finditer(r'MEDIA:\s*(\S+)', _extract_message_content(msg)):- attachments.append({"type": "media", "path": match.group(1)})- return attachments---# --- Event Bridge — polls SessionDB for new messages, maintains event queue -----QUEUE_LIMIT = 1000-POLL_INTERVAL = 0.2 # seconds between DB polls (200ms)---@dataclass-class QueueEvent:- """An event in the bridge's in-memory queue."""- cursor: int- type: str # "message", "approval_requested", "approval_resolved"- session_key: str = ""- data: dict = field(default_factory=dict)-- def as_dict(self) -> dict:- return {"cursor": self.cursor, "type": self.type, "session_key": self.session_key, **self.data}---def _ts_float(ts) -> float:- """Normalize a message timestamp (epoch int/float or ISO string) to float."""- if isinstance(ts, (int, float)):- return float(ts)- if not (isinstance(ts, str) and ts):- return 0.0- try:- return float(ts)- except ValueError:- try:- return datetime.fromisoformat(ts).timestamp()- except Exception:- return 0.0---def _latest_ts(messages) -> float:- """Newest normalized timestamp among *messages* (0.0 when none)."""- return max((_ts_float(m.get("timestamp", 0)) for m in (messages or ())), default=0.0)---class EventBridge:- """Background poller watching SessionDB for new messages, feeding an in-memory- event queue with waiter support (the Hermes analogue of OpenClaw's WebSocket- gateway bridge, polling SQLite instead)."""-- def __init__(self):- self._queue: list[QueueEvent] = []- self._cursor = 0- self._lock = threading.Lock()- self._new_event = threading.Event()- self._running = False- self._thread: Optional[threading.Thread] = None- self._last_poll_timestamps: dict[str, float] = {} # session_key -> unix timestamp- self._pending_approvals: dict[str, dict] = {} # populated from events- self._db_version = _StateDbVersion()- self._state_db_version: Optional[int] = None # skip polling work when state.db is unchanged- self._cached_sessions_index: dict = {}-- def start(self):- """Start the background polling thread."""- if self._running:- return- # Baseline existing history BEFORE polling so startup never replays old- # messages as events; sessions appearing later default to last_seen=0.0- # in _poll_once, so new-conversation delivery is preserved.- # Unit tests that drive _poll_once directly bypass start() and still observe first-poll delivery.- # See #13414.- self._establish_baseline()- self._running = True- self._thread = threading.Thread(target=self._poll_loop, daemon=True)- self._thread.start()- logger.debug("EventBridge started")-- def stop(self):- """Stop the background polling thread and wake any waiters."""- self._running = False- self._new_event.set()- if self._thread:- self._thread.join(timeout=5)- self._db_version.close()- logger.debug("EventBridge stopped")-- def _matching(self, after_cursor: int, session_key: Optional[str], limit: int) -> list[dict]:- with self._lock:- return [e.as_dict() for e in self._queue- if e.cursor > after_cursor and (not session_key or e.session_key == session_key)][:limit]-- def poll_events(self, after_cursor: int = 0, session_key: Optional[str] = None, limit: int = 20) -> dict:- """Return events since after_cursor, optionally filtered by session_key."""- events = self._matching(after_cursor, session_key, limit)- return {"events": events, "next_cursor": events[-1]["cursor"] if events else after_cursor}-- def wait_for_event(self, after_cursor: int = 0, session_key: Optional[str] = None, timeout_ms: int = 30000) -> Optional[dict]:- """Block until a matching event arrives or timeout expires."""- deadline = time.monotonic() + (timeout_ms / 1000.0)- while time.monotonic() < deadline:- found = self._matching(after_cursor, session_key, 1)- if found:- return found[0]- remaining = deadline - time.monotonic()- if remaining <= 0:- break- self._new_event.clear()- self._new_event.wait(timeout=min(remaining, POLL_INTERVAL))- return None-- def list_pending_approvals(self) -> list[dict]:- """List approval requests observed during this bridge session."""- with self._lock:- return sorted(self._pending_approvals.values(), key=lambda a: a.get("created_at", ""))-- def respond_to_approval(self, approval_id: str, decision: str) -> dict:- """Resolve a pending approval (best-effort without gateway IPC)."""- with self._lock:- approval = self._pending_approvals.pop(approval_id, None)- if not approval:- return {"error": f"Approval not found: {approval_id}"}- self._enqueue(QueueEvent(0, "approval_resolved", approval.get("session_key", ""), # cursor set by _enqueue- {"approval_id": approval_id, "decision": decision}))- return {"resolved": True, "approval_id": approval_id, "decision": decision}-- def _enqueue(self, event: QueueEvent) -> None:- """Add an event to the queue (trimmed to QUEUE_LIMIT) and wake any waiters."""- with self._lock:- self._cursor += 1- event.cursor = self._cursor- self._queue.append(event)- while len(self._queue) > QUEUE_LIMIT:- self._queue.pop(0)- self._new_event.set()-- def _establish_baseline(self) -> None:- """Record per-session latest timestamps and the state.db signature WITHOUT- emitting events. Only sessions existing now are baselined; later ones- default to last_seen=0.0 in _poll_once, so their first message is delivered."""- db = _get_session_db()- if not db:- return- try:- self._state_db_version = self._db_version.read()- try:- self._cached_sessions_index = _load_sessions_index()- except Exception:- self._cached_sessions_index = {}- for session_key, entry in self._cached_sessions_index.items():- session_id = entry.get("session_id", "")- if not session_id:- continue- try:- latest = _latest_ts(db.get_messages(session_id))- except Exception:- continue- if latest > 0.0:- self._last_poll_timestamps[session_key] = latest- finally:- _close_quietly(db, "baseline")-- def _poll_loop(self):- """Background loop: poll SessionDB for new messages."""- db = _get_session_db()- if not db:- logger.warning("EventBridge: SessionDB unavailable, event polling disabled")- return- try:- while self._running:- try:- self._poll_once(db)- except Exception as e:- logger.debug("EventBridge poll error: %s", e)- time.sleep(POLL_INTERVAL)- finally:- _close_quietly(db, "polling")-- def _poll_once(self, db):- """Check for new messages across all sessions.-- One state.db ``data_version`` read gates all work, making 200ms polling nearly free.- The routing index lives in the same database as the messages, so a new- conversation and its first message land in a single commit (no- dual-file race that could drop brand-new conversations).-- See #8925, #9006.- """- version = self._db_version.read()- if version is not None and version == self._state_db_version:- return- self._state_db_version = version- # Refresh the index on every change tick: one indexed query, never lags messages.- self._cached_sessions_index = _load_sessions_index()-- for session_key, entry in self._cached_sessions_index.items():- session_id = entry.get("session_id", "")- if not session_id:- continue- last_seen = self._last_poll_timestamps.get(session_key, 0.0)- try:- messages = db.get_messages(session_id)- except Exception:- continue- if not messages:- continue- for msg in messages:- if msg.get("role", "") not in {"user", "assistant"} or _ts_float(msg.get("timestamp", 0)) <= last_seen:- continue- content = _extract_message_content(msg)- if not content:- continue- self._enqueue(QueueEvent(0, "message", session_key, {- "role": msg.get("role", ""), "content": content[:500],- "timestamp": str(msg.get("timestamp", "")), "message_id": str(msg.get("id", "")),- }))- latest = _latest_ts(messages)- if latest > last_seen:- self._last_poll_timestamps[session_key] = latest---# --- MCP Server -----------------------------------------------------------------def _conversation_messages(session_key: str):- """(messages, error_json) for a conversation; exactly one is None."""- entry = _load_sessions_index().get(session_key)- if not entry:- return None, json.dumps({"error": f"Conversation not found: {session_key}"})- session_id = entry.get("session_id", "")- if not session_id:- return None, json.dumps({"error": "No session ID for this conversation"})- messages, error = _load_session_messages(session_id)- if error:- return None, json.dumps({"error": error})- return messages, None---def _platform_matches(wanted: Optional[str], actual: str) -> bool:- return not wanted or actual.lower() == wanted.lower()---class _ToolHandlers:- """The MCP tool handlers; each method named in _TOOL_NAMES is registered as one tool.-- Method docstrings are the wire-format tool descriptions and signatures the- input schemas — do not reword or reflow them.- """-- def __init__(self, bridge: EventBridge):- self.bridge = bridge-- def conversations_list(self, platform: Optional[str] = None, limit: int = 50, search: Optional[str] = None) -> str:- """List active messaging conversations across connected platforms.-- Returns conversations with their session keys (needed for messages_read),- platform, chat type, display name, and last activity time.-- Args:- platform: Filter by platform name (telegram, discord, slack, etc.)- limit: Maximum number of conversations to return (default 50)- search: Optional text to filter conversations by name- """- limit = _coerce_int(limit, default=50, minimum=1, maximum=200)- conversations = []- for key, entry in _load_sessions_index().items():- origin = entry.get("origin", {})- entry_platform = entry.get("platform") or origin.get("platform", "")- if not _platform_matches(platform, entry_platform):- continue- display_name = entry.get("display_name", "")- chat_name = origin.get("chat_name", "")- if search and not any(search.lower() in s.lower() for s in (display_name, chat_name, key)):- continue- conversations.append({- "session_key": key, "session_id": entry.get("session_id", ""), "platform": entry_platform,- "chat_type": entry.get("chat_type", origin.get("chat_type", "")),- "display_name": display_name, "chat_name": chat_name,- "user_name": origin.get("user_name", ""), "updated_at": entry.get("updated_at", ""),- })-- conversations = sorted(conversations, key=lambda c: c.get("updated_at", ""), reverse=True)[:limit]- return json.dumps({"count": len(conversations), "conversations": conversations}, indent=2)-- def conversation_get(self, session_key: str) -> str:- """Get detailed info about one conversation by its session key.-- Args:- session_key: The session key from conversations_list- """- entry = _load_sessions_index().get(session_key)- if not entry:- return json.dumps({"error": f"Conversation not found: {session_key}"})- origin = entry.get("origin", {})- return json.dumps({- "session_key": session_key, "session_id": entry.get("session_id", ""),- "platform": entry.get("platform") or origin.get("platform", ""),- "chat_type": entry.get("chat_type", origin.get("chat_type", "")),- "display_name": entry.get("display_name", ""),- "user_name": origin.get("user_name", ""), "chat_name": origin.get("chat_name", ""),- "chat_id": origin.get("chat_id", ""), "thread_id": origin.get("thread_id"),- "updated_at": entry.get("updated_at", ""), "created_at": entry.get("created_at", ""),- "input_tokens": entry.get("input_tokens", 0), "output_tokens": entry.get("output_tokens", 0),- "total_tokens": entry.get("total_tokens", 0),- }, indent=2)-- def messages_read(self, session_key: str, limit: int = 50) -> str:- """Read recent messages from a conversation.-- Returns the message history in chronological order with role, content,- and timestamp for each message.-- Args:- session_key: The session key from conversations_list- limit: Maximum number of messages to return (default 50, most recent)- """- limit = _coerce_int(limit, default=50, minimum=1, maximum=200)- all_messages, error = _conversation_messages(session_key)- if error:- return error- filtered = []- for msg in all_messages:- role = msg.get("role", "")- content = _extract_message_content(msg) if role in {"user", "assistant"} else ""- if content:- filtered.append({"id": str(msg.get("id", "")), "role": role,- "content": content[:2000], "timestamp": msg.get("timestamp", "")})- messages = filtered[-limit:]- return json.dumps({"session_key": session_key, "count": len(messages),- "total_in_session": len(filtered), "messages": messages}, indent=2)-- def attachments_fetch(self, session_key: str, message_id: str) -> str:- """List non-text attachments for a message in a conversation.-- Extracts images, media files, and other non-text content blocks- from the specified message.-- Args:- session_key: The session key from conversations_list- message_id: The message ID from messages_read- """- all_messages, error = _conversation_messages(session_key)- if error:- return error- target_msg = next((m for m in all_messages if str(m.get("id", "")) == message_id), None)- if not target_msg:- return json.dumps({"error": f"Message not found: {message_id}"})- attachments = _extract_attachments(target_msg)- return json.dumps({"message_id": message_id, "count": len(attachments), "attachments": attachments}, indent=2)-- def events_poll(self, after_cursor: int = 0, session_key: Optional[str] = None, limit: int = 20) -> str:- """Poll for new conversation events since a cursor position.-- Returns events that have occurred since the given cursor. Use the- returned next_cursor value for subsequent polls.-- Event types: message, approval_requested, approval_resolved-- Args:- after_cursor: Return events after this cursor (0 for all)- session_key: Optional filter to one conversation- limit: Maximum events to return (default 20)- """- after_cursor = _coerce_int(after_cursor, default=0, minimum=0, maximum=10**18)- limit = _coerce_int(limit, default=20, minimum=1, maximum=200)- result = self.bridge.poll_events(after_cursor=after_cursor, session_key=session_key, limit=limit)- return json.dumps(result, indent=2)-- def events_wait(self, after_cursor: int = 0, session_key: Optional[str] = None, timeout_ms: int = 30000) -> str:- """Wait for the next conversation event (long-poll).-- Blocks until a matching event arrives or the timeout expires.- Use this for near-real-time event delivery without polling.-- Args:- after_cursor: Wait for events after this cursor- session_key: Optional filter to one conversation- timeout_ms: Maximum wait time in milliseconds (default 30000)- """- after_cursor = _coerce_int(after_cursor, default=0, minimum=0, maximum=10**18)- timeout_ms = _coerce_int(timeout_ms, default=30000, minimum=0, maximum=300000) # cap 5 min- event = self.bridge.wait_for_event(after_cursor=after_cursor, session_key=session_key, timeout_ms=timeout_ms)- return json.dumps({"event": event} if event else {"event": None, "reason": "timeout"}, indent=2)-- def messages_send(self, target: str, message: str) -> str:- """Send a message to a platform conversation.-- The target format is "platform:chat_id" — same format used by the- channels_list tool. You can also use human-friendly channel names- that will be resolved automatically.-- Examples:- target="telegram:6308981865"- target="discord:#general"- target="slack:#engineering"-- Args:- target: Platform target in "platform:identifier" format- message: The message text to send- """- if not target or not message:- return json.dumps({"error": "Both target and message are required"})- try:- from tools.send_message_tool import send_message_tool- return send_message_tool({"action": "send", "target": target, "message": message})- except ImportError:- return json.dumps({"error": "Send message tool not available"})- except Exception as e:- return json.dumps({"error": f"Send failed: {e}"})-- def channels_list(self, platform: Optional[str] = None) -> str:- """List available messaging channels and targets across platforms.-- Returns channels that you can send messages to. The target strings- returned here can be used directly with the messages_send tool.-- Args:- platform: Filter by platform name (telegram, discord, slack, etc.)- """- directory = _load_channel_directory()- if not directory:- # No cached directory: derive send targets from the routing index.- targets, seen = [], set()- for key, entry in _load_sessions_index().items():- origin = entry.get("origin", {})- p = entry.get("platform") or origin.get("platform", "")- chat_id = origin.get("chat_id", "")- target_str = f"{p}:{chat_id}"- if not p or not chat_id or not _platform_matches(platform, p) or target_str in seen:- continue- seen.add(target_str)- targets.append({"target": target_str, "platform": p,- "name": entry.get("display_name") or origin.get("chat_name", ""),- "chat_type": entry.get("chat_type", origin.get("chat_type", ""))})- return json.dumps({"count": len(targets), "channels": targets}, indent=2)- channels = []- for plat, entries_list in directory.get("platforms", {}).items():- if not _platform_matches(platform, plat) or not isinstance(entries_list, list):- continue- for ch in entries_list:- if isinstance(ch, dict):- chat_id = ch.get("id", ch.get("chat_id", ""))- channels.append({"target": f"{plat}:{chat_id}" if chat_id else plat, "platform": plat,- "name": ch.get("name", ch.get("display_name", "")), "chat_type": ch.get("type", "")})- return json.dumps({"count": len(channels), "channels": channels}, indent=2)-- def permissions_list_open(self) -> str:- """List pending approval requests observed during this bridge session.-- Returns exec and plugin approval requests that the bridge has seen- since it started. Approvals are live-session only — older approvals- from before the bridge connected are not included.- """- approvals = self.bridge.list_pending_approvals()- return json.dumps({"count": len(approvals), "approvals": approvals}, indent=2)-- def permissions_respond(self, id: str, decision: str) -> str:- """Respond to a pending approval request.-- Args:- id: The approval ID from permissions_list_open- decision: One of "allow-once", "allow-always", or "deny"- """- if decision not in {"allow-once", "allow-always", "deny"}:- return json.dumps({"error": f"Invalid decision: {decision}. Must be allow-once, allow-always, or deny"})- return json.dumps(self.bridge.respond_to_approval(id, decision), indent=2)---# Registration order == list_tools order (wire format).-_TOOL_NAMES = (- "conversations_list", "conversation_get", "messages_read", "attachments_fetch",- "events_poll", "events_wait", "messages_send", "channels_list",- "permissions_list_open", "permissions_respond",-)---def create_mcp_server(event_bridge: Optional[EventBridge] = None) -> MCPServer:- """Create and return the Hermes MCP server with all tools registered."""- if not _MCP_SERVER_AVAILABLE:- raise ImportError(f"MCP server requires the 'mcp' package. Install with: {sys.executable} -m pip install 'mcp'")- mcp = MCPServer("hermes", instructions=(- "Hermes Agent messaging bridge. Use these tools to interact with "- "conversations across Telegram, Discord, Slack, WhatsApp, Signal, "- "Matrix, and other connected platforms."- ))- handlers = _ToolHandlers(event_bridge or EventBridge())- for name in _TOOL_NAMES:- mcp.tool()(getattr(handlers, name))- return mcp---def run_mcp_server(verbose: bool = False) -> None:- """Start the Hermes MCP server on stdio."""- if not _MCP_SERVER_AVAILABLE:- print("Error: MCP server requires the 'mcp' package.\n"- f"Install with: {sys.executable} -m pip install 'mcp'", file=sys.stderr)- sys.exit(1)- logging.basicConfig(level=logging.DEBUG if verbose else logging.WARNING, stream=sys.stderr)- bridge = EventBridge()- bridge.start()- server = create_mcp_server(event_bridge=bridge)- import asyncio-- async def _run():- try:- await server.run_stdio_async()- finally:- bridge.stop()-- try:- asyncio.run(_run())- except KeyboardInterrupt:- bridge.stop()diff --git a/plugins/AGENTS.md b/plugins/AGENTS.mdindex a9fc087d5f1..c04972ea9d0 100644--- a/plugins/AGENTS.md+++ b/plugins/AGENTS.md@@ -36,7 +36,10 @@ command. A hook with no concrete consumer is speculative infrastructure and is ronce the plugin dir exists): a later `hermes plugins remove` sticks, a failed install retries.Core special cases become `PlatformEntry` seams the plugin sets (`trusted_inbound`,`display_tier`, `shared_env_prefixes`), never a name check. A core `hermes auth <name>` login- becomes the plugin's own `hermes <name>` command (row field `cli`; the old spelling prints the new one).+ becomes the plugin's own `hermes <name>` command (row field `cli`; the old spelling prints the new one),+ and a nested core command becomes a top-level plugin command (`command` + `old_command`:+ `hermes mcp serve` → `hermes mcp-serve`). A feature with no in-home signal (MCP clients live+ outside Hermes) gets an `in_use` that is always False: hint only, never an automatic install.- **No new third-party-product plugins (June 2026).** Observability/metrics backends, vendor SaaSconnectors, analytics dashboards, paid-service tie-ins ship as standalone plugin repos(`~/.hermes/plugins/` or pip entry point) promoted in Discord `#plugins-skills-and-skins`. Reason:diff --git a/skills/autonomous-ai-agents/hermes-agent/references/cli-reference.md b/skills/autonomous-ai-agents/hermes-agent/references/cli-reference.mdindex f68b358cb5f..1104b1bdadb 100644--- a/skills/autonomous-ai-agents/hermes-agent/references/cli-reference.md+++ b/skills/autonomous-ai-agents/hermes-agent/references/cli-reference.md@@ -68,7 +68,7 @@ hermes bundles Skill bundles (one /<name> alias loads several skillhermes mcp add NAME (--url or --command) | remove | list | test NAMEhermes mcp catalog | install NAME Curated catalog installhermes mcp configure NAME Toggle tool selection-hermes mcp serve Run Hermes as an MCP server+hermes mcp-serve Run Hermes as an MCP server (mcp-serve plugin)```Details (transport, tool discovery, catalog): `references/native-mcp.md`.diff --git a/tests/gateway/test_branch_routing_columns.py b/tests/gateway/test_branch_routing_columns.pyindex 9171840ddff..dbd5b3b4083 100644--- a/tests/gateway/test_branch_routing_columns.py+++ b/tests/gateway/test_branch_routing_columns.py@@ -139,7 +139,7 @@ class TestBranchRoutingColumns:)# origin_json completes the identity (#82633 reset-path pattern):# consumers reading routing/presentation data from state.db- # (mcp_serve, mirror, channel directory) need the full origin on+ # (the mcp-serve plugin, mirror, channel directory) need the full origin on# the branch row without waiting for any backfill.assert row["origin_json"], ("branched session lost origin_json — state.db consumers see an "diff --git a/tests/hermes_cli/test_argparse_flag_propagation.py b/tests/hermes_cli/test_argparse_flag_propagation.pyindex e561a4ca61b..9d5a6957ef1 100644--- a/tests/hermes_cli/test_argparse_flag_propagation.py+++ b/tests/hermes_cli/test_argparse_flag_propagation.py@@ -100,7 +100,7 @@ class TestChatVerboseArg:class TestAcceptHooksOnAgentSubparsers:"""Verify --accept-hooks is accepted at every agent-subcommandposition (before the subcommand, between group/subcommand, and- after the leaf subcommand) for gateway/cron/mcp/acp. Regression+ after the leaf subcommand) for gateway/cron/acp. Regressionagainst prior behaviour where the flag only worked on the rootparser and `chat`, so `hermes gateway run --accept-hooks` failedwith `unrecognized arguments`."""@@ -113,17 +113,14 @@ class TestAcceptHooksOnAgentSubparsers:["cron", "--accept-hooks", "tick", "--help"],["cron", "tick", "--accept-hooks", "--help"],["cron", "run", "--accept-hooks", "dummy-id", "--help"],- ["--accept-hooks", "mcp", "serve", "--help"],- ["mcp", "--accept-hooks", "serve", "--help"],- ["mcp", "serve", "--accept-hooks", "--help"],["acp", "--accept-hooks", "--help"],]# One driver subprocess parses ALL argvs: hermes_cli.main is a very heavy# import (previously 11 separate `python -m hermes_cli.main` spawns with a# 15s timeout each — a cold import on a loaded CI worker regularly blew- # that deadline, making this test flaky). Importing once and parsing 11- # times removes the repeated-import cost entirely; the generous timeout+ # that deadline, making this test flaky). Importing once and parsing each+ # argv removes the repeated-import cost entirely; the generous timeout# only trips on a genuine hang. `--help` exits via SystemExit(0), which# the driver catches per argv._DRIVER = r"""diff --git a/tests/hermes_cli/test_cli_startup_trim.py b/tests/hermes_cli/test_cli_startup_trim.pyindex a414b0c0fe8..9e467504613 100644--- a/tests/hermes_cli/test_cli_startup_trim.py+++ b/tests/hermes_cli/test_cli_startup_trim.py@@ -59,7 +59,6 @@ def test_non_chat_agent_command_still_registers_hooks(monkeypatch):@pytest.mark.parametrize(("command", "subcommand", "interactive"), [("gateway", {"gateway_command": "run"}, False), # a service: a hidden console is not a person (#127822)("cron", {"cron_command": "tick"}, False), # scheduled: nobody at the console- ("mcp", {"mcp_action": "serve"}, False), # stdin carries the protocol stream("acp", {}, False), # stdin carries the protocol stream("rl", {}, True), # a foreground command may still ask at its terminal])diff --git a/tests/hermes_cli/test_left_core_migration.py b/tests/hermes_cli/test_left_core_migration.pyindex 5a2a249e508..c5a83cc0e8a 100644--- a/tests/hermes_cli/test_left_core_migration.py+++ b/tests/hermes_cli/test_left_core_migration.py@@ -378,6 +378,36 @@ def test_old_spotify_commands_point_at_the_plugin(tmp_path, monkeypatch):assert lcm.moved_command_hint("hermes", "honcho") == ""+def test_old_mcp_serve_spelling_names_the_plugin_command(tmp_path, monkeypatch, capsys):+ """`hermes mcp serve` (what MCP client configs launch) exits 2 with the new spelling and the install+ line on stderr, never on stdout (the MCP wire); once the plugin is installed only the spelling."""+ import sys++ from hermes_cli import main as main_mod+ home = _home(tmp_path)+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setattr(sys, "argv", ["hermes", "mcp", "serve", "--tools"])+ parser, _ = main_mod._build_cli_parser()+ with pytest.raises(SystemExit) as exc:+ parser.parse_args(["mcp", "serve", "--tools"])+ out, err = capsys.readouterr()+ assert exc.value.code == 2 and out == ""+ assert "`hermes mcp serve` is now `hermes mcp-serve`" in err+ assert "plugins install mcp-serve" in err+ (home / "plugins" / "mcp-serve").mkdir(parents=True)+ hint = lcm.moved_command_hint("hermes mcp", "serve")+ assert "is now `hermes mcp-serve`" in hint and "install" not in hint+++def test_mcp_serve_is_never_installed_automatically(tmp_path):+ """MCP clients live outside Hermes, so no home shows the feature in use: hint only, no install."""+ installs = []+ home = _home(tmp_path, config="mcp_servers:\n hermes:\n command: hermes\n args: [mcp, serve]\n")+ assert lcm.migrate_home(home, install=lambda name: installs.append(name) or {"ok": True},+ say=lambda _m: None) == []+ assert installs == []++_LANGFUSE_KEYS_ENV = "HERMES_LANGFUSE_PUBLIC_KEY=pk-lf-x\nHERMES_LANGFUSE_SECRET_KEY=sk-lf-x\n"diff --git a/tests/hermes_cli/test_mcp_startup.py b/tests/hermes_cli/test_mcp_startup.pyindex 4f64730553c..10ba9f954fb 100644--- a/tests/hermes_cli/test_mcp_startup.py+++ b/tests/hermes_cli/test_mcp_startup.py@@ -170,46 +170,6 @@ def test_prepare_agent_startup_skips_discovery_when_chat_resolves_to_tui(assert mcp_startup._current_home_thread() is None-def test_prepare_agent_startup_keeps_discovery_for_non_chat_commands(- monkeypatch,-):- """Non-chat commands never launch the TUI, so they must keep their own- MCP discovery even when the ambient display config resolves to TUI —- ``_is_tui_chat_launch`` must not consult ``_resolve_use_tui`` there."""- calls = {"inline": 0}-- monkeypatch.setattr(main_mod, "_resolve_use_tui", lambda _args: True)- monkeypatch.setitem(- sys.modules,- "hermes_cli.plugins",- types.SimpleNamespace(discover_plugins=lambda: None),- )- monkeypatch.setitem(- sys.modules,- "hermes_cli.config",- types.SimpleNamespace(- read_raw_config=lambda: {"mcp_servers": {"demo": {"transport": "stdio"}}},- load_config=dict,- ),- )- monkeypatch.setitem(- sys.modules,- "agent.shell_hooks",- types.SimpleNamespace(register_from_config=lambda *_a, **_k: None),- )- monkeypatch.setitem(- sys.modules,- "tools.mcp_tool_discovery",- types.SimpleNamespace(- discover_mcp_tools=lambda: calls.__setitem__("inline", calls["inline"] + 1),- ),- )-- main_mod._prepare_agent_startup(_agent_args(command="mcp", mcp_action="serve"))-- assert calls["inline"] == 1--def test_background_mcp_discovery_suppresses_interactive_oauth(monkeypatch):state = {"active": False, "during_discover": None}@@ -454,7 +414,6 @@ def test_prepare_agent_startup_installs_server_filter(monkeypatch, _reset_mcp_setypes.SimpleNamespace(discover_plugins=lambda: None),)monkeypatch.setattr(main_mod, "_should_background_mcp_startup", lambda args: False)- monkeypatch.setattr(main_mod, "_command_has_dedicated_mcp_startup", lambda args: True)main_mod._prepare_agent_startup(_agent_args(toolsets="terminal,code-mcp"))assert mcp_startup.get_mcp_server_filter() == ["terminal", "code-mcp"]diff --git a/tests/test_mcp_serve.py b/tests/test_mcp_serve.pydeleted file mode 100644index b898bb003b1..00000000000--- a/tests/test_mcp_serve.py+++ /dev/null@@ -1,1394 +0,0 @@-"""-Tests for mcp_serve — Hermes MCP server.--Three layers of tests:-1. Unit tests — helpers, content extraction, attachment parsing-2. EventBridge tests — queue mechanics, cursors, waiters, concurrency-3. End-to-end tests — call actual MCP tools through the MCPServer's public API- with real session data in SQLite and sessions.json-"""--import asyncio-import inspect-import json-import os-import sqlite3-import time-import threading-from unittest.mock import MagicMock--import pytest--# ----------------------------------------------------------------------------# Fixtures-# ----------------------------------------------------------------------------[email protected](autouse=True)-def _isolate_hermes_home(tmp_path, monkeypatch):- """Redirect HERMES_HOME to a temp directory."""- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- try:- import hermes_constants- monkeypatch.setattr(hermes_constants, "get_hermes_home", lambda: tmp_path)- except (ImportError, AttributeError):- pass- return tmp_path--def sessions_dir(tmp_path):- sdir = tmp_path / "sessions"- sdir.mkdir(parents=True, exist_ok=True)- return sdir--def sample_sessions():- return {- "agent:main:telegram:dm:123456": {- "session_key": "agent:main:telegram:dm:123456",- "session_id": "20260329_120000_abc123",- "platform": "telegram",- "chat_type": "dm",- "display_name": "Alice",- "created_at": "2026-03-29T12:00:00",- "updated_at": "2026-03-29T14:30:00",- "input_tokens": 50000,- "output_tokens": 2000,- "total_tokens": 52000,- "origin": {- "platform": "telegram",- "chat_id": "123456",- "chat_name": "Alice",- "chat_type": "dm",- "user_id": "123456",- "user_name": "Alice",- "thread_id": None,- "chat_topic": None,- },- },- "agent:main:discord:group:789:456": {- "session_key": "agent:main:discord:group:789:456",- "session_id": "20260329_100000_def456",- "platform": "discord",- "chat_type": "group",- "display_name": "Bob",- "created_at": "2026-03-29T10:00:00",- "updated_at": "2026-03-29T13:00:00",- "input_tokens": 30000,- "output_tokens": 1000,- "total_tokens": 31000,- "origin": {- "platform": "discord",- "chat_id": "789",- "chat_name": "#general",- "chat_type": "group",- "user_id": "456",- "user_name": "Bob",- "thread_id": None,- "chat_topic": None,- },- },- "agent:main:slack:group:C1234:U5678": {- "session_key": "agent:main:slack:group:C1234:U5678",- "session_id": "20260328_090000_ghi789",- "platform": "slack",- "chat_type": "group",- "display_name": "Carol",- "created_at": "2026-03-28T09:00:00",- "updated_at": "2026-03-28T11:00:00",- "input_tokens": 10000,- "output_tokens": 500,- "total_tokens": 10500,- "origin": {- "platform": "slack",- "chat_id": "C1234",- "chat_name": "#engineering",- "chat_type": "group",- "user_id": "U5678",- "user_name": "Carol",- "thread_id": None,- "chat_topic": None,- },- },- }--def populated_sessions_dir(sessions_dir, sample_sessions):- (sessions_dir / "sessions.json").write_text(json.dumps(sample_sessions))- return sessions_dir--def _create_test_db(db_path, session_id, messages):- """Create a minimal SQLite DB mimicking hermes_state schema."""- conn = sqlite3.connect(str(db_path))- conn.execute("""- CREATE TABLE IF NOT EXISTS sessions (- id TEXT PRIMARY KEY,- source TEXT DEFAULT 'cli',- started_at TEXT,- message_count INTEGER DEFAULT 0- )- """)- conn.execute("""- CREATE TABLE IF NOT EXISTS messages (- id INTEGER PRIMARY KEY AUTOINCREMENT,- session_id TEXT NOT NULL,- role TEXT NOT NULL,- content TEXT,- tool_call_id TEXT,- tool_calls TEXT,- tool_name TEXT,- timestamp TEXT,- token_count INTEGER DEFAULT 0,- finish_reason TEXT,- reasoning TEXT,- reasoning_details TEXT,- codex_reasoning_items TEXT- )- """)- conn.execute(- "INSERT OR IGNORE INTO sessions (id, source, started_at, message_count) VALUES (?, 'gateway', ?, ?)",- (session_id, "2026-03-29T12:00:00", len(messages)),- )- for msg in messages:- content = msg.get("content", "")- if isinstance(content, (list, dict)):- content = json.dumps(content)- conn.execute(- "INSERT INTO messages (session_id, role, content, timestamp, tool_calls) VALUES (?, ?, ?, ?, ?)",- (session_id, msg["role"], content,- msg.get("timestamp", "2026-03-29T12:00:00"),- json.dumps(msg["tool_calls"]) if msg.get("tool_calls") else None),- )- conn.commit()- conn.close()--def mock_session_db(tmp_path, populated_sessions_dir):- """Create a real SQLite DB with test messages and wire it up."""- db_path = tmp_path / "state.db"- messages = [- {"role": "user", "content": "Hello Alice!", "timestamp": "2026-03-29T12:00:01"},- {"role": "assistant", "content": "Hi! How can I help?", "timestamp": "2026-03-29T12:00:05"},- {"role": "user", "content": "Check the image MEDIA: /tmp/screenshot.png please",- "timestamp": "2026-03-29T12:01:00"},- {"role": "assistant", "content": "I see the screenshot. It shows a terminal.",- "timestamp": "2026-03-29T12:01:10"},- {"role": "tool", "content": '{"result": "ok"}', "timestamp": "2026-03-29T12:01:15"},- {"role": "user", "content": "Thanks!", "timestamp": "2026-03-29T12:02:00"},- ]- _create_test_db(db_path, "20260329_120000_abc123", messages)-- # Create a mock SessionDB that reads from our test DB- class TestSessionDB:- def __init__(self):- self._db_path = db_path-- def get_messages(self, session_id):- conn = sqlite3.connect(str(self._db_path))- conn.row_factory = sqlite3.Row- rows = conn.execute(- "SELECT * FROM messages WHERE session_id = ? ORDER BY id",- (session_id,),- ).fetchall()- conn.close()- result = []- for r in rows:- d = dict(r)- if d.get("tool_calls"):- d["tool_calls"] = json.loads(d["tool_calls"])- result.append(d)- return result-- return TestSessionDB()--class _FakeTool:- def __init__(self, fn):- self.name = fn.__name__- self.description = inspect.getdoc(fn) or ""- self.fn = fn--class _FakeToolManager:- def __init__(self):- self._tools = {}-- def add_tool(self, fn):- self._tools[fn.__name__] = _FakeTool(fn)-- async def call_tool(self, name, args=None):- return self._tools[name].fn(**(args or {}))-- def list_tools(self):- return list(self._tools.values())--class _FakeMCPServer:- """Stand-in for ``mcp.server.MCPServer`` (``FastMCP`` before mcp 2.0)."""-- def __init__(self, *args, **kwargs):- self._tool_manager = _FakeToolManager()-- def tool(self):- def decorator(fn):- self._tool_manager.add_tool(fn)- return fn-- return decorator-- async def call_tool(self, name, args=None):- """Dispatch straight to the handler, with no schema validation.-- Mirrors ``MCPServer.call_tool``'s name so ``_run_tool`` works against- either server, but deliberately skips the SDK's pydantic coercion:- the parameter-coercion tests exist to prove the handlers' own- ``_coerce_int`` guards hold when a client sends a wrongly-typed value,- which the real server would reject before the handler ever ran.- """- return await self._tool_manager.call_tool(name, args)--def fake_mcp_server(populated_sessions_dir, mock_session_db, monkeypatch):- import mcp_serve-- monkeypatch.setattr(mcp_serve, "_get_sessions_dir", lambda: populated_sessions_dir)- monkeypatch.setattr(mcp_serve, "_get_session_db", lambda: mock_session_db)- monkeypatch.setattr(mcp_serve, "_load_channel_directory", dict)- monkeypatch.setattr(mcp_serve, "_MCP_SERVER_AVAILABLE", True)- monkeypatch.setattr(mcp_serve, "MCPServer", _FakeMCPServer)-- bridge = mcp_serve.EventBridge()- server = mcp_serve.create_mcp_server(event_bridge=bridge)- return server, bridge--# ----------------------------------------------------------------------------# 1. UNIT TESTS — helpers, extraction, attachments-# -----------------------------------------------------------------------------class TestHelpers:- def test_load_session_messages_closes_database_on_error(self, monkeypatch):- import mcp_serve-- db = MagicMock()- db.get_messages.side_effect = RuntimeError("read failed")- monkeypatch.setattr(mcp_serve, "_get_session_db", lambda: db)-- messages, error = mcp_serve._load_session_messages("s1")-- assert messages is None- assert "read failed" in error- db.close.assert_called_once()-- def test_get_sessions_dir(self, tmp_path):- from mcp_serve import _get_sessions_dir- result = _get_sessions_dir()- assert result == tmp_path / "sessions"-- def test_coerce_int_handles_invalid_and_out_of_range_values(self):- from mcp_serve import _coerce_int-- assert _coerce_int(None, default=50, minimum=1, maximum=200) == 50- assert _coerce_int("20", default=50, minimum=1, maximum=200) == 20- assert _coerce_int("bad", default=50, minimum=1, maximum=200) == 50- assert _coerce_int(999, default=50, minimum=1, maximum=200) == 200- assert _coerce_int(-5, default=50, minimum=1, maximum=200) == 1-- def test_load_sessions_index_empty(self, sessions_dir, monkeypatch):- import mcp_serve- monkeypatch.setattr(mcp_serve, "_get_sessions_dir", lambda: sessions_dir)- assert mcp_serve._load_sessions_index() == {}-- def test_load_sessions_index_with_data(self, populated_sessions_dir, monkeypatch):- import mcp_serve- monkeypatch.setattr(mcp_serve, "_get_sessions_dir", lambda: populated_sessions_dir)- result = mcp_serve._load_sessions_index()- assert len(result) == 3-- def test_load_sessions_index_corrupt(self, sessions_dir, monkeypatch):- (sessions_dir / "sessions.json").write_text("not json!")- import mcp_serve- monkeypatch.setattr(mcp_serve, "_get_sessions_dir", lambda: sessions_dir)- assert mcp_serve._load_sessions_index() == {}--class TestContentExtraction:- def test_text(self):- from mcp_serve import _extract_message_content- assert _extract_message_content({"content": "Hello"}) == "Hello"-- def test_multipart(self):- from mcp_serve import _extract_message_content- msg = {"content": [- {"type": "text", "text": "A"},- {"type": "image", "url": "http://x.com/i.png"},- {"type": "text", "text": "B"},- ]}- assert _extract_message_content(msg) == "A\nB"-- def test_empty(self):- from mcp_serve import _extract_message_content- assert _extract_message_content({"content": ""}) == ""- assert _extract_message_content({}) == ""- assert _extract_message_content({"content": None}) == ""--class TestAttachmentExtraction:- def test_image_url_block(self):- from mcp_serve import _extract_attachments- msg = {"content": [- {"type": "image_url", "image_url": {"url": "http://x.com/pic.jpg"}},- ]}- att = _extract_attachments(msg)- assert len(att) == 1- assert att[0] == {"type": "image", "url": "http://x.com/pic.jpg"}-- def test_media_tag_in_text(self):- from mcp_serve import _extract_attachments- msg = {"content": "Here MEDIA: /tmp/out.png done"}- att = _extract_attachments(msg)- assert len(att) == 1- assert att[0] == {"type": "media", "path": "/tmp/out.png"}-- def test_multiple_media_tags(self):- from mcp_serve import _extract_attachments- msg = {"content": "MEDIA: /a.png and MEDIA: /b.mp3"}- assert len(_extract_attachments(msg)) == 2-- def test_no_attachments(self):- from mcp_serve import _extract_attachments- assert _extract_attachments({"content": "plain text"}) == []-- def test_image_content_block(self):- from mcp_serve import _extract_attachments- msg = {"content": [{"type": "image", "url": "http://x.com/p.png"}]}- att = _extract_attachments(msg)- assert att[0]["type"] == "image"--# ----------------------------------------------------------------------------# 2. EVENT BRIDGE TESTS — queue, cursors, waiters, concurrency-# -----------------------------------------------------------------------------class TestEventBridge:-- def test_enqueue_and_poll(self):- from mcp_serve import EventBridge, QueueEvent- b = EventBridge()- b._enqueue(QueueEvent(cursor=0, type="message", session_key="k1",- data={"content": "hi"}))- r = b.poll_events(after_cursor=0)- assert len(r["events"]) == 1- assert r["events"][0]["type"] == "message"- assert r["next_cursor"] == 1-- def test_cursor_filter(self):- from mcp_serve import EventBridge, QueueEvent- b = EventBridge()- for i in range(5):- b._enqueue(QueueEvent(cursor=0, type="message", session_key=f"s{i}"))- r = b.poll_events(after_cursor=3)- assert len(r["events"]) == 2- assert r["events"][0]["session_key"] == "s3"-- def test_poll_limit(self):- from mcp_serve import EventBridge, QueueEvent- b = EventBridge()- for i in range(10):- b._enqueue(QueueEvent(cursor=0, type="message", session_key=f"s{i}"))- r = b.poll_events(after_cursor=0, limit=3)- assert len(r["events"]) == 3-- def test_wait_immediate(self):- from mcp_serve import EventBridge, QueueEvent- b = EventBridge()- b._enqueue(QueueEvent(cursor=0, type="message", session_key="t",- data={"content": "hi"}))- event = b.wait_for_event(after_cursor=0, timeout_ms=100)- assert event is not None- assert event["type"] == "message"-- def test_wait_timeout(self):- from mcp_serve import EventBridge- start = time.monotonic()- event = EventBridge().wait_for_event(after_cursor=0, timeout_ms=150)- assert event is None- assert time.monotonic() - start >= 0.1-- def test_wait_wakes_on_enqueue(self):- from mcp_serve import EventBridge, QueueEvent- b = EventBridge()- result = [None]-- def waiter():- result[0] = b.wait_for_event(after_cursor=0, timeout_ms=5000)-- t = threading.Thread(target=waiter)- t.start()- time.sleep(0.05)- b._enqueue(QueueEvent(cursor=0, type="message", session_key="wake"))- t.join(timeout=2)- assert result[0] is not None- assert result[0]["session_key"] == "wake"-- def test_queue_limit(self):- from mcp_serve import EventBridge, QueueEvent, QUEUE_LIMIT- b = EventBridge()- for i in range(QUEUE_LIMIT + 50):- b._enqueue(QueueEvent(cursor=0, type="message", session_key=f"s{i}"))- assert len(b._queue) == QUEUE_LIMIT-- def test_concurrent_enqueue(self):- from mcp_serve import EventBridge, QueueEvent- b = EventBridge()- errors = []-- def batch(start):- try:- for i in range(100):- b._enqueue(QueueEvent(cursor=0, type="message",- session_key=f"s{start}_{i}"))- except Exception as e:- errors.append(e)-- threads = [threading.Thread(target=batch, args=(i,)) for i in range(5)]- for t in threads:- t.start()- for t in threads:- t.join()- assert not errors- assert len(b._queue) == 500- assert b._cursor == 500-- def test_approvals_lifecycle(self):- from mcp_serve import EventBridge- b = EventBridge()- b._pending_approvals["a1"] = {- "id": "a1", "kind": "exec",- "description": "rm -rf /tmp",- "session_key": "test", "created_at": "2026-03-29T12:00:00",- }- assert len(b.list_pending_approvals()) == 1- result = b.respond_to_approval("a1", "deny")- assert result["resolved"] is True- assert len(b.list_pending_approvals()) == 0-- def test_respond_nonexistent(self):- from mcp_serve import EventBridge- r = EventBridge().respond_to_approval("nope", "deny")- assert "error" in r--# ----------------------------------------------------------------------------# 3. END-TO-END TESTS — call MCP tools through the MCP server-# -----------------------------------------------------------------------------def mcp_server_e2e(populated_sessions_dir, mock_session_db, monkeypatch, require_mcp_2_sdk):- """Create a fully wired MCP server for E2E testing (pinned SDK: 1.x lacks mcp.server.MCPServer)."""- import mcp_serve- monkeypatch.setattr(mcp_serve, "_get_sessions_dir", lambda: populated_sessions_dir)- monkeypatch.setattr(mcp_serve, "_get_session_db", lambda: mock_session_db)- monkeypatch.setattr(mcp_serve, "_load_channel_directory", dict)-- bridge = mcp_serve.EventBridge()- server = mcp_serve.create_mcp_server(event_bridge=bridge)- return server, bridge--def _run_tool(server, name, args=None):- """Call an MCP tool through the server's public API and return parsed JSON.-- Goes through ``MCPServer.call_tool`` rather than the private- ``_tool_manager`` the FastMCP-era version reached into: mcp 2.0's- ``ToolManager.call_tool`` gained a required ``context`` argument, and the- public method is what an actual MCP client exercises anyway. It returns a- ``CallToolResult``, so unwrap the text content block our tools produce.- """- result = asyncio.get_event_loop().run_until_complete(- server.call_tool(name, args or {})- )- if isinstance(result, str): # FastMCP-era shape- return json.loads(result)- text = "".join(- block.text for block in (getattr(result, "content", None) or [])- if getattr(block, "text", None)- )- return json.loads(text) if text else result--def _event_loop():- """Ensure an event loop exists for sync tests calling async tools."""- loop = asyncio.new_event_loop()- asyncio.set_event_loop(loop)- yield loop- loop.close()--class TestE2EConversationsList:- def test_list_all(self, mcp_server_e2e, _event_loop):- server, _ = mcp_server_e2e- result = _run_tool(server, "conversations_list")- assert result["count"] == 3- platforms = {c["platform"] for c in result["conversations"]}- assert platforms == {"telegram", "discord", "slack"}-- def test_list_sorted_by_updated(self, mcp_server_e2e, _event_loop):- server, _ = mcp_server_e2e- result = _run_tool(server, "conversations_list")- keys = [c["session_key"] for c in result["conversations"]]- # Telegram (14:30) > Discord (13:00) > Slack (11:00)- assert keys[0] == "agent:main:telegram:dm:123456"- assert keys[1] == "agent:main:discord:group:789:456"- assert keys[2] == "agent:main:slack:group:C1234:U5678"-- def test_filter_by_platform(self, mcp_server_e2e, _event_loop):- server, _ = mcp_server_e2e- result = _run_tool(server, "conversations_list", {"platform": "discord"})- assert result["count"] == 1- assert result["conversations"][0]["platform"] == "discord"-- def test_filter_by_platform_case_insensitive(self, mcp_server_e2e, _event_loop):- server, _ = mcp_server_e2e- result = _run_tool(server, "conversations_list", {"platform": "TELEGRAM"})- assert result["count"] == 1-- def test_search_by_name(self, mcp_server_e2e, _event_loop):- server, _ = mcp_server_e2e- result = _run_tool(server, "conversations_list", {"search": "Alice"})- assert result["count"] == 1- assert result["conversations"][0]["display_name"] == "Alice"-- def test_search_no_match(self, mcp_server_e2e, _event_loop):- server, _ = mcp_server_e2e- result = _run_tool(server, "conversations_list", {"search": "nobody"})- assert result["count"] == 0-- def test_limit(self, mcp_server_e2e, _event_loop):- server, _ = mcp_server_e2e- result = _run_tool(server, "conversations_list", {"limit": 2})- assert result["count"] == 2--class TestE2EConversationGet:- def test_get_existing(self, mcp_server_e2e, _event_loop):- server, _ = mcp_server_e2e- result = _run_tool(server, "conversation_get",- {"session_key": "agent:main:telegram:dm:123456"})- assert result["platform"] == "telegram"- assert result["display_name"] == "Alice"- assert result["chat_id"] == "123456"- assert result["input_tokens"] == 50000-- def test_get_nonexistent(self, mcp_server_e2e, _event_loop):- server, _ = mcp_server_e2e- result = _run_tool(server, "conversation_get",- {"session_key": "nonexistent:key"})- assert "error" in result--class TestE2EMessagesRead:- def test_read_messages(self, mcp_server_e2e, _event_loop):- server, _ = mcp_server_e2e- result = _run_tool(server, "messages_read",- {"session_key": "agent:main:telegram:dm:123456"})- assert result["count"] > 0- # Should filter out tool messages — only user/assistant- roles = {m["role"] for m in result["messages"]}- assert "tool" not in roles- assert "user" in roles- assert "assistant" in roles-- def test_read_messages_content(self, mcp_server_e2e, _event_loop):- server, _ = mcp_server_e2e- result = _run_tool(server, "messages_read",- {"session_key": "agent:main:telegram:dm:123456"})- contents = [m["content"] for m in result["messages"]]- assert "Hello Alice!" in contents- assert "Hi! How can I help?" in contents-- def test_read_messages_have_ids(self, mcp_server_e2e, _event_loop):- server, _ = mcp_server_e2e- result = _run_tool(server, "messages_read",- {"session_key": "agent:main:telegram:dm:123456"})- for msg in result["messages"]:- assert "id" in msg- assert msg["id"] # non-empty-- def test_read_with_limit(self, mcp_server_e2e, _event_loop):- server, _ = mcp_server_e2e- result = _run_tool(server, "messages_read",- {"session_key": "agent:main:telegram:dm:123456",- "limit": 2})- assert result["count"] == 2-- def test_read_nonexistent_session(self, mcp_server_e2e, _event_loop):- server, _ = mcp_server_e2e- result = _run_tool(server, "messages_read",- {"session_key": "nonexistent:key"})- assert "error" in result--class TestE2EAttachmentsFetch:- def test_fetch_media_from_message(self, mcp_server_e2e, _event_loop):- server, _ = mcp_server_e2e- # First get message IDs- msgs = _run_tool(server, "messages_read",- {"session_key": "agent:main:telegram:dm:123456"})- # Find the message with MEDIA: tag- media_msg = None- for m in msgs["messages"]:- if "MEDIA:" in m["content"]:- media_msg = m- break- assert media_msg is not None, "Should have a message with MEDIA: tag"-- result = _run_tool(server, "attachments_fetch", {- "session_key": "agent:main:telegram:dm:123456",- "message_id": media_msg["id"],- })- assert result["count"] >= 1- assert result["attachments"][0]["type"] == "media"- assert result["attachments"][0]["path"] == "/tmp/screenshot.png"-- def test_fetch_from_nonexistent_message(self, mcp_server_e2e, _event_loop):- server, _ = mcp_server_e2e- result = _run_tool(server, "attachments_fetch", {- "session_key": "agent:main:telegram:dm:123456",- "message_id": "99999",- })- assert "error" in result-- def test_fetch_from_nonexistent_session(self, mcp_server_e2e, _event_loop):- server, _ = mcp_server_e2e- result = _run_tool(server, "attachments_fetch", {- "session_key": "nonexistent:key",- "message_id": "1",- })- assert "error" in result--class TestE2EEventsPoll:- def test_poll_empty(self, mcp_server_e2e, _event_loop):- server, _bridge = mcp_server_e2e- result = _run_tool(server, "events_poll")- assert result["events"] == []- assert result["next_cursor"] == 0-- def test_poll_with_events(self, mcp_server_e2e, _event_loop):- from mcp_serve import QueueEvent- server, bridge = mcp_server_e2e- bridge._enqueue(QueueEvent(cursor=0, type="message",- session_key="agent:main:telegram:dm:123456",- data={"role": "user", "content": "Hello"}))- bridge._enqueue(QueueEvent(cursor=0, type="message",- session_key="agent:main:telegram:dm:123456",- data={"role": "assistant", "content": "Hi"}))-- result = _run_tool(server, "events_poll")- assert len(result["events"]) == 2- assert result["events"][0]["content"] == "Hello"- assert result["events"][1]["content"] == "Hi"- assert result["next_cursor"] == 2-- def test_poll_cursor_pagination(self, mcp_server_e2e, _event_loop):- from mcp_serve import QueueEvent- server, bridge = mcp_server_e2e- for i in range(5):- bridge._enqueue(QueueEvent(cursor=0, type="message",- session_key=f"s{i}"))-- page1 = _run_tool(server, "events_poll", {"limit": 2})- assert len(page1["events"]) == 2- assert page1["next_cursor"] == 2-- page2 = _run_tool(server, "events_poll",- {"after_cursor": page1["next_cursor"], "limit": 2})- assert len(page2["events"]) == 2- assert page2["next_cursor"] == 4-- def test_poll_session_filter(self, mcp_server_e2e, _event_loop):- from mcp_serve import QueueEvent- server, bridge = mcp_server_e2e- bridge._enqueue(QueueEvent(cursor=0, type="message", session_key="a"))- bridge._enqueue(QueueEvent(cursor=0, type="message", session_key="b"))- bridge._enqueue(QueueEvent(cursor=0, type="message", session_key="a"))-- result = _run_tool(server, "events_poll",- {"session_key": "b"})- assert len(result["events"]) == 1--class TestE2EEventsWait:- def test_wait_timeout(self, mcp_server_e2e, _event_loop):- server, _ = mcp_server_e2e- result = _run_tool(server, "events_wait", {"timeout_ms": 100})- assert result["event"] is None- assert result["reason"] == "timeout"-- def test_wait_with_existing_event(self, mcp_server_e2e, _event_loop):- from mcp_serve import QueueEvent- server, bridge = mcp_server_e2e- bridge._enqueue(QueueEvent(cursor=0, type="message",- session_key="test",- data={"content": "waiting for this"}))- result = _run_tool(server, "events_wait", {"timeout_ms": 100})- assert result["event"] is not None- assert result["event"]["content"] == "waiting for this"--class TestMCPToolParameterCoercion:- def test_conversations_list_coerces_string_limit(self, fake_mcp_server, _event_loop):- server, _ = fake_mcp_server- result = _run_tool(server, "conversations_list", {"limit": "2"})- assert result["count"] == 2-- def test_messages_read_coerces_string_limit(self, fake_mcp_server, _event_loop):- server, _ = fake_mcp_server- result = _run_tool(- server,- "messages_read",- {"session_key": "agent:main:telegram:dm:123456", "limit": "2"},- )- assert result["count"] == 2-- def test_events_poll_coerces_string_cursor_and_limit(self, fake_mcp_server, _event_loop):- from mcp_serve import QueueEvent-- server, bridge = fake_mcp_server- bridge._enqueue(QueueEvent(cursor=0, type="message", session_key="a"))- bridge._enqueue(QueueEvent(cursor=0, type="message", session_key="b"))-- result = _run_tool(server, "events_poll", {"after_cursor": "0", "limit": "1"})- assert len(result["events"]) == 1- assert result["next_cursor"] == 1-- def test_events_wait_coerces_invalid_timeout(self, fake_mcp_server, _event_loop):- from mcp_serve import QueueEvent-- server, bridge = fake_mcp_server- bridge._enqueue(- QueueEvent(- cursor=0,- type="message",- session_key="test",- data={"content": "waiting for this"},- )- )-- result = _run_tool(server, "events_wait", {"after_cursor": "0", "timeout_ms": "bad"})- assert result["event"] is not None- assert result["event"]["content"] == "waiting for this"--class TestE2EMessagesSend:- def test_send_missing_args(self, mcp_server_e2e, _event_loop):- server, _ = mcp_server_e2e- result = _run_tool(server, "messages_send", {"target": "", "message": "hi"})- assert "error" in result--class TestE2EChannelsList:- def test_channels_from_sessions(self, mcp_server_e2e, _event_loop):- server, _ = mcp_server_e2e- result = _run_tool(server, "channels_list")- assert result["count"] == 3- targets = {c["target"] for c in result["channels"]}- assert "telegram:123456" in targets- assert "discord:789" in targets- assert "slack:C1234" in targets-- def test_channels_platform_filter(self, mcp_server_e2e, _event_loop):- server, _ = mcp_server_e2e- result = _run_tool(server, "channels_list", {"platform": "slack"})- assert result["count"] == 1- assert result["channels"][0]["target"] == "slack:C1234"-- def test_channels_with_directory(self, mcp_server_e2e, _event_loop, monkeypatch):- """Populated channel_directory.json should be unwrapped via the 'platforms' key.-- Regression test for issue #21474: the writer wraps platforms under- {"updated_at": ..., "platforms": {...}} but the reader was iterating- directory.items() directly, so channels_list always returned 0.- """- import mcp_serve- monkeypatch.setattr(mcp_serve, "_load_channel_directory", lambda: {- "updated_at": "2026-05-07T12:00:00",- "platforms": {- "telegram": [- {"id": "123456", "name": "Alice", "type": "dm"},- {"id": "-100999", "name": "Dev Group", "type": "group"},- ],- "discord": [- {"id": "789", "name": "general", "type": "text"},- ],- },- })- server, _ = mcp_server_e2e- result = _run_tool(server, "channels_list")- assert result["count"] == 3- targets = {c["target"] for c in result["channels"]}- assert targets == {"telegram:123456", "telegram:-100999", "discord:789"}-- def test_channels_with_directory_platform_filter(self, mcp_server_e2e, _event_loop, monkeypatch):- """Platform filter should work against the wrapped 'platforms' payload."""- import mcp_serve- monkeypatch.setattr(mcp_serve, "_load_channel_directory", lambda: {- "updated_at": "2026-05-07T12:00:00",- "platforms": {- "telegram": [{"id": "123456", "name": "Alice", "type": "dm"}],- "discord": [{"id": "789", "name": "general", "type": "text"}],- },- })- server, _ = mcp_server_e2e- result = _run_tool(server, "channels_list", {"platform": "discord"})- assert result["count"] == 1- assert result["channels"][0]["target"] == "discord:789"--class TestE2EPermissions:- def test_list_empty(self, mcp_server_e2e, _event_loop):- server, _ = mcp_server_e2e- result = _run_tool(server, "permissions_list_open")- assert result["count"] == 0- assert result["approvals"] == []-- def test_list_with_approvals(self, mcp_server_e2e, _event_loop):- server, bridge = mcp_server_e2e- bridge._pending_approvals["a1"] = {- "id": "a1", "kind": "exec",- "description": "sudo rm -rf /",- "session_key": "test",- "created_at": "2026-03-29T12:00:00",- }- result = _run_tool(server, "permissions_list_open")- assert result["count"] == 1- assert result["approvals"][0]["id"] == "a1"-- def test_respond_allow(self, mcp_server_e2e, _event_loop):- server, bridge = mcp_server_e2e- bridge._pending_approvals["a1"] = {"id": "a1", "kind": "exec"}- result = _run_tool(server, "permissions_respond",- {"id": "a1", "decision": "allow-once"})- assert result["resolved"] is True- assert result["decision"] == "allow-once"- # Should be gone now- check = _run_tool(server, "permissions_list_open")- assert check["count"] == 0-- def test_respond_deny(self, mcp_server_e2e, _event_loop):- server, bridge = mcp_server_e2e- bridge._pending_approvals["a2"] = {"id": "a2", "kind": "plugin"}- result = _run_tool(server, "permissions_respond",- {"id": "a2", "decision": "deny"})- assert result["resolved"] is True-- def test_respond_invalid_decision(self, mcp_server_e2e, _event_loop):- server, bridge = mcp_server_e2e- bridge._pending_approvals["a3"] = {"id": "a3", "kind": "exec"}- result = _run_tool(server, "permissions_respond",- {"id": "a3", "decision": "maybe"})- assert "error" in result-- def test_respond_nonexistent(self, mcp_server_e2e, _event_loop):- server, _ = mcp_server_e2e- result = _run_tool(server, "permissions_respond",- {"id": "nope", "decision": "deny"})- assert "error" in result--# ----------------------------------------------------------------------------# 4. TOOL LISTING — verify all 10 tools are registered-# -----------------------------------------------------------------------------class TestToolRegistration:-- def test_tools_have_descriptions(self, mcp_server_e2e, _event_loop):- server, _ = mcp_server_e2e- for tool in server._tool_manager.list_tools():- assert tool.description, f"Tool {tool.name} has no description"--# ----------------------------------------------------------------------------# 5. SERVER LIFECYCLE / CLI INTEGRATION-# -----------------------------------------------------------------------------class TestServerCreation:-- def test_create_without_mcp_sdk(self, monkeypatch):- import mcp_serve- monkeypatch.setattr(mcp_serve, "_MCP_SERVER_AVAILABLE", False)- with pytest.raises(ImportError, match="MCP server requires"):- mcp_serve.create_mcp_server()--class TestRunMcpServer:- def test_run_without_mcp_exits(self, monkeypatch):- import mcp_serve- monkeypatch.setattr(mcp_serve, "_MCP_SERVER_AVAILABLE", False)- with pytest.raises(SystemExit) as exc_info:- mcp_serve.run_mcp_server()- assert exc_info.value.code == 1--class TestCliIntegration:-- def test_dispatcher_routes_serve(self, monkeypatch, tmp_path):- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- mock_run = MagicMock()- monkeypatch.setattr("mcp_serve.run_mcp_server", mock_run)-- import argparse- args = argparse.Namespace(mcp_action="serve", verbose=True)- from hermes_cli.mcp_config import mcp_command- mcp_command(args)- mock_run.assert_called_once_with(verbose=True)--# ----------------------------------------------------------------------------# 6. EDGE CASES-# -----------------------------------------------------------------------------class TestEdgeCases:-- def test_sessions_without_origin(self, sessions_dir, monkeypatch):- data = {"agent:main:telegram:dm:111": {- "session_key": "agent:main:telegram:dm:111",- "session_id": "20260329_120000_xyz",- "platform": "telegram",- "updated_at": "2026-03-29T12:00:00",- }}- (sessions_dir / "sessions.json").write_text(json.dumps(data))- import mcp_serve- monkeypatch.setattr(mcp_serve, "_get_sessions_dir", lambda: sessions_dir)- entries = mcp_serve._load_sessions_index()- assert entries["agent:main:telegram:dm:111"]["platform"] == "telegram"--# ----------------------------------------------------------------------------# 7. EVENT BRIDGE POLL LOOP E2E — real SQLite DB, mtime optimization-# -----------------------------------------------------------------------------class TestEventBridgePollE2E:- """End-to-end tests for the EventBridge polling loop with real files."""-- def test_poll_detects_new_messages(self, tmp_path, monkeypatch):- """Write to SQLite + sessions.json, verify EventBridge picks it up."""- import mcp_serve- sessions_dir = tmp_path / "sessions"- sessions_dir.mkdir()- monkeypatch.setattr(mcp_serve, "_get_sessions_dir", lambda: sessions_dir)-- session_id = "20260329_150000_poll_test"- db_path = tmp_path / "state.db"-- # Write sessions.json- sessions_data = {- "agent:main:telegram:dm:poll_test": {- "session_key": "agent:main:telegram:dm:poll_test",- "session_id": session_id,- "platform": "telegram",- "chat_type": "dm",- "display_name": "PollTest",- "updated_at": "2026-03-29T15:00:05",- "origin": {"platform": "telegram", "chat_id": "poll_test"},- }- }- (sessions_dir / "sessions.json").write_text(json.dumps(sessions_data))-- # Write messages to SQLite- messages = [- {"role": "user", "content": "First message",- "timestamp": "2026-03-29T15:00:01"},- {"role": "assistant", "content": "Reply",- "timestamp": "2026-03-29T15:00:03"},- ]- _create_test_db(db_path, session_id, messages)-- # Create a mock SessionDB that reads our test DB- class TestDB:- def get_messages(self, sid):- conn = sqlite3.connect(str(db_path))- conn.row_factory = sqlite3.Row- rows = conn.execute(- "SELECT * FROM messages WHERE session_id = ? ORDER BY id",- (sid,),- ).fetchall()- conn.close()- return [dict(r) for r in rows]-- monkeypatch.setattr(mcp_serve, "_get_session_db", lambda: TestDB())-- bridge = mcp_serve.EventBridge()- # Run one poll cycle manually- bridge._poll_once(TestDB())-- # Should have found the messages- result = bridge.poll_events(after_cursor=0)- assert len(result["events"]) == 2- assert result["events"][0]["role"] == "user"- assert result["events"][0]["content"] == "First message"- assert result["events"][1]["role"] == "assistant"-- def test_poll_skips_when_unchanged(self, tmp_path, monkeypatch):- """Second poll with no file changes should be a no-op."""- import mcp_serve- sessions_dir = tmp_path / "sessions"- sessions_dir.mkdir()- monkeypatch.setattr(mcp_serve, "_get_sessions_dir", lambda: sessions_dir)-- session_id = "20260329_150000_skip_test"- db_path = tmp_path / "state.db"-- sessions_data = {- "agent:main:telegram:dm:skip": {- "session_key": "agent:main:telegram:dm:skip",- "session_id": session_id,- "platform": "telegram",- "updated_at": "2026-03-29T15:00:05",- "origin": {"platform": "telegram", "chat_id": "skip"},- }- }- (sessions_dir / "sessions.json").write_text(json.dumps(sessions_data))- _create_test_db(db_path, session_id, [- {"role": "user", "content": "Hello", "timestamp": "2026-03-29T15:00:01"},- ])-- class TestDB:- def __init__(self):- self.call_count = 0-- def get_messages(self, sid):- self.call_count += 1- conn = sqlite3.connect(str(db_path))- conn.row_factory = sqlite3.Row- rows = conn.execute(- "SELECT * FROM messages WHERE session_id = ? ORDER BY id",- (sid,),- ).fetchall()- conn.close()- return [dict(r) for r in rows]-- # The index comes from sessions.json: a real SessionDB open would migrate this minimal- # DB and move its mtime between the polls.- monkeypatch.setattr(mcp_serve, "_get_session_db", lambda: None)- db = TestDB()- bridge = mcp_serve.EventBridge()-- # First poll — should process- bridge._poll_once(db)- first_calls = db.call_count- assert first_calls >= 1-- # Second poll — files unchanged, should skip entirely- bridge._poll_once(db)- assert db.call_count == first_calls, \- "Second poll should skip DB queries when files unchanged"-- def test_poll_detects_new_message_after_db_write(self, tmp_path, monkeypatch):- """Write a new message to the DB after first poll, verify it's detected."""- import mcp_serve- sessions_dir = tmp_path / "sessions"- sessions_dir.mkdir()- monkeypatch.setattr(mcp_serve, "_get_sessions_dir", lambda: sessions_dir)-- session_id = "20260329_150000_new_msg"- db_path = tmp_path / "state.db"-- sessions_data = {- "agent:main:telegram:dm:new": {- "session_key": "agent:main:telegram:dm:new",- "session_id": session_id,- "platform": "telegram",- "updated_at": "2026-03-29T15:00:05",- "origin": {"platform": "telegram", "chat_id": "new"},- }- }- (sessions_dir / "sessions.json").write_text(json.dumps(sessions_data))- _create_test_db(db_path, session_id, [- {"role": "user", "content": "First", "timestamp": "2026-03-29T15:00:01"},- ])-- class TestDB:- def get_messages(self, sid):- conn = sqlite3.connect(str(db_path))- conn.row_factory = sqlite3.Row- rows = conn.execute(- "SELECT * FROM messages WHERE session_id = ? ORDER BY id",- (sid,),- ).fetchall()- conn.close()- return [dict(r) for r in rows]-- db = TestDB()- bridge = mcp_serve.EventBridge()-- # First poll- bridge._poll_once(db)- r1 = bridge.poll_events(after_cursor=0)- assert len(r1["events"]) == 1-- # Add a new message to the DB- conn = sqlite3.connect(str(db_path))- conn.execute(- "INSERT INTO messages (session_id, role, content, timestamp) VALUES (?, ?, ?, ?)",- (session_id, "assistant", "New reply!", "2026-03-29T15:00:10"),- )- conn.commit()- conn.close()- # Touch the DB file to update mtime (WAL mode may not update mtime on small writes)- before = db_path.stat()- os.utime(db_path, ns=(before.st_atime_ns, before.st_mtime_ns + 1_000_000_000))-- # Update sessions.json updated_at to trigger re-check- sessions_data["agent:main:telegram:dm:new"]["updated_at"] = "2026-03-29T15:00:10"- (sessions_dir / "sessions.json").write_text(json.dumps(sessions_data))-- # Second poll — should detect the new message- bridge._poll_once(db)- r2 = bridge.poll_events(after_cursor=r1["next_cursor"])- assert len(r2["events"]) == 1- assert r2["events"][0]["content"] == "New reply!"-- def test_poll_picks_up_new_conversation_on_db_change(- self, tmp_path, monkeypatch- ):- """A brand-new conversation must be picked up on the tick where- state.db changes.-- Since #9006 the routing index lives IN state.db (session rows carry- session_key/origin metadata), so a new conversation's registration and- its first message land in the same file — a single mtime check covers- both and the old dual-file (sessions.json + state.db) race (#8925) is- structurally impossible. This test asserts the index is refreshed on a- db-mtime bump, so a conversation the bridge has never seen before is- emitted on the same tick.- """- import mcp_serve-- sessions_dir = tmp_path / "sessions"- sessions_dir.mkdir()- monkeypatch.setattr(mcp_serve, "_get_sessions_dir", lambda: sessions_dir)-- # _poll_once reads <HERMES_HOME>/state.db for its mtime gate; the autouse- # fixture points HERMES_HOME at tmp_path.- db_path = tmp_path / "state.db"- db_path.write_text("placeholder")-- session_id = "20260329_150000_late_register"- # The routing index now comes from _load_sessions_index() (state.db- # primary, sessions.json fallback). Stub it to return the new- # conversation, simulating the gateway having just written the- # session row + first message in one state.db transaction.- monkeypatch.setattr(- mcp_serve, "_load_sessions_index",- lambda: {- "agent:main:telegram:dm:late": {- "session_id": session_id,- "platform": "telegram",- "origin": {"platform": "telegram", "chat_id": "late"},- }- },- )-- class DB:- def get_messages(self, sid):- return [{- "id": 1, "role": "user",- "content": "Hello from a freshly-registered conversation",- "timestamp": "2026-03-29T15:00:00",- }]-- bridge = mcp_serve.EventBridge()- # Bridge has never seen this db state and has an empty cached index —- # exactly the state after a new conversation's first write.- assert bridge._cached_sessions_index == {}-- bridge._poll_once(DB())-- result = bridge.poll_events(after_cursor=0)- assert len(result["events"]) == 1- assert result["events"][0]["session_key"] == "agent:main:telegram:dm:late"- assert result["events"][0]["content"].startswith("Hello from a freshly")-- def test_startup_baseline_suppresses_historical_replay(self, tmp_path, monkeypatch):- """start()'s baseline records existing history without emitting it, so a- fresh EventBridge does not replay stored messages on startup; only- messages written after the baseline are delivered."""- import mcp_serve-- db_path = tmp_path / "state.db"- db_path.write_text("placeholder")- session_id = "20260329_150000_history"- monkeypatch.setattr(- mcp_serve, "_load_sessions_index",- lambda: {- "agent:main:telegram:dm:hist": {- "session_id": session_id,- "platform": "telegram",- "origin": {"platform": "telegram", "chat_id": "hist"},- }- },- )- store = [{- "id": 1, "role": "user", "content": "pre-existing history",- "timestamp": "2026-03-29T15:00:00",- }]-- class DB:- def get_messages(self, sid):- return list(store)-- monkeypatch.setattr(mcp_serve, "_get_session_db", lambda: DB())-- bridge = mcp_serve.EventBridge()- bridge._establish_baseline()- # Messages that existed before start() are not replayed.- assert bridge.poll_events(after_cursor=0)["events"] == []-- # A message written after the baseline IS delivered on the next tick.- store.append({- "id": 2, "role": "assistant", "content": "arrived after start",- "timestamp": "2026-03-29T15:05:00",- })- before = db_path.stat()- os.utime(db_path, ns=(before.st_atime_ns, before.st_mtime_ns + 1_000_000_000)) # bump mtime so the poll gate opens- bridge._poll_once(DB())- events = bridge.poll_events(after_cursor=0)["events"]- assert len(events) == 1- assert events[0]["content"] == "arrived after start"-- def test_new_conversation_after_baseline_is_delivered(self, tmp_path, monkeypatch):- """A conversation that first appears AFTER the startup baseline is still- delivered on its state.db-change tick — sessions absent from the- baseline default to last_seen=0.0."""- import mcp_serve-- db_path = tmp_path / "state.db"- db_path.write_text("placeholder")- index: dict = {}- messages: dict = {}- monkeypatch.setattr(mcp_serve, "_load_sessions_index", lambda: dict(index))-- class DB:- def get_messages(self, sid):- return list(messages.get(sid, []))-- monkeypatch.setattr(mcp_serve, "_get_session_db", lambda: DB())-- bridge = mcp_serve.EventBridge()- bridge._establish_baseline() # no conversations exist yet-- # The gateway registers a brand-new conversation + its first message.- sid = "20260329_150000_fresh"- index["agent:main:telegram:dm:fresh"] = {- "session_id": sid,- "platform": "telegram",- "origin": {"platform": "telegram", "chat_id": "fresh"},- }- messages[sid] = [{- "id": 1, "role": "user", "content": "hello after baseline",- "timestamp": "2026-03-29T15:10:00",- }]- before = db_path.stat()- os.utime(db_path, ns=(before.st_atime_ns, before.st_mtime_ns + 1_000_000_000))- bridge._poll_once(DB())-- events = bridge.poll_events(after_cursor=0)["events"]- assert len(events) == 1- assert events[0]["session_key"] == "agent:main:telegram:dm:fresh"- assert events[0]["content"] == "hello after baseline"-- def test_wal_commit_without_checkpoint_is_delivered(self, tmp_path, monkeypatch):- """A WAL-mode commit lands in state.db-wal; state.db's own mtime moves only at a- checkpoint, so a gate keyed on the main file alone kept new messages undelivered."""- import mcp_serve- from hermes_state import SessionDB-- def commit_message(role, content, ts):- # Another process's connection: its commit lands in the WAL like a gateway turn's.- conn = sqlite3.connect(str(tmp_path / "state.db"))- with conn:- conn.execute("INSERT INTO messages (session_id, role, content, timestamp) VALUES (?, ?, ?, ?)",- ("s1", role, content, ts))- conn.close()-- monkeypatch.setattr(mcp_serve, "_get_session_db", lambda: SessionDB(tmp_path / "state.db"))- db = SessionDB(tmp_path / "state.db")- try:- db.create_session("s1", "telegram", session_key="agent:main:telegram:dm:wal",- chat_id="wal", chat_type="dm")- commit_message("user", "before baseline", 100.0)- bridge = mcp_serve.EventBridge()- bridge._establish_baseline()- bridge._poll_once(db)- assert bridge.poll_events(after_cursor=0)["events"] == []-- for i in range(5):- commit_message("assistant", f"reply {i} after baseline", 101.0 + i)- # No checkpoint ran: the main database file is untouched by these commits.- bridge._poll_once(db)- finally:- db.close()-- events = bridge.poll_events(after_cursor=0)["events"]- assert [e["content"] for e in events] == [f"reply {i} after baseline" for i in range(5)]-- def test_commit_in_the_baseline_mtime_tick_is_delivered(self, tmp_path, monkeypatch):- """A commit in the same coarse mtime tick as the baseline leaves every stat field the- same; the gate must still see it."""- import mcp_serve- from hermes_state import SessionDB-- db = SessionDB(tmp_path / "state.db")- try:- db.create_session("s1", "telegram", session_key="agent:main:telegram:dm:tick",- chat_id="tick", chat_type="dm")- db.append_message("s1", role="user", content="before baseline")- monkeypatch.setattr(mcp_serve, "_get_session_db", lambda: db)- bridge = mcp_serve.EventBridge()- bridge._establish_baseline()- pinned = {name: (tmp_path / name).stat().st_mtime_ns for name in ("state.db", "state.db-wal")}-- db.append_message("s1", role="assistant", content="same tick")- for name, mtime_ns in pinned.items():- os.utime(tmp_path / name, ns=(mtime_ns, mtime_ns))- bridge._poll_once(db)- finally:- db.close()-- events = bridge.poll_events(after_cursor=0)["events"]- assert [e["content"] for e in events] == ["same tick"]-- def test_one_commit_costs_one_full_poll(self, tmp_path, monkeypatch):- """Every full poll loads each active session's transcript. An isolated commit must open- the gate exactly once: a gate that distrusts recent mtimes re-polls for seconds after every- write, and a gateway writing that often keeps the bridge in permanent full-poll mode."""- import mcp_serve- from hermes_state import SessionDB-- db = SessionDB(tmp_path / "state.db")- try:- db.create_session("s1", "telegram", session_key="agent:main:telegram:dm:cost",- chat_id="cost", chat_type="dm")- monkeypatch.setattr(mcp_serve, "_get_session_db", lambda: db)- bridge = mcp_serve.EventBridge()- bridge._establish_baseline()- full_polls = []- real_load = mcp_serve._load_sessions_index- monkeypatch.setattr(mcp_serve, "_load_sessions_index", lambda: full_polls.append(1) or real_load())-- db.append_message("s1", role="user", content="one write")- for _ in range(10):- bridge._poll_once(db)- finally:- db.close()-- assert len(full_polls) == 1- assert [e["content"] for e in bridge.poll_events(after_cursor=0)["events"]] == ["one write"]-- @pytest.mark.parametrize(- "home_name",- [- pytest.param("home#1", marks=pytest.mark.platforms("any")),- pytest.param("home%23", marks=pytest.mark.platforms("any")),- # A literal question mark is valid on POSIX, but forbidden in Windows filenames.- pytest.param("home?x", marks=pytest.mark.platforms("posix")),- ],- )- def test_the_version_gate_watches_the_real_db_under_a_uri_special_home(self, tmp_path, monkeypatch, home_name):- """``#``/``?``/``%xx`` in HERMES_HOME must not truncate or re-decode the read-only URI: the- gate would then watch some other (empty) database whose version never follows state.db."""- import hermes_constants- import mcp_serve- from hermes_state import SessionDB-- home = tmp_path / home_name- home.mkdir()- monkeypatch.setattr(hermes_constants, "get_hermes_home", lambda: home)- db = SessionDB(home / "state.db")- try:- gate = mcp_serve._StateDbVersion()- before = gate.read()- db.create_session("s1", "telegram", session_key="agent:main:telegram:dm:uri",- chat_id="uri", chat_type="dm")- after = gate.read()- gate.close()- finally:- db.close()-- assert before is not None and after != beforediff --git a/website/docs/reference/cli-commands.md b/website/docs/reference/cli-commands.mdindex e6cc93fbc0d..c5194bc862d 100644--- a/website/docs/reference/cli-commands.md+++ b/website/docs/reference/cli-commands.md@@ -93,7 +93,7 @@ The install also ships `hermes-agent`, a minimal runner that sends one query and| `hermes journey` (aliases `learning`, `memory-graph`) | Timeline of learned skills + memories over time. || `hermes memory` | Configure external memory provider. Plugin-specific subcommands (e.g. `hermes honcho`) register automatically when their provider is active. || `hermes acp` | Run Hermes as an ACP server for editor integration. |-| `hermes mcp` | Manage MCP server configurations and run Hermes as an MCP server. |+| `hermes mcp` | Manage MCP server configurations. Running Hermes as an MCP server is the [mcp-serve plugin](../user-guide/features/mcp.md#running-hermes-as-an-mcp-server). || `hermes connectors` | List, connect, rename and disconnect hosted connector accounts. || `hermes plugins` | Manage Hermes Agent plugins (install, enable, disable, remove). || `hermes portal` | Nous Portal status, subscription link, and Tool Gateway routing. See [Tool Gateway](../user-guide/features/tool-gateway.md). |@@ -1614,14 +1614,13 @@ See [ACP Editor Integration](../user-guide/features/acp.md) and [ACP Internals](hermes mcp <subcommand>```-Manage MCP (Model Context Protocol) server configurations and run Hermes as an MCP server.+Manage MCP (Model Context Protocol) server configurations. Running Hermes itself as an MCP server moved to the `mcp-serve` plugin (`hermes plugins install mcp-serve`, then `hermes mcp-serve`); `hermes mcp serve` prints that new spelling.| Subcommand | Description ||------------|-------------|| *(none)* or `picker` | Interactive catalog picker — browse Nous-approved MCPs and install/enable/disable. || `catalog` | List Nous-approved MCPs (plain text, scriptable). || `install <name>` | Install a catalog entry (e.g. `hermes mcp install deepwiki`). |-| `serve [-v\|--verbose]` | Run Hermes as an MCP server — expose conversations to other agents. || `add <name> [--url URL] [--command CMD] [--auth oauth\|header] [--args ...]` | Add a custom MCP server with automatic tool discovery. `--args` passes the remaining argv to the stdio command, so put it last. || `remove <name>` (alias: `rm`) | Remove an MCP server from config. || `list` (alias: `ls`) | List configured MCP servers. |diff --git a/website/docs/user-guide/features/hooks.md b/website/docs/user-guide/features/hooks.mdindex b59ade9aea9..71209c03370 100644--- a/website/docs/user-guide/features/hooks.md+++ b/website/docs/user-guide/features/hooks.md@@ -2078,7 +2078,7 @@ Three escape hatches bypass the interactive prompt — any one is sufficient:2. `HERMES_ACCEPT_HOOKS=1` environment variable3. `hooks_auto_accept: true` in `~/.hermes/config.yaml`-Only a foreground `hermes chat` (or `hermes rl`) ever asks. The gateway, cron, `hermes mcp serve`, `hermes acp` and CI never prompt, even when stdin looks like a terminal (a hidden console from a Windows login-item launcher does), so they need one of these three or an allowlist entry. Otherwise a newly-added hook stays un-registered and a warning names the profile's allowlist file it is missing from (`profiles/<name>/shell-hooks-allowlist.json` for a non-default profile). `hermes gateway run --accept-hooks` (like `HERMES_ACCEPT_HOOKS=1` on the gateway) approves the hooks of every profile that gateway serves, including hooks added after it started.+Only a foreground `hermes chat` (or `hermes rl`) ever asks. The gateway, cron, `hermes mcp-serve --tools` (the mcp-serve plugin), `hermes acp` and CI never prompt, even when stdin looks like a terminal (a hidden console from a Windows login-item launcher does), so they need one of these three or an allowlist entry. Otherwise a newly-added hook stays un-registered and a warning names the profile's allowlist file it is missing from (`profiles/<name>/shell-hooks-allowlist.json` for a non-default profile). `hermes gateway run --accept-hooks` (like `HERMES_ACCEPT_HOOKS=1` on the gateway) approves the hooks of every profile that gateway serves, including hooks added after it started.**Script edits are silently trusted.** The allowlist keys on the exact command string, not the script's hash, so editing the script on disk does not invalidate consent. `hermes hooks doctor` flags mtime drift so you can spot edits and decide whether to re-approve.diff --git a/website/docs/user-guide/features/mcp.md b/website/docs/user-guide/features/mcp.mdindex 4c567fb6c92..06f4eb8f655 100644--- a/website/docs/user-guide/features/mcp.md+++ b/website/docs/user-guide/features/mcp.md@@ -1025,102 +1025,24 @@ The 5-minute default timeout mirrors the gateway approval default so users on as## Running Hermes as an MCP server-In addition to connecting **to** MCP servers, Hermes can also **be** an MCP server. This lets other MCP-capable agents (Claude Code, Cursor, Codex, or any MCP client) use Hermes's messaging capabilities — list conversations, read message history, and send messages across all your connected platforms.--### When to use this--- You want Claude Code, Cursor, or another coding agent to send and read Telegram/Discord/Slack messages through Hermes-- You want a single MCP server that bridges to all of Hermes's connected messaging platforms at once-- You already have a running Hermes gateway with connected platforms--### Quick start+Hermes can also **be** an MCP server, so Claude Code, Claude Desktop, Cursor, Codex or any MCP client can list and read your messaging conversations, wait for new messages and send messages across every platform Hermes is connected to, and optionally call Hermes' own web, browser, vision, image generation, skills and TTS tools. This ships as the official **mcp-serve** plugin:```bash-hermes mcp serve+hermes plugins install mcp-serve```-This starts a stdio MCP server. The MCP client (not you) manages the process lifecycle.--### MCP client configuration--Add Hermes to your MCP client config. For example, in Claude Code's `~/.claude/claude_desktop_config.json`:-```json{"mcpServers": {"hermes": {"command": "hermes",- "args": ["mcp", "serve"]- }- }-}-```--Or if you installed Hermes in a specific location:--```json-{- "mcpServers": {- "hermes": {- "command": "/home/user/.hermes/hermes-agent/venv/bin/hermes",- "args": ["mcp", "serve"]+ "args": ["mcp-serve"]}}}```-### Available tools--The MCP server exposes 10 tools, matching OpenClaw's channel bridge surface plus a Hermes-specific channel browser:--| Tool | Description |-|------|-------------|-| `conversations_list` | List active messaging conversations. Filter by platform or search by name. |-| `conversation_get` | Get detailed info about one conversation by session key. |-| `messages_read` | Read recent message history for a conversation. |-| `attachments_fetch` | Extract non-text attachments (images, media) from a specific message. |-| `events_poll` | Poll for new conversation events since a cursor position. |-| `events_wait` | Long-poll / block until the next event arrives (near-real-time). |-| `messages_send` | Send a message through a platform (e.g. `telegram:123456`, `discord:#general`). |-| `channels_list` | List available messaging targets across all platforms. |-| `permissions_list_open` | List pending approval requests observed during this bridge session. |-| `permissions_respond` | Allow or deny a pending approval request. |--### Event system--The MCP server includes a live event bridge that polls Hermes's session database for new messages. This gives MCP clients near-real-time awareness of incoming conversations:--```-# Poll for new events (non-blocking)-events_poll(after_cursor=0)--# Wait for next event (blocks up to timeout)-events_wait(after_cursor=42, timeout_ms=30000)-```--Event types: `message`, `approval_requested`, `approval_resolved`--The event queue is in-memory and starts when the bridge connects. Older messages are available through `messages_read`.--### Options--```bash-hermes mcp serve # Normal mode-hermes mcp serve --verbose # Debug logging on stderr-```--### How it works--The MCP server reads conversation data directly from Hermes's session store — `~/.hermes/state.db` is the primary source, with `sessions.json` kept only as a legacy fallback. A background thread polls the database for new messages and maintains an in-memory event queue. For sending messages, it uses the same internal send engine (`tools/send_message_tool.py`) that powers cron delivery and the `hermes send` CLI.--The gateway does NOT need to be running for read operations (listing conversations, reading history, polling events). It DOES need to be running for send operations, since the platform adapters need active connections.--### Current limits--- The embedded `hermes mcp serve` exposes a **stdio-only** MCP server today. If you need an HTTP MCP server, run a separate adapter — or, much more commonly, use the MCP **client** side of Hermes, which already speaks both stdio and HTTP (`url` + `headers` in `mcp_servers.yaml` / `config.yaml`; see [HTTP servers](#http-servers) above).-- Event polling at ~200ms intervals via mtime-optimized DB polling (skips work when files are unchanged)-- No `claude/channel` push notification protocol yet-- Text-only sends (no media/attachment sending through `messages_send`)+It used to be built in as `hermes mcp serve`. An MCP client configured with `"args": ["mcp", "serve"]` changes them to `["mcp-serve"]`; the tool names and parameters are unchanged, and `hermes mcp serve` now prints the new spelling and the install line. Tools, the `--tools` mode and its safety limits are documented in the [plugin's README](https://github.com/NousResearch/hermes-official-plugins/tree/main/mcp-serve).## Related docsdiff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/mcp.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/mcp.mdindex 6624ac0076f..d7ede3347f4 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/mcp.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/mcp.md@@ -489,102 +489,24 @@ mcp_servers:## 将 Hermes 作为 MCP 服务器运行-除了连接**到** MCP 服务器,Hermes 也可以**作为** MCP 服务器运行。这让其他支持 MCP 的 agent(Claude Code、Cursor、Codex 或任何 MCP 客户端)能够使用 Hermes 的消息能力——列出会话、读取消息历史,以及跨所有已连接平台发送消息。--### 适用场景--- 你希望 Claude Code、Cursor 或其他编程 agent 通过 Hermes 发送和读取 Telegram/Discord/Slack 消息-- 你需要一个单一的 MCP 服务器,同时桥接 Hermes 所有已连接的消息平台-- 你已经有一个运行中的 Hermes gateway,并已连接各平台--### 快速开始+Hermes 也可以**作为** MCP 服务器运行,让 Claude Code、Claude Desktop、Cursor、Codex 或任何 MCP 客户端列出和读取你的消息会话、等待新消息、跨所有已连接平台发送消息,并可选地调用 Hermes 自己的网页、浏览器、视觉、图像生成、技能和 TTS 工具。该功能现由官方 **mcp-serve** 插件提供:```bash-hermes mcp serve+hermes plugins install mcp-serve```-这会启动一个 stdio MCP 服务器。进程生命周期由 MCP 客户端(而非你)管理。--### MCP 客户端配置--将 Hermes 添加到你的 MCP 客户端配置中。例如,在 Claude Code 的 `~/.claude/claude_desktop_config.json` 中:-```json{"mcpServers": {"hermes": {"command": "hermes",- "args": ["mcp", "serve"]- }- }-}-```--或者,如果你将 Hermes 安装在特定位置:--```json-{- "mcpServers": {- "hermes": {- "command": "/home/user/.hermes/hermes-agent/venv/bin/hermes",- "args": ["mcp", "serve"]+ "args": ["mcp-serve"]}}}```-### 可用工具--MCP 服务器暴露 10 个工具,与 OpenClaw 的 channel bridge 接口一致,并额外提供一个 Hermes 专属的 channel 浏览器:--| 工具 | 描述 |-|------|-------------|-| `conversations_list` | 列出活跃的消息会话。可按平台过滤或按名称搜索。 |-| `conversation_get` | 通过 session key 获取某个会话的详细信息。 |-| `messages_read` | 读取某个会话的近期消息历史。 |-| `attachments_fetch` | 从特定消息中提取非文本附件(图片、媒体)。 |-| `events_poll` | 从指定游标位置轮询新的会话事件。 |-| `events_wait` | 长轮询/阻塞,直到下一个事件到达(接近实时)。 |-| `messages_send` | 通过平台发送消息(例如 `telegram:123456`、`discord:#general`)。 |-| `channels_list` | 列出所有平台上可用的消息目标。 |-| `permissions_list_open` | 列出本次 bridge 会话中观察到的待审批请求。 |-| `permissions_respond` | 允许或拒绝待审批请求。 |--### 事件系统--MCP 服务器包含一个实时事件桥,轮询 Hermes 的会话数据库以获取新消息。这让 MCP 客户端能够近实时感知新来的会话:--```-# 轮询新事件(非阻塞)-events_poll(after_cursor=0)--# 等待下一个事件(阻塞,直到超时)-events_wait(after_cursor=42, timeout_ms=30000)-```--事件类型:`message`、`approval_requested`、`approval_resolved`--事件队列存储在内存中,在 bridge 连接时开始工作。较旧的消息可通过 `messages_read` 获取。--### 选项--```bash-hermes mcp serve # 普通模式-hermes mcp serve --verbose # 在 stderr 输出调试日志-```--### 工作原理--MCP 服务器直接从 Hermes 的会话存储(`~/.hermes/sessions/sessions.json` 和 SQLite 数据库)读取会话数据。后台线程轮询数据库以获取新消息,并维护一个内存事件队列。发送消息时,使用与 Hermes agent 本身相同的 `send_message` 基础设施。--读取操作(列出会话、读取历史、轮询事件)**不需要** gateway 运行。发送操作**需要** gateway 运行,因为平台适配器需要活跃连接。--### 当前限制--- 内嵌的 `hermes mcp serve` 目前只暴露 **stdio-only** MCP 服务器。如果你需要 HTTP MCP 服务器,请运行单独的适配器——或者,更常见的做法是使用 Hermes 的 MCP **客户端**侧,它已经同时支持 stdio 和 HTTP(`mcp_servers.yaml` / `config.yaml` 中的 `url` + `headers`;参见上方的 [HTTP 服务器](#http-servers))。-- 事件轮询间隔约 200ms,通过基于 mtime 优化的数据库轮询实现(文件未变化时跳过处理)-- 暂不支持 `claude/channel` 推送通知协议-- 仅支持纯文本发送(`messages_send` 不支持媒体/附件发送)+它以前内置为 `hermes mcp serve`。配置了 `"args": ["mcp", "serve"]` 的 MCP 客户端需改为 `["mcp-serve"]`;工具名称和参数保持不变,`hermes mcp serve` 现在会提示新的写法和安装命令。工具列表、`--tools` 模式及其安全限制见[插件 README](https://github.com/NousResearch/hermes-official-plugins/tree/main/mcp-serve)。## 相关文档