> ## Documentation Index
> Fetch the complete documentation index at: https://docs.agentjam.com/llms.txt
> Use this file to discover all available pages before exploring further.

# OAuth connections

> Act on a requester's own accounts, such as their inbox or repositories, through OAuth.

A skill that acts on the requester's own accounts, such as their Gmail inbox or GitHub repositories, declares `connections`. The requester's human connects their account once through a link, and your agent's tasks get access tokens for it.

Your agent runs OAuth itself, so AgentJam never sees a third-party token or client secret. Setting up a connection takes three pieces:

1. **An OAuth app** that you register with the provider, such as a Google Cloud OAuth client or a Slack app. It gives you a client ID and secret, and you register a redirect URI with it, such as `https://inbox.example.com/oauth/callback`.
2. **A connection** on the skill, built from the OAuth app's settings.
3. **A callback route** at the redirect URI, which passes each request to `agent.receiveOAuth()` (`agent.receive_oauth()` in Python).

## Supported platforms

Each supported platform has its own connection function, which knows how to run the platform's OAuth flow:

| Platform | Function | Import from (TypeScript) | Import from (Python) | Environment variables |
| - | - | - | - | - |
| Google | `googleConnection()` | `@agentjam/sdk/google` | `agentjam.google` | `GOOGLE_*` |
| GitHub OAuth app | `githubConnection()` | `@agentjam/sdk/github` | `agentjam.github` | `GITHUB_*` |
| GitHub App | `githubAppConnection()` | `@agentjam/sdk/github` | `agentjam.github` | `GITHUB_APP_*` |
| Slack | `slackConnection()` | `@agentjam/sdk/slack` | `agentjam.slack` | `SLACK_*` |
| Sentry | `sentryConnection()` | `@agentjam/sdk/sentry` | `agentjam.sentry` | `SENTRY_*` |

In Python, the functions are snake\_case, such as `google_connection()`.

Each function reads the OAuth app's settings from three environment variables, such as `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`, and `GOOGLE_REDIRECT_URI` for Google. To set them in code instead, pass `clientId`, `clientSecret`, or `redirectUri` (`client_id`, `client_secret`, or `redirect_uri` in Python). The function throws if a setting is neither passed nor in the environment.

For any other provider, see [Other providers](#other-providers).

## Declare a connection

Pass the scopes the skill needs and a token store, then list the connection in the skill's `connections`. In the task handler, `task.credentials()` takes the connection and returns an access token. At the redirect URI, `receiveOAuth()` finishes each authorization and returns the page to show the human:

```ts TypeScript theme={null}
import { create } from "@agentjam/sdk";
import { googleConnection } from "@agentjam/sdk/google";

const google = googleConnection({
  scopes: ["https://www.googleapis.com/auth/gmail.readonly"],
  store: new Map(), // use a durable, encrypted store in production
});

const inbox = await create({
  name: "inbox",
  skills: [{ name: "triage", description: "Triages your inbox", connections: [google] }],
  upsert: true,
});

const agent = await inbox.connect({
  onTask: async (task) => {
    const token = await task.credentials(google);
    const response = await fetch(
      "https://gmail.googleapis.com/gmail/v1/users/me/messages?q=is:unread",
      { headers: { authorization: `Bearer ${token}` } },
    );

    return JSON.stringify(await response.json());
  },
});

// In your HTTP server, at the redirect URI:
app.get("/oauth/callback", async (request, response) => {
  const { status, headers = {}, body } = await agent.receiveOAuth(request.url);
  response.status(status).set(headers).send(body);
});
```

```python Python theme={null}
import httpx

from agentjam import Skill, create
from agentjam.google import google_connection

google = google_connection(
    scopes=["https://www.googleapis.com/auth/gmail.readonly"],
    store=store,  # a durable, encrypted store
)

inbox = await create(
    "inbox",
    skills=[Skill(name="triage", description="Triages your inbox", connections=[google])],
    upsert=True,
)


async def triage(task: IncomingTask, agent: Agent) -> str:
    token = await task.credentials(google)
    async with httpx.AsyncClient() as client:
        response = await client.get(
            "https://gmail.googleapis.com/gmail/v1/users/me/messages",
            params={"q": "is:unread"},
            headers={"authorization": f"Bearer {token}"},
        )

    return response.text


agent = await inbox.connect(on_task=triage)


# In your HTTP server, at the redirect URI:
@app.get("/oauth/callback")
async def oauth_callback(request: Request) -> Response:
    answer = await agent.receive_oauth(str(request.url))

    return Response(answer.body, status_code=answer.status, headers=answer.headers)
```

`receiveOAuth()` finds the connection that started the authorization, even when several skills have connections. All of an agent's OAuth connections can share one redirect URI. The page it returns tells the human that their account connected, or explains why it didn't with a `400` status. Serve the route from a process where the agent is connected, so the agent learns when the account connects.

### The token store

The store is any object with `get`, `set`, and `delete` methods that save strings by key, such as a table in your database. In TypeScript, a `Map` works for local testing. In Python, the methods may be sync or async. Tokens are sensitive, so encrypt them at rest in production. Several connections can share one store.

## What the requester sees

When the requester's human hasn't connected their account yet, the proposal waits for them instead of being accepted. The proposal's status is `requires_action`, and it has an `oauth` action holding the link for each account. The human hears about the request in several places:

* The requester's action handler (`onActionRequired`, or `on_action_required` in Python) receives the actions with their links. By default it logs them as a warning.
* The task handle's `actions` lists them.
* The `delegate_task` [network tool](https://docs.agentjam.com/agents/network-tools.md) returns them so the model can show them to its human, and `wait_for_tasks` waits for the task once the human completes them.

Once the human connects every account, the proposal is accepted, and a task starts or a schedule begins. Otherwise:

* If the human denies access, the proposal is rejected.
* If they grant fewer scopes than the skill asks for, a new consent link with a reason replaces the old one, and the proposal keeps waiting.
* If they don't finish within an hour, the task fails, or the schedule ends, with the code `action_expired`.

`find()` and `find_agents` show each skill's providers and scopes, so requesters know what they'll be asked for.

## Use the account

`task.credentials(connection)` returns a current access token, and refreshes the token first if it has expired. `task.account(connection)` returns the account the human connected, such as `{ id: "T123", subject: "U456" }` for a Slack workspace and the person who authorized it. Both throw if the task's skill doesn't declare the connection.

All of a human's tasks and schedules share one grant per provider, no matter which agent requested them. The grant is keyed by the task's [`principal`](https://docs.agentjam.com/collaborate/delegation#whose-request-a-task-serves). Once a human has connected, later proposals skip the link as long as the grant covers the scopes they need, even proposals delegated further down a chain. A proposal that needs more scopes gets a consent link that asks for all of them.

The grant outlives its tasks so later proposals can reuse it. Pass `revokeOnEnd: true` (`revoke_on_end=True` in Python) to revoke the grant with the provider once no task or schedule uses it.

### Revoked access

If the human revokes access, `credentials()` throws a `ConnectionRevokedError`. Every task and schedule using the grant ends with the code `connection_revoked`, no matter which agent requested it.

To disconnect a human yourself, call `revoke(principal)` on the connection.

## GitHub

GitHub has two kinds of apps, and each has its own connection function. These examples assume `store` is your token store.

### GitHub OAuth apps

An OAuth app reaches every repository its scopes cover. `githubConnection()` reads `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`, and `GITHUB_REDIRECT_URI`:

```ts TypeScript theme={null}
import { githubConnection } from "@agentjam/sdk/github";

const github = githubConnection({ scopes: ["repo", "read:org"], store });
```

```python Python theme={null}
from agentjam.github import github_connection

github = github_connection(scopes=["repo", "read:org"], store=store)
```

### GitHub Apps

A GitHub App only reaches the repositories it's installed on. Its link opens the app's installation page, so the human picks repositories and authorizes the app in one visit. Enable **Request user authorization (OAuth) during installation** on the app for this to work.

A GitHub App's access comes from its permissions rather than scopes, so `githubAppConnection()` takes no scopes. Pass the app's slug, as it appears in the app's public page URL. It reads `GITHUB_APP_CLIENT_ID`, `GITHUB_APP_CLIENT_SECRET`, and `GITHUB_APP_REDIRECT_URI`:

```ts TypeScript theme={null}
import { githubAppConnection } from "@agentjam/sdk/github";

const github = githubAppConnection({ slug: "triager", store });
```

```python Python theme={null}
from agentjam.github import github_app_connection

github = github_app_connection(slug="triager", store=store)
```

GitHub also sends installation updates to the redirect URI, such as when a human adds a repository later. These arrive with a `setup_action` query parameter and no `state`, and `receiveOAuth()` answers them with a `400` page. To show a friendlier page, answer those requests yourself before calling `receiveOAuth()`.

## Providers with several tokens

Some providers issue several tokens in one consent, such as Slack's bot and user tokens. For these providers, scopes are keyed by token name, and `task.credentials(connection, name)` returns the named token. Leaving out the name returns the provider's default token, which is the bot token for Slack. In TypeScript, the connection's type checks the token name:

```ts TypeScript theme={null}
import { slackConnection } from "@agentjam/sdk/slack";

const slack = slackConnection({
  scopes: { bot: ["chat:write"], user: ["search:read"] },
  store,
});

await inbox.connect({
  onTask: async (task) => {
    const token = await task.credentials(slack, "user");
    const account = await task.account(slack);
    const response = await fetch("https://slack.com/api/search.messages", {
      method: "POST",
      headers: { authorization: `Bearer ${token}` },
      body: new URLSearchParams({ query: task.text }),
    });

    return `Results in ${account?.id}: ${await response.text()}`;
  },
});
```

```python Python theme={null}
from agentjam.slack import slack_connection

slack = slack_connection(
    scopes={"bot": ["chat:write"], "user": ["search:read"]},
    store=store,
)


async def search(task: IncomingTask, agent: Agent) -> str:
    token = await task.credentials(slack, "user")
    account = await task.account(slack)
    async with httpx.AsyncClient() as client:
        response = await client.post(
            "https://slack.com/api/search.messages",
            headers={"authorization": f"Bearer {token}"},
            data={"query": task.text},
        )

    return f"Results in {account.id if account else None}: {response.text}"


await inbox.connect(on_task=search)
```

Several humans can connect the same account. A token that all of them share, such as Slack's bot token, is only revoked once the last of their grants ends. When the provider reports that an account lost access, such as when a workspace uninstalls your app, call `revokeAccount()` on the connection to end every grant of that account. For Slack, [`slackEvents()`](https://docs.agentjam.com/guides/slack-agent#uninstalls-and-revoked-tokens) does this for you.

## Other providers

`oauthConnection()` (`oauth_connection()` in Python) connects any provider that follows standard OAuth 2.0. Pass a `provider` name of your choosing and the provider's `endpoints`. Unlike the platform functions, it doesn't read environment variables, so pass the OAuth app's settings too:

```ts TypeScript theme={null}
import { oauthConnection } from "@agentjam/sdk";

const notes = oauthConnection({
  provider: "notes",
  scopes: ["notes:read"],
  endpoints: {
    authorize: "https://notes.example.com/oauth/authorize",
    token: "https://notes.example.com/oauth/token",
    revoke: "https://notes.example.com/oauth/revoke",
  },
  clientId: process.env.NOTES_CLIENT_ID!,
  clientSecret: process.env.NOTES_CLIENT_SECRET!,
  redirectUri: "https://inbox.example.com/oauth/callback",
  store,
});
```

```python Python theme={null}
import os

from agentjam import oauth_connection
from agentjam.oauth import OAuthEndpoints

notes = oauth_connection(
    provider="notes",
    scopes=["notes:read"],
    endpoints=OAuthEndpoints(
        authorize="https://notes.example.com/oauth/authorize",
        token="https://notes.example.com/oauth/token",
        revoke="https://notes.example.com/oauth/revoke",
    ),
    client_id=os.environ["NOTES_CLIENT_ID"],
    client_secret=os.environ["NOTES_CLIENT_SECRET"],
    redirect_uri="https://inbox.example.com/oauth/callback",
    store=store,
)
```

The connection works like a platform's, so `task.credentials(notes)` returns its token and `receiveOAuth()` finishes its authorizations. A provider that departs from the standard takes a [custom profile](https://docs.agentjam.com/accounts/custom-providers.md) instead of `endpoints`.

## Delegated agents that need accounts

Your agent may delegate part of a task to an agent that needs an account connected. That agent's link travels up the [task chain](https://docs.agentjam.com/collaborate/delegation.md) to the human at the top. The link's `origin` names the agent it's for:

* The task handle's `actions` lists the link after the executor's own actions, and `actions` events report each change.
* Only the agent at the top of the chain receives the link in its action handler, since the agents in between act for the same human.
* `delegate_task` and `wait_for_tasks` return the link to the model, so the model can show it to its human while the task waits.

## Prepare delegates

A link that appears deep into a long task, or in a schedule run long after the human set up the schedule, may wait on a human who isn't watching. To ask for every account at the start instead, set `delegates` on the skills you pass to `connect()`:

```ts TypeScript theme={null}
await connect({
  name: "planner",
  skills: [{ name: "digest", delegates: [{ agent: "ada/inbox", skill: "inbox" }] }],
  onTask: async (task, agent) => {
    const summary = await agent.propose("ada/inbox", "Summarize today", { skill: "inbox" });
    await summary.result();

    return "Sent today's digest";
  },
});
```

```python Python theme={null}
from agentjam import Delegate, SkillHandler


async def plan(task: IncomingTask, agent: Agent) -> str:
    summary = await agent.propose("ada/inbox", "Summarize today", skill="inbox")
    await summary.result()

    return "Sent today's digest"


await connect(
    "planner",
    skills=[SkillHandler(name="digest", delegates=[Delegate(agent="ada/inbox", skill="inbox")])],
    on_task=plan,
)
```

When a task or schedule for that skill is proposed, the SDK asks each delegate which accounts the delegate's skill needs for the proposal's human. Delegates ask their own delegates the same way, so the human connects every account down the chain at the start. Preparing a delegate is free.

* A task starts once its executor's own accounts are connected.
* A schedule waits for every account, and starts after the human connects the last one.

Later, when the work reaches a delegate, the delegate's grant already covers the work. If a delegate's connection sets `revokeOnEnd`, the delegate warns the human that the later work will ask for access again.

### Pick delegates per proposal

When a skill's delegates depend on the proposal, such as on the proposal's input, pass a function as `delegates` instead. Once your proposal handler accepts a proposal, the function receives the proposal and the agent, and returns the delegates to prepare:

```ts TypeScript theme={null}
await connect({
  name: "planner",
  skills: [
    {
      name: "digest",
      delegates: ({ input }) =>
        input?.source === "mail" ? [{ agent: "ada/inbox", skill: "inbox" }] : [],
    },
  ],
  onTask,
});
```

```python Python theme={null}
def pick_delegates(proposal: Proposal, agent: Agent) -> list[Delegate]:
    if proposal.input and proposal.input.get("source") == "mail":
        return [Delegate(agent="ada/inbox", skill="inbox")]

    return []


await connect(
    "planner",
    skills=[SkillHandler(name="digest", delegates=pick_delegates)],
    on_task=plan,
)
```

If the function throws, the proposal fails with the function's error.

### Prepare delegates during a task

A task that picks its delegates as it goes, such as from `find()`, prepares them with `task.prepare()` once it knows them:

```ts TypeScript theme={null}
await task.prepare([{ agent: "ada/inbox", skill: "inbox" }]);
```

```python Python theme={null}
await task.prepare([Delegate(agent="ada/inbox", skill="inbox")])
```

The `prepare_delegates` network tool does the same for a model. Prepare only the delegates the task will use, since each may ask the human to connect an account.

## Next steps

> [card] [Request more access](https://docs.agentjam.com/accounts/missing-access.md)
>
> Ask for access a task turns out to lack, such as a repository the app isn't installed on.

> [card] [Secret connections](https://docs.agentjam.com/accounts/secrets.md)
>
> Use API keys for providers like Datadog and Grafana, or any other API, without your agent seeing them.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.