"""Manages the underlying filesystem MCP server as an internal dependency.
Swappable — change BACKEND_CONFIG to use a different MCP server implementation."""
import shutil
import tempfile

from fastmcp import Client

BACKEND_CONFIG = {
    "command": "npx",
    "args": ["-y", "@modelcontextprotocol/server-filesystem"],
}
TOOL_NAME = "edit_file"


def create_client(allowed_dirs: list[str]) -> Client:
    """Create a client that spawns the filesystem MCP server with given directories.
    Also grants access to the system temp directory for internal temp file operations.
    """
    npx_path = shutil.which("npx")
    if npx_path is None:
        raise RuntimeError(
            "npx is not installed or not on PATH. "
            "Install Node.js (https://nodejs.org) to use this MCP server. "
            "npx is required to run @modelcontextprotocol/server-filesystem."
        )
    config = {
        **BACKEND_CONFIG,
        "command": npx_path,
        "args": [*BACKEND_CONFIG["args"], *allowed_dirs, tempfile.gettempdir()],
    }
    return Client({"mcpServers": {"filesystem": config}})
