The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(lsp): declare custom language servers in config (lsp.servers.<id> with extensions)
teknium18420737a8254
diff --git a/agent/lsp/cli.py b/agent/lsp/cli.pyindex bc03021ed5c..6fcb2bd91ed 100644--- a/agent/lsp/cli.py+++ b/agent/lsp/cli.py@@ -56,20 +56,37 @@ def run_lsp_command(args: argparse.Namespace) -> int:return 130+def _all_servers() -> list:+ """Config-declared servers (``lsp.servers.<id>.extensions``) ahead of the built-in registry."""+ from agent.lsp.servers import SERVERS, custom_servers+ from hermes_cli.config import load_config_readonly+ try:+ lsp_cfg = load_config_readonly().get("lsp") or {}+ except Exception: # noqa: BLE001 — a broken config still lists the built-ins+ lsp_cfg = {}+ return [*custom_servers(lsp_cfg.get("servers") if isinstance(lsp_cfg, dict) else None), *SERVERS]++def _status_for(server_id: str) -> str:+ import osfrom agent.lsp.install import detect_status+ from agent.lsp.servers import SERVERS, ServerContext+ custom = next((s for s in _all_servers() if s.server_id == server_id and s not in SERVERS), None)+ if custom is not None: # no install recipe: installed iff the configured command resolves+ cwd = os.getcwd()+ return "installed" if custom.build_spawn(cwd, ServerContext(cwd, install_strategy="manual")) else "manual-only"return detect_status(_recipe_pkg_for(server_id))def _cmd_status(emit_json: bool) -> int:from agent.lsp import get_service- from agent.lsp.servers import SERVERS+ servers = _all_servers()svc = get_service()info = svc.get_status() if svc is not None else {"enabled": False}if emit_json:import jsonregistry = [{"server_id": s.server_id, "extensions": list(s.extensions), "description": s.description,- "binary_status": _status_for(s.server_id)} for s in SERVERS]+ "binary_status": _status_for(s.server_id)} for s in servers]sys.stdout.write(json.dumps({"service": info, "registry": registry}, indent=2) + "\n")return 0@@ -91,7 +108,7 @@ def _cmd_status(emit_json: bool) -> int:if backend_warnings := _backend_warnings():out += ["", "Backend warnings", "================"] + [f" ! {line}" for line in backend_warnings]out += ["", "Registered Servers", "=================="]- for s in SERVERS:+ for s in servers:status = _status_for(s.server_id)ext_summary = ", ".join(list(s.extensions)[:5])if len(s.extensions) > 5:@@ -104,8 +121,7 @@ def _cmd_status(emit_json: bool) -> int:def _cmd_list(installed_only: bool) -> int:- from agent.lsp.servers import SERVERS- for s in SERVERS:+ for s in _all_servers():status = _status_for(s.server_id)if not (installed_only and status != "installed"):sys.stdout.write(f"{s.server_id:24s} [{status:11s}] {','.join(s.extensions)}\n")diff --git a/agent/lsp/manager.py b/agent/lsp/manager.pyindex 36056e14f3d..fa0f46f65c8 100644--- a/agent/lsp/manager.py+++ b/agent/lsp/manager.py@@ -20,7 +20,7 @@ from typing import Any, Callable, Dict, List, Optional, Tuplefrom agent.lsp import eventlogfrom agent.lsp.client import DIAGNOSTICS_DOCUMENT_WAIT, LSPClient, _diagnostic_key as _diag_key-from agent.lsp.servers import ServerContext, ServerDef, find_server_for_file, language_id_for+from agent.lsp.servers import ServerContext, ServerDef, custom_servers, find_server_for_file, language_id_forfrom agent.lsp.workspace import clear_cache, resolve_workspace_for_filelogger = logging.getLogger("agent.lsp.manager")@@ -103,6 +103,7 @@ class LSPService:init_overrides: Optional[Dict[str, Dict[str, Any]]] = None,disabled_servers: Optional[List[str]] = None,idle_timeout: float = DEFAULT_IDLE_TIMEOUT,+ extra_servers: Optional[List[ServerDef]] = None,) -> None:self._enabled = enabledself._wait_mode = wait_mode if wait_mode in {"document", "full"} else "document"@@ -113,6 +114,7 @@ class LSPService:self._init_overrides = init_overrides or {}self._disabled_servers = set(disabled_servers or [])self._idle_timeout = idle_timeout+ self._extra_servers: List[ServerDef] = list(extra_servers or [])self._loop = _BackgroundLoop()if self._enabled:@@ -165,8 +167,14 @@ class LSPService:if isinstance(c.get("initialization_options"), dict)},disabled_servers=[n for n, c in servers.items() if c.get("disabled")],idle_timeout=idle_timeout,+ extra_servers=custom_servers(servers),)+ def _server_for(self, file_path: str) -> Optional[ServerDef]:+ """Config-declared servers first (they may claim an extension ahead of a built-in), then the registry."""+ extra = find_server_for_file(file_path, self._extra_servers) if self._extra_servers else None+ return extra or find_server_for_file(file_path)+# ---- public API ----def is_active(self) -> bool:@@ -190,7 +198,7 @@ class LSPService:def enabled_for(self, file_path: str) -> bool:"""True iff LSP should run for this file: registered non-disabled server, git workspace,and pair not broken (a failed server costs nothing until ``hermes lsp restart`` / exit)."""- srv = find_server_for_file(file_path) if self._enabled else None+ srv = self._server_for(file_path) if self._enabled else Noneif srv is None or srv.server_id in self._disabled_servers:return Falsekey = self._broken_key(srv, file_path)@@ -225,7 +233,7 @@ class LSPService:"""if not self.enabled_for(file_path):return []- server_id = find_server_for_file(file_path).server_id # enabled_for guarantees a match+ server_id = self._server_for(file_path).server_id # enabled_for guarantees a matchtry:t = timeout if timeout is not None else self._wait_timeout + 2.0diags = self._loop.run(self._open_and_wait_async(file_path), timeout=t)@@ -277,7 +285,7 @@ class LSPService:The outer ``_loop.run`` timeout cancels the in-flight spawn before ``_get_or_spawn`` could recordthe failure; without this every later write would re-pay the full timeout. Also kills anyhalf-initialized client and logs the failure once."""- srv = find_server_for_file(file_path)+ srv = self._server_for(file_path)key = self._broken_key(srv, file_path) if srv is not None else Noneif key is None:return@@ -339,7 +347,8 @@ class LSPService:if client is None:return Nonetry:- version = await client.open_file(file_path, language_id=language_id_for(file_path))+ srv = self._server_for(file_path)+ version = await client.open_file(file_path, language_id=language_id_for(file_path, srv))if not snapshot:await client.save_file(file_path)fresh = await client.wait_for_diagnostics(@@ -356,7 +365,7 @@ class LSPService:async def _current_diags_async(self, file_path: str) -> _Diags:ws, gated = resolve_workspace_for_file(file_path)- srv = find_server_for_file(file_path)+ srv = self._server_for(file_path)if not (ws and gated and srv):return []# Same key _get_or_spawn() stored under: single-root servers live under their@@ -369,7 +378,7 @@ class LSPService:return list(client.diagnostics_for(file_path, fresh_only=True)) if client else []async def _get_or_spawn(self, file_path: str) -> Optional[LSPClient]:- srv = find_server_for_file(file_path)+ srv = self._server_for(file_path)if srv is None:return Noneif srv.server_id in self._disabled_servers:diff --git a/agent/lsp/servers.py b/agent/lsp/servers.pyindex 9fd9a29da44..ea62bf95f85 100644--- a/agent/lsp/servers.py+++ b/agent/lsp/servers.py@@ -75,6 +75,8 @@ class ServerDef:# Server handles ``workspace/didChangeWorkspaceFolders``: one process serves every project root# (git worktrees included) as extra workspaceFolders instead of one process per root.multi_root: bool = False+ # didOpen languageId; "" = derive from LANGUAGE_BY_EXT (custom servers name theirs in config).+ language_id: str = ""def matches(self, file_path: str) -> bool:return _file_ext_or_basename(file_path) in self.extensions@@ -398,14 +400,54 @@ SERVERS: List[ServerDef] = []-def find_server_for_file(file_path: str) -> Optional[ServerDef]:- """Return the registry entry that handles ``file_path``, or None."""- return next((srv for srv in SERVERS if srv.matches(file_path)), None)+def find_server_for_file(file_path: str, servers: Optional[Sequence[ServerDef]] = None) -> Optional[ServerDef]:+ """Return the first entry of ``servers`` (default: the built-in registry) that handles ``file_path``."""+ return next((srv for srv in (SERVERS if servers is None else servers) if srv.matches(file_path)), None)-def language_id_for(path: str) -> str:- """Return the LSP languageId to send in didOpen for ``path``."""+def language_id_for(path: str, srv: Optional[ServerDef] = None) -> str:+ """Return the LSP languageId to send in didOpen for ``path`` (a custom server's own id wins)."""+ if srv is not None and srv.language_id:+ return srv.language_idreturn LANGUAGE_BY_EXT.get(_file_ext_or_basename(path), "plaintext")-__all__ = ["ServerDef", "ServerContext", "SpawnSpec", "SERVERS", "find_server_for_file", "language_id_for", "LANGUAGE_BY_EXT"]+def _custom_spawn(server_id: str, command: Sequence[str]) -> _SpawnFn:+ """Spawn builder for a config-declared server: ``command[0]`` is a path or a PATH lookup, no auto-install."""+ def build(root: str, ctx: ServerContext) -> Optional[SpawnSpec]:+ bin_path = _which(os.path.expanduser(command[0]))+ if bin_path is None:+ _warn_once(f"custom:{server_id}", f"lsp.servers.{server_id}: command {command[0]!r} not found on PATH — server skipped")+ return None+ return _make_spec(root, ctx, server_id, [bin_path, *command[1:]])+ return build+++def custom_servers(servers_cfg: Any) -> List[ServerDef]:+ """``lsp.servers`` entries that declare ``extensions`` and name no built-in server are user-declared+ servers (issue #100257). They go AHEAD of the built-ins so a custom entry can claim an extension;+ malformed entries are logged and skipped so one typo never disables the rest of the subsystem."""+ if not isinstance(servers_cfg, dict):+ return []+ builtin = {s.server_id for s in SERVERS}+ out: List[ServerDef] = []+ for server_id, cfg in servers_cfg.items():+ if server_id in builtin or not isinstance(cfg, dict) or "extensions" not in cfg:+ continue+ command, exts, markers = cfg.get("command"), cfg.get("extensions"), cfg.get("root_markers")+ if not (isinstance(command, list) and command and all(isinstance(c, str) and c for c in command)+ and isinstance(exts, list) and exts and all(isinstance(e, str) and e for e in exts)):+ logger.warning("lsp.servers.%s: custom server needs command: [bin, ...args] and extensions: [.ext, ...] — ignored", server_id)+ continue+ out.append(ServerDef(+ str(server_id), tuple(e.lower() if e.startswith(".") else e for e in exts),+ _markers_root([str(m) for m in markers] if isinstance(markers, list) and markers else None),+ _custom_spawn(str(server_id), command),+ description=str(cfg.get("description") or f"{server_id} — custom (lsp.servers)"),+ language_id=str(cfg.get("language_id") or ""),+ ))+ return out+++__all__ = ["ServerDef", "ServerContext", "SpawnSpec", "SERVERS", "custom_servers", "find_server_for_file",+ "language_id_for", "LANGUAGE_BY_EXT"]diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex 5f0970c3936..0e191cb6841 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -2257,6 +2257,9 @@ DEFAULT_CONFIG = {# Per-server overrides keyed by registry server_id (pyright, gopls...): disabled: true;# command: ["path/to/server", "--stdio"] (bypasses auto- install); env: {...};# initialization_options: {...} (merged into LSP initializationOptions).+ # A key that is NOT a built-in id declares a custom server (matched before the built-ins):+ # command: ["my-ls", "--stdio"]; extensions: [".ext"]; optional root_markers: [...],+ # language_id: "..." (didOpen languageId), description: "...". Manual install only."servers": {},},# X (Twitter) Search via xAI's x_search Responses tool. Registers when xAI creds existdiff --git a/tests/agent/lsp/test_custom_servers.py b/tests/agent/lsp/test_custom_servers.pynew file mode 100644index 00000000000..ffdf453a823--- /dev/null+++ b/tests/agent/lsp/test_custom_servers.py@@ -0,0 +1,51 @@+"""Config-declared LSP servers (``lsp.servers.<id>`` with ``extensions``) route files and spawn like built-ins."""+from __future__ import annotations++import os+import subprocess+import sys++import pytest++from agent.lsp.manager import LSPService+from agent.lsp.servers import SERVERS, ServerContext, custom_servers, find_server_for_file, language_id_for++_MOCK = os.path.join(os.path.dirname(__file__), "_mock_lsp_server.py")+++def test_custom_server_precedes_builtins_and_carries_language_id():+ cfg = {+ "pyright": {"disabled": True}, # override of a built-in id is NOT a custom server+ "blade": {"command": [sys.executable, _MOCK], "extensions": [".PHP"], "language_id": "blade"},+ "broken": {"command": "not-a-list", "extensions": [".zzz"]}, # malformed → skipped, not fatal+ }+ custom = custom_servers(cfg)+ assert [s.server_id for s in custom] == ["blade"]+ registry = [*custom, *SERVERS]+ assert find_server_for_file("/w/index.php", registry).server_id == "blade" # custom wins over intelephense+ assert find_server_for_file("/w/index.php").server_id == "intelephense" # built-in registry untouched+ assert language_id_for("/w/index.php", custom[0]) == "blade"+ assert language_id_for("/w/index.php") == "php"+ spec = custom[0].build_spawn("/w", ServerContext("/w", install_strategy="manual"))+ assert spec is not None and spec.command == [sys.executable, _MOCK]+++def test_service_gets_diagnostics_from_config_declared_server(tmp_path):+ subprocess.run(["git", "init", "-q", str(tmp_path)], check=True)+ target = tmp_path / "doc.pnch"+ target.write_text("hello\n")+ (tmp_path / "x.rs").write_text("fn main() {}\n")+ svc = LSPService(+ enabled=True, wait_mode="document", wait_timeout=5.0, install_strategy="manual",+ env_overrides={"panache": {"MOCK_LSP_SCRIPT": "errors"}}, idle_timeout=0,+ extra_servers=custom_servers({"panache": {"command": [sys.executable, _MOCK], "extensions": [".pnch"]}}),+ )+ try:+ assert svc.enabled_for(str(target))+ diags = svc.get_diagnostics_sync(str(target))+ assert diags and diags[0]["source"] == "mock-lsp"+ # Control: a built-in extension still routes to the registry entry, not the custom server.+ assert svc._server_for(str(tmp_path / "x.rs")).server_id == "rust-analyzer"+ finally:+ svc.shutdown()diff --git a/website/docs/user-guide/features/lsp.md b/website/docs/user-guide/features/lsp.mdindex 1fdca90ba25..dca50d5b170 100644--- a/website/docs/user-guide/features/lsp.md+++ b/website/docs/user-guide/features/lsp.md@@ -208,6 +208,32 @@ lsp:`initializationOptions` payload sent in the `initialize`handshake. Server-specific; consult the language server's docs.+### Custom servers++Any `lsp.servers` key that is **not** a built-in server id declares+your own language server. It needs `command` and `extensions`; the+other keys are optional. Custom servers are matched *before* the+built-ins, so they can also take over an extension Hermes already+handles.++```yaml+lsp:+ servers:+ panache:+ command: ["panache-lsp", "--stdio"] # PATH lookup or an absolute/~ path+ extensions: [".pnch"] # or basenames like "Justfile"+ root_markers: ["panache.toml"] # nearest dir with one of these; default: workspace root+ language_id: "panache" # didOpen languageId; default: derived from the extension+ description: "Panache markdown"+ env: { PANACHE_LOG: "warn" } # same optional keys as built-ins+ initialization_options: {}+```++Custom servers are never auto-installed: put the binary on PATH (or+give an absolute path) and `hermes lsp status` lists it as+`installed`. A malformed entry is logged and skipped without+affecting the other servers.+## Installation locationsWhen `install_strategy: auto`, Hermes installs binaries into