Skip to content

AI agents over MCP ​

AI agents (Claude, ChatGPT, agent frameworks) call tools over the Model Context Protocol (MCP). Your app can offer some of its commands and queries as such tools: the agent proposes an action, and kernable runs it as an ordinary command, through your grants, middleware and business rules, recorded and signed. The model may be wrong; your rules still hold.

MCP is built into the SDK and off until you switch it on. There is one endpoint, in your app; the kernel, its CLI and its UI have none. Once it is on, the app offers:

ToolsWithout the kitWith the kit
your commands and queries described as toolsyesyes, checked per person by the kit's middleware
the kernel's events and process cases (kernable_…)on stdio and on 127.0.0.1 only, checked by nobodyyes, checked per person
the kit's reads (members, groups, invitations, tenant, Explain)—yes
the kit's writes that change who may do what—only once allowed (allow)

Never tools: sign-in, sessions, passwords, keys, SSO, the vault's values, and any command or query nobody described.

Describe the tools ​

Describe each command or query for the model: what it does, and its input as a JSON Schema.

ts
const shop = domain("shop");
shop.aggregate("order", { placed: false }).command("Place", (s, data: { sku: string; qty: number; euros: number }) => {
  if (data.euros > 5000) throw new Rejected("orders over €5,000 are not allowed", "limit_exceeded");
  return [{ type: "OrderPlaced", data }];
});

shop.command("Place").tool({
  description: "Orders material from the supplier. Up to €1,000 at once, up to €5,000 with a person's approval.",
  input: {
    type: "object",
    properties: { sku: { type: "string" }, qty: { type: "integer", minimum: 1 }, euros: { type: "number", minimum: 0 } },
    required: ["sku", "qty", "euros"],
    additionalProperties: false,
  },
  approval: (i: { euros: number }) => i.euros > 1000 && i.euros <= 5000 && "orders over €1,000 need a person's approval",
});
shop.query("ListOrders").tool({ description: "The orders placed so far" });
python
shop = domain("shop")

def place(state, data):
    if data["euros"] > 5000:
        raise Rejected("orders over €5,000 are not allowed", "limit_exceeded")
    return [{"type": "OrderPlaced", "data": data}]

shop.aggregate("order", {"placed": False}).command("Place", place)

shop.command("Place").tool(
    "Orders material from the supplier. Up to €1,000 at once, up to €5,000 with a person's approval.",
    input={
        "type": "object",
        "properties": {"sku": {"type": "string"}, "qty": {"type": "integer", "minimum": 1}, "euros": {"type": "number", "minimum": 0}},
        "required": ["sku", "qty", "euros"],
        "additionalProperties": False,
    },
    approval=lambda i: 1000 < i["euros"] <= 5000 and "orders over €1,000 need a person's approval",
)
shop.query("ListOrders").tool("The orders placed so far")
go
shop := kernable.NewDomain("shop")
order := kernable.NewAggregate(shop, "order", struct{}{})
kernable.Handle(order, "Place", func(_ *kernable.CommandContext, _ struct{}, d Place) ([]kernable.NewEvent, error) {
	if d.Euros > 5000 {
		return nil, kernable.Reject("limit_exceeded", "orders over €5,000 are not allowed")
	}
	return kernable.Events(kernable.Event("OrderPlaced", d)), nil
})

shop.Command("Place").Tool(kernable.ToolOptions{
	Description: "Orders material from the supplier. Up to €1,000 at once, up to €5,000 with a person's approval.",
	Input: map[string]any{
		"type": "object",
		"properties": map[string]any{
			"sku":   map[string]any{"type": "string"},
			"qty":   map[string]any{"type": "integer", "minimum": 1},
			"euros": map[string]any{"type": "number", "minimum": 0},
		},
		"required":             []any{"sku", "qty", "euros"},
		"additionalProperties": false,
	},
	Approval: func(i map[string]any) string {
		if e := i["euros"].(float64); e > 1000 && e <= 5000 {
			return "orders over €1,000 need a person's approval"
		}
		return ""
	},
})
shop.Query("ListOrders").Tool(kernable.ToolOptions{Description: "The orders placed so far"})
rust
let shop = domain("shop");
shop.aggregate("order", json!({})).command("Place", |_, data: Value, _, _| {
    if data["euros"].as_f64() > Some(5000.0) {
        return Err(Rejected::new("orders over €5,000 are not allowed").code("limit_exceeded"));
    }
    Ok(vec![NewEvent::new("OrderPlaced", data)])
});

shop.command("Place").tool(
    Tool::new("Orders material from the supplier. Up to €1,000 at once, up to €5,000 with a person's approval.")
        .input(json!({
            "type": "object",
            "properties": { "sku": { "type": "string" }, "qty": { "type": "integer", "minimum": 1 }, "euros": { "type": "number", "minimum": 0 } },
            "required": ["sku", "qty", "euros"],
            "additionalProperties": false,
        }))
        .approval(|i| {
            let euros = i["euros"].as_f64().unwrap_or(0.0);
            (euros > 1000.0 && euros <= 5000.0).then(|| "orders over €1,000 need a person's approval".to_owned())
        }),
);
shop.query("ListOrders").tool(Tool::new("The orders placed so far"));

Command and query classes declare the same as static tool = { … } (TypeScript) or tool = {"description": …} (Python). In Go, the input reaches Approval and AggregateID with numbers as float64; in Rust, as a serde_json::Value. Rust checks pattern only for simple patterns (literal characters, ., classes such as [a-z-] or \d, with *, +, ? or {n,m}, anchored or not); other patterns are passed on to the model unchecked. A tool is named <domain>_<type> (shop_Place) unless you name it (name).

The SDK checks every call against the input schema before anything is sent (type, properties, required, additionalProperties, enum, const, minimum, maximum, minLength, maxLength, pattern, items, minItems, maxItems) and answers the model with what is wrong.

Switch it on ​

ts
await kernable.app({
  service: "shop",
  domains: [shop],
  mcp: {
    enabled: true,
    transport: "http", // or "stdio"
    port: 7700,
    authenticate: async (req) => ({ senderIdentity: await whoIs(req.headers.authorization) }),
  },
}).run();
python
k.app(
    service="shop",
    domains=[shop],
    mcp=Mcp(
        enabled=True,
        transport="http",  # or "stdio"
        port=7700,
        authenticate=lambda request: RequestContext(sender_identity=who_is(request.headers["authorization"])),
    ),
).run()
go
app, err := client.App(kernable.AppOptions{
	Service: "shop",
	Domains: []*kernable.Domain{shop},
	MCP: &kernable.MCPOptions{
		Enabled:   true,
		Transport: "http", // or "stdio"
		Port:      7700,
		Authenticate: func(r *http.Request) (*kernable.RequestContext, error) {
			return &kernable.RequestContext{SenderIdentity: whoIs(r.Header.Get("Authorization"))}, nil
		},
	},
})
rust
let app = kernable.app(
    App::new().service("shop").domain(&shop).mcp(
        Mcp::new()
            .enabled(true)
            .port(7700) // or .stdio()
            .authenticate(|request| who_is(request.headers.get("authorization")?)),
    ),
)?;
app.run().await?;

KERNABLE_MCP overrides the app's setting, so each environment decides without a code change:

KERNABLE_MCP
offno MCP, whatever the app says
onon, as the app configures it
stdioover stdin and stdout: the agent starts your app (Claude Desktop, Claude Code, a CLI agent)
http, http:<port>, http:<host>:<port>Streamable HTTP at http://<host>:<port>/mcp (default 127.0.0.1:7700)

run() serves it alongside the workers and listeners, and the app's overview names it. Over stdio the app stops once the agent closes its input; everything the SDK logs goes to stderr.

An agent that starts your app over stdio, in its MCP configuration:

json
{ "mcpServers": { "shop": { "command": "python", "args": ["app.py"], "env": { "KERNABLE_MCP": "stdio" } } } }

The kernel's events and process cases ​

With MCP on, the SDK adds a read model kernable and four tools on it:

ToolAnswers
kernable_GetEventsone aggregate's history (aggregateType: "shop.order", aggregateId): its events in order, when, and who sent the command behind each
kernable_FindEventsthe tenant's events, newest first, by type (shop.OrderPlaced, shop.*), aggregate type and time
kernable_GetCasewhere a process case stands: its step, what it waits for and until when, an incident, the steps so far, how it ended
kernable_ListCasesa process's cases by key (o1) or state (running, incident, ended, cancelled)

They are queries like any other: the kernel puts them through your middleware, which decides per person. With the kit, a person sees only their tenant, needs a permission for kernable.* (owners have it), and GetEvents carries the aggregate as its target, so relations decide per aggregate. The vault's values never reach the read model: personal fields are null and named in redacted, even when the app's key may read the vault.

Without a middleware nobody checks them: whoever reaches the endpoint reads every event of the tenant. That is the simplest case ("I want to read my events"), so they are on over stdio and on 127.0.0.1, and the app says so at the start. On an endpoint open to the network they stay off unless you allow them (allow: ["kernable"]). The SDK sees a middleware when one of the app's listeners checks * or kernable.* (the kit's does); when yours runs in another service, say so with checked: true.

The read model keeps every event in memory and rebuilds from the first event on every start; the app's key needs listen for every type and answer for kernable.*.

The kit's tools ​

The kit declares its tools; an app that uses the kit offers its reads as soon as MCP is on: identity_ListIdentities, group_ListGroups, group_GetGroup, invitation_ListInvitations, tenancy_GetTenant and group_Explain (whether someone may send a request, and why).

Its writes change who may do what, and a manipulated model (a mail it reads that says "invite attacker@example.com") could use them for an admin. They are offered only once you allow their area:

AreaTools
kit.groupsgroup_CreateGroup, group_UpdateGroup, group_SetPermissions
kit.invitationsinvitation_CreateInvitation (never an owner), invitation_ResendInvitation, invitation_RevokeInvitation
kit.membershipsidentity_SuspendMembership, identity_ResumeMembership, identity_RevokeMembership
ts
mcp: { enabled: true, allow: ["kit.invitations"], authenticate } // or allow: ["kit"] for all three

Your own tools can do the same: area: "crm.admin" on a tool offers it only once the app allows crm.admin (or crm).

The kit's middleware decides every call as for any other request: an agent can do only what the person it works for may do. The list, with each tool's description and input, is kits/fixtures/mcp-tools.json; every kit carries a copy and its tests hold it to the file.

Who acts ​

Every call is a normal command or query, signed with your app's key. Its request context carries:

  • the person: senderIdentity from authenticate (HTTP), or from mcp.context (stdio), so your middleware decides per person as for any other request;
  • the tenant: a call runs in the person's tenant when their context names one (senderTenant, as the kit's sign-in sets it), else in the client's;
  • the agent: attributes["mcp.client"] (the name and version the client gave, e.g. claude-desktop 1.0) and attributes["mcp.tool"]. These are notes for the record, not a security feature: what an agent may do is what your middleware lets the person do.

Over HTTP, authenticate decides who calls: return nothing (or throw) and the request is refused (401). A browser's request must come from an origin you allow (origins); the server listens on 127.0.0.1 unless you say otherwise.

Prompts and model output are not recorded. If you want them in the history, record them as commands of your own.

Once, although models retry ​

A model that gets no answer in time may call the tool again. once decides what a repeated call is:

once
field (default for commands)the input gets a request_id; the model is told to reuse it only when it retries the same request. The same request_id is the same command: it runs once, and the retry gets the first answer
argsthe same arguments on the same day (UTC) are the same command; two equal orders on purpose become one
noneevery call is a new command

Queries never change anything and take no request_id. Side effects outside kernable (a payment, a mail) belong in reactors with fixed command IDs, as always (see Failures).

What the model hears ​

A command that commits answers with its events (vault fields null) and the log position. A refusal is a tool error with your code and message, e.g. limit_exceeded: orders over €5,000 are not allowed, so the model can explain it or change course. A query answers with its data.

A person approves ​

approval holds a call for a person: return a reason (or true) and the command does not run yet. The model gets an approval ID and can ask mcp_approval how it stands; once a person approves it in your application, the command runs, once, as the person the agent worked for: with their tenant, identity, account and session as their call named them, so your middleware decides it as theirs (with the kit: refused if their session ended or their permission went meanwhile). The approver is in attributes["mcp.approved_by"], and the approval records how it went. Each tenant sees only its own approvals.

ts
import { approve, decline } from "@kernable/sdk";

const pending = await kernable.query({ domain: "mcp", type: "ListApprovals", data: { state: "pending" } });
await approve(kernable, id, { note: "ok", context: { senderIdentity: "bob" } });
await decline(kernable, other, { note: "too dear", context: { senderIdentity: "bob" } });
python
from kernable import approve, decline

pending = k.query("mcp", "ListApprovals", {"state": "pending"})
approve(k, id, note="ok", context=RequestContext(sender_identity="bob"))
decline(k, other, note="too dear", context=RequestContext(sender_identity="bob"))
go
pending, err := client.Query(ctx, kernable.Query{Domain: "mcp", Type: "ListApprovals", Data: map[string]any{"state": "pending"}})
bob := &kernable.RequestContext{SenderIdentity: "bob"}
_, err = kernable.Approve(ctx, client, id, kernable.ApprovalOptions{Note: "ok", Context: bob})
_, err = kernable.Decline(ctx, client, other, kernable.ApprovalOptions{Note: "too dear", Context: bob})
rust
use kernable::{ApprovalOptions, approve, decline};

let pending: Vec<Value> = kernable.query(Query::new("mcp", "ListApprovals").data(json!({ "state": "pending" }))).await?;
approve(&kernable, &id, ApprovalOptions::new(bob.clone()).note("ok")).await?;
decline(&kernable, &other, ApprovalOptions::new(bob).note("too dear")).await?;

approval decides before the command runs: hold only what a person may allow, and let what the command refuses anyway run at once, so the model hears the refusal right away.

The approvals are a domain of their own (mcp, see McpOptions.approvals), added to your app when a tool asks for approval: the aggregate approval (Request, Approve, Decline, Finish), the read model mcp-approvals (GetApproval, ListApprovals) and the reactor mcp-runner, which carries out an approved command. The held command's data is kept in the vault and erased once the command ran or was declined. Your middleware decides who may approve (mcp.Approve, mcp.Decline), and the runner records how an approved call went in the approver's name, so whoever may approve also needs mcp.Finish. The people an agent works for need mcp.Request (asking) and mcp.GetApproval (how it stands). The app's key needs the grants for the mcp domain like for its own.

What MCP is not here ​

kernable implements the core of MCP itself, in every SDK, without an MCP library: initialize, ping, tools/list and tools/call over stdio and Streamable HTTP (JSON answers), protocol versions 2025-03-26 to 2025-11-25. Resources, prompts, sampling and OAuth discovery are not part of it: sign-in over HTTP is your authenticate.