内容
# VS Code MCP 服务器
[](https://github.com/nabheet/vscode-mcp-server/actions/workflows/ci.yml)
[](LICENSE)
让 AI 代理在 VS Code 中读取、写入、调试和执行命令,就像人类开发者一样。该 [MCP(模型上下文协议)](https://modelcontextprotocol.io) 服务器通过 SSE 暴露了 40 多种 VS Code 工具(调试器、终端、LSP、文件操作、命令),兼容 opencode、Claude、Cursor 和任何 MCP 客户端。
## 快速开始
1. **安装扩展**,从 [VS Code 市场](https://marketplace.visualstudio.com/items?itemName=nabheet.vscode-ide-mcp) 或从 [最新版本](https://github.com/nabheet/vscode-mcp-server/releases) 安装 `.vsix` 文件。
2. **重新加载 VS Code** — 扩展程序在启动时自动启动,监听 `http://127.0.0.1:9876`。
3. **配置您的 AI 工具**(例如 opencode)以通过 SSE 连接:
```json
{
"vscode-mcp": {
"type": "remote",
"url": "http://127.0.0.1:9876/mcp"
}
}
```
4. **验证** 服务器正在运行:
```bash
curl -s -X POST http://127.0.0.1:9876/mcp \
-H 'Content-Type: application/json' \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
```
## 架构
```
VS Code 扩展(onStartupFinished)
└─ src/extension.ts — 生命周期:激活、工具注册、停用
└─ src/config.ts — 设置(端口、身份验证、TLS)来自 VS Code + 环境变量
└─ src/mcp/
├─ server.ts — HTTP 服务器:CORS、身份验证、TLS、SSE 传输、JSON-RPC 调度
├─ transport.ts — JSON-RPC 2.0 处理程序 + MCP 协议生命周期(初始化、tools/list、tools/call)
└─ tools/
├─ commands.ts — 执行任何 VS Code 命令,列出命令,获取代码操作
├─ navigation.ts — 打开文件,行/列跳转,选择行,资源管理器显示,关闭编辑器
├─ workspace.ts — 读取/写入/创建/删除文件,glob 搜索,工作区文件夹
├─ debug.ts — 启动/停止调试,断点(添加/删除/列出),步进/继续,
│ 调用堆栈,变量,帧范围评估
├─ terminal.ts — 在集成终端中执行命令,捕获输出(30 秒超时)
└─ lsp.ts — 诊断(200 行上限),悬停,引用,定义,符号,
补全,代码操作,调用层次,重命名
└─ src/utils/
├─ types.ts — MCP 方法常量,类型定义
└─ path.ts — 工作区根感知路径解析
```
## 工具
| 工具 | 模块 | 描述 |
|------|--------|-------------|
| `execute_command` | commands | 通过 ID 执行任何 VS Code 命令 |
| `list_commands` | commands | 列出所有可用的 VS Code 命令(可选内部) |
| `get_code_actions` | commands | 获取行上可用的重构/快速修复 |
| `open_file` | navigation | 在编辑器中打开文件 |
| `open_file_at_line` | navigation | 在特定行打开文件 |
| `open_file_at_position` | navigation | 在特定行和列打开文件 |
| `select_lines` | navigation | 在活动编辑器中选择行 |
| `reveal_in_explorer` | navigation | 在侧边栏显示文件 |
| `focus_editor` | navigation | 聚焦编辑器组 |
| `close_editor` | navigation | 关闭活动编辑器 |
| `close_all_editors` | navigation | 关闭所有编辑器 |
| `list_files` | workspace | 通过 glob 模式列出文件 |
| `read_file` | workspace | 读取文件内容 |
| `write_file` | workspace | 写入文件内容(创建或覆盖) |
| `create_file` | workspace | 创建新空文件 |
| `delete_file` | workspace | 删除文件或目录(递归,使用回收站) |
| `get_workspace_folders` | workspace | 列出工作区根 |
| `start_debugging` | debug | 从启动配置启动调试会话 |
| `stop_debugging` | debug | 停止活动调试会话 |
| `step_over` | debug | 跳过当前行 |
| `step_into` | debug | 进入函数 |
| `step_out` | debug | 跳出函数 |
| `continue` | debug | 继续执行 |
| `add_breakpoint` | debug | 添加断点(支持条件,命中条件) |
| `remove_breakpoint` | debug | 删除断点 |
| `list_breakpoints` | debug | 列出所有断点 |
| `get_debug_variables` | debug | 从暂停会话获取帧局部变量 |
| `get_stack_trace` | debug | 获取调用堆栈帧 |
| `evaluate_in_debug_console` | debug | **帧范围** 评估 — 可以读取局部变量,如 `pre`、`self`、`t` |
| `execute_in_terminal` | terminal | 在集成终端中执行命令(30 秒输出捕获超时) |
| `get_terminal_output` | terminal | 获取终端输出缓冲区 |
| `find_references` | lsp | 查找光标处符号的所有引用 |
| `go_to_definition` | lsp | 导航到符号定义 |
| `go_to_type_definition` | lsp | 导航到类型定义 |
| `go_to_implementation` | lsp | 导航到符号实现 |
| `get_hover` | lsp | 获取光标处悬停信息 |
| `get_diagnostics` | lsp | 获取文件诊断(上限 200 行) |
| `get_document_symbols` | lsp | 获取活动文档中的符号 |
| `get_workspace_symbols` | lsp | 搜索工作区符号 |
| `get_call_hierarchy` | lsp | 获取传入和传出调用层次 |
| `rename_symbol` | lsp | 跨工作区重命名符号 |
| `get_completions` | lsp | 获取光标处的补全项 |
## 从其他 AI 工具连接
### opencode
添加到您的 `opencode.global.jsonc` 或 `opencode.json`:
```jsonc
{
"mcpServers": {
"vscode-mcp": {
"type": "remote",
"url": "http://127.0.0.1:9876/mcp"
}
}
}
```
### Claude Desktop / Claude Code
添加到 `claude_desktop_config.json`:
```json
{
"mcpServers": {
"vscode-mcp": {
"type": "remote",
"url": "http://127.0.0.1:9876/mcp"
}
}
}
```
或通过 stdio(如果您更喜欢托管子进程):
```json
{
"mcpServers": {
"vscode-mcp": {
"command": "node",
"args": ["path/to/vscode-mcp-server/out/cli.js"]
}
}
}
```
### Cursor
在 Cursor 设置 → 功能 → MCP 服务器 → 添加新 MCP 服务器:
```
名称:vscode-mcp
类型:remote
网址:http://127.0.0.1:9876/mcp
```
### Windsurf / Continue.dev / 任何 MCP 兼容工具
添加一个 `type: "remote"` MCP 服务器,指向:
```
http://127.0.0.1:9876/mcp
```
服务器使用 **SSE 传输**(标准 MCP HTTP 传输)。如果工具仅支持 stdio,您可以使用 SSE 到 stdio 的桥接器,如 `mcp-remote`,或编写一个薄包装器。
### 以编程方式连接
```python
# 示例:使用 MCP Python SDK
from mcp import ClientSession
from mcp.client.sse import sse_client
async with sse_client("http://127.0.0.1:9876/mcp") as transport:
async with ClientSession(transport) as session:
result = await session.list_tools()
for tool in result.tools:
print(f"{tool.name}: {tool.description}")
```
```typescript
// 示例:使用 MCP TypeScript SDK
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
const transport = new SSEClientTransport(new URL("http://127.0.0.1:9876/mcp"));
const client = new Client({ name: "my-agent", version: "1.0.0" });
await client.connect(transport);
const tools = await client.listTools();
```
### 启用 TLS 和身份验证
通过 VS Code 设置或环境变量启用 TLS 和/或身份验证,然后相应地更新您的客户端 URL 和标头。
**服务器端设置:**
| 方法 | 设置 |
|--------|---------|
| VS Code 设置 | `vscode-mcp-server.tlsCertPath`、`vscode-mcp-server.tlsKeyPath`、`vscode-mcp-server.authToken` |
| 环境变量 | `MCP_TLS_CERT_PATH`、`MCP_TLS_KEY_PATH`、`MCP_AUTH_TOKEN` |
#### opencode
```jsonc
{
"mcpServers": {
"vscode-mcp": {
"type": "remote",
"url": "https://127.0.0.1:9876/mcp", // https, not http
"headers": {
"Authorization": "Bearer <your-token>"
}
}
}
}
```
#### Claude Desktop / Claude Code
```json
{
"mcpServers": {
"vscode-mcp": {
"type": "remote",
"url": "https://127.0.0.1:9876/mcp",
"headers": {
"Authorization": "Bearer <your-token>"
}
}
}
}
```
#### Cursor
在 Cursor 设置 → 功能 → MCP 服务器:
```
名称:vscode-mcp
类型:remote
网址:https://127.0.0.1:9876/mcp
标头:{ "Authorization": "Bearer <your-token>" }
```
#### 编程(Python with TLS + auth)
```python
from mcp import ClientSession
from mcp.client.sse import sse_client
async with sse_client(
"https://127.0.0.1:9876/mcp",
headers={"Authorization": "Bearer <your-token>"},
) as transport:
async with ClientSession(transport) as session:
result = await session.list_tools()
```
#### 编程(TypeScript with TLS + auth)
```typescript
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
const transport = new SSEClientTransport(
new URL("https://127.0.0.1:9876/mcp"),
{ headers: { Authorization: "Bearer <your-token>" } }
);
const client = new Client({ name: "my-agent", version: "1.0.0" });
await client.connect(transport);
```
#### curl(用于测试)
```bash
# 启用 TLS
curl -sk https://127.0.0.1:9876/mcp \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer <your-token>' \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
# 启用 TLS + 身份验证,直接 POST
curl -sk -X POST https://127.0.0.1:9876/mcp \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer <your-token>' \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
```
> ⚠️ **安全注意**:当设置了身份验证令牌但未启用 TLS 时,服务器会记录警告。明文 HTTP 上的 Bearer 令牌可能会在本地网络中被拦截。请为任何非回环访问使用 TLS。
### 示例:工具列表(37 个工具)
连接后,`tools/list` 返回所有工具的模式。关键类别:
| 类别 | 工具 |
|----------|-------|
| **编辑器** | `open_file`、`open_file_at_line`、`open_file_at_position`、`select_lines`、`reveal_in_explorer`、`focus_editor`、`close_editor`、`close_all_editors` |
| **工作区** | `read_file`、`write_file`、`create_file`、`delete_file`、`list_files`、`get_workspace_folders` |
| **调试** | `start_debugging`、`stop_debugging`、`step_over`、`step_into`、`step_out`、`continue`、`add_breakpoint`、`remove_breakpoint`、`list_breakpoints`、`get_debug_variables`、`get_stack_trace`、`evaluate_in_debug_console` |
| **终端** | `execute_in_terminal`、`get_terminal_output` |
| **LSP** | `find_references`、`go_to_definition`、`go_to_type_definition`、`go_to_implementation`、`get_hover`、`get_diagnostics`、`get_document_symbols`、`get_workspace_symbols`、`get_call_hierarchy`、`rename_symbol`、`get_completions`、`get_code_actions` |
| **命令** | `execute_command`、`list_commands` |
## MCP 协议
### 传输
支持两种传输模式:
**1. SSE(推荐)** — `GET /mcp` 打开一个 SSE 流,服务器发送一个带有会话特定 POST URL 的 `endpoint` 事件。客户端将 JSON-RPC 消息发送到 `POST /mcp/session/:id/message`,响应通过 SSE `message` 事件到达。
**2. 直接 POST(向后兼容)** — `POST /mcp` 带有 JSON-RPC 正文。同步请求/响应。
### 生命周期
实现了完整的 MCP 协议生命周期:
1. **客户端发送 `initialize`** — 服务器响应协议版本(`2024-11-05`)、功能(`tools`)和服务器信息
2. **客户端发送 `notifications/initialized`** — 确认准备就绪(无需响应)
3. **`tools/list`** — 返回所有工具定义,带有 JSON 模式
4. **`tools/call`** — 按名称调用工具,带有参数
### 端口重试
如果默认端口(9876)忙,服务器将尝试最多 5 个连续端口(每个尝试 ±1)。如果所有端口都失败,扩展程序将记录错误并停用。
## 配置
所有设置都在 `vscode-mcp-server.*` 下:
| 设置 | 默认值 | 描述 |
|---------|---------|-------------|
| `port` | `9876` | HTTP 服务器端口(如果忙则自动重试) |
| `authToken` | `""` | Bearer 令牌(空 = 无身份验证)。⚠️ 如果设置了令牌但未启用 TLS,则会记录警告(明文风险) |
| `tlsCertPath` | `""` | TLS 证书 PEM 路径(启用 HTTPS) |
| `tlsKeyPath` | `""` | TLS 密钥 PEM 路径(启用 HTTPS) |
设置会回退到环境变量:
| 环境变量 | 覆盖 | 默认值 |
|---------|-----------|---------|
| `MCP_PORT` | `port` | `9876` |
| `MCP_AUTH_TOKEN` | `authToken` | (无) |
| `MCP_TLS_CERT_PATH` | `tlsCertPath` | (无) |
| `MCP_TLS_KEY_PATH` | `tlsKeyPath` | (无) |
| `MCP_SERVER_MAX_RETRIES` | 端口重试次数 | `3` |
VS Code 设置优先于环境变量。
### 安全
- CORS 限制为回环源(`Access-Control-Allow-Origin: http://127.0.0.1:<port>`)
- Bearer 令牌身份验证使用时序安全比较
- 有效负载限制:1 MB
- 启用了 TLS 但不是必需的(默认仅限回环)
- 当设置了身份验证令牌但未启用 TLS 时记录警告
## 调试提示
### 帧范围评估
`evaluate_in_debug_console` 自动解析顶部堆栈帧的 `frameId` 并将其传递给 DAP `evaluate` 请求。这意味着可以直接读取局部变量:
```
evaluate_in_debug_console("pre") → 69.75
evaluate_in_debug_console("self") → Order(order_id='ORD-001', ...)
```
如果没有暂停的调试会话,它会回退到全局范围评估。
### 调试工作流
1. 打开目标文件:`open_file("src/main.py")`
2. 设置断点:`add_breakpoint("src/main.py", 42)`
3. 启动调试:`start_debugging("Launch Config Name")`
4. 步进:`step_over()`、`step_into()`、`step_out()`
5. 检查:`get_stack_trace()`、`get_debug_variables()`、`evaluate_in_debug_console("my_var")`
6. 继续:`continue()`
7. 停止:`stop_debugging()`
## 开发
```bash
npm install
npm run compile # 构建 TypeScript → out/
npm run watch # 监视模式
npm test # 3 个测试套件中 75 个测试(服务器、传输、工具)
```
### 调试扩展本身
1. 在 VS Code 中按 F5(使用 `.vscode/launch.json` “运行扩展”配置)
2. 打开一个新的扩展开发主机窗口
3. MCP 服务器在端口 9876 上自动启动
4. 在 `src/` 中设置断点以调试工具处理程序
5. `npm: watch` 任务在保存时自动编译
### 用于分发的打包
```bash
npx @vscode/vsce package
# 生成 vscode-mcp-server-*.vsix
```
## 备注
- 工作区文件操作相对于第一个工作区根目录
- 调试工具需要工作区中活动的调试配置(`launch.json`)
- 终端工具在 VS Code 中创建集成终端;输出捕获有 30 秒超时以防止资源泄漏
- LSP 工具查询活动语言服务器;诊断上限为 200 行,带有 `... 和 N 更多` 后缀
- 启用了 `sourceMap: true` — 在调试扩展本身时,断点在调试器中有效
MCP 配置
以下是此 MCP Server 的配置信息,可直接复制到 Cursor 或其他 MCP 客户端中使用。
mcp.json
连接信息
猜你喜欢
暂无推荐服务器