MentorAgent

← All articles

AI in Software Architecture · Part 1

Let an agent call your layered services with MentorAgent

Keep the rules in the business layer, put the agent at the edge, and test the whole path without a model.

MentorAgent team · 7 min read· Leggi in italiano

MentorAgent cover: the title Actions on a layered app, in the AI in Software Architecture series; a stack of three layers (Shop.Web, Shop.Business, Shop.Data) with an Agent box attached to the top layer only.
In this article

In AI in a Layered Architecture (external site) the model sat at the bottom of the shop, and the business layer decided when to call it. This how-to goes the other way. A customer types "cancel my last order", and an agent calls your business layer.

The rules stay where they are. The agent is one more way in, next to the HTTP endpoint and the nightly import, and the arrows of the layers do not change. You will add three actions to the order service of that article, two reads and a cancellation that asks the customer first, and test them without a model.

A layered shop has presentation, business and data. Presentation calls business, business calls data, and nothing points back. An agent that calls your services is a new kind of presentation: it receives a request, turns it into a call and shows the result. So MentorAgent goes where presentation goes:

  • Shop.Business has no MentorAgent package. OrderService keeps every rule.
  • Shop.Web holds a small class of actions, the registration and the chat endpoint.

The cancellation is a rule of the shop, so it lives in OrderService. It refuses what the shop forbids: an order that is not the customer's, one that has shipped, one past the window, one whose refund fails.

C#
// Shop.Business: the rules of the shop. It knows nothing about HTTP, SQL, chats or agents
public sealed class OrderService(IOrderRepository orders, IUnitOfWork unitOfWork, IPaymentClient payments, TimeProvider clock)
{
    public async Task<CancelOrderResult> CancelAsync(Guid customerId, Guid orderId, CancellationToken cancellationToken)
    {
        var order = await orders.FindAsync(orderId, cancellationToken);
        if (order is null || order.CustomerId != customerId)
            return CancelOrderResult.Refused("Order not found");

        if (order.Status != OrderStatus.Placed)
            return CancelOrderResult.Refused($"The order is already {order.Status.ToString().ToLowerInvariant()}");

        if (clock.GetUtcNow().UtcDateTime - order.CreatedAt > CancelWindow)
            return CancelOrderResult.Refused("The cancellation window has closed");

        if (!await payments.RefundAsync(customerId, order.Total, cancellationToken))
            return CancelOrderResult.Refused("The refund was declined, so the order was not cancelled");

        order.Status = OrderStatus.Cancelled;
        await unitOfWork.SaveChangesAsync(cancellationToken);
        return CancelOrderResult.Cancelled();
    }
}

Another customer's order gets the same answer as one that does not exist, so nobody can use the agent to probe ids. The 24-hour window is an example value. The service also has ListRecentAsync, which never returns more than 20 orders, and GetAsync, in the same style.

Step 2: the actions, a thin class at the edge

Section titled “Step 2: the actions, a thin class at the edge”

The actions live in Shop.Web. Each method hands one call to the service and adds nothing.

C#
// The agent at the edge: a thin class in the presentation project. Each method hands one call to OrderService
public sealed class ShopActions(OrderService orders, ICurrentCustomer customer)
{
    [MentorAction(Description = "Lists the signed-in customer's most recent orders, newest first, with date, total and status", ReadOnly = true)]
    public Task<IReadOnlyList<OrderSummary>> ListMyOrdersAsync(
        [Description("How many orders to list, at most 20")] int count,
        CancellationToken cancellationToken) =>
        orders.ListRecentAsync(customer.RequireId(), count, cancellationToken);

    [MentorAction(Description = "Cancels an order of the signed-in customer and refunds it, if the shop's rules still allow it", RequiresConfirmation = true)]
    public Task<CancelOrderResult> CancelOrderAsync(
        [Description("The id of the order, as listed by list_my_orders")] Guid orderId,
        CancellationToken cancellationToken) =>
        orders.CancelAsync(customer.RequireId(), orderId, cancellationToken);
}

The code has a third action, GetOrderAsync, written like the first. What each part does:

  • The tool name comes from the method: ListMyOrdersAsync is list_my_orders, and CancelOrderAsync is cancel_order.
  • ReadOnly = true lets the agent call the read without asking.
  • RequiresConfirmation = true stops the call before the cancellation runs. MentorAgent sends your client a confirmation request with the description and the arguments, and the method runs only after the customer approves it on POST /mentor/approve. A [MentorAction] that is not read-only asks by default; writing it puts the rule in the code.
  • [Description] is what the model reads to choose a tool. Write what it does and what it returns.
  • The model fills count and orderId. It fills no customer and no token: they are not parameters.

Why a separate class? The attributes could go on OrderService itself, and the docs allow it. But [MentorAction] comes from a MentorAgent package, so Shop.Business would reference it and the layer would know the agent. The class at the edge keeps the dependency rule, and lets you choose exactly what the agent sees. The container creates the class, so register it as any service.

Step 3: the customer, from the sign-in, never from the model

Section titled “Step 3: the customer, from the sign-in, never from the model”

An order id is not an identity. The customer comes from the sign-in of the connection or of the request:

C#
// Who is signed in. The agent never decides this: the id comes from the token, not from the model
public interface ICurrentCustomer
{
    Guid? Id { get; }
}

public sealed class SignedInCustomer(MentorServerUserContext hubUser, IHttpContextAccessor http) : ICurrentCustomer
{
    public Guid? Id
    {
        get
        {
            var user = hubUser.User ?? http.HttpContext?.User;
            var id = user?.FindFirstValue("oid") ?? user?.FindFirstValue("sub") ?? user?.FindFirstValue(ClaimTypes.NameIdentifier);
            return Guid.TryParse(id, out var customerId) ? customerId : null;
        }
    }
}

The SignalR hub keeps the user of each connection in MentorServerUserContext, and a request to /mentor/chat has it in HttpContext. Both come with AddMentorAgentServer(). Do not rely on IHttpContextAccessor alone: over the hub's long polling transport it found nobody in our tests. RequireId() throws when nobody is signed in, so the service is never called without a customer. With JwtBearer, keep the claim names as they arrive (MapInboundClaims set to false), or the handler renames them.

Install the packages: Novior.MentorAgent, Novior.MentorAgent.Server and the package of your model provider. The server gives your client the hub and /mentor/chat.

C#
builder.Services.AddShop();

builder.Services.AddMentorAgent(options =>
{
    options.AppName = "Shop";
    options.AppDescription = "An online shop: customers ask about their orders and cancel them";
    options.ScanAssemblies = [typeof(ShopActions).Assembly];
    options.ChatClient = new OpenAIClient(
            new ApiKeyCredential(builder.Configuration["Ai:ApiKey"]!),                          // from user secrets or a vault, never from the source
            new OpenAIClientOptions { Endpoint = new Uri(builder.Configuration["Ai:Endpoint"]!) })
        .GetChatClient(builder.Configuration["Ai:Model"]!)
        .AsIChatClient();
});
builder.Services.AddMentorAgentServer();

app.RefuseChatOverGet();

// The chat endpoints answer signed-in customers only
app.MapMentorAgentServer(configureTransports: endpoints => endpoints.RequireAuthorization());

AddShop is the registration of the shop without the agent: the lower layers, OrderService, ICurrentCustomer and ShopActions. ScanAssemblies tells MentorAgent where to look for actions. The endpoints are open until you protect them, which is the last line.

RefuseChatOverGet matters when customers sign in with a cookie. /mentor/chat answers GET too. Since 1.3.0 it refuses a request that another site starts in the browser, but MentorAgent checks no antiforgery token, and a browser without Fetch Metadata is not covered, so it is still safer to accept only the requests your client really sends. Your client posts JSON, so the app refuses the GET:

C#
public static IApplicationBuilder RefuseChatOverGet(this IApplicationBuilder app) =>
    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);
    });

With bearer tokens alone the browser attaches nothing by itself, and the middleware costs nothing.

The whole path runs with the real MentorAgent pipeline and the real rules. Only the model is a stand-in, ScriptedModel, a small IChatClient in the code: it asks for one tool, then answers. No call leaves your machine.

First, a check that the agent offers exactly what you meant. IMentorActionCatalog lists the actions as MentorAgent sees them:

C#
[Test]
public async Task TheAgentOffersExactlyTheThreeActions_AndOnlyTheWriteAsksForConfirmation()
{
    // Arrange
    await using var app = new App("list_my_orders");

    // Act
    var actions = app.Host.Services.GetRequiredService<IMentorActionCatalog>().GetActions();

    // Assert
    Assert.That(actions.Select(a => a.ToolName), Is.EquivalentTo(new[] { "list_my_orders", "get_order", "cancel_order" }));
    Assert.That(actions.Single(a => a.ToolName == "cancel_order").RequiresConfirmation, Is.True);
}

Then the case that matters: the model names an order that is not the customer's, and the customer even confirms.

C#
[Test]
public async Task ConfirmingAnOrderOfAnotherCustomer_ChangesNothing()
{
    // Arrange: the model names an order that is not Mario's, and Mario even confirms
    await using var app = new App("cancel_order");
    var theirs = app.GivenAnOrder(Guid.NewGuid());

    // Act
    var asked = await app.SendAsync("Cancel the order of somebody else", confirm: true);

    // Assert: the call ran, and the rule lives in the service, so the agent cannot get around it
    Assert.That(asked, Has.Count.EqualTo(1));
    Assert.That(theirs.Status, Is.EqualTo(OrderStatus.Placed));
}

To see it fail, we removed the owner check from the service: the service test and this one both turned red. The code also has tests for the confirmation and the refusal, for the fact that the model sees orderId and nothing else, and for OrderService not referencing MentorAgent.

The last tests serve the real hub and /mentor/chat in memory, with a test sign-in, and check who the customer is inside an action:

C#
[TestCase(HttpTransportType.WebSockets)]
[TestCase(HttpTransportType.LongPolling)]
public async Task OverTheHub_TheActionServesTheSignedInCustomerOnly(HttpTransportType transport)
{
    // Arrange: Mario and Luisa have one order each, and Mario signs in to the hub
    var model = ListFiveOrders();
    await using var app = await StartShopAsync(model);
    await using var hub = await ConnectAsMarioAsync(app, transport);

    // Act
    await hub.InvokeAsync("SendMessage", "Show my orders", null);

    // Assert
    Assert.That(model.Results, Has.Some.Contain("12.5"));
    Assert.That(model.Results, Has.None.Contain("99.99"));
}

The same check runs on /mentor/chat, where a GET gets 405. One more test cancels over the hub: the order stays as it is while the request waits, an approval from Luisa gets 403, and Mario's approval cancels it.

  • It does not make a read safe. Whatever an action returns goes to the model. Return small summaries, as OrderSummary does, never entities. Filtering stays in your method, as it does without an agent.
  • It does not know your roles. For staff-only actions, add RequiredRoles. MentorAgent checks them in code, before the confirmation, not in the prompt.
  • It does not tie every confirmation to its customer. On the hub only the customer who asked can answer it. Over /mentor/chat, whoever holds the actionId can: keep the endpoint signed-in, as in Step 4, and keep the id out of your logs. The details are in Secure the endpoints.
  • It does not keep the tool list short. Each action you send, with a one-line description, costs about 25 input tokens in every call. With the tool filter only the matching actions travel: with 50 actions, the input tokens halve (a measurement). The settings are in Fewer tokens, lower cost.

The other half, where the model lives and what happens when it is slow or silent, is in the Medium article (external site).

New to MentorAgent? Start with What is MentorAgent.

Written with the help of AI; code and facts checked by the MentorAgent team.