Skip to content

Add standalone Type Server Protocol (TSP) server to Pyright - #11537

Merged
Rich Chiodo (rchiodo) merged 10 commits into
microsoft:mainfrom
rchiodo:rchiodo-move-typeserver-to-pyright
Jul 10, 2026
Merged

Rich Chiodo (rchiodo) merged 10 commits into
microsoft:mainfrom
rchiodo:rchiodo-move-typeserver-to-pyright

Conversation

@rchiodo

Copy link
Copy Markdown
Collaborator

Summary

Adds a standalone Type Server Protocol (TSP) implementation to Pyright, so Pyright can serve TSP on its own. The implementation is ported from Pylance's packages/typeServer, with the Pylance-specific pieces (notebook support, virtual-file overlays, stub generation) copied over so Pyright has equivalent functionality.

What's included

  • packages/pyright-internal/src/typeServer/ — the TSP module: protocol definitions (protocol/), the server (server.ts), the program wrapper (programWrapper.ts), type/declaration conversion (typeServerConversion*), cancellation, notebook support (notebook*), a virtual-file overlay filesystem, and stub generation.
  • packages/pyright-typeserver — a new package that bundles a distributable pyright-typeserver binary (run as pyright-typeserver --stdio).
  • Tests — in-proc TSP tests, notebook TSP tests, and virtual-file redirect tests under src/tests/typeServer/.
  • Docs — docs/type-server.md plus sidebar/internals links.
  • CI — the validation workflow builds the new package.

The change is almost entirely additive; the only pre-existing files touched are .github/workflows/validation.yml and the docs index.

Design notes

  • Fully synchronous. Unlike Pylance's async wrapper, Pyright's TSP server runs synchronously. Cancellation is token/file-based, matching normal Pyright, so requests can be cancelled mid-flight.
  • No IProgramSnapshot concept. Pyright doesn't model program snapshots the way Pylance does. The port drops that abstraction, folds it into the regular IProgram, and uses a monotonic snapshot counter purely for staleness detection.
  • Dead code removed. Client-side-only conversion helpers and unused provider/factory plumbing from the Pylance original were dropped during the port.

Validation

  • packages/pyright-internal builds clean (tsc), eslint reports 0 errors, prettier applied.
  • The Jest typeServer test suites pass.
  • Validated end-to-end against Pylance's own TSP client test suite (microsoft/pyrx typeServer.external.test.ts): 33/33 passing when Pylance drives Pyright's built type-server bundle over TSP. A companion PR fixes three pre-existing bugs in that pyrx suite — microsoft/pyrx#8838.

Commits

  • Add standalone TSP (Type Server Protocol) server to Pyright
  • Add notebook support to Pyright TSP server
  • Wire up pyright-typeserver package build, CI, and docs
  • Make TSP server synchronous and merge IProgramSnapshot into IProgram
  • Remove unused client-side protocol-to-Pyright type deserialization
  • Remove dead code from typeServer

Rich Chiodo (rchiodo) and others added 7 commits July 8, 2026 19:37
Port Pylance's type-server implementation into Pyright so Pyright can host a
standalone TSP server on its own. Covers scaffolding, the conversion core, the
async program wrapper + sync-to-async evaluator adapter, the server + node entry
point, and the virtual-file overlay file system with the stub-gen redirect
handlers.

- packages/pyright-typeserver: distributable package (rspack bundle) with node
  entry points, mirroring how the pyright package wraps pyright-internal.
- packages/pyright-internal/src/typeServer: protocol types, TSP<->Pyright
  conversion, async wrapper, TypeServer (LanguageServerBase-based), and the
  TypeServerFileSystem / VirtualFileOverlayFileSystem used for the Django
  stub-gen virtual-file redirect (TspSupplemental notifications).
- Tests: in-proc TSP harness + type-query tests and virtual-file-redirect tests.

Telemetry and profiling are intentionally omitted (Pyright has no telemetry).

Co-authored-by: Copilot App <[email protected]>
Ports Pylance's notebook cell-chain handling into the standalone Pyright type server so notebooks analyze as a linear chain of chained cell source files.

- notebookCellChain.ts: generic cell-chain core (createNotebookData, openNotebookCellChain, updateNotebookStructure, verifyCellChainIsLinear) retyped onto Pyright's Workspace.
- notebookDocumentHandler.ts: slim document handler with a serial event queue and per-notebook deferred data chain; drops Pylance-specific python-path/kernel/settings/startup machinery.
- server.ts: wires notebookDocument/did* notifications, notebook-cell URI mapping in getWorkspaceForFile/getContainingWorkspacesForFile/convertLspUriStringToUri, and advertises notebookDocumentSync.
- nodeMain.ts + in-proc harness: construct and register a NotebookUriMapper.
- notebook.typeServer.test.ts: ports the 8 Pylance cell-chain tests.

Co-authored-by: Copilot App <[email protected]>
Completes the standalone type server packaging.

- Adds the root bin shim (pyright-typeserver.js) that main/bin reference, mirroring the pyright package's index.js; sets __rootDirectory and requires the bundled dist entry.
- Adds a .gitignore for the README/LICENSE copied in during publish.
- Adds an npm publish --dry-run validation step for pyright-typeserver to the CI build job.
- Documents the Type Server Protocol server (docs/type-server.md) and links it from the sidebar and internals.

Co-authored-by: Copilot App <[email protected]>
Convert the ported type-server implementation from a fake-async model to a fully synchronous one and collapse the vestigial IProgramSnapshot 'pinned view' into IProgram.

- Remove asyncWrapper/asyncTypeEvaluatorTypes/syncEvaluatorAdapter; rename asyncWrapper.ts to programWrapper.ts as a thin synchronous wrapper over Pyright's Program.
- Merge IProgramSnapshot into IProgram; drop the dead IProgramHost/PropertyBag/PropertyKey and the redundant snapshot/host/*FileCachedData members.
- Delete _createSnapshotWrapper/_throwIfOutOfDate and the per-method snapshot params; keep the snapshot content-version counter as a live protocol feature.
- Add explicit boundary staleness gates to _onResolveImport and _onGetPythonSearchPaths to preserve stale-snapshot rejection.

Cancellation is file/token based like the rest of Pyright. tsc, eslint, prettier, 24 typeServer jest tests, and the bin-shim smoke test all pass.

Co-authored-by: Copilot App <[email protected]>
The type server only serializes Pyright types into protocol types (via ProtocolTypeFactory). The reverse direction (protocol -> Pyright Type) is what a TSP client performs, and its entry point (PyrightTypeFactory) was never instantiated anywhere in the server or tests.

Delete the dead deserialization cluster:
- typeProvider.ts and typeShellFactory.ts (whole files)
- PyrightTypeFactory in typeServerConversionUtils.ts
- The now-orphaned IPyrightTypeFactory interface, protocol type guards (isClass/isFunction/isEnumLiteral/isSentinelLiteral), and fromProtocolTypes*/fromProtocolVariance helpers in typeServerConversionTypes.ts

fromProtocolDecl/fromProtocolNode stay: the server uses them to locate the input declaration/node for a type query. tsc, eslint, prettier, 24 typeServer jest tests, and the bin-shim smoke test all pass.

Co-authored-by: Copilot App <[email protected]>
Remove exported symbols in packages/pyright-internal/src/typeServer that have no
references outside their defining file, identified via static analysis and
manually confirmed:

- programTypes.ts: ISymbolDefinitionProviderFactory, ISymbolDefinitionProvider,
  ISymbolUsageProvider, ISymbolUsageProviderFactory, OpenFileContent,
  IServiceFactory (Pylance extension-point cluster, never wired up)
- typeUtils.ts: lookUpClassMembers, getFunctionParameterNode,
  getParameterAnnotationNode, TypeMember
- typeServerConversionTypes.ts: toProtocolNodeOrUndefined,
  fromProtocolNodeOrUndefined, fromProtocolTypeFlags
- notebookCellChain.ts: NotebookDocumentSelector, isNotebookKernelChange
- programWrapper.ts: makeParseResultsProvider

Also removes the resulting orphaned imports. No behavior change; tsc, eslint,
prettier, the typeServer jest suites (24), and the phase7 smoke all pass.

Co-authored-by: Copilot App <[email protected]>
@heejaechang

Copy link
Copy Markdown
Collaborator

🔒 Automated review in progress — Heejae Chang (@heejaechang) is auto-reviewing this PR.

@github-actions

This comment has been minimized.

@heejaechang

Copy link
Copy Markdown
Collaborator

Looks solid and safe to merge — the change is almost entirely additive and the type-server suites pass. The main theme worth the author's attention is duplication of spec-sensitive logic ported from Pylance/analyzer (enums/typeGuards, and the hand-copied wire protocol), plus one latent notebook-mode trap in the virtual-file redirect path. None block merge, but addressing the duplication reduces long-term drift risk against the 'identical to Pyright's other front ends' guarantee.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved via Review Center.

Rich Chiodo (rchiodo) and others added 2 commits July 9, 2026 14:39
…ting

Regenerate pyright-typeserver package-lock.json with npm 10 (matching CI's
node 22.x) to remove libc fields that npm 11 adds, and remove a trailing
blank line in nodeMain.ts flagged by prettier.

Co-authored-by: Copilot App <[email protected]>
Bump @types/node to ^25.9.2 and esbuild-loader to ^4.5.0 to match the
versions used by the other packages on main, resolving syncpack mismatches
in the merged CI tree.

Co-authored-by: Copilot App <[email protected]>
@github-actions

This comment has been minimized.

@heejaechang

Copy link
Copy Markdown
Collaborator

Solid additive port — thanks for the thorough validation against the real client suite. I've dropped the style-rule nits (readonly modifiers, helper placement, dynamic require, duplicated helper) as non-blocking noise, and collapsed the many duplicated/latent findings. Three non-blocking notes remain below for robustness and test strength; none block merge.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved via Review Center.

@heejaechang

Copy link
Copy Markdown
Collaborator

GitHub cannot anchor PR review comments to unchanged lines in the diff. Falling back to a general PR comment for packages/pyright-internal/src/typeServer/server.ts:L9931.

_onSetVirtualFileRedirect / _onRemoveVirtualFileRedirect pass literal IPythonMode.None to updateOpenFileContents, whereas ProgramWrapper.updateFileContents reads and preserves fileInfo.ipythonMode. This is latent today (redirect realUri targets are module files, never notebook cells), but if a realUri is ever an open cell it would reset the mode and detach it from the cell chain. Mirror the wrapper's read-and-preserve pattern to close the trap.

@heejaechang

Copy link
Copy Markdown
Collaborator

Solid additive port of the TSP server into Pyright — well isolated and validated end-to-end. A few non-blocking suggestions: tighten a couple of deterministic test assertions, de-duplicate one shared helper, and add a fork-drift signpost on the copied enum logic.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved via Review Center.

@rchiodo

Copy link
Copy Markdown
Collaborator Author

Please take a look at all of Heejae's comments.

- Dedupe getSymbolFromScope: export from typeEvalUtils and reuse it in
  programWrapper instead of maintaining a byte-identical copy.
- Preserve existing IPythonMode on virtual-file redirect re-pushes so open
  notebook cells aren't reset/detached from their cell chain.
- Enforce the snapshot-cache invariant: pass the global type cache explicitly
  from _getProgram and reject re-wrapping a program with a different cache.
- Document the type server protocol single source of truth (typeServerProtocol.ts
  authoritative; tsp.json generated; cross-repo copy must be kept in sync).
- Add "forked from analyzer/*; keep in sync" signposts to typeServer enums.ts
  and typeGuards.ts.
- Strengthen weak TSP type tests to assert concrete TypeKind and class name.

Co-authored-by: Copilot <[email protected]>
@github-actions

Copy link
Copy Markdown
Contributor

Diff from mypy_primer, showing the effect of this PR on open source code:

sympy (https://github.com/sympy/sympy)
-   .../projects/sympy/sympy/solvers/ode/single.py:867:9 - error: Expression with type "tuple[Unknown | Any | NaN | Expr | Infinity | NegativeInfinity | Zero | Float, list[tuple[Unknown, Unknown]] | list[Unknown]] | tuple[Unknown | Any | NaN | Expr | Infinity | NegativeInfinity | Zero | Float, list[tuple[Unknown, Unknown]] | list[Unknown], list[tuple[Unknown, Unknown]] | list[Unknown]]" cannot be assigned to target tuple
-     Type "tuple[Unknown | Any | NaN | Expr | Infinity | NegativeInfinity | Zero | Float, list[tuple[Unknown, Unknown]] | list[Unknown], list[tuple[Unknown, Unknown]] | list[Unknown]]" is incompatible with target tuple
+   .../projects/sympy/sympy/solvers/ode/single.py:867:9 - error: Expression with type "tuple[ComplexInfinity | NaN | Rational | Zero | Infinity | NegativeInfinity | Float | NotImplementedType | Expr | Unknown | Any, list[tuple[Unknown, Unknown]] | list[Unknown]] | tuple[ComplexInfinity | NaN | Rational | Zero | Infinity | NegativeInfinity | Float | NotImplementedType | Expr | Unknown | Any, list[tuple[Unknown, Unknown]] | list[Unknown], list[tuple[Unknown, Unknown]] | list[Unknown]]" cannot be assigned to target tuple
+     Type "tuple[ComplexInfinity | NaN | Rational | Zero | Infinity | NegativeInfinity | Float | NotImplementedType | Expr | Unknown | Any, list[tuple[Unknown, Unknown]] | list[Unknown], list[tuple[Unknown, Unknown]] | list[Unknown]]" is incompatible with target tuple
+   .../projects/sympy/sympy/solvers/ode/single.py:1404:20 - error: Operator "/" not supported for types "Basic" and "Basic" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/ode/single.py:1883:22 - error: "is_Rational" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/solvers/ode/single.py:1886:22 - error: "is_Rational" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/solvers/ode/single.py:1905:25 - error: Operator "*" not supported for types "Zero | One | Expr | Unknown | None" and "Zero | One | Expr | Unknown | None"
+     Operator "*" not supported for types "Expr" and "None"
+     Operator "*" not supported for types "None" and "Expr"
+     Operator "*" not supported for types "None" and "None" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/ode/single.py:1905:33 - error: Operator "*" not supported for types "Zero | One | Expr | Unknown | None" and "Zero | One | Expr | Unknown | None"
+     Operator "*" not supported for types "Expr" and "None"
+     Operator "*" not supported for types "None" and "Expr"
+     Operator "*" not supported for types "None" and "None" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/ode/single.py:1914:21 - error: Operator "*" not supported for "None" (reportOptionalOperand)
+   .../projects/sympy/sympy/solvers/ode/single.py:1914:29 - error: Operator "*" not supported for "None" (reportOptionalOperand)
+   .../projects/sympy/sympy/solvers/ode/single.py:1914:44 - error: Operator "*" not supported for "None" (reportOptionalOperand)
+   .../projects/sympy/sympy/solvers/ode/single.py:1914:52 - error: Operator "*" not supported for "None" (reportOptionalOperand)
-   .../projects/sympy/sympy/solvers/ode/single.py:2646:27 - error: Argument of type "One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Infinity | NegativeInfinity | Float | Number | Expr | Unknown | int" cannot be assigned to parameter "stop" of type "SupportsIndex" in function "__new__"
-     Type "One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Infinity | NegativeInfinity | Float | Number | Expr | Unknown | int" is not assignable to type "SupportsIndex"
-       "Expr" is incompatible with protocol "SupportsIndex"
-         "__index__" is not present (reportArgumentType)
-   .../projects/sympy/sympy/solvers/ode/single.py:2652:9 - error: Operator "+=" not supported for types "One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Infinity | NegativeInfinity | Float | Number | Expr | Any | Unknown" and "Basic | Any | Unknown"
+   .../projects/sympy/sympy/solvers/ode/single.py:2652:9 - error: Operator "+=" not supported for types "One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Infinity | NegativeInfinity | Float | Number | Expr | Any | Unknown" and "Basic"
+   .../projects/sympy/sympy/solvers/ode/single.py:2760:30 - error: Object of type "None" is not subscriptable (reportOptionalSubscript)
-   .../projects/sympy/sympy/solvers/tests/test_solveset.py:445:30 - error: Cannot access attribute "limit_denominator" for class "NaN"
-     Attribute "limit_denominator" is unknown (reportAttributeAccessIssue)
-   .../projects/sympy/sympy/solvers/tests/test_solveset.py:445:30 - error: Cannot access attribute "limit_denominator" for class "ComplexInfinity"
-     Attribute "limit_denominator" is unknown (reportAttributeAccessIssue)
-   .../projects/sympy/sympy/stats/joint_rv_types.py:576:27 - error: Argument of type "One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Infinity | NegativeInfinity | Float | Number | Expr" cannot be assigned to parameter "stop" of type "SupportsIndex" in function "__new__"
+   .../projects/sympy/sympy/stats/joint_rv_types.py:576:27 - error: Argument of type "One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Unknown | Infinity | NegativeInfinity | Float | Number | Expr" cannot be assigned to parameter "stop" of type "SupportsIndex" in function "__new__"
-     Type "One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Infinity | NegativeInfinity | Float | Number | Expr" is not assignable to type "SupportsIndex"
+     Type "One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Unknown | Infinity | NegativeInfinity | Float | Number | Expr" is not assignable to type "SupportsIndex"
-   .../projects/sympy/sympy/stats/rv_interface.py:451:42 - error: Operator "-" not supported for types "Unknown | Basic | Any" and "Rational | NaN | ComplexInfinity"
+   .../projects/sympy/sympy/stats/rv_interface.py:451:42 - error: Operator "-" not supported for types "Unknown | Basic | Any" and "Rational | Unknown"
-     Operator "-" not supported for types "Basic" and "Rational"
-     Operator "-" not supported for types "Basic" and "NaN"
-     Operator "-" not supported for types "Basic" and "ComplexInfinity" (reportOperatorIssue)
+     Operator "-" not supported for types "Basic" and "Rational" (reportOperatorIssue)
-   .../projects/sympy/sympy/stats/tests/test_finite_rv.py:248:19 - error: Argument of type "Rational | NaN | ComplexInfinity" cannot be assigned to parameter "p" of type "Half" in function "Coin"
+   .../projects/sympy/sympy/stats/tests/test_finite_rv.py:248:19 - error: Argument of type "Rational | Unknown" cannot be assigned to parameter "p" of type "Half" in function "Coin"
-     Type "Rational | NaN | ComplexInfinity" is not assignable to type "Half"
+     Type "Rational | Unknown" is not assignable to type "Half"
-       "ComplexInfinity" is not assignable to "Half" (reportArgumentType)
+       "Rational" is not assignable to "Half" (reportArgumentType)
-   .../projects/sympy/sympy/utilities/tests/test_wester.py:402:38 - error: Cannot access attribute "limit_denominator" for class "NaN"
-     Attribute "limit_denominator" is unknown (reportAttributeAccessIssue)
-   .../projects/sympy/sympy/utilities/tests/test_wester.py:402:38 - error: Cannot access attribute "limit_denominator" for class "ComplexInfinity"
-     Attribute "limit_denominator" is unknown (reportAttributeAccessIssue)
-     Return type mismatch: base method returns type "tuple[One, Self@Expr]", override returns type "tuple[One | NegativeOne | Zero | Integer | Expr | Unknown | Rational | NaN | ComplexInfinity, Expr | Unknown | Self@Add]"
+     Return type mismatch: base method returns type "tuple[One, Self@Expr]", override returns type "tuple[One | NegativeOne | Zero | Integer | Unknown | Rational, Expr | Unknown | Self@Add]"
-       "tuple[One | NegativeOne | Zero | Integer | Expr | Unknown | Rational | NaN | ComplexInfinity, Expr | Unknown | Self@Add]" is not assignable to "tuple[One, Self@Expr]"
+       "tuple[One | NegativeOne | Zero | Integer | Unknown | Rational, Expr | Unknown | Self@Add]" is not assignable to "tuple[One, Self@Expr]"
-           Type "One | NegativeOne | Zero | Integer | Expr | Unknown | Rational | NaN | ComplexInfinity" is not assignable to type "One"
+           Type "One | NegativeOne | Zero | Integer | Unknown | Rational" is not assignable to type "One"
-             "Expr" is not assignable to "One" (reportIncompatibleMethodOverride)
+             "Rational" is not assignable to "One" (reportIncompatibleMethodOverride)
-   .../projects/sympy/sympy/vector/dyadic.py:253:7 - error: Base classes for class "DyadicAdd" define method "primitive" in incompatible way
-     Return type mismatch: base method returns type "tuple[Number, Expr]", override returns type "tuple[One, Self@Add] | tuple[Rational | NaN | ComplexInfinity, Unknown | Self@Add]"
-       Type "tuple[One, Self@Add] | tuple[Rational | NaN | ComplexInfinity, Unknown | Self@Add]" is not assignable to type "tuple[Number, Expr]"
-         "tuple[Rational | NaN | ComplexInfinity, Unknown | Self@Add]" is not assignable to "tuple[Number, Expr]"
-           Tuple entry 1 is incorrect type
-             Type "Rational | NaN | ComplexInfinity" is not assignable to type "Number" (reportIncompatibleMethodOverride)
+   .../projects/sympy/sympy/vector/implicitregion.py:188:18 - error: Operator "/" not supported for types "int | Unknown" and "Alg | Unknown | GaussianRational | MPQ | GaussianInteger | MPZ | Expr | Rational | One | NegativeOne | Zero | Integer | NaN | Infinity | NegativeInfinity | Float | Number | Poly"
+     Operator "/" not supported for types "int" and "MPZ" (reportOperatorIssue)

... (truncated 59 lines) ...

@heejaechang

Copy link
Copy Markdown
Collaborator

Looks solid — approving. Clean additive port, tests pass, and external validation is green. A batch of readonly-by-default / test-strictness convention notes were raised by the first pass; they carry no functional impact and several sibling comments in that batch misread the diff, so I'm not blocking on them. If you want to satisfy those conventions, adding readonly to the never-reassigned private fields in programWrapper.ts / typeCache.ts / notebookUriMapper.ts is a trivial optional follow-up.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved via Review Center.

@rchiodo
Rich Chiodo (rchiodo) merged commit 4c60ea9 into microsoft:main Jul 10, 2026
16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants