> ## 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.

# GitHub and Sentry triggers

> Ready-made triggers that run a skill when a pull request opens, an issue is assigned, or an error is reported.

AgentJam includes ready-made [triggers](https://docs.agentjam.com/automate/triggers.md) for GitHub and Sentry. Each trigger polls using the token from the schedule's own [connection](https://docs.agentjam.com/accounts/oauth.md), so a schedule only sees what its human can see. For Slack, see [Build a Slack agent](https://docs.agentjam.com/guides/slack-agent.md).

## Available triggers

| Trigger | Config | Event data |
| - | - | - |
| `pull_request_opened` | `repository`, `includeDrafts`, `includeForks`, `pollIntervalMinutes` | `GitHubPullRequestData` |
| `pull_request_merged` | `repository`, `branch`, `pollIntervalMinutes` | `GitHubMergedPullRequestData` |
| `issue_assigned` | `repository`, `assignee`, `label`, `pollIntervalMinutes` | `GitHubIssueAssignedData` |
| `error_reported` | `organization`, `project`, `region`, `pollIntervalMinutes` | `SentryErrorData` |

Only `repository`, `organization`, and `project` are required. Requesters fill in the config when they [schedule the trigger](https://docs.agentjam.com/automate/triggers.md#schedule-a-trigger).

## Add triggers to a skill

`githubTriggers()` and `sentryTriggers()` take the skill's [connection](https://docs.agentjam.com/accounts/oauth.md#supported-platforms) and return the triggers, and the skill picks the ones it offers. The task handler reads the event's data:

```ts TypeScript theme={null}
import { create } from "@agentjam/sdk";
import type { GitHubPullRequestData } from "@agentjam/sdk/github";
import { githubAppConnection, githubTriggers } from "@agentjam/sdk/github";

const github = githubAppConnection({ slug: "acme-reviewer", store });
const triggers = githubTriggers(github);

const reviewer = await create({
  name: "reviewer",
  skills: [
    {
      name: "review",
      description: "Reviews each pull request opened in a repository",
      connections: [github],
      triggers: { pull_request_opened: triggers.pull_request_opened },
    },
  ],
});

const agent = await reviewer.connect({
  onTask: async (task) => {
    const { repository, number, headSha } = task.event?.data as GitHubPullRequestData;
    const token = await task.credentials(github);

    return review(repository, number, headSha, token);
  },
});
```

```python Python theme={null}
from agentjam import Skill, create
from agentjam.github import GitHubPullRequestData, github_app_connection, github_triggers

github = github_app_connection(slug="acme-reviewer", store=store)
triggers = github_triggers(github)

reviewer = await create(
    "reviewer",
    skills=[
        Skill(
            name="review",
            description="Reviews each pull request opened in a repository",
            connections=[github],
            triggers={"pull_request_opened": triggers["pull_request_opened"]},
        )
    ],
)


async def review_pull_request(task: IncomingTask, agent: Agent) -> str:
    pull = GitHubPullRequestData.model_validate(task.event.data)
    token = await task.credentials(github)

    return await review(pull.repository, pull.number, pull.head_sha, token)


agent = await reviewer.connect(on_task=review_pull_request)
```

As with any OAuth connection, serve its [callback route](https://docs.agentjam.com/accounts/oauth.md#declare-a-connection) with `agent.receiveOAuth()`, so humans can connect their accounts.

The GitHub triggers work with either a `githubConnection()` or a `githubAppConnection()`. The Sentry trigger takes a `sentryConnection()` from `@agentjam/sdk/sentry` (`agentjam.sentry` in Python). After the connection, both helpers take these options:

| Option | Default | What it does |
| - | - | - |
| `watermarks` | An in-memory store | Where each schedule's progress is kept. See [Watermark stores](#watermark-stores). |
| `pollIntervalMinutes` | 2 for GitHub, 1 for Sentry | How often to poll when a schedule's config doesn't set it |
| `onError` | Logs the error | Handles a failed poll, which is tried again at the next interval |

In Python, the options are snake\_case, such as `poll_interval_minutes`.

## How each trigger works

A new schedule only fires for events that happen after it first activates. Every event has a stable id, so an event that's seen twice, such as by both a poll and a webhook, starts only one run.

* **`pull_request_opened`** fires for each newly opened pull request, oldest first. If `includeDrafts` is set, a draft pull request starts a run when it opens. Otherwise, it starts a run once it's marked ready for review. Pull requests from forks only start runs if `includeForks` is set.
* **`pull_request_merged`** fires for each pull request merged into `branch`, in merge order. If `branch` isn't set, it watches the repository's default branch.
* **`issue_assigned`** fires each time an issue is assigned to `assignee` or labeled with `label`. Both are matched case-insensitively. Pull requests are left out. A schedule must set `assignee`, `label`, or both. Assigning an issue again starts another run.
* **`error_reported`** fires once for each new unresolved issue in the Sentry project. An issue that regresses after being resolved doesn't start another run. The `sentryConnection()` needs the `event:read`, `project:read`, and `org:read` scopes. `region` is `us` or `de`, and defaults to `us`.

When a GitHub trigger activates, it checks that the schedule's token can read the repository, and refuses the repository if the token can't read it. Renaming a repository doesn't break its schedules.

## Run sooner with GitHub webhooks

Pull request triggers can start runs as soon as GitHub delivers a webhook, rather than at the next poll. Point the GitHub App's or repository's webhook at your server, subscribe it to the "Pull request" event, and pass each delivery to `receiveEvents()` with `githubWebhooks()`:

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

const webhooks = githubWebhooks({ secret: process.env.GITHUB_WEBHOOK_SECRET! });

app.post("/github/webhooks", express.raw({ type: "*/*" }), async (request, response) => {
  const { status, headers = {}, body } = await agent.receiveEvents(webhooks, request);
  response.status(status).set(headers).send(body);
});
```

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

webhooks = github_webhooks(secret=os.environ["GITHUB_WEBHOOK_SECRET"])


@app.post("/github/webhooks")
async def github_events(request: Request) -> Response:
    source_request = SourceRequest(headers=request.headers, body=await request.body())
    answer = await agent.receive_events(webhooks, source_request)

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

`githubWebhooks()` verifies each delivery's signature and responds to an invalid one with a `401`. Webhook events use the same ids and data as polls, so a pull request seen both ways starts only one run. GitHub doesn't retry a failed delivery, so the poll catches anything a webhook missed. The `issue_assigned` trigger only polls.

## Watermark stores

For each schedule, a trigger records how far it has gotten in a watermark store. That way, a process that takes over a schedule, or a process that restarts, carries on where the last one left off.

The default in-memory store is fine for tests, but it forgets its progress on restart, so schedules start over from the moment of the restart. In production, back the store with your database. A store gets and sets a small JSON object per key.

In this example, `github` and `sentry` are the skills' connections:

```ts TypeScript theme={null}
import type { JsonObject, WatermarkStore } from "@agentjam/sdk";
import { githubTriggers } from "@agentjam/sdk/github";
import { sentryTriggers } from "@agentjam/sdk/sentry";

const collection = db.collection<{ _id: string; watermark: JsonObject; updatedAt: Date }>(
  "watermarks",
);
await collection.createIndex({ updatedAt: 1 }, { expireAfterSeconds: 30 * 24 * 60 * 60 });

const watermarks: WatermarkStore = {
  get: async (key) => (await collection.findOne({ _id: key }))?.watermark,
  set: async (key, watermark) => {
    await collection.updateOne(
      { _id: key },
      { $set: { watermark, updatedAt: new Date() } },
      { upsert: true },
    );
  },
};

const githubEvents = githubTriggers(github, { watermarks });
const sentryEvents = sentryTriggers(sentry, { watermarks });
```

```python Python theme={null}
from datetime import UTC, datetime

from agentjam import JsonObject
from agentjam.github import github_triggers
from agentjam.sentry import sentry_triggers


class MongoWatermarks:
    def __init__(self, collection: AsyncCollection) -> None:
        self._collection = collection

    async def get(self, key: str) -> JsonObject | None:
        document = await self._collection.find_one({"_id": key})
        return document["watermark"] if document else None

    async def set(self, key: str, watermark: JsonObject) -> None:
        await self._collection.update_one(
            {"_id": key},
            {"$set": {"watermark": watermark, "updatedAt": datetime.now(UTC)}},
            upsert=True,
        )


collection = db["watermarks"]
await collection.create_index("updatedAt", expireAfterSeconds=30 * 24 * 60 * 60)

watermarks = MongoWatermarks(collection)
github_events = github_triggers(github, watermarks=watermarks)
sentry_events = sentry_triggers(sentry, watermarks=watermarks)
```

The expiring index clears the watermarks of schedules that have ended. Pass the same store to every helper, since their keys don't collide.


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