Configuration

Configure sampling, logging, capture, pairing, artifact providers, tool registration, and guard policy with the Ansight options builder.

The .NET SDK is configured through Options.CreateBuilder().

For most development builds, start with the setup package that matches the app.

Standard .NET apps:

using Ansight;

var options = Options.CreateBuilder()
    .WithAnsightSdk(ansight =>
    {
        ansight.WithBundledHostConnection(typeof(AppBootstrap).Assembly);
    })
    .Build();

Runtime.InitializeAndActivate(options);

.NET MAUI apps:

using Ansight.Maui;

builder.UseAnsight<App>();

The all-in-one setup applies FPS sampling, 400ms sampling, 120s retention, JPEG capture at 2000ms/quality-60/max-width-480, host auto-probe, bundled host connection, platform pairing where supported, tool registration, and full tool access. Battery level telemetry and touch capture stay opt-in. The callback runs after runtime defaults and before default tool-suite registration:

using Ansight;
using Ansight.Tools.SecureStorage;

var options = Options.CreateBuilder()
    .WithAnsightSdk(ansight =>
    {
        ansight.WithSecureStorageTools(secure =>
        {
            secure.WithStorageIdentifier("MyApp");
            secure.AllowKeyPrefix("ansight.secure.");
        });
    })
    .Build();

If the callback registers a suite such as secure storage or preferences, the all-in-one setup skips its default registration for that suite and keeps the configured version. Full tool access is applied before the callback, so the callback can also narrow the guard with WithReadOnlyToolAccess(), WithReadWriteToolAccess(), or WithToolGuard(...).

MethodPackagePurpose
WithAnsightSdk(...)AnsightApply runtime defaults, non-MAUI tools, platform pairing, bundled host config, host auto-probe, JPEG capture, and full tool access.
WithAnsightDefaults()AnsightApply runtime defaults without registering tools or enabling tool access.
WithAnsightRemoteTools()AnsightRegister all non-MAUI remote tools only, skipping suites already registered on the builder.
WithAnsightMaui(...)Ansight.MauiApply the base all-in-one setup and register MAUI tools, skipping suites already registered on the builder.
UseAnsight(...)Ansight.MauiInitialize and activate Ansight from MauiAppBuilder.

See .NET Setup Packages for package selection and full examples.

Minimal Example

using Ansight;

var options = Options.CreateBuilder()
    .WithFramesPerSecond()
    .WithRetentionPeriodSeconds(600)
    .Build();

Runtime.InitializeAndActivate(options);

Default Behavior

When you use Options.Default, Ansight starts with:

  • sample frequency: 500ms
  • retention: 10 minutes
  • FPS enabled: true
  • battery level enabled: false
  • touch capture enabled: false
  • default memory channels: platform defaults
  • tool registry: empty
  • tool guard: disabled
  • host auto-probe: enabled
  • host connection: default saved, bundled, and developer-pairing resolution rules

An empty Options.CreateBuilder().Build() uses the same scalar defaults, memory channel defaults, host auto-probe defaults, and host connection defaults, but FPS remains disabled until you call WithFramesPerSecond() or an all-in-one setup extension.

Validation clamps important values:

  • sample frequency is kept between 200ms and 2000ms
  • retention is kept between 60s and 3600s
  • JPEG capture interval is kept at 250ms or higher
  • JPEG quality is kept between 1 and 100
  • JPEG maxWidth is clamped to 8192
  • touch move distance thresholds must be finite and non-negative
  • touch move FPS thresholds must be non-negative

Builder Methods

MethodPurpose
WithSampleFrequencyMilliseconds(ushort)Set the telemetry sampling cadence.
WithFramesPerSecond()Enable FPS tracking at startup.
WithBatteryLevel()Enable battery level tracking at startup when the platform supports it.
WithoutBatteryLevel()Disable battery level tracking.
WithRetentionPeriodSeconds(ushort)Set how long metrics and events remain buffered.
WithAdditionalChannels(IEnumerable<Channel>)Replace the custom channel collection.
AddAdditionalChannel(Channel)Add one custom channel.
WithDefaultMemoryChannels(DefaultMemoryChannels)Replace the built-in memory channel flags.
WithoutDefaultMemoryChannels(DefaultMemoryChannels)Remove selected built-in memory channels.
WithAdditionalLogger(ILogCallback)Forward Ansight logs to your logger.
WithBuiltInLogger()Use the built-in console logger.
WithTools(IEnumerable<ITool>)Replace the registered tool collection.
AddTool(ITool)Add one tool.
AddTools(IEnumerable<ITool>)Add multiple tools.
ContainsTool(string)Check whether a tool id is already registered on the builder.
WithArtifactProviders(IEnumerable<IArtifactProvider>)Replace the registered artifact provider collection.
AddArtifactProvider(IArtifactProvider)Add one artifact provider and register the core artifact tools.
AddArtifactProviders(IEnumerable<IArtifactProvider>)Add multiple artifact providers and register the core artifact tools.
ContainsArtifactProvider(string)Check whether an artifact provider id is already registered on the builder.
WithSessionJpegCapture(...)Enable periodic live-session JPEG capture.
WithSessionJpegCapture(SessionJpegCaptureOptions)Supply a fully populated JPEG capture object.
WithoutSessionJpegCapture()Disable live-session JPEG capture.
WithTouchCapture(...)Enable app-local touch input capture while the runtime is active.
WithTouchCapture(TouchCaptureOptions)Supply a fully populated touch capture object.
WithoutTouchCapture()Disable app-local touch input capture.
WithToolGuard(ToolGuard)Set an explicit guard policy.
WithToolsDisabled()Disable tool discovery and execution.
WithReadOnlyToolAccess()Allow read-scoped tools only.
WithReadWriteToolAccess()Allow read and write tools, but not delete tools.
WithAllToolAccess()Allow read, write, and delete tools.
WithHostAutoProbe(HostAutoProbeOptions?)Enable or customize background reconnect probing.
WithoutHostAutoProbe()Disable background reconnect probing.
WithHostConnection(HostConnectionOptions?)Replace the runtime-owned host connection configuration.
WithBundledHostConnection(Assembly, IHostConnectionConfigReader?)Read standard bundled pairing resources from an assembly.
WithBundledHostConnection(HostConnectionBundledAssetLoader, IHostConnectionConfigReader?)Read standard bundled pairing resources through a shared text-asset loader.
ConfigureHostConnection(Action<HostConnectionOptions>)Mutate the host connection configuration inline.
WithHostConnectionDiscoveryPort(int)Override the UDP discovery port used for host connection bootstrap.
WithHostConnectionProfileRetention(TimeSpan)Set how long remembered host profiles remain valid.
Build()Validate and produce the final Options instance.

Package-specific tool registration extensions are added by optional tool packages when you use Ansight.Core directly. The Ansight and Ansight.Maui all-in-one packages reference those tool packages for you.

Use AddTool(ITool) or AddTools(IEnumerable<ITool>) for app-specific tools that you implement yourself. See Custom Tools for the full custom-tool pattern.

Use artifact providers when app-specific output should be discovered and downloaded as a file or stream. See Artifacts for the provider model and request flow.

Tool Suite Extension Methods

Common entry points:

ExtensionPackageNuGetPurpose
WithMauiTools()Ansight.Tools.MauiNuGetRegister .NET MAUI page, visual-tree, element, binding, resource, navigation, layout, handler, theme, and binding-context tools.
WithVisualTreeTools()Ansight.Tools.VisualTreeNuGetRegister live UI hierarchy and screenshot tools.
WithReflectionTools(Action<ReflectionToolsOptionsBuilder>)Ansight.Tools.ReflectionNuGetRegister the reflection tools and configure traversal and member visibility.
WithDatabaseTools()Ansight.Tools.DatabaseNuGetRegister SQLite discovery, schema, and query tools.
WithFileSystemTools(Action<FileSystemToolsOptionsBuilder>)Ansight.Tools.FileSystemNuGetRegister sandbox file access and additional tagged roots.
WithPreferencesTools(Action<PreferencesToolsOptionsBuilder>)Ansight.Tools.PreferencesNuGetRegister preference access with store and key restrictions.
WithSecureStorageTools(Action<SecureStorageToolsOptionsBuilder>)Ansight.Tools.SecureStorageNuGetRegister secure-storage access with storage selection and key allow-lists.

Memory Channels

DefaultMemoryChannels is a flags enum:

  • ManagedHeap
  • NativeHeap
  • ResidentSetSize
  • PhysicalFootprint
  • All

Platform defaults:

  • Android: ManagedHeap | NativeHeap | ResidentSetSize
  • iOS and Mac Catalyst: ManagedHeap | PhysicalFootprint
  • other targets: ManagedHeap

Battery Level Telemetry

Battery level telemetry is off by default. Enable it when battery state is useful session context:

var options = Options.CreateBuilder()
    .WithBatteryLevel()
    .Build();

When supported, Ansight records battery charge percentage on the reserved Battery Level channel at the configured sample frequency. Android, iOS, and Mac Catalyst currently expose platform battery readers; other targets skip battery samples.

Use WithoutBatteryLevel() to turn the channel off in shared setup code.

Host Auto-Probe Options

HostAutoProbeOptions controls background reconnect behavior while the runtime is active.

PropertyMeaningDefault
EnabledWhether automatic probe/reconnect runs at all.true
InitialDelayDelay after activation before the first probe.1s
ProbeIntervalDelay between probe attempts while disconnected.5s
ReconnectDelayDelay before probing resumes after a disconnect.10s
ClientNameOptional client name override for automatic connects.null

If you do not want automatic reconnect behavior, call:

var options = Options.CreateBuilder()
    .WithoutHostAutoProbe()
    .Build();

Host Connection Options

HostConnectionOptions controls how the runtime discovers saved, bundled, and developer pairing configs.

PropertyMeaning
SavedConfigPathOverride the path used to store the saved host config.
DiscoveryPortOptional UDP discovery port override.
BundledConfigAssemblyAssembly containing embedded ansight.developer-pairing.json or ansight.json resources.
BundledDeveloperConfigLoaderCustom loader for ansight.developer-pairing.json.
BundledConfigLoaderCustom loader for ansight.json.
ConfigReaderPlatform-owned reader for file or QR payload input. Ansight.Pairing supplies the default QR reader.

Use WithBundledHostConnection(typeof(AppBootstrap).Assembly) for embedded resources. Use the loader overload when the pairing resources live in packaged app assets.

Session JPEG Capture Options

Use JPEG capture only when you actually need live visual artifacts. See JPEG Screenshots for the full split between periodic session capture and the on-demand ui.get_screenshot tool.

var options = Options.CreateBuilder()
    .WithSessionJpegCapture(intervalMilliseconds: 2000, quality: 60, maxWidth: 720)
    .Build();

SessionJpegCaptureOptions properties:

PropertyMeaningDefault from WithSessionJpegCapture()
IntervalMillisecondsCapture interval while a pairing session is open. Values below 250ms are clamped.2000
QualityJPEG quality from 1 to 100.70
MaxWidthOptional output width cap. null keeps full width. Values above 8192 are clamped.720

This feature adds rendering, encoding, and transport overhead. Keep it conservative.

Touch Capture Options

Touch capture is off by default. Enable it when you want Ansight Studio session review and MCP touch-review tools to show where the user tapped, dragged, long-pressed, or cancelled a gesture:

var options = Options.CreateBuilder()
    .WithTouchCapture(
        captureMoveEvents: true,
        captureCancelEvents: true,
        moveCaptureDistanceThreshold: 4,
        moveCaptureFramesPerSecond: 15)
    .Build();

WithTouchCapture() records app-window coordinates while the runtime is active and streams them over an open host connection as touch input records. Touch records are not written to IDataSink, and they are separate from metrics and timeline events.

TouchCaptureOptions properties:

PropertyMeaningDefault
CaptureMoveEventsInclude drag, scroll, and other move updates in addition to down/up events.true
CaptureCancelEventsInclude platform cancellation events.true
MoveCaptureDistanceThresholdMinimum movement, in logical display units, before another move event is recorded. Set 0 to disable distance filtering.4
MoveCaptureFramesPerSecondMaximum move capture cadence per pointer. Set 0 to disable FPS filtering.15

Android, iOS, and Mac Catalyst currently have platform capture sessions. Other targets accept the option but do not emit touch records.

Use WithoutTouchCapture() to explicitly disable touch capture in shared setup code.

Tool Guard Policy

Registering tools is not enough on its own. You must also choose a guard.

Built-in guards:

  • ToolGuard.Disabled
  • ToolGuard.ReadOnly
  • ToolGuard.ReadWrite
  • ToolGuard.FullAccess

Delete-scoped tools stay blocked unless you use WithAllToolAccess() or build a custom ToolGuard.

Reflection writes and invocations are Write tools, so they require WithReadWriteToolAccess() or a custom ToolGuard. The current reflection options surface controls traversal and member visibility; it does not include write or invoke allow-lists.

Example: Core-Only Telemetry + Pairing + Tools

using Ansight;
using Ansight.Tools.Reflection;
using Ansight.Tools.VisualTree;

var session = new DebugSessionViewModel();

var sessionRoot = ReflectionRootRegistry.Register(
    "session",
    session,
    new ReflectionRootMetadata("Current Session")
    {
        Description = "Debug session view model",
        Hints = ["debug", "session"]
    },
    ReferenceType.Strong);

var options = Options.CreateBuilder()
    .WithFramesPerSecond()
    .WithRetentionPeriodSeconds(900)
    .WithSessionJpegCapture(intervalMilliseconds: 3000, quality: 60, maxWidth: 720)
    .WithVisualTreeTools()
    .WithReflectionTools(reflection =>
    {
        reflection.WithAssemblyTraversalMode(ReflectionAssemblyTraversalMode.AllowAll);
        reflection.WithNamespaceTraversalMode(ReflectionNamespaceTraversalMode.AllowAll);
        reflection.WithDefaultMemberVisibility(ReflectionMemberVisibility.PublicOnly);
    })
    .WithReadOnlyToolAccess()
    .Build();

Runtime.InitializeAndActivate(options);