Skip to content
Anlyon
Esc
↑↓navigate↵open⌘Jpreview
On this page

Examples

Copy working code for the calls an agent app makes most: invoke an action for a user, connect their account, relay their approval, wait for a team decision, retry safely, read a receipt, settle an unknown outcome and verify a webhook.

Each recipe below is one task, complete and ready to paste: TypeScript first, then curl, then Python. For the full walkthrough that sets up the action, the approval policy and the per-user limit these recipes rely on, start with the quickstart.

Set up the clients

npm install @anlyonhq/sdk     # TypeScript
pip install anlyon            # Python

Use two keys, because the key that decides where a credential may go should not be the key your running app holds:

export ANLYON_OPERATOR_KEY=anlyon_live_...  # defines actions, limits and policies
export ANLYON_APP_KEY=anlyon_live_...       # your server: actions:invoke, actions:read, end-users:write, end-users:approvals
export ANLYON_SIGNING_SECRET=...            # verifies webhook deliveries

Create both in the console under Settings → API Keys. Turn on Require an end user for the app key if it should only ever act for your users. See API keys and scopes.

Invoke an action for one of your users

Your server names the user from its own session. The call uses that user’s connected account, counts against their limits and waits for their approval when a policy says so. When the user has not connected the integration, nothing is sent and you get a link to connect.

import { Client, EndUserNotConnectedError } from '@anlyonhq/sdk';

const anlyon = new Client({ apiKey: process.env.ANLYON_APP_KEY! });

try {
  const { data } = await anlyon.forUser(session.user.id).actions.invoke('open-issue', {
    title: 'Export fails',
    body: 'Reported in chat.',
  });
  if (data!.status === 'pending_approval') console.log('Waiting on the user:', data!.approvalId);
  else console.log(data!.status, data!.grade, data!.effectId);
} catch (error) {
  if (error instanceof EndUserNotConnectedError) console.log('Connect first:', error.connectUrl);
  else throw error;
}
curl -s -X POST https://api.anlyon.com/api/v2/actions/open-issue/invoke \
  -H "Authorization: Bearer $ANLYON_APP_KEY" \
  -H "Anlyon-End-User: user_123" \
  -H "Content-Type: application/json" \
  -d '{ "input": { "title": "Export fails", "body": "Reported in chat." } }'
import os
from anlyon import Client, EndUserNotConnectedError

anlyon = Client(api_key=os.environ["ANLYON_APP_KEY"])

try:
    data = anlyon.for_user(session_user_id).actions.invoke(
        "open-issue", {"title": "Export fails", "body": "Reported in chat."}
    ).data
    if data["status"] == "pending_approval":
        print("Waiting on the user:", data["approvalId"])
    else:
        print(data["status"], data["grade"], data["effectId"])
except EndUserNotConnectedError as error:
    print("Connect first:", error.connect_url)

Give an agent your actions as tools

With the Vercel AI SDK, anlyonTools turns each action into a tool. Pass a client bound to the user: the tool schemas have no user field, and a missing connection comes back to the model as a connect_required result instead of an error.

import { anlyonTools } from '@anlyonhq/ai-sdk';

const tools = await anlyonTools({ client: anlyon.forUser(session.user.id) });

For MCP clients such as Claude Code or Cursor, see MCP servers. For the full app, see Act for your users.

Connect a user’s account

Send the user to a connect link. It works once, for 10 minutes. On your callback route, confirm the connection for the user in your own session, never one read from the URL.

import { parseConnectRedirect } from '@anlyonhq/sdk';

// 1. The Connect GitHub button.
const { data: link } = await anlyon.endUsers.createConnectLink({
  endUserId: session.user.id,
  integration: 'github',
  redirectUrl: 'https://app.example.com/connections/callback',
});
// Redirect the browser to link!.url

// 2. The callback route.
const result = parseConnectRedirect(request.url);
if (result?.status === 'pending_confirmation' && result.flowId) {
  await anlyon.endUsers.confirmConnection(session.user.id, result.flowId);
}
curl -s -X POST https://api.anlyon.com/api/v2/end-users/user_123/connect-links \
  -H "Authorization: Bearer $ANLYON_APP_KEY" \
  -H "Anlyon-End-User: user_123" \
  -H "Content-Type: application/json" \
  -d '{ "integration": "github", "redirectUrl": "https://app.example.com/connections/callback" }'
link = anlyon.end_users.create_connect_link(
    end_user_id=session_user_id,
    integration="github",
    redirect_url="https://app.example.com/connections/callback",
).data
# Redirect the browser to link["url"]. On the callback route:
anlyon.end_users.confirm_connection(session_user_id, flow_id)

A connect link for an integration that uses an API key opens a hosted form where the user pastes their own key. A flow started for another user answers 403 END_USER_MISMATCH on confirm and connects nothing. See Workspace and end-user connections.

Pass on a user’s approval

When a policy says decidedBy: "end_user", the call waits for the user it acts for. Show them their pending approvals in your app and relay their click. Approving runs the parked call exactly as they saw it. Needs end-users:approvals.

const { data: pending } = await anlyon.endUsers.approvals.list(session.user.id, { status: 'pending' });

// The user clicked Approve on one of them.
const { data: decision } = await anlyon.endUsers.approvals.decide(session.user.id, approvalId, {
  decision: 'approve',
});
console.log(decision!.approval.status, decision!.invocation?.status);
curl -s "https://api.anlyon.com/api/v2/end-users/user_123/approvals?status=pending" \
  -H "Authorization: Bearer $ANLYON_APP_KEY" \
  -H "Anlyon-End-User: user_123"

curl -s -X POST https://api.anlyon.com/api/v2/end-users/user_123/approvals/$APPROVAL_ID/decide \
  -H "Authorization: Bearer $ANLYON_APP_KEY" \
  -H "Anlyon-End-User: user_123" \
  -H "Content-Type: application/json" \
  -d '{ "decision": "approve" }'
pending = anlyon.end_users.approvals.list(session_user_id, status="pending").data

decision = anlyon.end_users.approvals.decide(session_user_id, approval_id, decision="approve").data
print(decision["approval"]["status"], decision["invocation"]["status"])

A user can only see and decide their own approvals: another user’s id answers 404. Always take the id from your session.

Wait for a team decision

When your team decides, the call comes back pendingApproval: true. Wait for the decision instead of polling. Needs approvals:read. The wait returns the approval whatever happens: still pending when the timeout passes first.

const decided = await anlyon.approvals.waitForDecision(data!.approvalId!, { timeoutMs: 10 * 60_000 });

if (decided.status === 'approved') console.log('Anlyon made the call.');
else if (decided.status === 'pending') console.log('Still waiting. The approval stays decidable.');
else console.log('Not sent:', decided.status);
# Long-poll one approval for up to the server's wait ceiling.
curl -s "https://api.anlyon.com/api/v2/approvals/$APPROVAL_ID?waitSeconds=30" \
  -H "Authorization: Bearer $ANLYON_APP_KEY"
decided = anlyon.approvals.wait_for_decision(data["approvalId"], timeout_seconds=600)

if decided["status"] == "approved":
    print("Anlyon made the call.")
elif decided["status"] == "pending":
    print("Still waiting. The approval stays decidable.")
else:
    print("Not sent:", decided["status"])

To decide from code instead of the console or Slack, use a different key from the one that requested, with approvals:decide: approvals.approve(id, { note }) or POST /api/v2/approvals/{id}/approve. A key can never decide an approval it requested.

Retry safely with an idempotency key

Anlyon does not retry an invocation on its own. If your code retries, reuse a key derived from the operation. The retry is answered from the recorded invocation, and the action does not run again.

await anlyon.forUser(session.user.id).actions.invoke(
  'open-issue',
  { title: 'Export fails', body: 'Reported in chat.' },
  { idempotencyKey: `issue:${ticketId}` },
);
curl -s -X POST https://api.anlyon.com/api/v2/actions/open-issue/invoke \
  -H "Authorization: Bearer $ANLYON_APP_KEY" \
  -H "Anlyon-End-User: user_123" \
  -H "Idempotency-Key: issue:T-4417" \
  -H "Content-Type: application/json" \
  -d '{ "input": { "title": "Export fails", "body": "Reported in chat." } }'
anlyon.for_user(session_user_id).actions.invoke(
    "open-issue",
    {"title": "Export fails", "body": "Reported in chat."},
    idempotency_key=f"issue:{ticket_id}",
)

The same key with a different request answers 409 idempotency_key_reuse. See Idempotency and retries.

Read the receipt

A governed call returns an effectId. The effect is the receipt: its grade, its outcome and the evidence behind them.

const { data: receipt } = await anlyon.forUser(session.user.id).actions.effect(effectId);
console.log(receipt!.outcome, receipt!.grade, receipt!.verification);

// Every call that is not yet confirmed by a read-back.
const { data: unread } = await anlyon.actions.effects({ grade: 'acknowledged' });
curl -s https://api.anlyon.com/api/v2/actions/effects/$EFFECT_ID \
  -H "Authorization: Bearer $ANLYON_APP_KEY" \
  -H "Anlyon-End-User: user_123"

curl -s "https://api.anlyon.com/api/v2/actions/effects?grade=acknowledged" \
  -H "Authorization: Bearer $ANLYON_OPERATOR_KEY"
receipt = anlyon.for_user(session_user_id).actions.effect(effect_id).data
print(receipt["outcome"], receipt["grade"], receipt["verification"])

unread = anlyon.actions.effects(grade="acknowledged").data

confirmed means a read-back matched the request. See Receipts and grades for all seven grades.

Settle an unknown outcome

When a response is lost, the invocation is unknown. Do not retry. A governed effect settles itself when its read-back finds the write. For an action without declarations, check the destination and record what you found. Recording needs actions:resolve, which no key gets by default, and the key that made the call can never resolve it.

const operator = new Client({ apiKey: process.env.ANLYON_OPERATOR_KEY! });

const { data: unknown } = await operator.actions.invocations({ status: 'unknown' });

await operator.actions.resolveInvocation('inv_01JABCDEF', {
  outcome: 'succeeded',
  evidence: 'Issue #412 is open in acme/support.',
  externalReference: '412',
});
curl -s "https://api.anlyon.com/api/v2/actions/invocations?status=unknown" \
  -H "Authorization: Bearer $ANLYON_OPERATOR_KEY"

curl -s -X POST https://api.anlyon.com/api/v2/actions/invocations/inv_01JABCDEF/resolve \
  -H "Authorization: Bearer $ANLYON_OPERATOR_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "outcome": "succeeded", "evidence": "Issue #412 is open in acme/support.", "externalReference": "412" }'
operator = Client(api_key=os.environ["ANLYON_OPERATOR_KEY"])

unknown = operator.actions.invocations(status="unknown").data

operator.actions.resolve_invocation(
    "inv_01JABCDEF",
    outcome="succeeded",
    evidence="Issue #412 is open in acme/support.",
    external_reference="412",
)

For a governed effect, reconcile, replay or resolve the effect instead. See Refund safely when the agent retries and When the outcome is unknown.

Gate a function that stays in your process

When a call cannot move into an action, gate your own function on an approval. Your process still runs it with your credential, so this gives you the decision and the record, not credential isolation, limits or a receipt.

const guardedRefund = anlyon.approvals.gate(
  { title: 'Refund a customer?', timeoutMs: 10 * 60_000 },
  async (orderId: string, amount: number) => { /* refund logic */ },
);

await guardedRefund('ord_42', 129.99);
@anlyon.approvals.gate(title="Refund a customer?", timeout_seconds=600)
def refund(order_id: str, amount: float) -> None:
    ...  # refund logic

refund("ord_42", 129.99)

See Approval gates.

Verify a webhook

Anlyon signs every delivery. Verify the signature before you act on an event.

// app/api/webhooks/anlyon/route.ts
import { serve } from '@anlyonhq/sdk/nextjs';

export const { POST } = serve(async (request) => {
  const event = await request.json();
  if (event.type === 'approval.requested') await notifyReviewers(event);
  if (event.type === 'action.unknown') await openReconciliationTicket(event);
  return { success: true };
});
import os
from flask import Flask, request
from anlyon import Receiver

app = Flask(__name__)
receiver = Receiver(os.environ["ANLYON_SIGNING_SECRET"])

@app.route("/webhooks/anlyon", methods=["POST"])
def handle_webhook():
    raw_body = request.get_data(as_text=True)
    if not receiver.verify(signature=request.headers.get("Anlyon-Signature"), body=raw_body):
        return "Invalid signature", 401
    event = request.get_json()
    return "OK", 200

Express, Hono and plain Node.js handlers, the event list and the subscription call are on Events and webhooks.

Fix common errors

What you see Why What to do
409 END_USER_NOT_CONNECTED (EndUserNotConnectedError) The user has not connected the integration. Nothing was sent. Show a Connect button with connectUrl, or make a link with createConnectLink.
409 END_USER_RECONNECT_REQUIRED (EndUserReconnectRequiredError) The provider refused the user’s credential. Ask the user to connect again with a connect link.
400 END_USER_REQUIRED The key requires an end user and the call named none. Build the client with forUser() on your server.
403 END_USER_MISMATCH A connect flow started for another user. Confirm with the user from your session.
403 AUTHORIZATION_ERROR The key lacks a scope. The message names it. Create a key with that scope. Scopes are fixed when a key is created.
402 PAYMENT_REQUIRED The workspace has no plan. An admin starts one in Settings → Plan & billing. See anlyon.com/pricing.
200 with grade: "refused" and impact_limit_exceeded A limit had no room. Nothing was sent. Wait for the next period or raise the limit.
409 idempotency_key_reuse The same key came with a different request. Reuse the request, or use a new key for a new decision.
409 PREVIEW_MISMATCH The call differs from the reviewed preview. Preview again and get it reviewed.
409 ENVIRONMENT_HALTED The environment is halted. Resume it when it is safe.
status: "unknown" The response was lost. Do not retry. Settle it as above.

Was this page helpful?