Agent capabilities
Agent capabilities expose narrow application actions to authenticated AI agent transports. They are another entrypoint into ordinary Beignet use cases, not a second business-logic layer or an agent orchestration framework.
Beignet owns the transport-neutral definition, validation, application context, execution, tracing, and instrumentation. An integration such as Better Auth Agent Auth owns agent registration, tokens, grants, constraints, and approval.
Define the agent-facing contract
Bind the app context and verified principal types once:
// lib/agent-capabilities.ts
import { createAgentCapabilities } from "@beignet/core/agent-capabilities";
import type { AppContext } from "@/app-context";
export type AgentPrincipal = {
agentId: string;
userId: string;
};
export const { defineAgentCapability, defineAgentCapabilityRegistry } =
createAgentCapabilities<AppContext, AgentPrincipal>();Keep definitions near the feature and delegate behavior to existing use cases. The capability schema may differ from an HTTP contract when an agent needs a curated input or output:
// features/issues/agent-capabilities.ts
import { z } from "zod";
import { createIssueUseCase } from "@/features/issues/use-cases";
import { defineAgentCapability } from "@/lib/agent-capabilities";
export const createIssueCapability = defineAgentCapability("issues.create", {
description: "Create an issue in one workspace.",
input: z.object({
workspaceId: z.string().min(1),
title: z.string().min(1).max(200),
}),
output: z.object({ id: z.string(), title: z.string() }),
async handle({ ctx, input }) {
const { workspaceId: _workspaceId, ...useCaseInput } = input;
return createIssueUseCase.run({ ctx, input: useCaseInput });
},
});Both schemas are runtime boundaries. Arguments are parsed before context construction; handler results are parsed before they reach the transport.
Register and execute capabilities
Compose definitions explicitly and create one executor. The context resolver is the security boundary between a verified transport identity and your application's authorization state:
// server/agent-capabilities.ts
import {
createAgentCapabilityExecutor,
} from "@beignet/core/agent-capabilities";
import { appError } from "@/features/shared/errors";
import { createIssueCapability } from "@/features/issues/agent-capabilities";
import { defineAgentCapabilityRegistry } from "@/lib/agent-capabilities";
export const agentCapabilityRegistry =
defineAgentCapabilityRegistry([createIssueCapability]);
export const agentCapabilityExecutor = createAgentCapabilityExecutor({
registry: agentCapabilityRegistry,
async createContext({ principal, input }) {
const server = await import("@/server").then(({ getServer }) => getServer());
const membership = await server.ports.members.findMembership({
workspaceId: input.workspaceId,
userId: principal.userId,
});
if (!membership) throw appError("NotAWorkspaceMember");
return server.createServiceContext({
asUser: { id: principal.userId, role: membership.role },
tenantId: input.workspaceId,
});
},
});Never accept a tenant role from agent claims. Re-read membership from an
authoritative app port, then use createServiceContext(...) so the server
attaches the same gate and correlation state used by other entrypoints. See
Routes and server.
execute(...) is typed by literal capability name for tests and in-process
callers. Protocol adapters use executeDynamic(...) with an authorize(...)
callback when transport authorization must inspect parsed input. Core invokes
that callback against the exact parsed value before context construction, then
uses the same value for the context and handler.
MCP tools
@beignet/mcp registers an existing capability registry on an MCP SDK server.
It derives tool names, descriptions, and schemas from the definitions and calls
the existing executor for validation, context, business rules, and tracing.
bun add @beignet/mcp @beignet/core @modelcontextprotocol/server@^2.3.1 zodThe integration supports MCP SDK v2 (@modelcontextprotocol/server,
>=2.3.1 <3.0.0). The application owns the server and transport, token
verification, current grants, and any embedded UI resources. This is separate
from the development-time MCP server exposed by the Beignet CLI.
Compose a server using the registry above:
// server/mcp.ts
import {
createMcpAgentCapabilityAdapter,
type CreateMcpAgentCapabilityAdapterOptions,
} from "@beignet/mcp";
import { McpServer } from "@modelcontextprotocol/server";
import {
agentCapabilityRegistry,
agentCapabilityExecutor,
} from "@/server/agent-capabilities";
type McpAccess = Pick<
CreateMcpAgentCapabilityAdapterOptions<
typeof agentCapabilityRegistry.definitions
>,
"principal" | "authorize"
>;
export function createAppMcpServer(access: McpAccess) {
const server = new McpServer({ name: "issues", version: "1.0.0" });
createMcpAgentCapabilityAdapter({
registry: agentCapabilityRegistry,
executor: agentCapabilityExecutor,
...access,
tools: {
"issues.create": {
title: "Create issue",
annotations: {
readOnlyHint: false,
destructiveHint: false,
idempotentHint: false,
openWorldHint: false,
},
},
},
}).register({ server });
return server;
}Supply both callbacks from your authenticated host:
principal(request)resolves a verified principal on every tool call. The request is the SDK'sServerContext; never derive user identity from tool arguments. HTTP authentication middleware still verifies tokens before accepting protocol traffic and owns OAuth challenges.authorize({ name, input, principal, request })checks current grants and scope, throwing an app catalog error to deny.inputis already parsed and is the same object passed to context construction and execution. A grant captured when the server was created is insufficient if it can be revoked.
Execution proceeds through principal resolution, capability input validation, transport authorization, delegated context construction, the capability handler, and output validation. Keep membership and business policies in the executor's context resolver and use cases. MCP annotations are descriptive hints and do not enforce authorization.
Use the SDK's createMcpHandler for Fetch HTTP serving or its other transport
adapters. It creates a fresh server per HTTP request; the application supplies
the callbacks above. To share lazy executor initialization across those
servers, create the Beignet adapter once and call register({ server }) from
the SDK factory. executor accepts an async loader, caches a successful load,
and retries after a failed load. The adapter never caches principals or grants.
register({ server, capabilities: ["issues.create"] }) can limit discovery.
Every invocation still runs authorize. Registration returns
{ unregister() }, which removes only the tools it installed; the host owns
the server and transport lifecycle.
Results and embedded UI
By default, an object output becomes structuredContent plus a JSON text
block. Arrays, primitives, nullable outputs, and other schemas without an
object root use { result: output }, with a matching advertised schema.
The envelope preserves a custom converter's declared $schema dialect,
local $ref and $dynamicRef targets (including empty self-references and
percent-encoded JSON Pointer fragments), and draft-07 fragment-only $id anchors.
Draft-2019-09 schemas using $recursiveAnchor or $recursiveRef must have
their own nonempty $id resource boundary to be wrapped. Otherwise adapter
creation fails with McpAgentCapabilityAdapterError; use an object-root output
or custom renderer if the converter cannot provide that boundary.
Results must contain plain JSON values; unsupported values such as Date,
bigint, undefined, and cyclic objects fail instead of being silently lost.
Each tool can override presentation with both outputSchema and render.
The renderer receives the validated capability output. Its structuredContent
is validated against its own schema and can accompany MCP text, image, audio,
resource links, or embedded resources. For example, the issue capability above
can return a link:
tools: {
"issues.create": {
outputSchema: z.object({ id: z.string(), title: z.string() }),
render(issue) {
return {
content: [{
type: "resource_link",
uri: `https://app.example.com/issues/${issue.id}`,
name: issue.title,
}],
structuredContent: { id: issue.id, title: issue.title },
};
},
},
}This is the tools option inside createMcpAgentCapabilityAdapter; import
z from zod. Keep MCP-specific title, annotations, icons, and _meta
here, separate from the transport-neutral capability definition. UI resource
registration, HTML, security policy, and deployment remain app-owned SDK work.
The adapter derives JSON Schema with Beignet's Zod converter by default;
provide schemaConverter for another Standard Schema implementation. Inputs
and custom rendered outputs need object-root schemas. Validation stays in the
executor so SDK registration does not run input/output transforms a second time.
Custom render validators follow the executor's result semantics: a nonempty
issues array or missing value fails validation; an empty issues array
with a value succeeds.
MCP failures
Invocation failures return MCP tool results with isError: true. Invalid input
receives bounded hints from the same JSON Schema advertised by tools/list:
The tool arguments are invalid. workspaceId: expected string; minimum length 1.The adapter can describe declared field names, array indices, expected types, standard formats, length and numeric limits, and small public enum/constant values. It never copies submitted values, arbitrary validator messages, unknown object keys, or dynamic record keys. Non-enumerable object properties and array entries beyond the declared length cannot contribute hints. For a record entry, feedback stops at the declared record field. Hints describe schema expectations; they may not explain a custom refinement's reason for rejecting a value.
At adapter creation, the configured schemaConverter result for input is
serialized to JSON once. Tool registration and hints share that snapshot, so
custom toJSON() methods, getters, and later mutations cannot make hints expose
data absent from the advertised schema. Input schemas that cannot serialize to
a JSON object fail setup with McpAgentCapabilityAdapterError. Formatting does not
convert or validate again. It follows bounded local JSON Pointer references
within the root resource for draft-07, draft-2019-09, and draft-2020-12 schemas.
It does not merge alternative branches, infer conditional constraints, fetch references, or
cross nested schema resource boundaries. When it cannot safely describe a
constraint, it points to the nearest known field and asks the caller to check
the tool's input schema. Unfamiliar dialects use the generic invalid-arguments
message. Default validation feedback is capped at 2,000 characters and inspects
at most eight issues and eight path segments per issue.
Declared AppError messages remain unchanged. Unexpected errors and invalid
capability or renderer output remain generic. Only use an AppError message
that is safe for the agent to receive.
Use errorMessage({ error, name }) to log failures or provide a safe public
message; return undefined to retain the default hints. A throwing callback
also falls back to the default. Custom messages are app-owned: never return raw
exceptions containing submitted values, credentials, or internal data.
Applications with a custom formatter solely for redacted field and constraint
hints can remove it. Keep authorization, business errors, and tool rendering in
the application.
The adapter supports completed request/response results. Streaming, interactive elicitation, task polling, and UI resource serving remain with the host. It checks request cancellation before execution and around authorization; it does not interrupt a capability handler already running.
Better Auth Agent Auth
Install the bridge beside Better Auth's Agent Auth plugin:
bun add @beignet/agent-auth-better-auth \
@better-auth/agent-auth@0.6.2 better-auth@1.7.26 zod@^4.6.6The bridge supports Agent Auth >=0.6.2 <0.7.0 and Better Auth
>=1.7.7 <1.8.0, with Zod ^4.6.6. The command pins the auth versions
Beignet validates together.
Agent Auth remains on 0.6.2. Apps upgrading from Better Auth 1.7.0–1.7.2
need the account schema cleanup
for existing databases.
import { agentAuth } from "@better-auth/agent-auth";
import { createBetterAuthAgentCapabilityAdapter } from "@beignet/agent-auth-better-auth";
import { APIError } from "better-auth/api";
import {
agentCapabilityExecutor,
agentCapabilityRegistry,
} from "@/server/agent-capabilities";
const capabilityBridge = createBetterAuthAgentCapabilityAdapter({
registry: agentCapabilityRegistry,
executor: agentCapabilityExecutor,
principal({ agentSession }) {
if (!agentSession.userId) {
throw new APIError("FORBIDDEN", {
message: "A delegated user is required.",
});
}
return {
agentId: agentSession.agentId,
userId: agentSession.userId,
};
},
metadata: {
"issues.create": {
approvalStrength: "session",
requiredConstraints: ["workspaceId"],
},
},
});
agentAuth({
...capabilityBridge,
providerName: "my-app",
modes: ["delegated"],
});After registering agentAuth(...), regenerate the Better Auth schema for your
database adapter and apply the resulting migration. Repeat this step after
upgrading Agent Auth or changing Better Auth plugins that add or modify
database fields, so registration, grant, and protocol state match the runtime.
When auth initialization and server composition depend on each other, pass a lazy executor instead of creating a proxy object in the app:
import { agentCapabilityRegistry } from "@/lib/agent-capability-registry";
const capabilityBridge = createBetterAuthAgentCapabilityAdapter({
registry: agentCapabilityRegistry,
executor: () =>
import("@/server/agent-capabilities").then(
({ agentCapabilityExecutor }) => agentCapabilityExecutor,
),
principal({ agentSession }) {
if (!agentSession.userId) {
throw new APIError("FORBIDDEN", {
message: "A delegated user is required.",
});
}
return { agentId: agentSession.agentId, userId: agentSession.userId };
},
});Keep the transport-safe registry in a module that does not import server composition; only the executor needs the dynamic server import. The first successful resolution is memoized for the warm module instance, including concurrent execution. Failed initialization is retried on the next request.
The bridge converts Zod schemas to JSON Schema during setup. Apps using another
Standard Schema library pass a SchemaConverter. Unsupported schemas fail at
boot with the capability name rather than failing on the first request.
Agent Auth evaluates grant constraints against raw arguments before calling the
bridge. Beignet then verifies that the active grant still contains every field
currently declared in requiredConstraints. Tightening capability metadata
therefore makes older broad grants unusable at execution time. Revoke or migrate
those stale grants so agents can request replacement grants with the newly
required scope; Beignet does not mutate Agent Auth's persistence.
If validation changes a field constrained by the active grant, Beignet rejects the invocation before context construction or application work begins. Keep constrained identifiers and amounts non-transforming; unconstrained fields may still use normalization and other schema transformations. The bridge snapshots active constrained values before parsing once, so in-place mutation and a second parse cannot change the value used for execution.
The bridge supports Agent Auth's default capability execution endpoint. Custom capability locations are intentionally excluded because they route requests to app-owned handlers outside Beignet's validation, context, constraint, tracing, and output boundary.
Better Auth verifies the agent and active grant before calling the executor. The app still verifies that the represented user may access the requested tenant and relies on use cases and policies for business authorization.
Errors and observability
Core execution uses stable error codes for unknown capabilities, invalid input,
invalid output, and execution failures. The Better Auth bridge maps malformed
arguments to protocol-safe client errors and redacts invalid output and
unexpected failures as internal errors. Declared Beignet AppError failures
use their stable application code as the Agent Auth error code. Individual
execution also preserves the HTTP status; batch execution preserves the
per-item code but does not have a per-item HTTP status. Intentional Better Auth
APIError failures remain public. Throw one of those explicit public errors
when a failure is safe for an agent to receive; ordinary errors are always
redacted.
Executor hooks observe start, completion, and failure across lookup, input,
authorization, context, handler, and output stages. Successful completion
events include the capability definition, application context, validated input,
validated output, principal, and duration. Failure events include the validated
input and context only when execution reached those stages; malformed raw input
and unvalidated handler output are never exposed. Because early stages run
before application context exists, failure events expose an optional ctx.
Pass independent instrumentation and tracing options to the executor when
malformed input or context-construction failures must reach those ports;
otherwise Beignet derives them from ctx after successful context construction.
Recorded attributes are bounded, and principal data, arguments, and results are
never recorded automatically. Lifecycle hooks remain best-effort observers;
place mandatory audit writes inside the application workflow.
Use the adapter-specific test helper when testing the Better Auth bridge:
import { createBetterAuthAgentCapabilityTestContext } from
"@beignet/agent-auth-better-auth/testing";
await capabilityBridge.onExecute?.(
createBetterAuthAgentCapabilityTestContext({
capability: "issues.create",
arguments: { workspaceId: "workspace_1", title: "Fix login" },
constraints: { workspaceId: "workspace_1" },
}),
);The first release supports synchronous promise-based results. Streaming, asynchronous polling, model loops, prompts, conversation memory, and approval UI remain transport or application concerns.