Skip to content

5.19 LSP 服务器

💡 一句话总结:配置语言服务器,为你的项目提供智能代码提示、跳转和诊断。


学完你能做什么

  • 为不同语言配置 LSP 服务器
  • 获得智能代码补全和导航功能
  • 让 AI 理解项目的代码结构
  • 解决 LSP 相关的常见问题

你现在的困境

  • 代码补全不智能
  • 跳转不到定义
  • AI 无法理解代码的依赖关系
  • 不知道 LSP 是什么,如何配置

什么时候用这一招

  • 当你需要:让 AI 深度理解项目代码
  • 而且不想:手动查找代码定义和引用

🎒 开始前的准备

确保你已经完成以下事项:


核心思路

什么是 LSP

LSP (Language Server Protocol) 是一种标准协议,让编辑器和语言服务器之间通信。

编辑器 (VS Code) <--> LSP 协议 <--> 语言服务器
       (显示)                          (分析)

功能

  • ✅ 代码补全
  • ✅ 跳转到定义
  • ✅ 查找引用
  • ✅ 语法检查
  • ✅ 重构支持

OpenCode 与 LSP

OpenCode 通过以下方式使用 LSP:

LSP 功能OpenCode 工具用途
Symbolslsp_symbols获取代码结构
Definitionlsp_goto_definition跳转到定义
Referenceslsp_find_references查找引用
Diagnosticslsp_diagnostics获取错误和警告
Renamelsp_rename符号重命名

支持的 LSP 服务器

JavaScript / TypeScript

TypeScript Language Server (内置)

特点

  • VS Code 内置
  • 无需额外安装
  • 完整支持 TypeScript 和 JavaScript

配置示例

json
// .vscode/settings.json
{
  "typescript.tsdk": "node_modules/typescript/lib",
  "typescript.enablePromptUseWorkspaceTsdk": true
}

Volar (Vue)

特点

  • Vue 3 专用
  • 更好的模板支持

配置

json
{
  "volar.completion.autoImportComponent": true,
  "volar.codeLens.pugTools": false
}

Python

Pylance (推荐)

特点

  • 微软官方
  • 基于 Pyright
  • 性能优秀

安装

bash
pip install pyright

配置

json
// .vscode/settings.json
{
  "python.defaultInterpreterPath": "/usr/bin/python3",
  "python.analysis.typeCheckingMode": "basic",
  "python.analysis.autoImportCompletions": true
}

Jedi

特点

  • 经典的 Python LSP
  • 功能全面

Pyright

特点

  • Pylance 的核心引擎
  • 类型检查严格

Go

gopls (内置)

特点

  • 官方 Go 语言服务器
  • 无需额外安装

配置

json
{
  "gopls": {
    "ui.diagnostic.staticcheck": true,
    "build.experimentalWorkspaceModule": true
  }
}

Rust

rust-analyzer (推荐)

特点

  • 社区开发
  • 功能强大
  • 响应迅速

安装

bash
rustup component add rust-analyzer

配置

json
{
  "rust-analyzer.checkOnSave.command": "clippy",
  "rust-analyzer.cargo.loadOutDirsFromCheck": true
}

Java

Eclipse JDT Language Server

特点

  • Eclipse 团队维护
  • 功能完整

配置

json
{
  "java.configuration.runtimes": [
    {
      "name": "JavaSE-11",
      "path": "/usr/lib/jvm/java-11-openjdk"
    }
  ]
}

C / C++

clangd (推荐)

特点

  • LLVM 官方
  • 基于 Clang
  • 性能优秀

安装

bash
# macOS
brew install llvm

# Linux
sudo apt install clangd

# Windows
# 使用 LLVM installer

配置

json
{
  "clangd.arguments": [
    "--background-index",
    "--clang-tidy",
    "--header-insertion=iwyu"
  ]
}

C/C++ IntelliSense (MSVC)

特点

  • 微软官方
  • Windows 平台

C#

C# Dev Kit (OmniSharp)

特点

  • 微软官方
  • .NET 生态

配置

json
{
  "omnisharp.enableRoslynAnalyzers": true,
  "omnisharp.enableImportCompletion": true
}

PHP

Intelephense (推荐)

特点

  • 功能全面
  • 商业软件

配置

json
{
  "intelephense.completion.insertUseDeclaration": true,
  "intelephense.completion.fullyQualifyGlobalConstantsAndFunctions": true
}

Ruby

Solargraph

特点

  • 社区开发
  • 功能完善

安装

bash
gem install solargraph

配置

json
{
  "solargraph.diagnostics": true,
  "solargraph.completion": true
}

其他语言

语言推荐服务器安装方式
Lualua-language-servernpm install -g lua-language-server
DartDart Analysis ServerDart SDK 自带
KotlinKotlin Language ServerIntelliJ IDEA
SwiftSourceKit-LSPXcode
Haskellhaskell-language-serverghcup install hls
ScalaMetalsCoursier

配置 LSP

通用配置格式

AGENTS.md 或项目配置中:

yaml
lsp_servers:
  typescript:
    command: typescript-language-server
    args: ["--stdio"]
    filetypes: [typescript, javascript]
    root_patterns: ["tsconfig.json", "package.json"]

  python:
    command: pylance
    args: ["--stdio"]
    filetypes: [python]
    root_patterns: [".git", "setup.py", "pyproject.toml"]

配置参数说明

参数说明必填
commandLSP 服务器可执行文件
args启动参数
filetypes支持的文件类型
root_patterns项目根目录标识
init_options初始化选项
settings服务器配置

跟我做

实战 1:为 TypeScript 项目配置 LSP

目标:配置完整的 TypeScript LSP 环境

  1. 安装 TypeScript:
bash
npm install --save-dev typescript
  1. 创建 tsconfig.json
json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "lib": ["ES2020"],
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}
  1. 创建 .vscode/settings.json
json
{
  "typescript.tsdk": "node_modules/typescript/lib",
  "typescript.enablePromptUseWorkspaceTsdk": true,
  "editor.formatOnSave": true
}
  1. 在 OpenCode 中测试 LSP:
使用 lsp_symbols 工具查看 src 目录的结构

你应该看到:完整的符号列表,包括类、函数、接口等


实战 2:为 Python 项目配置 Pylance

目标:配置 Python LSP,获得类型提示和补全

  1. 创建虚拟环境:
bash
python3 -m venv venv
source venv/bin/activate
  1. 安装依赖:
bash
pip install pyright
  1. 创建 .vscode/settings.json
json
{
  "python.defaultInterpreterPath": "${workspaceFolder}/venv/bin/python",
  "python.analysis.typeCheckingMode": "basic",
  "python.analysis.autoImportCompletions": true,
  "python.analysis.autoSearchPaths": true
}
  1. 创建 pyproject.toml
toml
[tool.pyright]
include = ["src"]
exclude = ["**/node_modules", "**/__pycache__"]
stubPath = "stubs"

[tool.pyright.analysis]
typeCheckingMode = "basic"
  1. 在 OpenCode 中测试:
使用 lsp_goto_definition 跳转到某个函数的定义

你应该看到:准确跳转到函数定义位置


实战 3:为多语言项目配置多个 LSP

目标:在包含多种语言的项目中配置多个 LSP 服务器

  1. 项目结构:
project/
├── frontend/  # TypeScript
├── backend/   # Python
└── shared/    # JSON
  1. 创建 .vscode/settings.json
json
{
  "[typescript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode",
    "typescript.tsdk": "frontend/node_modules/typescript/lib"
  },
  "[python]": {
    "editor.defaultFormatter": "ms-python.black-formatter",
    "python.defaultInterpreterPath": "backend/venv/bin/python"
  }
}
  1. 测试每个语言的 LSP:
使用 lsp_symbols 分别查看 frontend 和 backend 目录的代码结构

你应该看到:每个目录都有各自的符号列表


📋 LSP 功能对照表

功能与工具对应

LSP 功能OpenCode 工具参数说明
文档符号lsp_symbols(scope="document")获取当前文件的符号
工作区符号lsp_symbols(scope="workspace", query="XXX")全项目搜索符号
跳转定义lsp_goto_definition(filePath, line, char)跳转到符号定义
查找引用lsp_find_references(filePath, line, char)查找所有引用
获取诊断lsp_diagnostics(filePath, severity)获取错误/警告
重命名符号lsp_rename(filePath, line, char, newName)重命名并更新引用

使用场景

任务推荐工具示例
查看文件结构lsp_symbols(scope="document")列出所有类和函数
搜索特定函数lsp_symbols(scope="workspace", query="useState")找到所有 useState
理解代码逻辑lsp_goto_definition追踪函数调用链
重构代码lsp_find_references + lsp_rename安全重命名
检查代码质量lsp_diagnostics获取所有诊断信息

检查点 ✅

全部通过才能继续

  • [ ] 为项目的主要语言配置了 LSP
  • [ ] LSP 工具能正常工作
  • [ ] AI 能利用 LSP 理解代码结构
  • [ ] 理解了 LSP 与 OpenCode 工具的对应关系

踩坑提醒

现象原因解决
LSP 无法启动路径不对或未安装检查 command 路径,安装 LSP 服务器
符号列表为空语言服务器未识别项目确保项目有正确的配置文件
跳转失败项目未正确初始化运行项目初始化命令(如 npm install)
性能慢项目太大排除 node_modules 等目录
类型检查不准确配置错误检查 tsconfig.json、pyrightconfig.json 等配置

高级技巧

1. 项目根目录识别

LSP 会根据以下模式识别项目根目录:

yaml
root_patterns:
  - "package.json"
  - "tsconfig.json"
  - "pyproject.toml"
  - "go.mod"
  - "Cargo.toml"
  - ".git"

2. 工作区多项目配置

对于 monorepo 项目:

json
// .vscode/settings.json
{
  "typescript.tsdk": "node_modules/typescript/lib",
  "typescript.tsserver.experimental.enableProjectDiagnostics": true,
  "typescript.workspaceSymbols.scope": "currentProject"
}

3. 排除目录

提高性能,排除不必要的目录:

json
{
  "files.exclude": {
    "**/node_modules": true,
    "**/dist": true,
    "**/build": true,
    "**/.git": true
  },
  "search.exclude": {
    "**/node_modules": true,
    "**/dist": true
  }
}

4. 性能优化

json
{
  "typescript.tsserver.maxTsServerMemory": 8192,
  "typescript.tsserver.watchOptions": {
    "watchDirectory": "useFsEvents",
    "watchFile": "useFsEvents"
  }
}

最佳实践

1. 提交 LSP 配置到版本控制

bash
git add .vscode/settings.json tsconfig.json pyproject.toml
git commit -m "chore: add LSP configuration"

2. 使用统一配置

团队使用 .editorconfig 统一基础设置,配合 LSP 实现深度智能。

3. 定期更新 LSP 服务器

bash
# TypeScript
npm update typescript

# Python
pip install --upgrade pyright

# Rust
rustup update

4. 监控 LSP 日志

遇到问题时开启日志:

json
{
  "typescript.tsserver.trace": "verbose",
  "python.analysis.diagnosticLogging": true
}

本课小结

你学会了:

  1. LSP 的作用和重要性
  2. 不同语言的 LSP 服务器配置
  3. OpenCode 如何使用 LSP 工具
  4. 多语言项目的 LSP 配置
  5. LSP 性能优化技巧

下一课预告

下一课我们将学习上下文压缩配置,了解如何优化 token 使用,提高 AI 响应效率。


📚 更多完整模板Prompt 模板库