convez.ai
MCP ServerDesenvolvimento WebAvançado
beruang

LSP MCP — Servidor de Inteligência de Código

beruang/lsp-mcp

Inteligência de código via LSP para agentes Claude e outros clientes MCP

Ver no GitHub
InicialPluginScore · de 0 a 100

Servidor MCP que expõe Language Server Protocol como ferramentas seguras de inteligência de código para agentes de IA. Suporta TypeScript, JavaScript, Python, Go e Rust com 59 ferramentas para navegação, diagnósticos, refatoração e análise profunda de código.

Instalação

$npx convez-ai beruang/lsp-mcp

1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.

Métricas

Estrelas
1
Forks
0
Acompanhando
0
Saúde
28%
Último commit
há 5 meses
Versão
—
Issues abertas
0
Contribuidores
3

Casos de uso

  • Análise semântica e navegação de código em múltiplas linguagens
  • Diagnósticos de erro e sugestões de refatoração em tempo real
  • Busca de referências, definições e símbolos em workspace inteiro
  • Suporte para agentes de IA entenderem e modificarem código com segurança

Veredito

LSP MCP é uma solução madura e robusta para conectar inteligência de código de múltiplas linguagens a agentes Claude. Ideal para builds que precisam de análise semântica profunda, mas requer setup manual de language servers e conhecimento técnico sólido.

README

A tradução para o português deste README ainda está na fila.

MCP LSP — Code Intelligence Server

Node.js TypeScript MCP License

A Model Context Protocol (MCP) stdio server that wraps language servers to expose a safe, read-oriented code-intelligence tool surface for coding agents. Supports TypeScript, JavaScript, Python, Go, and Rust — 59 tools across navigation, diagnostics, refactoring, deep understanding, hierarchy, lifecycle, and operations.


Table of Contents


Quick Start

# Prerequisites: install language servers
npm install -g typescript-language-server pyright
# Go and Rust: install gopls and rust-analyzer via your package manager

# Clone and install
git clone https://github.com/beruang/lsp-mcp.git
cd lsp-mcp
pnpm install

# Build
pnpm run build

# Point at a workspace and start
WORKSPACE_PATH=/path/to/your/project node dist/index.js

Connect any MCP client to the server's stdio transport.


Prerequisites

DependencyVersionPurpose
Node.js>= 20Runtime
pnpm—Package management
typescript-language-server—TypeScript/JavaScript LSP backend
pyright-langserver—Python LSP backend
gopls—Go LSP backend
rust-analyzer—Rust LSP backend

Language servers must be on $PATH. The server checks availability via lsp_list_supported_languages.


Installation

pnpm install

Dependencies: @modelcontextprotocol/sdk, vscode-jsonrpc, vscode-languageserver-types, zod, diff.


Configuration

Environment Variables

VariableRequiredDefaultDescription
WORKSPACE_PATHNoprocess.cwd()Absolute path to the workspace root

Runtime Config (V4)

VariableDefaultDescription
LSP_MAX_REFERENCES200Max references returned
LSP_MAX_WORKSPACE_SYMBOLS100Max workspace symbols
LSP_MAX_DIAGNOSTICS500Max diagnostics
LSP_MAX_COMPLETION_ITEMS50Max completion items
LSP_MAX_CHANGED_FILES100Max files in rename preview
LSP_MAX_EDITS1000Max edits in workspace edit
LSP_MAX_CONTEXT_CHARACTERS20000Max context characters
LSP_TIMEOUT_HOVER_MS3000Hover timeout
LSP_TIMEOUT_DEFINITION_MS5000Definition timeout
LSP_TIMEOUT_REFERENCES_MS10000References timeout
LSP_REQUEST_LOG_MAX_ENTRIES500Request log ring buffer size
LSP_RAW_REQUEST_ENABLEDfalseEnable debug raw request tool
LSP_VERBOSE_LOGGINGfalseVerbose logging

Use lsp_get_config to inspect effective configuration and lsp_update_runtime_config to adjust limits, timeouts, cache TTLs, and debug flags at runtime (in-memory only).


Architecture

src/
├── index.ts                          # Entry point — MCP server bootstrap
├── config/
│   ├── languageServers.ts            # Language server registry
│   ├── defaults.ts                   # Default runtime config values
│   ├── envConfig.ts                  # Environment variable parsing
│   └── runtimeConfig.ts              # In-memory config merge + validation
├── lsp/
│   ├── LspClient.ts                  # LSP connection: spawn, initialize, request, shutdown
│   ├── LspClientManager.ts           # Per-language client pool + state queries
│   ├── LspState.ts                   # 8-state machine with validated transitions
│   ├── capabilities.ts               # Server capabilities extraction
│   ├── diagnosticsCache.ts           # publishDiagnostics notification cache
│   ├── documentStore.ts              # didOpen/didChange state tracking
│   └── normalize.ts                  # LSP → normalized shape converters
├── mcp/
│   ├── registerTools.ts              # All 59 MCP tool registrations
│   ├── toolErrors.ts                 # Structured error envelope
│   └── schemas.ts                    # Zod schemas
├── navigation/                       # V3: declaration, typeDef, implementation, signatureHelp, completion
├── hierarchy/                        # V3: call hierarchy + type hierarchy (prepare, incoming/outgoing, super/subtypes)
├── workspaceEdit/                    # V2: parse, validate, preview workspace edits
├── codeActions/                      # V2: code action cache + normalization
├── diagnostics/                      # V2: snapshot store, compare, wait-for-diagnostics
├── context/                          # V3: enclosing symbol, symbol context, file outline
├── analysis/                         # V3: change impact, fix candidates, explain diagnostics
├── formatting/                       # V2: format + range format preview
├── refactor/                         # V2: prepare rename, organize imports
├── composite/                        # V1: diagnostics summary, inspect symbol
├── diff/                             # V1: applyTextEdits, workspaceEditToDiff
├── semantic/                         # V3: fixDiagnosticCandidates, explainDiagnostics, analyzeChangeImpact
├── documents/                        # V4: open, close, sync, save, list documents
├── ops/                              # V4: server status, restart, shutdown, readiness, liveness, workspace status
├── observability/                    # V4: request tracker, request log
├── cache/                            # V4: cache status + selective clearing
├── debug/                            # V4: raw request (disabled by default, method denylist)
├── safety/
│   ├── paths.ts                      # Workspace containment check
│   └── limits.ts                     # Truncation caps and timeouts
└── utils/
    ├── asyncTimeout.ts               # Promise race with timeout
    ├── uri.ts                        # URI ↔ path conversion
    ├── symbols.ts                    # Symbol kind normalization
    ├── ids.ts                        # ID generation
    ├── text.ts                       # Text utilities
    └── time.ts                       # Time utilities

API Reference

Every tool returns either a success payload or a structured error:

{
  "error": {
    "code": "path_outside_workspace",
    "message": "Human-readable description",
    "details": {}
  }
}

Navigation & Discovery

ToolLSP MethodDescription
lsp_hovertextDocument/hoverType information and documentation at cursor
lsp_definitiontextDocument/definitionGo-to-definition locations
lsp_referencestextDocument/referencesFind all references to a symbol
lsp_document_symbolstextDocument/documentSymbolSymbol outline for a file
lsp_workspace_symbolsworkspace/symbolWorkspace-wide symbol search
lsp_declarationtextDocument/declarationGo-to-declaration
lsp_type_definitiontextDocument/typeDefinitionGo-to-type-definition
lsp_implementationtextDocument/implementationFind implementations

Diagnostics

ToolDescription
lsp_diagnosticsCached diagnostics for a file or workspace-wide
lsp_diagnostics_summaryGrouped diagnostics with root-cause heuristic
lsp_wait_for_diagnosticsWait for fresh diagnostics after a change
lsp_snapshot_diagnosticsSave a named diagnostic snapshot for comparison
lsp_compare_diagnosticsDiff two diagnostic snapshots
lsp_explain_diagnosticsCluster diagnostics and identify root causes
lsp_fix_diagnostic_candidatesMulti-source fix suggestions (hover + code actions + definition)

Refactoring & Editing

ToolLSP MethodDescription
lsp_rename_previewtextDocument/renamePreview rename via WorkspaceEdit + unified diff
lsp_prepare_renametextDocument/prepareRenameCheck if rename is valid at a position
lsp_code_actions_previewtextDocument/codeActionPreview code actions with diffs
lsp_resolve_code_actioncodeAction/resolveResolve a cached code action
lsp_format_previewtextDocument/formattingPreview formatting with diff
lsp_range_format_previewtextDocument/rangeFormattingPreview range formatting with diff
lsp_organize_imports_previewtextDocument/organizeImportsPreview import organization with diff
lsp_workspace_edit_preview—Preview any WorkspaceEdit + unified diff
lsp_validate_workspace_edit—Validate WorkspaceEdit safety

Deep Understanding

ToolLSP MethodDescription
lsp_signature_helptextDocument/signatureHelpFunction signature at call site
lsp_completiontextDocument/completionCode completion suggestions
lsp_inspect_symbolcompositeAggregate: hover + definition + refs + risk hints
lsp_symbol_contextcompositeSurrounding symbols at a position
lsp_enclosing_symbolcompositeInnermost enclosing symbol
lsp_file_outlinecompositeFile-level symbol outline

Hierarchy & Impact

ToolLSP MethodDescription
lsp_prepare_call_hierarchytextDocument/prepareCallHierarchyPrepare call hierarchy for a symbol
lsp_incoming_callscallHierarchy/incomingCallsWho calls this symbol
lsp_outgoing_callscallHierarchy/outgoingCallsWhat this symbol calls
lsp_prepare_type_hierarchytextDocument/prepareTypeHierarchyPrepare type hierarchy
lsp_supertypestypeHierarchy/supertypesSuper-types of a symbol
lsp_subtypestypeHierarchy/subtypesSub-types of a symbol
lsp_analyze_change_impactcompositeCross-file impact analysis for a proposed change

Server Lifecycle

ToolDescription
lsp_server_statusRuntime status for all configured language servers
lsp_restart_serverRestart a language server (reopens docs, clears diagnostics)
lsp_shutdown_serverGraceful shutdown with timeout
lsp_list_supported_languagesConfigured languages, extensions, commands, binary availability
lsp_get_capabilitiesNormalized LSP capabilities per language

Document Lifecycle

ToolLSP MethodDescription
lsp_open_documenttextDocument/didOpenRegister a document with the LSP server
lsp_close_documenttextDocument/didCloseUnregister a document
lsp_sync_documenttextDocument/didChangeNotify LSP of content changes
lsp_save_documenttextDocument/didSaveNotify LSP of a save
lsp_list_open_documents—All currently tracked open documents

Health

ToolDescription
lsp_health_checkServer health and per-language LSP capabilities
lsp_readinessWorkspace + language server availability check
lsp_livenessFast liveness check + optional memory stats

Observability & Cache

ToolDescription
lsp_request_logLSP request history with filtering
lsp_clear_request_logClear request log entries
lsp_cache_statusEntry counts for all internal caches
lsp_clear_cachesSelective or full cache clearing

Configuration

ToolDescription
lsp_get_configEffective config (defaults → env → runtime overrides)
lsp_update_runtime_configIn-memory config updates (limits, timeouts, caches, debug)

Debug

ToolDescription
lsp_raw_requestRaw LSP request with method denylist (disabled by default)

Multi-Workspace

ToolDescription
lsp_list_workspacesKnown workspaces (foundation)
lsp_workspace_statusStatus for a specific workspace (foundation)

Error Handling

Every tool returns errors in a uniform envelope:

{
  "error": {
    "code": "path_outside_workspace",
    "message": "Path is outside workspace: /etc/passwd",
    "details": {}
  }
}

Error Codes

CodeTrigger
path_outside_workspacefilePath does not resolve inside WORKSPACE_PATH
unsupported_languageFile extension has no registered LSP server
file_not_foundFile does not exist on disk
lsp_server_unavailableLanguage server binary not on $PATH
lsp_server_not_initializedServer not initialized
lsp_request_failedLSP request returned an error
lsp_request_timeoutLSP request exceeded its deadline
lsp_capability_unsupportedServer does not support the capability
declaration_not_supportedServer lacks declaration provider
type_definition_not_supportedServer lacks type definition provider
implementation_not_supportedServer lacks implementation provider
signature_help_not_supportedServer lacks signature help provider
completion_not_supportedServer lacks completion provider
call_hierarchy_not_supportedServer lacks call hierarchy provider
call_hierarchy_item_not_foundHierarchy item ID not found
call_hierarchy_item_expiredHierarchy item TTL expired
type_hierarchy_not_supportedServer lacks type hierarchy provider
type_hierarchy_item_not_foundType hierarchy item ID not found
type_hierarchy_item_expiredType hierarchy item TTL expired
change_impact_analysis_incompleteChange impact partial results
diagnostic_not_foundDiagnostic index not found
invalid_config_keyUnknown config key in update
invalid_config_valueInvalid config value (e.g., negative limit)
immutable_config_keyAttempt to change workspacePath at runtime
server_not_foundLanguage not configured
restart_rate_limitedToo many restarts in window
raw_request_disabledDebug tool is disabled
method_deniedLSP method blocked by denylist
document_not_foundDocument not in open documents store

Safety Model

The server is designed for read-oriented coding agents:

GuardMechanism
Workspace containmentEvery file path validated against WORKSPACE_PATH
No file writesAll tools are read-only; lsp_rename_preview returns a diff but never applies edits
Result capsAll list results are truncated with configurable limits
TimeoutsEvery LSP request has a per-method deadline
Structured errorsAll errors use the uniform { error: { code, message, details } } envelope
Request log privacyLogs method, duration, status — never full file contents (unless verbose logging explicitly enabled)
Method denylistlsp_raw_request blocks workspace/applyEdit, workspace/executeCommand, and other dangerous methods
Restart rate limitingMax 3 restarts per 60s per language
State machine validationInvalid LSP state transitions are logged and rejected

Development

pnpm run typecheck     # TypeScript type-check
pnpm run lint          # ESLint (zero warnings)
pnpm run lint:fix      # ESLint auto-fix
pnpm run dev           # Run with tsx (no build)
pnpm run build         # Build to dist/
pnpm run start         # Start built artifact

Pre-commit Hook

husky + lint-staged:

  1. eslint --fix --max-warnings 0
  2. pnpm run typecheck
  3. pnpm run verify:decoupling

Conventions

  • Module system: ESM ("type": "module", NodeNext)
  • TypeScript: strict, target ES2022
  • Testing: node --test + tsx
  • Linting: ESLint with @typescript-eslint, zero-warnings policy

Testing

pnpm test              # All unit tests
npm run test:safety    # Safety tests
npm run test:integration  # Integration tests (requires language servers)

Coverage

  • 106+ tests across unit, integration, and safety suites
  • 5 languages: TypeScript, JavaScript, Python, Go, Rust
  • V1-V3 regression: all passing with every V4 change

Supported Languages

LanguageExtensionsLanguage ServerLanguage ID
TypeScript.ts, .tsxtypescript-language-server --stdiotypescript
JavaScript.js, .jsxtypescript-language-server --stdiotypescript
Python.pypyright-langserver --stdiopython
Go.gogoplsgo
Rust.rsrust-analyzerrust

Adding a language:

  1. Entry in src/config/languageServers.ts
  2. Binary on $PATH
  3. Optional waitConfig in src/lsp/diagnosticsCache.ts

Troubleshooting

lsp_server_unavailable

which typescript-language-server pyright-langserver gopls rust-analyzer
npm install -g typescript-language-server pyright

Use lsp_list_supported_languages to check binary availability at runtime.

path_outside_workspace

Set WORKSPACE_PATH to the project root. Symlinks are resolved before containment check.

No diagnostics

Diagnostics are cached from publishDiagnostics notifications. For cold cache, use lsp_diagnostics with workspaceWide: true to trigger a warm-up pass, or lsp_wait_for_diagnostics.

Stale diagnostics after external edit

Use lsp_sync_document to notify the LSP of changes, then lsp_wait_for_diagnostics. For bulk recovery, lsp_restart_server with reopenDocuments: true.


Changelog

VersionFocusKey Additions
V4Production operationsServer lifecycle, document lifecycle, observability, cache, config, health, debug, multi-workspace (21 tools)
V3Deep understandingHierarchy (call + type), declaration, type definition, implementation, signature help, completion, impact analysis (17 tools)
V2Safe refactoringPreview-first editing — rename, code actions, formatting, organize imports, diagnostics snapshots (11 tools)
V1Semantic navigationHover, definition, references, symbols, diagnostics, rename preview, inspect (10 tools)

License

MIT

Ver o original no GitHub

Bom para

Relacionados