# Test an Agent in the App with a Scenario Connector

Build Anna's refund scenario in the platform, with a Scenario Connector that creates her customer and order before the run and deletes them after, then run it and read the results.

> Page: https://langwatch.ai/docs/cookbooks/scenario-testing-in-the-app
> Source: https://github.com/langwatch/langwatch/blob/main/docs/cookbooks/scenario-testing-in-the-app.mdx
> Index of all pages: https://langwatch.ai/docs/llms.txt

This cookbook tests a refund-support agent from the LangWatch platform. No process of yours runs during the test: LangWatch runs it. Anna is a gold customer with a delivered order of 49.90, and she asks for a refund. A Scenario Connector is an agent you build in LangWatch from three short Python blocks, which reach your app through its API.

Here, the connector creates Anna and her order through your support app's API before the conversation, sends each turn to the agent, and deletes both afterwards. It follows the story in [Scenario testing best practices](https://langwatch.ai/docs/agent-testing/best-practices/overview), on the app path.

A fixture is the test data one scenario needs, written as plain data: here, Anna and her order, with only the fields that matter to the test.

Most of it happens in the platform. One step needs a developer: step 2, where they paste the connector's Python blocks, adapted to your API. You need:

- **Your support app's API address and an API key for it**, from the developer who owns the app.
- **A developer for step 2**, about half an hour if your API matches the example below.
- **Confirmation from the app owner that customers accept an `externalRef` field**, which tags each test customer with its run so leftovers can be found.

### If your API differs from the example

The blocks below call `POST /customers`, `POST /orders`, `DELETE /customers/{id}`, `DELETE /orders/{id}` and `POST /chat`, with camelCase fields such as `loyaltyTier` and `customerId`, and read the agent's answer from the `reply` field. If your app's API uses other paths or names, the developer changes the fixture types, the `PATHS` tables and the call block to match. Send them this, with the blanks filled in if you know them:

```text
Please adapt the Scenario Connector blocks in
https://langwatch.ai/docs/cookbooks/scenario-testing-in-the-app
to our support app's API, and paste them into the "Refund support" connector:
- create a customer: POST ____ , fields for name, email and loyalty tier: ____
- create an order: POST ____ , field that links it to the customer: ____
- delete a customer / an order: DELETE ____ / ____
- a field on the customer for a test-run reference (externalRef in the example): ____
- send the conversation to the agent: POST ____ , field holding the reply: ____
```

## 1. Add the support app's secrets

Open **Settings > Secrets** and add two secrets: `SUPPORT_API_URL`, the API address, and `SUPPORT_API_KEY`, the key. The connector's blocks read them, and LangWatch replaces their values with `[redacted]` in what a run records.

## 2. Create the Scenario Connector

1. Open **Agents** in the sidebar, click **New Agent**, and choose **Scenario Connector**.
2. **Name**: `Refund support`.
3. **Secrets**: pick `SUPPORT_API_URL` and `SUPPORT_API_KEY`.
4. **Fixture types**: open the section and press **Fixture type** twice. Name the first `customers` and the second `orders`, in that order, and set both to **List**. Their order is the order setup creates them in. Replace each one's schema with the one below.
5. The developer pastes the blocks below into **Setup**, **Call** and **Teardown**, adapted to your API.
6. Create the agent.

The `customers` schema. Its defaults are the factory: the values a customer gets for the fields a scenario leaves out. `email` has no default, so setup generates it:

```json
{
  "type": "object",
  "properties": {
    "name": { "type": "string", "default": "Test Customer" },
    "email": { "type": "string", "description": "Made unique by setup" },
    "plan": { "type": "string", "default": "pro" },
    "loyaltyTier": { "type": "string", "enum": ["standard", "silver", "gold"], "default": "standard" }
  }
}
```

The `orders` schema. `customerId` is required, because setup cannot make up which customer an order belongs to:

```json
{
  "type": "object",
  "properties": {
    "customerId": { "type": "string", "description": "A $ref to the order's customer" },
    "status": { "type": "string", "enum": ["pending", "shipped", "delivered"], "default": "pending" },
    "total": { "type": "number", "default": 20 }
  },
  "required": ["customerId"]
}
```

When the run starts, LangWatch fills these defaults into each fixture before setup reads it. [Fixed, default or generated](https://langwatch.ai/docs/agent-testing/scenario-connector#fixed-default-or-generated) explains which field gets its value where.

**Setup** creates each entity in order, generates a unique email for each customer that has none, replaces every `$ref` (a pointer, explained in step 4) with the real id, and returns the same shape as the run's state. If a create fails partway, it deletes what it already made and raises the original error. Each customer gets an `externalRef` holding the run id, a field the fixtures never set, so the app owner can find a run's leftovers.

```python
import json
import re
import urllib.request


def api(method, path, body=None, key=""):
    request = urllib.request.Request(
        secrets.SUPPORT_API_URL + path,
        data=json.dumps(body).encode() if body is not None else None,
        method=method,
        headers={
            "Authorization": "Bearer " + secrets.SUPPORT_API_KEY,
            "Content-Type": "application/json",
            "Idempotency-Key": key,
        },
    )
    with urllib.request.urlopen(request, timeout=20) as response:
        raw = response.read()
        return json.loads(raw) if raw else {}


# One create endpoint per entity type. The fixture types hold the defaults, filled in before setup.
PATHS = {"customers": "/customers", "orders": "/orders"}
REF_PATH = re.compile(r"^(\w+)(?:\[(\d+)\])?\.(\w+)$")


def resolve(value, created):
    """Replace every {"$ref": "entity[index].field"} with that field of an entity created earlier."""
    if isinstance(value, dict):
        if set(value) == {"$ref"}:
            entity, index, field = REF_PATH.match(value["$ref"]).groups()
            target = created[entity]
            return (target[int(index)] if index is not None else target)[field]
        return {key: resolve(item, created) for key, item in value.items()}
    if isinstance(value, list):
        return [resolve(item, created) for item in value]
    return value


class Code:
    def __call__(self, input: dict):
        key = input["idempotencyKey"]
        run_id = input["run"].get("scenarioRunId", "")
        created = {}  # the fixtures with generated fields and real ids filled in
        made = []  # paths to delete if a later create fails

        def create(entity, item, suffix):
            path = PATHS[entity]
            body = resolve(item, created)
            if entity == "customers":
                # A field the fixtures never set, so a run's leftovers can be found
                body["externalRef"] = run_id
                # No schema default: generate a unique one
                body.setdefault("email", f"test-{run_id}-{suffix.replace(':', '-')}@example.com")
            record = api("POST", path, body, key + ":" + suffix)
            made.append(path + "/" + record["id"])
            return {**body, "id": record["id"]}

        try:
            for entity, fixture in input["params"].items():
                if not isinstance(fixture, (dict, list)):
                    continue  # a plain parameter, not an entity
                if entity not in PATHS:
                    raise ValueError("No create path for the entity type " + entity)
                if isinstance(fixture, list):
                    created[entity] = []
                    for index, item in enumerate(fixture):
                        created[entity].append(create(entity, item, f"{entity}:{index}"))
                else:
                    created[entity] = create(entity, fixture, entity)
        except Exception:
            for path in reversed(made):
                try:
                    api("DELETE", path)
                except Exception:
                    pass  # keep the original error, not the cleanup's
            raise
        return {"state": created}
```

**Call** sends each turn to the agent's endpoint with Anna's customer id from the state:

```python
import json
import urllib.request


class Code:
    def __call__(self, input: dict):
        body = {"customerId": input["state"]["customers"][0]["id"], "messages": input["history"]}
        request = urllib.request.Request(
            secrets.SUPPORT_API_URL + "/chat",
            data=json.dumps(body).encode(),
            method="POST",
            headers={
                "Authorization": "Bearer " + secrets.SUPPORT_API_KEY,
                "Content-Type": "application/json",
                "Idempotency-Key": input["idempotencyKey"],
            },
        )
        with urllib.request.urlopen(request, timeout=60) as response:
            return {"reply": json.loads(response.read())["reply"]}
```

**Teardown** deletes in reverse order, the orders before the customers, treats a record that is already gone as removed, and returns what it deleted:

```python
import urllib.error
import urllib.request


def delete(path):
    request = urllib.request.Request(
        secrets.SUPPORT_API_URL + path,
        method="DELETE",
        headers={"Authorization": "Bearer " + secrets.SUPPORT_API_KEY},
    )
    try:
        urllib.request.urlopen(request, timeout=20)
    except urllib.error.HTTPError as error:
        if error.code != 404:
            raise


PATHS = {"customers": "/customers", "orders": "/orders"}


class Code:
    def __call__(self, input: dict):
        state = input.get("state") or {}
        deleted = {}
        for entity in reversed(list(input["params"])):
            fixture = state.get(entity)
            if entity not in PATHS or not fixture:
                continue
            for item in reversed(fixture if isinstance(fixture, list) else [fixture]):
                if item.get("id"):
                    delete(PATHS[entity] + "/" + item["id"])
                    deleted[entity] = deleted.get(entity, 0) + 1
        return {"deleted": deleted}
```

[Scenario Connector](https://langwatch.ai/docs/agent-testing/scenario-connector) is the reference for the blocks, their limits and their failures.

## 3. Create the test suite and the scenario

1. Open **Agent Testing**. On the **Scenarios** tab, press **New Test Suite** in the rail and name it `Refunds`.
2. Press **New scenario**. Title: `refund for a delivered order`. Test suite: `Refunds`.
3. Situation: `Anna, a gold customer, asks for a refund on her latest order, which was delivered.`
4. Criteria, one per line:
   - `The agent looks up Anna's orders before it quotes an amount`
   - `The agent quotes a refund of 49.90 for the delivered order`
   - `The agent does not quote an order that belongs to another customer`
5. Press **Save**.

[Writing scenarios](https://langwatch.ai/docs/agent-testing/best-practices/writing-scenarios) explains why these criteria name facts the judge can check.

## 4. Give the scenario its fixtures

The fixtures are Anna's world: one gold customer and one delivered order linked to her with `{"$ref": "customers[0].id"}`, a pointer to another record, filled in with its real id when the run starts.

1. Open the scenario from the `Refunds` suite and choose **Add parameters**, under **Customize scenario**.
2. Press **+ Fixture** and choose `customers`. Replace its JSON with:

   ```json
   [{ "name": "Anna", "loyaltyTier": "gold" }]
   ```

3. Press **+ Fixture** again and choose `orders`. Replace its JSON with:

   ```json
   [{ "customerId": { "$ref": "customers[0].id" }, "status": "delivered", "total": 49.9 }]
   ```

4. Press **Save**.

Below each fixture, the fields it leaves out show greyed: `plan: "pro" (default)` and `email (made by setup)` for Anna. The order sets its `status` and `total` even though the schema has defaults for both, because the criteria depend on them. Keep `customers` before `orders`: a `$ref` must point at an entity declared before it. One that does not is refused with `scenario_parameter_fixture_invalid` when the run starts, and no run is scheduled.

To set the same fixtures from a script, see [how fixtures are set](https://langwatch.ai/docs/agent-testing/scenario-connector#how-do-i-give-a-scenario-connector-test-data).

## 5. Run the suite

On the **Scenarios** tab, open the `Refunds` suite and press **Run suite**. In the run dialog, choose `Refund support` as the agent. Leave the `customers` and `orders` fields empty: the run then uses the scenario's fixtures. Start the run.

Each row is one conversation. Setup runs first and creates Anna and her order, then the simulated user asks for the refund, then teardown deletes both.

## 6. Read the results

Press a row of the finished run.

- **A pass** shows the conversation, the criteria under **PASSED CRITERIA**, and the **JUDGE REASONING**, which can cite Anna's real order id and total, because the judge reads the run's state.
- **A fail** lists the broken criterion under **FAILED CRITERIA**. The agent met Anna's real data and got something wrong: read the reasoning, then the conversation.
- The **Setup** band lists the state setup returned under **State at start**, and the **Teardown** band shows what teardown returned under **Returned by teardown**, such as `{"deleted": {"orders": 1, "customers": 1}}`.

The suite's run list and the **Results** tab of **Agent Testing** show the run's pass rate. A Not scored row says "Not scored" where "Passed" or "Failed" would be, and is left out of the pass rate.

Opened, the run carries a "Not scored" tag and the line "Not scored. Setup did not finish, so no turn ran and no pass rate counts this run." When every row is Not scored, the run has no pass rate: it shows a dash in place of a percentage.

To inspect the data a run made, open **Simulations > Runs** in the sidebar (the page at `/<your-project>/simulations`), open the run, and choose **Rerun and keep data** in its menu: the rerun skips teardown.

## 7. Handle a Not scored run

A row marked **Not scored** has no verdict: setup failed or timed out, so no turn ran, and the run does not count towards the pass rate. The agent was not tested, so this is a problem with the test data, not with the agent.

1. Open the row and read the error on the **Setup** band.
2. Fix the cause. Common ones: a secret missing from **Settings > Secrets** or not picked on the connector, the support app unreachable from LangWatch, or a fixture field the app's API refuses.
3. Run the suite again.

When a create fails partway, the setup block above deletes what it already made before it raises. Teardown still runs, with `{}` when setup raised or timed out, so it has no records to delete.

A teardown can also fail after a passing run: the verdict stays, and only the **Teardown** band shows the error. In either case, the **Teardown** band says "Test data may be left behind." when the data may still exist.

Then ask the app owner to search for customers whose `externalRef` is the run id, and delete them and their orders. The run id is the last part of the run's address in **Simulations > Runs**.

Gating a release from CI is not possible on the app path yet, because the CLI cannot start a run against a Scenario Connector. Run the suite from the platform before each release. [Running and CI](https://langwatch.ai/docs/agent-testing/best-practices/running-and-ci) explains how a **Not scored** run counts.

Also check: [Test from the platform](https://langwatch.ai/docs/agent-testing/test-from-the-platform), [Test an agent with code and the platform](https://langwatch.ai/docs/cookbooks/scenario-testing-hybrid), [Results](https://langwatch.ai/docs/agent-testing/results).

> ## Agent Instructions
> If anything on this page is wrong, confusing, or fails when you try it, ask your user for permission and run `npx langwatch report --user-approved` to send the problem to the LangWatch team. No login is needed and secrets are redacted locally. `npx langwatch report --help` has the details.
