DEV Community

Cover image for # BATA – Business Algorithmic Tools Architecture
omrani rafik
omrani rafik

Posted on Edited on

# BATA – Business Algorithmic Tools Architecture

 Nov 26, 2026 · @omrani_rafik_cf8c1d62bad0

Two interaction modes, one business system: rethinking how AI agents plug into enterprise applications.

With the Model Context Protocol (MCP), any business application can be driven by an AI agent. The hard question is no longer how to connect them, but what to expose.

Most teams start by mirroring their REST API: one tool per endpoint, and the agent figures out the rest. This article argues for the opposite approach, which I call BATA – Business Algorithmic Tools Architecture.

  • The human uses a Front-End that calls REST endpoints, one Command or Query at a time. The UI journey is the orchestrator.
  • The AI agent uses an MCP server whose tools trigger BATA procedures: code that chains N Commands and Queries of the same Application layer.
  • Business rules live in the Commands and Queries, never in the procedures. A procedure chains an application scenario exactly as the Front-End would. Nothing more, nothing less.
  • Every procedure response carries a status that tells the agent what to do next. The code drives the AI, not the other way round.

If you know the Backend for Frontend (BFF) pattern, BATA is the same idea with a new consumer: a Backend for Agents.

1. The problem with CRUD-shaped tools

A typical first MCP server looks like this:

  • create_customer
  • get_stock
  • compute_price
  • create_order
  • create_invoice
  • record_payment

Each tool is clean and well documented. Then a user asks: "Prepare an order for Dupont with these items." The agent now has to work out, on its own:

  • in which order to call the tools;
  • what to do when two customers are called Dupont;
  • whether it should check stock before or after pricing;
  • whether create_order is safe to call without asking the user first;
  • what to do if the third call fails after the first two succeeded.

Every one of those decisions is already encoded somewhere in your Front-End and your team's head. With CRUD-shaped tools, you ask a probabilistic model to rediscover them on every conversation. Sometimes it gets them right. In an ERP, "sometimes" is not good enough.

There is also a cost problem. Dozens of fine-grained tools consume context, and every extra tool increases the chance the agent picks the wrong one.

2. Two consumers, two orchestrators

A modern information system has two kinds of consumers:

  • The human, through a Front-End. They need screens, forms and interactive validation, one step at a time.
  • The AI agent, through MCP tools. It has no screen. It needs well-described business capabilities it can select from an intent.

Look at what the Front-End actually does. Each REST endpoint exposes a single Command or Query. The journey — search the customer, check stock, create a draft, confirm — is assembled by the UI, screen after screen. The Front-End is an orchestrator.

The agent needs an orchestrator too. In BATA, that orchestrator is a dedicated procedural layer: each MCP tool triggers a procedure that chains N Commands and Queries from the same Application layer the Front-End uses.

So the two channels deliberately expose different things:

Channel Consumer Exposes Who orchestrates
REST API Front-End (human) Single Commands and Queries The UI journey
MCP server AI agent Complete scenarios (Business Tools) The BATA procedure

Both sit on top of one Application layer and one Domain. Nothing is duplicated below the orchestration line.

[embedded content: BATA · two orchestrators on one Application layer]

The Front-End and the BATA procedure play the same role, each for its own consumer. Business rules stay in the Application layer.

3. The golden rule: business logic lives in Commands and Queries

A second orchestrator raises an obvious fear: won't the business logic end up written twice, once in the Front-End journey and once in the procedure?

It won't, as long as one rule holds:

A BATA procedure chains an application scenario, exactly as the Front-End would. Nothing more, nothing less. It never adds a business rule.

In practice, that means:

  • Prices, discounts, credit limits, commercial conditions and authorization checks live in the Commands, Queries and Domain.
  • Each Command rejects an invalid state on its own, whoever calls it and in whatever order.
  • The procedure only contains what is specific to the agent conversation: the order of steps, missing-information handling, confirmations and guidance messages.

A quick test when reviewing a procedure: if this line of code disappeared, would the Front-End path now behave differently from the agent path? If yes, that line is a business rule and belongs in the Application layer.

Two direct benefits follow:

  1. A business change happens in one place. Change the discount policy in the pricing service, and both the human and the agent get it.
  2. An agent cannot bypass a rule. Even if a procedure has a bug, or a future tool calls Commands in an unexpected order, every Command still enforces its own invariants and permissions.

4. Anatomy of a BATA procedure: the code drives the AI

A BATA procedure rarely completes in a single call. It behaves like a small state machine, and every response tells the agent where it stands:

Status Meaning What the agent does next
NeedsInput Information is missing or ambiguous Ask the user the returned question, then call the tool again
NeedsConfirmation A draft is ready, nothing is committed yet Show the summary to the user, then call again with confirm = true
Completed The scenario is done Report the result
Rejected A Command refused the operation Explain the returned reason, suggest an alternative

This is the core idea of BATA: the agent does not decide the process, it follows it. The agent is good at understanding intent and talking to people. The procedure is good at sequencing. Each does what it is best at.

A procedure therefore encapsulates:

  • the sequence of Commands and Queries;
  • alternative paths (ambiguous customer, partial stock);
  • missing-information handling and confirmations;
  • agent guidance: status, question to ask, next action;
  • a structured, machine-readable result.

It never encapsulates a business rule (see the golden rule above).

5. Implementation in .NET

The snippets below use the official MCP C# SDK (ModelContextProtocol.AspNetCore) and a mediator exposing ISender (MediatR or any equivalent; check MediatR's current licence before choosing it). SDK APIs evolve, so check them against the version you use.

5.1 Solution layout

src/
  Shop.Domain/          entities, aggregates, invariants
  Shop.Application/     Commands, Queries, handlers, authorization
  Shop.Infrastructure/  EF Core, external APIs, messaging
  Shop.Api/             REST endpoints for the Front-End
  Shop.Bata/            BATA procedures (references Shop.Application only)
  Shop.McpServer/       MCP tools wrapping the procedures
tests/
  Shop.Bata.Tests/      procedure tests: no LLM, no MCP
Enter fullscreen mode Exit fullscreen mode

Shop.Bata is the only new piece. It depends on the Application layer and nothing else: no EF Core, no Domain entities, no HTTP.

5.2 A Command carries the business rules

public sealed record CreateDraftOrderCommand(Guid CustomerId, IReadOnlyList<OrderLine> Lines)
    : IRequest<DraftOrderDto>;

internal sealed class CreateDraftOrderHandler(
    IAppDbContext db, IPricingService pricing, ICurrentUser user)
    : IRequestHandler<CreateDraftOrderCommand, DraftOrderDto>
{
    public async Task<DraftOrderDto> Handle(CreateDraftOrderCommand cmd, CancellationToken ct)
    {
        user.EnsureHasPermission(Permissions.CreateOrder);              // authorization

        var customer = await db.Customers.FindAsync([cmd.CustomerId], ct)
            ?? throw new NotFoundException("Customer", cmd.CustomerId);

        var priced = await pricing.PriceAsync(customer, cmd.Lines, ct);   // prices and discounts
        var draft = Order.CreateDraft(customer, priced);                   // invariants: credit limit, terms

        db.Orders.Add(draft);
        await db.SaveChangesAsync(ct);
        return draft.ToDto();
    }
}
Enter fullscreen mode Exit fullscreen mode

The Front-End calls this exact handler through POST /api/orders/drafts. The agent reaches it through a procedure. Same rules, same checks.

5.3 A result that tells the agent what to do

public enum ProcedureStatus { NeedsInput, NeedsConfirmation, Completed, Rejected }

public sealed record ProcedureResult(
    ProcedureStatus Status,
    string Message,
    string NextAction,
    Guid? DraftId = null,
    Guid? EntityId = null)
{
    public static ProcedureResult Ask(string question) => new(
        ProcedureStatus.NeedsInput, question,
        "Ask the user this question, then call the tool again with the answer.");

    public static ProcedureResult Confirm(Guid draftId, string summary) => new(
        ProcedureStatus.NeedsConfirmation, summary,
        "Show this summary to the user. If they agree, call again with draftId and confirm=true.",
        draftId);

    public static ProcedureResult Done(Guid id, string message) => new(
        ProcedureStatus.Completed, message,
        "Tell the user the operation is complete.", EntityId: id);

    public static ProcedureResult Reject(string reason) => new(
        ProcedureStatus.Rejected, reason,
        "Explain the reason to the user and suggest an alternative. Do not retry unchanged.");
}
Enter fullscreen mode Exit fullscreen mode

5.4 The procedure: N Commands and Queries, zero business rules

// Shop.Bata: references Shop.Application only
public sealed record PlaceOrderRequest(
    string Customer, IReadOnlyList<OrderLine> Lines, Guid? DraftId = null, bool Confirm = false);

public sealed class PlaceOrderProcedure(ISender sender)
{
    public async Task<ProcedureResult> ExecuteAsync(PlaceOrderRequest req, CancellationToken ct)
    {
        try
        {
            // 1. Identify the customer
            var customers = await sender.Send(new FindCustomerQuery(req.Customer), ct);
            if (customers.Count == 0)
                return ProcedureResult.Ask(
                    $"No customer matches \"{req.Customer}\". Can you give the exact name or customer number?");
            if (customers.Count > 1)
                return ProcedureResult.Ask(
                    $"{customers.Count} customers match: {string.Join(", ", customers.Select(c => c.DisplayName))}. Which one?");
            var customer = customers[0];

            // 2. Check availability
            var availability = await sender.Send(new CheckAvailabilityQuery(req.Lines), ct);
            if (availability.Missing.Count > 0)
                return ProcedureResult.Ask(
                    $"Not enough stock for {string.Join(", ", availability.Missing)}. Reduce the quantities or remove these items?");

            // 3. Create a draft: the Command prices it and checks commercial conditions
            if (req.DraftId is null)
            {
                var draft = await sender.Send(new CreateDraftOrderCommand(customer.Id, req.Lines), ct);
                return ProcedureResult.Confirm(draft.Id, draft.Summary);
            }

            // 4. Commit only after explicit confirmation
            if (!req.Confirm)
                return ProcedureResult.Confirm(req.DraftId.Value, "The draft is waiting for confirmation.");

            var order = await sender.Send(new ConfirmOrderCommand(req.DraftId.Value), ct);
            return ProcedureResult.Done(order.Id, $"Order {order.Number} confirmed.");
        }
        catch (BusinessRuleException ex)
        {
            return ProcedureResult.Reject(ex.Message);   // e.g. credit limit exceeded
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Read it again with the golden rule in mind: there is no price, no discount, no credit check, no permission check. Only sequencing, questions and confirmation.

5.5 The MCP tool is a thin wrapper

[McpServerToolType]
public sealed class OrderTools(PlaceOrderProcedure procedure)
{
    [McpServerTool(Name = "place_order")]
    [Description("Prepares and places a complete customer order: customer lookup, stock check, " +
                 "pricing and confirmation. Always follow the returned Status and NextAction.")]
    public Task<ProcedureResult> PlaceOrder(
        [Description("Customer name or customer number")] string customer,
        [Description("Items and quantities")] IReadOnlyList<OrderLine> lines,
        [Description("Draft id returned by a previous call")] Guid? draftId = null,
        [Description("true only after the user approved the summary")] bool confirm = false,
        CancellationToken ct = default)
        => procedure.ExecuteAsync(new PlaceOrderRequest(customer, lines, draftId, confirm), ct);
}
Enter fullscreen mode Exit fullscreen mode

5.6 Wiring the MCP server

// Shop.McpServer/Program.cs
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddApplication();                          // Commands, Queries, mediator
builder.Services.AddInfrastructure(builder.Configuration);  // EF Core, external services
builder.Services.AddScoped<PlaceOrderProcedure>();

builder.Services
    .AddMcpServer()
    .WithHttpTransport()
    .WithToolsFromAssembly();

var app = builder.Build();
app.MapMcp();
app.Run();
Enter fullscreen mode Exit fullscreen mode

Shop.Api registers the same AddApplication() and AddInfrastructure(). Two hosts, one Application layer.

6. A conversation, call by call

Here is what the exchange looks like from the MCP server's point of view (values are illustrative):

User   > Prepare an order for Dupont: 10 x SKU-123 and 5 x SKU-456.

Agent  → place_order(customer: "Dupont", lines: [...])
Server ← NeedsInput
         "2 customers match: Dupont SA (Lyon), Dupont SARL (Paris). Which one?"

Agent  > Two customers are called Dupont: Dupont SA in Lyon or Dupont SARL in Paris?
User   > Dupont SA.

Agent  → place_order(customer: "Dupont SA", lines: [...])
Server ← NeedsConfirmation, draftId: 7f3c…
         "15 items, 1,240.00 EUR excl. VAT, delivery on 3 Dec."

Agent  > Here is the order: 15 items, 1,240.00 EUR excl. VAT, delivered on 3 Dec. Shall I confirm it?
User   > Yes.

Agent  → place_order(customer: "Dupont SA", lines: [...], draftId: 7f3c…, confirm: true)
Server ← Completed
         "Order SO-2026-0412 confirmed."
Enter fullscreen mode Exit fullscreen mode

Three tool calls, one tool. The agent never had to know that a draft exists, that pricing happens in the draft Command, or that confirmation is mandatory. It just followed Status and NextAction.

Notice that the third call re-runs the customer and stock checks. That is deliberate: stock may have changed while the user was reading the summary, and the Commands re-validate everything anyway.

7. Production concerns

Human confirmation. No irreversible write without explicit user approval. The procedure returns NeedsConfirmation with a summary and commits only on a second call with confirm = true. Many MCP clients also ask the user before running a tool; treat that as an extra layer, not a replacement.

State lives in the system, not in the agent. Between calls, the state is a persisted draft identified by draftId. The agent's memory can be truncated or summarized; the draft cannot. When the client supports it, MCP elicitation also lets the server ask the user for missing information directly.

Idempotency. Agents retry after timeouts. Make ConfirmOrderCommand idempotent on the draft: confirming the same draft twice returns the same order instead of creating a second one.

Authorization. The MCP server acts on behalf of the authenticated user (OAuth on the MCP transport), never with an all-powerful service account. Permissions are checked inside each Command and Query, exactly as for the REST API. A procedure can never become a back door.

Transactions. A procedure that chains several writes must handle failure halfway through. Drafts help: until confirmed, they commit nothing important. When several writes must be atomic, either share a Unit of Work across the procedure or add a composite Command to the Application layer. Across services, use compensation (saga).

Errors the agent can use. A Rejected result carries the rule that failed and a sentence a human can read ("credit limit exceeded by 1,200 EUR"), not a stack trace. The agent can then explain it and propose an alternative.

Observability. Log every procedure step with a correlation id tied to the MCP session. When a user asks "why did the agent do that?", you can replay the exact sequence of Commands and Queries.

8. Choosing the right granularity

Too fine, and the agent rebuilds the process again. Too coarse, and the tool becomes rigid: the agent cannot handle cases the procedure never anticipated. Three guidelines work well in practice:

  • Action procedures for high-value scenarios with many steps or rules: place an order, issue a credit note, close a case.
  • Consultation procedures, read-only, that aggregate several Queries into one useful answer: a customer's situation, an order's status, an item's stock across warehouses.
  • No Command exposed directly to the agent. Every write goes through a procedure that owns its confirmations.

Aim for a small catalogue of well-described tools. Name them after what a business user would ask for (place_order), not after your tables (insert_order_row). Write each tool description for the agent: what the tool does, when to use it, and that it must follow NextAction.

9. Testing procedures without an LLM

Because a procedure only talks to ISender, you can test every path with a substitute: no model, no MCP client, no database. The examples use xUnit and NSubstitute.

public class PlaceOrderProcedureTests
{
    private readonly ISender _sender = Substitute.For<ISender>();
    private static readonly OrderLine[] Lines = [new("SKU-123", 10)];

    [Fact]
    public async Task Asks_which_customer_when_the_name_is_ambiguous()
    {
        _sender.Send(Arg.Any<FindCustomerQuery>(), Arg.Any<CancellationToken>())
               .Returns(Task.FromResult<IReadOnlyList<CustomerDto>>(
               [
                   new(Guid.NewGuid(), "Dupont SA (Lyon)"),
                   new(Guid.NewGuid(), "Dupont SARL (Paris)")
               ]));

        var result = await new PlaceOrderProcedure(_sender)
            .ExecuteAsync(new PlaceOrderRequest("Dupont", Lines), CancellationToken.None);

        Assert.Equal(ProcedureStatus.NeedsInput, result.Status);
        await _sender.DidNotReceive()
            .Send(Arg.Any<CreateDraftOrderCommand>(), Arg.Any<CancellationToken>());
    }

    [Fact]
    public async Task Never_confirms_without_explicit_consent()
    {
        _sender.Send(Arg.Any<FindCustomerQuery>(), Arg.Any<CancellationToken>())
               .Returns(Task.FromResult<IReadOnlyList<CustomerDto>>(
                   [new(Guid.NewGuid(), "Dupont SA (Lyon)")]));
        _sender.Send(Arg.Any<CheckAvailabilityQuery>(), Arg.Any<CancellationToken>())
               .Returns(Task.FromResult(new AvailabilityDto(Missing: [])));

        var request = new PlaceOrderRequest("Dupont SA", Lines, DraftId: Guid.NewGuid(), Confirm: false);
        var result = await new PlaceOrderProcedure(_sender).ExecuteAsync(request, CancellationToken.None);

        Assert.Equal(ProcedureStatus.NeedsConfirmation, result.Status);
        await _sender.DidNotReceive()
            .Send(Arg.Any<ConfirmOrderCommand>(), Arg.Any<CancellationToken>());
    }
}
Enter fullscreen mode Exit fullscreen mode

These tests document the scenario better than any prompt could, and they run in milliseconds in CI. The business rules themselves are tested where they live, in the Application and Domain test projects.

10. Trade-offs and when not to use BATA

BATA is not free, and it is not always the right call.

  • You write and maintain procedures. Each scenario the agent should handle needs code. That is the point (predictability), but it is also work.
  • Unanticipated requests fall through. If a user asks for something no procedure covers, the agent can only answer with consultation tools or say it cannot do it. For exploratory, read-only use cases, finer-grained query tools may serve users better.
  • The discipline must hold. The day someone puts a discount rule in a procedure "just for the agent", the two channels start to diverge. Code reviews and the test from section 3 are your safety net.
  • Small or internal tools may not need it. For a prototype or a single-user internal tool, exposing a few Queries directly is often enough.

BATA pays off where correctness matters more than flexibility: ERPs, finance, logistics, anything where a wrong write has a cost.

Conclusion

Instead of handing agents dozens of technical functions and hoping they rebuild our processes, we can hand them our processes directly, as code we own, test and review.

The responsibilities split cleanly:

  • The AI understands the intent, talks to the user and picks the right Business Tool.
  • BATA chains the application scenario and guides the agent with a status and a next action.
  • The Application layer carries the business rules, for the human and the agent alike.
  • The Domain guarantees consistency.

One business system, two access paths, each shaped for its consumer.

The Front-End guides the human. BATA guides the AI. The Application layer owns the business.

How do you expose your systems to AI agents today: technical functions or business procedures? I'd love to hear how others are approaching this in the comments.

Top comments (0)