# Muse connector documentation

This document describes the Calorie service for Muse connector setup and review. The service is single-tenant: the owner's agent is the only client.

A public copy of this guide is served at `/docs/muse-connector` (and `/muse-connector.md`) on the deployment. The machine-readable catalog is `/llms.txt`.

## Connection

- **Name:** Calorie
- **MCP endpoint:** `https://calorie.txe.app/mcp`
- **Transport:** Streamable HTTP
- **REST base (fallback):** `https://calorie.txe.app/api/v1`
- **Authentication:** static bearer service token
  - `Authorization: Bearer <SERVICE_TOKEN>`
  - `X-API-Key: <SERVICE_TOKEN>` is also accepted
- **Scopes:** one owner-scoped service token; no OAuth scopes in v1
- **Environment:** production only; there is one tenant and no public signup

The owner supplies the token; it is not published in this guide. Configure it as a secret in Muse. Rotate it with `wrangler secret put SERVICE_TOKEN`.

## What the connector does

The service records food entries, body weights, and manually chosen calorie/protein targets, and resolves food candidates from a local cache plus USDA FoodData Central and Open Food Facts. It does not perform coaching, expenditure estimation, or automatic target adjustment in v1.

## Tools

Read/write classifications follow the MCP annotations returned by `tools/list`.

| Tool | Class | Arguments | Returns | Side effects |
|---|---|---|---|---|
| `log_entry` | write | `meal`, `description`, `quantity`, `serving_label`, `nutrition`, `source`; optional `date`, `occurred_at`, `upc`, `food_ref`, `note`, `idempotency_key` | `{ entry, today, idempotent_replay }` | Creates one soft-deletable nutrition entry |
| `get_today` | read | optional `date` | `{ day, entries }` | None |
| `get_range` | read | `from`, `to` (inclusive, max 366 days) | `{ days, entries }` | None |
| `undo_last` | write, destructive | none | `{ undone, today }` | Soft-deletes the most recent entry |
| `delete_entry` | write, destructive | `entry_id` | `{ deleted }` | Soft-deletes one entry |
| `log_weight` | write | `weight_lb`; optional `date`, `idempotency_key` | `{ weight, trend_7d_avg_lb, idempotent_replay }` | Upserts one weight per local date |
| `get_weights` | read | `from`, `to` (inclusive, max 366 days) | `{ weights }` | None |
| `search_food` | read, open-world | exactly one of `q` or `upc`; optional `limit` 1-10 (default 5) | `{ candidates, cached }` | Caches upstream candidates; never creates an entry |
| `get_settings` | read | none | `{ settings }` | None |
| `update_target` | write | any of `target_kcal`, `target_protein_g`, `goal`; `null` clears | `{ settings }` | Updates the single settings row |

Sensitive writes: all writes affect the owner's health log. `undo_last` and `delete_entry` are destructive and should require user approval when the client supports it. There are no payments, purchases, or account-creation actions.

### Input and output notes

- `nutrition` is `{ kcal: integer >= 0, protein_g, carbs_g, fat_g }`; macros are >= 0 with at most one decimal.
- Entry nutrition is the total for the logged `quantity`, not per serving.
- `log_entry` never calls a nutrition source; the agent resolves nutrition first.
- `search_food` returns candidates only. A no-match result is `200` with `candidates: []`.
- Dates are `YYYY-MM-DD` in America/Denver; timestamps are RFC 3339 UTC.
- Weights are pounds, one decimal place, greater than zero.
- Targets start `null`; the service never invents them.

## Status and errors

REST uses standard HTTP status codes. MCP tools return `isError: true` and the same error object.

```json
{ "error": { "code": "validation_error", "message": "nutrition.kcal: Too small..." } }
```

| Code | Status | Meaning |
|---|---|---|
| `validation_error` | 400 | Invalid arguments |
| `unauthenticated` | 401 | Missing or incorrect bearer token |
| `not_found` | 404 | Unknown route |
| `nothing_to_undo` | 404 | No entry to undo |
| `entry_not_found` | 404 | Unknown or already-deleted entry |
| `idempotency_conflict` | 409 | Same idempotency key, different payload |
| `idempotency_in_progress` | 409 | Same idempotency key is still processing |
| `upstream_unavailable` | 502 | Cache miss and both nutrition sources are unreachable |
| `internal_error` | 500 | Unexpected failure (details are logged, not returned) |

## Idempotency and retries

`log_entry` and `log_weight` accept an optional UUID `idempotency_key`. Replaying the same key and payload returns the original response with `idempotent_replay: true`; a different payload returns `409`. Agents should retry `idempotency_in_progress` after a short delay.

## Rate limits

There is no application-level rate limit in v1. Cloudflare edge protections apply. Food searches are cached locally; USDA and Open Food Facts have their own upstream limits. Repeated searches for the same food hit the cache and do not call upstream.

## Test instructions

Run the server through MCP Inspector first:

```bash
npx @modelcontextprotocol/inspector@latest
```

Connect to the deployment's `/mcp` URL and add `Authorization: Bearer <SERVICE_TOKEN>`.

1. Set `SERVICE_TOKEN` in the connector configuration.
2. Call `get_settings`; on a fresh install, targets are `null` and timezone is `America/Denver`.
3. Call `get_today`; it returns an empty day with zero totals.
4. Call `search_food` with `{ "q": "greek yogurt", "limit": 5 }`; choose a candidate.
5. Call `log_entry` with the candidate's `nutrition_per_serving` scaled to the quantity being eaten.
6. Call `get_today` again; the new entry and totals appear.
7. Call `undo_last` if the test entry should be removed.

There is no separate test account; this is a single-tenant personal deployment. Use a clearly labeled description such as `"connector test entry"` and `undo_last` afterwards.

REST equivalents are available for curl-based testing; see `GET /llms.txt` on the deployment.

## Privacy and data handling

- Data is stored only in the owner's Cloudflare D1 database.
- The service does not log request payloads, secrets, or health data. Write operations record only operation metadata in an internal audit table.
- Food search queries are sent to USDA FoodData Central and Open Food Facts. No analytics or third-party tracking is used.
- Public routes (`/`, `/llms.txt`, `/health`, `/docs`, `/docs/muse-connector`, `/muse-connector.md`) contain documentation or a static status only and never expose stored data.
