951 lines
34 KiB
Python
951 lines
34 KiB
Python
"""Встроенный MCP-сервер файловой системы.
|
||
|
||
Сервер работает поверх stdio и общается с клиентом построчным JSON-RPC 2.0.
|
||
stdout занят только протоколом, все логи уходят в stderr.
|
||
|
||
Запуск:
|
||
python3 -m XUI.core.mcp.fs_server --root /abs/path [--root /another]
|
||
|
||
Реализованы инструменты list_dir, stat, read_file, write_file, create_dir,
|
||
move, copy, delete и search. Все пути обязаны оставаться внутри разрешённых
|
||
корневых каталогов; символические ссылки, ведущие наружу, не раскрываются.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import fnmatch
|
||
import json
|
||
import os
|
||
import shutil
|
||
import stat
|
||
import sys
|
||
import tempfile
|
||
import time
|
||
import traceback
|
||
from pathlib import PurePosixPath
|
||
from typing import Any, Callable, Iterable
|
||
|
||
PROTOCOL_VERSION = "2025-06-18"
|
||
SERVER_NAME = "xenith-fs"
|
||
SERVER_VERSION = "1.0"
|
||
|
||
MAX_FILE_BYTES = 2 * 1024 * 1024 # жёсткий предел чтения/записи — 2 МиБ
|
||
DEFAULT_READ_BYTES = 200_000
|
||
DEFAULT_SEARCH_RESULTS = 100
|
||
MAX_SEARCH_RESULTS = 200
|
||
|
||
TRASH_DIR_NAME = ".xenith-trash"
|
||
|
||
_MISSING = object()
|
||
|
||
|
||
class ToolError(Exception):
|
||
"""Ожидаемая ошибка выполнения инструмента (отдаётся как isError)."""
|
||
|
||
|
||
def log(message: str) -> None:
|
||
"""Пишем только в stderr: stdout принадлежит JSON-RPC."""
|
||
print(f"[xenith-fs] {message}", file=sys.stderr, flush=True)
|
||
|
||
|
||
def _is_within(path: str, root: str) -> bool:
|
||
"""Проверяет, что path находится внутри root (или совпадает с ним)."""
|
||
try:
|
||
return os.path.commonpath([path, root]) == root
|
||
except ValueError:
|
||
# Разные диски / некорректные пути.
|
||
return False
|
||
|
||
|
||
def _rel(path: str, root: str) -> str:
|
||
rel = os.path.relpath(path, root)
|
||
return "." if rel == "." else rel
|
||
|
||
|
||
class PathGuard:
|
||
"""Разрешение и проверка путей относительно списка корней."""
|
||
|
||
def __init__(self, roots: Iterable[str]):
|
||
resolved: list[str] = []
|
||
for raw in roots:
|
||
if not isinstance(raw, str) or not raw.strip():
|
||
raise ValueError("--root требует непустой путь")
|
||
root = os.path.realpath(os.path.abspath(os.path.expanduser(raw)))
|
||
if not os.path.isdir(root):
|
||
raise ValueError(f"корень не является каталогом: {raw}")
|
||
if root not in resolved:
|
||
resolved.append(root)
|
||
if not resolved:
|
||
raise ValueError("нужен хотя бы один --root")
|
||
self.roots = resolved
|
||
|
||
def root_for(self, path: str) -> str | None:
|
||
"""Находит самый конкретный корень, содержащий path."""
|
||
best: str | None = None
|
||
for root in self.roots:
|
||
if _is_within(path, root):
|
||
if best is None or len(root) > len(best):
|
||
best = root
|
||
return best
|
||
|
||
def _existing_ancestor(self, path: str) -> tuple[str, str, str]:
|
||
"""Возвращает (существующий предок, его realpath, корень)."""
|
||
probe = path
|
||
while not os.path.lexists(probe):
|
||
parent = os.path.dirname(probe)
|
||
if parent == probe:
|
||
raise ToolError("cannot resolve path: no existing ancestor")
|
||
probe = parent
|
||
real = os.path.realpath(probe)
|
||
root = self.root_for(real)
|
||
if root is None:
|
||
raise ToolError("path escapes the allowed roots (outside root; traversal or symlink escape blocked)")
|
||
return probe, real, root
|
||
|
||
def resolve(
|
||
self,
|
||
raw: Any,
|
||
*,
|
||
must_exist: bool = False,
|
||
follow_final: bool = True,
|
||
) -> tuple[str, str]:
|
||
"""Возвращает (безопасный абсолютный путь, содержащий его корень).
|
||
|
||
follow_final=False позволяет работать с самой символической ссылкой
|
||
(например, удалить её), не раскрывая её цель.
|
||
"""
|
||
if not isinstance(raw, str):
|
||
raise ToolError("path must be a string")
|
||
if "\x00" in raw:
|
||
raise ToolError("path contains a NUL byte")
|
||
|
||
if raw == "":
|
||
candidate = self.roots[0]
|
||
elif os.path.isabs(raw):
|
||
candidate = os.path.abspath(raw)
|
||
else:
|
||
candidate = os.path.abspath(os.path.join(self.roots[0], raw))
|
||
|
||
if follow_final:
|
||
probe, real, _root = self._existing_ancestor(candidate)
|
||
if probe == candidate:
|
||
resolved = real
|
||
else:
|
||
rel = os.path.relpath(candidate, probe)
|
||
resolved = os.path.normpath(os.path.join(real, rel))
|
||
root = self.root_for(resolved)
|
||
if root is None:
|
||
raise ToolError("path escapes the allowed roots (outside root; traversal or symlink escape blocked)")
|
||
if must_exist and not os.path.lexists(resolved):
|
||
raise ToolError(f"path not found: {raw}")
|
||
return resolved, root
|
||
|
||
# Сам корень не имеет родителя внутри разрешённой области.
|
||
if candidate in self.roots:
|
||
return candidate, candidate
|
||
|
||
# Последний компонент не раскрываем: так безопасно удалять/перемещать
|
||
# саму ссылку, не трогая объект, на который она указывает.
|
||
parent = os.path.dirname(candidate)
|
||
if parent == candidate:
|
||
raise ToolError("invalid path")
|
||
parent_real, root = self.resolve(parent, must_exist=False, follow_final=True)
|
||
resolved = os.path.normpath(os.path.join(parent_real, os.path.basename(candidate)))
|
||
root = self.root_for(resolved)
|
||
if root is None:
|
||
raise ToolError("path escapes the allowed roots (outside root; traversal or symlink escape blocked)")
|
||
if must_exist and not os.path.lexists(resolved):
|
||
raise ToolError(f"path not found: {raw}")
|
||
return resolved, root
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Валидация аргументов tools/call
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def _arg_str(
|
||
args: dict[str, Any],
|
||
name: str,
|
||
*,
|
||
required: bool = True,
|
||
default: str | None = None,
|
||
) -> str:
|
||
if name not in args:
|
||
if required:
|
||
raise ToolError(f"missing required argument: {name}")
|
||
return default # type: ignore[return-value]
|
||
value = args[name]
|
||
if not isinstance(value, str):
|
||
raise ToolError(f"argument '{name}' must be a string")
|
||
return value
|
||
|
||
|
||
def _arg_bool(args: dict[str, Any], name: str, default: bool = False) -> bool:
|
||
value = args.get(name, default)
|
||
if not isinstance(value, bool):
|
||
raise ToolError(f"argument '{name}' must be a boolean")
|
||
return value
|
||
|
||
|
||
def _arg_int(
|
||
args: dict[str, Any],
|
||
name: str,
|
||
default: int,
|
||
*,
|
||
minimum: int | None = None,
|
||
maximum: int | None = None,
|
||
) -> int:
|
||
value = args.get(name, default)
|
||
if isinstance(value, bool) or not isinstance(value, int):
|
||
raise ToolError(f"argument '{name}' must be an integer")
|
||
if minimum is not None and value < minimum:
|
||
raise ToolError(f"argument '{name}' must be >= {minimum}")
|
||
if maximum is not None and value > maximum:
|
||
raise ToolError(f"argument '{name}' must be <= {maximum}")
|
||
return value
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# JSON Schema для tools/list
|
||
# ---------------------------------------------------------------------------
|
||
|
||
_TOOLS: list[dict[str, Any]] = [
|
||
{
|
||
"name": "list_dir",
|
||
"description": "Показать содержимое каталога внутри разрешённых корней.",
|
||
"inputSchema": {
|
||
"type": "object",
|
||
"properties": {
|
||
"path": {
|
||
"type": "string",
|
||
"description": "Путь относительно первого корня или абсолютный путь внутри корня.",
|
||
},
|
||
"recursive": {"type": "boolean", "default": False},
|
||
},
|
||
"required": ["path"],
|
||
"additionalProperties": False,
|
||
},
|
||
},
|
||
{
|
||
"name": "stat",
|
||
"description": "Метаданные файла, каталога или символической ссылки.",
|
||
"inputSchema": {
|
||
"type": "object",
|
||
"properties": {"path": {"type": "string"}},
|
||
"required": ["path"],
|
||
"additionalProperties": False,
|
||
},
|
||
},
|
||
{
|
||
"name": "read_file",
|
||
"description": "Прочитать текстовый файл (по умолчанию первые 200000 байт).",
|
||
"inputSchema": {
|
||
"type": "object",
|
||
"properties": {
|
||
"path": {"type": "string"},
|
||
"max_bytes": {
|
||
"type": "integer",
|
||
"minimum": 1,
|
||
"maximum": MAX_FILE_BYTES,
|
||
"default": DEFAULT_READ_BYTES,
|
||
},
|
||
},
|
||
"required": ["path"],
|
||
"additionalProperties": False,
|
||
},
|
||
},
|
||
{
|
||
"name": "write_file",
|
||
"description": "Атомарно записать текстовый файл (не более 2 МиБ).",
|
||
"inputSchema": {
|
||
"type": "object",
|
||
"properties": {
|
||
"path": {"type": "string"},
|
||
"content": {"type": "string"},
|
||
"overwrite": {"type": "boolean", "default": False},
|
||
},
|
||
"required": ["path", "content"],
|
||
"additionalProperties": False,
|
||
},
|
||
},
|
||
{
|
||
"name": "create_dir",
|
||
"description": "Создать каталог (включая отсутствующих родителей).",
|
||
"inputSchema": {
|
||
"type": "object",
|
||
"properties": {"path": {"type": "string"}},
|
||
"required": ["path"],
|
||
"additionalProperties": False,
|
||
},
|
||
},
|
||
{
|
||
"name": "move",
|
||
"description": "Переместить файл или каталог внутри разрешённых корней.",
|
||
"inputSchema": {
|
||
"type": "object",
|
||
"properties": {
|
||
"src": {"type": "string"},
|
||
"dst": {"type": "string"},
|
||
"overwrite": {"type": "boolean", "default": False},
|
||
},
|
||
"required": ["src", "dst"],
|
||
"additionalProperties": False,
|
||
},
|
||
},
|
||
{
|
||
"name": "copy",
|
||
"description": "Скопировать файл или каталог внутри разрешённых корней.",
|
||
"inputSchema": {
|
||
"type": "object",
|
||
"properties": {
|
||
"src": {"type": "string"},
|
||
"dst": {"type": "string"},
|
||
"overwrite": {"type": "boolean", "default": False},
|
||
},
|
||
"required": ["src", "dst"],
|
||
"additionalProperties": False,
|
||
},
|
||
},
|
||
{
|
||
"name": "delete",
|
||
"description": "Удалить объект; по умолчанию он попадает в .xenith-trash внутри корня.",
|
||
"inputSchema": {
|
||
"type": "object",
|
||
"properties": {
|
||
"path": {"type": "string"},
|
||
"trash": {"type": "boolean", "default": True},
|
||
},
|
||
"required": ["path"],
|
||
"additionalProperties": False,
|
||
},
|
||
},
|
||
{
|
||
"name": "search",
|
||
"description": "Поиск по именам и текстовому содержимому файлов.",
|
||
"inputSchema": {
|
||
"type": "object",
|
||
"properties": {
|
||
"query": {"type": "string"},
|
||
"path": {"type": "string", "default": "."},
|
||
"glob": {"type": "string"},
|
||
"max_results": {
|
||
"type": "integer",
|
||
"minimum": 1,
|
||
"maximum": MAX_SEARCH_RESULTS,
|
||
"default": DEFAULT_SEARCH_RESULTS,
|
||
},
|
||
},
|
||
"required": ["query"],
|
||
"additionalProperties": False,
|
||
},
|
||
},
|
||
]
|
||
|
||
|
||
def _glob_matches(rel_path: str, name: str, pattern: str) -> bool:
|
||
if fnmatch.fnmatchcase(name, pattern) or fnmatch.fnmatchcase(rel_path, pattern):
|
||
return True
|
||
try:
|
||
return PurePosixPath(rel_path).match(pattern)
|
||
except (TypeError, ValueError):
|
||
return False
|
||
|
||
|
||
def _tool_error(message: str) -> dict[str, Any]:
|
||
return {
|
||
"content": [{"type": "text", "text": message}],
|
||
"isError": True,
|
||
}
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Сервер
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
class FsServer:
|
||
def __init__(self, roots: Iterable[str]):
|
||
self.guard = PathGuard(roots)
|
||
self._handlers: dict[str, Callable[[dict[str, Any]], Any]] = {
|
||
"list_dir": self._list_dir,
|
||
"stat": self._stat,
|
||
"read_file": self._read_file,
|
||
"write_file": self._write_file,
|
||
"create_dir": self._create_dir,
|
||
"move": self._move,
|
||
"copy": self._copy,
|
||
"delete": self._delete,
|
||
"search": self._search,
|
||
}
|
||
|
||
# ---- JSON-RPC ---------------------------------------------------------
|
||
|
||
def handle_message(self, msg: dict[str, Any]) -> dict[str, Any] | None:
|
||
msg_id = msg.get("id", _MISSING)
|
||
is_notification = msg_id is _MISSING
|
||
|
||
def ok(result: Any) -> dict[str, Any] | None:
|
||
if is_notification:
|
||
return None
|
||
return {
|
||
"jsonrpc": "2.0",
|
||
"id": None if is_notification else msg_id,
|
||
"result": result,
|
||
}
|
||
|
||
def err(code: int, message: str) -> dict[str, Any] | None:
|
||
if is_notification:
|
||
return None
|
||
return {
|
||
"jsonrpc": "2.0",
|
||
"id": None if is_notification else msg_id,
|
||
"error": {"code": code, "message": message},
|
||
}
|
||
|
||
jsonrpc = msg.get("jsonrpc", "2.0")
|
||
if jsonrpc != "2.0":
|
||
return err(-32600, "unsupported jsonrpc version")
|
||
|
||
method = msg.get("method")
|
||
if not isinstance(method, str):
|
||
return err(-32600, "request is missing a method")
|
||
|
||
params = msg.get("params", {})
|
||
if params is None:
|
||
params = {}
|
||
if not isinstance(params, dict):
|
||
return err(-32602, "params must be an object")
|
||
|
||
if method == "initialize":
|
||
return ok(
|
||
{
|
||
"protocolVersion": PROTOCOL_VERSION,
|
||
"capabilities": {"tools": {}},
|
||
"serverInfo": {"name": SERVER_NAME, "version": SERVER_VERSION},
|
||
}
|
||
)
|
||
|
||
if method == "notifications/initialized":
|
||
log("клиент инициализирован")
|
||
return None
|
||
|
||
if method == "ping":
|
||
return ok({})
|
||
|
||
if method == "tools/list":
|
||
return ok({"tools": _TOOLS})
|
||
|
||
if method == "tools/call":
|
||
name = params.get("name")
|
||
if not isinstance(name, str) or not name:
|
||
return err(-32602, "tools/call requires a string tool name")
|
||
arguments = params.get("arguments", {})
|
||
if arguments is None:
|
||
arguments = {}
|
||
if not isinstance(arguments, dict):
|
||
return err(-32602, "arguments must be an object")
|
||
result = self._call_tool(name, arguments)
|
||
if is_notification:
|
||
return None
|
||
return {"jsonrpc": "2.0", "id": msg_id, "result": result}
|
||
|
||
return err(-32601, f"method not found: {method}")
|
||
|
||
# ---- Выполнение инструментов -----------------------------------------
|
||
|
||
def _call_tool(self, name: str, args: dict[str, Any]) -> dict[str, Any]:
|
||
handler = self._handlers.get(name)
|
||
if handler is None:
|
||
return _tool_error(f"unknown tool: {name}")
|
||
|
||
try:
|
||
value = handler(args)
|
||
except ToolError as exc:
|
||
return _tool_error(str(exc))
|
||
except OSError as exc:
|
||
detail = exc.strerror or str(exc)
|
||
filename = getattr(exc, "filename", None)
|
||
if filename:
|
||
detail = f"{detail}: {filename}"
|
||
return _tool_error(f"filesystem error: {detail}")
|
||
except Exception as exc: # noqa: BLE001 - сервер не должен падать
|
||
log(f"внутренняя ошибка {name}:\n{traceback.format_exc()}")
|
||
return _tool_error(f"internal error in tool {name}: {exc}")
|
||
|
||
if isinstance(value, str):
|
||
text = value
|
||
else:
|
||
text = json.dumps(value, ensure_ascii=False, indent=2)
|
||
return {
|
||
"content": [{"type": "text", "text": text}],
|
||
"isError": False,
|
||
}
|
||
|
||
# ---- Инструменты ------------------------------------------------------
|
||
|
||
def _list_dir(self, args: dict[str, Any]) -> dict[str, Any]:
|
||
raw = _arg_str(args, "path")
|
||
recursive = _arg_bool(args, "recursive", False)
|
||
base, root = self.guard.resolve(raw, must_exist=True)
|
||
if not os.path.isdir(base):
|
||
raise ToolError(f"not a directory: {raw}")
|
||
|
||
entries: list[dict[str, Any]] = []
|
||
stack = [base]
|
||
while stack:
|
||
current = stack.pop()
|
||
try:
|
||
with os.scandir(current) as it:
|
||
items = sorted(it, key=lambda e: e.name.casefold())
|
||
except OSError as exc:
|
||
raise ToolError(f"cannot read directory {current}: {exc}") from exc
|
||
|
||
for entry in items:
|
||
try:
|
||
is_dir = entry.is_dir(follow_symlinks=False)
|
||
except OSError:
|
||
is_dir = False
|
||
if is_dir and entry.name == TRASH_DIR_NAME:
|
||
continue
|
||
try:
|
||
info = self._entry_info(entry.path, root)
|
||
except OSError:
|
||
continue
|
||
entries.append(info)
|
||
if recursive and is_dir:
|
||
stack.append(entry.path)
|
||
|
||
entries.sort(key=lambda item: item["path"])
|
||
return {
|
||
"path": _rel(base, root),
|
||
"root": root,
|
||
"count": len(entries),
|
||
"entries": entries,
|
||
}
|
||
|
||
def _entry_info(self, path: str, root: str) -> dict[str, Any]:
|
||
st = os.lstat(path)
|
||
if stat.S_ISLNK(st.st_mode):
|
||
kind = "symlink"
|
||
elif stat.S_ISDIR(st.st_mode):
|
||
kind = "dir"
|
||
elif stat.S_ISREG(st.st_mode):
|
||
kind = "file"
|
||
else:
|
||
kind = "other"
|
||
return {
|
||
"name": os.path.basename(path),
|
||
"path": _rel(path, root),
|
||
"type": kind,
|
||
"size": st.st_size,
|
||
"mtime": st.st_mtime,
|
||
}
|
||
|
||
def _stat(self, args: dict[str, Any]) -> dict[str, Any]:
|
||
raw = _arg_str(args, "path")
|
||
path, root = self.guard.resolve(raw, must_exist=True, follow_final=False)
|
||
st = os.lstat(path)
|
||
info = self._entry_info(path, root)
|
||
info["mode"] = oct(stat.S_IMODE(st.st_mode))
|
||
if stat.S_ISLNK(st.st_mode):
|
||
target = os.path.realpath(path)
|
||
if self.guard.root_for(target) is None:
|
||
raise ToolError(
|
||
"path escapes the allowed roots "
|
||
"(outside root; traversal or symlink escape blocked)"
|
||
)
|
||
info["target"] = _rel(target, root)
|
||
return info
|
||
|
||
def _read_file(self, args: dict[str, Any]) -> str:
|
||
raw = _arg_str(args, "path")
|
||
max_bytes = _arg_int(args, "max_bytes", DEFAULT_READ_BYTES, minimum=1)
|
||
limit = min(max_bytes, MAX_FILE_BYTES)
|
||
|
||
path, _root = self.guard.resolve(raw, must_exist=True)
|
||
st = os.stat(path)
|
||
if not stat.S_ISREG(st.st_mode):
|
||
raise ToolError(f"not a regular file: {raw}")
|
||
|
||
with open(path, "rb") as fh:
|
||
chunk = fh.read(limit + 1)
|
||
|
||
clipped = len(chunk) > limit
|
||
if clipped:
|
||
chunk = chunk[:limit]
|
||
text = chunk.decode("utf-8", errors="replace")
|
||
if clipped:
|
||
text += f"\n\n[... truncated: showing the first {limit} bytes of {raw}]"
|
||
return text
|
||
|
||
def _write_file(self, args: dict[str, Any]) -> dict[str, Any]:
|
||
raw = _arg_str(args, "path")
|
||
content = _arg_str(args, "content")
|
||
overwrite = _arg_bool(args, "overwrite", False)
|
||
|
||
data = content.encode("utf-8")
|
||
if len(data) > MAX_FILE_BYTES:
|
||
raise ToolError(
|
||
f"content exceeds {MAX_FILE_BYTES} bytes (got {len(data)})"
|
||
)
|
||
|
||
path, root = self.guard.resolve(raw, follow_final=True)
|
||
if path == root:
|
||
raise ToolError("refusing to overwrite the root directory")
|
||
|
||
existed = os.path.lexists(path)
|
||
if existed:
|
||
if not overwrite:
|
||
raise ToolError(f"file already exists: {raw}")
|
||
if os.path.isdir(path) and not os.path.islink(path):
|
||
raise ToolError(f"path is a directory: {raw}")
|
||
|
||
parent = os.path.dirname(path)
|
||
os.makedirs(parent, exist_ok=True)
|
||
# После создания родителей ещё раз убеждаемся, что путь внутри корня.
|
||
path, root = self.guard.resolve(path, follow_final=True)
|
||
parent = os.path.dirname(path)
|
||
|
||
mode = 0o644
|
||
if existed:
|
||
try:
|
||
mode = stat.S_IMODE(os.stat(path).st_mode)
|
||
except OSError:
|
||
pass
|
||
|
||
fd, tmp_path = tempfile.mkstemp(prefix=".xenith-write-", dir=parent)
|
||
try:
|
||
with os.fdopen(fd, "wb") as fh:
|
||
fh.write(data)
|
||
fh.flush()
|
||
os.fsync(fh.fileno())
|
||
try:
|
||
os.chmod(tmp_path, mode)
|
||
except OSError:
|
||
pass
|
||
os.replace(tmp_path, path)
|
||
except BaseException:
|
||
try:
|
||
os.unlink(tmp_path)
|
||
except OSError:
|
||
pass
|
||
raise
|
||
|
||
return {
|
||
"ok": True,
|
||
"path": _rel(path, root),
|
||
"root": root,
|
||
"bytes": len(data),
|
||
"overwritten": existed,
|
||
}
|
||
|
||
def _create_dir(self, args: dict[str, Any]) -> dict[str, Any]:
|
||
raw = _arg_str(args, "path")
|
||
path, root = self.guard.resolve(raw, follow_final=True)
|
||
|
||
if os.path.lexists(path):
|
||
if not os.path.isdir(path):
|
||
raise ToolError(f"path exists and is not a directory: {raw}")
|
||
return {"ok": True, "path": _rel(path, root), "created": False}
|
||
|
||
os.makedirs(path, exist_ok=True)
|
||
path, root = self.guard.resolve(path, follow_final=True)
|
||
return {"ok": True, "path": _rel(path, root), "created": True}
|
||
|
||
@staticmethod
|
||
def _remove_path(path: str) -> None:
|
||
"""Удаляет объект, не переходя по символическим ссылкам."""
|
||
st = os.lstat(path)
|
||
if stat.S_ISDIR(st.st_mode) and not stat.S_ISLNK(st.st_mode):
|
||
shutil.rmtree(path)
|
||
else:
|
||
os.unlink(path)
|
||
|
||
def _move(self, args: dict[str, Any]) -> dict[str, Any]:
|
||
src_raw = _arg_str(args, "src")
|
||
dst_raw = _arg_str(args, "dst")
|
||
overwrite = _arg_bool(args, "overwrite", False)
|
||
|
||
src, src_root = self.guard.resolve(src_raw, must_exist=True, follow_final=False)
|
||
dst, dst_root = self.guard.resolve(dst_raw, follow_final=False)
|
||
|
||
if src == src_root:
|
||
raise ToolError("refusing to move the root directory")
|
||
if dst == dst_root:
|
||
raise ToolError("refusing to replace the root directory")
|
||
if src == dst:
|
||
raise ToolError("source and destination are the same")
|
||
|
||
src_is_dir = os.path.isdir(src) and not os.path.islink(src)
|
||
if src_is_dir and _is_within(dst, src):
|
||
raise ToolError("cannot move a directory into itself")
|
||
|
||
parent = os.path.dirname(dst)
|
||
os.makedirs(parent, exist_ok=True)
|
||
dst, dst_root = self.guard.resolve(dst_raw, follow_final=False)
|
||
|
||
if os.path.lexists(dst):
|
||
if not overwrite:
|
||
raise ToolError(f"destination already exists: {dst_raw}")
|
||
self._remove_path(dst)
|
||
|
||
shutil.move(src, dst)
|
||
return {
|
||
"ok": True,
|
||
"src": _rel(src, src_root),
|
||
"dst": _rel(dst, dst_root),
|
||
"src_root": src_root,
|
||
"dst_root": dst_root,
|
||
}
|
||
|
||
def _copy(self, args: dict[str, Any]) -> dict[str, Any]:
|
||
src_raw = _arg_str(args, "src")
|
||
dst_raw = _arg_str(args, "dst")
|
||
overwrite = _arg_bool(args, "overwrite", False)
|
||
|
||
src, src_root = self.guard.resolve(src_raw, must_exist=True, follow_final=True)
|
||
dst, dst_root = self.guard.resolve(dst_raw, follow_final=False)
|
||
|
||
if src == src_root:
|
||
raise ToolError("refusing to copy the root directory")
|
||
if dst == dst_root:
|
||
raise ToolError("refusing to replace the root directory")
|
||
if src == dst:
|
||
raise ToolError("source and destination are the same")
|
||
|
||
src_is_dir = os.path.isdir(src)
|
||
if src_is_dir and _is_within(dst, src):
|
||
raise ToolError("cannot copy a directory into itself")
|
||
if not src_is_dir and not stat.S_ISREG(os.stat(src).st_mode):
|
||
raise ToolError(f"not a regular file: {src_raw}")
|
||
|
||
parent = os.path.dirname(dst)
|
||
os.makedirs(parent, exist_ok=True)
|
||
dst, dst_root = self.guard.resolve(dst_raw, follow_final=False)
|
||
|
||
if os.path.lexists(dst):
|
||
if not overwrite:
|
||
raise ToolError(f"destination already exists: {dst_raw}")
|
||
self._remove_path(dst)
|
||
|
||
if src_is_dir:
|
||
# symlinks=True: копируем ссылки как ссылки, не раскрывая их.
|
||
shutil.copytree(src, dst, symlinks=True)
|
||
else:
|
||
shutil.copy2(src, dst)
|
||
|
||
return {
|
||
"ok": True,
|
||
"src": _rel(src, src_root),
|
||
"dst": _rel(dst, dst_root),
|
||
"src_root": src_root,
|
||
"dst_root": dst_root,
|
||
}
|
||
|
||
def _delete(self, args: dict[str, Any]) -> dict[str, Any]:
|
||
raw = _arg_str(args, "path")
|
||
use_trash = _arg_bool(args, "trash", True)
|
||
|
||
path, root = self.guard.resolve(raw, must_exist=True, follow_final=False)
|
||
if path == root:
|
||
raise ToolError("refusing to delete the root directory")
|
||
rel = _rel(path, root)
|
||
|
||
if use_trash:
|
||
if rel == TRASH_DIR_NAME or rel.startswith(TRASH_DIR_NAME + os.sep):
|
||
raise ToolError("refusing to move the trash into itself; use trash=false")
|
||
stamp = f"{time.strftime('%Y%m%d-%H%M%S')}-{time.time_ns() % 1_000_000_000:09d}"
|
||
dest = os.path.join(root, TRASH_DIR_NAME, stamp, rel)
|
||
# Проверяем путь корзины: .xenith-trash может оказаться ссылкой наружу.
|
||
dest, _trash_root = self.guard.resolve(dest, follow_final=False)
|
||
base_dest = dest
|
||
counter = 1
|
||
while os.path.lexists(dest):
|
||
dest = f"{base_dest}-{counter}"
|
||
counter += 1
|
||
os.makedirs(os.path.dirname(dest), exist_ok=True)
|
||
shutil.move(path, dest)
|
||
return {
|
||
"ok": True,
|
||
"path": rel,
|
||
"trashed": True,
|
||
"trash_path": _rel(dest, root),
|
||
"root": root,
|
||
}
|
||
|
||
self._remove_path(path)
|
||
return {"ok": True, "path": rel, "trashed": False, "root": root}
|
||
|
||
def _search(self, args: dict[str, Any]) -> dict[str, Any]:
|
||
query = _arg_str(args, "query")
|
||
raw_path = _arg_str(args, "path", required=False, default=".")
|
||
pattern = _arg_str(args, "glob", required=False, default=None)
|
||
limit = _arg_int(args, "max_results", DEFAULT_SEARCH_RESULTS, minimum=1)
|
||
limit = min(limit, MAX_SEARCH_RESULTS)
|
||
|
||
base, root = self.guard.resolve(raw_path or ".", must_exist=True)
|
||
needle = query.casefold()
|
||
results: list[dict[str, Any]] = []
|
||
truncated = False
|
||
|
||
def inspect(full_path: str) -> bool:
|
||
"""Возвращает False, когда пора прекратить обход."""
|
||
nonlocal truncated
|
||
rel = _rel(full_path, root)
|
||
name = os.path.basename(full_path)
|
||
if pattern and not _glob_matches(rel, name, pattern):
|
||
return True
|
||
|
||
try:
|
||
st = os.lstat(full_path)
|
||
except OSError:
|
||
return True
|
||
if stat.S_ISLNK(st.st_mode):
|
||
return True
|
||
|
||
match: dict[str, Any] | None = None
|
||
if needle == "" or needle in name.casefold():
|
||
match = {"path": rel, "type": "file", "match": "name"}
|
||
elif stat.S_ISREG(st.st_mode) and st.st_size <= MAX_FILE_BYTES:
|
||
try:
|
||
with open(full_path, "rb") as fh:
|
||
raw = fh.read(MAX_FILE_BYTES + 1)
|
||
except OSError:
|
||
return True
|
||
if len(raw) <= MAX_FILE_BYTES and b"\x00" not in raw[:8192]:
|
||
text = raw.decode("utf-8", errors="ignore")
|
||
for lineno, line in enumerate(text.splitlines(), 1):
|
||
if needle in line.casefold():
|
||
snippet = line.strip()
|
||
if len(snippet) > 300:
|
||
snippet = snippet[:300] + "..."
|
||
match = {
|
||
"path": rel,
|
||
"type": "file",
|
||
"match": "content",
|
||
"line": lineno,
|
||
"text": snippet,
|
||
}
|
||
break
|
||
|
||
if match is not None:
|
||
if len(results) >= limit:
|
||
truncated = True
|
||
return False
|
||
results.append(match)
|
||
return True
|
||
|
||
if os.path.isdir(base):
|
||
stop = False
|
||
for dirpath, dirnames, filenames in os.walk(base, followlinks=False):
|
||
dirnames[:] = sorted(
|
||
name
|
||
for name in dirnames
|
||
if name != TRASH_DIR_NAME
|
||
and not os.path.islink(os.path.join(dirpath, name))
|
||
)
|
||
for filename in sorted(filenames):
|
||
if not inspect(os.path.join(dirpath, filename)):
|
||
stop = True
|
||
break
|
||
if stop:
|
||
break
|
||
else:
|
||
inspect(base)
|
||
|
||
return {
|
||
"query": query,
|
||
"path": _rel(base, root),
|
||
"count": len(results),
|
||
"truncated": truncated,
|
||
"max_results": limit,
|
||
"results": results,
|
||
}
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# stdio / JSON-RPC транспорт
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def _emit(message: dict[str, Any]) -> None:
|
||
sys.stdout.write(json.dumps(message, ensure_ascii=False, separators=(",", ":")) + "\n")
|
||
sys.stdout.flush()
|
||
|
||
|
||
def _error_response(request_id: Any, code: int, message: str) -> dict[str, Any]:
|
||
return {
|
||
"jsonrpc": "2.0",
|
||
"id": request_id,
|
||
"error": {"code": code, "message": message},
|
||
}
|
||
|
||
|
||
def serve(server: FsServer) -> int:
|
||
for line in sys.stdin:
|
||
line = line.strip()
|
||
if not line:
|
||
continue
|
||
|
||
try:
|
||
msg = json.loads(line)
|
||
except json.JSONDecodeError as exc:
|
||
_emit(_error_response(None, -32700, f"JSON parse error: {exc.msg}"))
|
||
continue
|
||
|
||
if not isinstance(msg, dict):
|
||
_emit(_error_response(None, -32600, "request must be a JSON object"))
|
||
continue
|
||
|
||
try:
|
||
response = server.handle_message(msg)
|
||
except Exception: # noqa: BLE001 - не роняем транспорт из-за одного запроса
|
||
log(f"необработанная ошибка запроса:\n{traceback.format_exc()}")
|
||
request_id = msg.get("id")
|
||
response = _error_response(request_id, -32603, "internal server error")
|
||
|
||
if response is not None:
|
||
_emit(response)
|
||
|
||
return 0
|
||
|
||
|
||
def main(argv: list[str] | None = None) -> int:
|
||
parser = argparse.ArgumentParser(
|
||
prog="xenith-fs",
|
||
description="Встроенный MCP-сервер файловой системы (stdio JSON-RPC 2.0)",
|
||
)
|
||
parser.add_argument(
|
||
"--root",
|
||
action="append",
|
||
required=True,
|
||
metavar="PATH",
|
||
help="разрешённый корневой каталог (можно указывать несколько раз)",
|
||
)
|
||
args = parser.parse_args(argv)
|
||
|
||
try:
|
||
server = FsServer(args.root)
|
||
except (ValueError, OSError) as exc:
|
||
log(f"не удалось запустить сервер: {exc}")
|
||
return 2
|
||
|
||
# stdout — только протокол; принудительно UTF-8, чтобы JSON не ломался.
|
||
try:
|
||
sys.stdin.reconfigure(encoding="utf-8", errors="replace")
|
||
sys.stdout.reconfigure(encoding="utf-8", newline="\n")
|
||
except (AttributeError, ValueError):
|
||
pass
|
||
|
||
log("запущен; корни: " + ", ".join(server.guard.roots))
|
||
try:
|
||
return serve(server)
|
||
except (BrokenPipeError, KeyboardInterrupt):
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|