> For the complete documentation index, see [llms.txt](https://docs.tryterra.co/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.tryterra.co/context/context.md). Agents can also search and read this documentation through its [MCP server](https://docs.tryterra.co/~gitbook/mcp).

# Overview

Give your AI agent an end user's health data over MCP: answer open questions with get\_health\_context, or compute exact figures with the data tools.

Context gives your AI agent an [MCP](https://modelcontextprotocol.io) server for one end user's health data. The server has seven tools:

* **`get_health_context`** takes the end user's question as they asked it and returns structured, cited context: the signals that bear on it, how fresh they are, and what is missing.
* **Six data tools** (`get_sleep_data`, `get_activity_data`, `get_daily_data`, `get_body_data`, `get_nutrition_data`, `get_menstruation_data`) read one kind of record and compute totals, averages, counts and extremes for you.

Your agent doesn't make API calls, handle webhooks, trigger backfills, or store and parse data. It gets the data that bears on the question, without filling its context window.

{% hint style="info" %}
**Context is not a tool for writing Terra code.** It reads your end users' health data at runtime. To help your coding agent write a Terra integration, install the [Agent skills](https://docs.tryterra.co/developer-tools/agent-skills) and the [Terra CLI](https://docs.tryterra.co/developer-tools/terra-cli/terra-cli), which answers questions from these docs with `terra docs ask --question`. To let an assistant manage your Terra account, use the [MCP server](https://docs.tryterra.co/developer-tools/mcp-server) in Developer Tools.
{% endhint %}

## Quick install

Add the MCP configuration to your client to get started. Below are setup guides for some example AI IDEs, but you can use Context with any system that supports MCP.

You need to include your `dev-id` and `x-api-key` in the HTTP headers. You can find these on the [Terra dashboard](https://dashboard.tryterra.co) under **API keys**. The `user_id` is passed as part of the server URL.

{% tabs %}
{% tab title="Claude Code" %}
In your terminal, run the following command:

```bash
claude mcp add --transport http terra-ai https://access.tryterra.co/api/v2/mcp/<user_id> \
  --header "dev-id: <YOUR_DEV_ID>" \
  --header "x-api-key: <YOUR_API_KEY>"
```

{% endtab %}

{% tab title="Claude desktop" %}

1. In Claude Desktop, navigate to **Settings > Developer**
2. Select **Edit Config** to open the configuration file
3. Paste the following into **claude\_desktop\_config.json**

```json
{
  "mcpServers": {
    "terra-ai": {
      "url": "https://access.tryterra.co/api/v2/mcp/<user_id>",
      "headers": {
        "dev-id": "YOUR_DEV_ID",
        "x-api-key": "YOUR_API_KEY"
      }
    }
  }
}
```

{% endtab %}

{% tab title="Cursor" %}

1. Open Cursor, then navigate to **Cursor Settings > Tools & Integrations**
2. Select **New MCP Server**
3. Paste the following into **mcp.json**

```json
{
  "mcpServers": {
    "terra-ai": {
      "url": "https://access.tryterra.co/api/v2/mcp/<user_id>",
      "headers": {
        "dev-id": "YOUR_DEV_ID",
        "x-api-key": "YOUR_API_KEY"
      }
    }
  }
}
```

{% endtab %}

{% tab title="VS Code" %}

1. Open VS Code, then open the configuration file by running `MCP: Open User Configuration` in the command palette
2. Paste the following into **mcp.json**

```json
{
  "servers": {
    "terra-ai": {
      "type": "http",
      "url": "https://access.tryterra.co/api/v2/mcp/<user_id>",
      "headers": {
        "dev-id": "YOUR_DEV_ID",
        "x-api-key": "YOUR_API_KEY"
      }
    }
  }
}
```

{% endtab %}

{% tab title="Windsurf" %}

1. Open Windsurf, then navigate to **Windsurf Settings > Cascade > MCP servers**
2. Select **Manage MCP Servers**
3. Select **View raw config**
4. Paste the following into **mcp\_config.json**

```json
{
  "mcpServers": {
    "terra-ai": {
      "url": "https://access.tryterra.co/api/v2/mcp/<user_id>",
      "headers": {
        "dev-id": "YOUR_DEV_ID",
        "x-api-key": "YOUR_API_KEY"
      }
    }
  }
}
```

{% endtab %}

{% tab title="Replit" %}

1. Open Replit, navigate to the **Integrations** page, and scroll down to MCP Servers for **Replit Agent**
2. Select **Add MCP server**
3. Enter the server URL `https://access.tryterra.co/api/v2/mcp/<user_id>`
4. Add custom headers: your `dev-id` and your `x-api-key`
5. Select **Test & Save**
   {% endtab %}
   {% endtabs %}

## Tools

| Tool                    | Use it for                                                                                 | Returns                                                                                                                   |
| ----------------------- | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------- |
| `get_health_context`    | Open questions: how am I doing, how was my week, what should I look at, what data is there | Signals with evidence ids, freshness, limitations, loading status, and pointers to the data tools for more detail         |
| `get_sleep_data`        | Sleep, one row per night, dated by the morning it ended                                    | Time asleep and in bed, stages, efficiency, score, and heart rate, HRV, breathing rate, SpO2 and temperature during sleep |
| `get_activity_data`     | Workouts and other recorded sessions, one row per session                                  | Type, duration, distance, calories, heart rate, pace                                                                      |
| `get_daily_data`        | Per-day, per-week or per-month totals and averages                                         | Steps, distance, floors, calories, active time, resting heart rate, HRV, SpO2, stress and scores                          |
| `get_body_data`         | Body measurements                                                                          | Weight, body fat, BMI, blood pressure, glucose, temperature                                                               |
| `get_nutrition_data`    | Logged food and drink, per day                                                             | Calories, macronutrients and micronutrients                                                                               |
| `get_menstruation_data` | Menstrual cycle records                                                                    | Cycle day, phase, period and cycle length, fertility window                                                               |

For every field each data tool can return, see [data models](https://docs.tryterra.co/reference/health-and-fitness-api/data-models).

## Choose a tool

* **Ask `get_health_context` first for an open question.** It plans which data and which period answer the question, and returns only that.
* **Use a data tool for an exact figure over a named period**, such as an average, a total, a count, or a best or worst day. The data tools compute it from the records.
* **Don't answer from a `get_health_context` response that doesn't hold the metric and the period asked about.** If it holds something else, has no signals, or says data is still loading, query the data tools or tell the end user what is missing.

The server's own instructions tell your agent the same thing. The [skill](#give-your-agent-the-skill) puts it where your agent reads it before it picks a tool.

## Ask an open question

`get_health_context` takes these parameters:

| Parameter       | Required | Description                                                                                                                                                |
| --------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `query`         | Yes      | The end user's question, exactly as they asked it. The tool picks the data and the period from it.                                                         |
| `start_date`    | No       | Start of the period, `YYYY-MM-DD` or RFC 3339. Overrides the period it reads from the question. Pass it only when the end user named exact dates.          |
| `end_date`      | No       | End of the period, `YYYY-MM-DD` (the whole day) or RFC 3339. Requires `start_date`.                                                                        |
| `reference_id`  | No       | Read every connection the end user added under this `reference_id`, not only the one in the server URL. Pass it when the question spans all their devices. |
| `include_tools` | No       | Always include pointers to the data tools in the response. They are included anyway when the response is short and more detail is available.               |

The response is structured data, not prose. Your agent writes the answer from it.

## Query the data tools

Each data tool reads one kind of record for the end user in the server URL. They take the same parameters:

| Parameter  | Description                                                    |
| ---------- | -------------------------------------------------------------- |
| `select`   | Totals, averages, counts and extremes, computed for you        |
| `group_by` | One result per day, week, month or category                    |
| `fields`   | The records themselves                                         |
| `where`    | Filters, for example on `date`                                 |
| `order_by` | Sort order, with `limit` for the highest, lowest or latest few |
| `limit`    | The number of rows to return                                   |

Filter and group on `date`, the end user's local calendar day as `YYYY-MM-DD`. Every result has `meta.today`, the end user's current local date. `null` means there is no reading, never zero, and aggregations skip it. If nothing matches, `meta.available` lists the dates that have data.

## Give your agent the skill

The skill tells your agent which tool to call and when not to trust a `get_health_context` response. Save it as `terra-context/SKILL.md` in your agent's skills folder: `.claude/skills` for Claude Code. You can also download it from the [Context page](https://dashboard.tryterra.co/context) in the dashboard.

```markdown
---
name: terra-context
description: Answer a user's questions about their own health data (sleep, activity, daily summaries, body, nutrition, menstrual cycle) through Terra's Context MCP server. Use whenever the user asks how they slept, trained, recovered, ate, or how they are doing, or asks for a figure, trend, comparison or coverage of their wearable and health-app data.
---

# Terra Context

Terra's Context MCP server gives you read-only access to one user's health data from
the device or app they connected (Garmin, Oura, Whoop, Fitbit, Apple Health,
Google Health, Withings, MyFitnessPal and others). Every session is bound to one
connected source, so the tools already know whose data to read.

…
```

<details>

<summary>Show the full skill</summary>

````markdown
---
name: terra-context
description: Answer a user's questions about their own health data (sleep, activity, daily summaries, body, nutrition, menstrual cycle) through Terra's Context MCP server. Use whenever the user asks how they slept, trained, recovered, ate, or how they are doing, or asks for a figure, trend, comparison or coverage of their wearable and health-app data.
---

# Terra Context

Terra's Context MCP server gives you read-only access to one user's health data from
the device or app they connected (Garmin, Oura, Whoop, Fitbit, Apple Health,
Google Health, Withings, MyFitnessPal and others). Every session is bound to one
connected source, so the tools already know whose data to read.


## The tools

| Tool | What it is for |
|---|---|
| `get_health_context` | The user's question, answered with a planned summary: the right data types and period, signals with evidence, freshness and limitations. |
| `get_daily_data` | One row per local day: steps, distance, floors, calories, active time, resting heart rate, HRV, SpO2, stress, scores. |
| `get_sleep_data` | One row per sleep, dated by the morning it ended: time asleep and in bed, stages, efficiency, score, overnight heart rate, HRV, breathing rate, SpO2. |
| `get_activity_data` | One row per workout or session: type, duration, distance, calories, heart rate. |
| `get_body_data` | Body measurements: weight, body fat, blood pressure, glucose, temperature. |
| `get_nutrition_data` | Logged food and drink per day: calories, macros, micros. |
| `get_menstruation_data` | Cycle day, phase, period and cycle length, fertility window. |

A tool is only listed when the source can serve it, so read the tool list
before assuming one exists.

## How to open

**Start with `get_health_context`, passing the user's question verbatim as
`query`.** It reads the period and the metric from the question ("in
September", "last week against the week before", "my HRV"), retrieves only what
bears on it, and tells you plainly when the data is missing, stale or still
loading. Answer from it when it holds what was asked.

Go straight to a data tool instead in two cases:

- **One named figure over a named period**, where you already know the tool:
  "steps yesterday", "average resting heart rate in October", "my longest run in
  August". One `select` call returns the exact number.
- **A scheduled, morning or daily report:** call `get_daily_brief` if the server lists it.
- **Follow-ups in the same conversation**, when the last context response
  already covers the period. Reuse its signals and its drill-down descriptors.

If you do not know which tool holds a metric, or whether this source records it
at all, ask `get_health_context`: it reads the right data types for the
question and says what is missing.

## Using `get_health_context`

Arguments:

- `query` (required): the user's words, unedited. Do not paraphrase, shorten or
  translate them into keywords.
- `start_date` / `end_date`: only when the user gave exact dates. Otherwise let
  the question carry the period.
- `include_tools`: force drill-down descriptors. They come automatically when
  more detail exists.
- `reference_id`: omit it. Pass it only when the question spans every device the
  person connected, and your product passed that identifier at connection time.

Reading the response, in this order:

1. **`status` and `limitations`.** `status` is `complete`, `partial`, `no_data`
   or `error`. `limitations` are instructions, not footnotes. Two matter most:
   - *"No … values were found in the data read for this window"*: the metric
     asked about is not there. Do not answer it from the other signals. Say it
     is not available, or query the data tools.
   - *"Nothing was recorded in the period asked about. The most recent record,
     from …, is shown instead"*: you are looking at older data. Say so, with the
     date, before giving any number.
2. **`intent_plan`.** It shows how the question was understood: `start_date`,
   `end_date`, `metrics`, `required_context`. If that is not what the user
   meant, call again with explicit dates, or use the data tools.
3. **Signals.** They sit in one of two places, so check both:
   - a question about one topic returns `signals`, `evidence` and `insights` at
     the top level;
   - a broad question returns `contexts[]`, each with its own `signals`,
     `evidence`, `insights` and `status`.
4. **A signal's `value`** is either a single number (the latest record) or an
   object with `average`, `count`, `min`, `max`, `latest` and, for things that
   add up, `total`. Quote `count` with an average ("over 30 nights"). `unit` is
   on every signal.
5. **`freshness.results_window`** is the span of data actually found. If it
   ends days before now, say so before answering about "today" or "last night".
6. **`backfill_status.windows[]`**: a window marked `backfilling` or
   `never_requested` may not be fully loaded, which is normal in the first hour
   after a user connects. Say the history is still loading. Never describe
   missing rows as "you did not sleep" or "no workouts".
7. **`user_context.summary`** is what Terra remembers about this user:
   preferences, goals, defaults. Honour it without being asked.
8. **`tools.descriptors`** name a data tool with `arguments` already scoped to
   the period. They list `"fields": ["date"]` as a placeholder: keep the `where`
   exactly as given and add the fields you need.

The same metric can appear under more than one name: `average_hrv_rmssd` in the
daily context is the day's figure, `window_average_sleep_hrv_rmssd` the average
across the nights read, and `average_sleep_hrv_rmssd` the latest night alone.
Use the one that matches the question, and name which you used.

## Using the data tools

Each takes **either** `fields` **or** `select`, never both, plus optional
`where`, `group_by`, `order_by` and `limit`.

- **`fields`** returns the records themselves.
- **`select`** returns computed totals, averages, counts and extremes. Prefer it
  to adding up rows yourself.
- **`group_by` only goes with `select`**, and every selected value then needs an
  aggregation. `fields` with `group_by` is rejected.

### Rules that decide whether the answer is right

- **Filter and group on `date`.** It is the user's local calendar day,
  `YYYY-MM-DD`. A sleep is dated by the morning it ended, so last night's sleep
  has today's date. `*_timestamp` fields are UTC instants: use them only for
  clock-time questions ("what time did I wake up").
- **Take "today" from `meta.today`**, which every result carries, not from your
  own clock. Yesterday and "this week" follow from it. If
  `meta.utc_offset_seconds` is absent, the source reports no timezone and today
  is the UTC date.
- **Today's daily row is the day so far.** Leave it out of daily averages, and
  say it is partial if you report it.
- **`null` means no reading, never zero.** Aggregations skip it, so an average
  covers the days that have a value. Report the count alongside.
- **Daily data is already one row per day and sleep one row per night.** Do not
  group, sum or de-duplicate to get there. A night the device recorded in
  several sessions is one row with the total.
- **Naps are left out** of sleep queries unless the query mentions `is_nap`.
  Filter `is_nap = true` for naps only.
- **Numbers can arrive as strings.** Aggregated values, some durations and all
  `*_timestamp` values (unix milliseconds) come back as strings. Convert before
  doing arithmetic.
- **An empty result is information.** `meta.available` then gives the first and
  last date this source holds for that tool, and `meta.note` says what to check.
  Use them to tell "wrong period" from "this source has none of this".

### Units

Durations and `*_time` fields are seconds. Distance and elevation are metres,
speed metres per second, calories kcal, heart rate bpm, HRV (`avg_rmssd`,
`avg_sdnn`) milliseconds, `avg_oxygen_saturation` percent, weight kg,
temperature Celsius. `sleep_efficiency` is a ratio from 0 to 1.

### Where metrics live

- **Steps, floors, day calories, resting heart rate:** `get_daily_data`. A
  workout's steps and calories in `get_activity_data` cover that session only.
- **HRV, SpO2, breathing rate:** the night's figure in `get_sleep_data`, the
  day's in `get_daily_data`. Sources differ in which they fill.
- **Weight and body fat:** `get_body_data`, in fields such as
  `day_avg_weight_kg` and `day_avg_bodyfat_percentage`.
- **Not every source records every metric.** Some report no steps, others no
  sleep efficiency or HRV. `get_health_context` shows what this source holds.

Field names are listed in each tool's schema under `fields`. A wrong name is
answered with the closest right ones, for example: `dailies has no field
"avg_hrv_rmssd"; closest: avg_rmssd`.

### Query patterns

Each day's figures for a period. No `group_by`: the rows are already per day.

```json
{
  "fields": ["date", "steps", "resting_heart_rate"],
  "where": {"and": [
    {"filter": {"field": "date", "op": "GTE", "value": "2026-11-20"}},
    {"filter": {"field": "date", "op": "LTE", "value": "2026-11-26"}}
  ]}
}
```

An average over a period, with the number of days behind it:

```json
{
  "select": [
    {"field_name": "steps", "aggregation": "AVG", "alias": "avg_steps"},
    {"field_name": "steps", "aggregation": "COUNT", "alias": "days"}
  ],
  "where": {"and": [
    {"filter": {"field": "date", "op": "GTE", "value": "2026-10-01"}},
    {"filter": {"field": "date", "op": "LTE", "value": "2026-10-31"}}
  ]}
}
```

The best, worst or latest record: `order_by` with `limit`.

```json
{
  "fields": ["date", "steps"],
  "where": {"and": [
    {"filter": {"field": "date", "op": "GTE", "value": "2026-10-01"}},
    {"filter": {"field": "date", "op": "LTE", "value": "2026-10-31"}}
  ]},
  "order_by": [{"field": "steps", "direction": "DESC"}],
  "limit": 1
}
```

Totals per week or month, or one month against another. The key comes back as
`date_week` or `date_month` (the first day of the bucket) with a readable
`_label`. Weeks start on Sunday.

```json
{
  "select": [{"field_name": "resting_heart_rate", "aggregation": "AVG", "alias": "rhr"}],
  "group_by": [{"field_name": "date", "time_bucket": "MONTH"}],
  "where": {"and": [
    {"filter": {"field": "date", "op": "GTE", "value": "2026-09-01"}},
    {"filter": {"field": "date", "op": "LTE", "value": "2026-10-31"}}
  ]}
}
```

The most recent sleep. Ask for the latest row, not for a date you assume has
data: the device may not have synced.

```json
{
  "fields": ["date", "asleep_time", "in_bed_seconds", "deep_sleep_time", "rem_sleep_time", "sleep_efficiency", "avg_rmssd"],
  "order_by": [{"field": "date", "direction": "DESC"}],
  "limit": 1
}
```

Workouts of one type. Filter `type` by name. In grouped results the type comes
back in full, as `ACTIVITY_TYPE_RUNNING`.

```json
{
  "fields": ["date", "name", "activity_time", "distance", "avg_heart_rate"],
  "where": {"and": [
    {"filter": {"field": "type", "op": "EQ", "value": "RUNNING"}},
    {"filter": {"field": "date", "op": "GTE", "value": "2026-11-01"}}
  ]}
}
```

Sessions and distance by type:

```json
{
  "select": [
    {"field_name": "type", "aggregation": "COUNT", "alias": "sessions"},
    {"field_name": "distance", "aggregation": "SUM", "alias": "metres"}
  ],
  "group_by": [{"field_name": "type"}],
  "order_by": [{"field": "sessions", "direction": "DESC"}]
}
```

The latest weight, however long ago it was recorded:

```json
{
  "fields": ["date", "day_avg_weight_kg"],
  "order_by": [{"field": "date", "direction": "DESC"}],
  "limit": 1
}
```

Operators: `EQ`, `NEQ`, `GT`, `GTE`, `LT`, `LTE`, `IN` (a list), `LIKE` (text
fields only). Aggregations: `AVG`, `SUM`, `COUNT`, `MIN`, `MAX`, `MEDIAN`,
`STDDEV`, `PERCENTILE` (with `percentile`, 0 to 100). Time buckets: `DAY`,
`WEEK`, `MONTH`. `order_by` takes a field, a group key or an alias. Rows come
newest first by default. `limit` goes up to 1,095, and `meta.truncated` is set
when more rows matched than were returned.

## Answering well

- **Quote what Terra returned.** Never invent or extrapolate a value.
- **Say what the number covers:** the period, and how many days or nights had a
  reading.
- **Separate "no data" from "nothing happened".** A device that stopped
  syncing, history still loading, and a source that does not record a metric
  all look like empty results. `limitations`, `freshness`, `backfill_status`,
  and `meta.available` tell you which it is.
- **Say when data is old.** If the latest record is from last week, lead with
  that.
- **Do not add totals across devices.** With `reference_id`, two devices can
  both count the same steps. Report each source, or the one the user means.
- **Keep the user's calendar.** Dates in results are already local.

## Errors

- **A message describing the query mistake** (unknown field, `group_by needs an
  aggregation`, `fields` and `select` together, a value of the wrong type): fix
  the arguments as the message says and resend once.
- **Session not found, or a 404 on a session that was working:** the server was
  updated. Start a new session and repeat the call.
- **`Context is not enabled for this account`:** use the data tools.
- **A context response whose limitation says the question could not be
  interpreted:** it holds recent data, not an answer to the question. Use the
  data tools for the specific figure.
- **`404 invalid user id`:** the connection is no longer active. Do not retry;
  the user needs to reconnect.
- **A 502 or a timeout:** retry once.
- Two failed attempts at the same question is the limit. Report what you could
  not retrieve.

## What this server is not

It reads one user's data at request time. It does not connect devices, trigger
historical loads or write anything. If the user asks to connect a new source, or
their data looks stale after reconnecting, hand off to your product's connection
flow.
````

</details>

## Example questions

These go to `get_health_context`:

* How am I doing this week?
* How did I sleep last week compared to the week before?
* What should I look at in my recovery?

These go to a data tool:

* What was my average resting heart rate in October?
* What's my longest streak of days with at least 7 hours of sleep?
* Which three runs this month had the highest average heart rate?
