Part 3, The Kiota Side Quest Harder than I thought

TL;DR – The official Mistral OpenAPI spec is 49,000 lines. Kiota’s –include-path flag filters it at generation time to the one endpoint I care about. The question was never “how do I shrink this file”. It was “how do I ask for less”. Along the way I got a Ferrari when I wanted a go-kart, plus a free sample of tool-calling scaffolding that pays off later in the series.

This is a small diversion from the main series, but it is the insight the whole project turned on. This post is the long-form version of the side quest; with the reasoning I skipped on stage. Buried in the model’s failed attempts, its reasoning kept naming Kiota, Microsoft’s OpenAPI client generator.

First attempt so many files

kiota generate --language CSharp
  --class-name MistralChatCompletionClient
  --namespace-name Mistral
  --openapi mistral-openapi.yaml

Second attempt 3% of the original count

kiota generate --language CSharp
  --class-name MistralChatCompletionClient
  --namespace-name Mistral
  --openapi mistral-openapi.yaml
  --output Generated
  --include-path "/v1/chat/completions*"

The interesting commandline flag is –include-path. The full 49,000-line spec, filtered at generation time to one endpoint. I did not edit the YAML. I did not trim anything by hand. I told the generator what I wanted and it brought back only that.

Bonus, the newer snapshot generated the response-side cache-hit field. One snapshot can send prompt_cache_key, the other cannot report the hit. Two downloads of “the same” file (days apart), and they disagree about what the API says back.

Full spec‘–include-path “/v1/chat/completions*”
.cs files2,39069
Lines of C#257,7416,463
Directories3035
Intersection-type wrappers3420
Generation time~35s~3s

Because the number of files was so big, I ran a cyclomatic complexity analyser over the two libraries.

Full spec (2,390 files)Chat only (69 files)
Total cyclomatic complexity~18,233~488
Total decision points~15,843~419
Average CC per file7.67.1
Files over CC 103788
Worst fileUsageQueryRowOUT.cs, CC ~189ChatCompletionRequest.cs, CC ~152

Complexity scales with breadth, not depth. Average complexity per file is nearly identical between the two (7.6 vs 7.1). The full client is not harder to read per file, there are just 37x more files. The worst offenders are serialization sinks. UsageQueryRowOUT (CC ~189), ExtendedOAuthServerMetadata (~188), CreateResponseResponse (~157), ChatCompletionRequest (~152).

The Kiota 1.39 generates for .NET 10, so an older standalone .NET 8 or 9 runtime will crash at startup with a MissingMethodException from the diagnostics stack. Point DOTNET_ROOT at a .NET 10 runtime and it runs clean.

I compared my fresh download against a generated client from a different snapshot of the same spec, taken weeks apart. One snapshot has RAG deployments, their metrics and the Vespa deployment models. The other has dataset-records bulk operations, workflow deployment archives, and a pile of new admin workspace-member models.

There were also a surprising number of warnings.

PS C:\Users\BrynLewis\Downloads\Kiota> kiota generate --language CSharp --class-name MistralChatCompletionClient --namespace-name Mistral --openapi openapi.yaml --output Generated --include-path "/v1/chat/completions*"
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/ - The schema PipelineConfigDefinition is a polymorphic type but does not define a discriminator. This will result in serialization errors.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/ - The schema EmbeddingInput is a polymorphic type but does not define a discriminator. This will result in serialization errors.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/ - The schema OutputContentChunks is a polymorphic type but does not define a discriminator. This will result in serialization errors.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/ - The schema ChatClassificationRequestInputs is a polymorphic type but does not define a discriminator. This will result in serialization errors.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/ - The schema EvaluatorStatistics is a polymorphic type but does not define a discriminator. This will result in serialization errors.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/ - The schema /v1/workflows/{workflow_identifier}/execute is a polymorphic type but does not define a discriminator. This will result in serialization errors.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/ - The schema /v1/workflows/registrations/{workflow_registration_id}/execute is a polymorphic type but does not define a discriminator. This will result in serialization errors.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/ - The schema /v1/conversations/{conversation_id} is a polymorphic type but does not define a discriminator. This will result in serialization errors.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/ClientSecret/properties/value - The format password is not supported by Kiota for the type String and will be ignored.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/AudioTranscriptionRequest/properties/file_url/anyOf/0 - The format uri is not supported by Kiota and the string type will be used.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/AudioTranscriptionRequestStream/properties/file_url/anyOf/0 - The format uri is not supported by Kiota and the string type will be used.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/AuthData/properties/client_secret/anyOf/0 - The format password is not supported by Kiota for the type String and will be ignored.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/ConnectorMCPPublicUpdate/properties/server/anyOf/0 - The format uri is not supported by Kiota and the string type will be used.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/ExtendedOAuthServerMetadata/properties/issuer - The format uri is not supported by Kiota and the string type will be used.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/ExtendedOAuthServerMetadata/properties/authorization_endpoint/anyOf/0 - The format uri is not supported by Kiota and the string type will be used.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/ExtendedOAuthServerMetadata/properties/token_endpoint - The format uri is not supported by Kiota and the string type will be used.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/ExtendedOAuthServerMetadata/properties/registration_endpoint/anyOf/0 - The format uri is not supported by Kiota and the string type will be used.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/ExtendedOAuthServerMetadata/properties/service_documentation/anyOf/0 - The format uri is not supported by Kiota and the string type will be used.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/ExtendedOAuthServerMetadata/properties/op_policy_uri/anyOf/0 - The format uri is not supported by Kiota and the string type will be used.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/ExtendedOAuthServerMetadata/properties/op_tos_uri/anyOf/0 - The format uri is not supported by Kiota and the string type will be used.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/ExtendedOAuthServerMetadata/properties/revocation_endpoint/anyOf/0 - The format uri is not supported by Kiota and the string type will be used.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/ExtendedOAuthServerMetadata/properties/introspection_endpoint/anyOf/0 - The format uri is not supported by Kiota and the string type will be used.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/OAuth2ClientCredentialsInput/properties/client_secret/anyOf/0 - The format password is not supported by Kiota for the type String and will be ignored.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/OAuth2ClientCredentialsInput/properties/client_private_key/anyOf/0 - The format password is not supported by Kiota for the type String and will be ignored.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/Oauth2MetadataSecrets/properties/client_secret/anyOf/0 - The format password is not supported by Kiota for the type String and will be ignored.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/CreateConnectorRequest/properties/oauth2_server_metadata_url/anyOf/0 - The format uri is not supported by Kiota and the string type will be used.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/CreateConnectorRequest/properties/server - The format uri is not supported by Kiota and the string type will be used.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/CreateHTTPConnectorRequest/properties/oauth2_server_metadata_url/anyOf/0 - The format uri is not supported by Kiota and the string type will be used.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/CreateHTTPConnectorRequest/properties/server - The format uri is not supported by Kiota and the string type will be used.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/UpdateHTTPConnectorRequest/properties/server/anyOf/0 - The format uri is not supported by Kiota and the string type will be used.
Generation skipped as no changes were detected

Hint: to force the generation to overwrite an existing client pass the --clean-output switch.
Example: kiota generate --clean-output

Hint: use the info command to get the list of dependencies you need to add to your project.
Example: kiota info -d "C:\Users\BrynLewis\Downloads\Kiota\openapi.yaml" -l CSharp
PS C:\Users\BrynLewis\Downloads\Kiota>

Next in the series: Part 4, the human as the clipboard, file tools, permissioning, and the CLI demo where the tool-calling scaffolding parked here finally earns its keep.

Part 2, Half-Arsed DTOs, and the 49,000-Line Spec

TL;DR – Hand-typing DTOs one 422 at a time slows you down. The official Mistral API OpenAPI spec is 49,000 lines and cannot fit in a 128K context window. The fix was a 296-line community extract and Kiota’s include-path trick. Same model, same request, only the approach changed.

This post is the long-form version of the middle third of the talk, everything between the two demos. It is the part I compressed hardest on stage because it is numbers and screenshots, which is a shame because it contains the actual lesson.

Sick of half-arsed DTOs

Once the basic loop from Part1 worked, the DTOs became the bottleneck. Hand-typed message and choice DTOs fixed one 422 at a time. Every fix revealed a property I had missed or a union variant I did not know existed. Every session started with fixingcasing and enums again, in prompts, over and over again.

// DTOs for the Mistral API
public record ChatCompletionRequest(
    [property: JsonPropertyName("model")] string Model,
    [property: JsonPropertyName("messages")] ChatMessage[] Messages,
    [property: JsonPropertyName("temperature")] float? Temperature = null,
    [property: JsonPropertyName("max_tokens")] int? MaxTokens = null,
    [property: JsonPropertyName("stream")] bool? Stream = null
);

public record ChatMessage(
    [property: JsonPropertyName("role")] string Role,
    [property: JsonPropertyName("content")] string Content
);

public record ChatCompletionResponse(
    [property: JsonPropertyName("id")] string Id,
    [property: JsonPropertyName("object")] string Object,
    [property: JsonPropertyName("created")] long Created,
    [property: JsonPropertyName("model")] string Model,
    [property: JsonPropertyName("choices")] Choice[] Choices,
    [property: JsonPropertyName("usage")] Usage Usage
);

public record Choice(
    [property: JsonPropertyName("index")] int Index,
    [property: JsonPropertyName("message")] ChatMessage Message,
    [property: JsonPropertyName("finish_reason")] string FinishReason
);

public record Usage(
    [property: JsonPropertyName("prompt_tokens")] int PromptTokens,
    [property: JsonPropertyName("completion_tokens")] int CompletionTokens,
    [property: JsonPropertyName("total_tokens")] int TotalTokens
);

There is a machine-readable source of truth. The OpenAPI spec. That is when the project stopped being “a chat client” and started being “a client generator’s customer”.

The full spec

Download from docs.mistral.ai/openapi.yaml. 49,000 lines. 1.5 MB. About 300K tokens. Chat completions, Files API, OCR, insertions, all of the things. My context window is approximately128K. It cannot/wouldnot fit so I did the obvious thing anyway. Loaded the whole spec and my client went pop. Prompts hundreds of thousands of tokens deep. Responses slowing and “token maxing”. With the useful answer hidden at the bottom of the payload.

Two lessons came out of the wreck. First, this is why “just give the model the docs” fails in real projects: ground truth has to fit in the window, and the interesting APIs do not. Second, the failure forced the question that saves the whole project: 49,000 lines is what is in it.

The thinking told me

Buried in the model’s failed attempts at code, its reasoning kept naming two things. Kiota, Microsoft’s OpenAPI client generator. Also, a chat-completions-only YAML by API Evangelists. It could not build either. But it knew they existed. It also offered Python libraries and NodeJS utilities, and I even considered generating a console application to chop up the file before choosing to explore instead.

The Telerik Fiddler raw POSTs with 422 typos. First chat client with Memento amnesia and JsonDocument, which made the large model parsing go pop. Second chat client with hand-typed DTOs and a system message, which brought context. Then a chat client plus the big YAML, where the context exploded and .NET regressed. Third chat client with an IMistralService abstraction, plus the small YAML, which works and became YAMLClientLibrary and YAMLClientApplication.

// Client
public class MistralClient
{
    private readonly HttpClient _httpClient;
    private readonly string _apiKey;
    private readonly string _model;

    public MistralClient(HttpClient httpClient, IConfiguration config)
    {
        _httpClient = httpClient;
        _apiKey = config["FOEHN_API_KEY"] ?? throw new InvalidOperationException("FOEHN_API_KEY not set");
        _model = config["MFOEHN_MODEL"] ?? "mistral-medium-latest";
        _httpClient.DefaultRequestHeaders.Authorization = new("Bearer", _apiKey);
    }

    public async Task<ChatResponse> ChatAsync(ChatRequest request)
    {
        var response = await _httpClient.PostAsJsonAsync(
            "https://api.mistral.ai/v1/chat/completions",
            request);

        return await response.EnsureSuccessStatusCode().Content.ReadFromJsonAsync<ChatResponse>()
            ?? throw new InvalidOperationException("Empty response");
    }
}

In Retrospect

Since my session (3 days AGO) Mistral.ai doc YAML link has been removed from the API docs page,but is still accessible. Using my “leet” search skills I found the URL of the YAML used by the Mistral Python & Typescript generators use. But I couldn’t access the SpeakeasyAPI endpoint. Some of the changes have been really odd

There are some libraries tghamm(NuGet), tryAGI(NuGet) libraries are based on an older/smaller (roughly 30%) version of the OpenAPI specification, but these weren’t in the spirit of the project.

Calls from New Zealand terminate in Cloudflare, then on to the EU or US. Typical response is 1 to 2 seconds. Occasional tails of 10 to 15 seconds. Bigger models slower, as expected. Fiddler showed the connection path before any application code existed.

There is no Australia East option for Mistral. You pick EU residency or US speed this any distributed API lesson, but the AI hype cycle makes you forget it. Reasoning models spend tokens thinking before they answer. My responses kept truncating mid-code. I escalated the prompt through four rewrites. The winner was “Just code. No thinking.” I dropped the punctuation too. It worked.

Sometimes the fix is asking for less, not explaining more. Negative-space instructions.

The max_tokens dial

Responses cut off mid-line usually are not the model failing. They hit the max_tokens cap. Raise the cap, same request, whole answer. Too small and you waste a full bill on a truncated answer, then retry and pay again. Too big is fine, it is only headroom, except with runaway generation, which bills forever. Tune the cap to your worst realistic response, not your average.

The model matrix

Small. Fast, cheap, occasionally shallow.
Medium. The workhorse. Best cost to quality for this workload.
Large. Made response parsing go pop, literally. Its answers came back so long and so ornately structured that my hand-rolled parsing choked. Beautiful prose, unusable payloads. Small and Medium answer the question. Large writes you an essay about the question.
Codestral. For development text insertions, not this.

Measure with your own workloads. The leaderboards do not know your payload.

.NET drift and prose prompts

I asked for .NET 10 and C# 14. I got .NET 8 idioms. Not malice. The model defaults to the median of its training data. Pleading in the prompt helped a little. Grounding helped completely. This shows up again in a moment as the recurring theme.

Meanwhile the prompts had become a hand-written mini-spec, badly, in prose. “Generate a C# v14 .NET 10 client library for this YAML.” Then a refined version with streaming, synchronous, shared, discriminators. Then “Don’t use NSwag”.

Negative instructions are weak. The model still has to guess what you do want.

System.md, the proto-skill

One attempt generated code that contained a system.md. Static instructions move to a file that rides along on every turn. The prompt shrinks to the request and the conventions persist.

The cache keys from Part 1: the live API reports cache hits, billed at 10%, and neither spec knew. The official one caught half the story. The request side has the plumbing, prompt_cache_key. The response side does not, prompt_tokens_details is missing from the generated interface. The snapshot froze mid-feature.

The exponential increase in speed

More code for me to copy n paste, well lots of code.

4,385 tokens for the client library.

7,756 more for a sample client. So far 11,924

14,332 for basic tool support. So far 26,256

19,999 for smarter searching. So far 46,255.

26,333 for searching with filters. So far 72,588.

31,353 for a slash-command UX. So far 103,941

36,924 for skills. All up 140,865 to get a functional application.

The Human as the Clipboard

The workflow so far: model writes code, I copy it out of the console, paste into a file, build, copy errors back in
Every round-trip has a human where a file operation should be

I am the tool’s tool

Part 1, One HTTP POST, Fiddler, SSE and the 422 That Lied

TL;DR – The whole Mistral Chat Completions API contract starts as one HTTP POST. A system message, a user message, an assistant message reply, and an optional tool message result. Four different payloads, not a list of strings. Streaming is done with Server Sent Events(SSE), JSON inside JSON. The first real “bug” was an HTTP Error 422 Unprocessable Content and the error message lied by omission.

This post is the long-form version of the first demo in the talk. The first and last time Telerik Fiddler (I’m over the licensing message) appears in the session.

The starting point

The Mistral API surface is huge (and the docs changed between the start and end of the series) Chat completions, Files, Models, Embeddings etc. The samples are TypeScript, Python and curl, which tells you who the expected audience is. I am a C# developer and only cared about chat completions.

On the top left of the docs page there is(was) a Yet Another Markup Language (YAML) download for the OpenAPI specification (the clickable link disappeared overnight). The download link is still a live, and the file is 30% bigger today.

The messages array is not a list of strings. It is four different payloads SystemMessage | UserMessage | AssistantMessage | ToolMessage.

A System Message is usually a plain string. Standing instructions, no response expected, rides along on every turn. It can be an array of typed chunks a TextChunk or ThinkChunk

A UserMessage contains the prompt. The content field is not just a string either. It can be an array of typed chunks. TextChunk. ImageURLChunk. DocumentURLChunk, ReferenceChunk, FileChunk, ThinkChunk, AudioChunk, ResourceChunk or ResourceLinkChunk

An Assistant Message is what comes back. In addition to the original UserMessage and response payload it can also carry ToolCalls. A ToolMessage closes the loop. It is a structured message with which a model asks the runtime to execute a specific tool/function on its behalf, rather than producing a plain text answer.

On the wire you send one HTTP POST with model name, SystemMessage,UserMessage, temperature, stream, and max_tokens (important for message truncation discussion). That is the entire contract. Later on both the request side and the response side, is this shape better dressed. Two different JSON payloads and this is where the DTO pain in Part 2 starts.

The demo

Non-streaming first. Fire the HTTP POST with stream off. One JSON, document comes back, choices[0].message.content. Easy to code. Dead to watch. A wall of silence, then everything at once.

{
   "model": "mistral-large-latest",
   "messages": [
      {
         "role": "user",
         "content": "Explain the software acronym ACID."
      }
   ]
}
{
   "id": "5272af17c792494bb8ea6871f68e1f08",
   "created": 1794546851,
   "model": "mistral-large-latest",
   "usage": {
      "prompt_tokens": 24,
      "total_tokens": 798,
      "completion_tokens": 774,
      "prompt_tokens_details": {
         "cached_tokens": 0
      },
      "completion_tokens_details": {
         "reasoning_tokens": 265
      },
      "service_tier": "standard"
   },
   "object": "chat.completion",
   "choices": [
      {
         "index": 0,
         "finish_reason": "stop",
         "message": {
            "role": "assistant",
            "tool_calls": null,
            "content": [
               {
                  "type": "thinking",
                  "thinking": [
                     {
                        "type": "text",
                        "text": "The user is asking for an explanation of the software acronym ACID. This is a fundamental concept in database systems and transaction processing. I should explain:\n\n1. What ACID stands for (Atomicity, Consistency, Isolation, Durability)\n2. What each property means in practical terms\n3. Why it matters (transactions, data integrity)\n4. Maybe a brief example to make it concrete\n5. Context (primarily used in relational databases)\n\nLet me structure this clearly:\n\n**ACID** stands for:\n- **Atomicity**: All-or-nothing. A transaction is treated as a single unit. Either all operations succeed or none do.\n- **Consistency**: The database moves from one valid state to another, maintaining all defined rules/constraints (integrity constraints, cascades, triggers).\n- **Isolation**: Concurrent transactions don't interfere with each other. Each sees the database as if it were the only one running.\n- **Durability**: Once committed, changes persist even in case of system failure (power loss, crash).\n\nI should mention this is crucial for financial systems, banking, etc. where data integrity is paramount.\n\nMaybe contrast briefly with BASE (NoSQL) to give context, but keep focus on ACID.\n\nLet me write this in a clear, educational tone."
                     }
                  ],
                  "closed": true
               },
               {
                  "type": "text",
                  "text": "**ACID** is an acronym describing the four key properties that guarantee reliable processing of database transactions. It ensures that data remains accurate and consistent even when errors, power failures, or other mishaps occur.\n\nHere is what each letter stands for:\n\n### **A — Atomicity**\nA transaction is an **\"all-or-nothing\"** proposition. Either *all* the operations in the transaction complete successfully, or *none* of them do. If any part fails, the entire transaction is rolled back to its original state.\n- **Example:** Transferring $100 from Account A to Account B requires two steps: debit A and credit B. If the credit fails, the debit is undone. You never end up with money disappearing into thin air.\n\n### **C — Consistency**\nA transaction must take the database from one **valid state to another valid state**, preserving all defined rules and constraints (data integrity, foreign keys, unique constraints, triggers, etc.).\n- **Example:** If a database rule says an account balance cannot be negative, a transaction that would make it negative will be rejected entirely, keeping the database consistent.\n\n### **I — Isolation**\nConcurrent transactions (multiple users/processes running at the same time) must not interfere with each other. Each transaction sees the database as if it were the only one executing, preventing \"dirty reads,\" non-repeatable reads, and phantom reads.\n- **Example:** If two people book the last seat on a flight simultaneously, isolation ensures only one succeeds and the other gets an error, rather than both getting the seat.\n\n### **D — Durability**\nOnce a transaction has been **committed**, it remains so permanently—even in the event of a system crash, power loss, or hardware failure. The changes are written to non-volatile storage (like disk) before the commit is acknowledged.\n- **Example:** After you see a \"payment successful\" confirmation, the record of that payment will still exist even if the server immediately loses power.\n\n---\n\n### Why it matters\nACID properties are critical in systems where correctness is non-negotiable—**banking, financial trading, inventory management, healthcare records, and e-commerce checkout systems**. They ensure that data integrity is maintained despite concurrent access, hardware failures, and software errors.\n\n*(Note: In contrast, some distributed NoSQL databases use **BASE**—Basically Available, Soft state, Eventual consistency—trading strict ACID guarantees for higher availability and scalability.)*"
               }
            ]
         }
      }
   ]
}

Flip stream to true. Same request. Now the response arrives as SSE. A stream of data: {…} events, ending in data: [DONE]. It looks faster and it genuinely is for the user. First tokens arrive while the model is still generating. But total time is the same. You have moved the wait into the stream.

The client has to stitch the deltas back together. Fragments and tool-call arguments arrive in pieces across chunks. Second, each one of these events is a string with JSON inside it. JSON inside JSON, parsed chunk after chunk. Get a boundary slightly wrong (like I did multiple times) and nothing fails cleanly. That is why my streaming client has a whole assembly class.

The 422 Trap

My favourite bug of the session. I accidentally changed one character in the request. The c in context to a C. The API answered 422, “missing required property”.

{
   "model": "mistral-large-latest",
   "messages": [
      {
         "role": "user",
         "Content": "Explain the software acronym ACID."
      }
   ]
}

The property was not missing. The casing was wrong. The API expects snake_case and I sent .NET’s default PascalCase(I wasn’t using DataAnnotations or JsonSerializerOptions yet)

Diff the request the docs show against the request you sent. Character by character, property by property. Casing, underscores, everything. Comment out the payload and add fields back one at a time until it breaks again. Inspect the payloads in a JSON viewer in the debugger.

Not glamorous. Not clever. Just effective. That one habit saved me more time across this project than every clever thing I did combined.

My First Chat Client

A console application. Read input, send it, print the response. The reflex of every developer since 1974 (I started coding in early then got my own compute an Amstrad CPC6128). The first surprise is structural. Every run starts from zero. No memory of the previous conversation. A Memento brain wipe.

The amnesia was never the model. The model has no state at all. It is entirely the plumbing. And there is a subtle failure mode hiding here: the model had nothing to “misremember” from, so it answers confidently either way. No wrong memory is bad. No memory answering confidently is worse, because it looks the same from the outside.

It’s Stateless(WTF)?

The API is stateless by design this is a deliberate choice, not a shortcoming. If the API held your conversation server-side, every turn would have to land on the machine holding the session. i.e. a sticky session, or every machine would have to have a shared session store.

Stickiness plus unpredictable turn times, this call runs 200ms, that one runs 30 seconds, means machines sitting reserved for slow conversations while new ones starve. Stateless means any request can run anywhere, on any GPU, and that is what makes the economics of inference work.

The vendor farms the storage problem back to you. You have the conversation on disk anyway, so it is cheap for you too. In Memento terms: the cloud has no new memories, only the polaroids you mail it.

There is a quiet upside I did not spot until much later. The client re-sends the same prefix every turn, so the API has a trick for exactly this pattern: prompt cache keys. You give the request a prompt_cache_key and the recurrent prefix gets served from cache at 10% of the token price. The stateless design quietly lends you a hand. Numbers from my logs in Part 3.

What this cost

Continuity is not free. As soon as the client re-sends the story every turn, the token count on each request climbs. Convenience and cost are the same dial. The API gives you amnesia and charges you for the cure. You build the memory, then pay per turn to keep it.

Next: Part 2. The hand-typed DTOs got fed up with me, so I went looking for the spec. The spec is 49,000 lines. It did not go well.

I Built My Own Agentic Client (So You Don’t Have To)

TL;DR – I built a series of Mistral API clients in C#, starting with one raw HTTP POST in Telerik Fiddler and ending with a command line interface(CLI) that has file tools, permissioning and context management. No SDK, no libraries. This post starts the series. Everything I mention is committed at KiwiBryn/CodeCampCHC2026, numbered in talk order.

Part 0- Series Introduction

On 21 November 2026 I gave a session at Christchurch Code Camp called “I Built My Own Agentic Client (So You Don’t Have To)”. This is the long-form version, split into a series of posts.

  • Part 1 – the first demo, one HTTP POST in Telerik Fiddler, and what the messages array on the wire actually looks like.
  • Part 2 – what happened between the two demos. Hand-typed DTOs, the OpenAPI spec that would not fit.
  • Part 3 – the second demo, the Mistral CLI. File tools, permissioning, context management and the Files API.

The honest subtitle was “Fiddler to a self-building, self-improving CLI”. The plan grew backwards from there. Everything in the repo got built twice. Once by me understanding it, once by the model generating it.

The rules

Every client in the series, I built. No SDK, no libraries. Visual Studio 2026, C#/.NET, Mistral Chat Completions API, System.Text.Json.

That was the constraint for the talk and it is the constraint for these posts. Constraints make a better story than plans.

One housekeeping note. Mistral hosts data in the EU by default. There is a US endpoint which is faster from New Zealand, but it is the US of A. The European Union (EU) General Data Protection Regulation (GDPR) was a factor for the clients I build professionally. Here it is mostly an excuse to say I checked.

Why bother

Three reasons, none of them “because it is there” or “just because”

First, understanding. If every client I use, I build, then when the payload is wrong I know which layer is lying. An HTTP Error 422 Unprocessable Content does not become a GitHub issue on someone else’s SDK repo. I have the wire trace and I have the Data Transfer Obect(DTO)s.

Second, judgement. An agentic client is a small amount of code around a large amount of policy. What the model may read, what it may write, what it may delete, what gets compressed. My view is that policy should be visible in code you can read over coffee, for the same reason you do not hand your car keys to a stranger.

Third, receipts. Everything in this series is committed and numbered in the order I built it. Clone KiwiBryn/CodeCampCHC2026 and follow along.

What I am not doing

I am not arguing nobody should use an SDK. Kiota shows up in Part 2 as a deliberate sidequest and it taught me two things I use. The reason to build one yourself, once, is that after you have done it, the SDK stops being magic and starts being a trade-off you can price.

Posts in this series

  • Part 1 – One HTTP POST, Fiddler, Server Sent Events(SSE), and the 422 that lied to me.
  • Part 2 – From half-arsed DTOs to 296 lines of YAML. The spec journey, the token ladder.
  • Part 3 – The CLI. Tools, permissioning, a model that went feral, and what it cost.

Next up: Part 1, the atom everything else is built from – one HTTP POST.

FohenAIBuilder Scan tool – 100% dog food

The first FoehnAIBuilder tool had to be a very basic scan tool so the LLM could find chunks of text in text files. The generated code had some issues which were pointed out by Copilot.

ReviewScanFiles.cs wonder how well is going to handle large files. I think more async would be good

Review: SearchFilesTool.cs — Large-File & Async Concerns

You’re right to be concerned. There are several places where large files or large trees will bite you.

Large-file / scalability issues

1. StreamReader with default buffer + no explicit encoding

new StreamReader(file) uses a 1 KB buffer and auto-detects encoding by reading a BOM. For large files this is inefficient. Pass a bigger buffer and make async real:

using var stream = new FileStream(
    file,
    FileMode.Open,
    FileAccess.Read,
    FileShare.ReadWrite | FileShare.Delete,
    bufferSize: 64 * 1024,
    FileOptions.Asynchronous | FileOptions.SequentialScan);
using var reader = new StreamReader(stream, detectEncodingFromByteOrderMarks: true);

FileOptions.SequentialScan hints the OS cache manager for forward-only reads. FileOptions.Asynchronous is what actually makes ReadLineAsync non-blocking — without it you’re doing sync I/O on the thread pool.

2. FileShare.Read (default) blocks files opened for write elsewhere

Locked files (log files, files being edited) throw and get skipped. FileShare.ReadWrite | FileShare.Delete lets you scan them.

3. Binary-file detection is weak

if (lineNumber == 1 &amp;&amp; line.Contains('\0')) break;

Only checks line 1; many binaries have text at the top. And a huge binary with no \n will be read into memory as one giant string before this check fires. Better:

  • Read the first ~4–8 KB as bytes, look for \0 → skip if binary.
  • Or exclude common binary extensions up front (.dll, .exe, .pdb, .png, .jpg, .zip, .bin, .so, .dylib, etc.).

4. No per-file size cap

A 2 GB log file will be fully streamed. Add a guard:

var info = new FileInfo(file);
if (info.Length &gt; MaxFileSizeBytes) continue;

5. No max-line-length guard

ReadLineAsync on a file with no newlines (minified JS, single-line log) will buffer the whole file into one string. Skip lines above ~8 KB.

6. matches stores full trimmed line

A minified match line could be megabytes. Truncate:

var snippet = line.Length &gt; 500 ? line[..500] + "…" : line;
matches.Add((Path.GetRelativePath(fullPath, file), lineNumber, snippet.Trim()));

Async concerns

7. Sequential file iteration

The outer foreach awaits one file at a time. On an SSD scanning thousands of files, most time is spent waiting on I/O. Use Parallel.ForEachAsync with bounded concurrency:

var gate = new Lock(); // .NET 9+ Lock
await Parallel.ForEachAsync(
    files,
    new ParallelOptions
    {
        MaxDegreeOfParallelism = Environment.ProcessorCount,
        CancellationToken = cancellationToken
    },
    async (file, ct) =&gt;
    {
        // scan file into a local list, then merge under `gate`
    });

Result order becomes non-deterministic — sort by (RelativePath, LineNumber) before printing so output is stable.

8. ReadLineAsync allocates a string per line

For hot paths, PipeReader + SequenceReader searching raw UTF-8 is much faster and lower-allocation, but more code. Probably overkill unless benchmarks say so.

9. Cancellation inside a huge file

ReadLineAsync(cancellationToken) honors cancellation on each read — good. The outer ThrowIfCancellationRequested becomes redundant once you parallelize (the ParallelOptions.CancellationToken covers it).

Other observations

  • filesScanned counter is misleading once parallelized — use Interlocked.Increment and only count successful opens.
  • sb.AppendLine uses Environment.NewLine. For LLM output, '\n' is more portable.
  • ToolPath.TryResolve(sandboxRoot, path, ...) — different signature than WriteFileTool uses. Worth checking consistency.
  • Skipped-file reporting: consider distinguishing filesScanned vs filesSkipped in the summary.

Suggested per-file scan method

private static async Task&lt;List&gt; ScanFileAsync(
    string file, string text, StringComparison comparison, int maxMatches, CancellationToken ct)
{
    var results = new List();

    var info = new FileInfo(file);
    if (info.Length == 0 || info.Length &gt; 50L * 1024 * 1024) // 50 MB cap
        return results;

    await using var stream = new FileStream(
        file, FileMode.Open, FileAccess.Read,
        FileShare.ReadWrite | FileShare.Delete,
        bufferSize: 64 * 1024,
        FileOptions.Asynchronous | FileOptions.SequentialScan);

    // Cheap binary sniff on first 4 KB
    var sniffLen = (int)Math.Min(4096, info.Length);
    var sniff = new byte[sniffLen];
    var read = await stream.ReadAsync(sniff, ct);
    if (sniff.AsSpan(0, read).IndexOf((byte)0) &gt;= 0) return results;
    stream.Position = 0;

    using var reader = new StreamReader(stream, detectEncodingFromByteOrderMarks: true);

    int lineNumber = 0;
    string? line;
    while ((line = await reader.ReadLineAsync(ct)) is not null)
    {
        lineNumber++;
        if (line.Length &gt; 8192) continue; // skip absurdly long lines
        if (line.Contains(text, comparison))
        {
            var snippet = line.Length &gt; 500 ? line[..500] + "…" : line;
            results.Add((lineNumber, snippet.Trim()));
            if (results.Count &gt;= maxMatches) break;
        }
    }

    return results;
}

Priorities

  1. FileOptions.Asynchronous | FileOptions.SequentialScan + bigger buffer — biggest win, tiny change.
  2. Per-file size cap + better binary detection — prevents worst-case blow-ups.
  3. Snippet truncation — bounds memory of matches.
  4. Parallel.ForEachAsync — the real “more async” you asked for; scales with cores/SSD.
  5. FileShare.ReadWrite | FileShare.Delete — fewer spurious skips.

Want me to produce the full rewritten file?

The review wasn’t great but for a “nasty” PoC it will be okay. Need to work on exception catching and directory escape functionality.

Mistral Chat Completion with tools first fail

When I tested the Mistral Vibe Code generated client for the Mistral Chat Completion API, everything looked good until I added a couple of tool calls. The very first request exploded with a runtime exception:

The Mistral Chat Completion API rejected the malformed assistant message: “Assistant message must have either content or tool_calls, but not none” This was the first clue that the polymorphic message model wasn’t being serialised correctly.

Inspecting the raw JSON request inside Visual Studio’s JSON Visualizer. The error object clearly showed the invalid assistant message structure generated by the client.

After digging through the JSON returned by Mistral and inspecting the request object in Visual Studio, I figured out that System.Text.Json wasn’t serializing the polymorphic MessageBase hierarchy correctly.

namespace MistralAI.Client.DTOs.Shared
{
   /// <summary>
   /// Represents a message in a chat conversation.
   /// </summary>
   [JsonPolymorphic(TypeDiscriminatorPropertyName = "role")]
   [JsonDerivedType(typeof(SystemMessage), "system")]
   [JsonDerivedType(typeof(UserMessage), "user")]
   [JsonDerivedType(typeof(AssistantMessage), "assistant")]
   [JsonDerivedType(typeof(ToolMessage), "tool")]
   public abstract class MessageBase
    {
        /// <summary>
        /// The role of the message author.
        /// </summary>
        [JsonPropertyName("role")]
        public string Role { get; set; } = string.Empty;

        /// <summary>
        /// The content of the message.
        /// </summary>
        [JsonPropertyName("content")]
        public string? Content { get; set; }
    }

    /// <summary>
    /// A message from the system.
    /// </summary>
    public class SystemMessage : MessageBase
    {
        public SystemMessage() => Role = "system";
    }

    /// <summary>
    /// A message from the user.
    /// </summary>
    public class UserMessage : MessageBase
    {
        public UserMessage() => Role = "user";
    }

    /// <summary>
    /// A message from the assistant.
    /// </summary>
    public class AssistantMessage : MessageBase
    {
        public AssistantMessage() => Role = "assistant";

        /// <summary>
        /// Tool calls made by the assistant.
        /// </summary>
        [JsonPropertyName("tool_calls")]
        public List<ToolCall>? ToolCalls { get; set; }
    }

The fix was to annotate the base class with JsonPolymorphic and JsonDerivedType attributes so the serialiser could select the correct concrete type based on the role field.

Ironically both Claude Code and Github Copilot had the serialisation attributes correct.

Mistral Chat Completions

Building a lightweight Codestral Chat Completion Command-Line Interface(CLI) is one of the fastest ways to understand how modern Large Language Model(LLM) Application Programming Interfaces (API) work in the real world. While everyone is talking about “agentic” programming (I now spend a lot of time reviewing code, as more agents = more reviews) and “token maxing” (difficult conversations with finance) this series of posts is about the plumbing.

I’m starting from the bottom and working my way up the stack. A raw Hypertext Transfer Protocol(HTTP) contract: an HTTP POST, a model name, a messages array, and a response object you have to parse yourself. With an HTTP proxy (Telerik Fiddler) I confirmed the Mistral Chat API endpoint Uniform Resource Locator(URL) and my API Key worked.

Before writing or generating typed Data Transfer Objects(DTO), or any kind of strongly‑typed client, streaming the response JSON into a jsonDocument was a good way to visualise the shape of the responses. I could enumerate properties, check for missing or inconsistent fields, validate casing, and confirm whether optional objects appear only in certain scenarios. Any undocumented polymorphic shapes, and response constructs can be impossible to model cleanly, and “hand-rolled” serialisation can be fragile.

//...
Console.Write("Enter chat message: ");
var prompt = Console.ReadLine();

// Anonymous type for the request body which feels bit "hinky" but, it works and is concise. Alternatively, could define a class for request body for better type safety and maintainability.
var requestObject = new
{
   model = settings.ModelName,
   messages = new[]
   {
      new { role = "user", content = prompt }
   }
};

// Alternatively, a JsonObject and JsonArray for more control over the JSON structure
var requestJson = new JsonObject()
{
   ["model"] = settings.ModelName,
   ["messages"] = new JsonArray
   {
      new JsonObject
      {
         ["role"] = "user",
         ["content"] = prompt
      }
   }
};

// Create HttpClient with required headers. Note that HttpClient should ideally be reused, but for simplicity we're creating a new instance here.
HttpClient httpClient = new()
{
   DefaultRequestHeaders =
   {
      Accept = { new MediaTypeWithQualityHeaderValue("application/json") },
      Authorization = new AuthenticationHeaderValue("Bearer", settings.ApiKey)
   },
   BaseAddress = new Uri(settings.BaseUrl)
};

using var httpResponse = await httpClient.PostAsync("chat/completions", new StringContent(JsonSerializer.Serialize(requestObject), Encoding.UTF8, "application/json"));

httpResponse.EnsureSuccessStatusCode();

using var stream = await httpResponse.Content.ReadAsStreamAsync();
using var responseDocument = await JsonDocument.ParseAsync(stream);

var content = responseDocument.RootElement.GetProperty("choices")[0].GetProperty("message").GetProperty("content").GetString();

Console.WriteLine(content);
Console.WriteLine();

var usage = responseDocument.RootElement.GetProperty("usage");
Console.WriteLine($"Prompt tokens: {usage.GetProperty("prompt_tokens").GetInt32()}");
Console.WriteLine($"Completion tokens: {usage.GetProperty("completion_tokens").GetInt32()}");
Console.WriteLine($"Total tokens: {usage.GetProperty("total_tokens").GetInt32()}");
Console.WriteLine();

Console.WriteLine("Press <Enter> to exit...");
Console.ReadLine();

Reading the response string and parsing it with a jsonDocument is straightforward but can be inefficient for large responses because it loads the entire response into memory.

I built the typed interface by inspecting real JSON responses especially structures like polymorphic message, and cross‑checking them against the Mistral API docs. This highlighted which fields are genuinely optional, which only appear for tool calls, and which vary by finish reason. It also highlighted that I would have to introduce polymorphic message classes so the interface can cleanly represent text messages, tool‑call messages, and whatever new variants the API adds later.

// Create HttpClient with required headers. Note that HttpClient should ideally be reused, but for simplicity we're creating a new instance here..
using HttpClient httpClient = new()
{
   DefaultRequestHeaders =
   {
      Accept = { new MediaTypeWithQualityHeaderValue("application/json") },
      Authorization = new AuthenticationHeaderValue("Bearer", settings.ApiKey)
   },
   BaseAddress = new Uri(settings.BaseUrl)
};

var jsonSerializerOptions = new JsonSerializerOptions()
{
   // PropertyNamingPolicy removed - [JsonPropertyName] attributes on model handle wire names
   WriteIndented           = false,
   DefaultIgnoreCondition  = JsonIgnoreCondition.WhenWritingNull,
   AllowTrailingCommas     = false,
   ReadCommentHandling     = JsonCommentHandling.Disallow,
   UnmappedMemberHandling  = JsonUnmappedMemberHandling.Skip,
};

Console.Write("Enter chat message: ");
var content = Console.ReadLine();

while (!string.IsNullOrWhiteSpace(content))
{
   var request = new ChatCompletionRequest
   {
      Model = settings.ModelName,
      Messages =
      [
         new ChatMessage { Role = "user", Content = content }
      ],
   };

   try
   {
      using var httpResponse = await httpClient.PostAsJsonAsync("chat/completions", request, jsonSerializerOptions);
      httpResponse.EnsureSuccessStatusCode();

      ChatCompletionResponse? chatCompletionResponse = await httpResponse.Content.ReadFromJsonAsync<ChatCompletionResponse>(jsonSerializerOptions);

      if (chatCompletionResponse != null)
      {
         foreach (var choice in chatCompletionResponse.Choices)
         {
            Console.WriteLine(choice.Message.Content);
         }

         Console.WriteLine();
         if (chatCompletionResponse.Usage != null)
         {
            Console.WriteLine($"Prompt tokens: {chatCompletionResponse.Usage.PromptTokens}");
            Console.WriteLine($"Completion tokens: {chatCompletionResponse.Usage.CompletionTokens}");
            Console.WriteLine($"Total tokens: {chatCompletionResponse.Usage.TotalTokens}");
         }
         Console.WriteLine();
      }
   }
   catch (HttpRequestException ex)
   {
      Console.WriteLine($"Request failed: {(int?)ex.StatusCode} {ex.Message}");
   }
   catch (TaskCanceledException)
   {
      Console.WriteLine("Request timed out.");
   }
   catch (JsonException ex)
   {
      Console.WriteLine($"Failed to parse response: {ex.Message}");
   }

   Console.Write("Enter chat message: ");
   content = Console.ReadLine();
}
public sealed class ChatCompletionRequest
{
   [JsonPropertyName("model")] public required string Model { get; init; }
   [JsonPropertyName("messages")] public required List<ChatMessage> Messages { get; init; }
   [JsonPropertyName("temperature")] public double? Temperature { get; init; }
   [JsonPropertyName("max_tokens")] public int? MaxTokens { get; init; }
   [JsonPropertyName("stream")] public bool? Stream { get; init; }
   [JsonPropertyName("response_format")] public ResponseFormat? ResponseFormat { get; init; }
}

public sealed class ChatMessage
{
   [JsonPropertyName("role")] public required string Role { get; init; }
   [JsonPropertyName("content")] public required string Content { get; init; }
}

public sealed class ResponseFormat
{
   [JsonPropertyName("type")] public required string Type { get; init; }
}

public sealed class ChatCompletionResponse
{
   [JsonPropertyName("id")] public required string Id { get; init; }
   [JsonPropertyName("choices")] public required List<ChatCompletionChoice> Choices { get; init; }
   [JsonPropertyName("usage")] public TokenUsage? Usage { get; init; }
}

public sealed class TokenUsage
{
   [JsonPropertyName("prompt_tokens")] public int? PromptTokens { get; init; }
   [JsonPropertyName("completion_tokens")] public int? CompletionTokens { get; init; }
   [JsonPropertyName("total_tokens")] public int? TotalTokens { get; init; }
}

public sealed class ChatCompletionChoice
{
   [JsonPropertyName("index")] public int Index { get; init; }
   [JsonPropertyName("message")] public required ChatMessage Message { get; init; }
   [JsonPropertyName("finish_reason")] public string? FinishReason { get; init; }
}

I had to capture the application output in two screenshots as the response text was longer.

The non-deterministic nature of LLMs resulted in different response messages, with the longest one consuming significantly more tokens, 530 vs. 799 (future posts will cover the use of Random_seed)

Azure Event Grid Arduino Client – The joy of certs

“Lets start at the very beginning, A very good place to start”

The Azure Event Grid MQTT Broker server X509 certificate chain can be copy ‘n’ paste from the output of the openssl command

openssl s_client -connect YourNamespace.newzealandnorth-1.ts.eventgrid.azure.net:8883 -showcerts

A self-signed X509 root certificate which can sign intermediate X509 certificates and key file can be generated with a single openssl command.

openssl req -x509 -newkey rsa:4096 -keyout rootCA.key -out rootCA.crt -days 3650 -nodes -subj "/CN=devMobile  /O=devMobile.co.nz /C=NZ" -addext "basicConstraints=critical,CA:TRUE" -addext "keyUsage=critical,keyCertSign"

For a non-trivial system there should be a number of intermediate certificates. I have tried creating intermediate certificates for a device type, geography, application, customer and combinations of these. The first couple of times got it wrong so start with a field trial so that it isn’t so painful to go back and fix. (beware the sunk cost fallacy)

openssl genrsa -out intermediate.key 4096

openssl req -new -key intermediate.key -out intermediate.csr -subj "/CN=intermediate  /O=devMobile.co.nz /C=NZ"

I found creating an intermediate certificate that could sign device certificates required a conf file for the basicConstraints and keyUsage configuration.

[ v3_intermediate_ca ]
basicConstraints = critical, CA:TRUE, pathlen:0
keyUsage = critical, keyCertSign
  • critical-The extension must be understood and processed by any application validating the certificate. If the application does not understand it, the certificate must be rejected.
  • CA:TRUE-This certificate is allowed to act as a Certificate Authority (CA), meaning it can sign other certificates.
  • pathlen:0-This CA can only issue end-entity (leaf) certificates and cannot issue further intermediate CA certificates.
  • keyCertSig- The certificate can be used to sign other certificates (i.e., it’s a CA certificate).
openssl x509 -req -in intermediate.csr  -CA rootCA.crt -CAkey rootCA.key -CAcreateserial -out intermediate.crt -days 1825 -extfile intermediate_ext.cnf -extensions v3_intermediate_ca

Creating a device certificate is similar to the process for the intermediate certificate but doesn’t need to be able to sign certificates.

openssl genrsa -out EdgeBox100A.key 4096

openssl req -new -key EdgeBox100A.key -out EdgeBox100A.csr -subj "/CN=EdgeBox100A"

openssl x509 -req -in EdgeBox100A.csr -CA intermediate.crt -CAkey intermediate.key -CAcreateserial -out EdgeBox100A.crt -days 365 

For production systems putting some thought into the Common name(CN), Organizational unit name(OU), Organization name(O), locality name(L), state or province name(S) and Country name(C)

// Minimalist ESP32 + Event Grid MQTT (mTLS) with PubSubClient
// Copyright (c) November 2025, devMobile Software
#include <PubSubClient.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>

#include "constants.h"
#include "secrets.h"

// --- Wi-Fi ---
//const char* WIFI_SSID     = "";
//const char* WIFI_PASSWORD = "";

// --- Event Grid MQTT ---
//const char* MQTT_SERVER = "";
const uint16_t MQTT_PORT = 8883;

//const char* MQTT_CLIENTID = "";
//const char* MQTT_USERNAME = "";
//const char* MQTT_PASSWORD = "";
//const char* MQTT_TOPIC_PUBLISH = "devices/";
//const char* MQTT_TOPIC_SUBSCRIBE = "devices/";

/*
// The certificate that is used to authenticate the MQTT Broker
const char CA_ROOT_PEM[] PROGMEM = R"PEM(
-----BEGIN CERTIFICATE-----
      Thumbprint: 56D955C849887874AA1767810366D90ADF6C8536
      CN: CN=Microsoft Azure ECC TLS Issuing CA 03
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
      Thumbprint: 7E04DE896A3E666D00E687D33FFAD93BE83D349E
      CN: CN=DigiCert Global Root G3
-----END CERTIFICATE-----
)PEM";

The certificate that is used to authenticate the device
static const char CLIENT_CERT_PEM[] PROGMEM = R"PEM(
-----BEGIN CERTIFICATE-----
 CN=Self signed device certificate
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
 CN=Self signed Intermediate certificate
-----END CERTIFICATE-----
)PEM";

 The PEM encoded private key of device
static const char CLIENT_KEY_PEM[] PROGMEM = R"PEM(
-----BEGIN PRIVATE KEY-----
-----END PRIVATE KEY-----
)PEM";
*/

WiFiClientSecure secureClient;
PubSubClient mqttClient(secureClient);

void setup() {
  Serial.begin(9600);
  delay(5000);
  Serial.println();

  // Connect to WiFi
  Serial.println("WiFi connecting");
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("*");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print("*");
  }
  Serial.println("\nWiFi connected");

  // Sync time for TLS
  Serial.println("\nTime synchronising");
  configTime(0, 0, "pool.ntp.org", "time.nist.gov");
  Serial.print("*");
  while (time(nullptr) < 100000) {
    delay(500);
    Serial.print("*");
  }
  Serial.println("\nTime synchronised");

  Serial.println("\nValidating ServerFQDN-Certificate combination");
  secureClient.setCACert(CA_ROOT_PEM);

  Serial.println("TCP connecting");
  if (secureClient.connect(MQTT_SERVER, MQTT_PORT)) {
    Serial.println("\nTCP connected");
  } else {
    Serial.println("\nTCP connection failed");
    return;
  }

  secureClient.setCertificate(CLIENT_CERT_A_PEM);
  secureClient.setPrivateKey(CLIENT_KEY_A_PEM);

  mqttClient.setServer(MQTT_SERVER, MQTT_PORT);

  Serial.println("\nMQTT connecting");
  Serial.print("*");
  while (!mqttClient.connect(MQTT_CLIENTID, MQTT_USERNAME, MQTT_PASSWORD)) {
    Serial.println(mqttClient.state());
    delay(5000);
    Serial.print("*");
  }
  Serial.println("\nMQTT connected");
}

static uint32_t sequenceNumber = 0;

void loop() {
  mqttClient.loop();

  Serial.print("'.");
  delay(10000);
}

My Arduino Xiao ESP32S3 and EdgeBox-ESP-100-Industrial Edge Controller devices could connect to the local Wi-Fi, get the time and date using the network time protocol(NTP), and validate the Azure Event Grid MQTT broker certificate. Then connect to the Azure Event Grid MQTT broker with the client name specified in the subject name of its X509 certificate.

Establishing a connection to the Azure Event Grid MQTT broker often failed which surprised me. Initially I didn’t have any retry logic which meant I wasted quite a bit of time trying to debug failed connections

.NET 10 OpenAPI and SwashBuckle NuGets

Yesterday I downloaded Microsoft Visual Studio 2026 and started updating the projects I am working on to .NET 10 and updating any NuGets.

I left these three NuGets to the last as I have had problems updating them before, and this time was no different. The updated NuGets “broke” my code because the way that security definitions and security requirements were implemented had changed.

These articles were the inspiration for my approach

   options.AddSecurityDefinition("X-API-Key", new OpenApiSecurityScheme
   {
      Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
      Name = "Authorization",
      In = ParameterLocation.Header,
      Type = SecuritySchemeType.Http,
      Scheme = "Bearer"
   });

   options.AddSecurityRequirement(document => new OpenApiSecurityRequirement
   {
      [new OpenApiSecuritySchemeReference("Bearer", document)] = [],
      [new OpenApiSecuritySchemeReference("X-API-Key", document)] = []
   });
});

Warning: make sure the schema etc. have same case so you don’t lose an hour from your life that you will never get back.

With the above updates the application would work but….

WithOpenApi was originally designed for minimal APIs to attach an OpenApiOperation to endpoint metadata so tools like Swashbuckle could consume it.

Deprecation of WithOpenApi extension method

However, starting with .NET 9, ASP.NET Core introduced native OpenAPI document generation via Microsoft.AspNetCore.OpenApi. This made WithOpenApi unnecessary because the new pipeline already supports operation customization through transformers.

app.MapGet("Version", () =>
{
   return Results.Ok(typeof(Program).Assembly.GetName().Version?.ToString());
}).RequireAuthorization()
         .WithName("Version")
         .Produces<string>(StatusCodes.Status200OK)
         .Produces(StatusCodes.Status401Unauthorized)
         .AddOpenApiOperationTransformer((operation, context, ct) =>
         {
            // Per-endpoint tweaks
            operation.Summary = "Returns version of the application";
            operation.Description = "Returns the version of the application from project metadata.";
            return Task.CompletedTask;
         });

The new transformer API (AddOpenApiOperationTransformer) works directly with the built-in OpenAPI pipeline. It allows per-operation or global modifications without relying on third-party libraries.

ONNXRuntime.AI-Faster R-CNN C# Sample differences

After building Faster R-CCN object detection applications with Copilot and Github Copilot the results when compared with the onnxruntime.ai Object detection with Faster RCNN Deep Learning in C# sample (which hasn’t been updated for years) were slightly different.

The sample image was 640×480 pixels

The FasterRCNNObjectDetectionApplicationGitHubCopilot application scaled image was initially 1056×800 then 1088×800 pixels.

The initial version the dimensions were “rounded down” to the next multiple of 32

// Calculate scale factor to fit within the range while maintaining aspect ratio
float scale = Math.Min((float)maxSize / Math.Max(originalWidth, originalHeight),
                                (float)minSize / Math.Min(originalWidth, originalHeight));

// Calculate new dimensions
int newWidth = (int)(originalWidth * scale);
int newHeight = (int)(originalHeight * scale);

// Ensure dimensions are divisible by 32
newWidth = (newWidth / divisor) * divisor;
newHeight = (newHeight / divisor) * divisor;
Scaled 1056×800

Then for the second version the dimensions were “rounded up” to the next multiple of 32

// Calculate scale factor to fit within the range while maintaining aspect ratio
float scale = Math.Min((float)maxSize / Math.Max(originalWidth, originalHeight),
                                (float)minSize / Math.Min(originalWidth, originalHeight));

// Calculate new dimensions
int newWidth = (int)(originalWidth * scale);
int newHeight = (int)(originalHeight * scale);

// Ensure dimensions are divisible by 32
newWidth = (int)(Math.Ceiling(newWidth / 32f) * 32f);
newHeight = (int)(Math.Ceiling(newHeight / 32f) * 32f);
Scaled 1088×800
Marked up 1088×800

The FasterRCNNObjectDetectionApplicationOriginal application scaled the input image to 1066×800

Scaled image 1066×800

The FasterRCNNObjectDetectionApplicationOriginal application pillar boxed/padded the image to 1088×800 as the DenseTensor was loaded.

using Image<Rgb24> image = Image.Load<Rgb24>(imageFilePath);

Console.WriteLine($"Before x:{image.Width} y:{image.Height}");

// Resize image
float ratio = 800f / Math.Min(image.Width, image.Height);
image.Mutate(x => x.Resize((int)(ratio * image.Width), (int)(ratio * image.Height)));

Console.WriteLine($"After x:{image.Width} y:{image.Height}");

// Preprocess image
var paddedHeight = (int)(Math.Ceiling(image.Height / 32f) * 32f);
var paddedWidth = (int)(Math.Ceiling(image.Width / 32f) * 32f);

Console.WriteLine($"Padded x:{paddedWidth} y:{paddedHeight}");

Tensor<float> input = new DenseTensor<float>(new[] { 3, paddedHeight, paddedWidth });
var mean = new[] { 102.9801f, 115.9465f, 122.7717f };
image.ProcessPixelRows(accessor =>
{
   for (int y = paddedHeight - accessor.Height; y < accessor.Height; y++)
   {
      Span<Rgb24> pixelSpan = accessor.GetRowSpan(y);
      for (int x = paddedWidth - accessor.Width; x < accessor.Width; x++)
      {
         input[0, y, x] = pixelSpan[x].B - mean[0];
         input[1, y, x] = pixelSpan[x].G - mean[1];
         input[2, y, x] = pixelSpan[x].R - mean[2];
      }
   }
});
Marked up image 1066×800

I think the three different implementations of the preprocessing steps and the graphics libraries used probably caused the differences in the results. The way an image is “resized” by System.Graphics.Common vs. ImageSharp(resampled, cropped and centered or padded and pillar boxed) could make a significant difference to the results.