AI in Software Architecture · Part 3
An AI assistant in a .NET MAUI app: the key stays on the server
Give the support screen of a MAUI shop app a MentorAgent assistant: the view model keeps its port, an adapter reads the agent's event stream, and the key and the order rules stay on your backend.

In this article
The article on Medium (external site) puts an assistant on the support screen of a shop's mobile app. Its answer to the architecture question: the view model asks a port written in the words of the shop, your own backend holds the key, and the answer streams into a bound property. This how-to builds the backend and the adapter with MentorAgent, and leaves the view model of the article as it is.
One thing first. A native .NET MAUI page, with XAML and a view model, has no ready-made MentorAgent widget: the widget is for Blazor, and that includes the Blazor Hybrid kind of MAUI app. A native page talks to the endpoints of Novior.MentorAgent.Server. That is what you build here.
Inside the app, or behind a server
Section titled “Inside the app, or behind a server”MentorAgent can run inside a MAUI Blazor Hybrid app, but then the model key is part of the app. The docs say it plainly: for an app you distribute, keep the agent and the key on a server and connect the app as a client (.NET MAUI as a client of a server). We take that route. The app needs no MentorAgent package at all.
Step 1: the backend
Section titled “Step 1: the backend”An ASP.NET Core app with two packages, Novior.MentorAgent.Server and a model provider (here Microsoft.Extensions.AI.OpenAI). The action is a method of a service. It reads, so it is marked ReadOnly, and it takes the customer from the token of the request, never from the question:
public sealed class OrderActions(IOrderStore orders, MentorServerUserContext hubUser, IHttpContextAccessor http)
{
[MentorAction(Description = "Returns the status of one of the signed-in customer's orders", ReadOnly = true)]
public async Task<string> GetOrderStatus(string orderNumber)
{
// The customer comes from the token of the request, never from the question
var customerId = (hubUser.User ?? http.HttpContext?.User)?.FindFirstValue(ClaimTypes.NameIdentifier)
?? throw new InvalidOperationException("Nobody is signed in.");
var status = await orders.GetStatusAsync(customerId, orderNumber);
return status is null
? $"This customer has no order {orderNumber}."
: $"Order {orderNumber} is {status}.";
}
}If the model passes an order number of somebody else, the store finds nothing for this customer. The rule does not depend on the prompt. A request to /mentor/chat carries its user in HttpContext, and a SignalR connection keeps it in MentorServerUserContext: reading both keeps the action right if you move to the hub later.
The registration is the one of the Any front end page, plus the sign-in check on the transports:
builder.Services.AddMentorAgent(options =>
{
options.AppName = "Shop";
options.AppDescription = "Order status for the customers of the shop";
options.ChatClient = new OpenAIClient(builder.Configuration["OpenAI:Key"]
?? throw new InvalidOperationException("Set OpenAI:Key with dotnet user-secrets."))
.GetChatClient("gpt-4o-mini")
.AsIChatClient();
options.ScanAssemblies = [typeof(OrderActions).Assembly];
options.RateLimitPerUser = 20;
});
builder.Services.AddMentorAgentServer();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapMentorAgentServer(configureTransports: e => e.RequireAuthorization());OpenAI:Key lives in user secrets or in the configuration of the server. Add your authentication scheme too (JWT bearer or Entra ID): without one, the endpoints have no way to tell who is calling. MapMentorAgentServer maps /mentor/chat, a Server-Sent Events (SSE) endpoint, and a SignalR hub. Secure the endpoints explains how to protect each one, because anybody who reaches them runs paid turns on your model.
Step 2: the adapter
Section titled “Step 2: the adapter”The port of the article stays:
public interface ISupportAssistant
{
IAsyncEnumerable<string> AskAsync(string question, CancellationToken cancellationToken);
}Only the adapter changes. It posts the question to /mentor/chat and reads the frames as they arrive. The SSE frames are data: lines with a JSON object: chunk carries a piece of the answer, completed ends the turn, error reports a failure.
using var request = new HttpRequestMessage(HttpMethod.Post, "mentor/chat")
{
Content = JsonContent.Create(new { message = question })
};
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream"));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await tokens.GetTokenAsync(cancellationToken));The token comes from the sign-in of the app, through the same IAccessTokenProvider as in the article. It travels in the Authorization header, not in a cookie, so no other site can send it for the customer. The app holds that token and the address of the backend, never a model key. Then the loop:
var frame = ReadFrame(line[5..]);
switch (frame.Type)
{
case "chunk":
yield return frame.Text;
break;
case "completed":
yield break;
case "error":
throw new AssistantUnavailableException("The agent reported an error: " + frame.Text);
case "confirmationRequired":
// This screen only reads, and has no box to ask. Leaving closes the request and the turn stops.
throw new AssistantUnavailableException("The agent asked for a confirmation");
}The lines come from StreamReader.ReadLineAsync, so a frame split across two network reads is put together before it is parsed. A stream that ends without completed is a dropped connection, and the adapter says so with AssistantUnavailableException, the exception the view model already knows. Cards and navigation frames are ignored: the answer is still whole without them.
Cancel needs nothing new. The token of the Cancel command reaches SendAsync and the read, and the request is aborted. The README of Novior.MentorAgent.Server says that over SSE the server cancels the turn when the client goes away. We did not test that part here.
Step 3: the app
Section titled “Step 3: the app”The composition root is the only place that knows the address of the backend. The extension method of the article now registers the new adapter:
services.AddHttpClient<ISupportAssistant, MentorAgentSupportAssistant>(client => client.BaseAddress = backend);
services.AddSingleton(new SupportChatOptions(stallTimeout));
services.AddTransient<SupportChatViewModel>();In the MAUI project, MauiProgram.CreateMauiApp calls it on builder.Services, after your IAccessTokenProvider, a class that wraps the sign-in library of your app, and before the XAML page of the article, registered with AddTransient. That is the pattern of the .NET MAUI dependency injection (external site) page: services in CreateMauiApp, a page whose constructor takes the view model. .NET MAUI is not available where this code was built, so a test makes the same calls on a plain ServiceCollection and checks that the view model gets the MentorAgent adapter:
[Test]
public void TheCallsOfMauiProgram_GiveTheViewModelTheMentorAgentAdapter()
{
// The calls of MauiProgram.CreateMauiApp, on a plain service collection
var services = new ServiceCollection();
services.AddLogging();
services.AddSingleton(Mock.Of<IAccessTokenProvider>());
services.AddSupportAssistant(new Uri("https://shop.example.com/"), TimeSpan.FromSeconds(20));
using var provider = services.BuildServiceProvider(new ServiceProviderOptions { ValidateOnBuild = true });
Assert.That(provider.GetRequiredService<SupportChatViewModel>(), Is.Not.Null);
Assert.That(provider.GetRequiredService<ISupportAssistant>(), Is.InstanceOf<MentorAgentSupportAssistant>());
}The view model also asks for an ILogger, so the test adds logging, and a mock stands in for the sign-in. In the app, SupportPage sets its BindingContext to the injected view model. The view model has no idea that the answers now come from MentorAgent.
Step 4: test it without a model
Section titled “Step 4: test it without a model”The tests start the real backend in memory with WebApplicationFactory. MentorAgent, its endpoints and the order action all run. Only the chat model is a stand-in that calls the order tool and then says what the tool returned, so no call leaves the machine:
[Test]
public async Task Ask_StreamsTheAnswerOfTheAgentInChunks()
{
var assistant = AssistantFor("customer-7");
var chunks = await ReadAllAsync(assistant);
Assert.That(chunks, Has.Count.GreaterThan(1));
Assert.That(string.Concat(chunks).Trim(), Is.EqualTo("Order 1042 is on its way."));
}The same fixture checks that another customer asking about order 1042 gets "no order", that a caller who is not signed in ends in the view model's fallback message, and that an error frame, a confirmationRequired frame and a stream that stops early all become AssistantUnavailableException. Two tests run the real SupportChatViewModel against the in-memory backend, so the whole path from the command to the bound property is covered. Nine tests, all green.
Good to know
Section titled “Good to know”- One question, one conversation. Every
/mentor/chatrequest starts a new session, so a follow-up such as "and the second one?" has nothing to refer to. For a chat with memory of the turns, use the SignalR hub with the .NET client,Microsoft.AspNetCore.SignalR.Client: the docs list it for MAUI apps. - Actions that change data. They ask for confirmation, and over SSE the stream waits for
POST /mentor/approve. This adapter refuses that case on purpose. Over SSE a confirmation has no owner: whoever holds itsactionIdcan answer it. See where nobody can answer before you add one. - Anonymous callers. Every anonymous request is a different user, and the rate limit cannot follow a person. Require sign-in, as above.
- The device. The backend, the adapter and the view model run in the tests. A real phone adds the network that comes and goes and an app that goes to the background; try those on the devices you support.
Get started
Section titled “Get started”New to MentorAgent? Start with What is MentorAgent.
Written with the help of AI; code and facts checked by the MentorAgent team.
