# Google CSE Migration Gateway (`vamsi-krishna/cse-migration-gateway`) Actor

Drop-in Google Custom Search JSON API alternative for teams migrating before Jan 2027. Import CX XML, run Standby /customsearch/v1 API with Brave or Tavily BYOK, audit migrations in batch, and return citation-ready Vertical RAG chunks. Demo with mock provider—no API key. Not affiliated with Google.

- **URL**: https://apify.com/vamsi-krishna/cse-migration-gateway.md
- **Developed by:** [Vamsi Krishna](https://apify.com/vamsi-krishna) (community)
- **Categories:** AI, Developer tools
- **Features:** Limited permissions, Single-tenant, Server interface
- **Stats:** 2 total users, 1 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $1.80 / 1,000 search requests

This Actor is paid per event and usage. You are charged both the fixed price for specific events and for Apify platform usage.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

### What does Search Migration Gateway do?

**Search Migration Gateway** is a drop-in **Google Custom Search JSON API** / [Programmable Search Engine](https://developers.google.com/custom-search/v1/overview) alternative for teams migrating before the **January 1, 2027** retirement. It imports your existing CX XML profiles, runs licensed web search via **Brave** or **Tavily** (BYOK), and optionally returns citation-ready **Vertical RAG** chunks—without unauthorized SERP scraping.

This Actor is **not** affiliated with, endorsed by, or made by Google. It does **not** reproduce exact Google ranking, result counts, spelling, or PageMap.

See the [compatibility matrix](docs/compatibility-matrix.md) for Supported / Approximate / Unsupported behavior.

### Why migrate from Google CSE?

- Keep clients that call `GET /customsearch/v1` with a base-URL + auth change
- Reuse portable CX assets: `context.xml`, `annotations.xml`, `promotions.xml`, `synonyms.xml`
- Run a persistent HTTP API on Apify **Standby**
- Enrich results with reconstructed metadata and RAG chunks
- Audit migration quality with `POST /v1/migrate/compare` or `batch_audit` dataset exports

### What data can Search Migration Gateway return?

| Field / area | Type | Description |
|---|---|---|
| `items[].title` / `link` / `snippet` | string | CSE-shaped result fields |
| `items[].pagemap` | object | Reconstructed when enrichment is on |
| `promotions` | array | CX promotions matched for the query |
| `extensions.enrichment.chunks` | array | Citation-ready RAG chunks |
| `extensions.compatibility` | object | Warnings, original vs provider query |
| Batch diffs | object | `order_changed`, `removed_domains`, promotions, timings |

### How to migrate a Custom Search Engine

**Quick demo (no API key needed):** Set `default_provider=mock` and `gateway_token=smg-demo-token` to try the full API immediately using synthetic results. No BYOK key required.

**Production setup:**

1. Set Actor input: `mode=standby`, **`gateway_token`**, **`default_provider`** (`brave` or `tavily`), matching BYOK key (`brave_api_key` or `tavily_api_key`), `storage_backend=kvs`.
2. Start Standby. URL shape: `https://<username>--search-migration-gateway.apify.actor`.
3. Check `GET /healthz` and `GET /readyz`.
4. Import XMLs: `POST /v1/cx/import` (multipart).
5. Activate: `POST /v1/cx/{cx}/activate` with `{ "version": N }`.
6. Point CSE clients at the Standby host. Send `Authorization: Bearer <gateway_token>` (or `X-Api-Key`). Google SDK `key=` query auth is **not** enough—use a custom HTTP adapter or switch to Bearer.
7. Optionally run `POST /v1/migrate/compare` or re-run with `mode=batch_audit`.
8. Rollback if needed: `POST /v1/cx/{cx}/rollback` with `{ "version": N }`.

OpenAPI: `/docs` on your Standby URL.

#### Useful endpoints

| Method | Path | Purpose |
|---|---|---|
| `GET` | `/healthz` | Liveness |
| `GET` | `/readyz` | Storage readiness |
| `POST` | `/v1/cx/import` | Import CX XML |
| `POST` | `/v1/cx/{cx}/activate` | Activate draft |
| `POST` | `/v1/cx/{cx}/rollback` | Rollback active version |
| `GET` | `/customsearch/v1` | Drop-in CSE JSON API |
| `POST` | `/v1/search` | Canonical search |
| `POST` | `/v1/rag/search` | Search + RAG |
| `POST` | `/v1/pages/extract` | Free utility: fetch/extract URLs (max 10) |
| `POST` | `/v1/migrate/compare` | Provider-raw vs CX-policy diff report |

### How much will it cost?

**Normal (non-Standby) runs:** pay-per-event (PPE) charges below **include Apify platform usage**. You still pay Brave/Tavily under your own key (BYOK) when those providers are used.

**Standby (live HTTP API):** PPE events do **not** cover platform usage. You pay three layers:

1. Apify **pay-per-event** charges below
2. Apify **Standby compute** (while the server is up / idle)
3. **Brave or Tavily** usage under your own key (BYOK) — billed by that provider

| Event | Price | When |
|---|---:|---|
| `apify-actor-start` | $0.00005 | Actor run start (platform synthetic) |
| `search` | $0.003 | Successful search (`enrichment_mode` not `rag`) |
| `rag-search` | $0.015 | Successful RAG search |
| `profile-import` | $0.25 | Successful CX profile activation |
| `migration-report` | $1.00 | Completed migrate compare / batch audit |

**Example (Standby):** ~1,000 searches ≈ **$3 PPE** + Brave/Tavily (~$5/1k on typical Search plans) + Standby compute. RAG is higher ($15 PPE per 1,000) because pages are fetched and chunked.

`/v1/pages/extract` is a **free utility** (no PPE event) but still consumes Standby compute.

### Input

See the **Input** tab for the full schema.

| Field | Description |
|---|---|
| `mode` | `standby` (HTTP API) or `batch_audit` (dataset export) |
| `gateway_token` | Secret Standby API token (required for auth) |
| `default_provider` | `brave` (default), `tavily`, or `mock` (demo/test — no API key needed) |
| `brave_api_key` | Brave Search BYOK key (required when `default_provider=brave`) |
| `tavily_api_key` | Tavily BYOK key (`tvly-...`) (required when `default_provider=tavily`) |
| `storage_backend` | `kvs` (platform, survives restarts) or `sqlite` (local) |
| `audit_cx` / `audit_queries` | Batch audit inputs |

### Output

You can download the dataset in various formats such as JSON, HTML, CSV, or Excel.

#### Example CSE-shaped item

```json
{
  "kind": "customsearch#result",
  "title": "Example Security Guide",
  "link": "https://docs.example.com/security",
  "displayLink": "docs.example.com",
  "snippet": "Overview of SOC 2 controls…"
}
```

#### Example migration audit row

```json
{
  "query": "soc2 checklist",
  "cx": "my-engine",
  "status": "success",
  "order_changed": true,
  "removed_domains": ["partner.org"],
  "promotion_count": 1,
  "first_link": "https://docs.example.com/security",
  "duration_ms": 342.5
}
```

CX profiles persist in the Key-Value Store as `{cx}_v{version}`, `versions_{cx}`, and `active_{cx}`.

### Tips and advanced options

- **Demo mode:** Set `default_provider=mock` to run a full demo with synthetic results — no Brave/Tavily key required. Useful for testing the full pipeline before committing to a provider.
- Prefer `kvs` on Apify so profiles survive Standby restarts; use `sqlite` for local `apify run`.
- Auth: Bearer or `X-Api-Key` must match `gateway_token`. Local only: `SEARCH_GATEWAY_DISABLE_AUTH=1`.
- Per-request provider override: `provider=tavily|brave` on POST body / query, plus `X-Tavily-Key` / `X-Brave-Key` / `X-Provider-Key`.
- Keep `top_n_rag` small; enrichment has concurrency and deadline caps.
- Remaining gaps: no Google legacy BYOK baseline adapter yet; image search unsupported; no exact Google parity.

### FAQ, disclaimers, and support

#### Do I need a search key and a gateway token?

Yes for production Standby: a BYOK key for your chosen provider (`brave_api_key` or `tavily_api_key`) and `gateway_token` for API auth.

#### Why 401 Unauthorized?

Missing/wrong Bearer or `X-Api-Key`, or Actor started without `gateway_token`.

#### Can results contain personal data?

> Our Actors are ethical and do not extract private user data that is not publicly available. Search snippets and fetched page content may still include personal data that websites publish. Personal data is protected by the GDPR and other regulations. You should not process personal data unless you have a legitimate reason. If you are unsure, consult your lawyers.

#### Where can I get help?

- **Issues** tab on the Actor page
- **API** tab for programmatic access
- `/docs` on Standby for OpenAPI

# Actor input Schema

## `mode` (type: `string`):

Console Start uses batch_audit (finite migration audit run). Live HTTP API uses Standby mode (persistent server). Default remains standby when mode is omitted (e.g. Standby starts).

## `default_provider` (type: `string`):

Upstream search provider used when the request does not override provider. Use 'mock' for a demo/test run that needs no API key.

## `brave_api_key` (type: `string`):

Your Brave Search subscription API key. Required when default_provider is 'brave'.

## `tavily_api_key` (type: `string`):

Your Tavily API key (tvly-...). Required when default_provider is 'tavily'.

## `gateway_token` (type: `string`):

Shared secret for Standby API auth. Clients must send it as Authorization: Bearer <token> or X-Api-Key. Leave empty to disable auth (not recommended in production).

## `storage_backend` (type: `string`):

Storage backend for profile persistence. Use 'kvs' on Apify (profiles survive Standby restarts). Use 'sqlite' for local apify run.

## `audit_cx` (type: `string`):

CX ID to run regression audit for in batch mode.

## `audit_queries` (type: `array`):

List of test queries to run during batch migration audit.

## Actor input object example

```json
{
  "mode": "batch_audit",
  "default_provider": "mock",
  "gateway_token": "smg-demo-token",
  "storage_backend": "kvs",
  "audit_cx": "demo-cx",
  "audit_queries": [
    "apify actors",
    "web scraping tools"
  ]
}
```

# Actor output Schema

## `dataset` (type: `string`):

Dataset of batch_audit query outcomes (query, status, timing, top hit)

## `keyValueStore` (type: `string`):

Key-Value Store keys for versioned CX profiles and active pointers

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "mode": "batch_audit",
    "default_provider": "mock",
    "gateway_token": "smg-demo-token",
    "storage_backend": "kvs",
    "audit_cx": "demo-cx",
    "audit_queries": [
        "apify actors",
        "web scraping tools"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("vamsi-krishna/cse-migration-gateway").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "mode": "batch_audit",
    "default_provider": "mock",
    "gateway_token": "smg-demo-token",
    "storage_backend": "kvs",
    "audit_cx": "demo-cx",
    "audit_queries": [
        "apify actors",
        "web scraping tools",
    ],
}

# Run the Actor and wait for it to finish
run = client.actor("vamsi-krishna/cse-migration-gateway").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "mode": "batch_audit",
  "default_provider": "mock",
  "gateway_token": "smg-demo-token",
  "storage_backend": "kvs",
  "audit_cx": "demo-cx",
  "audit_queries": [
    "apify actors",
    "web scraping tools"
  ]
}' |
apify call vamsi-krishna/cse-migration-gateway --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,vamsi-krishna/cse-migration-gateway"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/QtfYApY0FVZqMA8AH/builds/3mq7Uv8eov81FkFJt/openapi.json
