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

CrewAI: act in your users' accounts

Give a CrewAI 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.

CrewAI runs your crew. It does not hold your users’ GitHub or Gmail tokens, count what the crew 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 the crew’s process, and nothing stops the model from calling it again.

With Anlyon, the crew’s tool calls an action by name. Your server binds the tool to one user, Anlyon adds that user’s token at dispatch, checks their limit, parks the call until they approve it in your app, and returns a receipt. The crew never sees a token, and the tool has no user field the model could change.

This guide builds a support crew that opens GitHub issues in each user’s own account:

  1. The agent calls the open-issue tool. Anlyon parks the call for the user’s approval, and the crew finishes with “waiting for your approval”.
  2. The user approves in your app. Approving runs the parked call.
  3. On the next turn, the agent checks the call by its 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 one issues per 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 plus end-users:write and end-users:approvals, with Require an end user on.

The crew’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:

pip install crewai anlyon

Use any model CrewAI supports with tool calling. This guide uses llm="openai/gpt-5-mini".

Check the key at startup

import os
from anlyon import Client

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

# Fail fast on a wrong key: missing what the app needs, or holding what it must not.
anlyon.auth.require_scopes(
    ["actions:read", "actions:invoke", "end-users:write", "end-users:approvals"],
    forbidden=["approvals:decide", "policies:write", "impact-limits:write", "secrets:write"],
)

require_scopes() raises ScopeCheckError with missing and forbidden. It never changes the key.

Build the tools for one user

The tools are built for one user at a time. anlyon.for_user(end_user_id) binds the client to the user from your session, and every call the tools make happens for that user. Each tool returns JSON the model reads: the status, the receipt grade, the invocation id and what to do next.

# tools.py
import json
import os

from anlyon import Client, EndUserConnectionRequiredError, NotFoundError
from anlyon.integrations.action_tools import connect_required_result
from crewai.tools import tool

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

NOTES = {
    "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.",
}


def outcome(invocation: dict) -> str:
    """What the model reads back: status, receipt grade and what to do next."""
    status = invocation["status"]
    return json.dumps({
        "status": status,
        "grade": invocation.get("grade"),
        "invocationId": invocation["id"],
        "error": invocation.get("error"),
        "note": NOTES.get(status, ""),
    })


def tools_for(end_user_id: str, started: list[str]):
    """The crew's tools, bound to one user. `started` collects the invocation ids for your app."""
    user = anlyon.for_user(end_user_id)  # your server binds the user; the model cannot

    @tool("open-issue")
    def open_issue(title: str, body: str) -> str:
        """Open one GitHub issue in the user's own account. The user approves each issue."""
        try:
            invocation = user.actions.invoke("open-issue", {"title": title, "body": body}).data
        except EndUserConnectionRequiredError as error:
            # Not connected: nothing was sent. The model relays the message.
            return json.dumps(connect_required_result(error))
        started.append(invocation["id"])
        return outcome(invocation)

    @tool("check-request")
    def check_request(invocation_id: str) -> str:
        """Read what happened to an earlier open-issue call, by its invocation id."""
        try:
            return outcome(user.actions.invocation(invocation_id).data)
        except NotFoundError:
            return json.dumps({"status": "not_found", "note": "No such call for this user."})

    # CrewAI reuses a tool's result for the same input by default. A status changes, so never reuse it.
    check_request.cache_function = lambda args, result: False
    return [open_issue, check_request]

The open-issue tool takes the action’s own input, title and body, and nothing else. 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 crew for a user

Your route takes the user from its own session, never from the request body or the model. The invocation ids the tool started go back to your app with the reply:

# crew.py
from crewai import Agent, Crew, Task

from tools import tools_for

SYSTEM = (
    "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. Never call a tool again to get around a "
    "decision or an unknown outcome. Report the status and the grade."
)


def chat(session_user_id: str, text: str, waiting: list[str]) -> dict:
    started: list[str] = []
    support = Agent(
        role="Support engineer",
        goal="Track the user's bugs as GitHub issues.",
        backstory=SYSTEM,
        llm="openai/gpt-5-mini",
        tools=tools_for(session_user_id, started),
    )
    task = Task(
        description=(
            "The user says: {text}\n"
            "Calls still waiting from earlier turns: {waiting}. Check each with check-request."
        ),
        expected_output="A short reply to the user.",
        agent=support,
    )
    result = Crew(agents=[support], tasks=[task]).kickoff(
        inputs={"text": text, "waiting": ", ".join(waiting) or "none"}
    )
    return {"reply": result.raw, "started": started}

When the user asks to open an issue, the tool returns at once and the crew finishes. The call is parked in Anlyon, and 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."
}

Store started with the user’s conversation, and pass it back as waiting on the next turn. An approval can take hours, so the crew does not wait for it.

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.

from tools import anlyon


def pending_approvals(session_user_id: str) -> list[dict]:
    # This user's approvals only. Another user's answers 404.
    return anlyon.end_users.approvals.list(session_user_id, status="pending").data


def decide(session_user_id: str, approval_id: str, approve: bool) -> None:
    anlyon.end_users.approvals.decide(
        session_user_id, approval_id, decision="approve" if approve else "deny"
    )

On the next turn, the agent calls check-request with the stored 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. To learn about decisions without polling, subscribe to approval events with a webhook and start the next turn from there.

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 yet, so nothing was done. Ask them to connect it, 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:

from anlyon import parse_connect_redirect

link = anlyon.end_users.create_connect_link(
    end_user_id=session_user_id,
    integration="github",
    redirect_url="https://app.example.com/connections/callback",
).data  # send the browser to link["url"]

# In the callback route, with the user from your session:
result = parse_connect_redirect(callback_url)
if result and result.status == "pending_confirmation" and result.flow_id:
    anlyon.end_users.confirm_connection(session_user_id, result.flow_id)

See Workspace connections and end-user connections.

Read the result

Status Grade What the crew 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.
EndUserRequiredError (400 END_USER_REQUIRED) A call was made without for_user(). Always build the tools with tools_for(session_user_id, ...).
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 Raised after the SDK’s own retries. Each retry of one invoke sends the same idempotency key, so it is not run twice. Run the turn again. Check started first, so a call that was parked is not made again.

See the Python SDK for every error.

CrewAI hooks and Anlyon approvals together

A CrewAI PRE_TOOL_CALL hook runs in the crew’s process. It can ask whoever runs the crew with request_human_input(), or block a call by raising HookAborted. That suits a check at the terminal. It does not reach your user in your app, and a hook’s yes does not approve a pending Anlyon call.

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 end_users.approvals.decide can make it. Task(human_input=True) reviews the task’s final answer, not a tool call.

A CrewAI 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.

Was this page helpful?