---
name: agui-dotnet-wire-types
description: 'Add or modify a wire/protocol type in the AG-UI .NET SDK AGUI.Abstractions package — a new event, message, or content-part type, the AOT source-gen serializer context, or a polymorphic JSON converter, keeping it AOT-safe, JSON-wire-compatible with the TypeScript reference, and PublicAPI-clean. USE FOR: adding an AG-UI event type, adding a message role or input-content type, editing AGUIJsonSerializerContext, editing BaseEventJsonConverter / AGUIMessageJsonConverter / AGUIInputContentJsonConverter, fixing PublicAPI.Unshipped analyzer build failures on protocol types, wire-format round-trip serialization. DO NOT USE FOR: writing integration/SSE tests (use agui-dotnet-integration-tests), server hosting/endpoint code, or non-Abstractions packages.'
title: agui-dotnet-wire-types
canonical_url: https://skilld.dev/gh/ag-ui-protocol/ag-ui/agui-dotnet-wire-types
last_updated: 2026-11-15T23:16:06.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> If the user asked to install this Skill, run `npx skilld install ag-ui-protocol/ag-ui/agui-dotnet-wire-types`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/agui-dotnet-wire-types`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/ag-ui-protocol/ag-ui/agui-dotnet-wire-types) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/agui-dotnet-wire-types`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/agui-dotnet-wire-types --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/agui-dotnet-wire-types --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# AG-UI .NET Wire/Protocol Types

Add or change a serialized protocol type in `sdks/dotnet/src/AGUI.Abstractions/`. These types are the JSON wire format. **The TypeScript SDK is the reference** — every type must round-trip against its JSON. Add `// Keep in sync with sdks/typescript/packages/core/src/{events,types}.ts` to each new type.

The 5 source packages are `AGUI.Abstractions`, `AGUI.Formatting`, `AGUI.Protobuf`, `AGUI.Client`, `AGUI.Server`. Wire types live in `AGUI.Abstractions` only. (`sdks/dotnet/AGENTS.md` is the canonical reference for the serialization rules and conventions.)

Run all commands from `sdks/dotnet/`.

## Hard rules (forgetting any breaks the build or wire compat)

Every change to a polymorphic type touches **four** coordinated spots. Miss one and either the build fails or the type silently won't deserialize:

1. The concrete class (`Events/`, `Messages/`).
2. The discriminator constant (`AGUIEventTypes` / `AGUIRoles` / `AGUIInputContentTypes`).
3. The source-gen context registration (`Serialization/AGUIJsonSerializerContext.cs`).
4. The hand-written converter `Read` **and** `Write` cases (`BaseEventJsonConverter` / `AGUIMessageJsonConverter` / `AGUIInputContentJsonConverter`).

Plus: `PublicAPI.Unshipped.txt` (analyzer fails the build) and a round-trip test.

## Recipe: new EVENT type

1. **Class** in `Events/{Name}Event.cs`, `sealed`, deriving `BaseEvent`. Override `Type => AGUIEventTypes.{Name}`.
2. **Constant** in `Events/AGUIEventTypes.cs`: `public const string {Name} = "SCREAMING_SNAKE_CASE";`.
3. **Register** `[JsonSerializable(typeof({Name}Event))]` in `AGUIJsonSerializerContext`.
4. **Converter** in `BaseEventJsonConverter`: add a `Read` switch arm (`AGUIEventTypes.{Name} => jsonElement.Deserialize(options.GetTypeInfo(typeof({Name}Event))) as {Name}Event`) **and** a `Write` `case {Name}Event x: JsonSerializer.Serialize(writer, x, options.GetTypeInfo(typeof({Name}Event))); break;`.
5. **PublicAPI** — add every new public member to `src/AGUI.Abstractions/PublicAPI.Unshipped.txt` (format below).
6. **Test** in `tests/AGUI.Abstractions.UnitTests/{Name}EventTest.cs` (JsonDocument assertions).

```csharp
[JsonPropertyName("type")]
public override string Type => AGUIEventTypes.RunStarted;

[JsonPropertyName("threadId")]                          // required: init to string.Empty
public string ThreadId { get; set; } = string.Empty;

[JsonPropertyName("parentRunId")]                       // optional: no JsonIgnore needed
public string? ParentRunId { get; set; }

[JsonPropertyName("value")]                             // dynamic payload: JsonElement, never object
public JsonElement? Value { get; set; }
```

## Variation: MESSAGE type

Same shape, but: folder `Messages/`, derive `AGUIMessage`, discriminator is `role` keyed on `AGUIRoles` constants (lowercase, e.g. `"assistant"`), and the converter is `AGUIMessageJsonConverter` (`Read` + `Write` switch arms). Sync against `types.ts`. Most roles serialize directly; `AGUIUserMessage` is hand-serialized because its `content` is `string | array` — follow the existing `WriteUserMessage`/`DeserializeUserMessage` pattern if a role needs union content.

## Variation: INPUT-CONTENT part

Folder `Messages/`, derive `AGUIInputContent`, discriminator is `type` keyed on `AGUIInputContentTypes` constants (lowercase, e.g. `"image"`), converter is `AGUIInputContentJsonConverter`. **Also** add the same arm to `AGUIMessageJsonConverter.DeserializeUserMessage`'s inner `contentType switch`, since user-message arrays inline-dispatch content parts.

## Serialization / AOT rules

- `[JsonSerializable(typeof(T))]` for every new type — non-negotiable for AOT (no runtime reflection serializer).
- `[JsonPropertyName("camelCase")]` on every serialized property (explicit even though the context sets `CamelCase`).
- **No** `[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]` on optional properties. The
  context sets `DefaultIgnoreCondition = WhenWritingNull` once, for every type it knows, and
  `AGUIJsonUtilities.DefaultTypeInfoResolver` carries the same rule into caller-owned
  `JsonSerializerOptions`. Repeating it per property is what let three `null`s onto the wire before
  anyone noticed the pattern was optional. `NullOmissionTest` fails if the context-wide setting stops
  doing the work, so a re-added attribute is not a harmless duplicate — it hides the regression.
- A non-nullable `JsonElement` that the contract lets a producer leave out does need
  `[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]` (see `AGUITool.Parameters`): it
  is never `null`, so the null rule cannot reach it, and an unset `JsonElement` throws on write.
- Required strings init to `string.Empty`; collections init to `[]`.
- Serialize via the generated context: `AGUIJsonSerializerContext.Default.{Type}` (or `options.GetTypeInfo(typeof(T))` inside converters).
- Dynamic/arbitrary payloads are `JsonElement` / `JsonElement?`.
- **Never** `JsonSerializer.Serialize<object>(...)`, never pass raw strings through unparsed, never reflection-based serialization.

## Polymorphic converter pattern

Hand-written `JsonConverter<TBase>`, keyed on a discriminator property. `BaseEventJsonConverter` is the exemplar: `Read` deserializes to `JsonElement`, reads the discriminator, `switch`es to the concrete `GetTypeInfo(...)`, and throws `JsonException` on unknown/null; `Write` `switch`es on the runtime type. Both directions must list every concrete type. A new abstract family needs the converter referenced via `[JsonConverter(typeof(...))]` on the base class.

## PublicAPI.Unshipped.txt

The analyzer fails the build if a public member is missing here. Add one line per member, e.g. for an event:

```
AGUI.Abstractions.RunStartedEvent
AGUI.Abstractions.RunStartedEvent.RunStartedEvent() -> void
AGUI.Abstractions.RunStartedEvent.ThreadId.get -> string!
AGUI.Abstractions.RunStartedEvent.ThreadId.set -> void
override AGUI.Abstractions.RunStartedEvent.Type.get -> string!
AGUI.Abstractions.AGUIJsonSerializerContext.RunStartedEvent.get -> System.Text.Json.Serialization.Metadata.JsonTypeInfo<AGUI.Abstractions.RunStartedEvent>
```

`!` = non-null reference, `?` = nullable. Don't forget the source-gen context's generated `JsonTypeInfo<T>` getter line.

## Round-trip test (mandatory)

Assert JSON **property names** by parsing with `JsonDocument` — asserting the deserialized object alone misses camelCase/discriminator bugs. Don't compare full JSON strings; no reflection.

```csharp
var json = JsonSerializer.Serialize(evt, AGUIJsonSerializerContext.Default.CustomEvent);
using var doc = JsonDocument.Parse(json);
Assert.Equal("CUSTOM", doc.RootElement.GetProperty("type").GetString());
Assert.Equal("user_preference_updated", doc.RootElement.GetProperty("name").GetString());
```

Also test dispatch through the base: `JsonSerializer.Deserialize(json, AGUIJsonSerializerContext.Default.BaseEvent)` then `Assert.IsType<CustomEvent>(evt)`. For wire-format drift, add a fixture under `tests/AGUI.Abstractions.UnitTests/Compatibility/` produced by the TypeScript SDK and load it via `FixtureLoader` (`{Category}CompatibilityTest` naming).

## Code style / naming

- `sealed class` (no `record`); one type per file named for the type.
- No tuples in public APIs — define a named type.
- Event classes `{Name}Event`; event discriminators `SCREAMING_SNAKE_CASE` (member PascalCase); role/type/outcome discriminators are lowercase string constants in static classes — **never enums**.
- Braces always; `ArgumentNullException.ThrowIfNull(...)` for public validation; no `///` docs on `internal`/`private`.

## Validate

```bash
dotnet build
dotnet test tests/AGUI.Abstractions.UnitTests/
```
