Skip to content

.NET SDK reference

DotCraft.Sdk is the .NET client for AppServer applications. Start with the Quickstart for installation and a first run.

Package

FieldValue
PackageDotCraft.Sdk (NuGet)
Target frameworknet10.0
SerializationSystem.Text.Json with DotCraftJson.Options

DotCraft.Sdk is the only package to add: it ships both DotCraft.Sdk.dll and DotCraft.Protocol.dll.

Namespaces

NamespacePublic surface
DotCraft.SdkDotCraftClient, thread and run APIs, callbacks, MCP runtime, and high-level exceptions.
DotCraft.ProtocolProtocol primitives, RPC descriptors, and JSON options.
DotCraft.Protocol.AppServerAppServer DTOs, payloads, results, and notifications.
DotCraft.Sdk.WireDotCraftWireClient, transports, connection state, timeouts, and JSON-RPC errors.
DotCraft.Sdk.HubHub discovery, AppServer management, process policy, events, and structured errors.
DotCraft.Sdk.DynamicToolsAttribute-based Runtime Dynamic Tool authoring.
DotCraft.Sdk.AppBindingApp Binding handoff and result helpers.

Contracts is a separate assembly and logical layer, not a separate NuGet package.

High-level API

TaskAPI
ConnectConnectLocalAsync(), ConnectLocalChatAsync(), ConnectRemoteAsync(), ConnectAsync()
CloseDisposeAsync() / await using
ThreadsThreads.StartAsync(), ResumeAsync(), ListAsync(), ReadAsync(), ListTurnsAsync(), ListItemsAsync()
RunRunAsync(), RunStreamedAsync(), EnqueueAsync(), InterruptAsync()
Thread stateSnapshot, RefreshAsync(), SubscribeAsync(), UnsubscribeAsync(), SetModeAsync(), ArchiveAsync(), DeleteAsync()
Providers and modelsProviders.ListAsync(), Models.GetCatalogAsync()
Model configurationThreads.ReadModelConfigurationAsync(), UpdateModelConfigurationAsync()
Agent ProfilesAgentProfiles.ListAsync(), ReadAsync(), ValidateAsync(), UpsertAsync(), RemoveAsync(), RefreshThreadAsync()
MCP runtimeMcpRuntime.ListStatusAsync(), ReadResourceAsync(), CallToolAsync(), LoginOAuthAsync(), ReloadAsync()
App BindingAppBindings
Runtime toolsOnToolCall() or RegisterDynamicToolHandler()

Configure ApprovalHandler and UserInputHandler in connection options. Check Capabilities.AgentProfileManagement before exposing Agent Profile management. See Threads & runs and Tools & approvals for task flows.

Connect

MethodRequired argumentConnection ownership
ConnectLocalAsync(workspacePath, options?, cancellationToken)Workspace pathUses Hub to ensure the workspace AppServer, then connects to it.
ConnectLocalChatAsync(options?, cancellationToken)NoneUses Hub to ensure the default Chat workspace AppServer.
ConnectRemoteAsync(appServerUrl, options?, cancellationToken)WebSocket URL; optional token in DotCraftRemoteOptionsConnects directly to an existing AppServer.
ConnectAsync(transport, options?, cancellationToken)IJsonRpcTransportUses an application-owned custom transport.

DotCraftClientOptions controls client identity, capabilities, callbacks, streaming, config-change notifications, and reconnect behavior. DotCraftLocalOptions adds executable, Hub lock, user-profile, and startup-timeout settings.

The shared option fields are AutoReconnect, ClientName, ClientTitle, ClientVersion, ApprovalSupport, StreamingSupport, RequestUserInputSupport, ConfigChange, ExtraCapabilities, ApprovalHandler, and UserInputHandler. DotCraftRemoteOptions adds Token.

A remote URL points at the AppServer WebSocket endpoint, whose path ends in /ws. Pass the token in Token instead of embedding it in the URL, and keep both out of logs. See AppServer mode for how the server listens.

Threads and runs

DotCraftThreadClient exposes typed contract parameters:

csharp
Task<DotCraftThread> StartAsync(ThreadStartParams parameters, CancellationToken cancellationToken = default);
Task<DotCraftThread> ResumeAsync(ThreadResumeParams parameters, CancellationToken cancellationToken = default);
Task<ThreadListResult> ListAsync(ThreadListParams parameters, CancellationToken cancellationToken = default);
Task<ThreadReadResult> ReadAsync(ThreadReadParams parameters, CancellationToken cancellationToken = default);
Task<ThreadTurnsListResult> ListTurnsAsync(ThreadTurnsListParams parameters, CancellationToken cancellationToken = default);
Task<ThreadItemsListResult> ListItemsAsync(ThreadItemsListParams parameters, CancellationToken cancellationToken = default);

ReadAsync() and DotCraftThread.RefreshAsync() return the current Thread header without persisted Turns or Items. ListTurnsAsync() reads Turn metadata without Items; ListItemsAsync() reads Items across the Thread or for the optional ThreadItemsListParams.TurnId. Both page requests accept an opaque cursor, limit, and sort direction.

DotCraftThread accepts either text or IReadOnlyList<InputPart> in RunAsync() and RunStreamedAsync(). RunOptions controls sender context, raw-event collection, queue-if-busy behavior, and whether failed terminal turns throw. Cancellation interrupts an active turn once its ID is known.

The result is DotCraftRunResult; streamed events are DotCraftRunEvent or DotCraftRunEvent<TParams>. Thread-control methods operate on the handle's Id, while the low-level Turns surface accepts explicit protocol parameters.

Providers, models, MCP, and App Binding

ClientOperations
ProvidersListAsync() lists configured providers.
ModelsGetCatalogAsync(providerId?) returns models and typed capabilities.
ThreadsReadModelConfigurationAsync() and UpdateModelConfigurationAsync() preserve unrelated thread configuration fields.
McpRuntimeListStatusAsync(), ReadResourceAsync(), CallToolAsync(), LoginOAuthAsync(), ReloadAsync().
AppBindingsTyped connection, surface, thread-binding, and principal operations.

See MCP runtime and DotCraft App for task-oriented flows.

The MCP client accepts generated Contracts DTOs and returns generated result DTOs:

csharp
Task<McpServerStatusListResult> ListStatusAsync(McpServerStatusListParams? parameters = null, CancellationToken cancellationToken = default);
Task<McpServerResourceReadResult> ReadResourceAsync(McpServerResourceReadParams parameters, CancellationToken cancellationToken = default);
Task<McpServerToolCallResult> CallToolAsync(McpServerToolCallParams parameters, CancellationToken cancellationToken = default);
Task<McpServerOAuthLoginResult> LoginOAuthAsync(McpServerOAuthLoginParams parameters, CancellationToken cancellationToken = default);
Task<McpServerReloadResult> ReloadAsync(CancellationToken cancellationToken = default);

Callbacks and Runtime Dynamic Tools

csharp
delegate Task<ApprovalResponseResult> ApprovalHandler(
    ApprovalRequestParams request, CancellationToken cancellationToken);
delegate Task<UserInputResponseResult> UserInputHandler(
    UserInputRequestParams request, CancellationToken cancellationToken);

IDisposable OnToolCall(
    string? @namespace,
    string toolName,
    Func<DynamicToolCallParams, CancellationToken, Task<DynamicToolCallResult>> handler);

DotCraftThread.OnToolCall() scopes a handler to one thread. DotCraftClient.RegisterDynamicToolHandler() also supports a catch-all handler or an explicit thread/namespace/tool key. Dispose registrations with their owning scope.

Contracts and payloads

High-level methods return DotCraft.Protocol.AppServer contracts instead of duplicate SDK DTOs. SessionItem.Payload stays open as JsonElement so unknown item kinds survive older clients.

Use SessionItemPayloadParser.Parse(item) or TryGet<TPayload> for known payloads. Preserve Raw when your application does not recognize a future payload kind.

Typed and raw Wire API

Use generated descriptors or generated XxxAsync extension methods for cataloged operations:

csharp
var result = await client.Wire.ThreadListAsync(parameters, cancellationToken);

Use RequestRawAsync, NotifyRawAsync, and raw handlers only for third-party or not-yet-cataloged extensions. Typed methods do not accept arbitrary method strings.

DotCraftWireClient owns JSON-RPC and connection state. It does not approve requests, answer user input, or rebuild thread and tool resources.

Connection lifecycle

Wire state is Connecting, Initializing, Ready, Disconnected, Reconnecting, ReconnectError, or Closed.

  • Raw Wire connections do not reconnect by default.
  • Local and remote high-level connections enable reconnect by default. Override it with DotCraftClientOptions.AutoReconnect.
  • Ordinary requests default to a 30-second timeout.
  • Reconnect uses exponential backoff and queues at most 1024 new calls.
  • In-flight calls fail and are never replayed.
  • Initialization completes before queued calls are released.
  • Handler registrations survive reconnect. Thread subscriptions and runtime tool resources do not.
  • An active run fails with RunDisconnectedException; turn/start is never replayed.

Reconnect does not rebuild those resources for the application. Read or resume the thread, subscribe again, and re-register runtime tool handlers before continuing.

Disposing a local high-level client closes its AppServer connection. It does not stop Hub or the Hub-managed AppServer.

Errors

SDK exceptions derive from DotCraftException and carry a stable Code.

ExceptionCondition
JsonRpcExceptionAppServer returned a JSON-RPC error. Preserves RpcCode and ErrorData.
InitializationFailedExceptionConnection initialization failed.
ProtocolViolationExceptionA known message does not match its contract.
TurnInProgressExceptionThe thread already has an active turn.
ThreadNotFoundException / ThreadNotActiveExceptionThe target thread is missing or cannot run.
TurnFailedException / TurnCancelledExceptionA buffered run reached a failed or cancelled terminal state.
RunDisconnectedExceptionThe Wire session ended during an active run.
ApprovalTimeoutExceptionAppServer reports approval timeout.
RequestTimeoutExceptionA Wire request exceeded its timeout.
ReconnectQueueFullExceptionThe reconnect queue reached its capacity.

HubClientException carries the Hub Code, message, and Details.

Hub API

HubClient discovers or starts Hub, validates the local lock, resolves a workspace AppServer, and supports ensure, restart, stop, list, status, events, and shutdown operations.

Do not log Hub tokens, App Binding credentials, or full token-bearing WebSocket URLs.