LSP(Language Server Protocol)和引用系统(References)是 OpenCode "看懂"你的代码的基础设施。前者让 AI 获得编译器级别的语法和语义分析能力,后者让它能跨项目、跨文件引用代码上下文。
Language Server Protocol 是微软提出的开放协议,标准化了编辑器和语言服务之间的通信。OpenCode 通过 LSP 客户端接入各语言的 Language Server,从而获得:
// opencode.json
{
"lsp": {
"enabled": true,
"servers": {
"typescript": {
"command": "typescript-language-server",
"args": ["--stdio"]
},
"python": {
"command": "pyright-langserver",
"args": ["--stdio"]
},
"rust": {
"command": "rust-analyzer"
},
"go": {
"command": "gopls"
}
}
}
}
| 语言 | LSP Server | 安装命令 |
|------|-----------|---------|
| TypeScript/JS | typescript-language-server | npm i -g typescript-language-server typescript |
| Python | pyright | pip install pyright |
| Rust | rust-analyzer | rustup component add rust-analyzer |
| Go | gopls | go install golang.org/x/tools/gopls@latest |
| C/C++ | clangd | 通常系统自带 |
| Java | jdtls | 通过 Eclipse JDT LS |
配置 LSP 后,OpenCode 能理解:
> 查找所有调用 validateEmail 的位置 → Codex 通过 LSP 精确定位所有引用 > 重构:将 User 接口的 id 从 number 改为 string → Codex 找到所有使用 id 的地方,通过 LSP 确保类型安全 > 这段代码有什么编译错误? → LSP 实时诊断,Codex 解释并修复
{
"lsp": {
"servers": {
"typescript": {
"command": "typescript-language-server",
"args": ["--stdio"],
"root_patterns": ["tsconfig.json", "package.json"],
"file_types": [".ts", ".tsx", ".js", ".jsx"]
}
}
}
}
LSP 不工作的常见原因:
Language Server 未安装——检查 which typescript-language-server
项目缺少配置文件(tsconfig.json, pyproject.toml 等)
路径问题——用绝对路径指定 command
References 让 OpenCode 能引用当前项目之外的文件。比如:
// opencode.json
{
"references": {
"shared-types": "../shared-types/src/types/",
"api-docs": "../docs/api/",
"design-tokens": "../design-system/tokens/"
}
}
配置后,在对话中通过引用符号访问:
> @shared-types 查看 User 接口的完整定义,然后更新当前项目的类型 > @api-docs 对照 API 文档,检查当前路由定义是否完整 > @design-tokens 把当前组件的颜色值改为项目设计系统的 token
{
"references": {
"utils": {
"path": "../shared-utils/src/",
"description": "团队共享工具函数库",
"patterns": ["*.ts"],
"exclude": ["*.test.ts", "__tests__"]
}
}
}
引用 npm 工作区的共享包:monorepo 标准姿势
引用文档目录:让 AI 对照文档写代码
引用设计系统的 token 文件:保持 UI 一致性
不要引用 node_modules:浪费 token,毫无意义
LSP 让 OpenCode 像 IDE 一样理解代码(而非只看文本),References 让它突破单项目边界。两者结合,OpenCode 对代码的理解从"阅读文本"升级为"理解语义"。