Skip to content

11. An AI agent ​

Customers want to order by talking to an assistant: "add twelve pears to my order". The assistant is an AI model, and it may misunderstand. Here the shop offers some of its commands and a query as tools over the Model Context Protocol (MCP), which assistants such as Claude or ChatGPT speak. The model proposes; the shop's rules decide, as for any other request: the guard of part 6 still lets a customer touch only their own orders, and a large order waits for the customer's approval.

This part builds on the shop of parts 2 to 7 (the worker, the read models, the reactor and the guard). See AI agents over MCP for every option.

The tools ​

A new process, agent, describes what an agent may call. It declares the tools on the domain by name; it runs no aggregate itself, so each tool names the aggregate the worker runs:

ts
// The same domain by name, with what an agent may call and how it is described to the model.
const shop = domain("shop");
const orderId = { type: "string", description: "The order's ID (the aggregateId Place answered)" };
shop.command("Place").tool({
  description: "Opens a new, empty order for the customer. Its ID is the aggregateId in the answer.",
  aggregate: "order",
  input: { type: "object", properties: { customerId: { type: "string" } }, required: ["customerId"], additionalProperties: false },
});
shop.command("AddItem").tool({
  description: "Adds an item to a draft order. More than 10 of one item need the customer's approval.",
  aggregate: "order",
  aggregateId: "orderId",
  input: {
    type: "object",
    properties: { orderId, sku: { type: "string" }, qty: { type: "integer", minimum: 1 } },
    required: ["orderId", "sku", "qty"],
    additionalProperties: false,
  },
  approval: (i: { qty: number }) => i.qty > 10 && "more than 10 of one item need the customer's approval",
});
shop.command("Submit").tool({
  description: "Submits a draft order with at least one item.",
  aggregate: "order",
  aggregateId: "orderId",
  input: { type: "object", properties: { orderId }, required: ["orderId"], additionalProperties: false },
});
shop.query("GetOrder").tool({
  description: "An order: its customer, status and items.",
  input: { type: "object", properties: { id: orderId }, required: ["id"], additionalProperties: false },
});
py
# The same domain by name, with what an agent may call and how it is described to the model.
shop = domain("shop")
order_id = {"type": "string", "description": "The order's ID (the aggregateId Place answered)"}
shop.command("Place").tool(
    "Opens a new, empty order for the customer. Its ID is the aggregateId in the answer.",
    aggregate="order",
    input={"type": "object", "properties": {"customerId": {"type": "string"}}, "required": ["customerId"], "additionalProperties": False},
)
shop.command("AddItem").tool(
    "Adds an item to a draft order. More than 10 of one item need the customer's approval.",
    aggregate="order",
    aggregate_id="orderId",
    input={
        "type": "object",
        "properties": {"orderId": order_id, "sku": {"type": "string"}, "qty": {"type": "integer", "minimum": 1}},
        "required": ["orderId", "sku", "qty"],
        "additionalProperties": False,
    },
    approval=lambda i: i["qty"] > 10 and "more than 10 of one item need the customer's approval",
)
shop.command("Submit").tool(
    "Submits a draft order with at least one item.",
    aggregate="order",
    aggregate_id="orderId",
    input={"type": "object", "properties": {"orderId": order_id}, "required": ["orderId"], "additionalProperties": False},
)
shop.query("GetOrder").tool(
    "An order: its customer, status and items.",
    input={"type": "object", "properties": {"id": order_id}, "required": ["id"], "additionalProperties": False},
)
rs
// The same domain by name, with what an agent may call and how it is described to the model.
let shop = domain("shop");
let order_id = json!({ "type": "string", "description": "The order's ID (the aggregateId Place answered)" });
shop.command("Place").tool(
    Tool::new(
        "Opens a new, empty order for the customer. Its ID is the aggregateId in the answer.",
    )
    .aggregate("order")
    .input(
        json!({ "type": "object", "properties": { "customerId": { "type": "string" } },
                       "required": ["customerId"], "additionalProperties": false }),
    ),
);
shop.command("AddItem").tool(
    Tool::new("Adds an item to a draft order. More than 10 of one item need the customer's approval.")
        .aggregate("order")
        .aggregate_id_field("orderId")
        .input(json!({ "type": "object",
                       "properties": { "orderId": order_id, "sku": { "type": "string" }, "qty": { "type": "integer", "minimum": 1 } },
                       "required": ["orderId", "sku", "qty"], "additionalProperties": false }))
        .approval(|i| {
            (i["qty"].as_f64() > Some(10.0))
                .then(|| "more than 10 of one item need the customer's approval".to_owned())
        }),
);
shop.command("Submit").tool(
    Tool::new("Submits a draft order with at least one item.")
        .aggregate("order")
        .aggregate_id_field("orderId")
        .input(
            json!({ "type": "object", "properties": { "orderId": order_id },
                       "required": ["orderId"], "additionalProperties": false }),
        ),
);
shop.query("GetOrder").tool(
    Tool::new("An order: its customer, status and items.").input(json!({ "type": "object",
        "properties": { "id": order_id }, "required": ["id"], "additionalProperties": false })),
);
go
// The same domain by name, with what an agent may call and how it is described to the model.
shop := kernable.NewDomain("shop")
orderID := map[string]any{"type": "string", "description": "The order's ID (the aggregateId Place answered)"}
shop.Command("Place").Tool(kernable.ToolOptions{
	Description: "Opens a new, empty order for the customer. Its ID is the aggregateId in the answer.",
	Aggregate:   "order",
	Input: map[string]any{"type": "object", "properties": map[string]any{"customerId": map[string]any{"type": "string"}},
		"required": []any{"customerId"}, "additionalProperties": false},
})
shop.Command("AddItem").Tool(kernable.ToolOptions{
	Description:      "Adds an item to a draft order. More than 10 of one item need the customer's approval.",
	Aggregate:        "order",
	AggregateIDField: "orderId",
	Input: map[string]any{"type": "object", "properties": map[string]any{
		"orderId": orderID, "sku": map[string]any{"type": "string"}, "qty": map[string]any{"type": "integer", "minimum": 1},
	}, "required": []any{"orderId", "sku", "qty"}, "additionalProperties": false},
	Approval: func(i map[string]any) string {
		if i["qty"].(float64) > 10 {
			return "more than 10 of one item need the customer's approval"
		}
		return ""
	},
})
shop.Command("Submit").Tool(kernable.ToolOptions{
	Description:      "Submits a draft order with at least one item.",
	Aggregate:        "order",
	AggregateIDField: "orderId",
	Input: map[string]any{"type": "object", "properties": map[string]any{"orderId": orderID},
		"required": []any{"orderId"}, "additionalProperties": false},
})
shop.Query("GetOrder").Tool(kernable.ToolOptions{
	Description: "An order: its customer, status and items.",
	Input: map[string]any{"type": "object", "properties": map[string]any{"id": orderID},
		"required": []any{"id"}, "additionalProperties": false},
})

Only these four are offered from the shop: the model never sees Register, Erase or the passwords. The SDK adds the kernel's event and process tools (kernable_GetEvents, ...): the shop's guard does not check them, so the agent process offers them only on 127.0.0.1 and says so when it starts (see AI agents over MCP). Every call is checked against its input schema before it is sent, and every command tool gets a request_id: a model that retries after a timeout sends the same one, and the order changes once.

Serve them ​

The agent process is an app with MCP switched on. Who the customer is comes from the request:

ts
// The person the agent works for, from its request: here a bearer token that is the customer's
// ID. Use your real sign-in instead.
const kernable = new Kernable();
await kernable.app({
  service: "shop-agent",
  domains: [shop],
  mcp: {
    enabled: true,
    authenticate: (req) => {
      const customer = req.headers.authorization?.replace(/^Bearer /, "");
      return customer ? { senderIdentity: customer } : undefined;
    },
  },
}).run();
py
# The person the agent works for, from its request: here a bearer token that is the customer's
# ID. Use your real sign-in instead.
def who(request):
    customer = (request.headers.get("authorization") or "").removeprefix("Bearer ")
    return RequestContext(sender_identity=customer) if customer else None


k = Kernable()
k.app(service="shop-agent", domains=[shop], mcp=Mcp(enabled=True, authenticate=who)).run()
rs
// The person the agent works for, from its request: here a bearer token that is the
// customer's ID. Use your real sign-in instead.
let kernable = Kernable::new(Options::default())?;
let mcp = Mcp::new().enabled(true).authenticate(|request| {
    let customer = request
        .headers
        .get("authorization")?
        .strip_prefix("Bearer ")?;
    Some(RequestContext {
        sender_identity: customer.to_owned(),
        ..RequestContext::default()
    })
});
let app = kernable.app(App::new().service("shop-agent").domain(&shop).mcp(mcp))?;
app.run().await?;
go
// The person the agent works for, from its request: here a bearer token that is the customer's
// ID. Use your real sign-in instead.
client, err := kernable.New(kernable.Options{})
if err != nil {
	log.Fatal(err)
}
app, err := client.App(kernable.AppOptions{Service: "shop-agent", Domains: []*kernable.Domain{shop}, MCP: &kernable.MCPOptions{
	Enabled: true,
	Authenticate: func(r *http.Request) (*kernable.RequestContext, error) {
		customer := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
		if customer == "" {
			return nil, nil
		}
		return &kernable.RequestContext{SenderIdentity: customer}, nil
	},
}})
if err != nil {
	log.Fatal(err)
}
log.Fatal(app.Run(context.Background()))

Start it beside the shop's other processes. It serves at http://127.0.0.1:7700/mcp; KERNABLE_MCP switches it off or elsewhere without a code change (KERNABLE_MCP=off, KERNABLE_MCP=http:7800). Every call is a normal command or query of the shop, signed with the agent process's key, with the customer as senderIdentity and the client in the attributes (mcp.client, mcp.tool): the guard decides, and the log records who did what.

An agent orders ​

An AI client sends what this script sends: JSON-RPC over HTTP. It works for customer c1:

ts
// The agent works for c1: its requests carry c1's token.
let id = 0;
const mcp = async (method: string, params: object, customer = "c1") => {
  const res = await fetch(MCP, {
    method: "POST",
    headers: { "content-type": "application/json", authorization: `Bearer ${customer}` },
    body: JSON.stringify({ jsonrpc: "2.0", id: ++id, method, params }),
  });
  return (await res.json()).result;
};
const call = async (name: string, args: object, customer?: string) => {
  const result = await mcp("tools/call", { name, arguments: args }, customer);
  return result.isError ? result.content[0].text : result.structuredContent;
};

await mcp("initialize", { protocolVersion: "2025-11-25", capabilities: {}, clientInfo: { name: "tutorial-agent", version: "1" } });
const { tools } = await mcp("tools/list", {});
console.log("tools:", tools.map((t: { name: string }) => t.name).join(", "));

const placed = await call("shop_Place", { customerId: "c1", request_id: "r1" });
const orderId = placed.events[0].aggregateId;
console.log("placed", orderId);
console.log("apples:", (await call("shop_AddItem", { orderId, sku: "apple", qty: 2, request_id: "r2" })).committed);
// Retried after a timeout, with the same request_id: still two apples, not four.
await call("shop_AddItem", { orderId, sku: "apple", qty: 2, request_id: "r2" });
const pears = await call("shop_AddItem", { orderId, sku: "pear", qty: 12, request_id: "r3" });
console.log("pears:", pears.state, `(${pears.reason})`);
console.log("wrong input:", await call("shop_AddItem", { orderId, sku: "plum", qty: 0, request_id: "r4" }));
console.log("for c2:", await call("shop_AddItem", { orderId, sku: "fig", qty: 1, request_id: "r5" }, "c2"));

Twelve pears are more than the tool lets the agent order alone. The call answers with an approval ID instead; the customer approves in the shop's own app, and the held command runs, once:

ts
// c1 approves in the shop's own app; the held command then runs, once.
await approve(kernable, pears.approval_id, { note: "yes, 12", context: { senderIdentity: "c1" } });
let status;
do {
  status = await call("mcp_approval", { approval_id: pears.approval_id });
} while (status.state === "approved");
console.log("pears:", status.state, "by", status.decided_by);
console.log(await call("shop_GetOrder", { id: orderId }));
text
tools: shop_Place, shop_AddItem, shop_Submit, shop_GetOrder, kernable_GetEvents, kernable_FindEvents, kernable_GetCase, kernable_ListCases, mcp_approval
placed order-54407fa335688aaa
apples: true
pears: pending (more than 10 of one item need the customer's approval)
wrong input: invalid_input: input.qty: at least 1
for c2: forbidden: AddItem is not allowed for c2
pears: carried_out by c1
{
  id: 'order-54407fa335688aaa',
  customerId: 'c1',
  status: 'draft',
  items: { apple: 2, pear: 12 }
}

The agent's two calls with request_id r2 added two apples once. The wrong quantity never reached the shop, and c2 was refused by the guard, as a person would be.

Connect an assistant ​

An assistant that starts your app itself talks over stdin and stdout instead: in its MCP configuration, run the agent process with KERNABLE_MCP=stdio and pass the customer in mcp.context. Over HTTP, put your real sign-in into authenticate.

Next, see AI agents over MCP for retries, approvals and what the model hears.