8000 feat: add root level file handling by aschlean · Pull Request #117 · golf-mcp/golf · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
## Supported Versions
| Version | Supported |
| ------- | ------------------ |
| 0.2.13 | :white_check_mark: |
| 0.2.12 | :white_check_mark: |
| 0.2.11 | :white_check_mark: |
| 0.2.10 | :white_check_mark: |
Expand Down
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "golf-mcp"
version = "0.2.12"
version = "0.2.13"
description = "Framework for building MCP servers"
authors = [
{name = "Antoni Gmitruk", email = "antoni@golf.dev"}
Expand Down Expand Up @@ -66,7 +66,7 @@ golf = ["examples/**/*"]

[tool.poetry]
name = "golf-mcp"
version = "0.2.12"
version = "0.2.13"
description = "Framework for building MCP servers with zero boilerplate"
authors = ["Antoni Gmitruk <antoni@golf.dev>"]
license = "Apache-2.0"
Expand Down
2 changes: 1 addition & 1 deletion src/golf/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "0.2.12"
__version__ = "0.2.13"
112 changes: 112 additions & 0 deletions src/golf/core/builder.py
8000
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,22 @@ def generate(self) -> None:
console.print()
console.print(get_status_text("success", f"Build completed successfully in {output_dir_display}"))

def _generate_root_file_imports(self) -> list[str]:
"""Generate import statements for automatically discovered root files."""
root_file_imports = []
discovered_files = discover_root_files(self.project_path)

if discovered_files:
root_file_imports.append("# Import root-level Python files")

for filename in sorted(discovered_files.keys()):
module_name = Path(filename).stem # env.py -> env
root_file_imports.append(f"import {module_name}")

root_file_imports.append("") # Blank line

return root_file_imports

def _create_directory_structure(self) -> None:
"""Create the output directory structure"""
# Create main directories
Expand Down Expand Up @@ -810,6 +826,11 @@ def _generate_server(self) -> None:
"",
]

# Add imports for root files
root_file_imports = self._generate_root_file_imports()
if root_file_imports:
imports.extend(root_file_imports)

# Add auth imports if auth is configured
if auth_components.get("has_auth"):
imports.extend(auth_components["imports"])
Expand Down Expand Up @@ -1575,6 +1596,17 @@ def build_project(
shutil.copy2(health_path, output_dir)
console.print(get_status_text("success", "Health script copied to build directory"))

# Copy any additional Python files from project root
discovered_root_files = discover_root_files(project_path)

for filename, file_path in discovered_root_files.items():
dest_path = output_dir / filename
try:
shutil.copy2(file_path, dest_path)
console.print(get_status_text("success", f"Root file {filename} copied to build directory"))
except (OSError, shutil.Error) as e:
console.print(f"[red]Error copying {filename}: {e}[/red]")

# Create a simple README
readme_content = f"""# {settings.name}

Expand Down Expand Up @@ -1674,6 +1706,86 @@ def build_project(
)


def discover_root_files(project_path: Path) -> dict[str, Path]:
"""Automatically discover all Python files in the project root directory.

This function finds all .py files in the project root, excluding:
- Special Golf files (startup.py, health.py, readiness.py, auth.py, server.py)
- Component directories (tools/, resources/, prompts/)
- Hidden files and common exclusions (__pycache__, .git, etc.)

Args:
project_path: Path to the project root directory

Returns:
Dictionary mapping filenames to their full paths
"""
import ast

discovered_files = {}

# Files that are handled specially by Golf and should not be auto-copied
reserved_files = {
"startup.py",
"health.py",
"readiness.py",
"auth.py",
"server.py",
"pre_build.py", # Legacy auth file
"golf.json",
"golf.toml", # Config files
"__init__.py", # Package files
}

# Find all .py files in the project root (not in subdirectories)
try:
for file_path in project_path.iterdir():
if not file_path.is_file():
continue

filename = file_path.name

# Skip non-Python files
if not filename.endswith(".py"):
continue

# Skip reserved/special files
if filename in reserved_files:
continue

# Skip hidden files and temporary files
if filename.startswith(".") or filename.startswith("_") or filename.endswith("~"):
continue

# Validate it's a readable Python file
try:
with open(file_path, encoding="utf-8") as f:
# Read first 200 chars to validate it's a proper Python file
content = f.read(200)

# Basic Python syntax validation
try:
ast.parse(content + "\n# truncated for validation")
except SyntaxError:
# Still include files with syntax errors, but warn
console.print(f"[yellow]Warning: {filename} has syntax issues but will be included[/yellow]")

except (OSError, UnicodeDecodeError) as e:
console.print(f"[yellow]Warning: Cannot read {filename}, skipping: {e}[/yellow]")
continue

discovered_files[filename] = file_path

except OSError as e:
console.print(f"[yellow]Warning: Error scanning project directory: {e}[/yellow]")

if discovered_files:
file_list = ", ".join(sorted(discovered_files.keys()))
console.print(f"[dim]Found root Python files: {file_list}[/dim]")

return discovered_files


# Legacy function removed - replaced by parse_shared_files in parser module


Expand Down
138 changes: 137 additions & 1 deletion tests/core/test_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import json
from unittest.mock import patch

from golf.core.builder import build_manifest, ManifestBuilder, CodeGenerator
from golf.core.builder import build_manifest, ManifestBuilder, CodeGenerator, discover_root_files, build_project
from golf.core.config import load_settings
from golf.core.parser import ComponentType, parse_project

Expand Down Expand Up @@ -1837,3 +1837,139 @@ def simple_tool() -> Output:
assert "path=" not in server_content_212
assert 'transport="stdio"' in server_content_212
assert "mcp.run(" in server_content_212


class TestAutomaticRootFileDiscovery:
"""Test automatic discovery and inclusion of root-level Python files."""

def test_discover_root_files_finds_custom_files(self, sample_project: Path) -> None:
"""Test that discover_root_files finds custom Python files in project root."""
# Create some custom root files
(sample_project / "env.py").write_text("API_KEY = 'test'")
(sample_project / "config.py").write_text("DEBUG = True")
(sample_project / "utils.py").write_text("def helper(): pass")

discovered = discover_root_files(sample_project)

assert "env.py" in discovered
assert "config.py" in discovered
assert "utils.py" in discovered
assert discovered["env.py"] == sample_project / "env.py"

def test_discover_root_files_excludes_reserved_files(self, sample_project: Path) -> None:
"""Test that reserved/special files are excluded from discovery."""
# Create reserved files that should be excluded
(sample_project / "startup.py").write_text("print('startup')")
(sample_project / "auth.py").write_text("# auth config")
(sample_project / "server.py").write_text("# should not be included")
(sample_project / "__init__.py").write_text("# package file")

# Create files that should be included
(sample_project / "custom.py").write_text("# custom file")

discovered = discover_root_files(sample_project)

# Should exclude reserved files
assert "startup.py" not in discovered
assert "auth.py" not in discovered
assert "server.py" not in discovered
assert "__init__.py" not in discovered

# Should include custom files
assert "custom.py" in discovered

def test_discover_root_files_excludes_hidden_and_temp_files(self, sample_project: Path) -> None:
"""Test that hidden and temporary files are excluded."""
# Create files that should be excluded
(sample_project / ".hidden.py").write_text("# hidden")
(sample_project / "_private.py").write_text("# private")
(sample_project / "backup.py~").write_text("# backup")

# Create file that should be included
(sample_project / "visible.py").write_text("# visible")

discovered = discover_root_files(sample_project)

# Should exclude hidden/temp files
assert ".hidden.py" not in discovered
assert "_private.py" not in discovered
assert "backup.py~" not in discovered

# Should include visible file
assert "visible.py" in discovered

def test_root_files_automatically_copied_during_build(self, sample_project: Path, temp_dir: Path) -> None:
"""Test that discovered root files are automatically copied during build."""
# Create custom root files
(sample_project / "constants.py").write_text("API_URL = 'https://api.example.com'")
(sample_project / "helpers.py").write_text("def format_date(): pass")

# Build project
settings = load_settings(sample_project)
output_dir = temp_dir / "build"
build_project(sample_project, settings, output_dir)

# Verify files were automatically copied
assert (output_dir / "constants.py").exists()
assert (output_dir / "helpers.py").exists()
assert (output_dir / "constants.py").read_text() == "API_URL = 'https://api.example.com'"

def test_root_files_automatically_imported_in_server(self, sample_project: Path, temp_dir: Path) -> None:
"""Test that discovered root files are automatically imported in generated server.py."""
# Create root files
(sample_project / "environment.py").write_text("ENV = 'production'")
(sample_project / "settings.py").write_text("DEBUG = False")

# Generate server
settings = load_settings(sample_project)
generator = CodeGenerator(sample_project, settings, temp_dir)
generator.generate()

# Verify imports in generated server.py
server_content = (temp_dir / "server.py").read_text()
assert "import environment" in server_content
assert "import settings" in server_content
assert "# Import root-level Python files" in server_content

def test_components_can_use_auto_discovered_root_files(self, sample_project: Path, temp_dir: Path) -> None:
"""Test that components can import and use automatically discovered root files."""
# Create root file with shared constants
(sample_project / "shared.py").write_text('''
API_ENDPOINT = "https://api.service.com"
TIMEOUT = 30
VERSION = "1.0"
''')

# Create component that uses the shared constants
tool_code = '''"""Tool that uses shared constants."""
import shared

def run():
return f"Connecting to {shared.API_ENDPOINT} v{shared.VERSION} with {shared.TIMEOUT}s timeout"

export = run
'''
(sample_project / "tools" / "api_tool.py").write_text(tool_code)

# Build project
settings = load_settings(sample_project)
output_dir = temp_dir / "build_output"
build_project(sample_project, settings, output_dir)

# Verify shared.py was copied
shared_file = output_dir / "shared.py"
assert shared_file.exists()
assert "API_ENDPOINT" in shared_file.read_text()

# Verify the import is in the server file
server_content = (output_dir / "server.py").read_text()
assert "import shared" in server_content

def test_handles_syntax_errors_gracefully(self, sample_project: Path) -> None:
"""Test that files with syntax errors are still included but generate warnings."""
# Create file with syntax error
(sample_project / "broken.py").write_text("invalid python syntax +++")

# Should still discover the file
discovered = discover_root_files(sample_project)
assert "broken.py" in discovered
0