File size: 3,917 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
"""Tool registry and dispatcher for C_48_09_01."""
from __future__ import annotations

import importlib
import shutil
import tempfile
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional


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


TOOL_MODULES: List[str] = [
    "mcp_servers.tools.list_projects",
    "mcp_servers.tools.get_project_overview",
    "mcp_servers.tools.list_project_users",
    "mcp_servers.tools.list_instruments",
    "mcp_servers.tools.inspect_instrument_dictionary",
    "mcp_servers.tools.list_events",
    "mcp_servers.tools.search_records",
    "mcp_servers.tools.get_record_profile",
    "mcp_servers.tools.list_data_queries",
    "mcp_servers.tools.list_export_jobs",
    "mcp_servers.tools.inspect_audit_trail",
    "mcp_servers.tools.create_record",
    "mcp_servers.tools.update_record_field",
    "mcp_servers.tools.mark_form_complete",
    "mcp_servers.tools.open_data_query",
    "mcp_servers.tools.update_data_query_answer",
    "mcp_servers.tools.resolve_data_query",
    "mcp_servers.tools.schedule_export_job",
    "mcp_servers.tools.approve_export_job",
    "mcp_servers.tools.update_project_user_role",
    "mcp_servers.tools.create_instrument_field",
    "mcp_servers.tools.update_field_branching_logic",
    "mcp_servers.tools.archive_instrument",
    "mcp_servers.tools.bulk_import_records",
    "mcp_servers.tools.execute_data_quality_rules",
    "mcp_servers.tools.materialize_export_file",
    "mcp_servers.tools.apply_dictionary_version",
    "mcp_servers.tools.set_record_event_lock",
    "mcp_servers.tools.refresh_fixture_state",
    "mcp_servers.tools.evaluate_project_state"
]
STATIC_TOOL_REGISTRY: Dict[str, Callable[..., Dict[str, Any]]] = {}
_TOOLS_LOADED = False


def register_tool(name, func, description, input_schema):
    TOOL_REGISTRY[name] = func
    STATIC_TOOL_REGISTRY[name] = func
    _TOOL_METADATA[name] = {"description": description, "input_schema": input_schema}


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


def get_tool_names_for_environment():
    load_tools()
    return sorted(TOOL_REGISTRY)


def get_tool_metadata():
    load_tools()
    return dict(_TOOL_METADATA)


def _ensure_runtime_state_manager():
    global _state_manager, _runtime_root
    if _state_manager is not None:
        return _state_manager
    from mcp_servers.state.state_manager import StateManager
    project_root = Path(__file__).resolve().parents[1]
    seed = project_root / "data" / "database"
    _runtime_root = Path(tempfile.mkdtemp(prefix="redcap_runtime_"))
    runtime_data = _runtime_root / "data"
    shutil.copytree(seed, runtime_data / "temp")
    _state_manager = StateManager(db_path=str(runtime_data))
    return _state_manager


def cleanup_runtime():
    global _state_manager, _runtime_root
    _state_manager = None
    if _runtime_root is not None:
        shutil.rmtree(_runtime_root, ignore_errors=True)
    _runtime_root = None


def call_tool(tool_name, state_manager=None, **kwargs):
    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 _ensure_runtime_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}