> Documentation index: https://metorial.com/llms.txt. Every page is available as Markdown by adding .md to its URL.

# Run your own agent code in CI or a cron job with the Metorial SDK
URL: https://metorial.com/docs/build/guides/run-agents-in-ci-and-background-jobs

For agent code built on the Metorial SDK: the job reads a secret API key from an environment variable and passes stored provider auth config IDs to its session.

---

When agent code you wrote with the Metorial SDK runs in CI, a cron job or a background worker, it authenticates with a secret API key from an environment variable and creates its own session. Nothing opens a browser at run time. For apps that need a user's consent, the user connects once in your app, and the job passes the stored provider auth config ID when it creates the session.

**What you'll learn**

* Which steps need a browser and which do not
* How to create a key for the job and find the stored connection
* How to make the job fail clearly when something is missing

**Before you start**

* [Install the CLI and sign in](https://metorial.com/docs/build/sandboxes#install-the-tools)
* A provider deployment for each app the agent uses. `metorial-admin providers deployments list` shows them.

## What needs a browser

| Step                                                       | Browser | When                             |
| ---------------------------------------------------------- | ------- | -------------------------------- |
| Authenticate to Metorial                                   | No      | Every run, with the API key      |
| Create a session and call tools                            | No      | Every run                        |
| A user's OAuth consent for an app                          | Yes     | Once, ahead of time, in your app |
| Shared credentials such as an API key or a service account | No      | An admin sets them once          |

The job cannot fix a missing connection. It should stop and say which app needs attention.

## Set up the job

### 1. Create a key for the job

Give each job its own key, in the instance it runs against. Copy the secret from the output. It is shown only once.

```bash
metorial-admin instance list
metorial-admin api-keys create \
  --type instance_access_token_secret \
  --instance-id <instance-id> \
  --name nightly-agent
```

Useful options:

* `--expires-at`: sets an expiry date.
* `--ip-filters`: restricts the key to the addresses you list.

### 2. Find the stored connection

For an app that needs a sign-in, the job needs a provider auth config ID. Per-user IDs come from your database, where [the setup flow](https://metorial.com/docs/build/sdk/oauth) stored them. For a shared service account, connect it once and look up its ID:

```bash
metorial-admin providers auth-configs list --provider-deployment-id pde_your_deployment_id
```

Providers that use an API key set on the deployment need no ID.

### 3. Store the values as secrets

Put the key in your CI system's secret store and expose it as `METORIAL_API_KEY`. In GitHub Actions:

```yaml
name: nightly-agent
on:
  schedule:
    - cron: '0 6 * * *'
jobs:
  run-agent:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-node@v7
        with:
          node-version: 24
      - run: npm ci
      - run: npx tsx job.ts
        env:
          METORIAL_API_KEY: ${{ secrets.METORIAL_API_KEY }}
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
          SLACK_PROVIDER_DEPLOYMENT_ID: ${{ vars.SLACK_PROVIDER_DEPLOYMENT_ID }}
          SLACK_AUTH_CONFIG_ID: ${{ secrets.SLACK_AUTH_CONFIG_ID }}
```

### 4. Write the job

Install the packages, then save the file as `job.ts` or `job.py`. It exits with code 1 on any failure, so the run shows as failed.

**TypeScript**

```bash
npm install metorial @metorial/ai-sdk ai @ai-sdk/openai
npm install --save-dev tsx
```

```typescript
import { openai } from '@ai-sdk/openai';
import { metorialAiSdk } from '@metorial/ai-sdk';
import { generateText, stepCountIs } from 'ai';
import Metorial from 'metorial';

let metorial = new Metorial({ apiKey: process.env.METORIAL_API_KEY! });

try {
  let session = await metorial.connect({
    adapter: metorialAiSdk(),
    providers: [
      {
        providerDeploymentId: process.env.SLACK_PROVIDER_DEPLOYMENT_ID!,
        providerAuthConfigId: process.env.SLACK_AUTH_CONFIG_ID!
      }
    ]
  });

  let result = await generateText({
    model: openai('gpt-4o-mini'),
    prompt: 'Post a one-line status update to the #ops channel: nightly job finished.',
    stopWhen: stepCountIs(10),
    tools: session.tools()
  });

  console.log(result.text);
} catch (error) {
  console.error(error instanceof Error ? error.message : error);
  process.exit(1);
}
```

**Python**

```bash
pip install metorial openai-agents
```

```python
import asyncio
import os
import sys

from agents import Agent, Runner
from metorial import Metorial, MetorialError, metorial_openai_agents


async def main() -> None:
    metorial = Metorial(api_key=os.environ["METORIAL_API_KEY"])

    session = await metorial.connect(
        adapter=metorial_openai_agents(),
        providers=[
            {
                "provider_deployment_id": os.environ["SLACK_PROVIDER_DEPLOYMENT_ID"],
                "provider_auth_config_id": os.environ["SLACK_AUTH_CONFIG_ID"],
            }
        ],
    )

    agent = Agent(
        name="Nightly job",
        instructions="Use the Metorial tools to complete the task.",
        tools=session.tools(),
    )
    result = await Runner.run(
        agent,
        "Post a one-line status update to the #ops channel: nightly job finished.",
    )
    print(result.final_output)


try:
    asyncio.run(main())
except MetorialError as error:
    print(f"Metorial error: {error}", file=sys.stderr)
    sys.exit(1)
```

## Check it worked

The job log ends with the agent's final text and exit code 0. List the tool calls it made:

```bash
metorial-admin sessions tool-calls list \
  --provider-deployment-id pde_your_deployment_id \
  --limit 5
```

To see failures, run `metorial-admin sessions errors list --limit 5`.

## Troubleshooting

### `Invalid API key`

`METORIAL_API_KEY` is empty, truncated or from another instance. The TypeScript SDK prints `[METORIAL ERROR]: unauthorized - Invalid API key`, and the Python SDK prints `Invalid API key status=401`. Check that the secret is mapped into the job step.

### `API key is expired or has been revoked`

The key reached its expiry or was revoked. Create a new one and update the CI secret. `metorial-admin api-keys rotate` replaces a key you still have access to.

### `This API key is not allowed from your IP address`

The key has IP filters, and the runner's address is not among them. Hosted runners often use a different address on each run.

### `Provider requires an auth config to be provided`

The session included a provider deployment that needs a sign-in, and the provider auth config ID was missing. Check that the user finished the setup flow and that the ID reached the job.

## Next steps

* [Let each user connect their own account](https://metorial.com/docs/build/sdk/oauth): collect consent in your app and store the ID
* [Limit the tools an agent can use](https://metorial.com/docs/build/guides/limit-agent-tools): give the job only the tools it needs
* [Organizations, projects, and environments](https://metorial.com/docs/build/operate/organizations-and-projects): production and sandbox instances and their keys