# Call Platform Services

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 %}

`services.request` is the escape hatch to the platform's own HTTP APIs. It sends one JSON or text request to any service the Worker is granted. That includes services with no typed capability, such as Logs, Observability, Agents, and the Native Object Registry. It also includes services the typed capabilities already use, such as Native Objects, Files, the AI Gateway, and AI Search, when you need an endpoint or option their helpers don't offer. The host authenticates the request, so your code never handles a platform credential. A new endpoint on a granted service needs no adapter or template release.

`services.request` needs managed template 0.10.0 or later and an adapter from the same release. See [Release Versions](https://docs.contextual.io/build/contextual-workers/managed-workers.md#release-versions). On an earlier template, the call fails with `contract` (`unsupported-method`).

Prefer a typed capability when it does what you need. The typed capabilities page through results, stream large files, recover transfers, and check Native Object restrictions for you. `services.request` is limited to JSON or text bodies of 1 MiB, and on Native Objects to routes that name a type. See [Limits and Retries](#limits-and-retries) and [Native Object Rules](#native-object-rules).

## Grant the Services

A Worker can call only the services in its `PLATFORM_SERVICES` option. The option is a comma-separated list of service names. With no value, every request is refused. Every managed template already gives the host the service catalog, through its `platform-services` feature, so this option is the only thing to set. It decides which catalog services your code may call with `services.request`. The typed capabilities and your declared connections don't need it: the host reaches Native Objects, Files, the AI Gateway, AI Search, and the Connections API for them whatever the option says. Grant only the services the app uses:

```sh
ctxl workers create order-sync \
  --size small \
  --managed managed-event-worker:0.10.0 \
  --build .worker-image \
  --option PLATFORM_SERVICES=logsApi,observabilityApi \
  --config-id my-config \
  --pretty
```

To change the grant later, run `ctxl workers update <worker-id> --option PLATFORM_SERVICES=<names>`. In the admin console, set the option in the **Managed worker** fields.

These services are in the catalog:

| Service | API |
| --- | --- |
| `nativeObjectApi` | Native Objects. Use it for routes the record and attachment capabilities don't cover. |
| `nativeObjectRegistryApi` | Native Object Registry: object types and their definitions |
| `agentsApi` | Agents |
| `logsApi` | Tenant logs |
| `observabilityApi` | Observability metrics |
| `notificationsApi` | Notifications (JSON requests only, no event stream) |
| `filesApi` | Files. Use the attachment capabilities for transfers. |
| `aiGatewayApi` | AI Gateway, for endpoints beyond the AI capability |
| `aiSearchApi` | AI Search, for endpoints beyond `aiSearch.query` |

Only the listed services are supported. `agentsApi` and `nativeObjectRegistryApi` are available only in environments whose catalog includes them. `connectionsApi` cannot be granted: a Worker calls a third-party API only through a declared connection alias. See [Connections](https://docs.contextual.io/build/contextual-workers/managed-workers/capabilities.md#connections).

## Send a Request

Pass the service name, the HTTP method, and the path. The path starts with `/` and includes the API version and any URL-encoded query string. Optional parameters are `body` (a JSON value), `headers`, `responseType` (`json` or `text`), and `retryUnauthorized`.

{% tabs %}
{% tab title="TypeScript" %}
```ts
const response = await context.services!.request("logsApi", "POST", "/api/v1/$page/logs", {
  body: { pageSize: 10 },
})
if (response.status !== 200) throw new Error(`Logs returned ${response.status}`)
const page = response.body as { items?: unknown[] }
```
{% endtab %}
{% tab title="Rust" %}
```rust
use contextual_worker::ServicesRequestOptions;

let response = ctx.services().request("logsApi", "POST", "/api/v1/$page/logs", ServicesRequestOptions {
    body: Some(json!({"pageSize": 10})),
    ..Default::default()
}).await?;
anyhow::ensure!(response["status"] == 200, "Logs returned {}", response["status"]);
let page = &response["body"];
```
{% endtab %}
{% tab title="Go" %}
```go
var response struct {
	Status int             `json:"status"`
	Body   json.RawMessage `json:"body"`
}
if err := c.Services().Request("logsApi", "POST", "/api/v1/$page/logs",
	&worker.ServicesRequestOptions{Body: map[string]any{"pageSize": 10}}, &response); err != nil {
	return nil, err
}
if response.Status != 200 {
	return nil, fmt.Errorf("Logs returned %d", response.Status)
}
```
{% endtab %}
{% tab title="Python" %}
```python
response = await ctx.services.request("logsApi", "POST", "/api/v1/$page/logs", body={"pageSize": 10})
if response["status"] != 200:
    raise RuntimeError(f"Logs returned {response['status']}")
page = response["body"]
```
{% endtab %}
{% endtabs %}

The reply is `{ status, headers, body }`:

* **`status`** is the backend's HTTP status. A 4xx or 5xx from the backend is a reply, not a failure. Check it.
* **`headers`** has only `content-type`, `etag`, `retry-after`, and `x-request-id`.
* **`body`** is parsed JSON by default, or `null` for an empty body. With `responseType: "text"` it is the text. A backend error or redirect that isn't JSON is returned as text with its status.

A redirect is returned as its 3xx status. The host does not follow it.

### Set the Options

The optional parameters are spelled for each language:

| Language | Options |
| --- | --- |
| TypeScript | An object: `{ body, headers, responseType, retryUnauthorized }` |
| Rust | `ServicesRequestOptions { body, headers, response_type, retry_unauthorized, ..Default::default() }`. Each field is an `Option`; `body` and `headers` are `serde_json::Value`. |
| Go | `&worker.ServicesRequestOptions{Body, Headers, ResponseType, RetryUnauthorized}`, or `nil`. The reply is decoded into the pointer you pass last. |
| Python | Keyword arguments: `body=`, `headers=`, `response_type=`, `retry_unauthorized=` |

### Update a Native Object Record with a Hash Guard

Prefer `records.patch` for this. When you need a Native Object route that has no typed capability, send the hash you read in `x-if-hash-match`. Native Object ignores the standard `if-match` header. A stale hash returns 412, which is a reply, not a failure:

{% tabs %}
{% tab title="TypeScript" %}
```ts
const response = await context.services!.request("nativeObjectApi", "PATCH", `/api/v1/orders/${orderId}`, {
  headers: { "x-if-hash-match": recordHash },
  body: [{ op: "set", path: "/status", value: "processed" }],
})
if (response.status === 412) {
  // Someone changed the record. Read it again before you retry.
}
```
{% endtab %}
{% tab title="Rust" %}
```rust
use contextual_worker::ServicesRequestOptions;

let response = ctx.services().request("nativeObjectApi", "PATCH", &format!("/api/v1/orders/{order_id}"), ServicesRequestOptions {
    headers: Some(json!({"x-if-hash-match": record_hash})),
    body: Some(json!([{"op": "set", "path": "/status", "value": "processed"}])),
    ..Default::default()
}).await?;
if response["status"] == 412 {
    // Someone changed the record. Read it again before you retry.
}
```
{% endtab %}
{% tab title="Go" %}
```go
var response struct {
	Status int `json:"status"`
}
if err := c.Services().Request("nativeObjectApi", "PATCH", "/api/v1/orders/"+orderID, &worker.ServicesRequestOptions{
	Headers: map[string]string{"x-if-hash-match": recordHash},
	Body:    []map[string]any{{"op": "set", "path": "/status", "value": "processed"}},
}, &response); err != nil {
	return nil, err
}
if response.Status == 412 {
	// Someone changed the record. Read it again before you retry.
}
```
{% endtab %}
{% tab title="Python" %}
```python
response = await ctx.services.request(
    "nativeObjectApi", "PATCH", f"/api/v1/orders/{order_id}",
    headers={"x-if-hash-match": record_hash},
    body=[{"op": "set", "path": "/status", "value": "processed"}],
)
if response["status"] == 412:
    pass  # Someone changed the record. Read it again before you retry.
```
{% endtab %}
{% endtabs %}

### Raw Platform Call

`services.request` is also a raw platform call, with the same parameters as one object. See [Raw Platform Calls](https://docs.contextual.io/build/contextual-workers/managed-workers/raw-platform-calls.md):

```ts
const reply = await context.platform!.call("services.request", {
  service: "logsApi", method: "POST", path: "/api/v1/$page/logs", body: { pageSize: 10 },
})
```

## Headers

Your code can add only these headers: `accept`, `accept-language`, `content-type`, `if-match`, `x-if-hash-match`, `if-none-match`, `if-modified-since`, `if-unmodified-since`, `prefer`, `idempotency-key`, and `x-request-id`. `content-type` must be a JSON type, such as `application/json` or `application/merge-patch+json`. The host sets the authorization, tenant, and correlation headers. Any other header is refused with `validation` (`header-not-allowed`).

## Limits and Retries

* A request body can be at most 1 MiB of JSON. A response can be at most 1 MiB.
* A request can have at most 32 added headers, in at most 8 KiB.
* Each request must finish within 20 seconds, and within the invocation's own deadline.
* The host retries once after a 401 with a renewed token, for GET, HEAD, and OPTIONS only. For other methods, pass `retryUnauthorized: true`, and only when sending the request twice is safe.
* The host does not retry a dropped connection, a 429, or a 5xx.
* A failed or timed-out write can have taken effect. The failure has `effectMayHaveOccurred`. Check the result before you retry.

Binary and multipart bodies, server-sent events, WebSockets, and streaming are not supported. Use the attachment, cloud storage, and AI capabilities for large data.

## Worker Identity

The host chooses the credentials from the service, never from your request:

| Service | Credentials |
| --- | --- |
| `nativeObjectApi` and `aiSearchApi` | The tenant's managed Native Object connection |
| Every other service | The Worker's own OAuth client |

Worker identity uses the tenant-wide platform OAuth client. The host manages its tokens, and each backend applies its authentication and authorization checks to that identity. `PLATFORM_SERVICES` allows calls through `services.request`; it does not change the identity's backend permissions. The host never falls back to other credentials.

If a request returns 401 or 403, inspect the backend's error and confirm the target tenant, service, and resource. If the failure remains unresolved and appears to involve the Worker's managed credentials or permissions, [contact Contextual support](mailto:help@contextual.io) to investigate.

The same split applies to the typed capabilities. Records, attachments, and AI Search use the managed Native Object connection. AI generation, AI uploads, tool sessions, and loading your bound connections use the Worker's own client.

## Native Object Rules

A request to `nativeObjectApi` must use a route that names a concrete object type, such as `/api/v1/orders`, `/api/v1/$page/orders`, or `/api/v1/$versions/orders/<record-id>`. The host refuses:

* Routes across all types, such as `$versions`, `$audit-trail`, and `$attachments` without a type, even when the body names a type
* Connection records (`api-configuration`), in any case or encoding, in the path or query
* Revealing secret fields (`$secrets`)
* Unknown route prefixes, encoded `/` or `\` separators, and double-encoded paths

When the Worker's Native Object access is limited to specific types or is read-only, every `services.request` is refused. Use the typed capabilities, which check those restrictions.

## Refusals

The host checks each request before it sends anything. A refused request is a `PlatformError`:

| Code and Reason | Cause | What to Do |
| --- | --- | --- |
| `authorization`, `service-not-granted` | The service is not in `PLATFORM_SERVICES`. | Add it to the option. |
| `authorization`, `service-not-configured` | The service is not in this environment's catalog. | [Contact Contextual support](mailto:help@contextual.io) to check whether the service is available. |
| `authorization`, `service-not-allowed` | The request goes to the Connections API. | Use a declared connection alias. |
| `authorization`, `native-object-restricted` | Native Object restrictions are configured for the Worker. | Use the typed record capabilities. |
| `authorization`, `native-object-type-required` | The Native Object route does not name a concrete type, or is not a known route. | Use a route with a type, and query each type separately. |
| `authorization`, `connection-records` | The path or query names Connection records. | Use a declared connection alias. |
| `validation`, `header-not-allowed` | The request adds a header that is not allowed. | Remove the header. |
| `validation`, `content-type-not-json` | `content-type` is not a JSON type. | Send JSON. |
| `validation`, `header-limit` or `payload-too-large` | Too many headers, or a body over 1 MiB. | Reduce the request. |

A refusal has `retryable` false. Catch it and handle it, or let it fail the invocation.

## Find a Service's Address

`services.resolve` returns a service's URL. It needs no grant and gives no access. A service that isn't in the catalog fails with `authorization` (`service-not-configured`), so you can check whether an optional service is available:

{% tabs %}
{% tab title="TypeScript" %}
```ts
const { url } = await context.services!.resolve("observabilityApi")
```
{% endtab %}
{% tab title="Rust" %}
```rust
let service = ctx.services().resolve("observabilityApi").await?;
```
{% endtab %}
{% tab title="Go" %}
```go
var service struct {
	URL string `json:"url"`
}
if err := c.Services().Resolve("observabilityApi", &service); err != nil {
	return nil, err
}
```
{% endtab %}
{% tab title="Python" %}
```python
service = await ctx.services.resolve("observabilityApi")
```
{% endtab %}
{% endtabs %}
