AI in Software Architecture · Part 2
An AI assistant on an MVC page: stream its answer with MentorAgent
Put a MentorAgent assistant on the confirmation page of an ASP.NET Core MVC shop: the page renders at once, the answer streams in over Server-Sent Events or SignalR, and the assistant sees only the signed-in customer's orders.

In this article
The article on Medium (external site) puts an assistant on the confirmation page of an MVC shop. The answer to its architecture question is two requests: the page renders at once, and the answer gets an address of its own, as a stream. This how-to builds the same page with MentorAgent, and shows when the stream is Server-Sent Events (SSE) and when it is a SignalR hub.
One thing first. MentorAgent's ready-made chat widget is documented for Blazor and .NET MAUI apps, not for MVC or Razor Pages. An MVC page uses the endpoints of Novior.MentorAgent.Server and a small script of its own. That is what you build here, and the model's key stays on the server.
What you need
Section titled “What you need”An ASP.NET Core MVC app on .NET 10 with a sign-in, and two packages:
dotnet add package Novior.MentorAgent.Server
dotnet add package Microsoft.Extensions.AI.OpenAINovior.MentorAgent.Server brings Novior.MentorAgent with it. The model provider package is yours to add: this page uses OpenAI, and other providers are in Model providers.
Step 1: Register MentorAgent and protect its endpoints
Section titled “Step 1: Register MentorAgent and protect its endpoints”var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
builder.Services.AddScoped<SignedInCustomer>();
builder.Services.AddScoped<OrderActions>();
builder.Services.AddMentorAgent(options =>
{
options.AppName = "Shop";
options.AppDescription = "An online shop: the assistant answers questions about the orders of the customer";
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];
// The page shows plain text: ask for answers without Markdown
options.EnableRichResponses = false;
options.MaxMessageLength = 300;
options.RateLimitPerUser = 20;
});
builder.Services.AddMentorAgentServer();
var app = builder.Build();
// The page posts JSON and never uses GET: refuse it
app.Use(async (context, next) =>
{
if (HttpMethods.IsGet(context.Request.Method) && context.Request.Path.StartsWithSegments("/mentor/chat"))
context.Response.StatusCode = StatusCodes.Status405MethodNotAllowed;
else
await next(context);
});
app.UseAuthentication();
app.UseAuthorization();
app.MapMentorAgentServer(configureTransports: e => e.RequireAuthorization());MapMentorAgentServer maps the hub at /mentor-hub and SSE at /mentor/chat. Both are open until you protect them, and every turn is paid by you: configureTransports requires a signed-in user on both. The rate limit then counts per customer. For other schemes and for cross-origin pages, see Secure the endpoints.
The middleware is about the sign-in cookie. Since 1.3.0 /mentor/chat refuses a request that another site starts in the browser, but the MentorAgent endpoints check no antiforgery token, and a browser without Fetch Metadata is not covered, so with a cookie sign-in it is still safer to accept only the requests your page really sends. POST /mentor/chat reads only a JSON body, and a script on another origin would need a CORS policy that this app does not have. This page never uses GET, so the app refuses it. If you add a CORS policy with credentials, list only your own origins.
Step 2: One action, and the customer from the sign-in
Section titled “Step 2: One action, and the customer from the sign-in”The assistant gets one read-only action. The customer id is never a parameter: the model could be talked into any value, so it comes from the sign-in.
public sealed class SignedInCustomer(MentorServerUserContext hubUser, IHttpContextAccessor http)
{
public Guid? Id => Guid.TryParse((hubUser.User ?? http.HttpContext?.User)?.FindFirstValue(ClaimTypes.NameIdentifier), out var id) ? id : null;
}
public sealed class OrderActions(IOrderRepository orders, SignedInCustomer customer)
{
[MentorAction(Description = "Lists the most recent orders of the signed-in customer: number, date, total and status", ReadOnly = true)]
public async Task<string> ListMyOrders()
{
// The customer comes from the sign-in, never from the question or from the model
if (customer.Id is not { } customerId)
return NotSignedIn;
var recent = await orders.ListRecentAsync(customerId, 5, CancellationToken.None);
}
}The rest of the method formats the orders as lines of text. Why a small class for the user? The hub keeps the user of each connection in MentorServerUserContext, and a request to /mentor/chat has it in HttpContext. AddMentorAgentServer() registers IHttpContextAccessor. An AuthenticationStateProvider is not an option here: outside a Blazor circuit it throws, as the package README warns and as our first try showed. The id is the NameIdentifier that the shop's own sign-in writes in the cookie. With an external provider such as Entra ID, read an immutable claim such as oid instead.
ReadOnly = true matters. A [MentorAction] that changes data asks the user to confirm by default, and this page has no dialog. Add one when you add a write: Where nobody can answer explains what each channel does.
Step 3: A thin controller, a page without model text
Section titled “Step 3: A thin controller, a page without model text”[Authorize]
public sealed class OrdersController : Controller
{
// The page renders at once: no model is called here
public IActionResult Confirmation(Guid id) => View(new ConfirmationViewModel(id));
}The view holds the order, a form and the addresses of the endpoints, and nothing the model wrote:
<section id="assistant" data-chat-url="@Url.Content("~/mentor/chat")"
data-hub-url="@Url.Content("~/mentor-hub")" data-cancel-url="@Url.Content("~/mentor/cancel")">
<form id="assistant-form">
<input id="assistant-question" maxlength="300" required />
<button type="submit">Ask</button>
<button type="button" id="assistant-stop" hidden>Stop</button>
</form>
<p id="assistant-answer" style="white-space: pre-wrap" aria-live="polite"></p>
</section>
<script src="~/js/assistant.js" asp-append-version="true"></script>Step 4: Read the stream with SSE
Section titled “Step 4: Read the stream with SSE”POST /mentor/chat takes a JSON body, so the question stays out of the URL and out of the logs, unlike EventSource, which can only call a URL. The reply is text/event-stream, with one JSON object in each data: line:
data: {"type":"chunk","text":"Order 1042 ","aiGenerated":true}
data: {"type":"completed","aiGenerated":true}The page reads it with fetch:
async function readFrames(response, onFrame) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true }); // a read can end in the middle of a frame
const lines = buffer.split('\n');
buffer = lines.pop();
for (const line of lines)
if (line.startsWith('data:')) onFrame(JSON.parse(line.slice(5)));
}
}The submit handler calls it, with an AbortController for the Stop button:
await readFrames(response, frame => {
if (state !== 'open') return;
if (frame.type === 'chunk') answer.textContent += frame.text; // text, never markup
if (frame.type === 'completed') state = 'done';
if (frame.type === 'error') { state = 'failed'; answer.textContent = unavailable; }
});
if (state === 'open') answer.textContent = unavailable; // the stream ended without "completed"Three rules from the article carry over:
- Text, never markup.
textContentshows a<script>in the answer as text. Together withEnableRichResponses = false, the page shows what the model wrote and nothing more. - Decide how it ended. A
completedframe with noerrorbefore it is the only proof of a whole answer: MentorAgent sendscompletedafter anerrortoo. Anerror, a refused request or a stream that stops early all replace the text with one plain sentence. - A closed tab should stop the model. MentorAgent passes the request's abort token (
RequestAborted) to the turn, so when the server sees the request close, from Stop or from a closed tab, the turn is cancelled. We read this in the source and did not measure it: behind a proxy, check that a closed tab closes the request on the server too.
SSE or the SignalR hub
Section titled “SSE or the SignalR hub”Both reach the same agent, actions and rules. They differ in what they carry:
SSE, /mentor/chat | SignalR hub, /mentor-hub | |
|---|---|---|
| Client | fetch, nothing to install | @microsoft/signalr, with its own package and build |
| Conversation | Every request is a new one | One per connection: "and the second one?" works |
| Page context and UI actions | No | Yes |
| Stop | Abort the request | POST /mentor/cancel |
Use SSE for a question with a streamed answer, as on this page. Use the hub for a chat with follow-up questions, or when the assistant must drive the page. The hub's handlers are short:
connection.on('ReplyStarted', () => { }); // without a handler, SignalR logs a warning for every reply
connection.on('StreamingChunk', chunk => { answer.textContent += chunk; });
connection.on('BusyChanged', busy => { ask.disabled = busy; stop.hidden = !busy; });
connection.on('Error', () => { answer.textContent = unavailable; });Two traps: SendMessage always takes two arguments (connection.invoke('SendMessage', text, null)), and Stop and confirmations go over HTTP, not through the hub. Catch a failed start() or invoke() too, and show the same plain sentence. Any front end has the full list of events and a complete client.
Test it without a model
Section titled “Test it without a model”A scripted IChatClient stands in for the model: it asks for the action, then writes the result back a few words at a time. The test goes through the real pipeline, from the HTTP request to the action:
[Test]
public async Task Chat_StreamsTheAnswer_ForTheOrdersOfTheSignedInCustomerOnly()
{
// Arrange
var client = _factory.ClientFor(InMemoryOrderRepository.MarioId);
// Act
var response = await client.PostAsJsonAsync("/mentor/chat", new { message = "Where is my order?" });
var frames = await ReadFramesAsync(response);
// Assert
var types = frames.Select(f => f.GetProperty("type").GetString()).ToList();
var text = string.Concat(frames.Where(f => f.GetProperty("type").GetString() == "chunk").Select(f => f.GetProperty("text").GetString()));
Assert.That(types.Last(), Is.EqualTo("completed"));
Assert.That(types.Count(t => t == "chunk"), Is.GreaterThan(1), "the answer arrives in pieces");
Assert.That(text, Does.Contain("1042").And.Contain("1051"));
Assert.That(text, Does.Not.Contain("2077"), "an order of another customer");
}The solution has nine tests. Besides this one: the page renders without calling the model; an anonymous caller gets 401 and no model call; a GET, and a POST that is not JSON, are refused before the model; a message over the limit fails before the model is called; the same stream and the same rule through the hub; and the action alone with Moq. They call no provider.
Good to know
Section titled “Good to know”- No confirmation dialog. An action that asks for confirmation sends a
confirmationRequiredframe over SSE, and the stream waits forPOST /mentor/approve. This page has no such action. - Anonymous visitors. With the default
AnonymousIdentity, every request is a different user, and the rate limit cannot follow a person. Require sign-in, as above. - Proxies. Check from outside that a reverse proxy does not buffer
text/event-stream. - Several instances. A hub connection and its Stop and confirmation requests must reach the same instance.
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.
