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

# Search Query

Run a managed web search. Returns ranked hits, optionally with full extracted page content.

Run a natural-language web search. Returns ranked hits, optionally enriched with full extracted page text in the same call.

## HTTP Request

`POST` `{API_URL}/serverless/search`

## Request Body

| Parameter         | Type                                       | Default      | Description                                                                                                                          |
| ----------------- | ------------------------------------------ | ------------ | ------------------------------------------------------------------------------------------------------------------------------------ |
| `query`           | string (1–1024 chars)                      | **required** | Natural-language question or keyword string. Don't pre-tokenize — send the full query; the service handles query expansion for you.  |
| `depth`           | `"standard"` \| `"deep"`                   | `"standard"` | `deep` enables longer per-page extraction (up to 128 KiB / page vs. 32 KiB).                                                         |
| `max_results`     | int (1–20)                                 | `10`         | Max number of results returned. The legacy alias `top_n` is also accepted.                                                           |
| `language`        | string (≤ 8 chars)                         | `null`       | Optional ISO code hint (e.g. `"en"`, `"zh"`). Currently informational.                                                               |
| `enrich`          | bool                                       | `true`       | When `true`, top results get full page text via the routing fetcher. Set `false` if you only need titles/URLs (cuts latency 60–80%). |
| `time_range`      | `"d"` \| `"w"` \| `"m"` \| `"y"` \| `null` | `null`       | Restrict to results from past day / week / month / year. Combines with our automatic recency-intent detection — explicit value wins. |
| `include_domains` | string array (≤ 64)                        | `[]`         | Only return hits whose URL host matches one of these (host-suffix match — `example.com` covers `news.example.com`).                  |
| `exclude_domains` | string array (≤ 64)                        | `[]`         | Drop hits whose URL host matches one of these. Same matching rule as `include_domains`.                                              |

### `X-Request-Group-Id` — fan-out quota dedup

| Header               | Purpose                                                                                                                                                                                                       |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `X-Request-Group-Id` | UUID tying multiple `/search` calls of the **same user-facing prompt** into one quota slot. Critical for fan-out pipelines (deep research, agent loops). Without it, every call counts as its own quota slot. |

If your agent issues multiple sub-queries to answer one user question, supply the **same** UUID for all of them — they share one quota slot. Without the header, the server generates a fresh UUID per call (each counts as 1 group).

**Token Plan keys must send a signed token instead of a UUID.** On a plan key the group decides how much of a paid monthly allowance is consumed, so an arbitrary UUID is not accepted as evidence that several calls belong to one prompt. Mint one with [`POST /serverless/search/group`](https://docs.meganova.ai/api-reference/platform-api/search/create-request-group.md) and send the returned `token` verbatim in this header.

An unsigned value on a plan key is not an error — the call succeeds, it just earns nothing, because the server assigns a fresh group and bills it as a standalone prompt. A malformed, altered, expired, or foreign token is a `400`: a bad signature is rejected rather than quietly downgraded. Exceeding the token's fan-out budget is a `429`.

## Response

```json
{
  "data": {
    "results": [
      {
        "title":          "Best AI Agent Frameworks 2026: 6 Compared",
        "url":            "https://example.com/article",
        "description":    "Short snippet from the upstream source.",
        "content":        "Full extracted page text (populated when enrich=true).",
        "score":          0.93,
        "engine":         "primary",
        "published_date": "2026-04-15T08:00:00Z"
      }
    ],
    "usage": {
      "request_id":          "req_e80188fbf8944819bb3e2cbfab670f93",
      "upstream_calls":      6,
      "reformulations":      1,
      "cost_usd":            0.0011,
      "overage_charged_usd": 0.0,
      "duration_ms":         7685
    }
  },
  "message": "Search completed",
  "status":  "success"
}
```

### Fields

| Field                            | Description                                                                                                                                                                                      |
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `data.results[]`                 | Ranked array of hits, up to `max_results` long                                                                                                                                                   |
| `results[].title`                | Page title                                                                                                                                                                                       |
| `results[].url`                  | Page URL                                                                                                                                                                                         |
| `results[].description`          | Snippet returned by the upstream source                                                                                                                                                          |
| `results[].content`              | Full extracted page text. Populated when `enrich=true`; empty otherwise. Up to 32 KiB / page (`standard` depth) or 128 KiB / page (`deep` depth)                                                 |
| `results[].score`                | Relevance score reported by the upstream source. **Source-relative** — not comparable across sources. Order in the array is what matters                                                         |
| `results[].engine`               | Diagnostic label for the source that produced this hit. Customers don't need to act on this                                                                                                      |
| `results[].published_date`       | ISO 8601 publication date if upstream provided one. `null` for crawl-index hits with no date metadata                                                                                            |
| `data.usage.request_id`          | Unique identifier for this call. **Cache this** — useful for support tickets and debugging                                                                                                       |
| `data.usage.upstream_calls`      | Diagnostic counter for support tickets. Customers don't need to act on this                                                                                                                      |
| `data.usage.reformulations`      | Diagnostic counter for support tickets. Customers don't need to act on this                                                                                                                      |
| `data.usage.cost_usd`            | Informational only — not what you're billed. Use `overage_charged_usd` for actual charges                                                                                                        |
| `data.usage.overage_charged_usd` | Real $ debited from `credit_balance`. `0.0` when within today's free quota. Once you exceed `SEARCH_DAILY_FREE_QUOTA` distinct prompt-groups (default 50), this jumps to `\$0.002` per new group |
| `data.usage.duration_ms`         | Wall-clock latency on our side                                                                                                                                                                   |
| `status`                         | `"success"` for HTTP 200; `"failed"` for non-2xx (with an `error` object instead of `data`)                                                                                                      |
| `message`                        | Human-readable status                                                                                                                                                                            |

## Examples

### Standard search (with quota dedup)

```bash
curl -X POST '{API_URL}/serverless/search' \
  -H 'Authorization: Bearer {TOKEN/KEY}' \
  -H 'Content-Type: application/json' \
  -H "X-Request-Group-Id: $(uuidgen)" \
  -d '{
    "query": "latest AI agent frameworks 2026",
    "max_results": 5,
    "enrich": true
  }'
```

### Recency-limited + domain-filtered

```bash
curl -X POST '{API_URL}/serverless/search' \
  -H 'Authorization: Bearer {TOKEN/KEY}' \
  -H 'Content-Type: application/json' \
  -d '{
    "query": "AGI safety research",
    "time_range": "w",
    "include_domains": ["arxiv.org", "openai.com", "anthropic.com"]
  }'
```

### Snippet-only mode (no enrichment)

Cuts latency by 60–80%. Use when your downstream doesn't consume full page text.

```bash
curl -X POST '{API_URL}/serverless/search' \
  -H 'Authorization: Bearer {TOKEN/KEY}' \
  -H 'Content-Type: application/json' \
  -d '{ "query": "rust async runtime comparison", "enrich": false }'
```

### Python

```python
import os
import uuid
import requests

BASE = "{API_URL}/serverless"
HEADERS = {
    "Authorization": f"Bearer {os.environ['MEGANOVA_API_KEY']}",
    "Content-Type": "application/json",
}


def search(query, *, max_results=10, group_id=None,
           time_range=None, include_domains=None, exclude_domains=None):
    headers = dict(HEADERS)
    if group_id:
        headers["X-Request-Group-Id"] = group_id

    body = {"query": query, "max_results": max_results, "enrich": True}
    if time_range:
        body["time_range"] = time_range
    if include_domains:
        body["include_domains"] = include_domains
    if exclude_domains:
        body["exclude_domains"] = exclude_domains

    r = requests.post(f"{BASE}/search", headers=headers, json=body, timeout=30)
    r.raise_for_status()
    return r.json()["data"]


# Deep-research style — many sub-queries, one quota slot
prompt_group = str(uuid.uuid4())
for sub in ["benchmark RAG accuracy", "RAG hallucination rate", "long-context RAG"]:
    search(sub, max_results=5, group_id=prompt_group)
```

### JavaScript / TypeScript

```typescript
const BASE = "{API_URL}/serverless";
const KEY  = process.env.MEGANOVA_API_KEY!;

export async function search(query: string, opts: {
  maxResults?: number;
  groupId?: string;
  timeRange?: "d" | "w" | "m" | "y";
  includeDomains?: string[];
  excludeDomains?: string[];
} = {}) {
  const headers: Record<string, string> = {
    Authorization: `Bearer ${KEY}`,
    "Content-Type": "application/json",
  };
  if (opts.groupId) headers["X-Request-Group-Id"] = opts.groupId;

  const body: Record<string, unknown> = {
    query,
    max_results: opts.maxResults ?? 10,
    enrich: true,
  };
  if (opts.timeRange) body.time_range = opts.timeRange;
  if (opts.includeDomains?.length) body.include_domains = opts.includeDomains;
  if (opts.excludeDomains?.length) body.exclude_domains = opts.excludeDomains;

  const r = await fetch(`${BASE}/search`, {
    method: "POST",
    headers,
    body: JSON.stringify(body),
  });
  if (!r.ok) throw new Error(`Search failed: ${r.status} ${await r.text()}`);
  return (await r.json()).data;
}
```

## Related

* [Web Search overview](https://docs.meganova.ai/api-reference/platform-api/search.md)
* [Fetch URL](https://docs.meganova.ai/api-reference/platform-api/search/fetch-url.md) — extract content from a known URL
* [Get search usage](https://docs.meganova.ai/api-reference/platform-api/search/get-search-usage.md) — today's quota and spend
* [User Credit Balance](https://docs.meganova.ai/api-reference/platform-api/get-credit-balance.md)
