# Connect to Contextual

These instructions apply to the current Admin Console.

{% hint style="info" %}
Contextual Workers are in early access and may not be available in your account. [Contact Contextual support](mailto:help@contextual.io) to request that Workers be enabled for your tenant.
{% endhint %}

Start with the [single-image HTTP quickstart](https://docs.contextual.io/build/contextual-workers/quickstart.md). Use Compose or a managed template when your application needs several services, platform features, or event processing.

## Configure a Custom Compose Worker

The following `compose.yaml` defines a service using the quickstart Dockerfile and public port 8080:

```yaml
x-contextual:
  version: 1
services:
  web:
    build: .
    x-contextual:
      public: 8080
```

Use `--compose compose.yaml` in place of `--build .` when creating or updating the Worker. Keep the Dockerfile's health check. The CLI processes `build:` declarations before submitting the Compose definition.

Contextual supports a subset of Compose, with up to 50 services. Several services in one Worker share a network and must use distinct ports. Only named volumes are supported.

A public service needs a readiness check. A service can use the image's `HEALTHCHECK`, a Compose `healthcheck`, or an HTTP check that needs no shell or HTTP client in the image:

```yaml
services:
  web:
    build: .
    x-contextual:
      public: 8080
      http_healthcheck:
        path: /health
        port: 8080
```

Compose variables such as `${NAME}` are not supported in a custom Compose file. Write `$$` for a literal `$`. The Worker's environment variables are already set on every service, except variables used by Compose secrets. A service's own `environment` values apply only to that service and override Worker variables with the same name. Environment names that start with `CONTEXTUAL_` are reserved for the platform.

Use the [x-contextual Specification](https://docs.contextual.io/build/contextual-workers/x-contextual-specification.md) and [Version 1 JSON Schemas](https://docs.contextual.io/build/contextual-workers/x-contextual-specification/json-schemas.md) when asking a coding agent to prepare a file.

## Request Platform Access

A custom service requests platform access through a service-level `x-contextual.features` list. Enable only the features the service uses. Each feature sets environment variables in the service that requests it, and in no other service:

| Feature | What the Service Receives |
| --- | --- |
| `native-object-api` | `CONTEXTUAL_NATIVE_OBJECT_URL`, `CONTEXTUAL_ORG_ID`, and the tenant's Agent OAuth client: `CONTEXTUAL_NATIVE_OBJECT_AUTH_DOMAIN`, `CONTEXTUAL_NATIVE_OBJECT_CLIENT_ID`, `CONTEXTUAL_NATIVE_OBJECT_CLIENT_SECRET`, and `CONTEXTUAL_NATIVE_OBJECT_AUDIENCE`. |
| `messaging` | The Worker's topic and subscription in `CONTEXTUAL_MESSAGING_TOPIC` and `CONTEXTUAL_MESSAGING_SUBSCRIPTION`, and the tenant's Pulsar connection settings in other `CONTEXTUAL_MESSAGING_*` variables. The tenant must use Pulsar messaging. |
| `messaging-producer` | The same messaging settings, for a service that only sends messages. |
| `keda` | No variables. Scales the Worker on its topic backlog. Requires `messaging` on the same service. See [Events and Schedules](#events-and-schedules). |
| `logging` | Connection settings for publishing the Worker's logs to the tenant log topic. A tenant without its own log topic receives none. |
| `platform-services` | `CONTEXTUAL_PLATFORM_SERVICES`, a JSON object of platform API endpoints, such as Files, Connections, Logs, and AI Search. Endpoints grant no permissions. |

For example, a service that needs direct Native Object API access declares:

```yaml
x-contextual:
  features: [native-object-api]
```

Place the `x-contextual.features` block under the service that needs Native Object API access, alongside `image` or the CLI's `build` declaration. Read platform addresses from these variables. Do not hard-code them.

{% hint style="warning" %}
Feature credentials are tenant-wide. `native-object-api` provides the tenant's Agent OAuth client, and `messaging` provides the tenant's messaging identity. Code that receives them can use all of their permissions. Anyone who can edit a Worker can deploy code that uses them, so grant Worker edit permission accordingly.
{% endhint %}

The `managed-event-worker`, `managed-http-worker`, and `managed-scheduled-worker` handler templates select the trigger and the available platform access; your application's `worker.json` defines its handlers. The template's host makes platform calls for your code, so your app requests no features and receives no credentials. See [Managed Workers](https://docs.contextual.io/build/contextual-workers/managed-workers.md).

### Read tenant records from a custom Worker

Enable `native-object-api` on the Compose service that reads records. The feature supplies the Native Object API address and Agent OAuth client. Use the Agent token to look up the tenant's `native-object-api` Connection. The Connection's credentials need Read access to the custom Object Types the Worker uses.

1. Get an Agent token with `POST https://$CONTEXTUAL_NATIVE_OBJECT_AUTH_DOMAIN/oauth/token`. Send `grant_type: client_credentials` in the JSON body. Set `client_id`, `client_secret`, and `audience` from `CONTEXTUAL_NATIVE_OBJECT_CLIENT_ID`, `CONTEXTUAL_NATIVE_OBJECT_CLIENT_SECRET`, and `CONTEXTUAL_NATIVE_OBJECT_AUDIENCE`. Use the response's `access_token`. See [Get and use an access token](https://docs.contextual.io/tenants/tenant-apis/authentication-and-permissions.md#get-and-use-an-access-token).
2. Read the Connection with `GET $CONTEXTUAL_NATIVE_OBJECT_URL/api/v1/api-configuration/native-object-api`. Send the Agent token as `Authorization: Bearer <token>` and set `x-org-id` to the value of `CONTEXTUAL_ORG_ID`. This request needs the Connection's credential fields, so omit `doNotDecrypt` and keep the response inside the Worker.
3. Get a token for record reads from that Connection. For `client-grant`, send a `client_credentials` request to `authEndpoint` using the Connection's `clientId` and `clientSecret` as `client_id` and `client_secret`. Include `audience` and `scope` if set, and use the Connection's configured content type or JSON by default. For `bearer`, use `bearerToken` as the record token.
4. Read a custom record with `GET $CONTEXTUAL_NATIVE_OBJECT_URL/api/v1/<type>/<id>?doNotDecrypt=true`. Send the record token from step 3 in the Authorization header and the same `x-org-id` header. Encode the type and record ID as URL path segments. The [`doNotDecrypt` parameter](https://docs.contextual.io/build/object-types/object-type-details/data-schema/secret.md) keeps secret values out of this response.

## Secrets and Configuration Files

Worker environment variables are stored encrypted, and every service receives them unless a Compose secret uses them. Set secret values in the admin console under **Environment variables**. The CLI's `--env` flag puts the value in your shell history.

To deliver a secret as a file, declare a Compose secret that names a Worker environment variable in upper case. The service reads it from `/run/secrets/<name>`:

```yaml
secrets:
  api_key:
    environment: API_KEY
services:
  web:
    build: .
    secrets: [api_key]
```

A variable used this way is delivered only as the file. Only the services that list the secret receive the file, and no service receives the variable as an environment variable. A secret that no service lists has no effect. Secrets with a `file:` source are not supported.

To deliver a configuration file, declare a Compose config. The CLI reads a `file:` source and submits its content. The service reads it, read-only, at the target path:

```yaml
configs:
  settings:
    file: ./settings.json
services:
  web:
    build: .
    configs:
      - source: settings
        target: /app/settings.json
```

Configuration files are limited to 64 KiB in total. Compose variables are not supported in their content.

## Events and Schedules

An event Worker consumes the topic named for its Worker ID, through the tenant's topic template. Send it events the same way you send events to an Agent with that ID.

For event processing, use the `managed-event-worker` template. The template delivers each event to your handler and acknowledges it only after the handler succeeds. A failed event is redelivered, and there is no dead-letter queue. Your handler can receive the same event more than once, so make repeat processing safe. See [Templates and Options](https://docs.contextual.io/build/contextual-workers/managed-workers/templates-and-options.md#how-results-are-settled).

A custom Compose service can consume the topic itself with `messaging` and `keda`. Configure its backlog scaling under the same service's `x-contextual.scaling`:

```yaml
services:
  consumer:
    build: .
    x-contextual:
      public: false
      features: [messaging, keda]
      scaling:
        minReplicas: 0
        maxReplicas: 3
```

The minimum defaults to 0, which scales the Worker to zero while the backlog is empty. A Worker with a public service needs a minimum of at least 1. A Compose service is public only when it sets `x-contextual.public`. Backlog scaling replaces the Worker's replica and CPU settings.

An [Object Type trigger](https://docs.contextual.io/build/object-types/object-type-details/triggers.md#send-a-trigger-to-a-worker) can send an event containing record data to an event Worker after a record is inserted, updated, or deleted. The trigger's **Agent** picker lists Workers that scale on their event backlog, such as Workers using `managed-event-worker`.

For a scheduled job, use a UTC cron schedule through `--schedule`, with an application or scheduled template that finishes after each tick. Scheduled Workers have no public endpoint. The quickstart HTTP server keeps running and is not a scheduled-job example. See [Scheduled Workers](https://docs.contextual.io/build/contextual-workers/about-workers.md#scheduled-workers) for run limits.

Find available template names and versions in the console's **Managed worker** fields. To build an event or scheduled handler, follow [Build Your First Managed Worker](https://docs.contextual.io/build/contextual-workers/managed-workers/get-started.md) and choose the template in [Templates and Options](https://docs.contextual.io/build/contextual-workers/managed-workers/templates-and-options.md). For a coding agent, see [Build with a Coding Agent](https://docs.contextual.io/build/contextual-workers/managed-workers/coding-agents.md).

## Records and Files

Keep durable application state in Native Objects or an external data store. See [Runtime Environment](https://docs.contextual.io/build/contextual-workers/about-workers.md#runtime-environment) for the writable paths and storage limits in a Worker.

A Worker receives platform credentials only through the features its services request. A managed Worker reads and writes records through its host without credentials. It moves large attachment files straight to and from the Files API, with a short-lived token for that one file. See [Platform Capabilities](https://docs.contextual.io/build/contextual-workers/managed-workers/capabilities.md).
