# TasteRay Business - Recommendation API — AI Coding Assistant Integration Guide

> Machine-readable integration rules for coding agents (Claude Code, Codex, Cursor, Windsurf).
> Product family: **TasteRay Business - Recommendation API** (also referred to as TasteRay Emotional API).
> Canonical API reference: https://api.tasteray.com/docs.md (and https://api.tasteray.com/llms.txt)
> OpenAPI 3.1 schema: https://api.tasteray.com/openapi.json
> Official Business MCP Server (`@tasteray/business-mcp`): https://github.com/tasteray/business-mcp (`npx -y github:tasteray/business-mcp`)
> Runnable Examples & Cold-Start Benchmark: https://github.com/tasteray/business-api-examples

## 1. Architecture invariants (do not violate)

1. **Server-to-server only.** Never place `X-API-Key` (`reco_live_*`) in browser JavaScript, mobile app binaries, or public environment variables. Proxy every request through a backend route or edge Worker.
2. **Use plain HTTP (`fetch`, `httpx`, `curl`).** TasteRay does not publish an npm or PyPI SDK. Do not invent or install `@tasteray/sdk` or `tasteray-python`.
3. **Stateless per request.** The API stores no user profiles and no session history. Send the user's current request context (`context.preferences` and/or `context.profile`, plus optional `context.history` up to 50 items) on every call.
4. **Two distinct operating modes:**
   - **Candidate ranking (`items` provided):** Send `items: [{ id, name, ... }]` from your own database/catalog. The API ranks and returns only items from your list, echoing your `id` and `name`. Always filter entitlements, region, inventory, and already-seen items *before* calling the API.
   - **Open discovery (`items` omitted):** The API suggests titles/items matching the vertical and context.
5. **Expect multi-second LLM latency.** Every response writes a custom explanation (`explanation.why_match` and `explanation.key_factors`) and reports `meta.processing_time_ms`.
   - Set `options.fast: true` and `options.grounding: false` for interactive UI (~2–5 s).
   - Default web grounding (`grounding: true`) takes longer because it searches the live web first.
   - Cache responses per user/mood or precompute category rows rather than calling synchronously on every page view.

## 2. Exact endpoints

| Method & Path | Auth | Purpose |
|---|---|---|
| `GET /v1/health` | None | Service health check |
| `POST /v1/recommend` | `X-API-Key` | Rank candidate `items` or generate 1–10 recommendations with written reasons |
| `POST /v1/explain` | `X-API-Key` | Deep explanation (`summary`, `detailed_reasoning`, `potential_concerns`, `alternatives`) for one item |
| `GET /v1/usage` | `X-API-Key` | Current quota usage and rate-limit status |
| `POST /v1/demo/recommend` | None (IP limited: 5/min, 25/day) | Keyless smoke test (clamped to `fast: true`, `grounding: false`, `count <= 3`) |
| `POST /v1/demo/explain` | None (IP limited: 5/min, 25/day) | Keyless explanation smoke test (clamped to `fast: true`, `grounding: false`) |

## 3. Request contract (`POST /v1/recommend`)

Required fields (enforced by `validateRecommendationRequest`):

- `vertical`: non-empty string (any noun works: `"movies"`, `"tv-series"`, `"books"`, `"games"`, `"products"`, `"restaurants"`, etc.).
- `context`: object with **at least one of**:
  - `preferences`: non-empty array of strings, OR
  - `profile`: non-empty free-text string describing who the user is and what they want right now.
- Optional `context` fields:
  - `history`: array of up to 50 `{ item: string, rating: string }` objects (e.g. `{ "item": "Arrival", "rating": "loved" }`).
  - `history_text`: free-text summary of prior likes/dislikes.
- Optional `items`: array of candidate catalog items, each requiring non-empty string `id` and non-empty string `name`.
- Optional `options`:
  - `count`: integer `1..10` (default `3`). Handle responses containing fewer items than requested.
  - `explanation_depth`: `"brief"` | `"detailed"`.
  - `language`: locale string such as `"en_US"` or `"pl_PL"`.
  - `fast`: boolean (`true` skips slow reasoning/search for interactive use).
  - `grounding`: boolean (`true` enables live web search; `false` skips it).

## 4. Minimal server-side TypeScript example

```ts
interface TasteRayCandidate {
  id: string;
  name: string;
  description?: string;
}

export async function rankWithTasteRay(params: {
  apiKey: string;
  vertical: string;
  userPrompt: string;
  candidates: Array<TasteRayCandidate>;
  count?: number;
}) {
  const response = await fetch('https://api.tasteray.com/v1/recommend', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-API-Key': params.apiKey,
    },
    body: JSON.stringify({
      vertical: params.vertical,
      context: { profile: params.userPrompt },
      items: params.candidates,
      options: {
        count: params.count ?? 3,
        explanation_depth: 'brief',
        fast: true,
        grounding: false,
      },
    }),
  });

  if (!response.ok) {
    const err = await response.text();
    throw new Error(`TasteRay API ${response.status}: ${err}`);
  }

  return response.json();
}
```

## 5. Keyless smoke test for coding agents

Before asking the developer for a production API key, verify your payload shape against the keyless demo endpoint:

```bash
curl -sS -X POST https://api.tasteray.com/v1/demo/recommend \
  -H "Content-Type: application/json" \
  -d '{
    "vertical": "movies",
    "context": {
      "profile": "Tired after a long week. Want something absorbing and humane, not loud action."
    },
    "items": [
      { "id": "tmdb-666277", "name": "Past Lives" },
      { "id": "tmdb-329865", "name": "Arrival" },
      { "id": "tmdb-545611", "name": "Everything Everywhere All at Once" },
      { "id": "tmdb-976893", "name": "Perfect Days" }
    ],
    "options": { "count": 3, "fast": true, "grounding": false }
  }'
```

Look for HTTP `200`, `recommendations[].item.name`, `recommendations[].explanation.why_match`, `recommendations[].explanation.key_factors`, and `meta.processing_time_ms`.

## 6. Rate-limit headers & error handling

Every response from `POST /v1/recommend` and `POST /v1/explain` includes (`GET /v1/usage` is unmetered and omits these headers):

- `X-RateLimit-Limit`
- `X-RateLimit-Remaining`
- `X-RateLimit-Reset` (**Unix timestamp in milliseconds**, not seconds)

When `429` is returned, back off until `Number(res.headers.get('X-RateLimit-Reset')) - Date.now()`. Self-serve tiers: Free (1,000/mo, 5/min), Basic ($49/mo, 10,000/mo, 50/min), Pro ($199/mo, 100,000/mo, 200/min), Enterprise (custom). Get a self-serve key at https://api.tasteray.com/generate-key.

## 7. Embeddable product-page alternative (ForMe widget)

If the user only wants a drop-in **"Is this for me?"** conversational verdict button on product/title pages (no backend proxy required), use the TasteRay ForMe widget instead of calling `/v1/recommend`:

- Install guide (HTML / Markdown): https://forme.tasteray.com/install · https://forme.tasteray.com/install.md
- Docs & attributes: https://forme.tasteray.com/llms.txt
- Business overview: https://www.tasteray.com/business/stores.md

## 8. Official Business MCP Server & Starter Examples

Coding agents can call the API and generate validated ForMe widget embeds directly through the official **TasteRay Business - Recommendation API & ForMe MCP Server** (`@tasteray/business-mcp`):

```bash
# Works immediately with keyless /v1/demo/* endpoints; set TASTERAY_API_KEY for /v1/*
claude mcp add tasteray-business -- npx -y github:tasteray/business-mcp
```

- **MCP Server repo:** https://github.com/tasteray/business-mcp (package `@tasteray/business-mcp`)
- **Starter examples & live cold-start benchmark:** https://github.com/tasteray/business-api-examples (TypeScript, Python, cURL, Shopify Liquid, WooCommerce PHP, React)
- **B2B vs. Consumer note:** `@tasteray/business-mcp` is for developers, merchants, and catalog operators integrating TasteRay Business APIs and ForMe. The unscoped name `@tasteray/mcp` (`tasteray/mcp`) is reserved for the future consumer TasteRay (*Your culture and entertainment guide*) server.
