# Ship your AI Inbox, AI Workflow, AI Expert, AI Council, AI Researcher, AI Analyst, AI Predictor, AI Author, AI Estimator, or AI Auditor on Contextual.

Contextual simplifies the development, deployment, operations, and scaling of the AI-enabled services behind your applications, automations, and integrations.

[Deploy your first Worker](https://docs.contextual.io/build/contextual-workers/quickstart.md) · [Browse the docs](https://docs.contextual.io/welcome.md)

Example Worker status: ai-inbox is running on 2 small instances, classifying incoming email and creating invoice records.

## The code and data behind your solution.

### Workers

Workers run the code behind your solution in TypeScript, Rust, Go, or Python. Contextual builds, deploys, and scales your Worker and provides its logs.

[About Workers](https://docs.contextual.io/build/contextual-workers/about-workers.md)

`main.rs`:

```rust
use contextual_worker::{Worker, json};

fn main() -> std::process::ExitCode {
    Worker::new("hello-managed", env!("CARGO_PKG_VERSION"))
        .handler("default", |_, _| async {
            Ok(json!({
                "status": 200,
                "headers": {"content-type": "text/plain"},
                "body": "Hello from Contextual",
            }))
        })
        .run()
}
```

`handler.ts`:

```typescript
export default {
  apiVersion: "1",
  name: "hello-managed",
  version: "1.0.0",
  parseConfig: (config: unknown) => config,
  async run() {
    return {
      status: 200,
      headers: { "content-type": "text/plain" },
      body: "Hello from Contextual",
    }
  },
}
```

`main.go`:

```go
package main

import (
    "context"
    "os"

    "contextual.io/worker"
)

func main() {
    w := worker.New("hello-managed", "1.0.0")
    w.Handle("default", func(
        _ context.Context, _ worker.Event, _ *worker.Context,
    ) (any, error) {
        return map[string]any{
            "status":  200,
            "headers": map[string]string{"content-type": "text/plain"},
            "body":    "Hello from Contextual",
        }, nil
    })
    os.Exit(w.Run())
}
```

`main.py`:

```python
from contextual_worker import Worker

worker = Worker("hello-managed", "1.0.0")


@worker.handler("default")
async def default(event, ctx):
    return {
        "status": 200,
        "headers": {"content-type": "text/plain"},
        "body": "Hello from Contextual",
    }
```

### Object Types and Records

Bring your business data into your solution as records. Define custom Object Types as JSON schemas with validation and versions.

Your tenant provides an API for every Object Type so your Workers can read and write records right away.

[Object Types](https://docs.contextual.io/build/object-types.md)

`main.rs`:

```rust
use contextual_worker::{Context, Value, anyhow::{Context as _, Result}, json};

pub async fn approve_invoice(ctx: &Context, id: &str) -> Result<Value> {
    let records = ctx.records();
    let invoice = records.get("invoices", id, Default::default()).await?;
    let hash = invoice["_metaData"]["hash"].as_str().context("Missing record hash")?;
    let patch = json!([{"op": "add", "path": "/status", "value": "approved"}]);
    records.patch("invoices", id, patch, hash).await
}
```

`handler.ts`:

```typescript
import type { Context } from "./worker-types"

export async function approveInvoice(context: Context<unknown>, id: string) {
  const records = context.records!
  const invoice = await records.get("invoices", id)
  const hash = invoice._metaData?.hash
  if (!hash) throw new Error("Missing record hash")
  return records.patch("invoices", id, [
    { op: "add", path: "/status", value: "approved" },
  ], hash)
}
```

`main.go`:

```go
package main

import (
	"errors"

	"contextual.io/worker"
)

func approveInvoice(c *worker.Context, id string) (map[string]any, error) {
	records := c.Records()
	var invoice struct {
		MetaData struct{ Hash string } `json:"_metaData"`
	}
	if err := records.Get("invoices", id, nil, &invoice); err != nil {
		return nil, err
	}
	if invoice.MetaData.Hash == "" {
		return nil, errors.New("missing record hash")
	}

	patch := []map[string]any{{"op": "add", "path": "/status", "value": "approved"}}
	var updated map[string]any
	err := records.Patch("invoices", id, patch, invoice.MetaData.Hash, &updated)
	return updated, err
}
```

`main.py`:

```python
from contextual_worker import Context


async def approve_invoice(ctx: Context, invoice_id: str):
    invoice = await ctx.records.get("invoices", invoice_id)
    revision = invoice["_metaData"]["hash"]
    patch = [{"op": "add", "path": "/status", "value": "approved"}]
    return await ctx.records.patch("invoices", invoice_id, patch, revision)
```

## Ship your first Worker in minutes.

1. **Install the CLI**
2. **Connect to your tenant**
3. **Create the Worker**
4. **Call it and read the logs**

[Read the full guide](https://docs.contextual.io/build/contextual-workers/quickstart.md)

```console
$ npm install -g @contextual-io/cli
$ ctxl --version
@contextual-io/cli/0.16.0 darwin-arm64 node-v24.11.0
$ ctxl config add prod --tenant-id acme-prod
$ ctxl config use prod
$ ctxl config login
Logged in as you@acme.com.
Welcome to Contextual!
$ ctxl workers configure-docker --pretty
{
  "dockerConfig": "/Users/you/.docker/config.json",
  "hosts": [
    "images.acme-prod.my.contextual.io",
    "images.contextual.io"
  ]
}
$ ctxl workers create hello-worker --size small --build . \
    --env "GREETING=Hello from Contextual" --config-id prod --pretty
[+] Building 9.4s (8/8) FINISHED
The push refers to repository [images.acme-prod.my.contextual.io/hello-worker]
build-20261118170212: digest: sha256:9c1e… size: 1784
{
  "id": "hello-worker",
  "version": 1,
  "image": "images.acme-prod.my.contextual.io/hello-worker:build-20261118170212@sha256:9c1e…"
}
$ curl --fail "$WORKER_URL/"
{"greeting":"Hello from Contextual"}
$ ctxl workers logs hello-worker --config-id prod
[hello-worker-6d4f9c7b8-k2x9p/worker] Listening on port 8080
[hello-worker-6d4f9c7b8-k2x9p/worker] Handled GET /
```

## AI is one call away.

Classify, extract, answer, and act without managing keys or models.

### Generate

Classify a message or extract an invoice into your own schema. Use a configured AI Route to choose the provider, model, retries, and fallback.

[AI Routes](https://docs.contextual.io/connect/ai-routes.md)

### Search

Find the passages that answer a question from your own documents. Use a Search Profile and a named index to apply the retrieval settings you configured.

[AI Search](https://docs.contextual.io/connect/ai-search.md)

### Tools

Give an agent tools that act in your other systems. The model calls functions your handler implements.

[Platform Capabilities](https://docs.contextual.io/build/contextual-workers/managed-workers/capabilities.md#tools)

### AI Calls

Run a saved prompt by ID and use a label such as stable to control its version. The example needs AI Calls enabled and managed host 0.18.0 or later.

[Explore AI Calls](https://docs.contextual.io/connect/ai-calls.md)

`Generate · main.rs`:

```rust
use contextual_worker::{Context, Value, anyhow::Result, json};

pub async fn answer(ctx: &Context, route_id: &str, question: &str) -> Result<Value> {
    ctx.ai().generate(json!({
        "route": route_id,
        "system": "Answer in one sentence.",
        "prompt": question,
        "maxTokens": 128,
    })).await
}
```

`Search · main.rs`:

```rust
use contextual_worker::{AiSearchQueryOptions, Context, Value, anyhow::Result};

pub async fn search(
    ctx: &Context, profile_id: &str, index_id: &str, question: &str,
) -> Result<Value> {
    let options = AiSearchQueryOptions {
        index_id: Some(index_id.into()),
        top_k: Some(5),
    };
    let result = ctx.ai_search().query(profile_id, question, options).await?;
    Ok(result["items"].clone())
}
```

`Tools · main.rs`:

```rust
use contextual_worker::{Context, Value, anyhow::Result, json};

pub async fn answer_with_tools(ctx: &Context, route_id: &str, question: &str) -> Result<Value> {
    let request = json!({
        "route": route_id,
        "system": "Use lookup_order for shipping status. If it returns unknown, say so.",
        "prompt": question,
        "maxSteps": 4,
        "timeoutMs": 15000,
        "tools": {
            "lookup_order": {
                "description": "Read an order's shipping status",
                "inputSchema": {
                    "type": "object",
                    "properties": { "id": { "type": "string" } },
                    "required": ["id"],
                },
            },
        },
    });

    ctx.ai().generate_with_tools(request, |_, args| async move {
        let status = if args["id"] == "order-2041" { "shipped" } else { "unknown" };
        Ok(json!({ "status": status }))
    }).await
}
```

`AI Calls · main.rs`:

```rust
use contextual_worker::{Context, Value, anyhow::Result, json};

pub async fn summarize_order(ctx: &Context, note: &str) -> Result<Value> {
    let request = json!({
        "call": { "id": "order-summary", "label": "stable" },
        "variables": { "note": note },
    });
    let reply = ctx.platform_call("ai.generateCall", request).await?;
    Ok(reply["value"].clone())
}
```

`Generate · handler.ts`:

```typescript
import type { Context } from "./worker-types"

export async function answer(context: Context<unknown>, routeId: string, question: string) {
  return context.ai!.generate({
    route: routeId,
    system: "Answer in one sentence.",
    prompt: question,
    maxTokens: 128,
  })
}
```

`Search · handler.ts`:

```typescript
import type { Context } from "./worker-types"

export async function search(
  context: Context<unknown>, profileId: string, indexId: string, question: string,
) {
  const result = await context.aiSearch!.query(profileId, question, { indexId, topK: 5 })
  return result.items
}
```

`Tools · handler.ts`:

```typescript
import type { Context } from "./worker-types"

export async function checkOrder(context: Context<unknown>, routeId: string, question: string) {
  return context.ai!.generateWithTools({
    route: routeId,
    system: "Use lookup_order for shipping status. If it returns unknown, say so.",
    prompt: question,
    maxSteps: 4,
    timeoutMs: 15000,
    tools: {
      lookup_order: {
        description: "Look up an order's status",
        inputSchema: {
          type: "object",
          properties: { id: { type: "string" } },
          required: ["id"],
        },
      },
    },
  }, async (name, args) => {
    if (name !== "lookup_order") throw new Error("Unexpected tool")
    const { id } = args as { id: string }
    return { id, status: id === "order-2041" ? "shipped" : "unknown" }
  })
}
```

`AI Calls · handler.ts`:

```typescript
import type { Context } from "./worker-types"

export async function summarizeOrder(context: Context<unknown>, note: string) {
  const reply = await context.platform!.call("ai.generateCall", {
    call: { id: "order-summary", label: "stable" },
    variables: { note },
  })
  if (typeof reply !== "object" || reply === null || !("ok" in reply)
    || reply.ok !== true || !("value" in reply)) {
    throw new Error("AI Call failed", { cause: reply })
  }
  return reply.value
}
```

`Generate · main.go`:

```go
package main

import "contextual.io/worker"

func answer(c *worker.Context, routeID, question string) (map[string]any, error) {
	return c.AI().Generate(map[string]any{
		"route":     routeID,
		"system":    "Answer in one sentence.",
		"prompt":    question,
		"maxTokens": 128,
	})
}
```

`Search · main.go`:

```go
package main

import "contextual.io/worker"

func search(c *worker.Context, profileID, indexID, question string) (any, error) {
	options := &worker.AISearchQueryOptions{IndexID: indexID, TopK: 5}
	var result map[string]any
	if err := c.AISearch().Query(profileID, question, options, &result); err != nil {
		return nil, err
	}
	return result["items"], nil
}
```

`Tools · main.go`:

```go
package main

import (
	"context"

	"contextual.io/worker"
)

func answerWithTools(c *worker.Context, routeID, question string) (map[string]any, error) {
	request := map[string]any{
		"route":     routeID,
		"system":    "Use lookup_order for shipping status. If it returns unknown, say so.",
		"prompt":    question,
		"maxSteps":  4,
		"timeoutMs": 15000,
		"tools": map[string]any{
			"lookup_order": map[string]any{
				"description": "Read an order's shipping status",
				"inputSchema": map[string]any{
					"type":       "object",
					"properties": map[string]any{"id": map[string]any{"type": "string"}},
					"required":   []string{"id"},
				},
			},
		},
	}

	return c.AI().GenerateWithTools(request,
		func(_ context.Context, _ string, args map[string]any) (any, error) {
			status := "unknown"
			if args["id"] == "order-2041" {
				status = "shipped"
			}
			return map[string]any{"status": status}, nil
		},
	)
}
```

`AI Calls · main.go`:

```go
package main

import "contextual.io/worker"

func summarizeOrder(c *worker.Context, note string) (any, error) {
	request := map[string]any{
		"call":      map[string]any{"id": "order-summary", "label": "stable"},
		"variables": map[string]any{"note": note},
	}
	var reply struct {
		Value any `json:"value"`
	}
	if err := c.PlatformCall("ai.generateCall", request, &reply); err != nil {
		return nil, err
	}
	return reply.Value, nil
}
```

`Generate · main.py`:

```python
from contextual_worker import Context


async def answer(ctx: Context, route_id: str, question: str):
    return await ctx.ai().generate({
        "route": route_id,
        "system": "Answer in one sentence.",
        "prompt": question,
        "maxTokens": 128,
    })
```

`Search · main.py`:

```python
from contextual_worker import Context


async def search(ctx: Context, profile_id: str, index_id: str, question: str):
    result = await ctx.ai_search.query(profile_id, question, index_id=index_id, top_k=5)
    return result["items"]
```

`Tools · main.py`:

```python
from contextual_worker import Context


async def check_order(ctx: Context, route_id: str, question: str):
    async def tool(name, args):
        if name != "lookup_order":
            raise ValueError("Unexpected tool")
        order_id = args["id"]
        return {"id": order_id, "status": "shipped" if order_id == "order-2041" else "unknown"}

    return await ctx.ai().generate_with_tools({
        "route": route_id,
        "system": "Use lookup_order for shipping status. If it returns unknown, say so.",
        "prompt": question,
        "maxSteps": 4,
        "timeoutMs": 15000,
        "tools": {
            "lookup_order": {
                "description": "Look up an order's status",
                "inputSchema": {
                    "type": "object",
                    "properties": {"id": {"type": "string"}},
                    "required": ["id"],
                },
            },
        },
    }, tool)
```

`AI Calls · main.py`:

```python
from contextual_worker import Context


async def summarize_order(ctx: Context, note: str):
    reply = await ctx.platform_call("ai.generateCall", {
        "call": {"id": "order-summary", "label": "stable"},
        "variables": {"note": note},
    })
    return reply["value"]
```

## Build with a coding agent.

Give your coding agent access to Contextual documentation and the tools to build and deploy.

### Solution AI Knowledge MCP

Give your agent tools to search and read the docs. Add this server to your agent and follow the sign-in prompt.

`https://contextual-docs-mcp.contextualio.workers.dev`

[Connect your coding agent](https://docs.contextual.io/welcome.md#connect-your-coding-agent-to-contextual-knowledge)

### Solution AI Connect

A plugin for Claude Code and Codex with Contextual docs, CLI, and data-modeling skills.

[Get the plugin](https://github.com/ContextualIO/solution-ai-connect)

### Contextual CLI

Your agent uses `ctxl` to deploy Workers and work with your tenant.

`npm install -g @contextual-io/cli`

[View on npm](https://www.npmjs.com/package/@contextual-io/cli)

© 2026 Contextual

[Privacy Policy](https://contextual.io/privacy) · [Terms](https://contextual.io/terms)
