Skip to main content

Trusted C# execution

Trusted C# extends the shared native operation layer with explicitly reviewed query and modify method bodies. CLI, external MCP clients and the optional built-in Agent can use the same execution contracts. This guide describes permissions, transactions, bounds and qualification; isolated development provides the repeatable fixture-copy workflow.

Enable and execute​

Dynamic execution is disabled by default. For a trusted, disposable Revit session, launch Revit with REVITTHYME_TRUSTED_CODE=1 in its process environment. This setting is captured at add-in startup. Changing an MCP client's environment cannot enable it in an already running host. Ordinary utilities work without this setting.

Connect explicitly to the intended process/session, call get_context, then call run_query or run_modify with that captureId, a new GUID requestId, a C# source method body and trusted: true.

return new {
view = doc.ActiveView.Name,
walls = new FilteredElementCollector(doc).OfClass(typeof(Wall)).GetElementCount()
};

Available variables are doc (captured Document), uiapp (UIApplication) and cancellationToken. Imports include System, LINQ, generic collections, threading and the Revit DB, Architecture and UI namespaces. Use fully qualified names for other namespaces. Return JSON data, not live Revit objects, deferred enumerables or tasks. The host runs the code synchronously in its ExternalEvent API callback and owns its transaction. Do not open or commit a top-level transaction in submitted code. No packages, files, API lookup/reflection endpoint or agent runtime are automatically loaded.

run_query serializes the result then always rolls back the current-document transaction/group. It can therefore query temporary geometry without retaining it. It requires an editable document because rollback needs a transaction. run_modify regenerates, commits and captures native added/modified/deleted IDs from DocumentChanged, then assimilates the group into one Undo item. Compiler errors open no transaction. Runtime, serialization, result-size and returned-budget failures roll back. Rollback checks native completion status and the full element-ID set; uncertain outcomes report unconfirmed.

Trust, bounds and recovery​

Arbitrary C# has the Revit process's privileges. It is not sandboxed. Transaction rollback covers the current Revit document; it cannot undo file/network activity, UI changes or changes deliberately made to other documents. Both MCP tools are therefore annotated as potentially destructive, including query. Use reviewed code and disposable models first. Do not use these tools for untrusted submissions.

Source is bounded to 24 KiB UTF-8; returned JSON to 8 KiB; native change reports to 512 IDs; diagnostics to 12 bounded entries with source line/column. Each result records the source SHA-256 and elapsed milliseconds. Raw source is retained in session request memory for exact replay, not written automatically to a log. Test reports do contain submitted source and local paths and belong in private artifacts.

budgetMilliseconds defaults to 10000, range 100–30000. The token supports cooperative cancellation; the host also checks elapsed execution/serialization time after return. There is no hard timeout or interruption of an infinite loop in Revit's process. Compile time is included in reported elapsed time but excluded from the execution budget. A disconnected caller cannot stop running code. Queued cancellation prevents execution; running code finishes and retains its outcome. After a transport timeout, poll get_operation with the original ID. Replay only identical arguments/ID. A new ID could run the code twice. Refresh context after execution or rollback because native revisions can change.

CLI uses exactly the same operation and caller-supplied request ID:

.\project.cmd cli inspect --session C:\test\session.json --json > C:\test\capture.json
.\project.cmd cli run-query --session C:\test\session.json --capture C:\test\capture.json --source C:\test\query.csx --trusted true --request-id YOUR_GUID --json
.\project.cmd cli get-operation --session C:\test\session.json --request-id YOUR_GUID --json

Use run-modify for a committed edit. CLI returns JSON, exit 0 for success, 1 for a native rejection/rollback/uncertain result, and 2 for invalid CLI input/connection failure. The current native bridge uses protocol 14; install matching add-in/Core/CLI/MCP binaries. Roslyn 5.9.0 is pinned and bundled next to the add-in; Autodesk assemblies remain locally supplied.

Saved tool inputs and tests​

Reusable Tool Builder saves an individual trusted C# definition with typed inputs, expected results and concrete tests. MCP run_tool and CLI tool run load the exact digest-selected definition and validate the supplied input object before using the existing native execution operation. Stored query tools use run_query; stored modify tools use run_modify.

Authored method bodies can read a System.Text.Json.JsonElement named inputs, for example inputs.GetProperty("text").GetString(). The caller supplies JSON data, never C# fragments or string replacements. The adapter serializes validated inputs in a stable order and prepends their JSON binding to the method body. inputs is reserved for that binding. The final expanded source, including the binding, must fit 24 KiB UTF-8. Compiler source locations map back to the authored body.

The saved definition digest identifies the complete saved contract. The native result's sourceSha256 identifies the expanded submission, so different input values can produce different source hashes for the same definition. Request replay requires the same tool digest, inputs, execution/test choice and other native arguments. Poll the original request ID after an uncertain result before submitting another edit.

A saved test contains input values, model assumptions, an expected-result description and an assertion body returning a Boolean. Running with a test name executes that assertion as a rollback query; it does not first run the main tool. Prepare the stated disposable fixture, run the main tool explicitly, inspect its outcome, then run the assertion with a fresh capture. A saved definition reports not_run; its existence or a successful native operation is not proof that a test passed. This release does not manage test fixtures, promote tested versions or repair failures automatically.

All existing full-process trust limits apply to saved source and assertions. Rollback does not undo external side effects. Definition storage is private user data; keep source, inputs and returned model data out of public repositories when they contain project information.

Workflow result checks​

A saved tool can include a structured result-check plan alongside its expected-result description. After its main operation has definitely succeeded, the adapter reads the specified native observations and compares them with the plan. Expected values describe the intended result; allowed-change rules define which added, modified and deleted element IDs the operation may affect. A successful API call alone does not prove those expectations.

The original operation and its check report remain separate. An Applied modification stays Applied if its result check fails or cannot be confirmed. Inspect the native result and report before deciding what to do next. Checking does not automatically Undo, rerun, repair, save or sync the model. Existing saved definitions without a plan keep their original execution behavior, and a named test assertion remains an explicitly requested rollback query.

Checks use the authoritative retained native operation and its exact target, including document/view revision. Their attribution identifies the definition, plan and inputs used. After response loss, recover the original request before checking it; a new edit request is not a recovery method. If the expected native state can no longer be established, the report must show uncertainty rather than infer a pass from stale data or an operation's returned prose.

Observation source runs through a native path without a writable model transaction. Core compares the returned structured data; a checker cannot establish success by temporarily writing the expected value into the current document. This is still trusted C# with full process privileges, not a sandbox: file, network and deliberately accessed external-document side effects remain outside the observation contract. Use reviewed observation code and disposable fixtures first.

See the MCP result-check contract and CLI commands for plan fields, reports and explicit verification of retained operations. A report covers only its declared observations and change rules. Managed test execution, workflow construction and durable run logs remain separate features.

Disposable qualification and Cabin Eval​

Use isolated development to run reviewed C# against a disposable model. Capture the native outcome, then confirm Undo independently. See the Cabin Eval record for previous results and limits.

Apply a reviewed operation separately against a fresh capture for any later working-model edit. Production worksharing, other Revit releases and machines, untrusted code isolation, and hard interruption remain unqualified.