# Gyaansetu Web Search API

Gyaansetu's HTTP API is compatible with Tavily's (ADR-0001): the same endpoints, request fields, response shapes and errors. An agent already using Tavily's Python or JavaScript SDK, or LangChain's Tavily tool, switches by pointing the SDK's base URL at Gyaansetu's API hostname and using a Gyaansetu API Key.

## Hostnames

One Worker serves the API and the website (landing page, Google sign-in, dashboard). The `API_HOSTNAME` variable in `wrangler.jsonc` decides how requests are split:

- **Split mode** (`API_HOSTNAME` set, e.g. `"api.gyaansetu.example"`): that hostname serves only the API; every other hostname serves the website, except `/mcp` on this Worker's own `workers.dev` hostname, which also reaches the API. Point an SDK's base URL at `https://<API_HOSTNAME>`.
- **Single-hostname mode** (`API_HOSTNAME` empty, the default, and the only option on `workers.dev`, which gives a Worker one hostname): `POST /search` and `POST /extract` (also `//search` and `/search/`, as SDKs send with a trailing-slash base URL), plus `/mcp`, go to the API; every other path serves the website. Point an SDK's base URL at the Worker's own URL.

Google's OAuth redirect URI is `https://<website hostname>/api/auth/callback/google` in both modes.

## Authentication

Send `Authorization: Bearer <API Key>`. A missing or invalid API Key gets `401`. API Keys start with `gs-`; keys created before ADR-0006 start with `tvly-` and keep working.

## `POST /search`

Takes a JSON request body and answers with `query`, `answer`, `images`, `results[]` (`title`, `url`, `content`, `score`, `raw_content`, `published_date`), `response_time`, `request_id`, and `usage` when asked for. Fields Gyaansetu doesn't honour are accepted and ignored; `answer` is always `null`, and `images` and `results` are always lists.

| Field                                | How it is honoured                                                                                                                                                                                                                                                  |
| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `max_results`                        | 0 to 20 (default 10): how many Results to return.                                                                                                                                                                                                                   |
| `search_depth`                       | `basic` (default) returns the Search Provider's snippets as `content`, with a `score` from its rank. `advanced` loads each Candidate's page and returns the passages most relevant to the `query` as `content` (see below). `fast` and `ultra-fast` run as `basic`. |
| `chunks_per_source`                  | 1 to 3 (default 3): how many passages make up an `advanced` Result's `content`.                                                                                                                                                                                     |
| `include_raw_content`                | `true` or `markdown` adds each page's cleaned main content as `raw_content` in markdown, `text` as plain text; at either Search Depth. A page that fails to load has `raw_content: null` at `basic`.                                                                |
| `topic`                              | `news` asks SearXNG's news category; `finance` runs as `general`.                                                                                                                                                                                                   |
| `time_range`                         | Passed to the Search Provider (`day`/`week`/`month`/`year` or `d`/`w`/`m`/`y`).                                                                                                                                                                                     |
| `start_date`, `end_date`             | Best effort: with no `time_range`, the narrowest time range covering `start_date` is asked for, and Results dated outside the range are dropped. Undated Results are kept.                                                                                          |
| `include_images`                     | `images` lists image URLs from SearXNG's images category (at most `max_results`). Image descriptions and per-Result images are not supported.                                                                                                                       |
| `include_domains`, `exclude_domains` | Up to 300 included and 150 excluded domains. Sent to SearXNG as `site:`/`-site:` operators (up to 10 domains each), and every Search Provider's Candidates are filtered by domain. A domain covers its subdomains.                                                  |
| `language`                           | An ISO 639-1 code or English name (`fr`, `French`), passed to SearXNG.                                                                                                                                                                                              |
| `include_usage`                      | Adds `"usage": {"credits": <n>}`, the Credits the request cost.                                                                                                                                                                                                     |

An `advanced` Search asks the Search Provider for twice `max_results` Candidates (at most 20), loads each Candidate's page in parallel (as `basic` Extract Depth, 10 seconds each) and drops Candidates whose page fails to load, so a site that refuses the Worker (Stack Overflow, for one) is replaced by a spare Candidate rather than leaving the Search short. Each page is split into passages along its paragraphs, of at most 1,200 characters so that the Query and a passage fit the reranker's 512-token input, and the first 50 passages of each page are reranked against the `query` with Workers AI's `@cf/baai/bge-reranker-base`. A Result's `score` is its best passage's score, from 0 to 1; its `content` is its top `chunks_per_source` passages in page order, joined with `[...]`. Results are ordered by `score`, highest first.

A Search that finds nothing returns `200` with `results: []`. If SearXNG fails, the Search gets a `500` instead, so an agent can tell "nothing found" from "the service is broken" and retry:

```json
HTTP 500
{"detail": {"error": "Internal Server Error"}}
```

## `POST /extract`

Takes a JSON request body and answers with `results[]` (`url`, `raw_content`, `images`), `failed_results[]` (`url`, `error`), `response_time`, `request_id`, and `usage` when asked for. `results`, `failed_results` and each result's `images` are always lists; `images` is always empty.

| Field               | How it is honoured                                                                                                                                                                                                                               |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `urls`              | One URL, or a list of 1 to 20. More is a `400`.                                                                                                                                                                                                  |
| `format`            | `markdown` (default) or `text`: the page's main content, with navigation (breadcrumbs included), footers, scripts, popups and dialogs, hidden elements and diagram source (such as mermaid) removed. Code blocks are kept.                       |
| `extract_depth`     | `basic` (default) reads each page as the site serves it; `advanced` renders it in a browser (Cloudflare Browser Rendering) first, so pages built by JavaScript come out complete. Both then get the same cleanup, and each is cached separately. |
| `timeout`           | Seconds each page may take to load, 1 to 60 (default 10 at `basic`, 30 at `advanced`).                                                                                                                                                           |
| `query`             | Cuts each page's `raw_content` to its passages most relevant to the query, ranked as in an `advanced` Search: the top `chunks_per_source` in page order, joined with `[...]`.                                                                    |
| `chunks_per_source` | 1 to 5 (default 3): how many passages each page is cut to. Ignored without a `query`.                                                                                                                                                            |
| `include_usage`     | Adds `"usage": {"credits": <n>}`, the Credits the request cost.                                                                                                                                                                                  |

`include_images` and `include_favicon` are accepted and ignored.

A URL that fails (an invalid URL, a timeout, an HTTP error, a response that isn't HTML, a page Browser Rendering fails to render, or a page with nothing left after cleanup) is listed in `failed_results` with its error, and the rest of the Extract still succeeds. Cleaned pages are cached for 24 hours, by URL and Extract Depth.

## MCP: `/mcp`

Connect an MCP client to `<API_BASE_URL>/mcp`. In these examples, `<API_BASE_URL>` means the API base URL for the selected deployment mode: `https://<API_HOSTNAME>` in split mode, or the Worker's own URL in single-hostname mode. Authenticate with the API Key in an `Authorization: Bearer <API Key>` header (recommended); clients that cannot set headers can send `?apiKey=<API Key>` in the URL. A missing, invalid or revoked key gets HTTP `401` before the MCP handshake.

The server exposes two tools for the web, `gyaansetu_search` and `gyaansetu_extract` (ADR-0006). They take the same inputs as `/search` and `/extract` and use the same Search and Extract pipelines, Credits and Quota as the HTTP endpoints. MCP Search defaults to 5 Results; HTTP Search defaults to 10. MCP returns text rather than HTTP JSON: Search lists each Result's Title, URL and Content, plus Raw Content and image URLs when asked for, and has no `Answer:` section. Extract lists each successful URL with its Raw Content and failed URLs with their errors. Inputs Gyaansetu cannot honour, including `country`, `exact_match` and `include_favicon`, are accepted and ignored.

The Account Tools are six more read-only tools for the Account whose API Key you send. They return JSON text, never an API Key's secret, and none creates, renames or revokes a key.

- `gyaansetu_usage`: Credits and requests per UTC day and Channel. Takes `start_date` and `end_date` (`YYYY-MM-DD`, inclusive; the last 30 days by default, at most 366 days).
- `gyaansetu_credits`: the monthly Quota, Free Credits, Credit Balance and Available Credits.
- `gyaansetu_refusals`: requests turned away, counted per day and reason. Takes `days` (1 to 90, default 30).
- `gyaansetu_purchases`: Credit Pack purchases, newest first. Takes `limit` (1 to 100, default 20); `more` says whether older ones were left out.
- `gyaansetu_api_keys`: API Keys by name, prefix (null for keys made before prefixes were recorded), created and last used.
- `gyaansetu_buy_credits`: the link where the Account's owner buys a Credit Pack, the packs on offer, and whether they are on sale.

MCP tool calls share the Account's monthly Quota, Credit Balance and rate limit (60 requests a minute, or 300 while the Credit Balance is above zero) with HTTP and the Playground. Search and Extract cost the same as their HTTP equivalents; the Account Tools cost no Credits but count toward the rate limit. Only tool calls count; the authenticated `initialize` and `tools/list` handshake requests do not count toward usage or the rate limit. Invalid tool inputs, a used-up Quota and the rate limit return tool errors (`isError: true`) with the same messages as the HTTP errors.

### Claude Code

Use `<API_BASE_URL>` as described above, and replace the key placeholder with an API Key from the dashboard:

```sh
claude mcp add --transport http gyaansetu "<API_BASE_URL>/mcp" \
  --header "Authorization: Bearer YOUR_GYAANSETU_API_KEY"
```

### Cursor

Add this server to `mcp.json`, using `<API_BASE_URL>` as described above and replacing the key placeholder with an API Key from the dashboard:

```json
{
  "mcpServers": {
    "gyaansetu": {
      "url": "<API_BASE_URL>/mcp",
      "headers": {
        "Authorization": "Bearer YOUR_GYAANSETU_API_KEY"
      }
    }
  }
}
```

## Credits and pricing

Every Account has a Quota of 1,000 Credits per calendar month (UTC), shared by all its API Keys; it refills on the 1st. A `basic` Search costs 1 Credit and an `advanced` Search 2. An Extract costs 1 Credit per 5 successfully extracted URLs, rounded up, in each request (7 successes cost 2), at either Extract Depth and with or without a `query`; failed URLs cost nothing. The rounding is per request rather than accumulated across requests. The cost is charged after the work, for what it actually cost: a Search with zero Results, an Extract where every URL failed, a bad request and a server error cost nothing. The dashboard shows this month's usage, per UTC day.

When the Quota isn't enough, an Account can buy a Credit Pack on the dashboard: a one-time purchase (no subscription) that adds Credits to its Credit Balance. The packs are set in `src/credit-packs.ts`, which the home page, `/docs` and the dashboard all read:

<!-- prettier-ignore -->
| Credit Pack | Price |
|---|---|
| 5,000 Credits | $10 |
| 25,000 Credits | $40 |
| 100,000 Credits | $120 |

Prices are in US dollars and include any tax where the buyer lives. Dodo Payments sells the packs as the merchant of record, at its hosted checkout, which may show the price in the buyer's currency. The Credits land once Dodo confirms the payment.

Once the Quota is used up, requests spend the Account's Credit Balance: purchased Credits, which never expire. A request that crosses from one to the other takes what is left of the Quota and the rest from the Credit Balance. The dashboard shows the Credit Balance and how much of this month's usage came from each. While the Credit Balance is above zero, the rate limit is 300 requests a minute instead of 60 (see [Errors](#errors)).

An unused Credit Pack is refundable within 14 days of buying it, through support. A refund or a chargeback removes the pack's Credits; a chargeback can take the Credit Balance below zero. The Terms of Service cover payments in full.

The Quota and the Credit Balance are checked before any work. Once both are used up, requests get HTTP `432`, which Tavily's Python SDK raises as `ForbiddenError`. Its message says to buy Credits on the dashboard:

```json
HTTP 432
{"detail": {"error": "This request exceeds your plan's set usage limit. … buy Credits on the dashboard: https://…/dashboard"}}
```

A Credit Balance below zero, after a refund or chargeback, can't be spent: once the Quota is used up, requests get the same `432`, whose message points to support instead.

Concurrent requests near the end of the Quota or the Credit Balance may overshoot it slightly, taking the Credit Balance slightly below zero.

## The Playground

The dashboard's Playground runs a Search or an Extract for the signed-in Account without an API Key, through `POST /api/playground/search` and `POST /api/playground/extract` on the main hostname (session cookie). They take the same request bodies as `/search` and `/extract`, run the same pipelines, answer with the same JSON and errors, charge the Account's Quota the same way, and count against the same per-Account rate limit as its API Keys. A request with no session gets `401`.

## Errors

Every error body is `{"detail": {"error": "<message>"}}`, with these status codes: `400` bad request, `401` missing or invalid API Key, `404` unknown path, `429` rate limit reached (with `Retry-After` in seconds; 60 requests a minute per Account across its API Keys, the Playground and MCP, or 300 a minute while its Credit Balance is above zero), `432` Quota and Credit Balance used up, `500` server error.

## Where Results come from

SearXNG is the only Search Provider (ADR-0005). It asks third-party search engines and merges their results. When those engines block it, a Search returns no Results rather than an error.

Which Search Providers a Search asks is configuration: `SEARCH_PROVIDERS` in `wrangler.jsonc`, a comma-separated list of provider names (currently `searxng`). With more than one, a Search asks them all at the same time and merges their Candidates. It fails only when every one of them fails (ADR-0011).
