Code Editor MCP Server
This server is an MCP code-editing/filesystem tool server exposing file reading, directory operations, file writes, precise search/replace edits, and encoding conversion through MCP tools.
Filesystem metadata/root management: query file/dir metadata (
config_ops/get_file_info); the schema also exposesset_root_path/list_allowed_rootsfor whitelist management, though the README notes the whitelist is removed in favor of absolute path access.Read files:
read_file/read_filessupport absolute paths, line ranges, multi-file reads, auto/forced encoding detection, MIME/image detection, and pagination.Directory operations:
dir_opscreates/lists/deletes directories with tree/flat listing, depth/ignore/max_items options, mtime conflict checks, confirm tokens, recycle-bin deletion, and approval for risky deletes.File operations:
file_opswrites, appends, copies, moves, and deletes files with encoding selection, mtime conflict detection, and atomic-write behavior.Precise editing:
edit_block/edit_blocksperform single or batch search/replace edits with expected replacement counts, whitespace/escape flexibility, and fail-fast/continue/rollback policies.Encoding conversion:
convert_file_encodingbatch-converts files between encodings (utf-8, gbk, gb2312) with error handling and mismatch policies.Safety/control: tools can be independently enabled/disabled via environment variables or config; all paths must be absolute; critical/root directories are protected; deletes go to trash rather than permanent removal.
Implements file and code editing operations with Python-based encoding detection, file manipulation, and batch editing capabilities for Python source files and other text formats.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Code Editor MCP Server read_file /home/user/project/src/main.py"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
code-editor
面向多客户端并发、安全沙箱、编码感知的代码编辑 MCP 服务器。
路径访问更新:所有参数必须是绝对路径。路径白名单已移除,任意绝对路径均可访问;
CODE_EDIT_ROOT仅作为删除安全标记,不做访问边界或相对路径解析。每个工具可通过环境变量独立开关,关闭后该工具不会被注册,客户端与智能体完全不可见、不可调用。
安装与运行
# 安装(pip 或 uv 均可,包名 code-editor-mcp)
pip install code-editor-mcp # 或 uv pip install code-editor-mcp
# 更新最新版
pip install -U code-editor-mcp
# 直接启动 CLI 入口
code-editor
# 若从源码运行
uv sync
uv run python server.py关键环境变量:
CODE_EDIT_ROOT:安全标记(默认启动时的 CWD),仅用于删除安全校验,不做访问边界,也不参与相对路径解析。CODE_EDIT_TOOL_ENABLED_<TOOL>:工具开关(环境变量方式),1/true/yes启用(默认),0/false/no禁用。禁用后该工具不注册,客户端与智能体完全看不到。CODE_EDIT_TOOL_SWITCHES_FILE:工具开关配置文件路径(默认tools/tool_switches.json)。
工具开关配置(推荐)
本地使用推荐直接编辑 tools/tool_switches.json,无需设置环境变量:
{
"config_ops": false,
"read_files": false,
"dir_ops": false,
"file_ops": false,
"edit_blocks": true,
"convert_file_encoding": false
}值为
true启用、false禁用;未列出的工具默认启用。优先级:配置文件 > 环境变量 > 默认启用。
修改后重启 MCP 服务生效。
环境变量一览:
变量 | 作用 | 默认值 |
| 安全标记(非访问边界,不做路径解析) | 当前工作目录 |
| 开关 | 启用 |
| 开关 | 启用 |
| 开关 | 启用 |
| 开关 | 启用 |
| 开关 | 启用 |
| 开关 | 启用 |
| (legacy)内部 | 1000 |
|
| 50 |
设计要点
路径访问:白名单已移除,任意绝对路径均可访问;相对路径仍被拒绝。
CODE_EDIT_ROOT仅作删除安全标记,不做路径拼接。工具开关:每个工具可通过
CODE_EDIT_TOOL_ENABLED_<TOOL>独立禁用;禁用后不注册,客户端与智能体完全不可见、不可调用。乐观锁:写/删类支持秒或纳秒级
expected_mtime,10ms 容忍;写入走原子写避免部分落盘。默认忽略:
.git、__pycache__、node_modules、.DS_Store、.env*、.venv、*.log、*.pem;ignore_patterns传空字符串/空列表可关闭默认忽略。编码感知:
read_filesv2 默认逐文件auto检测/复用编码(基于最新 mtime 刷新的元信息缓存);如自动结果乱码,可在每个 request 里显式传encoding覆盖。安全删除:禁止删除当前根/其祖先/关键系统目录。
MCP 工具(code-editor)
文件系统工具
名称 | 工具 | 功能 | 主要参数/说明 | 常见误用 |
|
| 元信息查询 |
| 拼错 action;误以为还有 set_root/list_roots |
|
| LLM 友好读取:多文件/同文件多片段 + 分页 |
| 继续传旧的 |
| `dir_ops(action, dir_path, depth=2, format="tree" | "flat", ignore_patterns=None, max_items=1000, expected_mtime=None, confirm_token=None, allow_nonempty=None, approval_token=None)` | 统一目录操作 |
|
|
| 综合文件操作:write/append/copy/move/delete | 所有路径必须绝对;write 覆盖、append 追加;write/append 需 file_path+content;copy/move 需 source_path+destination_path;delete 需 file_path;encoding 仅写入使用;expected_mtime:写/删校验目标文件,拷贝/移动校验源文件;删除返回结构化结果 | action 不支持或参数缺失;copy 目标已存在;delete 目标是目录 |
|
| 批量转码并覆盖写回 | 绝对路径列表;utf-8/gbk/gb2312/gb18030;错误处理 strict/replace/ignore;编码检测( charset-normalizer ),策略 fail-fast / warn-skip(默认) / force;结果返回 detectedEncoding/Confidence/mismatch;内置别名兼容 utf8/utf_8/utf-8-sig/ascii/cp936/gb-2312/gb-18030 | 相对路径;二进制文件 |
dir_ops 参数要点(避免误调用)
create:仅dir_path必须;其余参数会被忽略。list:format仅支持tree/flat;max_items必须为正整数或 None。delete:必须同时提供expected_mtime、confirm_token、allow_nonempty(显式 True/False)。删除行为统一移动到回收站,不支持永久删除。
命中高风险规则时会返回
status=needs_approval,响应内包含approval_token与llm_instruction。盘符根目录(如
C:\/D:\/E:\)会被永久阻断并返回status=blocked_critical。confirm_token生成规则(严格匹配):
from pathlib import Path
import os
normalized = os.path.normcase(str(Path(dir_path).resolve()))
confirm_token = f"delete:{normalized}"代码精准编辑工具
名称 | 工具 | 功能 | 主要参数/说明 | 常见误用 |
|
| 单编辑/批量编辑:搜索替换 |
| 把 |
edit_blocks 返回格式(v0.3.0+)
edit_blocks 返回结构化数据,包含修改位置信息便于验证:
# edit_blocks(单编辑)返回示例
{
"status": "success",
"message": "Applied 2 edit(s) to /path/file.py (lines 10-12, 20-25)",
"file_path": "/path/file.py",
"replacements": 2,
"locations": [
{"start_line": 10, "end_line": 12, "start_col": 5, "end_col": 20},
{"start_line": 20, "end_line": 25, "start_col": 1, "end_col": 15}
]
}
# edit_blocks(批量)返回示例
{
"status": "success", # success/partial/error
"message": "Completed 3/3 edits",
"total_edits": 3,
"successful_edits": 3,
"failed_edits": 0,
"results": [
{"status": "success", "file_path": "...", "replacements": 1, "locations": [...], "message": "..."},
{"status": "success", "file_path": "...", "replacements": 1, "locations": [...], "message": "..."},
{"status": "success", "file_path": "...", "replacements": 1, "locations": [...], "message": "..."}
]
}使用示例
查询元信息:
config_ops(action="get_info", path="/abs/path/src/app.py")。带锁写入:
info = config_ops(action="get_info", path="/abs/path/src/app.py")→file_ops(action="write", file_path="/abs/path/src/app.py", content=content, expected_mtime=info["modified"])。精确替换(单编辑):
edit_blocks(edits={"file_path":"/abs/path/src/app.py","old_string":"old","new_string":"new","expected_replacements":1,"expected_mtime":info["modified"]})。单文件片段读取(range,行号 1-based):
read_files([
{"path": "/abs/path/src/app.py", "mode": "range", "start_line": 10, "line_count": 60}
])同文件多片段 + 跨文件(一次拿齐,减少多次调用):
read_files([
{"path": "/abs/path/src/app.py", "mode": "range", "start_line": 1, "line_count": 80, "id": "app_head"},
{"path": "/abs/path/src/app.py", "mode": "range", "start_line": 200, "line_count": 80, "id": "app_mid"},
{"path": "/abs/path/README.md", "mode": "range", "start_line": 1, "line_count": 120, "id": "readme"},
], max_total_chars=200000, parallelism=4)分页读取整文件(all + cursor):
resp1 = read_files([{"path": "/abs/path/src/app.py", "mode": "all"}], page_line_count=400)
cursor = resp1["results"][0].get("next_cursor")
resp2 = read_files([{"cursor": cursor}], page_line_count=400) # 继续下一页批量编辑(同文件多处修改):
edit_blocks(edits=[
{"file_path": "/abs/app.py", "old_string": "foo", "new_string": "bar"},
{"file_path": "/abs/app.py", "old_string": "hello", "new_string": "world"},
], error_policy="rollback")批量编辑(多文件):
edit_blocks(edits=[
{"file_path": "/abs/a.py", "old_string": "v1", "new_string": "v2"},
{"file_path": "/abs/b.py", "old_string": "v1", "new_string": "v2"},
], error_policy="continue")批量转码:
convert_file_encoding(["/abs/a.txt", "/abs/b.txt"], "gb2312", "utf-8", error_handling="replace", mismatch_policy="warn-skip")。列目录(扁平):
dir_ops(action="list", dir_path="/abs/path", format="flat", ignore_patterns=[".git", "node_modules"])。删除目录(显式确认,统一进回收站):
info = config_ops(action="get_info", path="/abs/path")→normalized = os.path.normcase(str(Path("/abs/path").resolve()))→token = f"delete:{normalized}"→dir_ops(action="delete", dir_path="/abs/path", expected_mtime=info["modified"], confirm_token=token, allow_nonempty=True)。高风险删除二次审批:首次调用 delete 可能返回
status=needs_approval+approval.approval_token,拿到用户明确同意后,带上approval_token再次调用同一 delete。
MCP 客户端快速配置示例
{
"mcpServers": {
"code-editor": {
"command": "code-editor",
"env": {
"CODE_EDIT_ROOT": "."
}
}
}
}[mcp_servers.code-editor]
command = "code-editor"
# 将工作目录指向当前项目,使 CODE_EDIT_ROOT 默认跟随启动时的 CWD
cwd = "."
startup_timeout_sec = 120安全/行为提示
路径验证:所有操作要求绝对路径;白名单已移除,任意绝对路径均可访问;
CODE_EDIT_ROOT仅为删除安全标记。工具开关:通过
CODE_EDIT_TOOL_ENABLED_<TOOL>可独立禁用任意工具;禁用后该工具不注册,客户端与智能体完全不可见、不可调用。删除防护:删除只允许移动到回收站;任何失败都会直接拒绝(不会降级为永久删除)。
盘符根目录阻断:
C:\、D:\、E:\(及其他文件系统根目录)会被永久阻断,并返回极高风险警告。二次审批:仅“重要目录 + 大规模删除”触发;返回会强制提示模型先询问用户并等待批准。
Available Tools
10 toolsconvert_file_encodingA
Convert files between encodings (utf-8, gbk, gb2312).
Args: file_paths: List of absolute file paths. source_encoding: Current encoding. target_encoding: Desired encoding. error_handling: "strict" | "replace" | "ignore" mismatch_policy: "warn-skip" | "fail-fast" | "force"
Inputs: file_paths (required), source_encoding (required), target_encoding (required), error_handling, +1 more. Returns: result
dir_opsA
Directory operations: create, list, or delete.
Args: action: "create" | "list" | "delete" dir_path: Absolute path to the directory. depth: Listing depth (list only). format: "tree" | "flat" (list only). ignore_patterns: Glob patterns to exclude (list only). max_items: Max entries for flat listing. expected_mtime: Required for delete (conflict detection). confirm_token: Required for delete ("delete:<normalized_path>"). allow_nonempty: Required for delete (explicit bool).
Inputs: action (required), dir_path (required), depth, format, +5 more. Returns: result
edit_blockB
Search and replace text in a file.
Args: file_path: Absolute path to the file. old_string: Text to find. new_string: Replacement text. expected_replacements: Required match count (default 1). expected_mtime: Conflict detection timestamp. ignore_whitespace: Match with flexible whitespace. normalize_escapes: Unescape \n, \t, etc. in search. encoding: File encoding (utf-8, gbk, gb2312).
Inputs: file_path (required), old_string (required), new_string (required), expected_replacements, +4 more. Returns: object
edit_blocksA
Apply multiple search/replace edits in a single call.
Args: edits: List of edit specs, each with: - file_path: Absolute path - old_string: Text to find - new_string: Replacement text - expected_replacements: Match count (default 1) - ignore_whitespace: Flexible whitespace (default False) - normalize_escapes: Unescape \n, \t (default False) error_policy: "fail-fast" | "continue" | "rollback" encoding: File encoding for all edits (utf-8, gbk, gb2312).
Inputs: edits (required), error_policy, encoding. Returns: object
file_opsA
File operations: write, append, copy, move, or delete.
Args: action: "write" | "append" | "copy" | "move" | "delete" file_path: Target path (write/append/delete). content: File content (write/append). source_path: Source path (copy/move). destination_path: Destination path (copy/move). expected_mtime: Conflict detection timestamp. encoding: Text encoding for write/append (utf-8, gbk, gb2312).
Inputs: action (required), file_path, content, source_path, +3 more. Returns: result
get_file_infoB
Get metadata for a file or directory.
Args: file_path: Absolute path to the target.
Inputs: file_path (required).
list_allowed_rootsA
Return the current whitelist of allowed directories.
Inputs: no named parameters. Returns: result
read_fileA
Read file content with optional line range.
Args: file_path: Absolute path to the file. offset: Start line (negative reads from end). length: Max lines to return. encoding: "auto"/None for auto-detection, or specify: utf-8, gbk, gb2312.
Returns: dict with keys: - content: File content as string - mimeType: MIME type of the file - isImage: Boolean indicating if file is an image - encoding: Detected encoding (e.g., "utf_8", "gbk", "gb2312") - encodingConfidence: Confidence score for encoding detection (float or None)
Inputs: file_path (required), offset, length, encoding.
read_filesA
Read multiple files in a single call.
Args: file_paths: List of absolute file paths. encoding: "auto"/None for auto-detection, or specify: utf-8, gbk, gb2312.
Returns: list of dicts, each with keys: - path: File path - content: File content as string - mimeType: MIME type of the file - isImage: Boolean indicating if file is an image - encoding: Detected encoding (e.g., "utf_8", "gbk", "gb2312") - encodingConfidence: Confidence score for encoding detection (float or None) - error: Error message (only present if read failed)
Inputs: file_paths (required), encoding. Returns: result
set_root_pathB
Add a directory to the allowed whitelist.
Args: root_path: Absolute path to an existing directory.
Inputs: root_path (required). Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 10 tools
Most tools have distinct purposes, but edit_block and edit_blocks are very similar in function, differing only in whether they apply a single or multiple edits. This overlap could cause an agent to select the wrong one. Other tools like dir_ops and file_ops are clear.
Naming is a mix of verb_noun (convert_file_encoding, edit_block, read_file) and noun_verb (dir_ops, file_ops). The 'ops' suffix is not a verb, breaking the pattern. Also singular/plural vary (edit_block vs edit_blocks, read_file vs read_files) but are consistent in context.
10 tools is well-scoped for a code editor server, covering file reading/writing/editing, directory ops, encoding, and configuration. Each tool earns its place without bloat or deficiency.
The tool set covers most core code editing operations: read, write, edit, directory listing, encoding conversion, and root management. A notable gap is the lack of a content search across files, which would be useful for a code editor. Otherwise, the surface is solid.
Maintenance
Related MCP Connectors
A real-time, multiplayer filesystem for agents and humans: shared files, live edits, history.
Manage files and folders directly from your workspace. Read and write files, list directories, cre…
Securely search and manage workspace context files for AI agents and teams.
Read, write, and combine connected apps and databases with shared code and per-person permissions.
Related MCP Servers
- FlicenseAqualityDmaintenanceEnables secure filesystem operations with directory sandboxing and optional read-only mode. Supports file reading/writing, directory management, file searching, and text operations while restricting access to specified directories.12-
- FlicenseNot gradedqualityDmaintenanceEnables safe file system operations including reading, writing, updating, and deleting files with built-in security safeguards, automatic backups, and comprehensive error handling. Provides directory listing, file metadata extraction, and protects against operations on system-critical paths.-
- FlicenseNot gradedqualityNot gradedmaintenanceEnables comprehensive filesystem operations including reading/writing files, directory management, file searching, editing with diff preview, compression, hashing, and merging with dynamic directory access control.1,381,610 npm-
- AlicenseNot gradedqualityDmaintenanceEnables AI agents to safely explore directories, read files, search content by pattern or filename, and edit files with checksum verification and dry-run preview within sandboxed filesystem access.68 npm76ISC