Mastra: act in your users' accounts
Give a Mastra agent a tool that calls an Anlyon action for one of your users, lets that user approve the call in your app, and reports the receipt grade.
Mastra runs your agent. It does not hold your users’ GitHub or Gmail tokens, count what the agent does per user, or ask the right person before a risky write. A tool that calls a provider itself needs that user’s token in your Mastra app, and a Mastra tool approval is answered by your own code, not by the provider call.
With Anlyon, the agent’s tool calls an action by name. Your server names the user in Mastra’s request context, the tool binds the Anlyon client to that user, and Anlyon adds the user’s token at dispatch, checks their limit, parks the call until they approve it in your app, and returns a receipt. The agent never sees a token, and the tool has no user field the model could change.
This guide builds a support agent that opens GitHub issues in each user’s own account:
- The model calls the
open-issuetool. Anlyon parks the call for the user’s approval, and the tool returns at once with the invocation id. - The user approves in your app. Approving runs the parked call.
- On the next turn, the model calls
check-requestwith the invocation id and reports the receipt grade.
Before you start
Run the quickstart first, or do its steps 1 and 4 in your environment. You then have:
- The action
open-issue. It opens one issue with the calling user’s own GitHub connection,{{connection:github}}, counts oneissuesper call and reads the issue back. - An approval policy with
decidedBy: "end_user": every call waits for the user it acts for. - An impact limit of 5 issues a day per user (
scope: "end_user"). - An app key,
ANLYON_APP_KEY, from the Standard preset plusend-users:writeandend-users:approvals, with Require an end user on.
The agent’s tools need actions:invoke (to call the action) and actions:read (to read the call later). Your server’s approval routes need end-users:approvals, and its connect routes end-users:write. Nothing here needs the GitHub token, approvals:decide or policies:write.
Install the packages:
npm install @anlyonhq/sdk @mastra/core zod
Use any model Mastra supports with tool calling. This guide uses 'openai/gpt-5-mini'.
Check the key at startup
// anlyon.ts
import { Client } from '@anlyonhq/sdk';
export const anlyon = new Client({ apiKey: process.env.ANLYON_APP_KEY! });
// Fail fast on a wrong key: missing what the app needs, or holding what it must not.
await anlyon.auth.requireScopes(
['actions:read', 'actions:invoke', 'end-users:write', 'end-users:approvals'],
{ forbidden: ['approvals:decide', 'policies:write', 'impact-limits:write', 'secrets:write'] },
);
requireScopes() throws ScopeCheckError with missing and forbidden. It never changes the key.
Define the tools
A Mastra agent is defined once and serves every user, so the tools read the user from Mastra’s request context. Your server sets it for each request from its own session. The model cannot set it, and neither tool’s input schema has a user field.
anlyon.forUser(endUserId) binds the client to that user. Each tool returns what the model reads: the status, the receipt grade, the invocation id and what to do next. The idempotency key is made from the tool call’s id, so a tool that runs twice for one call never opens two issues.
// tools.ts
import type { RequestContext } from '@mastra/core/request-context';
import { createTool } from '@mastra/core/tools';
import { EndUserConnectionRequiredError, NotFoundError, type Invocation } from '@anlyonhq/sdk';
import { z } from 'zod';
import { anlyon } from './anlyon';
const NOTES: Record<string, string> = {
succeeded: 'Done.',
pending_approval: "Waiting for the user's approval in the app. Do not call open-issue again.",
running: 'Still running. Check it later. Do not call open-issue again.',
unknown: 'The outcome is unknown. Do not call open-issue again.',
failed: 'It did not happen. Tell the user why.',
denied: 'The user declined. Do not call open-issue again.',
expired: 'Nobody approved it in time. Do not call open-issue again.',
};
/** What the model reads back: status, receipt grade and what to do next. */
function outcome(invocation: Invocation) {
return {
status: invocation.status,
grade: invocation.grade ?? null,
invocationId: invocation.id,
error: invocation.error,
note: NOTES[invocation.status] ?? '',
};
}
/** The user your server put in the request context. Never from the model. */
function userFrom(requestContext?: RequestContext) {
const endUserId = requestContext?.get('endUserId');
if (typeof endUserId !== 'string') throw new Error('No end user in the request context.');
return { endUserId, user: anlyon.forUser(endUserId) };
}
export const openIssue = createTool({
id: 'open-issue',
description: "Open one GitHub issue in the user's own account. The user approves each issue.",
inputSchema: z.object({
title: z.string().min(1).max(256),
body: z.string().min(1).max(20000),
}),
execute: async ({ title, body }, context) => {
const { endUserId, user } = userFrom(context?.requestContext);
const toolCallId = context?.agent?.toolCallId ?? crypto.randomUUID();
try {
const { data } = await user.actions.invoke(
'open-issue',
{ title, body },
// One tool call, one invocation, even if the tool runs again.
{ idempotencyKey: `mastra:${endUserId}:${toolCallId}` },
);
return outcome(data!);
} catch (error) {
if (error instanceof EndUserConnectionRequiredError) {
// Not connected: nothing was sent. The model relays the message.
return {
status: error.code === 'END_USER_RECONNECT_REQUIRED' ? 'reconnect_required' : 'connect_required',
integration: error.integration,
connectUrl: error.connectUrl,
message: `The user has not connected ${error.integration}, so nothing was done. Ask them to use the Connect button, then try again.`,
};
}
throw error;
}
},
});
export const checkRequest = createTool({
id: 'check-request',
description: 'Read what happened to an earlier open-issue call, by its invocation id.',
inputSchema: z.object({ invocationId: z.string() }),
execute: async ({ invocationId }, context) => {
const { user } = userFrom(context?.requestContext);
try {
const { data } = await user.actions.invocation(invocationId);
return outcome(data!);
} catch (error) {
if (error instanceof NotFoundError) return { status: 'not_found', note: 'No such call for this user.' };
throw error;
}
},
});
check-request reads an invocation through the same bound client. With a key that requires an end user, an invocation made for another user answers 404, so the model cannot read another user’s calls by guessing an id.
Run the agent for a user
Register the tools on the agent, then set the user in the request context in your route, from its own session:
// assistant.ts
import { Agent } from '@mastra/core/agent';
import { RequestContext } from '@mastra/core/request-context';
import { checkRequest, openIssue } from './tools';
export const assistant = new Agent({
id: 'support',
name: 'Support',
instructions:
'You help the user track bugs. To open a GitHub issue, call open-issue once. ' +
'If a tool says the user must connect an account, tell them to use the Connect button. ' +
'To learn what happened to an earlier call, call check-request with its invocation id. ' +
'Never call a tool again to get around a decision or an unknown outcome.',
model: 'openai/gpt-5-mini',
tools: { openIssue, checkRequest },
});
export async function chat(sessionUserId: string, text: string) {
const requestContext = new RequestContext();
requestContext.set('endUserId', sessionUserId); // your server binds the user; the model cannot
const result = await assistant.generate(text, { requestContext });
return result.text;
}
When the user asks to open an issue, the tool returns at once and the call is parked in Anlyon. Nothing has reached GitHub. The model reads:
{
"status": "pending_approval",
"grade": null,
"invocationId": "inv_01JABCDEF",
"error": null,
"note": "Waiting for the user's approval in the app. Do not call open-issue again."
}
The invocation id stays in the conversation, so the model can check it on a later turn. Keep the conversation with Mastra memory or your own storage. An approval can take hours, so the tool does not hold the agent run open.
Let the user approve in your app
Show the user their pending approvals: the exact title and body the agent wants to send. When they decide, your server relays it. Approving runs the parked call with the request exactly as the user saw it.
import { anlyon } from './anlyon';
export async function pendingApprovals(sessionUserId: string) {
// This user's approvals only. Another user's answers 404.
const { data } = await anlyon.endUsers.approvals.list(sessionUserId, { status: 'pending' });
return data!;
}
export async function decide(sessionUserId: string, approvalId: string, approve: boolean) {
await anlyon.endUsers.approvals.decide(sessionUserId, approvalId, {
decision: approve ? 'approve' : 'deny',
});
}
On the next turn, the model calls check-request with the invocation id. For open-issue it reads:
{ "status": "succeeded", "grade": "confirmed", "invocationId": "inv_01JABCDEF", "error": null, "note": "Done." }
confirmed means Anlyon read the issue back from GitHub and its title matched.
The approval stays pending for 24 hours by default; your workspace defaults can change the window. Your app can also read the invocation itself with anlyon.forUser(sessionUserId).actions.invocation(invocationId). To learn about decisions without polling, subscribe to approval events with a webhook.
Connect a user who has not connected GitHub
When the user has no GitHub connection, the action is not sent, and the tool returns:
{
"status": "connect_required",
"integration": "github",
"connectUrl": "https://...",
"message": "The user has not connected github, so nothing was done. Ask them to use the Connect button, then try again."
}
reconnect_required means the provider revoked the connection. Render connectUrl as a Connect GitHub button: it works once, for 10 minutes. It is null when the environment has no default redirect URL; then make a link yourself and confirm the connection in your callback:
import { parseConnectRedirect } from '@anlyonhq/sdk';
import { anlyon } from './anlyon';
const { data: link } = await anlyon.endUsers.createConnectLink({
endUserId: sessionUserId,
integration: 'github',
redirectUrl: 'https://app.example.com/connections/callback',
}); // send the browser to link!.url
// In the callback route, with the user from your session:
const result = parseConnectRedirect(request.url);
if (result?.status === 'pending_confirmation' && result.flowId) {
await anlyon.endUsers.confirmConnection(sessionUserId, result.flowId);
}
See Workspace connections and end-user connections.
Read the result
| Status | Grade | What the agent should do |
|---|---|---|
pending_approval |
pending or null |
Tell the user to approve it in the app. Check it on a later turn. |
running |
pending |
Check the same invocation later. |
succeeded |
confirmed or acknowledged |
Report it. confirmed: a read-back matched the request. |
failed |
failed or refused |
Report error. refused means Anlyon refused it at dispatch, for example on the user’s daily limit. Nothing was sent. |
unknown |
unknown |
No usable response. Anlyon does not send it again. Do not call the tool again. |
denied / expired |
denied |
Stop. Do not resubmit to get around the decision. |
Handle errors
| Error | What it means | What to do |
|---|---|---|
EndUserConnectionRequiredError |
The user has no working connection. | Handled in the tool: the model gets connect_required. |
No end user in the request context. |
The route did not set endUserId. |
Set it from your session on every generate() or stream() call. |
EndUserRequiredError (400 END_USER_REQUIRED) |
A call was made without forUser(). |
Make every call through anlyon.forUser(endUserId). |
NotFoundError from check-request |
The invocation id does not exist, or belongs to another user. | Handled in the tool: the model gets not_found. |
ScopeCheckError |
The key is wrong for the app. | Use a key with the scopes above. |
AnlyonError with code AUTHORIZATION_ERROR (403) |
The key lacks a scope a call needs. | Add it when you create the key. |
RateLimitError, NetworkError, TimeoutError |
Thrown after the SDK’s own retries. | Run the turn again. The idempotency key answers a repeated tool call from the first record. |
See the TypeScript SDK for every error.
Mastra approvals and Anlyon approvals together
Mastra’s requireApproval on createTool(), or requireToolApproval on generate() and stream(), pauses a tool call until your code calls approveToolCall() or declineToolCall() (approveToolCallGenerate() and declineToolCallGenerate() after generate()). That answer is made in your process, and it does not approve the Anlyon call. Turning both on for one tool asks twice.
The Anlyon approval is the decision on the real call: it goes to the user it acts for, it is bound to the exact request, and only endUsers.approvals.decide can make it.
A Mastra tool that calls a provider with its own token does not go through Anlyon, so no limit, approval or receipt applies to it. For a call you cannot move to an action yet, approvals.gate() waits for a decision and then runs your own function with your own credential.
Related
- TypeScript SDK: the client the tools use.
- Approvals: who decides, and how a policy routes a call.
- Receipts and grades and Idempotency and retries.
- Mastra’s tools, request context and agent approval.

