Open-source Revit MCP server: let Claude and other AI assistants read and edit BIM models, with human approval on every change.
Python aecai-agentsautodeskautomationbimclaudeifcmcpmcp-servermodel-context-protocolnavisworksrevitrevit-addinrevit-apirhino
feat: zero-config first run and one-click install links
sammohammad5783acad065d103
diff --git a/README.md b/README.mdindex 80b1794..1c5b4a1 100644--- a/README.md+++ b/README.md@@ -71,10 +71,25 @@ direct Revit tools above for live inspection. [Planned fixes and demo](docs/road## Quick start+**One-click install**++[](docs/install-buttons.md#vs-code)+[](https://cursor.com/en/install-mcp?name=aec-model-bridge&config=eyJjb21tYW5kIjoidXZ4IiwiYXJncyI6WyItLWZyb20iLCJnaXQraHR0cHM6Ly9naXRodWIuY29tL1NhbS1BRUMvYWVjLW1vZGVsLWJyaWRnZSNzdWJkaXJlY3Rvcnk9cGFja2FnZXMvbWNwLXNlcnZlci1yZXZpdCIsImFlYy1tb2RlbC1icmlkZ2UiXSwiZW52Ijp7Ik1DUF9SRVZJVF9NT0RFIjoiYnJpZGdlIn19)+[](https://github.com/Sam-AEC/aec-model-bridge/releases/latest)++The buttons need [uv](https://docs.astral.sh/uv/getting-started/installation/)+and no other setup: the server uses `~/Documents/AEC Model Bridge` as its+workspace unless you set your own. For Claude Desktop, download the `.mcpb`+file from the latest release and open it. Live Revit work still needs Revit and+[the add-in](#install-the-revit-add-in); mock mode needs nothing.++**Manual setup**+For live Revit automation you need Windows, a licensed Revit 2024 to 2027,Python 3.11 or newer, [uv](https://docs.astral.sh/uv/getting-started/installation/), and the Revit add-in([install steps](#install-the-revit-add-in)). Then add this to your-`claude_desktop_config.json` (Codex, Cursor and VS Code use the same values):+`claude_desktop_config.json` (Codex, Cursor and VS Code use the same values;+the two directory variables are optional and default to the workspace above):```json{diff --git a/docs/configuration-reference.md b/docs/configuration-reference.mdindex 7918652..3c45e70 100644--- a/docs/configuration-reference.md+++ b/docs/configuration-reference.md@@ -16,8 +16,8 @@ The server supports two runtime modes:| `MCP_REVIT_MODE` | Yes | `mock` | Selects the active bridge mode. || `MCP_REVIT_BRIDGE_URL` | No | auto-discovered | Explicit URL of the Revit bridge listener. Overrides registry discovery. || `MCP_REVIT_HOST_VERSION` | No | newest live Revit | Revit year to select from the local registry, such as `2024` or `2026`. |-| `MCP_REVIT_ALLOWED_DIRECTORIES` | Yes | none | Semicolon-separated directories the server may access. |-| `MCP_REVIT_WORKSPACE_DIR` | Yes | none | Root directory for generated files and workspace-backed tools. |+| `MCP_REVIT_ALLOWED_DIRECTORIES` | No | the workspace directory | Semicolon-separated directories the server may access. Path-traversal protection applies to exactly this list. An explicit value always wins. |+| `MCP_REVIT_WORKSPACE_DIR` | No | `~/Documents/AEC Model Bridge` | Root directory for generated files and workspace-backed tools. The default folder is created the first time the server needs it (never at import), so a one-click install works with no configuration. || `MCP_REVIT_AUDIT_LOG` | No | `workspace/audit.jsonl` | Audit log path used by the security layer. || `MCP_REVIT_ANTHROPIC_API_KEY` | No | unset | Anthropic API key for the panel's native Claude chat (`agent_native.py`, ADR 0012). If you don't set it, "Claude" chat falls back to the `claude` CLI when that's on PATH. Otherwise no AI provider is available. You can also put it in a `.env` file. The hub reads it only at startup, so restart Revit after you set or change it. The panel's Settings view can't set it. || `REVIT_SDK` | Build only | unset | Optional path used by the add-in build scripts. |diff --git a/docs/install-buttons.md b/docs/install-buttons.mdnew file mode 100644index 0000000..97fafd5--- /dev/null+++ b/docs/install-buttons.md@@ -0,0 +1,77 @@+# Install buttons++How the one-click install links in the README are built. Regenerate every+link with:++```text+python scripts/make_install_links.py # print them+python scripts/make_install_links.py --json # as JSON+python scripts/make_install_links.py --check # fail if README.md is out of date+```++`packages/mcp-server-revit/tests/test_install_links.py` decodes each link back+to JSON and compares it with the server entry below.++## The server entry++Same shape as an `mcpServers` entry in `claude_desktop_config.json`. No+directory variables are needed: the workspace defaults to+`~/Documents/AEC Model Bridge`.++```json+{"command":"uvx","args":["--from","git+https://github.com/Sam-AEC/aec-model-bridge#subdirectory=packages/mcp-server-revit","aec-model-bridge"],"env":{"MCP_REVIT_MODE":"bridge"}}+```++## VS Code++Official format ([VS Code MCP extension guide](https://code.visualstudio.com/api/extension-guides/ai/mcp)):+`vscode:mcp/install?` followed by `encodeURIComponent(JSON.stringify({name, ...server}))`.+Insiders uses `vscode-insiders:mcp/install?`. It can be opened from a browser+address bar or from a shell.++```text+vscode:mcp/install?%7B%22name%22%3A%22aec-model-bridge%22%2C%22command%22%3A%22uvx%22%2C%22args%22%3A%5B%22--from%22%2C%22git%2Bhttps%3A%2F%2Fgithub.com%2FSam-AEC%2Faec-model-bridge%23subdirectory%3Dpackages%2Fmcp-server-revit%22%2C%22aec-model-bridge%22%5D%2C%22env%22%3A%7B%22MCP_REVIT_MODE%22%3A%22bridge%22%7D%7D+```++Command-line alternative, documented in the+[VS Code MCP servers guide](https://code.visualstudio.com/docs/copilot/customization/mcp-servers)+(bash or cmd quoting):++```text+code --add-mcp "{\"name\":\"aec-model-bridge\",\"command\":\"uvx\",\"args\":[\"--from\",\"git+https://github.com/Sam-AEC/aec-model-bridge#subdirectory=packages/mcp-server-revit\",\"aec-model-bridge\"],\"env\":{\"MCP_REVIT_MODE\":\"bridge\"}}"+```++Why the README badge points here and not straight at the link: GitHub removes+`vscode:` and `cursor:` hrefs from rendered Markdown. The usual workaround is+the `https://vscode.dev/redirect/mcp/install?name=...&config=<encoded JSON>`+redirect (also `insiders.vscode.dev`), which answers 302 to the `vscode:` link.+That form is not in the official docs. For this server it does not work: when+tested, vscode.dev's firewall returned HTTP 403 for any value containing+`https://...#subdirectory=...`. Publishing the package to PyPI would allow a+plain `uvx aec-model-bridge` entry and a working redirect button.++## Cursor++Format ([Cursor deeplinks](https://docs.cursor.com/deeplinks)):++```text+cursor://anysphere.cursor-deeplink/mcp/install?name=<name>&config=<base64 of JSON.stringify(server)>+```++`config` is the server entry above, without `name`, base64-encoded (and+percent-encoded in the URL).++```text+cursor://anysphere.cursor-deeplink/mcp/install?name=aec-model-bridge&config=eyJjb21tYW5kIjoidXZ4IiwiYXJncyI6WyItLWZyb20iLCJnaXQraHR0cHM6Ly9naXRodWIuY29tL1NhbS1BRUMvYWVjLW1vZGVsLWJyaWRnZSNzdWJkaXJlY3Rvcnk9cGFja2FnZXMvbWNwLXNlcnZlci1yZXZpdCIsImFlYy1tb2RlbC1icmlkZ2UiXSwiZW52Ijp7Ik1DUF9SRVZJVF9NT0RFIjoiYnJpZGdlIn19+```++The README badge uses the https form that other MCP projects use because+GitHub strips `cursor:` links:+`https://cursor.com/en/install-mcp?name=<name>&config=<same base64>`. That+https form is not in the Cursor docs I could reach and was not reachable from+the machine used to build it, so check the button once in a browser.++## Claude Desktop++The release workflow attaches a `.mcpb` bundle named with the version, so the+README links to `https://github.com/Sam-AEC/aec-model-bridge/releases/latest`.diff --git a/packages/mcp-server-revit/src/revit_mcp_server/config.py b/packages/mcp-server-revit/src/revit_mcp_server/config.pyindex 0852521..c62ad26 100644--- a/packages/mcp-server-revit/src/revit_mcp_server/config.py+++ b/packages/mcp-server-revit/src/revit_mcp_server/config.py@@ -6,7 +6,7 @@ from pathlib import Pathfrom typing import Listfrom dotenv import load_dotenv-from pydantic import DirectoryPath, Field, field_validator+from pydantic import DirectoryPath, Field, PrivateAttr, field_validator, model_validatorfrom pydantic_settings import BaseSettings, SettingsConfigDictfrom pydantic_settings.sources.providers import env as env_source@@ -45,9 +45,17 @@ class _RawEnvSource(env_source.EnvSettingsSource):return value+def default_workspace_dir() -> Path:+ """Zero-config workspace: ``~/Documents/AEC Model Bridge`` (not created here)."""+ return Path.home() / "Documents" / "AEC Model Bridge"++class Config(BaseSettings):- workspace_dir: Path = Field(...)- allowed_directories: List[DirectoryPath] = Field(...)+ # Both default safely so a one-click install works with no configuration.+ # An explicit MCP_REVIT_* value always wins. The default directory is only+ # created on demand by ensure_workspace(), never at import time.+ workspace_dir: Path = Field(default_factory=default_workspace_dir)+ allowed_directories: List[DirectoryPath] = Field(default_factory=list)bridge_url: str | None = Field(default=None)host_version: str | None = Field(default=None)mode: BridgeMode = Field(default=BridgeMode.mock)@@ -58,6 +66,8 @@ class Config(BaseSettings):allow_python_host: bool = Field(default=False)anthropic_api_key: str | None = Field(default=None)+ _auto_dirs: List[Path] = PrivateAttr(default_factory=list)+model_config = SettingsConfigDict(env_prefix="MCP_REVIT_",case_sensitive=False,@@ -70,6 +80,29 @@ class Config(BaseSettings):return [Path(p.strip()) for p in value.split(";") if p.strip()]return value+ @model_validator(mode="after")+ def _apply_defaults(self):+ auto: List[Path] = []+ if "workspace_dir" not in self.model_fields_set:+ auto.append(self.workspace_dir)+ if "allowed_directories" not in self.model_fields_set:+ # Sandbox stays closed: only the workspace itself is allowed.+ self.allowed_directories = [self.workspace_dir]+ if self.workspace_dir not in auto:+ auto.append(self.workspace_dir)+ self._auto_dirs = auto+ return self++ def ensure_workspace(self) -> None:+ """Create the defaulted workspace directory if it does not exist yet.++ Only directories that came from defaults (the default workspace, or an+ allowed list derived from the workspace) are created; an explicitly+ configured allowed list is never created implicitly.+ """+ for directory in self._auto_dirs:+ directory.mkdir(parents=True, exist_ok=True)+@classmethoddef settings_customise_sources(cls,diff --git a/packages/mcp-server-revit/src/revit_mcp_server/legacy/server.py b/packages/mcp-server-revit/src/revit_mcp_server/legacy/server.pyindex 21f013d..a561506 100644--- a/packages/mcp-server-revit/src/revit_mcp_server/legacy/server.py+++ b/packages/mcp-server-revit/src/revit_mcp_server/legacy/server.py@@ -51,6 +51,8 @@ class MCPServer:unexpected = ", ".join(kwargs)raise TypeError(f"Unexpected keyword argument(s): {unexpected}")self.config = config_obj if config_obj is not None else config+ if hasattr(self.config, "ensure_workspace"):+ self.config.ensure_workspace()self.workspace = WorkspaceMonitor(self.config.allowed_directories)self.audit = AuditRecorder(self.config.audit_log)diff --git a/packages/mcp-server-revit/src/revit_mcp_server/registry_factory.py b/packages/mcp-server-revit/src/revit_mcp_server/registry_factory.pyindex fa6c282..8c95fe7 100644--- a/packages/mcp-server-revit/src/revit_mcp_server/registry_factory.py+++ b/packages/mcp-server-revit/src/revit_mcp_server/registry_factory.py@@ -50,6 +50,7 @@ def build_registry(test's plans/snapshots from being written into a shared directory."""if workspace is None:+ config.ensure_workspace() # creates the default workspace on first use onlyworkspace = WorkspaceMonitor(config.allowed_directories)registry = ProviderRegistry()diff --git a/packages/mcp-server-revit/tests/test_config.py b/packages/mcp-server-revit/tests/test_config.pyindex d815943..9a59c3f 100644--- a/packages/mcp-server-revit/tests/test_config.py+++ b/packages/mcp-server-revit/tests/test_config.py@@ -1,5 +1,9 @@+import pytestfrom revit_mcp_server.config import Config+from revit_mcp_server.errors import WorkspaceViolation+from revit_mcp_server.registry_factory import build_registry+from revit_mcp_server.security.workspace import WorkspaceMonitordef test_config_reads_env(monkeypatch, tmp_path):@@ -8,3 +12,74 @@ def test_config_reads_env(monkeypatch, tmp_path):cfg = Config()assert cfg.workspace_dir == tmp_pathassert tmp_path in cfg.allowed_directories+++def zero_config(monkeypatch, tmp_path):+ """No MCP_REVIT_* directory env vars, and a fake home so nothing touches the real one."""+ monkeypatch.delenv("MCP_REVIT_WORKSPACE_DIR", raising=False)+ monkeypatch.delenv("MCP_REVIT_ALLOWED_DIRECTORIES", raising=False)+ monkeypatch.setattr("pathlib.Path.home", classmethod(lambda cls: tmp_path))+ return tmp_path / "Documents" / "AEC Model Bridge"+++def test_defaults_without_env(zero_config):+ cfg = Config()+ assert cfg.workspace_dir == zero_config+ assert cfg.allowed_directories == [zero_config]+++def test_defaults_are_not_created_until_needed(zero_config):+ cfg = Config()+ assert not zero_config.exists() # constructing config has no side effect+ cfg.ensure_workspace()+ assert zero_config.is_dir()+ cfg.ensure_workspace() # idempotent+++def test_build_registry_creates_default_workspace_lazily(zero_config, monkeypatch):+ import revit_mcp_server.registry_factory as rf++ monkeypatch.setattr(rf, "config", Config())+ assert not zero_config.exists()+ workspace = build_registry()[-1]+ assert zero_config.is_dir()+ assert workspace.allowed_directories == [zero_config.resolve()]+++def test_explicit_values_win_and_are_not_created(zero_config, monkeypatch, tmp_path):+ ws = tmp_path / "explicit"+ ws.mkdir()+ monkeypatch.setenv("MCP_REVIT_WORKSPACE_DIR", str(ws))+ monkeypatch.setenv("MCP_REVIT_ALLOWED_DIRECTORIES", str(ws))+ cfg = Config()+ cfg.ensure_workspace()+ assert cfg.workspace_dir == ws+ assert cfg.allowed_directories == [ws]+ assert not zero_config.exists()+++def test_explicit_workspace_only_scopes_allowed_to_it(zero_config, monkeypatch, tmp_path):+ ws = tmp_path / "only_ws"+ monkeypatch.setenv("MCP_REVIT_WORKSPACE_DIR", str(ws))+ cfg = Config()+ assert cfg.allowed_directories == [ws]+ assert not ws.exists() # constructing config creates nothing+ cfg.ensure_workspace()+ assert ws.is_dir() # allowed dir was derived from the workspace, so it is created on demand+++def test_traversal_still_blocked_with_defaults(zero_config):+ cfg = Config()+ cfg.ensure_workspace()+ monitor = WorkspaceMonitor(cfg.allowed_directories)+ assert cfg.workspace_allowed(zero_config / "plans" / "x.json")+ assert monitor.assert_in_workspace(zero_config / "a.json") == (zero_config / "a.json").resolve()+ for bad in (+ zero_config / ".." / "secret.txt",+ zero_config / ".." / ".." / "etc" / "passwd",+ zero_config.parent / "AEC Model Bridge-evil" / "x",+ ):+ assert not cfg.workspace_allowed(bad)+ with pytest.raises(WorkspaceViolation):+ monitor.assert_in_workspace(bad)diff --git a/packages/mcp-server-revit/tests/test_install_links.py b/packages/mcp-server-revit/tests/test_install_links.pynew file mode 100644index 0000000..2c60ce7--- /dev/null+++ b/packages/mcp-server-revit/tests/test_install_links.py@@ -0,0 +1,57 @@+"""Decode the one-click install links back to JSON (see docs/install-buttons.md)."""+import base64+import importlib.util+import json+from pathlib import Path+from urllib.parse import parse_qs, unquote, urlsplit++REPO_ROOT = Path(__file__).resolve().parents[3]+_SCRIPT = REPO_ROOT / "scripts" / "make_install_links.py"+_spec = importlib.util.spec_from_file_location("make_install_links", _SCRIPT)+links = importlib.util.module_from_spec(_spec)+_spec.loader.exec_module(links)+++def test_vscode_deeplink_decodes_to_server_json():+ link = links.vscode_deeplink()+ assert link.startswith("vscode:mcp/install?")+ payload = json.loads(unquote(link.split("?", 1)[1]))+ assert payload == {"name": "aec-model-bridge", **links.SERVER}+ assert payload["command"] == "uvx"+ assert payload["env"] == {"MCP_REVIT_MODE": "bridge"}+ assert "aec-model-bridge" == payload["args"][-1]+++def test_vscode_redirect_decodes_to_server_json():+ parts = urlsplit(links.vscode_redirect())+ assert (parts.scheme, parts.netloc, parts.path) == ("https", "vscode.dev", "/redirect/mcp/install")+ query = parse_qs(parts.query)+ assert query["name"] == ["aec-model-bridge"]+ assert json.loads(query["config"][0]) == links.SERVER+++def test_vscode_cli_json_roundtrips():+ cli = links.vscode_cli()+ prefix = 'code --add-mcp "'+ assert cli.startswith(prefix) and cli.endswith('"')+ payload = json.loads(cli[len(prefix) : -1].replace('\\"', '"'))+ assert payload == {"name": "aec-model-bridge", **links.SERVER}+++def test_cursor_links_decode_to_server_json():+ for link in (links.cursor_deeplink(), links.cursor_web_link()):+ query = parse_qs(urlsplit(link).query)+ assert query["name"] == ["aec-model-bridge"]+ assert json.loads(base64.b64decode(query["config"][0])) == links.SERVER+ assert links.cursor_deeplink().startswith("cursor://anysphere.cursor-deeplink/mcp/install?name=")+++def test_server_needs_no_directory_config():+ assert set(links.SERVER["env"]) == {"MCP_REVIT_MODE"}+++def test_readme_uses_current_links():+ readme = (REPO_ROOT / "README.md").read_text(encoding="utf-8")+ for key in ("cursor_web_link", "claude_desktop_bundle"):+ assert links.all_links()[key] in readme, key+ assert "docs/install-buttons.md#vs-code" in readmediff --git a/scripts/make_install_links.py b/scripts/make_install_links.pynew file mode 100644index 0000000..46821b9--- /dev/null+++ b/scripts/make_install_links.py@@ -0,0 +1,120 @@+#!/usr/bin/env python3+"""Print (or verify) the one-click install links for AEC Model Bridge.++Usage:+ python scripts/make_install_links.py # print every link+ python scripts/make_install_links.py --json # print as JSON+ python scripts/make_install_links.py --check # fail if README.md is out of date++How each link is built is documented in docs/install-buttons.md.+"""+from __future__ import annotations++import argparse+import base64+import json+import sys+from pathlib import Path+from urllib.parse import quote++NAME = "aec-model-bridge"+REPO = "https://github.com/Sam-AEC/aec-model-bridge"+RELEASES_LATEST = f"{REPO}/releases/latest"++# The server entry, same shape as an `mcpServers` entry in claude_desktop_config.json.+SERVER = {+ "command": "uvx",+ "args": [+ "--from",+ f"git+{REPO}#subdirectory=packages/mcp-server-revit",+ "aec-model-bridge",+ ],+ "env": {"MCP_REVIT_MODE": "bridge"},+}+++def _compact(obj: object) -> str:+ return json.dumps(obj, separators=(",", ":"), ensure_ascii=False)+++def vscode_deeplink() -> str:+ """vscode:mcp/install?<encodeURIComponent(JSON.stringify({name, ...server}))>"""+ return "vscode:mcp/install?" + quote(_compact({"name": NAME, **SERVER}), safe="")+++def vscode_redirect() -> str:+ """https redirect (the form other MCP READMEs use); 302s to the vscode: deeplink.++ NOTE: vscode.dev's firewall answers 403 for this server's+ `...#subdirectory=...` argument, so this link is NOT used in the README.+ Kept for when the server is available without a #subdirectory= URL.+ """+ return (+ f"https://vscode.dev/redirect/mcp/install?name={quote(NAME, safe='')}"+ f"&config={quote(_compact(SERVER), safe='')}"+ )+++def vscode_cli() -> str:+ """Documented CLI install: code --add-mcp "<JSON>" (bash/cmd quoting)."""+ escaped = _compact({"name": NAME, **SERVER}).replace('"', '\\"')+ return f'code --add-mcp "{escaped}"'+++def _cursor_config() -> str:+ return base64.b64encode(_compact(SERVER).encode("utf-8")).decode("ascii")+++def cursor_deeplink() -> str:+ """cursor://anysphere.cursor-deeplink/mcp/install?name=<name>&config=<base64 JSON>"""+ return (+ "cursor://anysphere.cursor-deeplink/mcp/install"+ f"?name={quote(NAME, safe='')}&config={quote(_cursor_config(), safe='')}"+ )+++def cursor_web_link() -> str:+ """https link that GitHub keeps (it strips cursor: hrefs)."""+ return (+ f"https://cursor.com/en/install-mcp?name={quote(NAME, safe='')}"+ f"&config={quote(_cursor_config(), safe='')}"+ )+++def all_links() -> dict[str, str]:+ return {+ "vscode_deeplink": vscode_deeplink(),+ "vscode_redirect": vscode_redirect(),+ "vscode_cli": vscode_cli(),+ "cursor_deeplink": cursor_deeplink(),+ "cursor_web_link": cursor_web_link(),+ "claude_desktop_bundle": RELEASES_LATEST,+ }+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ parser.add_argument("--json", action="store_true", help="print links as JSON")+ parser.add_argument("--check", action="store_true", help="verify README.md uses the current links")+ args = parser.parse_args(argv)+ links = all_links()+ if args.check:+ readme = (Path(__file__).resolve().parent.parent / "README.md").read_text(encoding="utf-8")+ stale = [k for k in ("cursor_web_link", "claude_desktop_bundle") if links[k] not in readme]+ if "docs/install-buttons.md#vs-code" not in readme:+ stale.append("vscode_button")+ if stale:+ print("README.md is out of date for: " + ", ".join(stale), file=sys.stderr)+ return 1+ print("README.md install links are current.")+ return 0+ if args.json:+ print(json.dumps(links, indent=2))+ else:+ for key, value in links.items():+ print(f"{key}:\n{value}\n")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/server.json b/server.jsonindex 68d137d..f3f00dc 100644--- a/server.json+++ b/server.json@@ -33,14 +33,14 @@"name": "MCP_REVIT_WORKSPACE_DIR","description": "Workspace root directory for server file operations.","isSecret": false,- "isRequired": true,+ "isRequired": false,"format": "string"},{"name": "MCP_REVIT_ALLOWED_DIRECTORIES","description": "Semicolon-delimited allow-list of directories the server can access.","isSecret": false,- "isRequired": true,+ "isRequired": false,"format": "string"},{