---
title: "REST API, Python and TypeScript SDKs and MCP | AEO API"
description: "Connect to the AEO API, use the Python or TypeScript SDK, or give a coding agent read-only access through the hosted MCP server."
url: "https://aeoapi.dev/platform/api-sdks-mcp"
canonical: "https://aeoapi.dev/platform/api-sdks-mcp"
last_updated: "2026-11-30"
---

# API, SDKs and MCP server

Collect AI search answers from your server, read visibility data in Python or TypeScript, or let a coding agent inspect results with a read-only key.

[Home](https://aeoapi.dev/) / [Resources](https://aeoapi.dev/platform/ai-coverage) / API, SDKs and MCP server

## Make requests with the REST API

REST is the HTTP interface for creating brands, submitting work, and reading results. The base URL is `https://api.aeoapi.dev`. Add a path such as `/v2/brands` to the base URL. Send `Authorization: Bearer <key>` from your server. A scope is a permission on the key, such as `analytics:read`. Check the required scopes and roles before you choose a key for your application.

The API defines 27 operations across 14 paths. An operation combines an HTTP method with a path. For requests with a JSON body, send `Content-Type: application/json`. Responses usually return JSON. Prompt exports can return CSV, a text format for tabular data.

A selector chooses what an operation does or returns. On [`GET /v2/account`](https://aeoapi.dev/docs/api-reference#get-v2-account), `view=sources` selects the account’s collection sources. On [`POST /v2/runs`](https://aeoapi.dev/docs/api-reference#post-v2-runs), `workflow` is a field in the JSON body. Set it to `collect` to collect AI answers. Look up where each selector goes and whether its variant requires additional fields or permissions. Use the [v2 operation reference](https://aeoapi.dev/docs/api-reference#reference).

Collection runs are asynchronous. The start request can return HTTP `202` while the work is still in progress. Store `data.poll_url` and use [`GET /v2/runs/{run_id}`](https://aeoapi.dev/docs/api-reference#get-v2-runs-run_id) to check the state later. For lists that return `meta.next_cursor`, such as the brand list, pass that value as `cursor` in the next request. Keep the other filters the same and stop when there is no next cursor.

## Retry requests and protect updates

For writes that require the request key header shown below, save a new key with the request body. A request key identifies one submission. Within the seven-day retention window, resending the same key and body for the same account and operation returns the original response. Sending a changed body with that key returns HTTP `409`. Keep the key when you retry after losing a response.

Some updates also require a revision. For example, [`PATCH /v2/prompts`](https://aeoapi.dev/docs/api-reference#patch-v2-prompts) with `action=update` requires `If-Match`. Send the current revision as a quoted value. If the revision has changed, the API returns HTTP `412`. Read the latest revision and review the changes before submitting an updated request with a new request key.

For an error, read the HTTP status and the response fields `code`, `message`, and `retryable`. Save `request_id` so you can identify the failed call. Use `field_errors`, when present, to find which inputs to correct. If the API rate limits a request with HTTP `429`, wait the number of seconds in `Retry-After` before retrying. The same header gives the delay for a collection request that returns HTTP `503` with `source_pending`. If you change the requested source after checking availability, treat that as a new submission.

## Collect answers in three calls

Use cURL to send the HTTP requests and Python 3 to prepare the collection body. Set `AEO_API_BASE_URL` to `https://api.aeoapi.dev` and load `AEO_API_KEY` from your secret store. Use an editor, owner, or service key without a brand restriction, with `brands:write`, `prompts:write`, `collections:write`, and `collections:read`. These writes require an account with billing access. Set `BRAND_REQUEST_KEY` and `COLLECTION_REQUEST_KEY` to two new values, such as separate UUIDs. A UUID is a generated identifier.

### Create a brand with prompts

Replace the example brand details and tracked question with your own. [`POST /v2/brands`](https://aeoapi.dev/docs/api-reference#post-v2-brands) returns the brand ID in `data.id` and the saved prompt IDs in `data.prompt_ids`.

```
curl --fail-with-body "$AEO_API_BASE_URL/v2/brands" \
  -H "Authorization: Bearer $AEO_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $BRAND_REQUEST_KEY" \
  --output brand-response.json \
  --data-binary @- <<'JSON'
{
  "name": "Example Plumbing",
  "domains": ["example.com"],
  "category_ids": ["gcid:plumber"],
  "markets": [{"country": "US", "city": "Chicago", "language": "en"}],
  "prompts": ["What should homeowners compare when choosing a plumber in Chicago?"]
}
JSON
```

### Start a capped collection run

Availability depends on your account. Use [`GET /v2/account`](https://aeoapi.dev/docs/api-reference#get-v2-account) with `view=sources` and a key with `account:read` to find a platform and mode pair marked `available: true`. If you see no available pair, wait before submitting. Export the chosen values as `COLLECTION_PLATFORM` and `COLLECTION_MODE`. Export `COLLECTION_MAX_UNITS` as the maximum number of credits you authorize. Prepare the request, then submit it with [`POST /v2/runs`](https://aeoapi.dev/docs/api-reference#post-v2-runs).

```
python3 - <<'PY' > collection.json
import json
import os
import sys

with open("brand-response.json") as response:
    brand = json.load(response)["data"]

json.dump({
    "workflow": "collect",
    "brand_id": brand["id"],
    "prompt_ids": brand["prompt_ids"],
    "market": brand["markets"][0],
    "sources": [{
        "platform": os.environ["COLLECTION_PLATFORM"],
        "mode": os.environ["COLLECTION_MODE"],
    }],
    "max_units": int(os.environ["COLLECTION_MAX_UNITS"]),
}, sys.stdout)
PY
```

```
curl --fail-with-body "$AEO_API_BASE_URL/v2/runs" \
  -H "Authorization: Bearer $AEO_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $COLLECTION_REQUEST_KEY" \
  --data-binary @collection.json \
  --output run-response.json
```

### Read the run and its result

Set `RUN_ID` to `data.id` in `run-response.json`, including the run type prefix. Read `data.state` with [`GET /v2/runs/{run_id}`](https://aeoapi.dev/docs/api-reference#get-v2-runs-run_id). If the run is queued or running, wait and repeat the read.

```
curl --fail-with-body "$AEO_API_BASE_URL/v2/runs/$RUN_ID" \
  -H "Authorization: Bearer $AEO_API_KEY"
```

After completion, `data.result` contains the accepted and failed counts and the observation IDs included in the response. Each observation ID identifies a collected answer. Keep partial results marked as incomplete. If the run failed or was cancelled, check `data.error` when present before deciding what to do next.

## Call the API from Python or TypeScript

The SDKs add the operation path to the base URL you configure. Set the base URL to the API origin, `https://api.aeoapi.dev`. Both SDKs are on GitHub. [Python repository](https://github.com/aeo-api/aeoapi-python-sdk) · [Node.js repository](https://github.com/aeo-api/aeoapi-nodejs-sdk)

The full examples below use the key, request keys, source pair, and credit cap from the cURL setup. Export those variables before running either example. Use a key that also has `analytics:read`. Export `START_AT` and `END_AT` as RFC 3339 timestamps, with a UTC marker or time zone offset. Choose a window that includes the collection. For installation, see the [Python](https://aeoapi.dev/docs/sdks/python) or [TypeScript](https://aeoapi.dev/docs/sdks/typescript) SDK guide.

### Python

`AeoClient` waits for each request to finish before moving to the next line. The `with` block closes the client when it ends. Read the parsed result with `response.data`. If the API returns an error, `AeoApiError` gives you its status, code, request ID, and retry delay when supplied.

```
import os
import time

from aeo_sdk import AeoApiError, AeoClient

try:
    with AeoClient(
        os.environ["AEO_API_KEY"], base_url="https://api.aeoapi.dev"
    ) as client:
        brand = client.v2_post_brands(
            {
                "name": "Example Plumbing",
                "domains": ["example.com"],
                "category_ids": ["gcid:plumber"],
                "markets": [{"country": "US", "city": "Chicago", "language": "en"}],
                "prompts": ["What should homeowners compare when choosing a plumber in Chicago?"],
            },
            idempotency_key=os.environ["BRAND_REQUEST_KEY"],
        ).data

        run = client.v2_post_runs(
            {
                "workflow": "collect",
                "brand_id": brand["id"],
                "prompt_ids": brand["prompt_ids"],
                "market": brand["markets"][0],
                "sources": [{
                    "platform": os.environ["COLLECTION_PLATFORM"],
                    "mode": os.environ["COLLECTION_MODE"],
                }],
                "max_units": int(os.environ["COLLECTION_MAX_UNITS"]),
            },
            idempotency_key=os.environ["COLLECTION_REQUEST_KEY"],
        ).data
        run_id = run["id"]
        print("Run ID:", run_id)

        for _ in range(30):
            status = client.v2_get_runs_run_id(run_id).data
            if status["state"] == "completed":
                visibility = client.v2_get_analytics_dataset(
                    "visibility",
                    brand_id=brand["id"],
                    start_at=os.environ["START_AT"],
                    end_at=os.environ["END_AT"],
                )
                for row in visibility.data:
                    print(row["mention_rate"], row["coverage"]["valid_answers"])
                break
            if status["state"] in {"partial", "failed", "cancelled"}:
                print("Check the run before reporting visibility:", status["state"])
                break
            time.sleep(2)
        else:
            print("Check the run again later using its ID.")
except AeoApiError as error:
    print(error.status, error.code, error.request_id, error.retry_after)
    raise SystemExit(1)
```

### Async Python

Use `AsyncAeoClient` when your application already uses `async` and `await` so other work can continue while a request is in progress. It has the same brand, run, and analytics methods. Set `BRAND_ID` to a brand with collected results to try this read on its own.

```
import asyncio
import os

from aeo_sdk import AeoApiError, AsyncAeoClient

async def main():
    try:
        async with AsyncAeoClient(
            os.environ["AEO_API_KEY"], base_url="https://api.aeoapi.dev"
        ) as client:
            visibility = await client.v2_get_analytics_dataset(
                "visibility",
                brand_id=os.environ["BRAND_ID"],
                start_at=os.environ["START_AT"],
                end_at=os.environ["END_AT"],
            )
            for row in visibility.data:
                print(row["mention_rate"], row["coverage"]["valid_answers"])
    except AeoApiError as error:
        print(error.status, error.code, error.request_id, error.retry_after)
        raise SystemExit(1)

asyncio.run(main())
```

### TypeScript

Run this example on your server. Await each method and read the parsed reply from `response.body`. Both full examples stop polling after 30 checks. If yours stops while the run is still in progress, continue checking the printed run ID.

```
import { AeoApiError, AeoClient } from "@aeoapi/aeo-sdk";

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error("Set " + name);
  return value;
}

type Brand = {
  id: string;
  prompt_ids: string[];
  markets: { country: string; city?: string; language: string }[];
};
type VisibilityRow = {
  mention_rate: number | null;
  coverage: { valid_answers: number };
};

async function main() {
  const client = new AeoClient(env("AEO_API_KEY"), {
    baseUrl: "https://api.aeoapi.dev",
  });
  try {
    const created = await client.v2PostBrands(
      {
        name: "Example Plumbing",
        domains: ["example.com"],
        category_ids: ["gcid:plumber"],
        markets: [{ country: "US", city: "Chicago", language: "en" }],
        prompts: ["What should homeowners compare when choosing a plumber in Chicago?"],
      },
      { idempotencyKey: env("BRAND_REQUEST_KEY") },
    );
    const brand = (created.body as { data: Brand }).data;
    const started = await client.v2PostRuns(
      {
        workflow: "collect",
        brand_id: brand.id,
        prompt_ids: brand.prompt_ids,
        market: brand.markets[0],
        sources: [{
          platform: env("COLLECTION_PLATFORM"),
          mode: env("COLLECTION_MODE"),
        }],
        max_units: Number(env("COLLECTION_MAX_UNITS")),
      },
      { idempotencyKey: env("COLLECTION_REQUEST_KEY") },
    );
    const { id: runId } = (started.body as { data: { id: string } }).data;
    console.log("Run ID:", runId);

    for (let attempt = 0; attempt < 30; attempt++) {
      const status = await client.v2GetRunsRunId(runId);
      const { state } = (status.body as { data: { state: string } }).data;
      if (state === "completed") {
        const visibility = await client.v2GetAnalyticsDataset("visibility", {
          brand_id: brand.id,
          start_at: env("START_AT"),
          end_at: env("END_AT"),
        });
        const { data } = visibility.body as { data: VisibilityRow[] };
        for (const row of data) {
          console.log(row.mention_rate, row.coverage.valid_answers);
        }
        return;
      }
      if (["partial", "failed", "cancelled"].includes(state)) {
        console.log("Check the run before reporting visibility:", state);
        return;
      }
      await new Promise((resolve) => setTimeout(resolve, 2000));
    }
    console.log("Check the run again later using its ID.");
  } catch (error) {
    if (!(error instanceof AeoApiError)) throw error;
    console.error(error.status, error.code, error.requestId, error.retryAfter);
    process.exitCode = 1;
  }
}

void main();
```

The visibility dataset gives you `mention_rate`, the share of measured answers that mention the brand, and `coverage.valid_answers`, the number of valid answers behind the measurement. Show the count alongside the rate and retain the market and collection mode when reporting it. The window can include answers from other prompts you collected for the same brand. An empty dataset or a `null` rate means you have no rate to report for that selection.

### Common SDK methods

Python and TypeScript methods and their REST operations

| Python | TypeScript | What it does | REST operation |
| --- | --- | --- | --- |
| `v2_get_account` | `v2GetAccount` | Check account limits or available sources. | [`GET /v2/account`](https://aeoapi.dev/docs/api-reference#get-v2-account) |
| `v2_get_brands` | `v2GetBrands` | List brands the key can access. | [`GET /v2/brands`](https://aeoapi.dev/docs/api-reference#get-v2-brands) |
| `v2_post_brands` | `v2PostBrands` | Create a brand and optionally save prompts with it. | [`POST /v2/brands`](https://aeoapi.dev/docs/api-reference#post-v2-brands) |
| `v2_get_brands_brand_id` | `v2GetBrandsBrandId` | Read one brand profile. | [`GET /v2/brands/{brand_id}`](https://aeoapi.dev/docs/api-reference#get-v2-brands-brand_id) |
| `v2_get_prompts` | `v2GetPrompts` | Read saved questions for a brand. | [`GET /v2/prompts`](https://aeoapi.dev/docs/api-reference#get-v2-prompts) |
| `v2_patch_prompts` | `v2PatchPrompts` | Update a saved question or archive it. | [`PATCH /v2/prompts`](https://aeoapi.dev/docs/api-reference#patch-v2-prompts) |
| `v2_post_runs` | `v2PostRuns` | Start a workflow, such as collecting answers. | [`POST /v2/runs`](https://aeoapi.dev/docs/api-reference#post-v2-runs) |
| `v2_get_runs_run_id` | `v2GetRunsRunId` | Check a run and read its available result. | [`GET /v2/runs/{run_id}`](https://aeoapi.dev/docs/api-reference#get-v2-runs-run_id) |
| `v2_get_analytics_dataset` | `v2GetAnalyticsDataset` | Read metrics for a dataset such as visibility. | [`GET /v2/analytics/{dataset}`](https://aeoapi.dev/docs/api-reference#get-v2-analytics-dataset) |
| `v2_get_reports` | `v2GetReports` | Read or compare reports for a brand. | [`GET /v2/reports`](https://aeoapi.dev/docs/api-reference#get-v2-reports) |

## Give a coding agent read access with hosted MCP

Model Context Protocol (MCP) is a standard that lets an agent discover and call tools from another application. If your account has hosted MCP access, use a client that supports Streamable HTTP, the connection type for sending MCP requests over HTTP, and lets you set a custom header.

1. Add `https://api.aeoapi.dev/mcp` as the server URL and select Streamable HTTP.
2. Configure `Authorization: Bearer <key>` on every request. Use a viewer key with only the read scopes the agent needs. Keep the key in the client’s secret settings and out of chat and checked-in files.
3. Check the tool list after connecting. With `account:read`, try `get_account` with no arguments. A successful call returns the account overview in `structuredContent.data`.

Use `tools/list` to discover what your key and plan allow. The hosted server documentation lists the following read tools.

- Account and saved setup reads include `get_account`, `get_usage`, `list_brands`, and `list_prompts`.
- Work and result reads include `get_job`, `get_audit`, `get_recommendations`, and `get_optimization`.
- Analytics reads include `query_visibility`, `query_prompts`, and `query_attribution`.

If a documented tool is missing, check your key’s role and scopes and your plan. Hosted tools read data. Use REST or an SDK for actions such as creating a brand, starting a run, or changing a schedule. [Set up your MCP client and read your account.](https://aeoapi.dev/docs/mcp)

## Choose how your team connects

Use REST if you already have an HTTP client or want to handle request headers in your application. For example, a SaaS team can save the collection run ID with its own customer record, check that run later, and show the result in its product. Use the Python or TypeScript SDK if your application already uses that language and you want methods for building requests and reading responses.

Use hosted MCP for read-only questions during development or support. An agency developer can ask an agent with the right scope to check which brands a key can access before setting up client reporting. If you need a repeatable report in your own application, use REST or an SDK to call [`GET /v2/reports`](https://aeoapi.dev/docs/api-reference#get-v2-reports) with the same brand and report selectors each time.

Analyzer and Optimizer both include the REST operations for the collection and visibility examples on this page. Analyzer allows 60 requests per minute and two jobs at a time. Optimizer allows 300 requests per minute and ten jobs at a time. Reads use zero credits. Collection and other processing can use credits. Request access through the contact form and accept the emailed invitation. The API delivers results and the account portal handles keys, usage, and billing. [Compare plan access and limits.](https://aeoapi.dev/pricing)

When you have a completed collection, use [AI visibility tracking](https://aeoapi.dev/products/ai-visibility-tracking) to decide which mention measurements to report. Use [Reports and webhooks](https://aeoapi.dev/products/reports-webhooks) for saved reports and event delivery to an endpoint you manage.

## Questions

### How do I get an API key?

Request access through the contact form. Accept the emailed invitation to activate your account, then manage your keys in the account portal. [See the API setup requirements.](https://aeoapi.dev/docs/getting-started#prerequisites)

### Can I send the API key from browser JavaScript?

Keep your key on your server. Send requests to AEO API from there so the key stays out of the browser and public build variables. [Set up a server-side key.](https://aeoapi.dev/docs/getting-started#environment)

### How do I avoid starting the same collection twice?

Store the request key and body before sending the start request. If you retry that submission, resend both unchanged. Use a new key for a new collection. [See the collection start request.](https://aeoapi.dev/docs/prompt-collection#start)

### How do I find out which AI sources I can use?

Read the account sources view and look for an available platform and collection mode pair. Keep both values from the same row when you prepare the collection. [Check source availability on your account.](https://aeoapi.dev/docs/source-coverage)

### Where do I get the Python and TypeScript SDKs?

Both SDKs are available on GitHub. Use pip to install the Python SDK from its repository. For Node.js, clone the repository and build the package before installing it. [Open the SDK installation guides.](https://aeoapi.dev/docs/sdks)

### Can the hosted MCP server start a collection or change a schedule?

Hosted MCP tools are read-only. Start collections and update schedules through REST or an SDK with the required write permissions. [See the REST operation for starting runs.](https://aeoapi.dev/docs/api-reference#post-v2-runs)

### Do I use credits to check a run or read visibility?

Reading saved data and checking run state use zero credits. Starting a collection can use credits up to the cap in your request. [See how to read a run by ID.](https://aeoapi.dev/docs/api-reference#get-v2-runs-run_id)

## Next

- [Run the three-call collection quickstart](https://aeoapi.dev/docs/three-call-quickstart)
- [Open the v2 API reference](https://aeoapi.dev/docs/api-reference)
- [Compare building and buying AI search monitoring](https://aeoapi.dev/guides/build-vs-buy-ai-search-monitoring)
- [Request API access](https://aeoapi.dev/contact)
