"""
Script to combine multiple Python function files into a single core file.
This script scans a directory of Python files, extracts functions and imports,
and combines them into a single output file with FastMCP server configuration.
This is unfortunately necessary as the python sdk of the mondel context protocol
does not support modularity yet. This should be edited once modularity is supported.
https://github.com/modelcontextprotocol/python-sdk/issues/767
"""
from pathlib import Path
import ast
ROOT = Path(__file__).resolve().parent
SRC_DIR = ROOT / "functions" # Directory containing source function files
DEST_FILE = ROOT / "core_combined.py" # Output combined file path
def collect_functions_with_decorator(src_dir):
"""
Collect functions and imports from Python files in the source directory.
Args:
src_dir (Path): Directory path containing Python source files
Returns:
tuple: (sorted list of import statements, list of function definitions)
"""
imports = set()
functions = []
for py_file in src_dir.glob("*.py"):
if py_file.name == "__init__.py":
continue
source = py_file.read_text()
tree = ast.parse(source, filename=str(py_file))
local_imports = [line for line in source.splitlines()
if line.strip().startswith("import") or line.strip().startswith("from")]
imports.update(local_imports)
for node in tree.body:
if isinstance(node, ast.FunctionDef):
code = ast.unparse(node)
functions.append(code)
return sorted(imports), functions
def build_core_file(imports, functions):
"""
Build the combined core file with collected imports and functions.
Args:
imports (list): List of import statements to include
functions (list): List of function definitions to include
"""
with open(DEST_FILE, "w") as f:
f.write("# Autogenerated MCP server file\n")
f.write("from fastmcp import FastMCP\n")
for imp in imports:
f.write(f"{imp}\n")
f.write("\n")
f.write("mcp = FastMCP(\"Command Center\")\n\n")
for fn in functions:
f.write(fn + "\n\n")
f.write("""
if __name__ == "__main__":
mcp.run()
""")
if __name__ == "__main__":
imports, functions = collect_functions_with_decorator(SRC_DIR)
build_core_file(imports, functions)
print(f"Built {DEST_FILE.relative_to(ROOT)}")