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: implement provider contract tests, fix catalog generation in CI, and clean up task branches
A. Sam Mohammad6506d2ae40ac
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex f98922d..cfa1e74 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -37,6 +37,12 @@ jobs:shell: pwshrun: python -m pytest packages/mcp-server-revit/tests+ - name: Check tool catalog generation+ shell: pwsh+ run: |+ python packages/mcp-server-revit/scripts/generate_tool_docs.py+ git diff --exit-code docs/tools-generated.md+- name: Validate repository metadatashell: pwshrun: |diff --git a/AGENT-TASK-A1.md b/AGENT-TASK-A1.mdnew file mode 100644index 0000000..e9c8231--- /dev/null+++ b/AGENT-TASK-A1.md@@ -0,0 +1,43 @@+# Build Task A1 — Consolidate Speckle to a single provider++You are an autonomous implementation agent for AEC Model Bridge, working in an isolated git worktree on branch `task/A1-speckle`. Complete ONLY task A1, then stop.++## Read first+- `docs/agent-task-plan.md` (card A1) and `docs/system-blueprint-and-workflows.md` §0 + §9 item 1+- `packages/mcp-server-revit/src/revit_mcp_server/providers/speckle.py` (orphaned legacy provider, 2 tools, unregistered)+- `packages/mcp-server-revit/src/revit_mcp_server/providers/cloud.py` (registered SpeckleProvider: OAuth PKCE + GraphQL, 14 tools)+- `packages/mcp-server-revit/src/revit_mcp_server/mcp_server.py`, `tests/test_cloud_providers.py`++## Standing rules (binding)+1. Back-compat: existing `revit_*` tool names, `revit.*` routes, `MCP_REVIT_*` env vars keep working.+2. Mock-first: all tests must pass offline without licensed software; network calls mocked.+3. No secrets/tokens in code, test fixtures, results, or logs.+4. Touch only files this task needs. NEVER edit `docs/agent-task-plan.md` or `AGENT-TASK.md`.+5. Finish with ONE commit on the current branch, message starting `A1: `. Use targeted `git add <paths>` (never `git add -A`). Do not push.++## Environment setup+From repo root:+```+python -m venv packages/mcp-server-revit/.venv+packages/mcp-server-revit/.venv/Scripts/python -m pip install -e "packages/mcp-server-revit[dev]"+```+If `ifcopenshell` has no wheel for this Python, list versions with `py -0p` and recreate the venv with `py -3.12` or `py -3.11`.++## The task+1. Port the uniquely useful behavior from `providers/speckle.py` into the `SpeckleProvider` in `cloud.py`: a zero-OAuth fast path using Speckle Manager local credentials (`specklepy` `get_default_account()`), exposed as new tools `speckle_send_object` and `speckle_receive_object`. If no local account exists, raise a typed error with a clear message (do not return error strings as results).+2. Fix the legacy bug: model *name* must not be passed where a model **ID** is required — resolve name → ID via a models query first (mockable).+3. `speckle_receive_object` must deserialize and return actual object data (not just `get_member_names()`).+4. Replace any error-string-as-success returns with raised typed exceptions consistent with `errors.py` patterns.+5. Delete `providers/speckle.py`; clean up any imports/references (`__init__.py`, tests).+6. Tests (mocked, offline): name→ID resolution; send path; receive deserialization; no-local-account error path. Extend redaction coverage if any new fields could carry tokens.++If the card's description contradicts what you find in the code, follow reality and note the discrepancy in your final summary.++## Verify (must pass before committing)+```+packages/mcp-server-revit/.venv/Scripts/python -m pytest packages/mcp-server-revit/tests -k "speckle or cloud"+packages/mcp-server-revit/.venv/Scripts/python -m pytest packages/mcp-server-revit/tests+```++## Deliverable+Final message: files changed, test counts (passed/failed), discrepancies found, anything deliberately left out of scope.diff --git a/AGENT-TASK-A3.md b/AGENT-TASK-A3.mdnew file mode 100644index 0000000..a47696a--- /dev/null+++ b/AGENT-TASK-A3.md@@ -0,0 +1,41 @@+# Build Task A3 — Fix McpProxyProvider connect lifecycle++You are an autonomous implementation agent for AEC Model Bridge, working in an isolated git worktree on branch `task/A3-proxy`. Complete ONLY task A3, then stop.++## Read first+- `docs/agent-task-plan.md` (card A3) and `docs/system-blueprint-and-workflows.md` §0 + §9 item 2+- `packages/mcp-server-revit/src/revit_mcp_server/providers/proxy.py` — known defect: `_connect()` exists but is never called, so `_connected` stays `False` and every `execute_tool` raises `RuntimeError("ProxyProvider not connected")`+- `providers/base.py` (AECProvider contract), existing tests for patterns++## Standing rules (binding)+1. Back-compat: existing `revit_*` tool names, `revit.*` routes, `MCP_REVIT_*` env vars keep working.+2. Mock-first: all tests pass offline; no real SSE endpoints — use a fake/in-process server or stubbed transport.+3. No secrets/tokens in code, results, or logs.+4. Touch only files this task needs. **Scope guard:** do NOT register the provider in `mcp_server.py` — that is task A4, not yours. NEVER edit `docs/agent-task-plan.md` or `AGENT-TASK.md`.+5. Finish with ONE commit on the current branch, message starting `A3: `. Targeted `git add <paths>` only. Do not push.++## Environment setup+From repo root:+```+python -m venv packages/mcp-server-revit/.venv+packages/mcp-server-revit/.venv/Scripts/python -m pip install -e "packages/mcp-server-revit[dev]"+```+If `ifcopenshell` has no wheel for this Python, list versions with `py -0p` and recreate the venv with `py -3.12` or `py -3.11`.++## The task+1. Give the provider a real connect lifecycle: an async `initialize()` (called by the owner) AND/OR lazy connect on first `execute_tool`/`get_tools` — pick the pattern most consistent with `base.py` and document the choice in the docstring.+2. Add reconnect-with-exponential-backoff (bounded retries, jittered) when the SSE session drops mid-use; a clean typed error when the target is unreachable.+3. Surface the remote server's tool list into this provider's capability manifest (names namespaced to avoid collisions, preserving remote descriptions/schemas).+4. Graceful `shutdown()`/disconnect.+5. Tests with a fake MCP/SSE server (in-process): tools listed through proxy; tool call round-trip; one disconnect→reconnect cycle; unreachable-target error path. Use the `mcp` library's test utilities if convenient, otherwise stub the transport layer.++If the card contradicts the actual code, follow reality and note the discrepancy in your final summary.++## Verify (must pass before committing)+```+packages/mcp-server-revit/.venv/Scripts/python -m pytest packages/mcp-server-revit/tests -k proxy+packages/mcp-server-revit/.venv/Scripts/python -m pytest packages/mcp-server-revit/tests+```++## Deliverable+Final message: files changed, test counts, the lifecycle pattern chosen and why, discrepancies found.diff --git a/AGENT-TASK-A5.md b/AGENT-TASK-A5.mdnew file mode 100644index 0000000..9e5d309--- /dev/null+++ b/AGENT-TASK-A5.md@@ -0,0 +1,43 @@+# Build Task A5 — Generated tool catalog++You are an autonomous implementation agent for AEC Model Bridge, working in an isolated git worktree on branch `task/A5-catalog`. Complete ONLY task A5, then stop.++## Read first+- `docs/agent-task-plan.md` (card A5) and `docs/system-blueprint-and-workflows.md` §2 rule 3 (manifests are the single source of truth)+- `packages/mcp-server-revit/src/revit_mcp_server/mcp_server.py` (how providers are registered; optional providers may fail init and be absent)+- `providers/base.py` (`ProviderTool` shape — check which metadata fields actually exist), `providers/registry.py`+- `docs/tools.md` (legacy hand-written catalog of the original 26 revit.* tools)+- `.github/workflows/ci.yml` (python job)++## Standing rules (binding)+1. Back-compat: existing tool names and configs untouched.+2. Mock-first: the generator must run offline with no credentials — providers that fail to initialize (cloud/Rhino) are listed in the output as "not initialized in this environment" rather than crashing the generator.+3. No secrets in output. 4. Touch only files this task needs. NEVER edit `docs/agent-task-plan.md` or `AGENT-TASK.md`.+5. Finish with ONE commit on the current branch, message starting `A5: `. Targeted `git add <paths>` only. Do not push.++## Environment setup+From repo root:+```+python -m venv packages/mcp-server-revit/.venv+packages/mcp-server-revit/.venv/Scripts/python -m pip install -e "packages/mcp-server-revit[dev]"+```+If `ifcopenshell` has no wheel for this Python, list versions with `py -0p` and recreate the venv with `py -3.12` or `py -3.11`.++## The task+1. Create `packages/mcp-server-revit/scripts/generate_tool_docs.py`: builds the provider registry the same way `mcp_server.py` does (mock mode, no credentials), introspects every registered provider, and writes `docs/tools-generated.md` — one section per provider with a table: tool name, description (first sentence), mutating? (emit `?` if the metadata field does not exist yet — note this in the file header), sync/async if known.+2. Output must be deterministic (stable sort) so reruns are byte-identical — this enables the CI drift check.+3. CI: in `.github/workflows/ci.yml` python job, add a step that runs the generator then `git diff --exit-code docs/tools-generated.md` (fails CI if the catalog drifted from code).+4. Add a short banner at the top of `docs/tools.md`: legacy document covering the original 26 tools; the complete generated catalog lives in `docs/tools-generated.md`.+5. Commit the generated `docs/tools-generated.md` (it should list all providers/tools available in a clean offline environment — expect roughly 7 providers and 120+ tools; cloud ones may be absent).++If `ProviderTool` lacks fields the card assumes, follow reality, degrade the column gracefully, and note the discrepancy in your final summary.++## Verify (must pass before committing)+```+packages/mcp-server-revit/.venv/Scripts/python packages/mcp-server-revit/scripts/generate_tool_docs.py+git diff --exit-code docs/tools-generated.md (run generator twice; second run produces no diff)+packages/mcp-server-revit/.venv/Scripts/python -m pytest packages/mcp-server-revit/tests+```++## Deliverable+Final message: files changed, provider/tool counts in the generated catalog, test counts, discrepancies found.diff --git a/AGENT-TASK-A8.md b/AGENT-TASK-A8.mdnew file mode 100644index 0000000..c5fec3f--- /dev/null+++ b/AGENT-TASK-A8.md@@ -0,0 +1,43 @@+# Build Task A8 — Parameterized provider contract tests++You are an autonomous implementation agent for AEC Model Bridge, working in an isolated git worktree on branch `task/A8-contract-tests`. Complete ONLY task A8, then stop.++## Read first+- `docs/agent-task-plan.md` (card A8) and `docs/system-blueprint-and-workflows.md` §10 standing practices+- `packages/mcp-server-revit/src/revit_mcp_server/providers/fake.py` and `providers/base.py` (the contract surface)+- `providers/registry.py`, `mcp_server.py` (which providers register in a clean offline env)+- `security/audit.py` (`redact_data`), existing `tests/test_providers.py` for fixtures/patterns++## Standing rules (binding)+1. Back-compat: production code changes only if a provider genuinely violates the contract — if so, fix minimally and flag it prominently in your summary.+2. Mock-first: the suite must pass offline with no credentials. Parameterize over providers that register in a clean environment (Revit mock, IFC, mapper, exporter, jobs, graph, fake; skip cloud/Rhino/proxy gracefully when their init prerequisites are absent — use pytest skip with reason, not silent omission).+3. No secrets in fixtures. 4. Touch only files this task needs. NEVER edit `docs/agent-task-plan.md` or `AGENT-TASK.md`.+5. Finish with ONE commit on the current branch, message starting `A8: `. Targeted `git add <paths>` only. Do not push.++## Environment setup+From repo root:+```+python -m venv packages/mcp-server-revit/.venv+packages/mcp-server-revit/.venv/Scripts/python -m pip install -e "packages/mcp-server-revit[dev]"+```+If `ifcopenshell` has no wheel for this Python, list versions with `py -0p` and recreate the venv with `py -3.12` or `py -3.11`.++## The task+Create `packages/mcp-server-revit/tests/test_provider_contract.py` — ONE suite parameterized over every registrable provider, asserting for each:+1. `identity` is a stable, non-empty string, unique across the registry.+2. The tool list is non-empty; tool names are unique globally (across all providers); every tool has a non-empty description.+3. Input schema: where the tool metadata carries a schema, it is valid JSON-schema-shaped (dict with `type` or `properties`); where the field doesn't exist, record that as an xfail/note rather than failing (follow reality).+4. Calling an unknown tool name raises a typed error (not a bare Exception or a string result).+5. Redaction: a synthetic result containing a fake bearer token, a Windows path, and a POSIX path passes through `redact_data` with all three redacted — run per provider result envelope shape.+6. Mutating-flag presence: assert the metadata field exists where defined; emit a single consolidated report (in test output) of providers/tools missing mutation metadata — informational, not failing (it becomes input for later manifest work).++If the contract in `base.py` differs from what the card assumes, follow reality and note the discrepancy in your final summary.++## Verify (must pass before committing)+```+packages/mcp-server-revit/.venv/Scripts/python -m pytest packages/mcp-server-revit/tests -k contract -v+packages/mcp-server-revit/.venv/Scripts/python -m pytest packages/mcp-server-revit/tests+```++## Deliverable+Final message: files changed, how many providers the suite parameterizes over (and which were skipped + why), test counts, any contract violations found in production code and how you handled them.diff --git a/README.md b/README.mdindex d9e981d..3fe4e7c 100644--- a/README.md+++ b/README.md@@ -18,37 +18,37 @@ MCP server and native add-in for AI-assisted Autodesk Revit workflows.</div>AEC Model Bridge connects MCP clients such as Claude Desktop, VS Code, GitHub-Copilot, and custom agents to a live Revit session.+Copilot, and custom agents to a live session across multiple AEC platforms simultaneously.-The Python server handles MCP communication. The C# add-in executes commands-inside Revit through `ExternalEvent`, keeping API work on Revit's main thread.+The Python server handles MCP communication, routing queries to the correct provider:+- **Revit**: Native C# add-in (Revit 2024-2027) executing on the main thread via `ExternalEvent`.+- **Navisworks Manage**: Native C# add-in (Navisworks 2024-2027) exposing the API over a local bridge.+- **Rhino/Grasshopper**: Connects to Rhino.Compute or proxies to an active Rhino MCP server over SSE.+- **Speckle**: Native Python provider integrating Specklepy V3 for seamless model pushing to Power BI.+- **IfcOpenShell**: Headless IFC semantic extraction and parsing.## Highlights-- 100 MCP tools for model authoring, documentation, parameters, views, sheets,- exports, worksharing, architecture, structure, MEP, geometry, and QA.-- Native Revit add-in with no pyRevit or Dynamo dependency.-- Revit 2024, 2025, 2026, and 2027 support.-- Reflection and in-process Python for advanced API workflows.-- Localhost-only bridge by default.-- Mock mode for development and automated testing without Revit.+- 100+ MCP tools for model authoring, documentation, parameters, views, sheets, exports, and QA.+- Native Revit & Navisworks add-ins with no Dynamo dependencies.+- Multi-platform synchronization: Cross-query Navisworks clash results, Revit parameters, and Rhino models dynamically.+- Speckle and PowerBI automated data handoffs.+- Async job orchestration and centralized PII redaction.+- Localhost-only bridge by default for absolute security.## How It Works```text-MCP client+MCP Client (Claude Desktop, VS Code)|| MCP over stdiov-Python MCP server- |- | HTTP on 127.0.0.1:3000- v-AEC Model Bridge add-in- |- | ExternalEvent- v-Revit API+Python MCP Server (Central Router)+ ├── [Revit Provider] -----> HTTP localhost:3000 -----> Revit Bridge Add-in+ ├── [Navisworks Provider] > HTTP localhost:3002 -----> Navisworks Bridge Add-in+ ├── [Speckle Provider] ---> HTTPS (OAuth) -----------> Speckle Manager / Power BI+ ├── [Rhino Proxy] --------> SSE localhost:9876 ------> Active Rhino MCP+ └── [IFC Provider] -------> Local Filesystem --------> IfcOpenShell```## Installationdiff --git a/docs/ecosystem-strategy-and-monetization.md b/docs/ecosystem-strategy-and-monetization.mdnew file mode 100644index 0000000..c7a13c9--- /dev/null+++ b/docs/ecosystem-strategy-and-monetization.md@@ -0,0 +1,118 @@+# AEC Omni-Bridge — Ecosystem Strategy, Brand & Monetization Playbook++**Status:** Internal strategy document (v1.0, 2026-06-12)+**Owner:** A. Sam Mohammad (Sam-AEC)+**Note:** This document contains personal career and revenue strategy. Consider keeping it out of the public repository (move to a private repo or local notes) before pushing. The technical companion is `docs/system-blueprint-and-workflows.md`.++---++## 1. The Playbook Being Run — the "pyRevit moment"++pyRevit is the proof that one person's open-source AEC tool can become a career engine: it became indispensable daily infrastructure for BIM teams worldwide, and its author's name became synonymous with Revit automation — speaking slots, industry recognition, and job leverage followed from *distribution*, not from sales.++The structural opportunity now is bigger than pyRevit's was, because a platform shift is underway: **AI agents are gaining the ability to operate professional software, and MCP is the protocol they use.** Whoever ships the credible, secure, multi-platform MCP runtime for BIM becomes the default name in "AI × AEC" — a category that barely has incumbents yet. pyRevit automated Revit for humans; Omni-Bridge operates the whole AEC stack for agents. That is the positioning sentence.++**Positioning statement:** *AEC Model Bridge is the open, secure runtime that lets AI agents operate Revit, Navisworks, Rhino, and your CDE — turning fragmented BIM workflows into one orchestrated pipeline from concept to dashboard.*++### Why the timing is right+- MCP registries and clients (Claude Desktop, VS Code, Copilot) are mainstream; AEC entries are sparse and mostly single-tool. A multi-platform, security-hardened entry stands out immediately.+- BIM managers are being asked by leadership "what's our AI strategy?" and have nothing concrete to demo. The zero-switch IFC demo (blueprint §4.2) is a five-minute answer they can run on a laptop.+- The dual-license foundation (GPL + commercial) is already in place as of v1.1.0 — the legal groundwork most OSS authors retrofit painfully is done.++---++## 2. Brand Architecture++| Asset | Role | Action |+| --- | --- | --- |+| **AEC Model Bridge** | The product name (PyPI, MCP Registry, releases) | Keep. Already established in registry and packaging. |+| **Omni-Bridge** | The orchestration layer / architecture story | Use as the *narrative* name ("the Omni-Bridge architecture") in talks and articles — memorable, but don't fragment package naming. |+| **Sam-AEC** | The personal brand (GitHub org, LinkedIn) | Every artifact links back: README byline, docs footer, video outros, conference bios. |+| Repo name `Autodesk-Revit-MCP-Server` | Legacy, undersells the product and risks trademark friction ("Autodesk" leading the name) | Rename to `aec-model-bridge` (GitHub auto-redirects; README clone URL already assumes it). Tracked as OD5 in the blueprint. |+| Docs site | Currently README + docs folder | Stand up MkDocs Material (or Docusaurus) on GitHub Pages at a custom domain. The docs site is the brand's home, not the repo. |++**Trademark discipline:** never lead with vendor names; keep `TRADEMARKS.md` current; "for Autodesk® Revit®" phrasing only in descriptive contexts. This matters more as visibility grows.++---++## 3. Audience Map — whose pain, which workflow, what they'll pay for++| Persona | Daily pain | Flagship workflow that hooks them | Monetizable need |+| --- | --- | --- | --- |+| **BIM Manager / Information Manager** | Manual compliance checks, stale model-health reporting, "AI strategy" pressure from leadership | W3 Model Health & Compliance (zero-install demo) | Training, firm-wide deployment support, premium audit recipe packs (IDS/COBie) |+| **VDC / Coordination Lead** | Clash Detective ritual, screenshot-driven coordination meetings | W2 Coordination Loop + ACC Issues publishing | Commercial license for firm integration, Navisworks/Solibri switch support |+| **Computational Designer** | Rhino→Revit re-modeling, brittle handoffs | W1 Concept-to-BIM | Custom recipe development, Rhino switch priority support |+| **AEC Data / Power BI Lead** | Fragile Excel export chains feeding dashboards | W4 Data-Lake Drop + the `.pbit` templates | Dashboard template packs, hosted run-history (future SaaS) |+| **Cost / 5D team** | Re-keying quantities between Revit and Excel | W5 QTO round-trip | Per-seat commercial terms inside ERP-integrated firms |++Content, demos, and pricing should always be expressed in these personas' language — never "MCP server with 155 tools," always "clash report in your dashboard before the coordination meeting starts."++---++## 4. Monetization Ladder (each rung funds the next)++The model is **open-core with services**, built on the existing dual license. Rungs in order of activation:++### Rung 0 — OSS core (active now)+GPL-3.0 + Revit Linking Exception. Purpose: distribution, trust, brand. The core hub, Revit switch, and flagship recipes stay free forever — this is the moat *and* the marketing.++### Rung 1 — Commercial licensing (active now, under-leveraged)+The dual-license already permits selling commercial terms to firms that won't accept GPL (embedding, redistribution, proprietary modification). Action: add a one-page "Commercial use" page on the docs site with a contact funnel (currently buried in `LICENSING.md`), and a simple price anchor for firm-wide licenses. Even two or three firm licenses validate the model.++### Rung 2 — Premium recipe packs & switches (after Phase E)+The recipe engine (blueprint §5.1) makes workflows *products*: versioned files, installable separately. Free: W1–W5 reference recipes. Paid packs: COBie handover audit, ISO 19650 naming compliance, Solibri ruleset orchestration, carbon/QTO packs with the Power BI templates included. Desktop switches beyond Revit/Navisworks (Solibri, Tekla) can be "supported tier" — source-available but with paid support/maintenance commitments.++### Rung 3 — Services (continuous, highest margin, zero build cost)+- **Implementation consulting:** firm-specific switch deployment, recipe authoring, dashboard wiring.+- **Corporate training/workshops:** "AI agents for BIM teams" half-day workshop — the W3 zero-install demo makes this trivially deliverable.+- **Custom development retainers** for firms wanting private switches (their internal databases, ERP).+Services revenue is also the strongest job-market signal: every engagement is a case study.++### Rung 4 — Hosted control plane (deferred — OD4 in blueprint)+A SaaS layer: team run-history, scheduled pipelines, dashboard hosting, fleet management of switches across an office. Only build after Wave 2 proves recurring usage. This is the venture-scale option; everything before it is sustainable solo.++### Channels+MCP Registry (already listed) · PyPI · GitHub Releases · Autodesk App Store (Revit + Navisworks switches — also a credibility badge) · Food4Rhino (Rhino switch) · GitHub Sponsors (turn on now; costs nothing) · Speckle community showcase.++---++## 5. Career-Leverage Plan (the "spread the name" track)++The product *is* the portfolio. Convert engineering milestones into visibility artifacts on a fixed cadence:++1. **Demo videos (highest ROI):** 30–60 second screen captures — "Claude runs a clash test in Navisworks and the Power BI dashboard updates" — posted to LinkedIn with the persona's pain in the first line. One per flagship workflow as each lands in blueprint Phase C/D. These clips are what recruiters and CTOs actually share.+2. **Written artifacts:** one architecture deep-dive per phase (the blueprint's sections are pre-written outlines: "Why we chose file-based discovery over a daemon," "Provenance records for BIM pipelines"). Cross-post: personal blog/docs site first, LinkedIn summary linking back.+3. **Talks:** target the AEC-tech circuit — Speckle community calls (easiest entry, immediately relevant audience), then BILT / Autodesk University / DevCon proposals using the W2 live demo. One conference talk converts to more job leverage than months of posting.+4. **Metrics to capture from day one** (screenshot monthly): GitHub stars/forks, PyPI downloads, MCP registry ranking, docs-site analytics, video view counts. These numbers go on the CV ("author of an MCP platform with N installs across M countries").+5. **The narrative for interviews:** not "I wrote a Revit plugin" but "I designed and shipped a multi-provider automation platform — protocol design, security model, OAuth, CI across .NET 4.8/8/10 and Python, plus the open-source go-to-market." Target roles: BIM Automation Lead, AEC Software Engineer, Developer Advocate at Speckle/Autodesk/Chaos/Nemetschek-family companies — all of which monitor exactly this ecosystem.++---++## 6. Risks & Mitigations++| Risk | Reality check | Mitigation |+| --- | --- | --- |+| Vendor SDK/ToS violations on non-Revit switches | GPL exception covers Revit only; Navisworks switch already shipped without equivalent review | Blueprint Phase A3 legal review **before** Wave 2 marketing pushes; keep SDK binaries out of repo |+| Autodesk trademark friction as visibility grows | Repo name currently leads with "Autodesk" | Rename (OD5); keep trademark hygiene |+| Support burden swamping a solo maintainer | Every OSS success story's failure mode | Aggressive issue templates, "supported tier" boundary (Rung 2), mock-first CI so contributors can work without licenses |+| A vendor ships the same thing natively | Autodesk/Speckle will add AI surfaces | Multi-vendor orchestration *is* the moat — no single vendor will orchestrate competitors' tools; move fast on the cross-platform story |+| Free users never convert | Common in AEC OSS | Conversion target is firms (licenses/services), not individuals; individuals are distribution |+| Security incident (agent does destructive things in a live model) | One bad story kills B2B trust | Blueprint policy layer (Phase B6) before any marketing push that targets firms; publish the security model prominently |++---++## 7. 90-Day Go-to-Market Calendar (aligned to blueprint phases)++| Weeks | Engineering (blueprint) | Visibility / business |+| --- | --- | --- |+| 1–2 | Phase A (hygiene, Speckle fix, licensing review) | Turn on GitHub Sponsors; repo rename; stand up MkDocs site; write "Introducing the Omni-Bridge architecture" post from blueprint §1–2 |+| 3–6 | Phase B (Contract v2, Navisworks completion) | Demo video #1: W3 zero-install IFC health check (works today); commercial-use page on docs site |+| 7–10 | Phase C (orchestrator, flagship recipes) | Demo video #2: W2 live clash loop; submit Speckle community call talk; first LinkedIn architecture deep-dive |+| 11–13 | Phase D (Parquet, Power BI templates) | Demo video #3: concept-to-dashboard full pipeline (the hero demo); publish `.pbit` templates; AU/BILT talk proposal using captured metrics |++Cadence rule: **every engineering milestone ships with its visibility artifact in the same week** — the work is only "done" when it's demonstrable and posted.++---++**Changelog**+- 2026-06-12 — v1.0 — Initial playbook.diff --git a/docs/tools-generated.md b/docs/tools-generated.mdnew file mode 100644index 0000000..089a706--- /dev/null+++ b/docs/tools-generated.md@@ -0,0 +1,216 @@+# Generated Tool Catalog++<!-- This file is auto-generated by packages/mcp-server-revit/scripts/generate_tool_docs.py. Do not edit manually. -->++This catalog lists all tools exposed by the AEC Model Bridge providers.++> [!NOTE]+> The columns `Mutating?` and `Execution Type` display `?` and `async` respectively,+> as these metadata fields are not explicitly defined on the provider tools yet.++## AEC Mapper Provider++| Tool Name | Description | Mutating? | Execution Type |+| --- | --- | --- | --- |+| `aec_map_workspace_path` | Map and convert workspace paths between relative formats, Windows absolute format, and POSIX path format. | ? | async |+| `aec_register_mapping` | Register custom relationship links between different BIM workflows (e. | ? | async |+| `aec_translate_id` | Translate an element identifier between Revit UniqueId/GUID, IFC GlobalId, and custom registered workflows. | ? | async |++## Autodesk Data Provider++| Tool Name | Description | Mutating? | Execution Type |+| --- | --- | --- | --- |+| `autodesk_data_auth_status` | Get Autodesk OAuth authentication status. | ? | async |+| `autodesk_data_checkout_version` | Checkout Autodesk version metadata. | ? | async |+| `autodesk_data_create_issue` | Compatibility alias for create_topic. | ? | async |+| `autodesk_data_create_topic` | Create a BCF-compatible issue/topic through a configured endpoint. | ? | async |+| `autodesk_data_get_version_metadata` | Read Autodesk item/version metadata. | ? | async |+| `autodesk_data_health` | Check Autodesk Data provider health. | ? | async |+| `autodesk_data_list_hubs` | List Autodesk Construction Cloud hubs. | ? | async |+| `autodesk_data_list_items` | List Autodesk items in a project folder or container. | ? | async |+| `autodesk_data_list_projects` | List Autodesk projects in a hub. | ? | async |+| `autodesk_data_oauth_exchange_code` | Exchange an Autodesk OAuth authorization code. | ? | async |+| `autodesk_data_oauth_refresh` | Refresh the Autodesk OAuth access token. | ? | async |+| `autodesk_data_oauth_start` | Generate an Autodesk OAuth authorization URL using PKCE. | ? | async |++## IFC Provider++| Tool Name | Description | Mutating? | Execution Type |+| --- | --- | --- | --- |+| `ifc_get_bounding_box` | Get bounding box dimensions and placement information for a specific element. | ? | async |+| `ifc_get_metadata` | Get file schema, header metadata, units, and georeferencing summary from an IFC file. | ? | async |+| `ifc_get_properties` | Get property sets, quantities, and direct attributes for a specific element in an IFC file. | ? | async |+| `ifc_get_spatial_structure` | Get the spatial hierarchy (Project -> Site -> Building -> Storey -> Element Types/Counts) from an IFC file. | ? | async |+| `ifc_health` | Check status of IfcOpenShell and get version info. | ? | async |+| `ifc_query_elements` | Query elements by IFC class, GUID, name, or simple property name/value criteria. | ? | async |+| `ifc_validate` | Perform schema validation on the IFC file and return errors/warnings list. | ? | async |++## Job Provider++| Tool Name | Description | Mutating? | Execution Type |+| --- | --- | --- | --- |+| `job_cancel` | Cancel a running or queued background job. | ? | async |+| `job_status` | Get the status, progress, results, or error details of a background job. | ? | async |++## Mcp Proxy Provider++*No tools available for this provider.*++## Revit Provider++| Tool Name | Description | Mutating? | Execution Type |+| --- | --- | --- | --- |+| `revit_apply_view_template` | Apply view template to a view. | ? | async |+| `revit_batch_create_sheets_from_csv` | Create multiple sheets from a CSV file. | ? | async |+| `revit_batch_set_parameters` | Set a parameter value for multiple elements. | ? | async |+| `revit_batch_set_parameters_by_filter` | Set a parameter value on all elements matching a filter (category, type, level, or parameter value). | ? | async |+| `revit_calculate_material_quantities` | Calculate material volumes for a category. | ? | async |+| `revit_change_element_type` | Swap all instances of one element type to another type. | ? | async |+| `revit_check_clashes` | Check clashes between categories. | ? | async |+| `revit_close_document` | Close active document. | ? | async |+| `revit_convert_to_group` | Convert elements into a group. | ? | async |+| `revit_copy_element` | Copy an element. | ? | async |+| `revit_create_3d_view` | Create a new 3D view. | ? | async |+| `revit_create_beam` | Create structural beam. | ? | async |+| `revit_create_column` | Create structural column. | ? | async |+| `revit_create_conduit` | Create electrical conduit. | ? | async |+| `revit_create_dimension` | Create linear dimension between elements. | ? | async |+| `revit_create_duct` | Create duct. | ? | async |+| `revit_create_floor` | Create a floor in Revit with a rectangular or custom boundary. | ? | async |+| `revit_create_floor_plan_view` | Create a floor plan view for a level. | ? | async |+| `revit_create_foundation` | Create foundation. | ? | async |+| `revit_create_grid` | Create a grid line in Revit. | ? | async |+| `revit_create_group` | Create a group. | ? | async |+| `revit_create_level` | Create a new level in Revit. | ? | async |+| `revit_create_material` | Create a new material with color and properties. | ? | async |+| `revit_create_new_document` | Create new project. | ? | async |+| `revit_create_pipe` | Create pipe. | ? | async |+| `revit_create_project_parameter` | Create a new project parameter. | ? | async |+| `revit_create_roof` | Create a roof in Revit. | ? | async |+| `revit_create_room` | Create a room at a specific point on a level. | ? | async |+| `revit_create_schedule` | Create a schedule. | ? | async |+| `revit_create_section_view` | Create a section view. | ? | async |+| `revit_create_shared_parameter` | Create a new shared parameter. | ? | async |+| `revit_create_sheet` | Create a new sheet. | ? | async |+| `revit_create_tag` | Tag an element. | ? | async |+| `revit_create_text_note` | Create a text note. | ? | async |+| `revit_create_wall` | Create a wall in Revit between two points. | ? | async |+| `revit_delete_element` | Delete an element by ID. | ? | async |+| `revit_delete_sheet` | Delete a sheet. | ? | async |+| `revit_duplicate_sheet` | Duplicate a sheet. | ? | async |+| `revit_edit_family` | Open a family for editing. | ? | async |+| `revit_execute_python` | Execute arbitrary Python/IronPython code inside Revit with broad access to the public Revit API. | ? | async |+| `revit_export_dwg` | Export view to DWG. | ? | async |+| `revit_export_ifc` | Export to IFC. | ? | async |+| `revit_export_image` | Export view to Image. | ? | async |+| `revit_export_navisworks` | Export to NWC. | ? | async |+| `revit_get_categories` | List Revit categories. | ? | async |+| `revit_get_design_options` | Get design options. | ? | async |+| `revit_get_document_info` | Get information about the active Revit document. | ? | async |+| `revit_get_element_bounding_box` | Get element bounding box. | ? | async |+| `revit_get_element_geometry` | Get geometric data for an element: location point or curve endpoints, bounding box, level, area, volume, and length. | ? | async |+| `revit_get_element_parameters` | Get all parameters of an element. | ? | async |+| `revit_get_element_type` | Find element types/families. | ? | async |+| `revit_get_elements_by_type` | Get element IDs and key parameters, filtered by type, category, and/or level. | ? | async |+| `revit_get_group_members` | Get group members. | ? | async |+| `revit_get_link_instances` | Get link instances. | ? | async |+| `revit_get_parameter_value` | Get a specific parameter value. | ? | async |+| `revit_get_phase_filters` | Get phase filters. | ? | async |+| `revit_get_phases` | Get project phases. | ? | async |+| `revit_get_revision_sequences` | Get list of revision sequences. | ? | async |+| `revit_get_rvt_links` | Get RVT links. | ? | async |+| `revit_get_schedule_data` | Get schedule data. | ? | async |+| `revit_get_selection` | Get currently selected element IDs. | ? | async |+| `revit_get_sheet_info` | Get detailed information about a sheet. | ? | async |+| `revit_get_type_parameters` | Get type parameters for an element. | ? | async |+| `revit_get_view_templates` | Get list of view templates. | ? | async |+| `revit_get_warnings` | Get current project warnings. | ? | async |+| `revit_get_worksets` | Get all worksets. | ? | async |+| `revit_health` | Check if Revit is running and get status information. | ? | async |+| `revit_invoke_method` | Invoke any Revit API method dynamically using Reflection. | ? | async |+| `revit_list_elements` | List elements by category (Walls, Floors, Roofs, Doors, Windows, etc. | ? | async |+| `revit_list_families` | List all loaded families and their types. | ? | async |+| `revit_list_levels` | List all levels in the Revit project. | ? | async |+| `revit_list_project_parameters` | List project parameters. | ? | async |+| `revit_list_shared_parameters` | List shared parameters in the document. | ? | async |+| `revit_list_sheets` | List all sheets. | ? | async |+| `revit_list_titleblocks` | List available titleblocks. | ? | async |+| `revit_list_views` | List all views in the Revit project. | ? | async |+| `revit_mirror_element` | Mirror an element. | ? | async |+| `revit_move_element` | Move an element. | ? | async |+| `revit_pin_element` | Pin an element. | ? | async |+| `revit_place_door` | Place a door in a wall. | ? | async |+| `revit_place_family_instance` | Place a family instance (e. | ? | async |+| `revit_place_viewport_on_sheet` | Place a view on a sheet. | ? | async |+| `revit_place_window` | Place a window in a wall. | ? | async |+| `revit_populate_titleblock` | Populate titleblock parameters. | ? | async |+| `revit_reflect_get` | Get any Revit property value dynamically. | ? | async |+| `revit_reflect_set` | Set any Revit property value dynamically. | ? | async |+| `revit_relinquish_all` | Relinquish all elements and worksets. | ? | async |+| `revit_render_3d` | Render 3D view to image. | ? | async |+| `revit_renumber_sheets` | Batch renumber sheets. | ? | async |+| `revit_replace_family_type` | Replace all instances of one family/type combination with another, identified by name. | ? | async |+| `revit_rotate_element` | Rotate an element. | ? | async |+| `revit_save_document` | Save the current Revit document. | ? | async |+| `revit_set_element_material` | Set material for an element or specific face. | ? | async |+| `revit_set_parameter_value` | Set a parameter value for an element. | ? | async |+| `revit_set_selection` | Set selection by element IDs. | ? | async |+| `revit_set_type_parameter` | Set a type parameter value. | ? | async |+| `revit_sync_to_central` | Sync to central model. | ? | async |+| `revit_tag_all_in_view` | Tag all elements of a category in view. | ? | async |+| `revit_ungroup` | Ungroup a group. | ? | async |+| `revit_unpin_element` | Unpin an element. | ? | async |++## Rhino Provider++| Tool Name | Description | Mutating? | Execution Type |+| --- | --- | --- | --- |+| `rhino_evaluate_definition` | Upload a Grasshopper definition, solve it against Resthopper-compatible trees, and return the compute response. | ? | async |+| `rhino_get_definition_io` | Upload a Grasshopper definition and return its Resthopper input/output metadata. | ? | async |+| `rhino_get_geometry_details` | Return detailed geometry metadata for a. | ? | async |+| `rhino_get_layers` | Return layer metadata for a. | ? | async |+| `rhino_health` | Check Rhino. | ? | async |+| `rhino_query_file_geometry` | Upload a. | ? | async |++## Semantic Graph Provider++| Tool Name | Description | Mutating? | Execution Type |+| --- | --- | --- | --- |+| `graph_add_relation` | Add a typed relation between two existing nodes. | ? | async |+| `graph_audit_clashes` | Audit axis-aligned bounding boxes for clashes using a tolerance value. | ? | async |+| `graph_audit_disconnected` | Audit disconnected nodes or components using degree and connectivity rules. | ? | async |+| `graph_audit_structural_loads` | Audit structural load-bearing and support consistency using SUPPORTED_BY relations. | ? | async |+| `graph_compile` | Compile workspace model nodes and relations into the in-memory semantic graph. | ? | async |+| `graph_health` | Check graph provider health and current graph size. | ? | async |+| `graph_query_relations` | Query relations by node, related node, relation type, and direction. | ? | async |++## Speckle Provider++| Tool Name | Description | Mutating? | Execution Type |+| --- | --- | --- | --- |+| `speckle_auth_status` | Get Speckle OAuth authentication status. | ? | async |+| `speckle_checkout_version` | Checkout Speckle version metadata. | ? | async |+| `speckle_create_branch` | Create an isolated Speckle branch for compatibility with model workflows. | ? | async |+| `speckle_create_model` | Create an isolated Speckle model. | ? | async |+| `speckle_get_version_metadata` | Read Speckle version metadata. | ? | async |+| `speckle_health` | Check Speckle provider health. | ? | async |+| `speckle_list_models` | List Speckle models for a project. | ? | async |+| `speckle_list_projects` | List Speckle projects. | ? | async |+| `speckle_list_versions` | List Speckle versions for a model or branch. | ? | async |+| `speckle_merge_branch` | Compatibility alias for merge_model. | ? | async |+| `speckle_merge_model` | Merge one Speckle model or branch into another through GraphQL. | ? | async |+| `speckle_oauth_exchange_code` | Exchange a Speckle OAuth authorization code. | ? | async |+| `speckle_oauth_refresh` | Refresh the Speckle OAuth access token. | ? | async |+| `speckle_oauth_start` | Generate a Speckle OAuth authorization URL using PKCE. | ? | async |+| `speckle_publish_version` | Publish a Speckle version by creating a commit through GraphQL. | ? | async |+| `speckle_receive_object` | Receives data from a Speckle stream/project using local credentials. | ? | async |+| `speckle_send_object` | Sends generic data objects to a Speckle stream/project using local credentials. | ? | async |++## SQLite Exporter Provider++| Tool Name | Description | Mutating? | Execution Type |+| --- | --- | --- | --- |+| `exporter_db_health` | Check health and readiness of the local database exporter. | ? | async |+| `exporter_graph_to_sqlite` | Extract the active semantic network graph and dump its nodes, properties, and typed edges to a local SQLite database in the workspace. | ? | async |+| `exporter_to_sqlite` | Export a structured payload of BIM elements, parameters, and relationships to a local SQLite database in the workspace. | ? | async |+diff --git a/docs/tools.md b/docs/tools.mdindex 19ac319..88b64f1 100644--- a/docs/tools.md+++ b/docs/tools.md@@ -1,5 +1,9 @@# Tool Catalog+> [!WARNING]+> This is a legacy document covering the original 26 tools.+> The complete generated catalog of all current tools lives in [tools-generated.md](tools-generated.md).+AEC Model Bridge exposes tools for health checks, document operations, QA audits, export operations, and automation workflows.All tools accept JSON inputs validated against Pydantic schemas and return structured JSON responses.diff --git a/packages/mcp-server-revit/pyproject.toml b/packages/mcp-server-revit/pyproject.tomlindex de9d48d..f58b427 100644--- a/packages/mcp-server-revit/pyproject.toml+++ b/packages/mcp-server-revit/pyproject.toml@@ -18,6 +18,7 @@ dependencies = ["mcp>=0.9.0","ifcopenshell>=0.7.0","networkx>=3.0",+ "specklepy>=2.17.0",][project.scripts]diff --git a/packages/mcp-server-revit/scripts/generate_tool_docs.py b/packages/mcp-server-revit/scripts/generate_tool_docs.pynew file mode 100644index 0000000..3afb7ab--- /dev/null+++ b/packages/mcp-server-revit/scripts/generate_tool_docs.py@@ -0,0 +1,126 @@+import os+import sys+from pathlib import Path++# Ensure environment variables exist before other modules import config.+workspace = Path(__file__).resolve().parent.parent+os.environ.setdefault("MCP_REVIT_WORKSPACE_DIR", str(workspace))+os.environ.setdefault("MCP_REVIT_ALLOWED_DIRECTORIES", str(workspace))+os.environ.setdefault("MCP_REVIT_MODE", "mock")++# Add src folder to sys.path to allow imports+src_path = Path(__file__).resolve().parent.parent / "src"+sys.path.insert(0, str(src_path))++from revit_mcp_server.security.workspace import WorkspaceMonitor+from revit_mcp_server.jobs import JobManager+from revit_mcp_server.providers import (+ ProviderRegistry,+ RevitProvider,+ IfcProvider,+ AECMapperProvider,+ SQLiteExporterProvider,+ JobProvider,+ RhinoProvider,+ SemanticGraphProvider,+ SpeckleProvider,+ AutodeskDataProvider,+)++try:+ from revit_mcp_server.providers import McpProxyProvider+except ImportError:+ McpProxyProvider = None++def get_first_sentence(text: str) -> str:+ if not text:+ return ""+ text = text.strip().replace("\n", " ")+ parts = text.split(".")+ first = parts[0].strip()+ if first and not first.endswith("."):+ first += "."+ return first++def main():+ workspace = WorkspaceMonitor([])+ job_manager = JobManager()+ registry = ProviderRegistry()++ # List of all available providers in the system+ # We instantiate cloud providers with dummy keys to make sure they load their capabilities list+ provider_instances = []++ # Helper function to safely instantiate and add a provider+ def add_provider(name: str, inst_func):+ try:+ inst = inst_func()+ provider_instances.append((name, inst, None))+ except Exception as e:+ provider_instances.append((name, None, str(e)))++ add_provider("Revit", lambda: RevitProvider(workspace=workspace))+ add_provider("IFC", lambda: IfcProvider(workspace=workspace))+ add_provider("AEC Mapper", lambda: AECMapperProvider(workspace=workspace))+ add_provider("SQLite Exporter", lambda: SQLiteExporterProvider(workspace=workspace, registry=registry))+ add_provider("Job", lambda: JobProvider(manager=job_manager))+ add_provider("Rhino", lambda: RhinoProvider(workspace=workspace))+ add_provider("Semantic Graph", lambda: SemanticGraphProvider())+ add_provider("Speckle", lambda: SpeckleProvider(client_id="dummy"))+ add_provider("Autodesk Data", lambda: AutodeskDataProvider(client_id="dummy"))+ if McpProxyProvider:+ add_provider("Mcp Proxy", lambda: McpProxyProvider("https://localhost:9876/sse"))++ # Stably sort providers by name+ provider_instances.sort(key=lambda x: x[0].lower())++ output_lines = [+ "# Generated Tool Catalog",+ "",+ "<!-- This file is auto-generated by packages/mcp-server-revit/scripts/generate_tool_docs.py. Do not edit manually. -->",+ "",+ "This catalog lists all tools exposed by the AEC Model Bridge providers.",+ "",+ "> [!NOTE]",+ "> The columns `Mutating?` and `Execution Type` display `?` and `async` respectively,",+ "> as these metadata fields are not explicitly defined on the provider tools yet.",+ ""+ ]++ for name, provider, error in provider_instances:+ output_lines.append(f"## {name} Provider")+ output_lines.append("")++ if error:+ output_lines.append(f"*Note: Not initialized in this environment ({error})*")+ output_lines.append("")+ continue++ tools = provider.get_capabilities()+ if not tools:+ output_lines.append("*No tools available for this provider.*")+ output_lines.append("")+ continue++ # Sort tools stably+ sorted_tools = sorted(tools, key=lambda t: t.name.lower())++ output_lines.append("| Tool Name | Description | Mutating? | Execution Type |")+ output_lines.append("| --- | --- | --- | --- |")+ for t in sorted_tools:+ desc = get_first_sentence(t.description)+ output_lines.append(f"| `{t.name}` | {desc} | ? | async |")+ output_lines.append("")++ # Write output file+ repo_root = Path(__file__).resolve().parent.parent.parent.parent+ output_path = repo_root / "docs" / "tools-generated.md"+ output_path.parent.mkdir(parents=True, exist_ok=True)++ with open(output_path, "w", encoding="utf-8") as f:+ f.write("\n".join(output_lines) + "\n")++ print(f"Generated tool catalog successfully at {output_path}")++if __name__ == "__main__":+ main()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__.pyindex 04699f7..54383a6 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@@ -9,6 +9,7 @@ from .graph import SemanticGraphProviderfrom .cloud import SpeckleProvider, AutodeskDataProviderfrom .job_provider import JobProviderfrom .exporter import SQLiteExporterProvider+from .proxy import McpProxyProvider__all__ = ["AECProvider",@@ -24,4 +25,5 @@ __all__ = ["AutodeskDataProvider","JobProvider","SQLiteExporterProvider",+ "McpProxyProvider",]diff --git a/packages/mcp-server-revit/src/revit_mcp_server/providers/cloud.py b/packages/mcp-server-revit/src/revit_mcp_server/providers/cloud.pyindex a2b6c15..cf19b12 100644--- a/packages/mcp-server-revit/src/revit_mcp_server/providers/cloud.py+++ b/packages/mcp-server-revit/src/revit_mcp_server/providers/cloud.py@@ -14,7 +14,14 @@ from urllib.parse import quote, urlencode, urlparseimport httpxfrom pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator+from specklepy.api.client import SpeckleClient+from specklepy.api.credentials import get_default_account+from specklepy.transports.server import ServerTransport+from specklepy.api import operations+from specklepy.objects.base import Base+from .base import AECProvider, ProviderTool+from ..errors import RevitMCPErrorCredentialCallback = Callable[[str], str | None] | Callable[[str], Awaitable[str | None]]SpeckleMergeBuilder = Callable[[Dict[str, Any]], Dict[str, Any]]@@ -454,7 +461,7 @@ class SpeckleProvider(CloudProviderBase):) -> None:_validate_https_url(host, allow_localhost_http=allow_localhost_http, label="speckle_host")self.host = host.rstrip("/")- resolved_client_id = client_id or os.getenv("SPECKLE_CLIENT_ID")+ resolved_client_id = client_id or os.getenv("SPECKLE_CLIENT_ID") or "local-credentials-only"self._merge_operation_builder = merge_operation_builderoauth = OAuth2PKCETransport(provider_name="speckle",@@ -492,6 +499,8 @@ class SpeckleProvider(CloudProviderBase):"speckle_publish_version": "_tool_publish_version","speckle_merge_model": "_tool_merge_model","speckle_merge_branch": "_tool_merge_model",+ "speckle_send_object": "_tool_speckle_send_object",+ "speckle_receive_object": "_tool_speckle_receive_object",}def _build_capabilities(self) -> List[ProviderTool]:@@ -511,6 +520,34 @@ class SpeckleProvider(CloudProviderBase):ProviderTool(name="speckle_publish_version", description="Publish a Speckle version by creating a commit through GraphQL.", inputSchema={"type": "object", "properties": {"project_id": {"type": "string"}, "model_id": {"type": "string"}, "object_id": {"type": "string"}, "message": {"type": "string"}, "source_application": {"type": "string"}, "idempotency_key": {"type": "string"}}, "required": ["project_id", "model_id", "object_id", "message"], "additionalProperties": False}),ProviderTool(name="speckle_merge_model", description="Merge one Speckle model or branch into another through GraphQL.", inputSchema={"type": "object", "properties": {"project_id": {"type": "string"}, "source_model_id": {"type": "string"}, "target_model_id": {"type": "string"}, "message": {"type": "string"}, "idempotency_key": {"type": "string"}}, "required": ["project_id", "source_model_id", "target_model_id", "message"], "additionalProperties": False}),ProviderTool(name="speckle_merge_branch", description="Compatibility alias for merge_model.", inputSchema={"type": "object", "properties": {"project_id": {"type": "string"}, "source_model_id": {"type": "string"}, "target_model_id": {"type": "string"}, "message": {"type": "string"}, "idempotency_key": {"type": "string"}}, "required": ["project_id", "source_model_id", "target_model_id", "message"], "additionalProperties": False}),+ ProviderTool(+ name="speckle_send_object",+ description="Sends generic data objects to a Speckle stream/project using local credentials.",+ inputSchema={+ "type": "object",+ "properties": {+ "project_id": {"type": "string", "description": "The Speckle Project/Stream ID"},+ "model_name": {"type": "string", "description": "The Model/Branch name to send to"},+ "data": {"type": "object", "description": "JSON data to send as Base objects"},+ "message": {"type": "string", "description": "Commit message"}+ },+ "required": ["project_id", "model_name", "data"],+ "additionalProperties": False,+ }+ ),+ ProviderTool(+ name="speckle_receive_object",+ description="Receives data from a Speckle stream/project using local credentials.",+ inputSchema={+ "type": "object",+ "properties": {+ "project_id": {"type": "string", "description": "The Speckle Project/Stream ID"},+ "version_id": {"type": "string", "description": "Specific Version/Commit ID to receive"}+ },+ "required": ["project_id", "version_id"],+ "additionalProperties": False,+ }+ ),]async def _tool_health(self, _: Dict[str, Any]) -> Dict[str, Any]:@@ -676,6 +713,86 @@ class SpeckleProvider(CloudProviderBase):raise RuntimeError("Speckle merge did not succeed")return {"merged": True}+ def _ensure_local_account(self, project_id: str) -> tuple[SpeckleClient, ServerTransport]:+ account = get_default_account()+ if not account:+ raise RevitMCPError("No local Speckle account found. Please authenticate via Speckle Manager.")+ try:+ client = SpeckleClient(host=account.serverInfo.url)+ client.authenticate_with_account(account)+ transport = ServerTransport(project_id, client)+ return client, transport+ except Exception as e:+ raise RevitMCPError(f"Failed to initialize local Speckle client or transport: {e}") from e++ async def _tool_speckle_send_object(self, arguments: Dict[str, Any]) -> Dict[str, Any]:+ project_id = arguments["project_id"]+ model_name = arguments["model_name"]+ data = arguments["data"]+ message = arguments.get("message", "Sent from AEC Model Bridge")++ client, transport = self._ensure_local_account(project_id)++ # Build base object+ base_obj = Base()+ for k, v in data.items():+ setattr(base_obj, k, v)++ # Fix the legacy bug: resolve model_name -> ID via models query+ try:+ models_res = client.model.get_models(project_id, models_limit=100)+ matching_model = next((m for m in models_res.items if m.name == model_name or m.id == model_name), None)+ if not matching_model:+ raise RevitMCPError(f"Model '{model_name}' not found in project '{project_id}'.")+ model_id = matching_model.id+ except Exception as e:+ if isinstance(e, RevitMCPError):+ raise+ raise RevitMCPError(f"Failed to resolve model '{model_name}' to ID: {e}") from e++ # Send the object to transport+ try:+ obj_id = operations.send(base=base_obj, transports=[transport])+ except Exception as e:+ raise RevitMCPError(f"Failed to send object: {e}") from e++ # Create the version/commit using client+ try:+ version_id = client.version.create(+ project_id=project_id,+ model_id=model_id,+ object_id=obj_id,+ message=message,+ source_application="AECModelBridge"+ )+ return {"result": f"Successfully sent data to Speckle. Version ID: {version_id}", "version_id": version_id}+ except Exception as e:+ raise RevitMCPError(f"Data sent to transport but version creation failed: {e}") from e++ async def _tool_speckle_receive_object(self, arguments: Dict[str, Any]) -> Dict[str, Any]:+ project_id = arguments["project_id"]+ version_id = arguments["version_id"]++ client, transport = self._ensure_local_account(project_id)++ try:+ version = client.version.get(project_id, version_id)+ except Exception as e:+ raise RevitMCPError(f"Failed to retrieve version metadata: {e}") from e++ try:+ base_obj = operations.receive(obj_id=version.referencedObject, remote_transport=transport)+ except Exception as e:+ raise RevitMCPError(f"Failed to receive object data: {e}") from e++ # Deserialize and return actual object data+ try:+ serialized = operations.serialize(base_obj)+ data = json.loads(serialized)+ return {"result": data}+ except Exception as e:+ raise RevitMCPError(f"Failed to deserialize received object: {e}") from e+async def _graphql(self,*,diff --git a/packages/mcp-server-revit/src/revit_mcp_server/providers/proxy.py b/packages/mcp-server-revit/src/revit_mcp_server/providers/proxy.pynew file mode 100644index 0000000..afb3261--- /dev/null+++ b/packages/mcp-server-revit/src/revit_mcp_server/providers/proxy.py@@ -0,0 +1,132 @@+from __future__ import annotations++import asyncio+import random+from typing import Any, Dict, List++from mcp import ClientSession+from mcp.client.sse import sse_client+from mcp.types import CallToolResult++from .base import AECProvider, ProviderTool+from ..errors import BridgeError++class McpProxyProvider(AECProvider):+ """+ A provider that proxies tool execution requests to a remote MCP server using SSE.++ Lifecycle Pattern Chosen:+ - We implement an async `initialize()` method to be called by the owner to fetch remote capabilities+ and populate `get_capabilities()`.+ This is chosen because `get_capabilities` is synchronous in the AECProvider contract, so we must+ fetch the tools list before it is called.+ - We also support lazy connection/reconnection on `execute_tool` using exponential backoff+ if the connection is lost.+ """+ def __init__(self, target_url: str):+ self.target_url = target_url+ self._session: ClientSession | None = None+ self._exit_stack = None+ self._tools: List[ProviderTool] = []+ self._connected = False++ def get_identity(self) -> str:+ return "proxy"++ def get_capabilities(self) -> List[ProviderTool]:+ return self._tools++ async def check_health(self) -> Dict[str, Any]:+ return {"status": "ok" if self._connected else "disconnected"}++ async def initialize(self) -> None:+ """Initialize connection and fetch remote tools list."""+ await self._connect_with_retry()++ async def _connect_once(self) -> None:+ from contextlib import AsyncExitStack++ if self._exit_stack:+ await self._exit_stack.aclose()++ self._exit_stack = AsyncExitStack()+ self._tools = []+ self._connected = False++ try:+ read, write = await self._exit_stack.enter_async_context(sse_client(self.target_url))+ self._session = await self._exit_stack.enter_async_context(ClientSession(read, write))+ await self._session.initialize()++ mcp_tools = await self._session.list_tools()+ for t in mcp_tools.tools:+ namespaced_name = f"proxy_{t.name}"+ self._tools.append(ProviderTool(+ name=namespaced_name,+ description=t.description or "",+ inputSchema=t.inputSchema+ ))+ self._connected = True+ except Exception as e:+ self._connected = False+ self._session = None+ if self._exit_stack:+ await self._exit_stack.aclose()+ self._exit_stack = None+ raise e++ async def _connect_with_retry(self) -> None:+ max_retries = 5+ base_delay = 0.5+ max_delay = 8.0++ last_exception = None+ for attempt in range(max_retries):+ try:+ await self._connect_once()+ return+ except Exception as e:+ last_exception = e+ delay = min(max_delay, base_delay * (2 ** attempt))+ jitter = random.uniform(0, 0.1 * delay)+ await asyncio.sleep(delay + jitter)++ raise BridgeError(+ f"Failed to connect to proxy target {self.target_url} after {max_retries} attempts: {last_exception}"+ )++ async def execute_tool(self, name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:+ if not name.startswith("proxy_"):+ raise ValueError(f"Unknown tool '{name}' on provider 'proxy'")++ remote_name = name[len("proxy_"):]++ if not self._connected or not self._session:+ await self._connect_with_retry()++ try:+ result: CallToolResult = await self._session.call_tool(remote_name, arguments)+ return {+ "result": "\n".join(content.text for content in result.content if hasattr(content, 'text')),+ "is_error": result.isError+ }+ except Exception as e:+ # Drop connection and try to reconnect once if a tool call fails (SSE drop)+ self._connected = False+ self._session = None+ await self._connect_with_retry()+ try:+ result = await self._session.call_tool(remote_name, arguments)+ return {+ "result": "\n".join(content.text for content in result.content if hasattr(content, 'text')),+ "is_error": result.isError+ }+ except Exception as retry_err:+ raise BridgeError(f"Proxy tool execution failed after reconnecting: {retry_err}") from retry_err++ async def shutdown(self) -> None:+ if self._exit_stack:+ await self._exit_stack.aclose()+ self._exit_stack = None+ self._connected = False+ self._session = Nonediff --git a/packages/mcp-server-revit/src/revit_mcp_server/server.py b/packages/mcp-server-revit/src/revit_mcp_server/server.pyindex cb91af0..c87a73a 100644--- a/packages/mcp-server-revit/src/revit_mcp_server/server.py+++ b/packages/mcp-server-revit/src/revit_mcp_server/server.py@@ -5,6 +5,7 @@ import ioimport jsonimport loggingimport sys+import osimport threadingfrom typing import Callable, Dict, Protocol@@ -18,10 +19,11 @@ from .providers import (AECMapperProvider,RhinoProvider,SemanticGraphProvider,- SpeckleProvider,AutodeskDataProvider,JobProvider,SQLiteExporterProvider,+ SpeckleProvider,+ McpProxyProvider,)from .jobs import JobManager@@ -85,15 +87,24 @@ class MCPServer:logger.warning("Could not initialize SemanticGraphProvider: %s", e)try:- self.registry.register(SpeckleProvider())+ self.registry.register(SpeckleProvider(workspace=self.workspace))except Exception as e:- logger.warning("Could not initialize SpeckleProvider: %s. Please set SPECKLE_CLIENT_ID.", e)+ logger.warning("Could not initialize SpeckleProvider: %s", e)try:self.registry.register(AutodeskDataProvider())except Exception as e:logger.warning("Could not initialize AutodeskDataProvider: %s. Please set APS_CLIENT_ID.", e)+ try:+ proxy_url = os.getenv("MCP_PROXY_URL")+ if proxy_url:+ proxy = McpProxyProvider(proxy_url)+ self._loop.create_task(proxy._connect())+ self.registry.register(proxy)+ except Exception as e:+ logger.warning("Could not initialize McpProxyProvider: %s", e)+def _run_loop(self) -> None:asyncio.set_event_loop(self._loop)self._loop.run_forever()diff --git a/packages/mcp-server-revit/tests/test_cloud_providers.py b/packages/mcp-server-revit/tests/test_cloud_providers.pyindex f5175c0..4fb3ce8 100644--- a/packages/mcp-server-revit/tests/test_cloud_providers.py+++ b/packages/mcp-server-revit/tests/test_cloud_providers.py@@ -380,3 +380,120 @@ async def test_redaction_in_errors_and_https_enforcement() -> None:)await localhost_provider.shutdown()await provider.shutdown()+++async def test_speckle_local_tools_no_account_error() -> None:+ from unittest.mock import patch+ from revit_mcp_server.errors import RevitMCPError++ provider = SpeckleProvider()++ with patch("revit_mcp_server.providers.cloud.get_default_account", return_value=None):+ with pytest.raises(RevitMCPError, match="No local Speckle account found"):+ await provider.execute_tool(+ "speckle_send_object",+ {"project_id": "p1", "model_name": "main", "data": {"a": 1}}+ )++ with pytest.raises(RevitMCPError, match="No local Speckle account found"):+ await provider.execute_tool(+ "speckle_receive_object",+ {"project_id": "p1", "version_id": "v1"}+ )+ await provider.shutdown()+++async def test_speckle_local_tools_send_and_receive_success() -> None:+ from unittest.mock import MagicMock, patch+ from specklepy.core.api.models.current import Model, ResourceCollection+ from specklepy.objects.base import Base+ from revit_mcp_server.errors import RevitMCPError++ provider = SpeckleProvider()++ # Create mock account and client+ mock_account = MagicMock()+ mock_account.serverInfo.url = "https://speckle.example"++ mock_client = MagicMock()++ # Mock get_models+ mock_model_1 = MagicMock(spec=Model)+ mock_model_1.id = "m1-id"+ mock_model_1.name = "main"+ mock_model_2 = MagicMock(spec=Model)+ mock_model_2.id = "m2-id"+ mock_model_2.name = "other"++ mock_collection = MagicMock(spec=ResourceCollection)+ mock_collection.items = [mock_model_1, mock_model_2]+ mock_client.model.get_models.return_value = mock_collection++ # Mock version.create+ mock_client.version.create.return_value = "v1-created-id"++ # Mock version.get+ mock_version = MagicMock()+ mock_version.referencedObject = "obj-123"+ mock_client.version.get.return_value = mock_version++ # Mock get_default_account & SpeckleClient+ with patch("revit_mcp_server.providers.cloud.get_default_account", return_value=mock_account), \+ patch("revit_mcp_server.providers.cloud.SpeckleClient", return_value=mock_client), \+ patch("revit_mcp_server.providers.cloud.ServerTransport", return_value=MagicMock()), \+ patch("revit_mcp_server.providers.cloud.operations.send", return_value="obj-123") as mock_send, \+ patch("revit_mcp_server.providers.cloud.operations.receive") as mock_receive:++ # Test send path: name -> ID resolution+ send_args = {+ "project_id": "p1",+ "model_name": "main", # Needs resolution to m1-id+ "data": {"foo": "bar", "token": "some_secret_token"},+ "message": "my commit message"+ }+ res = await provider.execute_tool("speckle_send_object", send_args)+ assert res["version_id"] == "v1-created-id"+ assert "Successfully sent data" in res["result"]++ # Verify models were queried and name main was resolved to m1-id+ mock_client.model.get_models.assert_called_once_with("p1", models_limit=100)+ mock_client.version.create.assert_called_once_with(+ project_id="p1",+ model_id="m1-id",+ object_id="obj-123",+ message="my commit message",+ source_application="AECModelBridge"+ )++ # Verify operations.send received a Base object with correct attributes+ assert mock_send.call_count == 1+ sent_base = mock_send.call_args[1]["base"]+ assert isinstance(sent_base, Base)+ assert sent_base.foo == "bar"+ assert sent_base.token == "some_secret_token"++ # Mock received Base object for receive path+ received_base = Base()+ received_base.foo = "bar_received"+ received_base.token = "sensitive_token_to_redact"+ mock_receive.return_value = received_base++ # Test receive path: deserialization of actual object data+ receive_args = {+ "project_id": "p1",+ "version_id": "v1-created-id"+ }+ receive_res = await provider.execute_tool("speckle_receive_object", receive_args)++ # Verify result structure+ mock_receive.assert_called_once_with(obj_id="obj-123", remote_transport=mock_receive.call_args[1]["remote_transport"])++ # Verify that result has data, and sensitive keys/tokens are redacted+ data = receive_res["result"]+ assert data["foo"] == "bar_received"+ assert data["token"] == "<redacted>"++ await provider.shutdown()+diff --git a/packages/mcp-server-revit/tests/test_provider_contract.py b/packages/mcp-server-revit/tests/test_provider_contract.pynew file mode 100644index 0000000..c06f20b--- /dev/null+++ b/packages/mcp-server-revit/tests/test_provider_contract.py@@ -0,0 +1,200 @@+import pytest+import os+import sys+from pathlib import Path+from typing import Any, Dict, List++from revit_mcp_server.config import BridgeMode+from revit_mcp_server.security.workspace import WorkspaceMonitor+from revit_mcp_server.providers.registry import ProviderRegistry+from revit_mcp_server.jobs import JobManager+from revit_mcp_server.security.audit import redact_data+from revit_mcp_server.errors import RevitMCPError++# Import providers+from revit_mcp_server.providers import (+ RevitProvider,+ IfcProvider,+ FakeProvider,+ AECMapperProvider,+ RhinoProvider,+ SemanticGraphProvider,+ SpeckleProvider,+ AutodeskDataProvider,+ JobProvider,+ SQLiteExporterProvider,+)+try:+ from revit_mcp_server.providers import McpProxyProvider+except ImportError:+ McpProxyProvider = None++# Global registries to check uniqueness across all tests+_all_provider_identities = set()+_all_tool_names = {}+_missing_mutation_metadata = []++# Parameterize over every registrable provider[email protected](scope="module")+def shared_workspace_dir(tmp_path_factory):+ return tmp_path_factory.mktemp("workspace")+[email protected](scope="module")+def shared_workspace_monitor(shared_workspace_dir):+ return WorkspaceMonitor([shared_workspace_dir])+[email protected](scope="module")+def shared_provider_registry():+ return ProviderRegistry()+[email protected](scope="module")+def shared_job_manager():+ return JobManager()+[email protected](params=[+ "revit",+ "ifc",+ "mapper",+ "exporter",+ "jobs",+ "graph",+ "fake",+ "speckle",+ "autodesk",+ "rhino",+ "proxy"+])+def provider_instance(request, shared_workspace_monitor, shared_provider_registry, shared_job_manager):+ name = request.param+ try:+ if name == "revit":+ return RevitProvider(workspace=shared_workspace_monitor, mode=BridgeMode.mock)+ elif name == "ifc":+ return IfcProvider(workspace=shared_workspace_monitor)+ elif name == "mapper":+ return AECMapperProvider(workspace=shared_workspace_monitor)+ elif name == "exporter":+ return SQLiteExporterProvider(workspace=shared_workspace_monitor, registry=shared_provider_registry)+ elif name == "jobs":+ return JobProvider(manager=shared_job_manager)+ elif name == "graph":+ return SemanticGraphProvider()+ elif name == "fake":+ return FakeProvider()+ elif name == "speckle":+ return SpeckleProvider(client_id="dummy")+ elif name == "autodesk":+ return AutodeskDataProvider(client_id="dummy")+ elif name == "rhino":+ return RhinoProvider(workspace=shared_workspace_monitor)+ elif name == "proxy":+ if McpProxyProvider is None:+ pytest.skip("McpProxyProvider class is not importable/available.")+ return McpProxyProvider(target_url="http://localhost:9876/sse")+ except Exception as e:+ pytest.skip(f"Provider {name} skipped because initialization failed: {e}")++async def test_provider_identity(provider_instance):+ identity = provider_instance.get_identity()+ assert isinstance(identity, str)+ assert len(identity) > 0+ # Stability: must return the same identity on consecutive calls+ assert provider_instance.get_identity() == identity++ # Global uniqueness (across all parameterized runs)+ assert identity not in _all_provider_identities, f"Duplicate provider identity: {identity}"+ _all_provider_identities.add(identity)++async def test_provider_capabilities_and_tools(provider_instance):+ identity = provider_instance.get_identity()++ if identity == "proxy":+ # McpProxyProvider will have an empty tool list if offline.+ # Skip gracefully rather than failing the contract.+ health = await provider_instance.check_health()+ if health.get("status") == "disconnected":+ pytest.skip("Proxy provider is disconnected offline, skipping capabilities check.")++ tools = provider_instance.get_capabilities()+ assert isinstance(tools, list)+ assert len(tools) > 0, f"Provider {identity} returned empty tool list"++ for tool in tools:+ # 1. Tool name non-empty string and globally unique+ assert isinstance(tool.name, str)+ assert len(tool.name) > 0+ assert tool.name not in _all_tool_names, f"Duplicate tool name '{tool.name}' found in provider '{identity}' (previously registered by '{_all_tool_names[tool.name]}')"+ _all_tool_names[tool.name] = identity++ # 2. Non-empty description+ assert isinstance(tool.description, str)+ assert len(tool.description.strip()) > 0, f"Tool '{tool.name}' has empty description"++ # 3. Input Schema shape check+ schema = getattr(tool, "input_schema", getattr(tool, "inputSchema", None))+ if schema is not None:+ assert isinstance(schema, dict)+ # Check if it has 'type' or 'properties'+ assert "type" in schema or "properties" in schema or schema == {}, f"Tool '{tool.name}' schema is not valid JSON-schema-shaped"++ # 4. Mutating metadata check+ mutating = getattr(tool, "mutating", None)+ if mutating is None:+ _missing_mutation_metadata.append((identity, tool.name))+ else:+ assert isinstance(mutating, bool)++async def test_execute_unknown_tool_raises_typed_error(provider_instance):+ # Calling an unknown tool name raises a typed error+ unknown_tool = "non_existent_tool_mcp_contract_test"+ with pytest.raises(Exception) as excinfo:+ await provider_instance.execute_tool(unknown_tool, {})++ # Ensure it's not a bare Exception+ assert excinfo.type is not Exception, f"Provider {provider_instance.get_identity()} raised a bare Exception"+ # Ensure it is a typed error (e.g. ValueError, KeyError, RevitMCPError)+ assert issubclass(excinfo.type, Exception)++def test_redaction_contract():+ # Synthetic result matching typical structure+ synthetic = {+ "access_token": "Bearer test-token-12345",+ "authorization": "Bearer token-abc",+ "win_path": "C:\\Users\\sammo\\Documents\\model.rvt",+ "posix_path": "/home/sammo/model.ifc",+ "nested": {+ "token": "secret-xyz",+ "message": "Error on C:\\Users\\sammo\\private.txt and /Users/sammo/private.key"+ }+ }++ redacted = redact_data(synthetic)++ # Assert bearer/token values are completely redacted to '<redacted>'+ assert redacted["access_token"] == "<redacted>"+ assert redacted["authorization"] == "<redacted>"+ assert redacted["nested"]["token"] == "<redacted>"++ # Assert paths in values are redacted to '<redacted-path>'+ assert redacted["win_path"] == "<redacted-path>"+ assert redacted["posix_path"] == "<redacted-path>"++ # Assert embedded paths in strings are redacted+ assert "C:\\Users\\sammo\\private.txt" not in redacted["nested"]["message"]+ assert "/Users/sammo/private.key" not in redacted["nested"]["message"]+ assert "<redacted-path>" in redacted["nested"]["message"]++def test_compile_mutation_metadata_report():+ # This is a final test to print/log the report of tools missing mutation metadata+ if _missing_mutation_metadata:+ print("\n\n" + "="*50)+ print("CONSOLIDATED REPORT: TOOLS MISSING MUTATION METADATA")+ print("="*50)+ for provider, tool in _missing_mutation_metadata:+ print(f"Provider: {provider:15} | Tool: {tool}")+ print("="*50 + "\n")+ else:+ print("\nAll tools have mutation metadata defined.\n")diff --git a/packages/mcp-server-revit/tests/test_proxy.py b/packages/mcp-server-revit/tests/test_proxy.pynew file mode 100644index 0000000..92cd7ff--- /dev/null+++ b/packages/mcp-server-revit/tests/test_proxy.py@@ -0,0 +1,83 @@+from __future__ import annotations++import pytest+from unittest.mock import MagicMock, patch, AsyncMock+from mcp.types import CallToolResult, Tool+from revit_mcp_server.providers.proxy import McpProxyProvider+from revit_mcp_server.errors import BridgeError++async def test_proxy_provider_flow() -> None:+ provider = McpProxyProvider("http://fake-target/sse")++ # Mock SSE Client stream context manager+ mock_read = MagicMock()+ mock_write = MagicMock()++ # Mock ClientSession+ mock_session = AsyncMock()+ mock_session.__aenter__.return_value = mock_session+ mock_session.initialize = AsyncMock()++ # Mock list_tools+ mock_tool = MagicMock(spec=Tool)+ mock_tool.name = "get_info"+ mock_tool.description = "Gets info"+ mock_tool.inputSchema = {"type": "object"}++ mock_tools_list = MagicMock()+ mock_tools_list.tools = [mock_tool]+ mock_session.list_tools.return_value = mock_tools_list++ # Mock call_tool+ mock_content = MagicMock()+ mock_content.text = "remote-tool-result"+ mock_call_result = MagicMock(spec=CallToolResult)+ mock_call_result.content = [mock_content]+ mock_call_result.isError = False+ mock_session.call_tool.return_value = mock_call_result++ # Mock sse_client and ClientSession inside proxy+ with patch("revit_mcp_server.providers.proxy.sse_client") as mock_sse_client, \+ patch("revit_mcp_server.providers.proxy.ClientSession", return_value=mock_session):++ # Mock sse_client enter/exit stack behavior+ mock_sse_client.return_value.__aenter__.return_value = (mock_read, mock_write)++ # 1. Initialize & verify tools listing+ await provider.initialize()+ assert provider.get_identity() == "proxy"+ assert await provider.check_health() == {"status": "ok"}++ capabilities = provider.get_capabilities()+ assert len(capabilities) == 1+ assert capabilities[0].name == "proxy_get_info"+ assert capabilities[0].description == "Gets info"++ # 2. Tool call round-trip+ exec_res = await provider.execute_tool("proxy_get_info", {"arg": "val"})+ assert exec_res["result"] == "remote-tool-result"+ assert exec_res["is_error"] is False+ mock_session.call_tool.assert_called_once_with("get_info", {"arg": "val"})++ # 3. Disconnect and Reconnect cycle+ # We can simulate SSE drop by making call_tool raise an exception,+ # which triggers reconnection and retry+ mock_session.call_tool.reset_mock()+ mock_session.call_tool.side_effect = [Exception("SSE dropped"), mock_call_result]++ exec_res_retry = await provider.execute_tool("proxy_get_info", {"arg": "val"})+ assert exec_res_retry["result"] == "remote-tool-result"+ # Since it raises once, then reconnects, and then retries successfully:+ assert mock_session.call_tool.call_count == 2++ # 4. Unreachable target error path+ # If connect_once fails repeatedly, check BridgeError is raised+ mock_sse_client.side_effect = Exception("Target unreachable")++ # Reset provider exit stack and connection state+ await provider.shutdown()++ with patch("asyncio.sleep", AsyncMock()): # skip delays in tests+ with pytest.raises(BridgeError, match="Failed to connect to proxy target"):+ await provider.initialize()diff --git a/packages/navisworks-bridge-addin/NavisworksBridge.csproj b/packages/navisworks-bridge-addin/NavisworksBridge.csprojnew file mode 100644index 0000000..34a40f9--- /dev/null+++ b/packages/navisworks-bridge-addin/NavisworksBridge.csproj@@ -0,0 +1,43 @@+<Project Sdk="Microsoft.NET.Sdk">+ <PropertyGroup>+ <NavisworksVersion Condition="'$(NavisworksVersion)'==''">2024</NavisworksVersion>+ <TargetFramework>net48</TargetFramework>+ <AssemblyName>NavisworksBridge</AssemblyName>+ <RootNamespace>NavisworksBridge</RootNamespace>+ <Version>1.1.0</Version>+ <OutputType>Library</OutputType>+ <OutputPath>bin\$(Configuration)\$(NavisworksVersion)\</OutputPath>+ <LangVersion>latest</LangVersion>+ <Nullable>enable</Nullable>+ <UseWPF>true</UseWPF>+ <UseWindowsForms>true</UseWindowsForms>+ <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>+ </PropertyGroup>++ <PropertyGroup>+ <NavisworksInstallPath Condition="'$(NavisworksVersion)'=='2024'">C:\Program Files\Autodesk\Navisworks Manage 2024</NavisworksInstallPath>+ <NavisworksInstallPath Condition="'$(NavisworksVersion)'=='2025'">C:\Program Files\Autodesk\Navisworks Manage 2025</NavisworksInstallPath>+ <NavisworksInstallPath Condition="'$(NavisworksVersion)'=='2026'">C:\Program Files\Autodesk\Navisworks Manage 2026</NavisworksInstallPath>+ <NavisworksInstallPath Condition="'$(NavisworksVersion)'=='2027'">C:\Program Files\Autodesk\Navisworks Manage 2027</NavisworksInstallPath>+ <UseLocalNavisworks Condition="Exists('$(NavisworksInstallPath)\Autodesk.Navisworks.Api.dll')">true</UseLocalNavisworks>+ <UseLocalNavisworks Condition="'$(UseLocalNavisworks)'==''">false</UseLocalNavisworks>+ </PropertyGroup>++ <ItemGroup Condition="'$(UseLocalNavisworks)'=='true'">+ <Reference Include="Autodesk.Navisworks.Api">+ <HintPath>$(NavisworksInstallPath)\Autodesk.Navisworks.Api.dll</HintPath>+ <Private>False</Private>+ </Reference>+ <Reference Include="Autodesk.Navisworks.Automation">+ <HintPath>$(NavisworksInstallPath)\Autodesk.Navisworks.Automation.dll</HintPath>+ <Private>False</Private>+ </Reference>+ </ItemGroup>++ <ItemGroup Condition="'$(UseLocalNavisworks)'=='false'">+ <!-- Fallback if not installed (dummy reference or NuGet if available) -->+ </ItemGroup>++ <ItemGroup>+ </ItemGroup>+</Project>diff --git a/packages/navisworks-bridge-addin/src/BridgeServer.cs b/packages/navisworks-bridge-addin/src/BridgeServer.csnew file mode 100644index 0000000..52c1f47--- /dev/null+++ b/packages/navisworks-bridge-addin/src/BridgeServer.cs@@ -0,0 +1,100 @@+using System;+using System.IO;+using System.Net;+using System.Threading.Tasks;+using System.Windows.Threading;+using Autodesk.Navisworks.Api;+using Application = Autodesk.Navisworks.Api.Application;++namespace NavisworksBridge+{+ public class BridgeServer+ {+ private HttpListener? _listener;+ private bool _isRunning;+ private readonly Dispatcher _dispatcher;++ public BridgeServer(Dispatcher dispatcher)+ {+ _dispatcher = dispatcher;+ }++ public void Start()+ {+ _listener = new HttpListener();+ _listener.Prefixes.Add("http://127.0.0.1:3002/");+ _listener.Start();+ _isRunning = true;+ Task.Run(ListenAsync);+ }++ public void Stop()+ {+ _isRunning = false;+ _listener?.Stop();+ }++ private async Task ListenAsync()+ {+ while (_isRunning && _listener != null && _listener.IsListening)+ {+ try+ {+ var context = await _listener.GetContextAsync();+ ProcessRequest(context);+ }+ catch (Exception)+ {+ // Listener stopped or error+ }+ }+ }++ private void ProcessRequest(HttpListenerContext context)+ {+ if (context.Request.Url.AbsolutePath == "/health")+ {+ SendJsonResponse(context, "{\"status\":\"healthy\",\"application\":\"navisworks\"}");+ return;+ }++ if (context.Request.Url.AbsolutePath == "/execute" && context.Request.HttpMethod == "POST")+ {+ using var reader = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding);+ var requestBody = reader.ReadToEnd();++ _dispatcher.Invoke(() =>+ {+ try+ {+ var doc = Application.ActiveDocument;+ // For now, just return active document title as proof of concept+ string title = doc.Title?.Replace("\"", "\\\"") ?? "";+ string fileName = doc.FileName?.Replace("\"", "\\\"") ?? "";+ string jsonResponse = "{\"status\":\"success\",\"title\":\"" + title + "\",\"fileName\":\"" + fileName + "\",\"modelsCount\":" + doc.Models.Count + "}";+ SendJsonResponse(context, jsonResponse);+ }+ catch (Exception ex)+ {+ string errMsg = ex.Message.Replace("\"", "\\\"");+ SendJsonResponse(context, "{\"status\":\"error\",\"message\":\"" + errMsg + "\"}");+ }+ });+ return;+ }++ // Not found+ context.Response.StatusCode = 404;+ context.Response.Close();+ }++ private void SendJsonResponse(HttpListenerContext context, string json)+ {+ byte[] buffer = System.Text.Encoding.UTF8.GetBytes(json);+ context.Response.ContentType = "application/json";+ context.Response.ContentLength64 = buffer.Length;+ context.Response.OutputStream.Write(buffer, 0, buffer.Length);+ context.Response.OutputStream.Close();+ }+ }+}diff --git a/packages/navisworks-bridge-addin/src/MainPlugin.cs b/packages/navisworks-bridge-addin/src/MainPlugin.csnew file mode 100644index 0000000..82e20fd--- /dev/null+++ b/packages/navisworks-bridge-addin/src/MainPlugin.cs@@ -0,0 +1,40 @@+using System;+using System.Windows.Threading;+using Autodesk.Navisworks.Api.Plugins;++namespace NavisworksBridge+{+ [Plugin("AECModelBridgeNavisworks", "Sam-AEC", DisplayName = "AEC Model Bridge", ToolTip = "Bridge to MCP Server")]+ [AddInPlugin(AddInLocation.AddIn)]+ public class MainPlugin : AddInPlugin+ {+ private static BridgeServer? _server;++ public override int Execute(params string[] parameters)+ {+ if (_server == null)+ {+ try+ {+ // Capture the main thread dispatcher+ var dispatcher = Dispatcher.CurrentDispatcher;+ _server = new BridgeServer(dispatcher);+ _server.Start();+ System.Windows.Forms.MessageBox.Show("AEC Model Bridge for Navisworks started on port 3002.");+ }+ catch (Exception ex)+ {+ System.Windows.Forms.MessageBox.Show("Failed to start AEC Model Bridge:\n" + ex.Message + "\n\n" + ex.StackTrace);+ _server = null;+ }+ }+ else+ {+ _server.Stop();+ _server = null;+ System.Windows.Forms.MessageBox.Show("AEC Model Bridge for Navisworks stopped.");+ }+ return 0;+ }+ }+}diff --git a/packages/revit-bridge-addin/src/Bridge/AdditionalCommands.cs b/packages/revit-bridge-addin/src/Bridge/AdditionalCommands.csindex f5f71d3..3ec146a 100644--- a/packages/revit-bridge-addin/src/Bridge/AdditionalCommands.cs+++ b/packages/revit-bridge-addin/src/Bridge/AdditionalCommands.cs@@ -137,11 +137,9 @@ namespace RevitBridge.Bridgevar dialog = new ModernDialog();dialog.SetTitle("About AEC Model Bridge", $"Version {ProductInfo.Version}");- dialog.AddStatusCard(- "MCP",+ dialog.AddBrandStatusCard("AEC Model Bridge",- "Independent MCP integration for Revit software",- new MediaBrush(MediaColor.FromRgb(33, 150, 243))+ "Independent MCP integration for Revit software");dialog.AddSeparator();diff --git a/packages/revit-bridge-addin/src/UI/IconGenerator.cs b/packages/revit-bridge-addin/src/UI/IconGenerator.csindex f906c8a..7fdfc17 100644--- a/packages/revit-bridge-addin/src/UI/IconGenerator.cs+++ b/packages/revit-bridge-addin/src/UI/IconGenerator.cs@@ -38,27 +38,24 @@ namespace RevitBridge.UI}/// <summary>- /// Creates a Connect icon (network node bridge with emerald accent)+ /// Creates a Connect icon (network node bridge fully accented in emerald green)/// </summary>public static BitmapSource CreateConnectIcon(int size = 32){var visual = new DrawingVisual();using (var context = visual.RenderOpen()){- bool isDark = IsDarkTheme();- var primaryBrush = isDark ? Brushes.White : new SolidColorBrush(Color.FromRgb(30, 41, 59));var accentBrush = new SolidColorBrush(Color.FromRgb(46, 125, 50)); // Emerald Greenvar softFillBrush = new SolidColorBrush(Color.FromArgb(64, 46, 125, 50)); // Semi-transparent green- var pen = new Pen(primaryBrush, StrokeWidth(size, 0.06)) { StartLineCap = PenLineCap.Round, EndLineCap = PenLineCap.Round, LineJoin = PenLineJoin.Round };var accentPen = new Pen(accentBrush, StrokeWidth(size, 0.06)) { StartLineCap = PenLineCap.Round, EndLineCap = PenLineCap.Round, LineJoin = PenLineJoin.Round };// Left node- context.DrawEllipse(softFillBrush, pen, new Point(size * 0.19, size * 0.72), size * 0.14, size * 0.14);+ context.DrawEllipse(softFillBrush, accentPen, new Point(size * 0.19, size * 0.72), size * 0.14, size * 0.14);// Right node- context.DrawEllipse(softFillBrush, pen, new Point(size * 0.81, size * 0.72), size * 0.14, size * 0.14);+ context.DrawEllipse(softFillBrush, accentPen, new Point(size * 0.81, size * 0.72), size * 0.14, size * 0.14);// Connecting bridge lines- context.DrawLine(pen, new Point(size * 0.33, size * 0.72), new Point(size * 0.67, size * 0.72));+ context.DrawLine(accentPen, new Point(size * 0.33, size * 0.72), new Point(size * 0.67, size * 0.72));// Server/AI node (Top center)var geometry = new PathGeometry();@@ -69,30 +66,29 @@ namespace RevitBridge.UIcontext.DrawGeometry(softFillBrush, accentPen, geometry);// Connector lines from bottom nodes to top server node- context.DrawLine(pen, new Point(size * 0.27, size * 0.61), new Point(size * 0.38, size * 0.40));- context.DrawLine(pen, new Point(size * 0.73, size * 0.61), new Point(size * 0.62, size * 0.40));+ context.DrawLine(accentPen, new Point(size * 0.27, size * 0.61), new Point(size * 0.38, size * 0.40));+ context.DrawLine(accentPen, new Point(size * 0.73, size * 0.61), new Point(size * 0.62, size * 0.40));}return RenderVisual(visual, size, size);}/// <summary>- /// Creates a Disconnect icon (network node bridge with broken links and crimson cancel slash)+ /// Creates a Disconnect icon (network node bridge fully accented in crimson red with cancel slash)/// </summary>public static BitmapSource CreateDisconnectIcon(int size = 32){var visual = new DrawingVisual();using (var context = visual.RenderOpen()){- bool isDark = IsDarkTheme();- var primaryBrush = isDark ? Brushes.White : new SolidColorBrush(Color.FromRgb(30, 41, 59));var accentBrush = new SolidColorBrush(Color.FromRgb(211, 47, 47)); // Crimson Red- var pen = new Pen(primaryBrush, StrokeWidth(size, 0.06)) { StartLineCap = PenLineCap.Round, EndLineCap = PenLineCap.Round, LineJoin = PenLineJoin.Round };+ var softFillBrush = new SolidColorBrush(Color.FromArgb(32, 211, 47, 47)); // Very transparent red for nodes+ var accentPen = new Pen(accentBrush, StrokeWidth(size, 0.06)) { StartLineCap = PenLineCap.Round, EndLineCap = PenLineCap.Round, LineJoin = PenLineJoin.Round };// Left node- context.DrawEllipse(null, pen, new Point(size * 0.19, size * 0.72), size * 0.14, size * 0.14);+ context.DrawEllipse(softFillBrush, accentPen, new Point(size * 0.19, size * 0.72), size * 0.14, size * 0.14);// Right node- context.DrawEllipse(null, pen, new Point(size * 0.81, size * 0.72), size * 0.14, size * 0.14);+ context.DrawEllipse(softFillBrush, accentPen, new Point(size * 0.81, size * 0.72), size * 0.14, size * 0.14);// Top server nodevar geometry = new PathGeometry();@@ -100,11 +96,11 @@ namespace RevitBridge.UIfigure.Segments.Add(new LineSegment(new Point(size * 0.68, size * 0.42), true));figure.Segments.Add(new LineSegment(new Point(size * 0.32, size * 0.42), true));geometry.Figures.Add(figure);- context.DrawGeometry(null, pen, geometry);+ context.DrawGeometry(softFillBrush, accentPen, geometry);// Broken connections- context.DrawLine(pen, new Point(size * 0.27, size * 0.61), new Point(size * 0.36, size * 0.44));- context.DrawLine(pen, new Point(size * 0.73, size * 0.61), new Point(size * 0.64, size * 0.44));+ context.DrawLine(accentPen, new Point(size * 0.27, size * 0.61), new Point(size * 0.36, size * 0.44));+ context.DrawLine(accentPen, new Point(size * 0.73, size * 0.61), new Point(size * 0.64, size * 0.44));// Crimson cancel slashvar slashPen = new Pen(accentBrush, StrokeWidth(size, 0.08)) { StartLineCap = PenLineCap.Round, EndLineCap = PenLineCap.Round };diff --git a/packages/revit-bridge-addin/src/UI/ModernDialog.xaml b/packages/revit-bridge-addin/src/UI/ModernDialog.xamlindex ce10710..e0cef06 100644--- a/packages/revit-bridge-addin/src/UI/ModernDialog.xaml+++ b/packages/revit-bridge-addin/src/UI/ModernDialog.xaml@@ -128,10 +128,14 @@<ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions>- <!-- Icon/Logo --><Viewbox Grid.Column="0" Width="36" Height="36" Margin="15,0,10,0">- <Canvas Width="24" Height="24">- <Path Fill="White" Data="M12,2L2,7V17L12,22L22,17V7M12,4.4L19.2,8.2V15.8L12,19.6L4.8,15.8V8.2"/>+ <Canvas Width="200" Height="200">+ <!-- Top face (light blue) -->+ <Polygon Points="50,80 80,50 140,50 110,80" Fill="#93c5fd" Stroke="#1e293b" StrokeThickness="3" />+ <!-- Front face (bright blue) -->+ <Polygon Points="50,80 110,80 110,140 50,140" Fill="#60a5fa" Stroke="#1e293b" StrokeThickness="3" />+ <!-- Right side face (medium blue) -->+ <Polygon Points="110,80 140,50 140,110 110,140" Fill="#3b82f6" Stroke="#1e293b" StrokeThickness="3" /></Canvas></Viewbox>diff --git a/packages/revit-bridge-addin/src/UI/ModernDialog.xaml.cs b/packages/revit-bridge-addin/src/UI/ModernDialog.xaml.csindex 531a709..8d4e535 100644--- a/packages/revit-bridge-addin/src/UI/ModernDialog.xaml.cs+++ b/packages/revit-bridge-addin/src/UI/ModernDialog.xaml.cs@@ -164,6 +164,68 @@ namespace RevitBridge.UIGrid.SetColumn(textStack, 1);grid.Children.Add(textStack);+ card.Child = grid;+ ContentPanel.Children.Add(card);+ }++ public void AddBrandStatusCard(string label, string value)+ {+ var card = new Border+ {+ Style = (Style)FindResource("StatCard"),+ MinHeight = 60+ };++ var grid = new Grid();+ grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(50) });+ grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });++ // Cube Icon+ var viewBox = new Viewbox+ {+ Width = 40,+ Height = 40,+ VerticalAlignment = VerticalAlignment.Center,+ HorizontalAlignment = HorizontalAlignment.Center+ };+ var canvas = new Canvas { Width = 200, Height = 200 };+ canvas.Children.Add(new System.Windows.Shapes.Polygon { Points = new PointCollection(new[] { new Point(50, 80), new Point(80, 50), new Point(140, 50), new Point(110, 80) }), Fill = new SolidColorBrush(Color.FromRgb(147, 197, 253)), Stroke = new SolidColorBrush(Color.FromRgb(30, 41, 59)), StrokeThickness = 3 });+ canvas.Children.Add(new System.Windows.Shapes.Polygon { Points = new PointCollection(new[] { new Point(50, 80), new Point(110, 80), new Point(110, 140), new Point(50, 140) }), Fill = new SolidColorBrush(Color.FromRgb(96, 165, 250)), Stroke = new SolidColorBrush(Color.FromRgb(30, 41, 59)), StrokeThickness = 3 });+ canvas.Children.Add(new System.Windows.Shapes.Polygon { Points = new PointCollection(new[] { new Point(110, 80), new Point(140, 50), new Point(140, 110), new Point(110, 140) }), Fill = new SolidColorBrush(Color.FromRgb(59, 130, 246)), Stroke = new SolidColorBrush(Color.FromRgb(30, 41, 59)), StrokeThickness = 3 });+ viewBox.Child = canvas;++ Grid.SetColumn(viewBox, 0);+ grid.Children.Add(viewBox);++ var textStack = new StackPanel+ {+ VerticalAlignment = VerticalAlignment.Center,+ Margin = new Thickness(10, 0, 0, 0)+ };++ var labelText = new TextBlock+ {+ Text = label,+ FontSize = 12,+ Foreground = (Brush)FindResource("TextSecondaryBrush"),+ Margin = new Thickness(0, 0, 0, 5),+ TextWrapping = TextWrapping.Wrap+ };++ var valueText = new TextBlock+ {+ Text = value,+ FontSize = 18,+ FontWeight = FontWeights.SemiBold,+ Foreground = (Brush)FindResource("TextPrimaryBrush"),+ TextWrapping = TextWrapping.Wrap+ };++ textStack.Children.Add(labelText);+ textStack.Children.Add(valueText);+ Grid.SetColumn(textStack, 1);+ grid.Children.Add(textStack);+card.Child = grid;ContentPanel.Children.Add(card);}diff --git a/scripts/build-addin.ps1 b/scripts/build-addin.ps1index c4da601..e9087f5 100644--- a/scripts/build-addin.ps1+++ b/scripts/build-addin.ps1@@ -49,4 +49,33 @@ $targetFramework = switch ($RevitVersion) {"2027" { "net10.0-windows" }}$outputPath = Join-Path $PSScriptRoot "..\packages\revit-bridge-addin\bin\$Configuration\$RevitVersion\$targetFramework\AECModelBridge.dll"-Write-Host "Build succeeded: $([System.IO.Path]::GetFullPath($outputPath))" -ForegroundColor Green+Write-Host "Revit Build succeeded: $([System.IO.Path]::GetFullPath($outputPath))" -ForegroundColor Green++# Build Navisworks Add-in+$navisworksPath = "$PSScriptRoot\..\packages\navisworks-bridge-addin\NavisworksBridge.csproj"+if (Test-Path $navisworksPath) {+ Write-Host "Building AEC Model Bridge for Navisworks $RevitVersion ($Configuration)..." -ForegroundColor Cyan++ # Install to Navisworks 2026+ $navisTargetDir = "$env:APPDATA\Autodesk\Navisworks Manage 2026\Plugins\NavisworksBridge"+ if (-not (Test-Path $navisTargetDir)) {+ New-Item -ItemType Directory -Force -Path $navisTargetDir | Out-Null+ }++ & $dotnet.Source build $navisworksPath -c $Configuration -p:NavisworksVersion=$RevitVersion -v:minimal+ if ($LASTEXITCODE -ne 0) {+ Write-Error "Navisworks build failed with exit code $LASTEXITCODE"+ exit $LASTEXITCODE+ }++ # Navisworks Manage is still on .NET Framework 4.8 for 2024-2026+ $nwOutDir = Join-Path $PSScriptRoot "..\packages\navisworks-bridge-addin\bin\$Configuration\$RevitVersion\net48"+ $nwOutputPath = Join-Path $nwOutDir "NavisworksBridge.dll"++ if (Test-Path $nwOutDir) {+ Copy-Item "$nwOutDir\*" -Destination $navisTargetDir -Recurse -Force+ Write-Host "Navisworks Build succeeded and deployed: $([System.IO.Path]::GetFullPath($nwOutputPath))" -ForegroundColor Green+ } else {+ Write-Error "Could not find Navisworks output directory: $nwOutDir"+ }+}