# Agent access (MCP)

Terradium speaks [MCP](https://modelcontextprotocol.io), so a coding agent —
Claude Code, Cursor, Codex — can work on a project directly instead of you
relaying between a chat window and the dashboard.

The MCP server is **https://api.terradium.io/api/v1/mcp**. Tokens start with
`td_mcp_`. Writes need that project token. [terradium.io](https://terradium.io)
is the docs and OpenAPI host, not the MCP endpoint. Spec:
[/openapi.json](/openapi.json).

An agent can run the whole loop: set up the questions you want to be found for,
track your competitors, sample what the AI engines actually answer, see where
you're losing, write an article aimed at one of those gaps, publish it, rebuild
your site, and come back later to check whether the citation rate moved. None of
it needs the dashboard.

## Connect

Project settings → **Agent (MCP)** → **Create token**. You get a server URL and a
token; paste the config into your agent. Each project installs under its own
name, `terradium-<project>`, so connecting a second project doesn't replace the
first:

```json
{
  "mcpServers": {
    "terradium-acme": {
      "type": "http",
      "url": "https://api.terradium.io/api/v1/mcp",
      "headers": { "Authorization": "Bearer td_mcp_…" }
    }
  }
}
```

The token is shown **once**. If you lose it, revoke it and make another.

## Let your agent set up a new project

When you sign up or create a project, the **Connect agent** step hands you a
token and a prompt to paste into Claude Code, Cursor or any coding agent. The
agent follows a public setup skill — [/setup/mcp.md](/setup/mcp.md) — and asks
you about your brand, competitors and seed keywords, runs keyword research,
creates your tracked prompts and topics, and drafts your first content plan. A
checklist on the same screen ticks as each piece lands.

It stops at a **draft** plan. Nothing is generated or published until you
approve the plan in Plans.

### Without MCP

Every setup tool is also plain HTTP, for agents that can't install an MCP
server. Same token, same arguments, same errors:

```bash
curl -X POST https://api.terradium.io/api/v1/agent/tools/create_competitors \
  -H "Authorization: Bearer td_mcp_…" \
  -H "Content-Type: application/json" \
  -d '{"domains":["example.com"]}'
```

`GET /api/v1/agent/tools` lists the tools with their input schemas. A refusal is
the tool's coded error, `{"error": {"code", "message", "hint", "details"}}`:
`402` for `subscription_required`, `422` for everything else. Only the setup tools are exposed this way —
generating, publishing and activating a plan stay MCP-only. The full recipe is
[/setup/rest.md](/setup/rest.md).

## What a token can reach

A token is scoped to **one project**. It cannot see or touch any other project on
your account, and it is not tied to your login — revoking it doesn't affect your
dashboard access, and losing your password doesn't expose it.

MCP tokens (`td_mcp_…`) are separate from the API keys (`td_live_…`) you put in
your website's build. Those are read-only content keys that live in build configs
and CI; an MCP token can publish. Keeping them apart means a key leaked from a
frontend can never be used to write.

Every tool call is recorded in your audit log.

## Tools

No tool takes a project id. The token already names the project, so there is no
argument an agent could get wrong.

### Content

| Tool | What it does |
|---|---|
| `list_posts` | Published articles for this project |
| `get_post` | One article's markdown, by slug, plus the generation it came from |
| `list_sessions` | Recent generations and their status |
| `get_geo_health` | Whether AI engines can read your site, and whether publishing is currently allowed |
| `get_quota` | Generations and keyword-research runs used and remaining this billing period |
| `get_account` | Subscription (active, trial end, plan) and every allowance, with the billing link |
| `generate_draft` | Start an article. Consumes one generation from your quota |
| `publish_now` | Publish a finished article |
| `update_post` | **Destructive.** Rewrite a published article in place. The slug, and so the URL, is kept |
| `dispatch_build` | Trigger your connected GitHub build |

**Fixing a live article is `update_post`, not a new generation.** `generate_draft`
and `publish_now` produce a *new* article; if the one that's already indexed says
something wrong, you want the wrong words replaced at the URL that's already
collecting citations. `update_post` takes the slug, a new title and/or the whole
replacement markdown, and rewrites that row in place. The slug never follows the
title, so the URL survives. It costs no generation quota, updates the draft the
post was published from so a later republish can't revert it, and triggers your
site build so the customer-facing page catches up.

### Your project's settings

The Details, Brand & entity and Publishing tabs, without opening the dashboard.

| Tool | What it does |
|---|---|
| `get_project_details` | Name, description, website, blog URL pattern, writing language, active or not |
| `get_project_context` | The markdown brief the writer is given — the "AI context" box on Details |
| `set_project_context` | Replace that brief. Whole-document write, so read it first |
| `get_brand_entity` | Org name, logo, `sameAs` profiles, default author — the JSON-LD identity |
| `set_brand_entity` | Patch any of those. A field you send is set to exactly what you sent (`""` or `[]` clears); one you omit is unchanged |
| `get_publishing` | Whether articles publish on their own, after how long, and where |
| `set_publishing` | **Destructive.** Turn auto-publish on or off, and set the review window |

**Three objects have "brand" or "context" in their name and they are not the
same thing.** This is the one place an agent reliably gets lost, so it's worth
being blunt about:

- **`projectContext`** — the writer brief. Markdown, in your words, about what
  you sell and how you talk about it. It is the *only* one of the three that
  changes how an article is written.
- **the brand entity** — org name, logo, `sameAs`, author. It becomes the
  JSON-LD graph stamped onto every published article, which is how an AI engine
  knows who stands behind the page.
- **the brand profile** — language, country, `sells`, `audience`. It steers
  *sampling*: which language and market AI answers are collected in.

An empty brand profile does not mean your project has no context. Ask for
`get_project_context` before concluding anything is missing.

`set_publishing` and `set_review_window` overlap on purpose: the older tool
changes the window alone, the newer one can also flip auto-publish. Both merge
into your settings rather than replacing them, so neither can take your publish
schedule or IndexNow key with it.

### The questions you track

| Tool | What it does |
|---|---|
| `list_prompts` | Every tracked question, sampled or not. Filter by `status` (`active`/`archived`), `topic`, or `search` |
| `create_prompts` | Track new questions, up to 50 per call. Ones already tracked are skipped, not duplicated. Optionally files them under topics |
| `update_prompts` | Reword questions in place, keeping their samples and lift history |
| `archive_prompts` | Stop sampling a question without losing what it measured |
| `restore_prompts` | Put archived questions back in the schedule, history intact |
| `delete_prompts` | **Destructive.** Stop tracking questions *and* delete their samples and lift history |
| `get_prompt_metrics` | Every question with how it is performing: samples, appearance rate, citation rate, mean position |
| `get_prompt_lift` | One question's citation rate before vs after its article was written |

`list_prompts` is the whole set. `list_actions` is the subset worth writing for
right now, and `list_gaps` is every question scored and ranked, including the
ones already handled.

**Archive, don't delete.** A tracked question's value accrues: its runs are the
only record of whether anything you published moved the citation rate. Archiving
takes it out of the schedule and out of the gap ranking — so it stops costing you
per cycle — and keeps every run. Restoring puts the whole series back. Deleting
throws the record away, which is occasionally what you want and usually isn't.

Rewording works the same way. `update_prompts` edits the question in place, so
fixing a typo doesn't restart the measurement the way delete-then-create would.

### Grouping

| Tool | What it does |
|---|---|
| `list_topics` | Your groupings, with how many questions sit in each |
| `create_topics` | Create groupings. Idempotent, and case-insensitive |
| `rename_topic` | Rename a grouping without touching its members |
| `delete_topics` | Delete groupings. The questions in them are untouched |
| `set_prompt_topics` | File questions into groupings. Each entry replaces that question's topics |

Topics are yours. Terradium ships no taxonomy and won't infer one — a set of 50
questions usually falls into three or four buckets that only you can name, and a
category tree we invented would be a worse version of the one in your head.

Names are matched case-insensitively, so "Hire vs retainer" and "hire vs
retainer" stay one bucket rather than two that look like one. A question can sit
in up to ten.

### The brand profile

| Tool | What it does |
|---|---|
| `get_brand_profile` | Language, country, what you sell, who you sell to |
| `set_brand_profile` | A patch: omitted fields are kept, `""` clears. Replacing a field that is already set needs `overwrite: true` |

This is the **sampling** profile. Nothing in it reaches the article writer — that
is `projectContext`, and it is a different object with a different tool.

`language` is the one with teeth: it sets the language Google AI Overviews are
sampled in. An Indonesian brand measured against English-language answers is
measuring a market it doesn't sell to. Set it to an ISO 639-1 code (`id`), and
don't let an agent guess it from your domain suffix — it should ask.

`country` is recorded but not yet applied to sampling: the Google geo-target it
would need is a numeric id with no clean mapping from a country code, so the
deployment's configured location still stands. `sells` and `audience` are there
for an agent to read before it writes anything; nothing consumes them
automatically.

### Your competitive set

| Tool | What it does |
|---|---|
| `list_competitors` | The domains you're ranked against |
| `create_competitors` | Track competitor domains, up to 50 per call. A pasted URL is reduced to its host |
| `delete_competitors` | Stop tracking domains. Sampled history is kept |

### Sampling

| Tool | What it does |
|---|---|
| `get_visibility_settings` | Cadence, runs per question, engines, and which engines are reachable |
| `set_visibility_settings` | Change the schedule. This is a cost dial — see below |
| `run_sample` | Sample every active question now. Returns once queued; results land over the next few minutes |

### The scoreboard

| Tool | What it does |
|---|---|
| `get_setup` | What's still missing before the numbers mean anything. Start here when they look empty |
| `get_overview` | Per-engine performance, share of voice, the daily trend, the most-cited domains |
| `get_ranking` | Where you stand against every tracked competitor, and the change since the previous window |
| `list_sources` | The domains and pages the AI reads instead of you, and who wins the answers you lose |
| `list_runs` | Recent sampling runs, newest first |
| `list_answers` | Individual sampled answers and what each one cited |
| `get_answer` | One answer in full, with its ordered citation list |
| `list_gaps` | Every question scored for weakness, with the format most likely to win it |
| `get_head_to_head` | Per question: are you absent while a competitor is present? |
| `compare_windows` | Visibility now vs the previous window, per brand, with rank movement |
| `generate_for_gap` | Write for one weak question, attributed to it so `get_prompt_lift` can measure the result |

**`get_head_to_head` is the one that says where to spend a generation.**
`get_ranking` tells you how visible each brand is overall; this tells you which
*questions* you're losing, and to whom. Every fired answer lands in exactly one
of four buckets:

- **lost** — you're absent, a tracked competitor is present
- **won** — you're present, no tracked competitor is
- **contested** — both of you are in the answer
- **neither** — nobody you track was cited. An open field, not a defeat

Answers where no AI answer fired at all aren't counted. A question nothing
answers is a different problem from one you're losing — nobody won it.

Competitor membership is resolved when you read, not when the sample was taken,
so adding a competitor today correctly reclassifies the history it was absent
from.

### Narrowing a read

`get_overview`, `get_ranking`, `list_sources`, `list_gaps`, `get_head_to_head`
and `compare_windows` all take the same narrowing:

- `range` — `7d`, `28d` (default), `90d`
- `engine` — `google_aio`, `perplexity`, `chatgpt`, `gemini`
- `topic` — only questions in one of your groupings, by name
- `promptIds` — only these questions. Giving both intersects
- `bucket` — `day` (default), `week`, `month`, for any time series in the result

An unrecognised `range` or `engine` widens the view rather than emptying it, so
a typo can't look like "no data". A `topic` that matches nothing is an **error**
instead — an empty question set would read as "no filter" and hand back the
whole project's numbers under a narrowed heading, which is worse than a refusal.
An unrecognised `bucket` is refused too: day/week/month is a closed set, so
there's nothing to widen to.

On a 90-day window, `bucket: "week"` turns 90 noisy points into 13 readable
ones. Bucketing regroups the samples; it never drops or invents any.

Lists return a `totalCount` alongside the page.

Nothing here crawls anything. Every row in `list_sources` was parsed out of an
answer we already sampled and stored — if an agent wants what's on a cited page,
it fetches the URL itself.

### What an agent should ask about first

Three tools change something you'd rather be asked about, and each says so in
its own description:

- `delete_prompts` — a hard delete. The samples and the citation-lift history go
  with the question. `archive_prompts` is nearly always the better answer.
- `set_visibility_settings` — cadence × questions × engines × runs-per-question
  is how many paid engine calls happen every cycle. Values outside your plan are
  refused with a machine-readable code (`plan_cadence_not_allowed`,
  `plan_engine_limit`, `plan_sample_budget_exceeded`, …) rather than clamped, so
  an agent is told what it hit instead of quietly getting something smaller.
- `set_brand_profile` — `language` and `country` change which market future runs
  and keyword research measure. Replacing a value that is already set is refused
  with `would_overwrite` unless the agent passes `overwrite: true`.
- `set_review_window` / `set_publishing` — change whether, and when, finished
  articles go live in public (`0` hours, or `autoPublish: false`, means never).
- `set_project_context` — a whole-document write over your writer brief.
  Replacing a brief that exists needs `overwrite: true`.
- `update_post` — rewrites an article the public can already see. It keeps the
  URL, which is the point, but the old wording is gone.

There is no SQL or raw-query tool, by design.

## The limits still apply

An agent gets no special privileges. It is the same account, through a narrower
door:

- **Quota** — `generate_draft` and `generate_for_gap` consume your normal
  generation allowance and fail once it's exhausted. `run_sample` spends the
  sample-run allowance the same way.
- **Plan limits** — `create_prompts` stops at your plan's tracked-question cap
  and reports the rest as skipped with the reason, rather than failing the whole
  batch. `restore_prompts` meets the same cap. `get_visibility_settings` returns
  a `limits` object describing the envelope, so an agent can check before it
  writes.
- **Subscription** — writing needs an active subscription, exactly as the
  dashboard does. `run_sample` needs one too: it spends real budget.
- **Check before spending** — `get_account` shows the subscription and every
  allowance, and the paid tools (`start_keyword_job`, `generate_draft`,
  `generate_plan_item`, `generate_for_gap`, `run_sample`) take `dryRun: true`,
  which reports whether the call would go through and what it would spend
  without spending anything.
- **Errors are coded** — every refusal is
  `{"error": {"code", "message", "hint", "details"}}`, e.g.
  `subscription_required` (with `details.billingUrl`), `keyword_runs_exhausted`,
  `generation_quota_exhausted`, `plan_prompt_limit`, `would_overwrite`.
- **The readiness gate** — `publish_now` is refused while your site fails its
  [GEO readiness](/docs/ai-visibility) checks, the same rule
  [auto-publish](/docs/publishing) follows. Publishing into a page engines can't
  read achieves nothing. Ask the agent to run `get_geo_health` first.

## A good first conversation

> Check the GEO health of my site, then show me the three questions I'm losing
> worst. Pick the most winnable one, tell me what you'd write and in what format,
> and wait for me to say go.

Setting a project up is a conversation too:

> Here are 20 questions our customers actually ask. We sell in Indonesian — set
> the brand profile first. Group them into buckets that make sense to you, add
> these four competitor domains, then sample everything once so we have a
> baseline. Tell me what it costs before you run the sample.

Reviewing a slice of it, once samples have landed:

> For the "Hire vs retainer" topic over the last 90 days, bucketed weekly: where
> are we losing to a competitor rather than just being absent? Show me the three
> worst and who's taking them.

And pruning one, later:

> Show me the questions that have been sampled 20+ times and never once cited us.
> Archive them so we stop paying to ask, but keep the history in case we write
> for them later.

Agents are good at the loop — sample, find the gap, write for it, publish, watch
the citation rate. They are less good at knowing which gaps are worth your money.
Keep that decision.
