Introducing a new way to review your PRs.

Read the announcement

oraios / serena

A powerful MCP toolkit for coding, providing semantic retrieval and editing capabilities - the IDE for your agent

View on GitHub

13 documents · Updated Nov 16, 2026

docs / solidlsp-core

SolidLSP core process and protocol framework

Overview

This area is the reusable SolidLSP client runtime: it resolves a configured language server, prepares launch dependencies, starts or connects to the server, frames JSON-RPC/LSP traffic, exposes typed request/notification helpers, and normalizes server responses into SolidLSP/Serena-facing types.

The high-level entry point is SolidLanguageServer.create() in src/…/ls.py. It receives a LanguageServerConfig from src/…/ls_config.py, resolves config.ls_id.get_ls_class(), instantiates the language-specific subclass, and applies the request timeout. LanguageServerConfig owns runtime configuration such as indexed workspace_folders, non-indexed additional_workspace_folders, ignored path patterns, file encoding, LSP trace logging, whether to start the subprocess in an independent process group, and whether the project is trusted. LanguageServerId and LanguageServerRegistry in src/…/ls_config.py map language-server keys to implementation classes and source filename matchers; external adapters can register ExternalLanguageServerId instances via the solidlsp.language_server_registration entry point group.

Language-server instances in src/…/ls.py keep three categories of state. Process/protocol state is self.server, a LanguageServerInterface from src/…/ls_process.py; server_started; and any cached ProcessLaunchInfo. File state is open_file_buffers, whose LSPFileBuffer objects send textDocument/didOpen, didChange, and didClose notifications and keep file contents, modification timestamps, LSP document versions, and content hashes. Symbol state is stored under SolidLSPSettings.project_data_path/cache/<ls-key>/ as pickled raw document-symbol and high-level document-symbol caches, loaded and saved via src/…/cache.py with the restricted SafePickleLoader in src/…/pickle_util.py.

Startup is split between subclass policy and core mechanics. SolidLanguageServer.start() in src/…/ls.py marks the server as started, calls the subclass _start_server(), and stops the underlying interface if startup fails after a process was spawned. Subclasses are responsible for eventually calling self.server.start() and usually sending initialize/initialized. Core initialization payload assembly is in DefaultInitializeParamsBuilder (src/…/initialize_params.py): it sets processId, clientInfo, rootPath/rootUri, workspaceFolders, and merges custom initializationOptions from SolidLSPSettings.ls_specific_settings. SolidLanguageServer._create_initialize_params() registers capabilities.general.staleRequestSupport.retryOnContentModified back into the interface so only advertised stale-request methods are retried.

For stdio servers, SolidLanguageServer._create_language_server_interface() creates a StdioLanguageServer (src/…/ls_process.py) from a ProcessLaunchInfo. If the subclass did not pass a fixed launch command, src/…/dependency_provider.py supplies dependency providers that create commands and optional environments. LanguageServerDependencyProviderBaseCommand supports central custom overrides (ls_base_cmd, ls_path, ls_args, ls_extra_args); LanguageServerDependencyProviderSinglePath adapts providers centered around one executable/JAR path; and LanguageServerDependencyProviderUvx runs pinned PyPI-distributed servers via uvx or uv tool run, with install_dependencies() materializing the package through uv tool install. Downloaded artifacts use DownloadedDependency, DownloadedDependencyHashDatabase, and FileUtils.download_and_extract_archive_verified() for optional allowed-host checks and SHA256 verification.

Process management is implemented in src/…/ls_process.py and src/…/subprocess_util.py. StdioLanguageServer._start() launches the command through ManagedSubprocessLauncher, then starts daemon threads for stdout and stderr. On POSIX/Linux, ManagedSubprocessLauncher.launch() can start a new session and register PR_SET_PDEATHSIG through a dedicated spawner thread so independent language-server processes receive SIGTERM if the parent dies. Shutdown sends LSP shutdown, then exit, closes stdin, and terminates the process tree with a kill fallback. TCPLanguageServer in src/…/ls_process.py is the same LanguageServerInterface over an externally managed TCP socket; it retries connection until its deadline, sends framed messages with sendall(), and closes the socket without LSP shutdown on stop.

The protocol layer is JSON-RPC 2.0 over LSP Content-Length framing. src/…/server.py builds requests, notifications, responses, and error responses; create_message() serializes compact UTF-8 JSON and sends only the Content-Length header. make_request() and make_notification() omit params for shutdown and exit, while using {} for other None params for compatibility with servers that expect an object. LanguageServerInterface in src/…/ls_process.py allocates request IDs under a lock, records pending Request objects, writes messages through transport-specific _send_payload(), and routes incoming bodies by payload shape: request, notification, or response. Responses complete pending requests or attach LSPError; server-originated client requests dispatch to handlers registered with on_request(), and notifications dispatch to observers and method handlers.

The public request surface has two layers. LanguageServerRequest in src/…/ls_request.py is a synchronous method-name wrapper around LanguageServerInterface.send_request() for LSP methods such as initialize, definition, references, document_symbol, completion, hover, diagnostics, rename, and workspace symbols. LspNotification in src/…/lsp_requests.py wraps outbound notifications such as didOpen, didChange, didClose, initialized, file-watcher events, and progress cancellation. The generated src/…/lsp_types.py defines protocol TypedDicts/enums for LSP 3.17, while src/…/ls_types.py defines the smaller SolidLSP-facing types (Location, CompletionItem, Diagnostic, UnifiedSymbolInformation, etc.) used by higher-level APIs.

src/…/ls.py turns raw LSP results into normalized operations. request_definition(), request_implementation(), and request_references() open the target file, optionally wait for cross-file indexing, send the LSP request, normalize Location and LocationLink variants, convert URIs to repository-relative paths via PathUtils.uri_to_path()/get_relative_path(), and skip paths outside the repository, missing generated files, and ignored paths. request_text_document_diagnostics() supports LSP 3.17 pull diagnostics when _supports_pull_diagnostics() allows it, but falls back to stored textDocument/publishDiagnostics notifications observed by _observe_server_notification(). request_document_symbols() caches raw documentSymbol responses and high-level DocumentSymbols, normalizes DocumentSymbol/SymbolInformation into UnifiedSymbolInformation, adds locations, parent/child links, overload indices, and SymbolBody slices extracted from file buffers. request_full_symbol_tree() walks configured indexed workspace folders, respecting ignore rules and trust-aware symlink handling, and creates package/file symbols around document symbols.

Utility support is shared but still part of this runtime. src/…/ls_utils.py provides line/column conversion and text edit helpers that respect LSP newline rules; path/URI conversion; robust file reading with charset fallback and LF normalization; safe downloads, archive extraction, checksum verification, and platform/dotnet detection. src/…/subprocess_util.py provides subprocess defaults and tree termination for both dependency-install commands and launched language servers. src/…/zip.py contains a permissive SafeZipExtractor that extracts selected ZIP members, preserves POSIX permissions, and logs per-member failures. src/…/metals_db_utils.py is Scala-specific support in the core utilities: it parses Metals H2 lock files, detects active/stale Metals processes, and can remove verified stale locks.

Error paths are intentionally surfaced through a small set of exception types. SolidLSPException in src/…/ls_exceptions.py wraps request errors and exposes whether the cause is a LanguageServerTerminatedException; this is used by diagnostics fallback in src/…/ls.py to re-raise server termination while falling back for non-fatal pull-diagnostics failures. LanguageServerInterface.send_request() in src/…/ls_process.py wraps LSP error responses, timeouts, and transport termination in SolidLSPException. Stdout/TCP read-loop failures cancel all pending requests with LanguageServerTerminatedException, and failed writes do the same instead of leaving callers blocked until timeout. Invalid symbol/text ranges raise InvalidTextLocationError, while Metals stale locks can raise MetalsStaleLockError from src/…/ls_exceptions.py when language-specific code elects to fail instead of clean up.

Coupling

  • If a subclass changes the initialize capabilities it returns from _create_base_initialize_params() in src/…/ls.py, verify _register_content_modified_retry_methods() still sees the same capabilities.general.staleRequestSupport.retryOnContentModified methods. LanguageServerInterface.send_request() in src/…/ls_process.py only retries ContentModified for methods registered from that payload.
  • If LanguageServerConfig.workspace_folders or additional_workspace_folders in src/…/ls_config.py change semantics, verify DefaultInitializeParamsBuilder in src/…/initialize_params.py, _resolve_file_uri(), PathWorkspaceStatus, _activate_additional_workspaces(), and request_full_symbol_tree() in src/…/ls.py. The initialize request can include extra workspaces that SolidLSP deliberately does not index.
  • If LanguageServerId.get_source_fn_matcher() or FilenameMatcher.add_extensions() in src/…/ls_config.py changes, verify SolidLanguageServer.__init__() still resets cached per-language matchers and is_ignored_path() in src/…/ls.py still filters unsupported files consistently with symbol-tree traversal.
  • If JSON-RPC framing in src/…/server.py changes, check both transports in src/…/ls_process.py. StdioLanguageServer._read_ls_process_stdout() and TCPLanguageServer._read_loop() both parse Content-Length, consume headers until the blank line, and then read exactly the advertised byte count.
  • If generated request or notification wrappers in src/…/ls_request.py or src/…/lsp_requests.py are regenerated, verify the method strings used by src/…/ls.py still match the LSP methods expected by language-server subclasses; these wrappers do not validate server capabilities before sending.
  • If UnifiedSymbolInformation, SymbolBody, or cache version constants change in src/…/ls.py or src/…/ls_types.py, update the appropriate cache version/fingerprint. Raw server response changes belong in _raw_document_symbols_cache_fingerprint(); high-level normalization changes belong in _document_symbols_cache_fingerprint().
  • If dependency download verification changes in src/…/dependency_provider.py or src/…/ls_utils.py, verify CI behavior. DownloadedDependency.download_to() raises in CI when verification is enabled but no SHA256 is known, while non-CI runs only warn and continue unverified.
  • If subprocess launch or shutdown behavior changes in src/…/subprocess_util.py, verify StdioLanguageServer._stop() in src/…/ls_process.py. The process-group/PDEATHSIG assumptions are only safe when start_independent_lsp_process created a distinct session for the language server.

Risks

  • ManagedSubprocessLauncher.launch() in src/…/subprocess_util.py converts even list commands into a shell command and runs subprocess.Popen(..., shell=True). If a dependency provider or custom ls_base_cmd/ls_args in src/…/dependency_provider.py passes untrusted repository-controlled strings, those strings can become shell input; keep launch-command construction restricted to trusted settings or carefully quoted argument lists.
  • SafeZipExtractor in src/…/zip.py writes self.extract_dir / member.filename without the path traversal validation used by FileUtils._extract_zip_archive() in src/…/ls_utils.py. If it is used on archives from an untrusted source, a ../ member can write outside the extraction directory.
  • FileUtils.download_and_extract_archive_verified() in src/…/ls_utils.py validates tar member paths before tar_ref.extractall(), but it does not reject tar symlink or hardlink members. If a dependency archive is malicious, extraction may still create links that point outside the target tree even though plain member names passed validation.
  • DownloadedDependencyHashDatabase in src/…/dependency_provider.py stores hashes in SOLIDLSP_RESOURCES_DIR, which is src/solidlsp/resources from src/…/settings.py, not the user data directory. In installed or read-only deployments, updating hashes can fail and only log a warning, so CI hash enforcement can later fail for URLs whose hashes were not persisted.
  • LanguageServerInterface._request_handler() in src/…/ls_process.py returns MethodNotFound for unregistered server-to-client requests. If a server requires client support for a request such as configuration or work-done token creation and no handler was registered, initialization or later requests can fail even though outbound client requests are otherwise valid.