Okay, let's break down how you can interact with LSP servers from the CLI for debugging.
The most common way people debug LSP interactions isn't usually by directly querying the server from a generic CLI tool, but rather by inspecting the communication between their existing LSP client (in their editor/IDE) and the server.
However, if you do want direct CLI interaction or a dedicated tool, here are the main approaches:
1. Inspecting Traffic (Most Common Debugging Method)
How it works: You configure your editor's LSP client or the LSP server itself to log the raw JSON-RPC messages being sent back and forth.
Why it's common: It shows you exactly what your editor is sending and what the server is replying in the context of your actual workflow. This is often the most valuable information.
How to do it:
Editor LSP Client Logging:
Neovim (nvim-lspconfig): Set vim.lsp.set_log_level("debug") and check the log file location with :LspLog. You might also configure specific servers in lspconfig setup to log to a file. Some plugins like lsp_lines can show diagnostics inline.
VS Code: Check the "Output" panel and select the specific language server from the dropdown (e.g., "TypeScript Language Server"). Some extensions might have specific logging settings (e.g., "python.analysis.logLevel": "Trace" for Pylance).
Emacs (eglot/lsp-mode): Both have commands/variables to increase verbosity or show logs (*lsp-log* buffers, eglot-events-buffer, etc.). Check their specific documentation.
Sublime Text (LSP package): Check the Sublime Text console (View > Show Console) and package settings for logging options.
Server-Side Logging:
Many language servers accept command-line arguments to increase verbosity or specify a log file. Check the server's documentation.
These tools are specifically designed to talk LSP from the command line.
lsp-cli (Node.js based):
Purpose: Probably the closest match to what you're asking for. It connects to an LSP server (via stdio or TCP) and allows you to send LSP requests interactively or via commands.
# Start the server (example: pylsp)
# Then connect lsp-cli to its stdio
pylsp | lsp-cli
# Or connect via TCP if the server supports it
# some-lsp-server --tcp --port 12345 &
# lsp-cli --port 12345
# Once connected, you might interact like:
# > initialize --rootUri file:///path/to/project --processId $$
# < (initialize response)
# > textDocument/didOpen --uri file:///path/to/project/file.py --text "print('hello')"
# > textDocument/definition --uri file:///path/to/project/file.py --line 0 --character 3
# < (definition response)
Pros: Designed for this exact task.
Cons: Requires Node.js. Might need some setup to get the connection right.
Headless Editors (Neovim / Emacs):
How it works: You can run editors like Neovim or Emacs in a headless/batch mode and use their scripting capabilities (Lua for Neovim, Elisp for Emacs) to interact with their built-in LSP clients.
Pros: Very powerful, uses the same battle-tested client code as your editor.
Cons: Requires familiarity with the editor's scripting language. Can be complex to set up correctly, especially handling asynchronous responses.
3. Manual Interaction (Difficult)
How it works: Manually construct the JSON-RPC messages (including the Content-Length header and \r\n\r\n separator) and pipe them to the server's stdin, reading from its stdout.
# Python script to send one message and read one response (simplified!)
import sys
import json
import os
def send_message(msg):
msg_json = json.dumps(msg)
content_length = len(msg_json.encode('utf-8'))
header = f"Content-Length: {content_length}\r\n\r\n"
sys.stdout.write(header)
sys.stdout.write(msg_json)
sys.stdout.flush()
def read_message():
# WARNING: Naive reading - real implementation needs proper header parsing
# and handling of chunked reads, partial messages, etc.
header_lines = []
content_length = -1
while True:
line = sys.stdin.readline()
if not line: return None # EOF
if line == '\r\n': break # End of headers
header_lines.append(line.strip())
if line.lower().startswith('content-length:'):
content_length = int(line.split(':')[1].strip())
if content_length == -1:
raise ValueError("Missing Content-Length header")
content_raw = sys.stdin.read(content_length)
return json.loads(content_raw.decode('utf-8'))
# --- Actual Interaction ---
pid = os.getpid()
initialize_req = {
"jsonrpc": "2.0", "id": 1, "method": "initialize",
"params": {
"processId": pid, "rootUri": "file:///path/to/your/project",
"capabilities": {}, # Fill with basic capabilities
# ... other init params
}
}
send_message(initialize_req)
init_response = read_message()
print("Received Init Response:", init_response, file=sys.stderr)
# Send initialized notification (no response expected)
initialized_noti = {"jsonrpc": "2.0", "method": "initialized", "params": {}}
send_message(initialized_noti)
# Now maybe send a didOpen, then a definition request...
# ... read responses ...
You would run this like: or .
Recommendation:
Start with Logging: Configure your editor/server to log traffic. This is the easiest and often most informative way to debug.
Use lsp-cli: If you need to actively send specific requests from the CLI to reproduce an issue or test server capabilities, lsp-cli is likely the best dedicated tool.
Consider Headless Editors: If you're comfortable with Neovim/Emacs scripting, this offers a powerful way to leverage their existing LSP infrastructure.
Avoid Manual Interaction: Unless you have a very specific reason or are developing LSP tooling yourself, the manual approach is too complex for typical debugging.
Pros: No external dependencies beyond standard tools/languages.
Cons: Extremely tedious and error-prone. Managing state (like initialize before other requests), handling asynchronous notifications, and correctly parsing the byte stream with headers is complex. Generally not recommended unless you're building an LSP client.