C# scripting plugins
FabrCore 2.0 · Release and package availability
These guides track the current 2.0 source. Stable 2.0.0 publication is pending; package commands show the release target. Until it is published, follow the source quick start or use a matching available prerelease set. Release migration · Runtime modes
Let an agent write C# to calculate, reshape data and create small reports. Your application defines the available packages in a reusable plugin. Each script runs in a fresh .NET process.
FabrCore.Scripting is an optional package targeting .NET 10. Stable 2.0.0 package publication is pending; use matching packages built from the current source until publication. The downloadable OperationsDesk.Scripting checkpoint needs no model or API key.
Where scripting fits
Use scripts when the calculation or transformation varies with the question: grouping query results, calculating totals, parsing a document with a library, or producing a small file. Keep database authorization, credentials and business operations in application-owned tools. Those tools can return bounded, authorized data for the script to transform. A familiar C# syntax helps models write code, but it does not supply your database schema or guarantee correct calculations.
A plugin chooses the packages and guidance. An agent selects the plugin. Many agents can reuse the same setup; another plugin can define a different package set or version. Select one scripting plugin per agent because the inherited tool names are shared.
Register the runtime and define a plugin
Reference FabrCore.Scripting in the application or agent library. Register the runtime once in the application's services:
using FabrCore.Scripting;
builder.Services.AddFabrCoreScripting(options =>
{
options.CacheDirectory = Path.Combine(builder.Environment.ContentRootPath, "scripting-cache");
options.WorkingDirectory = Path.Combine(Path.GetTempPath(), "my-app-scripts");
// Optional private feeds: options.NuGetConfigPath = "/deployment/NuGet.Config";
});Derive from CSharpScriptingPluginBase and override Configure. The base class owns initialization, tool methods and disposal. Package setup is developer code; the model does not choose packages to install.
using FabrCore.Scripting;
using FabrCore.Sdk;
[PluginAlias("reporting-scripts")]
public sealed class ReportingScriptsPlugin : CSharpScriptingPluginBase
{
protected override void Configure(ScriptingEnvironmentBuilder environment) => environment
.AddPackage("Newtonsoft.Json", "13.0.3")
.AddImports("Newtonsoft.Json.Linq")
.WithTimeout(TimeSpan.FromSeconds(30))
.WithMemoryLimit(512L * 1024 * 1024)
.WithOutputLimit(32_768)
.WithArtifactLimit(1_048_576)
.WithInstructions("Use JObject.Parse(InputJson) to parse query results. " +
"Return a small JSON-serializable summary; check that inputs are complete.");
}AddPackage requires an exact version, including exact prereleases. Ranges and floating versions are rejected. NuGet restores transitive dependencies and records the graph in packages.lock.json. Roslyn packages are reserved to the worker. Your own helper or API-client packages can come from private feeds; they must work in a .NET 10 console process on the target platform. Package build targets execute during preparation, so package configuration is trusted application code.
Select the plugin in the agent
Include the concrete plugin assembly in normal FabrCore discovery. Add its alias before resolving tools in FabrCoreAgentProxy.OnInitialize. This uses the same registry as other FabrCore plugins.
if (!config.Plugins.Contains("reporting-scripts"))
config.Plugins.Add("reporting-scripts");
var tools = await ResolveConfiguredToolsAsync();
var created = await CreateChatClientAgent(
chatClientConfigName: config.Models ?? "default",
threadId: config.Handle ?? fabrcoreAgentHost.GetHandle(),
tools: tools);
agent = created.Agent;
session = created.Session;The model receives GetScriptingEnvironment and ExecuteCSharp. It should inspect the environment before writing code. Provide useful library signatures and examples through WithInstructions or normal agent knowledge. A package name alone does not explain a custom API.
How the result gets back to the agent
- The model calls
ExecuteCSharpwith source code and optional JSON input. - The plugin starts a fresh worker with the prepared packages. Roslyn evaluates the script there.
- The worker serializes the returned value into bounded JSON, alongside status, console output and any error.
- The host reads that response, collects bounded artifact bytes and removes the temporary execution directory.
- The plugin returns a
ScriptExecutionResultthrough the normal function-call result. The model can use it in its answer or correct a failed script. Trusted code invoking the plugin can inspect the same result directly.
| Script global | Meaning |
|---|---|
Input | JSON input as a JsonElement; JSON null if omitted. |
InputJson | The same input as text, convenient for Newtonsoft.Json. |
OutputDirectory | This invocation's output folder for collected files. |
var data = JObject.Parse(InputJson);
var total = data["orders"]!.Values<decimal>().Sum();
Console.WriteLine("Calculated order total.");
return new { Customer = data["customer"]!.ToString(), Total = total };The result has Status = Success, a Value containing {"Customer":"Eric","Total":400}, and separate console text in Output. Returning an object supplies data; printing it supplies diagnostic text. Check Status before reading Value.
| Result field | Use |
|---|---|
Status | Success, CompilationError, RuntimeError, TimedOut, Cancelled, MemoryLimitExceeded, OutputLimitExceeded or WorkerError. |
Value | Nullable JsonElement serialized from the script's return value. |
Output / Error | Bounded console output and compiler/runtime/worker error details. |
Artifacts | File names and byte arrays, subject to count and combined-size limits. |
Files and Blazor presentation
var path = System.IO.Path.Combine(OutputDirectory, "summary.csv");
System.IO.File.WriteAllText(path, "Customer,Total\nEric,400\n");
return new { File = "summary.csv", Total = 400 };The host returns the file's bytes as an artifact. Your application must store them and create a download link; the worker directory is removed after collection. At most 100 files and the configured combined byte limit are collected. Large byte arrays can consume model context, so applications can intercept and store them before presentation.
For Blazor, validate the returned data and render it with known components, or offer a stored artifact as a download. This feature is not a Razor compiler or a dynamic component loader. Scripts cannot receive live agent objects, DI services or a Blazor circuit across the process boundary.
Try the Surface sales demo
In the framework's SampleApp, open Surface and select scripting-demo (full handle demo-user:scripting-demo). Ask: “Use C# to calculate total demo sales revenue and break it down by category.” The blueprint provisions the agent and its SalesScriptingPlugin.
The agent calls GetDemoSales, inspects GetScriptingEnvironment, and passes the authorized fixture data to ExecuteCSharp. Expect three orders totaling USD 400: Bikes 250 and Accessories 150. A report request returns a sales-report.json artifact to the tool caller. Chat summarizes it; the sample does not host artifact downloads.
Chat requires your configured model. The deterministic test below verifies the same blueprint-selected plugin, real worker, calculations and artifact without model calls. First preparation needs the .NET 10 SDK and package access. Run this as a trusted local demo.
dotnet test samples/FabrCore.SampleApp.Tests/FabrCore.SampleApp.Tests.csproj --configuration Release --filter FullyQualifiedName~ScriptingDemoTestsSee the SampleApp setup and expected results. The downloadable Operations Desk checkpoint remains a separate, smaller example that needs no Host or model.
Prepare packages for deployment
First initialization prepares and caches the worker using the .NET 10 SDK, Roslyn 5.0.0 and the declared packages. Each execution needs the .NET 10 runtime. The dependency cache is keyed by package versions, worker source/protocol and target platform. Imports, guidance and execution limits remain per plugin. There is no shared script session and no worker pooling.
var runtime = app.Services.GetRequiredService<ScriptingRuntime>();
await runtime.PreparePluginAsync<ReportingScriptsPlugin>(app.Services);To run without SDK or package-feed access in production, prewarm on the target OS/architecture, preserve the cache, and set AllowEnvironmentPreparation = false on the production runtime. A missing environment then fails initialization. MSBuild does not discover plugin configuration automatically. Keep the cache private to the application identity and explicitly reprepare it when refreshing transitive dependencies.
ScriptingRuntimeOptions also provides DotnetPath, NuGetConfigPath, PreparationTimeout, MaxCodeCharacters and MaxInputCharacters. Default preparation timeout is five minutes; code and input limits are 128 Ki and 1 Mi characters respectively.
Limits and the execution boundary
The current implementation has process isolation and execution limits, but no OS-enforced security sandbox. A script runs under the same operating-system account as the FabrCore host. The following controls help manage ordinary failures and excessive output; they do not contain hostile code.
Protections available today
| Protection | What it does |
|---|---|
| Separate worker process | Roslyn and script dependencies run outside the agent process. Ordinary script exceptions and unexpected worker exits become tool errors. |
| JSON boundary | Scripts receive input data rather than live agent objects, DI services or Blazor circuits. |
| Filtered environment | Host environment variables such as API keys, connection strings and startup hooks are not automatically inherited. A small set of runtime variables is retained. |
| Timeout and cancellation | The default deadline is 30 seconds, including worker startup and compilation. The supervisor attempts to terminate the worker and its child processes on cancellation or timeout. |
| Memory monitoring | The supervisor samples worker working-set memory roughly every 50 ms, with a default 512 MiB limit. This is a best-effort check, not a hard quota or a limit across all child processes. |
| Bounded results | Code/input sizes, console output, JSON results and collected artifacts have limits. Defaults include 32,768 console characters, 1 MiB of combined artifacts and at most 100 artifacts. |
| Developer-defined packages | Developers select exact package versions. Script #r and #load directives are disabled. Package configuration controls preparation, not permissions. |
| Fresh execution directory | Each invocation starts with a new worker and temporary directory. The runtime attempts directory cleanup afterward; scripts have no managed persistent session. |
JSON return values and error text are bounded separately; the return value uses a conservative UTF-8 byte bound equal to the output character limit. Normal proxy tool resolution owns plugin disposal through teardown; direct registry callers should dispose the scope returned by ResolveToolScopeAsync.
These controls are implemented in WorkerProcess and ScriptingRuntime.
What remains accessible
When the host account's permissions allow it, a script can still:
- Read or modify files outside its execution directory, including application configuration.
- Make network requests and contact internal services.
- Start other processes or invoke native functionality. A process that deliberately escapes supervision is not contained by this implementation.
- Access or modify shared scripting caches and other resources available to the host account.
- Consume disk space. The artifact limit restricts what gets returned, not how much a script can write.
- Leave external changes behind after a timeout. Terminating a worker does not roll back file changes or network operations.
For example: removing a database password from the worker's environment does not protect that password if the worker can read it from the host's configuration file. Similarly, OutputDirectory identifies where to place returned files; it does not restrict filesystem access. Declared NuGet packages do not act as an API permission allowlist.
Isolating untrusted workloads
OS-enforced sandbox protections are not available in the current scripting runtime. Supply an external restricted execution boundary for untrusted workloads; this release makes no sandbox availability or delivery-date promise.
A full sandbox needs an execution boundary that enforces:
- A restricted execution identity, separated from the host's permissions and credentials.
- Filesystem restrictions that expose only the required inputs and output storage.
- Network restrictions that control outbound and internal-service access.
- OS-enforced resource quotas, including memory, CPU and disk usage.
- Process containment that covers child processes and prevents escape from supervision.
Putting the FabrCore host and script worker inside the same container still leaves them sharing that container's accessible resources. The script execution boundary must enforce the intended separation from the host and other workloads.
Continue with results, artifacts and failure exercises, or install the coding assistant skill with its complete source assets and runtime reference. The source reference records the current runtime behavior and validation commands.