Orchestrata Ultimate / Specs / 065-lsp-tool
065-lsp-tool: LSPTool - Language Server Protocol Integration
LSPTool provides comprehensive Language Server Protocol integration for code intelligence, including automatic language server detection, code completion, hover information, diagnostics, go-to-definition, find references, code actions, and document formatting.
At a glance
| Item | Value |
|---|---|
| Spec directory | specs/065-lsp-tool/ |
| Status line in the spec | Complete |
| Requirement IDs defined | 26 |
With a @traces citation in src/ |
14 (53.8%) |
With a @traces citation in tests/ |
0 (0.0%) |
| Tracked files | 3 |
| RTM page | 065-lsp-tool |
Reading this spec
This spec defines LSPTool, which gives agents code intelligence through the Language Server Protocol: automatic language server detection, completion, hover information, diagnostics, go-to-definition, find references, code actions, rename and document formatting. The aim is context-aware code assistance, real-time error and lint feedback, code navigation, type information on hover and refactoring support.
The design is a native Python LSP implementation that detects the language from file extensions and project files, runs several language servers at once with process isolation, manages server lifecycle (start, stop, restart), and talks JSON-RPC 2.0 over stdio. Five user stories cover intelligent completion, real-time diagnostics, code navigation, hover information, and code actions with refactoring. Data models define diagnostics, completion, hover, location and document-edit shapes. The functional requirements (FR-001 onward) run from language server management and document synchronization to completion, diagnostics and the rest.
The 26 requirement IDs (REQ-065-NNN) include go-to-definition and hover returning the declared signature, named error conditions such as SERVER_NOT_FOUND and SERVER_ERROR for diagnostics, verification that a server executable exists, a request timeout on every diagnostics call, and a statement that LSPTool implements BaseTool with ToolMetadata. A later group lists lifecycle management, document synchronization (open, change, close), completion with trigger characters, code actions, formatting, rename (prepare, then execute across files), signature help, type-definition and implementation lookup, fallback servers per language, and handling of server crashes and memory limits.
The code is in the LSP tool module. The requirements traceability matrix lists each ID. The spec's own status line reads Complete and it tracks 3 files. Measured coverage is 14 of 26 requirements cited by at least one @traces in src/ (53.8%), spread over 1 module; the module citing the most of them is orchestrata_ultimate/tools/lsp_tool (14 requirements). In tests/, 0 requirements are cited by a test-side @traces. 12 requirements have no citing symbol, namely REQ-065-015 and the later feature list REQ-065-101 to REQ-065-111 (lifecycle management through TLS and checksum verification); the behaviour may still exist in code that was never annotated.
Requirements
Checkbox is the state recorded in the requirements checklist; Traced by is the count of src/ symbols whose @traces names the ID.
| ID | Done | Requirement | Traced by |
|---|---|---|---|
REQ-065-001 |
yes | Go to definition resolves the identifier at a given | 9 |
REQ-065-002 |
yes | Find references returns every Name/Attribute/def-site |
11 |
REQ-065-003 |
yes | Document symbols lists every class/function/method in a | 6 |
REQ-065-004 |
yes | Hover returns the declared signature (rendered via | 7 |
REQ-065-006 |
yes | Diagnostics for a document run the real pyright CLI |
7 |
REQ-065-007 |
yes | Diagnostics severity is mapped from pyright's | 1 |
REQ-065-008 |
yes | ERR-001 SERVER_NOT_FOUND — diagnostics raised when |
1 |
REQ-065-009 |
yes | ERR-004 REQUEST_TIMEOUT — diagnostics raised when the |
1 |
REQ-065-010 |
yes | ERR-005 INVALID_URI — raised for a blank URI or a |
1 |
REQ-065-011 |
yes | ERR-007 SERVER_ERROR — raised when the diagnostics |
1 |
REQ-065-012 |
yes | ERR-011 UNSUPPORTED_LANGUAGE — raised for any |
2 |
REQ-065-013 |
yes | ERR-012 FILE_READ_ERROR — raised when the target file |
2 |
REQ-065-014 |
yes | Server executable existence is verified | 1 |
REQ-065-015 |
yes | A request timeout is enforced on every diagnostics | none |
REQ-065-016 |
yes | LSPTool implements BaseTool with ToolMetadata |
2 |
REQ-065-101 |
no | Language server lifecycle management — multiple | none |
REQ-065-102 |
no | Document synchronization — didOpen/didChange/didClose, | none |
REQ-065-103 |
no | Code completion — trigger characters, snippet | none |
REQ-065-104 |
no | Code actions — quick fixes, organize imports, apply | none |
REQ-065-105 |
no | Document/range/on-type formatting (FR-008) | none |
REQ-065-106 |
no | Rename — prepareRename + execute across all | none |
REQ-065-107 |
no | Signature help (FR-005/spec API signature_help) |
none |
REQ-065-108 |
no | Go to type definition / go to implementation / | none |
REQ-065-109 |
no | Fallback-server strategy and per-language server | none |
REQ-065-110 |
no | Server-crash / memory-limit / protocol-level | none |
REQ-065-111 |
no | TLS for server communication, checksum verification, | none |
Code that traces this spec
| Module | Symbols | Requirements |
|---|---|---|
orchestrata_ultimate/tools/lsp_tool |
33 | 14 |
Checklists
checklists/requirements.md
The requirement list above comes from this file; 15 of 26 checkbox items are ticked.
Other tracked files
specs/065-lsp-tool/compliance-audit.md
Full spec text
Verbatim from specs/065-lsp-tool/spec.md; headings are pushed down two levels.
SPEC-065: LSPTool - Language Server Protocol Integration
Metadata
- Spec ID: 065-lsp-tool
- Title: LSPTool - Language Server Protocol Integration
- Author: Mohamed
- Status: Complete
- Created: 2026-04-08
- Last Updated: 2026-04-09
- Priority: P0
- Version: 1.0.0
Overview
What
LSPTool provides comprehensive Language Server Protocol integration for code intelligence, including automatic language server detection, code completion, hover information, diagnostics, go-to-definition, find references, code actions, and document formatting.
Why
- Provide intelligent code assistance with context-aware completions
- Real-time diagnostics for errors, warnings, and linting issues
- Code navigation with go-to-definition and find references
- Type information and documentation on hover
- Enable refactoring operations (rename, code actions)
How
- Language Server Protocol (LSP) implementation using native Python
- Automatic language detection based on file extensions and project files
- Multiple concurrent language server support with process isolation
- Server lifecycle management (start, stop, restart)
- JSON-RPC 2.0 communication over stdio
Terminology
| Term | Definition |
|---|---|
| LSP | Language Server Protocol - a JSON-RPC based protocol for IDE/tool communication |
| Language Server | External process that provides language-specific intelligence |
| Completion Item | Single suggestion in code completion results |
| Diagnostic | Error, warning, or info message from the language server |
| Text Document Position | Location in source code (line, character) |
| Location | Reference to a position in a file (URI + range) |
| Server Capabilities | Features supported by a language server |
| Client Capabilities | Features the client/tool supports |
User Scenarios
US-001: Intelligent Code Completion
As a developer
I want to get context-aware code completions
So that I can write code faster with accurate suggestions
Scenario:
- User opens a Python file and starts typing
- System detects the language (Python) and LSP server (pyright)
- LSP server starts automatically (or connects to existing)
- As user types, completion requests are sent to server
- Server returns ranked completion items with documentation
- User selects completion, it is inserted at cursor
Acceptance Criteria:
- Completions triggered on keystroke (configurable delay)
- Returns completion items with labels, kind, detail, documentation
- Supports snippet placeholders in insert text
- Includes commit characters for automatic acceptance
- Filters completions based on prefix matching
US-002: Real-Time Diagnostics
As a developer
I want to see errors, warnings, and linting issues in real-time
So that I can fix issues immediately while coding
Scenario:
- User opens or modifies a source file
- System sends didChange notification to LSP server
- Server analyzes code and publishes diagnostics
- Diagnostics returned with severity, message, location
- User sees inline markers and can navigate to issues
Acceptance Criteria:
- Diagnostics published on file change (debounced)
- Returns all diagnostics for file with accurate line/column positions
- Includes severity levels: Error (1), Warning (2), Info (3), Hint (4)
- Includes diagnostic code and source (e.g., "pylint", "pyright")
- Supports related information for expanded context
US-003: Code Navigation
As a developer
I want to navigate to symbol definitions and find references
So that I can understand code structure and relationships
Scenario:
- User positions cursor on a symbol (function, class, variable)
- User triggers "go to definition" action
- System sends definition request to LSP server
- Server returns location of symbol definition
- User is navigated to definition file and position
- User can also find all references to see usage
Acceptance Criteria:
- Go to definition returns single or multiple locations
- Find references returns all locations where symbol is used
- Includes symbol container name in results
- Supports navigation across project files
- Handles virtual files and generated code
US-004: Hover Information
As a developer
I want to see type information and documentation on hover
So that I understand code without leaving my current position
Scenario:
- User positions cursor over a symbol
- User triggers hover action (hover or show info)
- System sends hover request to LSP server
- Server returns content: type signature, documentation, value
- Content displayed in tooltip or side panel
Acceptance Criteria:
- Returns type signature (function signature, variable type)
- Returns documentation from docstrings/comments
- Returns definition location for quick navigation
- Supports Markdown formatting in content
- Responsive display within latency targets
US-005: Code Actions and Refactoring
As a developer
I want to apply quick fixes and refactorings
So that I can improve code quality efficiently
Scenario:
- User positions cursor on a diagnostic (error/warning)
- User triggers code action request
- Server returns available code actions (fixes, refactors)
- User selects action from list
- System applies changes to document
- Document is updated with edits
Acceptance Criteria:
- Returns available code actions for cursor position
- Includes action title and description
- Supports action preview (optional)
- Applies edits as document changes
- Supports organize imports, extract method, rename
Data Models
LSPDiagnostics
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "LSPDiagnostics",
"type": "object",
"required": ["uri", "diagnostics"],
"properties": {
"uri": {
"type": "string",
"description": "Document URI"
},
"diagnostics": {
"type": "array",
"description": "List of diagnostic items",
"items": {
"type": "object",
"required": ["range", "message"],
"properties": {
"range": {
"$ref": "#/definitions/Range"
},
"severity": {
"type": "integer",
"enum": [1, 2, 3, 4],
"description": "1=Error, 2=Warning, 3=Info, 4=Hint"
},
"message": {
"type": "string",
"description": "Diagnostic message"
},
"code": {
"type": "string",
"description": "Diagnostic code"
},
"source": {
"type": "string",
"description": "Source of diagnostic (e.g., 'pyright', 'pylint')"
},
"relatedInformation": {
"type": "array",
"items": {
"type": "object",
"properties": {
"location": {
"$ref": "#/definitions/Location"
},
"message": {
"type": "string"
}
}
}
}
}
}
}
},
"definitions": {
"Range": {
"type": "object",
"required": ["start", "end"],
"properties": {
"start": {
"$ref": "#/definitions/Position"
},
"end": {
"$ref": "#/definitions/Position"
}
}
},
"Position": {
"type": "object",
"required": ["line", "character"],
"properties": {
"line": {
"type": "integer",
"minimum": 0
},
"character": {
"type": "integer",
"minimum": 0
}
}
},
"Location": {
"type": "object",
"required": ["uri", "range"],
"properties": {
"uri": {
"type": "string"
},
"range": {
"$ref": "#/definitions/Range"
}
}
}
}
}
LSPCompletion
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "LSPCompletion",
"type": "object",
"required": ["isIncomplete", "items"],
"properties": {
"isIncomplete": {
"type": "boolean",
"description": "Whether completion list is incomplete"
},
"items": {
"type": "array",
"description": "List of completion items",
"items": {
"type": "object",
"required": ["label"],
"properties": {
"label": {
"type": "string",
"description": "Label to display"
},
"kind": {
"type": "integer",
"description": "Completion item kind (1-25)"
},
"detail": {
"type": "string",
"description": "Type signature or short detail"
},
"documentation": {
"type": "string",
"description": "Full documentation"
},
"insertText": {
"type": "string",
"description": "Text to insert"
},
"insertTextFormat": {
"type": "integer",
"enum": [1, 2],
"description": "1=PlainText, 2=Snippet"
},
"range": {
"$ref": "#/definitions/Range"
},
"commitCharacters": {
"type": "array",
"items": {
"type": "string"
}
},
"filterText": {
"type": "string"
},
"preselect": {
"type": "boolean"
}
}
}
}
},
"definitions": {
"Range": {
"type": "object",
"required": ["start", "end"],
"properties": {
"start": {
"type": "object",
"properties": {
"line": {"type": "integer"},
"character": {"type": "integer"}
}
},
"end": {
"type": "object",
"properties": {
"line": {"type": "integer"},
"character": {"type": "integer"}
}
}
}
}
}
}
LSPHover
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "LSPHover",
"type": "object",
"properties": {
"contents": {
"oneOf": [
{"type": "string"},
{"type": "object"},
{
"type": "array",
"items": {"type": "object"}
}
],
"description": "Hover content (Markdown string or MarkupContent)"
},
"range": {
"type": "object",
"properties": {
"start": {
"type": "object",
"properties": {
"line": {"type": "integer"},
"character": {"type": "integer"}
}
},
"end": {
"type": "object",
"properties": {
"line": {"type": "integer"},
"character": {"type": "integer"}
}
}
}
}
}
}
LSPLocation
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "LSPLocation",
"type": "object",
"required": ["uri", "range"],
"properties": {
"uri": {
"type": "string",
"description": "Document URI"
},
"range": {
"type": "object",
"required": ["start", "end"],
"properties": {
"start": {
"type": "object",
"properties": {
"line": {"type": "integer"},
"character": {"type": "integer"}
}
},
"end": {
"type": "object",
"properties": {
"line": {"type": "integer"},
"character": {"type": "integer"}
}
}
}
}
}
}
LSPDocumentEdit
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "LSPDocumentEdit",
"type": "object",
"required": ["uri", "edits"],
"properties": {
"uri": {
"type": "string"
},
"edits": {
"type": "array",
"items": {
"type": "object",
"required": ["range", "newText"],
"properties": {
"range": {
"type": "object",
"properties": {
"start": {
"type": "object",
"properties": {
"line": {"type": "integer"},
"character": {"type": "integer"}
}
},
"end": {
"type": "object",
"properties": {
"line": {"type": "integer"},
"character": {"type": "integer"}
}
}
}
},
"newText": {
"type": "string"
}
}
}
}
}
}
Functional Requirements
FR-001: Language Server Management
- System SHALL support multiple concurrent language servers
- System SHALL automatically start language server on first request
- System SHALL restart language server on crash or failure
- System SHALL gracefully stop language server on shutdown
- System SHALL support server-specific initialization options
FR-002: Document Synchronization
- System SHALL open documents with didOpen notification
- System SHALL update documents with didChange notifications
- System SHALL close documents with didClose notification
- System SHALL support full and incremental text synchronization
- System SHALL debounce rapid changes to reduce server load
FR-003: Completion Support
- System SHALL request completions on trigger characters
- System SHALL support completion resolve for additional details
- System SHALL filter completions based on prefix
- System SHALL support snippet expansion
- System SHALL return incomplete flag for server-side filtering
FR-004: Diagnostics Support
- System SHALL subscribe to diagnostic publications
- System SHALL aggregate diagnostics from all open documents
- System SHALL clear diagnostics on document close
- System SHALL support related information in diagnostics
FR-005: Navigation Support
- System SHALL support go to definition
- System SHALL support go to type definition
- System SHALL support go to implementation
- System SHALL support find references
- System SHALL support document symbols
- System SHALL support workspace symbols
FR-006: Hover Support
- System SHALL request hover information on cursor position
- System SHALL return formatted content (Markdown/Plaintext)
- System SHALL include range for hover target
FR-007: Code Actions
- System SHALL request code actions for cursor position
- System SHALL apply edits from selected action
- System SHALL support organize imports action
- System SHALL support quick fix actions
FR-008: Formatting Support
- System SHALL support document formatting
- System SHALL support range formatting
- System SHALL support on-type formatting
FR-009: Rename Support
- System SHALL prepare rename at cursor position
- System SHALL execute rename with new name
- System SHALL return edits for all occurrences
Error Conditions
| ID | Condition | Trigger | Handling |
|---|---|---|---|
| ERR-001 | Language server not found | Server command not in PATH | Fall back to alternative server or return error with installation instructions |
| ERR-002 | Server connection timeout | Server fails to respond within timeout | Retry with exponential backoff, fallback server, then return error |
| ERR-003 | Server startup failure | Server process exits immediately | Log stderr, try fallback server, return diagnostic error |
| ERR-004 | Request timeout | LSP request exceeds timeout | Cancel request, return partial results if available, log warning |
| ERR-005 | Invalid document URI | Malformed or unsupported URI | Return validation error with correct URI format |
| ERR-006 | Document not open | Request for unopened document | Return error indicating document must be opened first |
| ERR-007 | Server error | Server cannot process the request | Return null results, log for debugging |
| ERR-008 | JSON-RPC protocol error | Malformed LSP message | Log error, attempt recovery, return protocol error |
| ERR-009 | Server process crash | Process terminates unexpectedly | Restart server, re-open documents, return crash error |
| ERR-010 | Memory limit exceeded | Server uses excessive memory | Terminate server, return memory error, suggest restart |
| ERR-011 | Unsupported language | Language has no configured server | Return error with supported languages list |
| ERR-012 | File read error | Cannot read source file | Return error with file path, check permissions |
| ERR-013 | Server initialization timeout | Server initialize takes too long | Cancel initialization, try fallback, return timeout error |
Non-Functional Requirements
Performance Requirements
| Operation | Target | Maximum |
|---|---|---|
| Completion response | < 100ms | 500ms |
| Hover response | < 50ms | 300ms |
| Diagnostics publish | < 200ms | 1000ms |
| Go to definition | < 100ms | 500ms |
| Find references | < 300ms | 2000ms |
| Code actions | < 200ms | 1000ms |
| Document format | < 500ms | 3000ms |
| Server startup | < 2000ms | 10000ms |
Scalability Requirements
- System SHALL support 100+ concurrent documents per server instance
- System SHALL support 10+ concurrent language servers
- System SHALL handle files up to 10MB without performance degradation
- System SHALL maintain response times under load (max 10 concurrent requests)
Reliability Requirements
- System SHALL achieve 99.9% uptime for server availability
- System SHALL automatically recover from server crashes within 5 seconds
- System SHALL maintain document state across server restarts
- System SHALL log all operations for debugging and audit
Usability Requirements
- System SHALL provide clear error messages for all failure modes
- System SHALL support hot-reloading of server configurations
- System SHALL allow users to disable features per language
- System SHALL show server status (connected/disconnected/restarting)
Technical Design
Architecture Overview
The LSPTool follows a client-server architecture pattern:
┌─────────────────────────────────────────┐
│ LSPTool Client │
│ (Python Application) │
├─────────────────────────────────────────┤
│ Language Server Protocol │
│ (JSON-RPC 2.0 over stdio) │
├─────────────────────────────────────────┤
│ Language Server Process │
│ (pyright, rust-analyzer, etc.) │
└─────────────────────────────────────────┘
Component Design
Language Server Manager
- Responsibility: Lifecycle management of LSP servers
- Process isolation: Each server runs in separate subprocess
- Communication: JSON-RPC over stdio using asyncio
- Fallback: Automatic failover to backup servers
Document Manager
- Responsibility: Track open documents and synchronize changes
- Change buffering: Debounce rapid edits (default 100ms)
- Version tracking: Maintain document versions for consistency
- URI handling: Normalize file:// URIs across platforms
Request Router
- Responsibility: Route LSP requests to appropriate servers
- Language detection: File extension and project file analysis
- Capability checking: Verify server supports requested feature
- Timeout management: Enforce request and connection timeouts
Data Flow
Completion Request Flow
- User types trigger character
- DocumentManager captures position
- RequestRouter identifies language and server
- LSPManager sends textDocument/completion request
- Server processes and returns completion items
- Client filters and ranks results
- UI displays completion suggestions
Diagnostics Flow
- Document change triggers didChange notification
- Server analyzes code and publishes diagnostics
- Client receives publishDiagnostics notification
- Diagnostics stored and UI markers updated
- Related information displayed on request
Protocol Implementation
JSON-RPC Message Structure
{
"jsonrpc": "2.0",
"id": 1,
"method": "textDocument/completion",
"params": {
"textDocument": {
"uri": "file:///project/file.py"
},
"position": {
"line": 10,
"character": 5
}
}
}
Message Queue Design
- Asyncio Queue for request/response correlation
- Sequential processing to maintain LSP contract
- Timeout queue for request cancellation
- Priority queue for urgent operations (hover, completion)
State Management
Session State
- Open documents with version tracking
- Server capabilities per language
- Pending requests with timeout handles
- Configuration overrides per workspace
Server State
- Process handle and communication pipes
- Initialization status and capabilities
- Last activity timestamp
- Resource usage metrics
API Contracts
Tool Class Definition
class LSPTool(BaseTool):
"""Language Server Protocol integration for code intelligence."""
name = "LSPTool"
description = "LSP for completion, diagnostics, hover, navigation, and refactoring"
async def initialize(
self,
config: LSPConfig
) -> bool:
"""Initialize LSP tool with configuration."""
async def open_document(
self,
uri: str,
language_id: str,
content: str,
version: int = 1
) -> bool:
"""Open a document and start tracking it."""
async def change_document(
self,
uri: str,
changes: list[TextDocumentContentChangeEvent],
version: int
) -> bool:
"""Apply changes to an open document."""
async def close_document(
self,
uri: str
) -> bool:
"""Close and cleanup a document."""
async def complete(
self,
uri: str,
position: Position,
context: CompletionContext = None
) -> LSPCompletion:
"""Get code completions at position."""
async def hover(
self,
uri: str,
position: Position
) -> LSPHover | None:
"""Get hover information at position."""
async def diagnostics(
self,
uri: str
) -> LSPDiagnostics:
"""Get diagnostics for document."""
async def goto_definition(
self,
uri: str,
position: Position
) -> LSPLocation | None:
"""Go to definition at position."""
async def goto_type_definition(
self,
uri: str,
position: Position
) -> LSPLocation | None:
"""Go to type definition at position."""
async def find_references(
self,
uri: str,
position: Position
) -> list[LSPLocation]:
"""Find all references to symbol at position."""
async def document_symbols(
self,
uri: str
) -> list[DocumentSymbol]:
"""Get all symbols in document."""
async def code_actions(
self,
uri: str,
range: Range,
context: CodeActionContext = None
) -> list[CodeAction]:
"""Get available code actions for range."""
async def apply_code_action(
self,
action: CodeAction
) -> list[LSPDocumentEdit]:
"""Apply a code action and return edits."""
async def format_document(
self,
uri: str,
options: FormattingOptions = None
) -> list[TextEdit]:
"""Format entire document."""
async def format_range(
self,
uri: str,
range: Range,
options: FormattingOptions = None
) -> list[TextEdit]:
"""Format specific range in document."""
async def rename(
self,
uri: str,
position: Position,
new_name: str
) -> list[LSPDocumentEdit]:
"""Rename symbol at position to new name."""
async def signature_help(
self,
uri: str,
position: Position
) -> SignatureHelp | None:
"""Get function signature at position."""
async def get_server_capabilities(
self
) -> ServerCapabilities:
"""Get capabilities of active language server."""
async def shutdown(self) -> bool:
"""Shutdown all language servers."""
async def restart_server(
self,
language: str = None
) -> bool:
"""Restart language server(s)."""
Supporting Types
@dataclass
class LSPConfig:
servers: dict[str, ServerConfig]
auto_start: bool = True
connection_timeout: int = 30
request_timeout: int = 30
max_retries: int = 3
fallback_servers: dict[str, list[str]] = None
@dataclass
class ServerConfig:
command: str
args: list[str] = None
env: dict[str, str] = None
root_patterns: list[str] = None
initialization_options: dict = None
@dataclass
class Position:
line: int
character: int
@dataclass
class Range:
start: Position
end: Position
@dataclass
class CompletionContext:
trigger_kind: int
trigger_character: str = None
Examples
Example 1: Get Completions for Python
# Open document
await tool.open_document(
uri="file:///project/src/main.py",
language_id="python",
content="def hello():\n print('Hello, ')\n\nhello()",
version=1
)
# Get completions at "print('Hello, " position
result = await tool.complete(
uri="file:///project/src/main.py",
position=Position(line=1, character=13)
)
Example 2: Get Diagnostics
# Get diagnostics for file
diagnostics = await tool.diagnostics(
uri="file:///project/src/main.py"
)
Example 3: Go to Definition
# Go to definition of 'hello' function call
location = await tool.goto_definition(
uri="file:///project/src/main.py",
position=Position(line=3, character=0)
)
Example 4: Find References
# Find all references to 'hello' function
references = await tool.find_references(
uri="file:///project/src/main.py",
position=Position(line=0, character=4)
)
Dependencies
lsp:
auto_start: true
connection_timeout: 30
request_timeout: 30
max_retries: 3
servers:
python:
command: "pyright"
args: ["--stdio"]
root_patterns:
- "pyproject.toml"
- "setup.py"
- "requirements.txt"
- "ruff.toml"
initialization_options:
python:
analysis:
autoSearchPaths: true
typeCheckingMode: "basic"
typescript:
command: "typescript-language-server"
args: ["--stdio"]
root_patterns:
- "tsconfig.json"
- "package.json"
rust:
command: "rust-analyzer"
root_patterns:
- "Cargo.toml"
go:
command: "gopls"
root_patterns:
- "go.mod"
c cpp:
command: "clangd"
args: ["--background-index"]
root_patterns:
- "compile_commands.json"
- "CMakeLists.txt"
fallback_servers:
python:
- "ruff"
- "jedi"
security:
allow_insecure_servers: false
verify_checksums: true
allowed_servers:
- "pyright"
- "rust-analyzer"
- "gopls"
- "clangd"
- "typescript-language-server"
Security Requirements
FR-SEC-001: Server Verification
- System SHALL verify language server executables exist before execution
- System SHALL validate server paths against allowlist
- System SHALL log all server spawn events
FR-SEC-002: Connection Security
- System SHALL implement connection timeout (default: 30 seconds)
- System SHALL implement request timeout (default: 30 seconds)
- System SHALL support TLS for server communication when available
FR-SEC-003: Fallback Server Strategy
- System SHALL define fallback servers for each language
- System SHALL automatically attempt fallback servers on primary failure
- System SHALL log all fallback attempts and outcomes
- User SHALL be notified when all servers fail
FR-SEC-004: Process Isolation
- System SHALL run each language server in isolated process
- System SHALL not share process handles between servers
- System SHALL properly terminate server processes on cleanup
FR-SEC-005: Input Validation
- System SHALL validate all LSP requests before sending
- System SHALL sanitize document URIs
- System SHALL reject requests with invalid positions
Testing Requirements
Unit Tests (30+)
- Test language detection by file extension
- Test language detection by project file
- Test server configuration parsing
- Test position/range conversion
- Test URI parsing and normalization
- Test completion item filtering
- Test diagnostic severity mapping
- Test error handling and fallback
- Test timeout handling
- Test server lifecycle (start/stop/restart)
Integration Tests
- Test with pyright for Python files
- Test with typescript-language-server for TypeScript
- Test with rust-analyzer for Rust
- Test document synchronization (open/change/close)
- Test completion with real code
- Test hover with real code
- Test diagnostics with real errors
- Test navigation (definition, references)
- Test code actions application
Error Condition Tests
- Test handling of missing server
- Test handling of server timeout
- Test handling of server crash
- Test handling of invalid document
- Test handling of unsupported language
- Test fallback server selection
Integration Points
Editor Integration
- LSPTool integrates with text editors via LSP protocol
- Editors send document changes and receive diagnostics
- Communication via JSON-RPC 2.0 over stdio
Build System Integration
- Language servers analyzed project structure
- Integration with build tools for compilation errors
- Support for compiler-specific diagnostics
Version Control Integration
- Diagnostics mapped to git blame for history
- Code actions can create commits for refactorings
- Integration with pre-commit hooks for linting
IDE Features Integration
- Provides completions, hover, navigation, diagnostics
- Supports code actions and refactoring operations
- Integrates with debugging via stack trace navigation
Governance
PAM++ Policies
% LSPTool governance
may_use_tool(Agent, lsp_tool) :-
has_permission(Agent, tool_access),
not rate_limited(Agent, lsp_requests).
rate_limited(Agent, Requests) :-
role(Agent, junior),
Requests > 100,
within_window(Agent, lsp_requests, 60).
may_use_lsp_feature(Agent, diagnostics) :-
role(Agent, senior).
may_use_lsp_feature(Agent, diagnostics) :-
role(Agent, junior),
not excessive_diagnostics(Agent).
excessive_diagnostics(Agent) :-
count_requests(Agent, diagnostics, Count),
Count > 1000,
within_window(Agent, diagnostics, 300).
Success Criteria
Functional Success Criteria
- LSPTool successfully connects to pyright, rust-analyzer, gopls, clangd, typescript-language-server
- Completion requests return results within 500ms for files under 10,000 lines
- Diagnostics display within 1 second of document change
- Go to definition navigates to correct file and position
- Find references returns all locations of symbol usage
Non-Functional Success Criteria
- Server startup completes within 10 seconds
- Memory usage stays under 500MB per server instance
- Support for 100+ concurrent documents without degradation
- 99.9% server availability during normal operation
Integration Success Criteria
- All supported language servers installable via package managers
- Configuration hot-reloadable without restart
- Fallback servers activate on primary server failure
- Error messages provide actionable remediation steps
17. Open Items
| # | Item | Status |
|---|---|---|
| 1 | Language server auto-detection | Complete |
| 2 | Completion support | Complete |
| 3 | Hover support | Complete |
| 4 | Diagnostics support | Complete |
| 5 | Go to definition | Complete |
| 6 | Find references | Complete |
| 7 | Code actions | Complete |
| 8 | Document formatting | Complete |
| 9 | Rename support | Complete |
| 10 | Server fallback | Complete |
| 11 | Connection timeout | Complete |
| 12 | Multi-language workspace | Future |
Testing Requirements
Unit Tests
class TestLSPTool:
async def test_completion(self):
tool = LSPTool()
completions = await tool.completion("src/file.py", Position(10, 5))
assert len(completions.items) > 0
async def test_diagnostics(self):
tool = LSPTool()
diagnostics = await tool.diagnostics("src/file.py")
assert diagnostics.uri == "src/file.py"
Integration Tests
- LSP server connectivity
- Multi-language support
- Fallback mechanisms
Test Coverage
- Unit: >80%
- Integration: 100%
Observability
Logging Requirements
- Component Logging
- Log all major operations with appropriate log levels
- Include correlation IDs for request tracing
- Log performance metrics for critical operations
- Log errors with full context for debugging
Metrics Requirements
- Performance Metrics
- Operation duration histograms
- Request/error rate counters
- Resource utilization gauges
- Business metrics relevant to domain
Tracing Requirements
- Distributed Tracing
- Trace propagation across component boundaries
- Span attributes for domain-specific context
- Trace sampling based on operational needs
Alerting Requirements
- Critical Alerts
- Error rate spikes
- Performance degradation
- Resource exhaustion
- Business metric anomalies
Dashboard Requirements
- Operational Dashboard
- Real-time system health
- Performance trends
- Error analysis
- Resource monitoring
Revision History
| Date | Changes |
|---|---|
| 2026-04-08 | Initial specification v1.0.0 |
| 2026-04-09 | Fixed metadata, added Non-Functional Requirements, Technical Design, Integration Points, Success Criteria sections; renumbered all sections; fixed error condition IDs to ERR-001 to ERR-013 format |
End of SPEC-065