Skip to content

Open-source Revit MCP server: let Claude and other AI assistants read and edit BIM models, with human approval on every change.

feat(hub): implement Plugin Module Registry discovery, I/O verification, validate/on_result hooks, and hello-world module

A. Sam Mohammade4b1333c484d
diff --git a/docs/module-authoring.md b/docs/module-authoring.md
new file mode 100644
index 0000000..ccfc04f
--- /dev/null
+++ b/docs/module-authoring.md
@@ -0,0 +1,70 @@
+# Developer Guide: Module Authoring
+
+Modules in AEC Model Bridge allow developers and firms to package commands, workflows, schemas, and QA rules.
+
+## 1. Directory Structure
+
+A module folder must reside either:
+- **Built-in**: `packages/mcp-server-revit/src/revit_mcp_server/modules/<module_id>/`
+- **User/Firm Folder** (if `enable_user_modules` is `True`): `%LOCALAPPDATA%\AECModelBridge\modules\<module_id>\`
+- **Installed Package**: Declared as `aec_model_bridge.modules` entry points.
+
+```
+<module_id>/
+├── module.json # Manifest (required)
+├── module.py # Python commands & hooks (optional)
+├── rules/ # QA/QC YAML rule definitions (optional)
+└── ui/ # HTML panel components (optional)
+```
+
+## 2. Manifest Schema (`module.json`)
+
+```json
+{
+ "id": "hello_world",
+ "name": "Hello World Module",
+ "version": "1.0.0",
+ "schema_version": 1,
+ "min_hub_version": "1.2.0",
+ "description": "A demo module.",
+ "author": "AEC Model Bridge",
+ "license": "GPL-3.0-or-later",
+ "requires_providers": ["revit"],
+ "permissions": ["model.read"],
+ "commands": [
+ {
+ "id": "say_hello",
+ "title": "Say Hello",
+ "surface": ["mcp"],
+ "execution_mode": "sync",
+ "is_mutating": false,
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "name": {"type": "string", "default": "World"}
+ },
+ "required": ["name"]
+ }
+ }
+ ],
+ "hooks": {
+ "validate": "module:HelloWorldModule.validate",
+ "on_result": "module:HelloWorldModule.on_result"
+ }
+}
+```
+
+## 3. Permissions
+
+Permissions declared in the manifest are verified at dispatch time:
+- `model.read`: Standard read tools.
+- `model.write`: Mutating tools (always checked against the ActionPlan approval gate).
+- `model.delete`: Destructive operations.
+- `workspace.write`: Restricted sandboxed files output.
+- `net.local` / `net.cloud`: Local connection vs cloud synchronizations.
+- `python.host`: Raw python escapes (e.g. `revit_execute_python`). Disabled unless `allow_python_host` is explicitly `True`.
+
+## 4. Hook Evaluation
+
+- **`validate` hook**: Called before execution. Returns `{"ok": true}` or `{"blockers": ["Details"]}` to reject execution.
+- **`on_result` hook**: Called after execution asynchronously.
diff --git a/docs/tools-generated.md b/docs/tools-generated.md
index f92a4ef..302d4c8 100644
--- a/docs/tools-generated.md
+++ b/docs/tools-generated.md
@@ -66,6 +66,13 @@ This catalog lists all tools exposed by the AEC Model Bridge providers.
*No tools available for this provider.*
+## Module Provider
+
+| Tool Name | Description | Mutating? | Execution Type |
+| --- | --- | --- | --- |
+| `hello_world_say_hello` | Say Hello. | No | sync |
+| `module_list_commands` | List all registered modules and their commands for dockable panels. | No | sync |
+
## Navisworks Provider
| Tool Name | Description | Mutating? | Execution Type |
diff --git a/packages/mcp-server-revit/scripts/generate_tool_docs.py b/packages/mcp-server-revit/scripts/generate_tool_docs.py
index e4ce6cf..d89f9b6 100644
--- a/packages/mcp-server-revit/scripts/generate_tool_docs.py
+++ b/packages/mcp-server-revit/scripts/generate_tool_docs.py
@@ -27,7 +27,10 @@ from revit_mcp_server.providers import (
AutodeskDataProvider,
NavisworksProvider,
ApprovalProvider,
+ ModuleProvider,
)
+from revit_mcp_server.module_registry import ModuleRegistry
+from revit_mcp_server.config import config
try:
from revit_mcp_server.providers import McpProxyProvider
@@ -61,7 +64,12 @@ def main():
except Exception as e:
provider_instances.append((name, None, str(e)))
+ # Initialize module registry and provider
+ mod_registry = ModuleRegistry(config_obj=config)
+ mod_registry.discover_and_load()
+
add_provider("Approval", lambda: ApprovalProvider(workspace=workspace, registry=registry))
+ add_provider("Module", lambda: ModuleProvider(module_registry=mod_registry, workspace=workspace))
add_provider("Revit", lambda: RevitProvider(workspace=workspace))
add_provider("IFC", lambda: IfcProvider(workspace=workspace))
add_provider("AEC Mapper", lambda: AECMapperProvider(workspace=workspace))
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/config.py b/packages/mcp-server-revit/src/revit_mcp_server/config.py
index 91b5713..b11e0e0 100644
--- a/packages/mcp-server-revit/src/revit_mcp_server/config.py
+++ b/packages/mcp-server-revit/src/revit_mcp_server/config.py
@@ -54,6 +54,8 @@ class Config(BaseSettings):
audit_log: Path = Field(default_factory=lambda: Path("audit.log"))
log_level: str = Field("INFO")
approval_mode: str = Field(default="required")
+ enable_user_modules: bool = Field(default=False)
+ allow_python_host: bool = Field(default=False)
model_config = SettingsConfigDict(
env_prefix="MCP_REVIT_",
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/mcp_server.py b/packages/mcp-server-revit/src/revit_mcp_server/mcp_server.py
index 0ec743b..2066ee7 100644
--- a/packages/mcp-server-revit/src/revit_mcp_server/mcp_server.py
+++ b/packages/mcp-server-revit/src/revit_mcp_server/mcp_server.py
@@ -29,7 +29,9 @@ from .providers import (
McpProxyProvider,
NavisworksProvider,
ApprovalProvider,
+ ModuleProvider,
)
+from .module_registry import ModuleRegistry
from .security.workspace import WorkspaceMonitor
from .security.audit import redact_data
from .jobs import JobManager
@@ -52,6 +54,11 @@ registry.register(AECMapperProvider(workspace=workspace))
registry.register(SQLiteExporterProvider(workspace=workspace, registry=registry))
registry.register(NavisworksProvider(workspace=workspace))
+# Initialize and register Module registry and Module provider
+module_registry = ModuleRegistry(config_obj=config)
+module_registry.discover_and_load()
+registry.register(ModuleProvider(module_registry=module_registry, workspace=workspace))
+
# Initialize Job Manager and Job Provider
job_manager = JobManager()
registry.register(JobProvider(manager=job_manager))
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/module_registry.py b/packages/mcp-server-revit/src/revit_mcp_server/module_registry.py
new file mode 100644
index 0000000..a7a8761
--- /dev/null
+++ b/packages/mcp-server-revit/src/revit_mcp_server/module_registry.py
@@ -0,0 +1,200 @@
+from __future__ import annotations
+
+import json
+import logging
+import os
+import sys
+import importlib.util
+from pathlib import Path
+from typing import Any, Callable, Dict, List, Optional
+from pydantic import BaseModel, Field
+
+from revit_mcp_server.errors import BridgeError
+
+logger = logging.getLogger(__name__)
+
+class CommandSpec(BaseModel):
+ id: str
+ title: str
+ surface: List[str] = Field(default_factory=lambda: ["mcp"])
+ mcp_tool: Optional[str] = None
+ execution_mode: str = "sync" # "sync" | "async"
+ is_mutating: bool = False
+ destructive: bool = False
+ requires_plan: bool = False
+ input_schema: Optional[Dict[str, Any]] = None
+ output_schema: Optional[Dict[str, Any]] = None
+ permissions: List[str] = Field(default_factory=list)
+
+class ModuleManifest(BaseModel):
+ id: str
+ name: str
+ version: str
+ schema_version: int = 1
+ min_hub_version: str = "1.2.0"
+ requires_providers: List[str] = Field(default_factory=list)
+ requires_tools: List[str] = Field(default_factory=list)
+ permissions: List[str] = Field(default_factory=list)
+ commands: List[CommandSpec] = Field(default_factory=list)
+ ui: Optional[Dict[str, Any]] = None
+ hooks: Optional[Dict[str, str]] = None
+
+class ModuleInstance:
+ def __init__(self, manifest: ModuleManifest, directory: Path):
+ self.manifest = manifest
+ self.directory = directory
+ self.code_module = None
+ self.class_instance = None
+
+ py_path = directory / "module.py"
+ if py_path.exists():
+ try:
+ spec = importlib.util.spec_from_file_location(
+ f"revit_mcp_server.modules.{manifest.id}", py_path
+ )
+ if spec and spec.loader:
+ mod = importlib.util.module_from_spec(spec)
+ sys.modules[f"revit_mcp_server.modules.{manifest.id}"] = mod
+ spec.loader.exec_module(mod)
+ self.code_module = mod
+
+ # Instantiate singleton class instance if dynamic class hook pattern is used
+ cls_name = "".join(x.capitalize() for x in manifest.id.split("_")) + "Module"
+ cls = getattr(mod, cls_name, None)
+ if cls and isinstance(cls, type):
+ self.class_instance = cls()
+ except Exception as e:
+ logger.error(f"Failed to load Python code for module '{manifest.id}': {e}")
+
+ def get_hook_callable(self, hook_name: str) -> Optional[Callable[..., Any]]:
+ if not self.manifest.hooks:
+ return None
+ hook_str = self.manifest.hooks.get(hook_name)
+ if not hook_str or not hook_str.startswith("module:"):
+ return None
+
+ path = hook_str[len("module:"):]
+ parts = path.split(".")
+
+ # Resolve from code module
+ if not self.code_module:
+ return None
+
+ if len(parts) == 1:
+ # Simple function at module level
+ return getattr(self.code_module, parts[0], None)
+ elif len(parts) == 2:
+ # Class method/instance method
+ cls_name, method_name = parts
+ if self.class_instance and self.class_instance.__class__.__name__ == cls_name:
+ return getattr(self.class_instance, method_name, None)
+
+ # Fallback check if the class exists on code_module
+ cls = getattr(self.code_module, cls_name, None)
+ if cls and isinstance(cls, type):
+ if not self.class_instance or not isinstance(self.class_instance, cls):
+ try:
+ self.class_instance = cls()
+ except Exception as e:
+ logger.error(f"Failed to instantiate hook class {cls_name}: {e}")
+ return None
+ return getattr(self.class_instance, method_name, None)
+
+ return None
+
+class ModuleRegistry:
+ def __init__(self, config_obj: Any = None):
+ self.config = config_obj
+ self.modules: Dict[str, ModuleInstance] = {}
+
+ def discover_and_load(self) -> None:
+ self.modules.clear()
+
+ # 1. Load built-in modules
+ built_in_dir = Path(__file__).parent / "modules"
+ if built_in_dir.exists() and built_in_dir.is_dir():
+ for child in built_in_dir.iterdir():
+ if child.is_dir() and (child / "module.json").exists():
+ self._load_module_dir(child, "built-in")
+
+ # 2. Load Entry Points
+ try:
+ # Python 3.10+ entry points API
+ import importlib.metadata
+ eps = importlib.metadata.entry_points(group="aec_model_bridge.modules")
+ for ep in eps:
+ try:
+ # An entry point can return a path string or a module path
+ module_path = ep.load()
+ if isinstance(module_path, str):
+ path = Path(module_path)
+ elif hasattr(module_path, "__file__") and module_path.__file__:
+ path = Path(module_path.__file__).parent
+ else:
+ continue
+ if path.exists() and (path / "module.json").exists():
+ self._load_module_dir(path, "entry-point")
+ except Exception as e:
+ logger.error(f"Failed to load module entry point '{ep.name}': {e}")
+ except Exception as e:
+ logger.warning(f"Error resolving entry points: {e}")
+
+ # 3. Load User modules if enabled
+ enable_user = getattr(self.config, "enable_user_modules", False)
+ if enable_user:
+ local_app_data = os.getenv("LOCALAPPDATA")
+ if local_app_data:
+ user_modules_dir = Path(local_app_data) / "AECModelBridge" / "modules"
+ else:
+ user_modules_dir = Path.home() / "AppData" / "Local" / "AECModelBridge" / "modules"
+
+ if user_modules_dir.exists() and user_modules_dir.is_dir():
+ for child in user_modules_dir.iterdir():
+ if child.is_dir() and (child / "module.json").exists():
+ self._load_module_dir(child, "user")
+ else:
+ logger.info("User modules directory scanning is disabled in configuration.")
+
+ def _load_module_dir(self, directory: Path, source_type: str) -> None:
+ manifest_path = directory / "module.json"
+ try:
+ with open(manifest_path, "r", encoding="utf-8") as f:
+ data = json.load(f)
+
+ manifest = ModuleManifest(**data)
+
+ # Version checks: min_hub_version gate
+ hub_version = "1.2.0"
+ if manifest.min_hub_version:
+ # Basic check: compare major/minor parts
+ try:
+ h_parts = [int(x) for x in hub_version.split(".")]
+ m_parts = [int(x) for x in manifest.min_hub_version.split(".")]
+ if m_parts > h_parts:
+ logger.warning(
+ f"Skipping module '{manifest.id}': requires hub version {manifest.min_hub_version} but running {hub_version}"
+ )
+ return
+ except ValueError:
+ # Ignore invalid semver parsing and skip safety checks if format is weird
+ pass
+
+ # Collision handling
+ if manifest.id in self.modules:
+ logger.warning(
+ f"Collision detected: module ID '{manifest.id}' from {source_type} directory '{directory}' "
+ f"overrides previously loaded module from '{self.modules[manifest.id].directory}'"
+ )
+
+ # Create instance and add
+ self.modules[manifest.id] = ModuleInstance(manifest, directory)
+ logger.info(f"Loaded module '{manifest.id}' from {directory} ({source_type})")
+
+ except Exception as e:
+ logger.error(f"Failed to load module manifest from '{manifest_path}': {e}")
+
+ def get_module(self, module_id: str) -> Optional[ModuleInstance]:
+ return self.modules.get(module_id)
+
+ def get_all_modules(self) -> List[ModuleInstance]:
+ return list(self.modules.values())
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/hello_world/module.json b/packages/mcp-server-revit/src/revit_mcp_server/modules/hello_world/module.json
new file mode 100644
index 0000000..1da250c
--- /dev/null
+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/hello_world/module.json
@@ -0,0 +1,32 @@
+{
+ "id": "hello_world",
+ "name": "Hello World Module",
+ "version": "1.0.0",
+ "schema_version": 1,
+ "min_hub_version": "1.2.0",
+ "description": "A demonstration module showcasing commands, schemas, validation hooks, and permission enforcement.",
+ "author": "AEC Model Bridge",
+ "license": "GPL-3.0-or-later",
+ "requires_providers": ["revit"],
+ "permissions": ["model.read"],
+ "commands": [
+ {
+ "id": "say_hello",
+ "title": "Say Hello",
+ "surface": ["mcp"],
+ "execution_mode": "sync",
+ "is_mutating": false,
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "name": {"type": "string", "default": "World"}
+ },
+ "required": ["name"]
+ }
+ }
+ ],
+ "hooks": {
+ "validate": "module:HelloWorldModule.validate",
+ "on_result": "module:HelloWorldModule.on_result"
+ }
+}
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/hello_world/module.py b/packages/mcp-server-revit/src/revit_mcp_server/modules/hello_world/module.py
new file mode 100644
index 0000000..5f4a1c2
--- /dev/null
+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/hello_world/module.py
@@ -0,0 +1,23 @@
+import logging
+from typing import Dict, Any
+
+logger = logging.getLogger(__name__)
+
+class HelloWorldModule:
+ def validate(self, payload: Dict[str, Any]) -> Dict[str, Any]:
+ # Hook validate logic
+ name = payload.get("name", "")
+ if name.lower() == "blocker":
+ return {"blockers": ["The name 'blocker' is explicitly disallowed."]}
+ elif name.lower() == "warning":
+ return {"warnings": ["Using the name 'warning' triggers a warning."]}
+ return {"ok": True}
+
+ def say_hello(self, name: str) -> Dict[str, Any]:
+ return {
+ "status": "success",
+ "message": f"Hello, {name}!"
+ }
+
+ def on_result(self, payload: Dict[str, Any]) -> None:
+ logger.info(f"HelloWorldModule post-result hook called with: {payload}")
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/providers/__init__.py b/packages/mcp-server-revit/src/revit_mcp_server/providers/__init__.py
index 18f1db6..231723d 100644
--- a/packages/mcp-server-revit/src/revit_mcp_server/providers/__init__.py
+++ b/packages/mcp-server-revit/src/revit_mcp_server/providers/__init__.py
@@ -12,6 +12,7 @@ from .job_provider import JobProvider
from .exporter import SQLiteExporterProvider
from .proxy import McpProxyProvider
from .approval_provider import ApprovalProvider
+from .module_provider import ModuleProvider
__all__ = [
"AECProvider",
@@ -30,4 +31,5 @@ __all__ = [
"SQLiteExporterProvider",
"McpProxyProvider",
"ApprovalProvider",
+ "ModuleProvider",
]
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/providers/module_provider.py b/packages/mcp-server-revit/src/revit_mcp_server/providers/module_provider.py
new file mode 100644
index 0000000..b33f7a2
--- /dev/null
+++ b/packages/mcp-server-revit/src/revit_mcp_server/providers/module_provider.py
@@ -0,0 +1,238 @@
+from __future__ import annotations
+
+import asyncio
+import inspect
+import logging
+from pathlib import Path
+from typing import Any, Callable, Dict, List, Optional
+
+from revit_mcp_server.errors import BridgeError
+from revit_mcp_server.module_registry import ModuleRegistry, ModuleInstance, CommandSpec
+from revit_mcp_server.security.workspace import WorkspaceMonitor
+from .base import AECProvider, ProviderTool
+
+logger = logging.getLogger(__name__)
+
+def validate_json_schema(data: Any, schema: Dict[str, Any], path: str = "root") -> None:
+ if not schema:
+ return
+
+ schema_type = schema.get("type")
+ if schema_type == "object":
+ if not isinstance(data, dict):
+ raise ValueError(f"Value at {path} must be an object/dict")
+ properties = schema.get("properties", {})
+ required = schema.get("required", [])
+ for req in required:
+ if req not in data:
+ prop_schema = properties.get(req, {})
+ if "default" not in prop_schema:
+ raise ValueError(f"Missing required field '{req}' at {path}")
+ else:
+ data[req] = prop_schema["default"]
+
+ for k, v in data.items():
+ if k in properties:
+ validate_json_schema(v, properties[k], f"{path}.{k}")
+
+ elif schema_type == "array":
+ if not isinstance(data, list):
+ raise ValueError(f"Value at {path} must be a list/array")
+ items_schema = schema.get("items")
+ if items_schema:
+ for idx, item in enumerate(data):
+ validate_json_schema(item, items_schema, f"{path}[{idx}]")
+
+ elif schema_type == "string":
+ if not isinstance(data, str):
+ raise ValueError(f"Value at {path} must be a string")
+
+ elif schema_type == "integer":
+ if not isinstance(data, int) or isinstance(data, bool):
+ raise ValueError(f"Value at {path} must be an integer")
+
+ elif schema_type == "number":
+ if not isinstance(data, (int, float)) or isinstance(data, bool):
+ raise ValueError(f"Value at {path} must be a number")
+
+ elif schema_type == "boolean":
+ if not isinstance(data, bool):
+ raise ValueError(f"Value at {path} must be a boolean")
+
+class ModuleProvider(AECProvider):
+ def __init__(self, module_registry: ModuleRegistry, workspace: WorkspaceMonitor):
+ self.registry = module_registry
+ self.workspace = workspace
+
+ def get_identity(self) -> str:
+ return "module"
+
+ def get_capabilities(self) -> List[ProviderTool]:
+ tools = []
+ # Expose the listing tool for panels
+ tools.append(ProviderTool(
+ name="module_list_commands",
+ description="List all registered modules and their commands for dockable panels",
+ inputSchema={"type": "object", "properties": {}, "required": []}
+ ))
+
+ for m in self.registry.get_all_modules():
+ for cmd in m.manifest.commands:
+ # Carry over all metadata
+ tools.append(ProviderTool(
+ name=f"{m.manifest.id}_{cmd.id}",
+ description=cmd.title,
+ inputSchema=cmd.input_schema or {"type": "object", "properties": {}, "required": []},
+ is_mutating=cmd.is_mutating,
+ destructive=cmd.destructive,
+ execution_mode=cmd.execution_mode,
+ permissions=cmd.permissions
+ ))
+ return tools
+
+ async def check_health(self) -> Dict[str, Any]:
+ return {
+ "status": "ok",
+ "loaded_modules_count": len(self.registry.get_all_modules())
+ }
+
+ async def shutdown(self) -> None:
+ pass
+
+ async def execute_tool(self, name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
+ if name == "module_list_commands":
+ return self._list_commands()
+
+ # Resolve target module and command
+ module_inst: Optional[ModuleInstance] = None
+ command_spec: Optional[CommandSpec] = None
+
+ for m in self.registry.get_all_modules():
+ for cmd in m.manifest.commands:
+ if f"{m.manifest.id}_{cmd.id}" == name:
+ module_inst = m
+ command_spec = cmd
+ break
+ if module_inst:
+ break
+
+ if not module_inst or not command_spec:
+ raise BridgeError(f"Module tool '{name}' not found in registry")
+
+ # 1. Enforce permissions
+ required_perms = command_spec.permissions + module_inst.manifest.permissions
+ if "python.host" in required_perms:
+ if not getattr(self.registry.config, "allow_python_host", False):
+ raise BridgeError(
+ f"Permission 'python.host' is required by command '{name}' but disabled in configuration."
+ )
+
+ # 2. Schema Input validation
+ if command_spec.input_schema:
+ try:
+ validate_json_schema(arguments, command_spec.input_schema)
+ except Exception as e:
+ raise BridgeError(f"Input schema validation failed: {e}")
+
+ # 3. Validate hook execution
+ validate_fn = module_inst.get_hook_callable("validate")
+ if validate_fn:
+ try:
+ val_res = await self._run_callable_with_timeout(validate_fn, arguments, timeout=2.0)
+ if isinstance(val_res, dict):
+ blockers = val_res.get("blockers")
+ if blockers:
+ raise BridgeError(f"Validation hook blocked execution: {blockers}")
+ except BridgeError:
+ raise
+ except Exception as e:
+ logger.warning(f"Error running validate hook for '{name}': {e}")
+
+ # 4. Command execution
+ cmd_fn = None
+ if module_inst.class_instance:
+ cmd_fn = getattr(module_inst.class_instance, command_spec.id, None)
+ elif module_inst.code_module:
+ cmd_fn = getattr(module_inst.code_module, command_spec.id, None)
+
+ if not cmd_fn:
+ raise BridgeError(f"Implementation for command '{command_spec.id}' not found in module code")
+
+ # Run execution
+ try:
+ result = await self._run_callable(cmd_fn, arguments)
+ except Exception as e:
+ raise BridgeError(f"Command execution failed: {e}") from e
+
+ # 5. Schema Output validation
+ if command_spec.output_schema and isinstance(result, dict):
+ try:
+ validate_json_schema(result, command_spec.output_schema)
+ except Exception as e:
+ logger.warning(f"Output schema validation failed: {e}")
+
+ # 6. on_result hook execution
+ result_fn = module_inst.get_hook_callable("on_result")
+ if result_fn:
+ try:
+ # Run hook in the background safely
+ asyncio.create_task(
+ self._run_callable_with_timeout(result_fn, {"arguments": arguments, "result": result}, timeout=2.0)
+ )
+ except Exception as e:
+ logger.warning(f"Error queuing on_result hook: {e}")
+
+ return result
+
+ def _list_commands(self) -> Dict[str, Any]:
+ module_list = []
+ for m in self.registry.get_all_modules():
+ cmd_list = []
+ for cmd in m.manifest.commands:
+ cmd_list.append({
+ "id": cmd.id,
+ "title": cmd.title,
+ "surface": cmd.surface,
+ "execution_mode": cmd.execution_mode,
+ "is_mutating": cmd.is_mutating,
+ "destructive": cmd.destructive,
+ "requires_plan": cmd.requires_plan
+ })
+ module_list.append({
+ "id": m.manifest.id,
+ "name": m.manifest.name,
+ "version": m.manifest.version,
+ "description": getattr(m.manifest, "description", ""),
+ "commands": cmd_list,
+ "ui": m.manifest.ui
+ })
+ return {"modules": module_list}
+
+ async def _run_callable(self, func: Callable[..., Any], arguments: Dict[str, Any]) -> Any:
+ sig = inspect.signature(func)
+ kwargs = {}
+ for param_name, param in sig.parameters.items():
+ if param_name in ("payload", "arguments"):
+ kwargs[param_name] = arguments
+ elif param_name == "workspace":
+ kwargs[param_name] = self.workspace
+ elif param_name in arguments:
+ kwargs[param_name] = arguments[param_name]
+
+ if not kwargs and len(sig.parameters) > 0:
+ if inspect.iscoroutinefunction(func):
+ return await func(arguments)
+ else:
+ return await asyncio.get_running_loop().run_in_executor(None, func, arguments)
+
+ if inspect.iscoroutinefunction(func):
+ return await func(**kwargs)
+ else:
+ return await asyncio.get_running_loop().run_in_executor(None, lambda: func(**kwargs))
+
+ async def _run_callable_with_timeout(self, func: Callable[..., Any], *args, timeout: float = 2.0) -> Any:
+ try:
+ return await asyncio.wait_for(self._run_callable(func, *args), timeout=timeout)
+ except asyncio.TimeoutError:
+ logger.warning(f"Timeout budget exceeded during hook execution ({timeout}s)")
+ return None
diff --git a/packages/mcp-server-revit/tests/test_module_registry.py b/packages/mcp-server-revit/tests/test_module_registry.py
new file mode 100644
index 0000000..53a0cc1
--- /dev/null
+++ b/packages/mcp-server-revit/tests/test_module_registry.py
@@ -0,0 +1,68 @@
+import pytest
+from pathlib import Path
+from revit_mcp_server.config import Config
+from revit_mcp_server.module_registry import ModuleRegistry
+from revit_mcp_server.providers.module_provider import ModuleProvider
+from revit_mcp_server.security.workspace import WorkspaceMonitor
+from revit_mcp_server.errors import BridgeError
+
+def test_module_registry_discovery(tmp_path):
+ cfg = Config(
+ workspace_dir=tmp_path,
+ allowed_directories=[tmp_path],
+ audit_log=tmp_path / "audit.log",
+ enable_user_modules=False
+ )
+ registry = ModuleRegistry(config_obj=cfg)
+ registry.discover_and_load()
+
+ # Assert Hello World is loaded
+ hello = registry.get_module("hello_world")
+ assert hello is not None
+ assert hello.manifest.name == "Hello World Module"
+
+async def test_module_provider_execution(tmp_path):
+ cfg = Config(
+ workspace_dir=tmp_path,
+ allowed_directories=[tmp_path],
+ audit_log=tmp_path / "audit.log",
+ enable_user_modules=False
+ )
+ registry = ModuleRegistry(config_obj=cfg)
+ registry.discover_and_load()
+
+ workspace = WorkspaceMonitor([tmp_path])
+ provider = ModuleProvider(module_registry=registry, workspace=workspace)
+
+ # Check capabilities list
+ caps = provider.get_capabilities()
+ cap_names = [c.name for c in caps]
+ assert "hello_world_say_hello" in cap_names
+ assert "module_list_commands" in cap_names
+
+ # 1. Execute success case
+ res = await provider.execute_tool("hello_world_say_hello", {"name": "Antigravity"})
+ assert res["status"] == "success"
+ assert "Hello, Antigravity!" in res["message"]
+
+ # 2. Execute default case (applies default input value)
+ res_default = await provider.execute_tool("hello_world_say_hello", {})
+ assert res_default["status"] == "success"
+ assert "Hello, World!" in res_default["message"]
+
+ # 3. Execute blocker case via validate hook
+ with pytest.raises(BridgeError) as exc_info:
+ await provider.execute_tool("hello_world_say_hello", {"name": "blocker"})
+ assert "blocked execution" in str(exc_info.value)
+
+ # 4. Schema validation failure
+ with pytest.raises(BridgeError) as exc_info:
+ await provider.execute_tool("hello_world_say_hello", {"name": 1234}) # integer, not string
+ assert "validation failed" in str(exc_info.value).lower()
+
+ # 5. List commands tool
+ list_res = await provider.execute_tool("module_list_commands", {})
+ assert "modules" in list_res
+ assert len(list_res["modules"]) >= 1
+ assert list_res["modules"][0]["id"] == "hello_world"