Skip to content
Open
61 changes: 61 additions & 0 deletions .github/workflows/test-workflow.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -89,5 +89,66 @@ jobs:
pip install -r requirements.txt
pip install -e .

- name: Install pinned Pyright for real integration tests
run: |
npm install --prefix "$RUNNER_TEMP/multilspy-pyright" --no-save --no-package-lock --ignore-scripts --no-audit --no-fund pyright@1.1.413
PYRIGHT_BIN="$RUNNER_TEMP/multilspy-pyright/node_modules/.bin/pyright-langserver"
test -x "$PYRIGHT_BIN"
echo "MULTILSPY_PYRIGHT_TEST_BINARY=$PYRIGHT_BIN" >> "$GITHUB_ENV"

- name: Run tests
run: pytest tests/multilspy -v --tb=short

pyright-windows:
name: Pyright native Windows (Python ${{ matrix.python-version }})
runs-on: windows-latest
timeout-minutes: 25
strategy:
fail-fast: false
matrix:
python-version: ["3.10", "3.12", "3.13", "3.14"]
env:
PYTHONUTF8: "1"

steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0

- name: Set up Python
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
with:
python-version: ${{ matrix.python-version }}

- name: Set up Node.js
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: "20"

- name: Install Python dependencies
run: |
python -m pip install -r requirements.txt
python -m pip install -e .

- name: Install pinned Pyright for Windows
shell: pwsh
run: |
$root = Join-Path $env:RUNNER_TEMP "multilspy-pyright"
npm install --prefix $root --no-save --no-package-lock --ignore-scripts --no-audit --no-fund pyright@1.1.413
if ($LASTEXITCODE -ne 0) { throw "npm installation failed" }
$binary = Join-Path $root "node_modules/.bin/pyright-langserver.cmd"
if (-not (Test-Path -LiteralPath $binary -PathType Leaf)) { throw "Pinned Pyright not installed" }
"MULTILSPY_PYRIGHT_TEST_BINARY=$binary" | Out-File -FilePath $env:GITHUB_ENV -Append -Encoding utf8

- name: Test real Pyright, protocol, Unicode and lifecycle on Windows
run: >-
python -m pytest -q
tests/multilspy/test_multilspy_pyright.py
tests/multilspy/test_pyright_adapter_notifications.py
tests/multilspy/test_pyright_process_lifecycle.py
tests/multilspy/test_lsp_result_shapes.py
tests/multilspy/test_path_utils_portability.py
tests/multilspy/test_completion_responses.py
tests/multilspy/test_utf16_buffer_positions.py
tests/multilspy/test_python_completions.py
tests/multilspy/test_sync_startup.py
tests/multilspy/test_sync_file_thread.py
--tb=short
93 changes: 92 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ pip install multilspy
| Code Language | Language Server |
| --- | --- |
| java | Eclipse JDTLS |
| python | jedi-language-server |
| python | jedi-language-server (default) or Pyright |
| rust | Rust Analyzer |
| csharp | OmniSharp / RazorSharp |
| typescript | TypeScriptLanguageServer |
Expand All @@ -53,6 +53,97 @@ pip install multilspy
| cpp | clangd |


For Python, Jedi remains the default language server. To use Pyright instead,
install [Pyright](https://github.com/microsoft/pyright) and explicitly select
the optional backend:

```python
from multilspy import LanguageServer
from multilspy.multilspy_config import Language, MultilspyConfig
from multilspy.multilspy_logger import MultilspyLogger

config = MultilspyConfig(
code_language=Language.PYTHON,
python_server="pyright",
server_binary="/absolute/path/to/pyright-langserver",
)
lsp = LanguageServer.create(config, MultilspyLogger(), "/path/to/python/project")
async with lsp.start_server():
definitions = await lsp.request_definition("module.py", 10, 4)
```

The server binary must already be installed; the adapter adds the --stdio
argument and does not download/install Pyright. If server_binary is
omitted, it uses pyright-langserver from PATH. The existing
MultilspyConfig(code_language=Language.PYTHON) continues using Jedi.

Positions follow LSP: line and column are zero-based and the column counts
UTF-16 code units, so a non-BMP character such as an emoji occupies two columns.
Type checking is configured by the project (pyrightconfig.json or pyproject.toml);
the adapter does not override `typeCheckingMode`.

The adapter was validated against Pyright 1.1.413 (`pyright-langserver --stdio`).
The table lists what that release advertises to multilspy's read-only client
and how multilspy exposes it:

| Pyright capability | multilspy access | Coverage |
| --- | --- | --- |
| definition, references, hover, document symbols, workspace symbols | `request_definition`, `request_references`, `request_hover`, `request_document_symbols`, `request_workspace_symbol` | tested against Pyright |
| completion (`isIncomplete` retries), completionItem/resolve | `request_completions`; resolve through `server.send.resolve_completion_item` | tested against Pyright |
| declaration, typeDefinition, documentHighlight, signatureHelp, call hierarchy (incoming and outgoing) | `server.send.*` low-level requests | tested against Pyright |
| prepareRename, rename | `server.send.*`; the response is a WorkspaceEdit proposal, multilspy never applies it | proposal shape tested |
| codeAction (quickfix, source.organizeImports) | `server.send.code_action`; available fixes depend on project diagnostics and may propose file edits, including type-stub generation or renames; organize imports uses a command | empty-response fixture tested; no writable quick-fix corpus |
| publishDiagnostics (typeCheckingMode off/basic/standard/strict) | asynchronous `PyrightServer.next_diagnostics()` bounded queue (not exposed by `SyncLanguageServer`) | tested against Pyright |
| workspace/configuration, workspace/applyEdit, client/registerCapability | answered by the adapter: fixed read-only settings, edits refused, registration acknowledged and ignored | tested with fixtures and against Pyright |
| executeCommand | advertised with an empty command list; `pyright.organizeimports` is disabled by the adapter settings, `pyright.createtypestub` writes files and is not supported | refusal of the server's applyEdit tested |
| implementation, pull diagnostics, semantic tokens, inlay hints, folding, selection ranges, document links, formatting, code lens | not advertised to the current client capability profile by Pyright 1.1.413; requests fail with MethodNotFound | unsupported in this profile |

Real Pyright integration tests require a preinstalled language server. Set
MULTILSPY_PYRIGHT_TEST_BINARY to its absolute executable path before running
pytest on tests/multilspy/test_multilspy_pyright.py. Without this variable
the real-server tests skip; if it is set to a missing/non-executable binary,
the tests fail. The GitHub Actions test workflow installs pinned Pyright
1.1.413 and exercises the real provider on every Python test matrix entry.
Other local unit/fixture tests still run without installing Pyright.
Exact-protocol fixtures and capabilities are version-pinned; when upgrading
Pyright, update and revalidate the expected responses rather than silently
skipping mismatched versions. For third-party import resolution, configure the
project through `pyrightconfig.json` or `[tool.pyright]` in `pyproject.toml`.

By default, Pyright's `workspace/applyEdit` requests are refused and organize
imports is disabled. To support editor-controlled writes, the embedding client
can register an **async** handler before starting the server:

```python
# `lsp` is a PyrightServer returned by LanguageServer.create(...).
async def apply_workspace_edit(params):
# Validate affected URIs, ranges, document versions and user permission.
# Handle BOTH `changes` and `documentChanges` (including file operations)
# and apply the edit atomically in YOUR editor/workspace layer.
return {"applied": False, "failureReason": "Not approved"}

lsp.set_workspace_edit_handler(apply_workspace_edit, timeout_seconds=60)
```

When a handler is installed, the adapter advertises workspace `applyEdit`
support and enables Pyright organize-imports commands. The handler's LSP
response reports whether **the client actually applied the edit**. A successful
rename request by itself returns an edit *proposal*; multilspy does not apply
that proposal. It is the caller's responsibility to preview, approve, and
apply the WorkspaceEdit, including document versions and file operations.
If documents are already open, update both the editor's in-memory buffers
and the language server's `didChange` state; writing the disk copy alone leaves
the LSP document snapshot stale. Handler exceptions and timeouts are reported
as unsuccessful edits and never treated as authorization to write.

**Security boundary:** this opt-in callback is NOT a subprocess sandbox.
In Pyright 1.1.413, `pyright.createtypestub` directly writes `.pyi` files on
the language-server side without calling `workspace/applyEdit`. Other raw
`server.send.execute_command` calls may have similar side effects. Never expose
arbitrary commands to untrusted callers; use OS-level filesystem restrictions
and isolated workspaces for untrusted projects. An embedding application must enforce its own workspace authorization and
process confinement independently of multilspy's generic LSP integration.

## Usage
Example usage:
```python
Expand Down
37 changes: 27 additions & 10 deletions src/multilspy/language_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,14 @@ def create(cls, config: MultilspyConfig, logger: MultilspyLogger, repository_roo
:return LanguageServer: A language specific LanguageServer instance.
"""
if config.code_language == Language.PYTHON:
if config.python_server == "pyright":
from multilspy.language_servers.pyright_language_server.pyright_server import (
PyrightServer,
)

return PyrightServer(config, logger, repository_root_path)
if config.python_server != "jedi":
raise MultilspyException("Unsupported Python language server")
from multilspy.language_servers.jedi_language_server.jedi_server import (
JediServer,
)
Expand Down Expand Up @@ -425,8 +433,7 @@ async def request_definition(
new_item["relativePath"] = PathUtils.get_relative_path(new_item["absolutePath"], self.repository_root_path)
ret.append(multilspy_types.Location(new_item))
elif (
LSPConstants.ORIGIN_SELECTION_RANGE in item
and LSPConstants.TARGET_URI in item
LSPConstants.TARGET_URI in item
and LSPConstants.TARGET_RANGE in item
and LSPConstants.TARGET_SELECTION_RANGE in item
):
Expand Down Expand Up @@ -490,6 +497,8 @@ async def request_references(
)

ret: List[multilspy_types.Location] = []
if response is None:
return ret
assert isinstance(response, list), f"Unexpected response from Language Server: {response}"
for item in response:
assert isinstance(item, dict)
Expand Down Expand Up @@ -539,6 +548,9 @@ async def request_completions(
response = {"items": response, "isIncomplete": False}
if not response["isIncomplete"]:
break
completion_params["context"] = {
"triggerKind": LSPTypes.CompletionTriggerKind.TriggerForIncompleteCompletions
}

# TODO: Understand how to appropriately handle `isIncomplete`
if response is None or (response["isIncomplete"] and not(allow_incomplete)):
Expand All @@ -550,26 +562,27 @@ async def request_completions(
response: List[LSPTypes.CompletionItem] = response

# TODO: Handle the case when the completion is a keyword
items = [item for item in response if item["kind"] != LSPTypes.CompletionItemKind.Keyword]
items = [item for item in response if item.get("kind") != LSPTypes.CompletionItemKind.Keyword]

completions_list: List[multilspy_types.CompletionItem] = []

for item in items:
assert "insertText" in item or "textEdit" in item
assert "kind" in item
# LSP CompletionItem requires label; insertText, textEdit,
# and kind are all optional.
kind = item.get("kind", LSPTypes.CompletionItemKind.Text)
completion_item = {}
if "detail" in item:
completion_item["detail"] = item["detail"]

if "label" in item:
completion_item["completionText"] = item["label"]
completion_item["kind"] = item["kind"]
completion_item["kind"] = kind
elif "insertText" in item:
completion_item["completionText"] = item["insertText"]
completion_item["kind"] = item["kind"]
completion_item["kind"] = kind
elif "textEdit" in item and "newText" in item["textEdit"]:
completion_item["completionText"] = item["textEdit"]["newText"]
completion_item["kind"] = item["kind"]
completion_item["kind"] = kind
elif "textEdit" in item and "range" in item["textEdit"]:
new_dot_lineno, new_dot_colno = (
completion_params["position"]["line"],
Expand All @@ -586,7 +599,7 @@ async def request_completions(
)

completion_item["completionText"] = item["textEdit"]["newText"]
completion_item["kind"] = item["kind"]
completion_item["kind"] = kind
elif "textEdit" in item and "insert" in item["textEdit"]:
assert False
else:
Expand All @@ -595,9 +608,13 @@ async def request_completions(
completion_item = multilspy_types.CompletionItem(**completion_item)
completions_list.append(completion_item)

# Preserve the server's completion ranking while deduplicating.
# Iterating over a set makes suggestions reorder across processes.
return [
json.loads(json_repr)
for json_repr in set([json.dumps(item, sort_keys=True) for item in completions_list])
for json_repr in dict.fromkeys(
json.dumps(item, sort_keys=True) for item in completions_list
)
]

async def request_document_symbols(self, relative_file_path: str) -> Tuple[List[multilspy_types.UnifiedSymbolInformation], Union[List[multilspy_types.TreeRepr], None]]:
Expand Down
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
{
"_description": "Conservative LSP 3.17 capabilities for the Python Pyright language server.",
"processId": "$processId",
"rootPath": "$rootPath",
"rootUri": "$rootUri",
"workspaceFolders": [
{"name": "$name", "uri": "$uri"}
],
"clientInfo": {"name": "multilspy"},
"capabilities": {
"general": {
"positionEncodings": ["utf-16"]
},
"workspace": {
"applyEdit": false,
"configuration": true,
"workspaceFolders": false,
"symbol": {"dynamicRegistration": false},
"workspaceEdit": {"documentChanges": true}
},
"textDocument": {
"definition": {"linkSupport": true},
"declaration": {"linkSupport": true},
"typeDefinition": {"linkSupport": true},
"references": {},
"hover": {"contentFormat": ["markdown", "plaintext"]},
"completion": {
"dynamicRegistration": false,
"contextSupport": true,
"completionItem": {
"snippetSupport": false,
"documentationFormat": ["plaintext"]
}
},
"signatureHelp": {
"dynamicRegistration": false,
"signatureInformation": {
"documentationFormat": ["plaintext"],
"parameterInformation": {"labelOffsetSupport": true}
}
},
"rename": {"dynamicRegistration": false, "prepareSupport": true},
"codeAction": {
"dynamicRegistration": false,
"codeActionLiteralSupport": {
"codeActionKind": {"valueSet": ["quickfix", "source.organizeImports"]}
}
},
"callHierarchy": {"dynamicRegistration": false},
"documentHighlight": {"dynamicRegistration": false},
"documentSymbol": {"hierarchicalDocumentSymbolSupport": true},
"publishDiagnostics": {"relatedInformation": true}
}
}
}
Loading
Loading