File size: 6,320 Bytes
f726fd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
"""Tool registry and dispatcher for C_14_01_54."""

from __future__ import annotations

import hashlib
import importlib
import json
import shutil
import tempfile
from contextlib import contextmanager
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional

try:
    import fcntl
except ImportError:
    fcntl = None


TOOL_REGISTRY: Dict[str, Callable[..., Dict[str, Any]]] = {}
_TOOL_METADATA: Dict[str, Dict[str, Any]] = {}
_state_manager = None
_runtime_root: Optional[Path] = None


def register_tool(name: str, func: Callable[..., Dict[str, Any]], description: str, input_schema: Dict[str, Any]) -> None:
    _TOOL_METADATA[name] = {"name": name, "function": func, "description": description, "input_schema": input_schema}
    TOOL_REGISTRY[name] = func


TOOL_MODULES: List[str] = [
    "mcp_servers.tools.get_node",
    "mcp_servers.tools.list_directory",
    "mcp_servers.tools.search_nodes",
    "mcp_servers.tools.get_file_content",
    "mcp_servers.tools.get_effective_permissions",
    "mcp_servers.tools.list_snapshots",
    "mcp_servers.tools.inspect_quota",
    "mcp_servers.tools.create_directory",
    "mcp_servers.tools.create_file",
    "mcp_servers.tools.update_file_content",
    "mcp_servers.tools.update_file_by_appending_content",
    "mcp_servers.tools.rename_node",
    "mcp_servers.tools.update_node_location",
    "mcp_servers.tools.clone_node",
    "mcp_servers.tools.change_permissions",
    "mcp_servers.tools.remove_node",
    "mcp_servers.tools.archive_directory",
    "mcp_servers.tools.apply_snapshot_restore",
    "mcp_servers.tools.apply_permissions_batch",
    "mcp_servers.tools.update_nodes_location_batch",
    "mcp_servers.tools.materialize_manifest"
]
STATIC_TOOL_REGISTRY: Dict[str, Callable[..., Dict[str, Any]]] = {}
_TOOLS_LOADED = False


def _resolve_data_root(db_path: str) -> Path:
    base = Path(db_path)
    if base.is_absolute():
        return base.resolve()
    cwd_candidate = (Path.cwd() / base).resolve()
    if cwd_candidate.exists():
        return cwd_candidate
    return (Path(__file__).resolve().parent.parent / base).resolve()


@contextmanager
def _database_init_lock(db_path: str):
    resolved_root = _resolve_data_root(db_path)
    digest = hashlib.sha256(str(resolved_root).encode("utf-8")).hexdigest()[:16]
    lock_dir = Path(tempfile.gettempdir()) / "c_14_01_54_locks"
    lock_dir.mkdir(parents=True, exist_ok=True)
    lock_file = (lock_dir / f"{digest}.lock").open("a+")
    try:
        if fcntl is not None:
            fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
        yield
    finally:
        if fcntl is not None:
            fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
        lock_file.close()


def _copy_seed_database(source_root: Path, runtime_root: Path) -> None:
    src = source_root / "database"
    runtime_db = runtime_root / "database"
    runtime_temp = runtime_root / "temp"
    if src.exists():
        shutil.copytree(src, runtime_db)
        shutil.copytree(src, runtime_temp)
    else:
        runtime_db.mkdir(parents=True, exist_ok=True)
        runtime_temp.mkdir(parents=True, exist_ok=True)


def cleanup_runtime() -> None:
    global _runtime_root, _state_manager
    runtime_root = _runtime_root
    _runtime_root = None
    _state_manager = None
    if runtime_root is not None and runtime_root.exists():
        shutil.rmtree(runtime_root, ignore_errors=True)


def init_database(db_path: str = "data") -> None:
    global _runtime_root, _state_manager
    source_root = _resolve_data_root(db_path)
    with _database_init_lock(str(source_root)):
        previous_runtime = _runtime_root
        runtime_root = Path(tempfile.mkdtemp(prefix="c_14_01_54_runtime_"))
        try:
            _copy_seed_database(source_root, runtime_root)
            from mcp_servers.state.state_manager import StateManager

            state_manager = StateManager(db_path=str(runtime_root))
            state_manager.source_db_path = str(source_root)
            state_manager.runtime_root = str(runtime_root)
            _state_manager = state_manager
            _runtime_root = runtime_root
        except Exception:
            shutil.rmtree(runtime_root, ignore_errors=True)
            raise
        finally:
            if previous_runtime is not None and previous_runtime != _runtime_root:
                shutil.rmtree(previous_runtime, ignore_errors=True)


def get_state_manager():
    global _state_manager
    if _state_manager is None:
        init_database("data")
    return _state_manager


def load_tools() -> None:
    global _TOOLS_LOADED
    if _TOOLS_LOADED:
        return
    for module_name in TOOL_MODULES:
        importlib.import_module(module_name)
    STATIC_TOOL_REGISTRY.clear()
    STATIC_TOOL_REGISTRY.update(TOOL_REGISTRY)
    _TOOLS_LOADED = True


def call_tool(tool_name: str, state_manager=None, **kwargs) -> Dict[str, Any]:
    func = TOOL_REGISTRY.get(tool_name)
    if func is None:
        load_tools()
        func = TOOL_REGISTRY.get(tool_name)
    if func is None:
        return {"type": "tool_result", "tool": tool_name, "content": {"status": "error", "data": {}, "message": f"UNKNOWN_TOOL: {tool_name}"}}
    sm = state_manager if state_manager is not None else get_state_manager()
    try:
        content = func(state_manager=sm, **kwargs)
    except Exception as exc:
        content = {"status": "error", "data": {}, "message": f"INTERNAL_ERROR: {type(exc).__name__}: {exc}"}
    return {"type": "tool_result", "tool": tool_name, "content": content}


def get_tool_names_for_environment() -> List[str]:
    load_tools()
    return sorted(TOOL_REGISTRY)


def get_tool_names() -> List[str]:
    return get_tool_names_for_environment()


def get_tools_list() -> List[Dict[str, Any]]:
    load_tools()
    return [
        {"name": name, "description": meta.get("description", ""), "input_schema": meta.get("input_schema", {})}
        for name, meta in sorted(_TOOL_METADATA.items())
    ]


def get_tool_info(tool_name: str) -> Optional[Dict[str, Any]]:
    load_tools()
    meta = _TOOL_METADATA.get(tool_name)
    if not meta:
        return None
    return {"name": tool_name, "description": meta.get("description", ""), "input_schema": meta.get("input_schema", {})}


list_available_tools = get_tools_list
get_env_tools = get_tool_names