Per-user auth, policy & audit for Mastra agents
TL;DR. npm i @agenticcontrolplane/governance, wrap each tool’s execute with governed(...), and bind the end user’s identity with withContext. Every wrapped Mastra tool call then gets per-user identity, a policy check (allow / deny / redact), PII detection and an audit trail.
Mastra is a TypeScript framework for building agents, with tools, workflows and multi-provider model routing. A typical production deployment shares one backend API key across every end user’s request. That means no per-user policy, no per-user audit trail, and no way to tell downstream systems which human triggered which action.
@agenticcontrolplane/governance closes that gap. Wrap each tool’s execute callback with governed(...), and bind the end user’s identity per request with withContext.
It uses the same /govern/tool-use endpoint and the same workspace policies as Claude Code. Two things differ. An ask comes back to the model as a denied tool call, so you approve it on the console and re-run. And the shell-command safety floor applies only to tools that carry a shell command.
Starter · 5-minute install. No framework-specific adapter is needed. The base
governed()from@agenticcontrolplane/governanceworks with Mastra’screateTool(). See the runnable starter, how a call is decided, or the frameworks index.
Install
npm install @agenticcontrolplane/governance @mastra/core zod
Minimal policy-enforced agent
import { Mastra } from "@mastra/core";
import { Agent } from "@mastra/core/agent";
import { createTool } from "@mastra/core/tools";
import { z } from "zod";
import {
configure,
governed,
withContext,
} from "@agenticcontrolplane/governance";
configure({ baseUrl: "https://api.agenticcontrolplane.com" });
// Wrap the execute callback with governed(name, fn). Mastra calls the
// wrapped version transparently; governance runs on every dispatch.
const lookupRecord = createTool({
id: "lookup_record",
description: "Look up a record by ID.",
inputSchema: z.object({ id: z.string() }),
outputSchema: z.object({ id: z.string(), data: z.any() }),
execute: governed("lookup_record", async ({ context }) => {
return { id: context.id, data: await db.records.findOne({ id: context.id }) };
}),
});
const agent = new Agent({
id: "my-mastra-agent",
name: "My Mastra Agent",
instructions: "You are an ACP-governed agent. Use the tools available.",
model: "openai/gpt-4o-mini",
tools: { lookupRecord },
});
const mastra = new Mastra({ agents: { agent } });
app.post("/run", async (req, res) => {
const userToken = req.header("authorization")!.replace(/^Bearer /, "").trim();
await withContext(
{ userToken, agentName: "my-mastra-agent", agentTier: "interactive" },
async () => {
const result = await mastra.getAgentById("my-mastra-agent")!.generate(req.body.prompt);
res.json({ result: result.text });
},
);
});
What governed does
It wraps any async function with ACP’s before and after checks:
- POSTs to
/govern/tool-usewith the tool name, the input, and the user JWT bound bywithContext. - If ACP denies, returns
"tool_error: <reason>". The model sees this as a tool result and adapts. Anaskis handled the same way. - If ACP allows, runs your function.
- POSTs the output to
/govern/tool-outputfor audit logging and PII scanning. - If ACP redacts, replaces the output with the redacted version.
- If ACP blocks the output after the fact (a leaked secret pattern, for example), returns
"tool_error: <reason>".
Mastra’s createTool({...execute}) receives the wrapped function, so Mastra doesn’t know the check is there.
If the gateway is down
If the gateway is unreachable or times out, the wrapped tool goes ahead with reason fail-open (<cause>). An [ACP] UNGOVERNED warning is printed once per cause, and the call is written to the lapse log. An outage won’t stop your agent, but calls made during it are not checked.
Per-tier policy
withContext binds an agentTier to the request scope:
interactive: a human at the keyboard, permissive default.subagent: invoked by another agent, no human in the immediate loop.background: autonomous, with no human anywhere. The most restrictive.api: a programmatic call from your backend.
A destructive tool denied in background can be allowed in interactive. Match the tier to how the agent is actually deployed.
Mastra-specific notes
- No ACP adapter for Mastra. The base
@agenticcontrolplane/governancepackage works with Mastra directly, so there is noacp-mastrashim. - Mastra’s
requireApproval: trueon a tool gates it with a stream-level approval event. That is separate from ACP. Use it for a human check on sensitive tools, alongside per-call ACP policy. - Mastra processors (
inputProcessors/outputProcessors) handle guardrails on message content: PII detection, prompt-injection scanning, moderation. They sit next to tool-layer control and don’t replace it. @mastra/core1.28 has no tool-dispatch middleware. Wrappingexecuteinline withgovernedis the documented way to add per-tool control.
Adding more tools
const sendEmail = createTool({
id: "send_email",
description: "Send an email.",
inputSchema: z.object({
to: z.string(),
subject: z.string(),
body: z.string(),
}),
execute: governed("send_email", async ({ context }) => {
return await mailer.send({ to: context.to, subject: context.subject, body: context.body });
}),
});
const agent = new Agent({
...,
tools: { lookupRecord, sendEmail },
});
Wrap each execute with governed("..."). A tool that isn’t wrapped is not checked.
Price and meter the model calls
governed covers what your agent does. The proxy covers what it spends. Both run against the same gateway, and init() sets them up together:
import { init } from "@agenticcontrolplane/governance";
init(); // call before you construct any model client
Model calls now land on the same trail as tool calls, with cost, tokens and cache data. If you build clients yourself, pass the options instead of calling init():
import { modelClientOptions } from "@agenticcontrolplane/governance";
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic(modelClientOptions("anthropic"));
The shapes are "anthropic", "openai" (chat completions) and "openai-responses". The last two are not interchangeable: /v1 serves chat completions and /openai/v1 serves responses.
init() handles each provider as all or nothing. It sets the base URL and the key, or it leaves that provider alone and tells you which one it skipped. If OPENAI_BASE_URL already points at your own gateway, ACP won’t reroute you.
Your coverage: tool calls (wrapped tools) and model calls (proxy).
Limitations
- Only tools wrapped with
governedare covered. A plainexecutecallback is not checked. - Tools and model calls are wired separately.
governedcovers tool calls and the proxy covers model calls. Each is its own edit, see Price and meter the model calls above. Wrapping tools without repointing the model client gives you control with no cost data. - Pre-release.
@agenticcontrolplane/governanceis on 0.x. Pin exact versions.