Skip to main content
Glama
search-gateway

search-gateway

by kabishou11

search-gateway

Self-hosted Web Search MCP for data-sensitive agents: policy-controlled egress, PII-minimized queries, and audited citations — official APIs or your own SearXNG, never search-engine scraping.

search-gateway sits between an agent and the places its searches would otherwise go. Every search runs through one pipeline, in a fixed order: a policy decision, query minimization, the selected backend, a bounded and guarded fetch of result pages, optional result-side redaction, and an audit record. It ends in citations that carry a URL, a fetch time and a content hash. The gateway speaks the Model Context Protocol (MCP) over stdio and can also be embedded as a library.

It is a policy and privacy gateway. It is not a thin wrapper around a metasearch instance, and it does not scrape.

The problem

Giving an agent a web search tool means handing whatever it writes to a third party. Queries written during real work routinely contain material that should not travel: names and email addresses, keys pasted by mistake, internal ticket numbers, project code names, intranet hostnames.

Around that single act, three things tend to be missing:

  • Control over egress. There is no single place that decides which sources may be used, which domains may never be searched for or fetched, and which queries must not leave at all.

  • Provenance for what comes back. Search results are external text that flows straight into the agent's context. Nothing records what was retrieved, when, or whether it has changed since.

  • An audit trail that is safe to keep. Logging the raw query defeats the purpose; logging nothing leaves no trail at all. The record has to say what was decided and sent without repeating what was typed.

Tools that obtain results by requesting a search engine's results page add a fourth problem: they are brittle, usually contrary to the engine's terms, and met with CAPTCHA walls.

Related MCP server: searxng-mcp

Who it is for

  • Teams that run agents near company data and need an enforceable statement of where search traffic may go: allowed sources, denied domains, denied terms, and a sink of their own for audit records.

  • Local-first users who want search without a vendor account: a self-hosted SearXNG instance or a local index, with keys to commercial APIs as an option rather than a requirement.

  • Operators of an intranet who want one search tool that answers from a first-party index and applies the same policy, fetch and audit rules as any other backend.

  • Security and compliance reviewers who need to see, in code and in tests, that the original query is not sent, that private addresses are refused, and that the audit log does not contain the raw query.

Architecture

 query ──► 1. policy ──► 2. minimization ──► 3. backend ──► 4. bounded fetch ──► 5. result redaction ──► 6. citations
              │                                                        (optional)
              └──────────────────────────── audit record ◄──────────────────────────────────────┘

Each stage fails closed. A request refused at any point returns a structured failure naming the reason, and the stages after it never run.

1. Policy

A policy pack is a handful of lists and limits, evaluated before anything is sent.

Key

Effect

policy.domains.allow

When non-empty, only results and fetches on these domains are allowed. A query that explicitly targets another domain (with site: or a URL) is refused.

policy.domains.deny

Domains that are never searched for, returned, or fetched. Results on them are dropped before anyone sees them.

policy.sources.allow / policy.sources.deny

Backend types that may be used, independent of what is configured.

policy.query.deny_terms

Case-insensitive substrings that refuse a query outright.

policy.query.max_length

Longer queries are refused, not truncated.

policy.default

deny requires every query to target an allowed domain explicitly.

A rule matches a domain and all of its subdomains. Denials are structured: they name the subject (query, URL or backend), the reason, and the rule by list and position. A query refused for a denied term cites the rule's position and does not repeat the term.

2. Query minimization

The original query exists only inside the process. Before it reaches a backend it is minimized by a conservative redactor: when in doubt, a token is replaced by a typed placeholder.

  • Built-in rules cover email addresses, phone numbers in international form, credential assignments (api_key=…), bearer credentials, well-known key prefixes, signed three-part tokens, long hexadecimal and high-entropy tokens, payment card numbers that pass the Luhn check, and private network addresses.

  • Operator rules in redaction.patterns cover internal identifiers: ticket keys, employee numbers, project codes, internal hostnames. Each becomes an [LABEL] placeholder.

  • A query with nothing searchable left after minimization is refused. The backend receives the minimized query and nothing else.

Redaction is pattern-based. It does not recognize names, addresses or other personal data that follows no fixed shape; for those, rely on the domain policy and on denied terms.

3. Backends

The set of backends is closed, and all of them are official HTTP interfaces or first-party:

Backend

What it is

Needs

searxng

A SearXNG instance you operate, queried through its JSON API and restricted to an engine allowlist

base_url, engines

brave

Brave Search API

BRAVE_API_KEY

kagi

Kagi Search API

KAGI_API_KEY

tavily

Tavily Search API, closed by default because it cannot rule out the use of queries for training at the request level (see below)

TAVILY_API_KEY, plus a confirmation

local

A local index in JSON form, which you produce, for an intranet or a single machine

index_path

Details are under Backends.

4. Bounded fetch, and untrusted content

The top results of a search can be fetched so that their citations carry a content hash. This is the gateway's server-side request forgery (SSRF) boundary, and every fetch is bounded and guarded, with every redirect hop guarded again:

  • Destination check. Only http and https. URLs with embedded credentials are refused. Loopback, private, link-local (including cloud metadata addresses), carrier-grade NAT, multicast and reserved ranges are refused for IPv4 and IPv6 alike, as are localhost and single-label or .local / .internal names. A hostname is resolved first and refused if any address it resolves to is non-public; the connection is then pinned to the addresses that were checked, so a second lookup cannot change the answer.

  • robots.txt. Checked per site, with wildcard and longest-match rules and Crawl-delay support. A robots.txt that cannot be retrieved is treated as "nothing may be fetched".

  • Rate limit. One token bucket per host, with a configurable interval, burst and maximum wait. A request that would wait longer is refused, not queued without bound.

  • Size and time. A byte limit per page, counted before and after decompression, a timeout for the whole exchange, a redirect limit, and a limit on extracted text.

  • Content types. HTML, XHTML and text/* are rendered to text. Other types are refused.

Everything that originated outside the process is marked in the data model: untrusted: true on every result, page and citation. Fetched text is third-party content. Treat it as data, never as instructions.

5. Result-side redaction (optional)

With redaction.results: true, the same redactor runs over titles, snippets and fetched text on the way back in, and each result reports how many replacements were made.

6. Citations

Every result carries a citation with at least three fields:

Field

Meaning

url

The result URL, or the final URL after redirects for a fetched page

fetchedAt

ISO 8601 time the page was fetched, or the retrieval time for a result that was not fetched

contentHash

SHA-256, hex, of the response body for a fetched page (hashOf: "page") or of title and snippet as returned (hashOf: "snippet")

Equal hashes mean equal content: the same response body for a page, the same title and snippet otherwise.

Audit

An audit record is handed to the sink for every request, allowed or refused, before the response is returned. A search that succeeds but cannot be recorded is not answered.

A record contains only configuration material and metadata: the policy decision and the rule's list and position, the backend, timestamps, counts, and the content hashes of the citations. When a query was sent, the record holds its minimized form and how many replacements were made. It never holds the original query, and it holds no result URLs, because a result URL can give away what a search was about.

As a last line of defense, the minimized query in a record is scanned once more before the record leaves for the sink, and a record that still contains redactable material is refused.

Records go where you say: nowhere (the default), a local file, or an HTTP collector you operate. An embedder can supply any sink in code. There is no first-party cloud and no telemetry.

Installation and configuration

Requirements

  • Node.js 20 or newer.

  • A backend: either a local index (included as an example), a SearXNG instance you operate, or keys to commercial search APIs. No key is needed to install, test or run the smoke check.

Install, test, smoke

npm install
npm test        # type-checks the sources, tests and scripts, then runs the test suite
npm run smoke   # loads the example configuration, connects an MCP client, runs two searches

Run

npm start -- --config config.yaml          # straight from the sources
npm run build && node dist/bin.js --config config.yaml   # from the build output

The path may also be given with SEARCH_GATEWAY_CONFIG. Without either, config.yaml in the working directory is used. The server speaks MCP over stdio; diagnostics go to stderr. In an MCP host's configuration:

{
  "mcpServers": {
    "search-gateway": {
      "command": "node",
      "args": ["/opt/search-gateway/dist/bin.js", "--config", "/opt/search-gateway/config.yaml"]
    }
  }
}

Start from the example: copy config.example.yaml to config.yaml. Relative paths inside the file are resolved against the file's own directory.

Tools

Tool

Arguments

Returns

search

query (required), backend, limit, fetch

Results with citations, the minimized query, the policy decision, dropped-result counts and a fetch summary

fetch

url (required)

One page, marked untrusted, with its citation

A refused request comes back as a tool error whose structured content holds the failure: an error code and message and, for a policy decision, the decision itself. Result fields are described by each tool's output schema.

Configuration reference

Key

Default

Notes

policy.default

allow

deny requires an explicit allowed domain in every query

policy.domains.allow / deny

[]

Bare domains; *.example.org is accepted and means the same as example.org

policy.sources.allow / deny

[]

Backend types

policy.query.deny_terms

[]

Case-insensitive substrings

policy.query.max_length

500

search.backend

the only configured backend

Required when more than one is configured

search.limit

10

1 to 50

redaction.patterns

[]

label, pattern, optional flags (i m s u v)

redaction.results

false

Redact snippets and fetched text on the way back in

fetch.enabled

true

Can be overridden per request

fetch.max_pages

3

Pages attempted per search

fetch.timeout_ms

10000

For the whole exchange

fetch.max_bytes

1048576

Per page

fetch.max_redirects

3

Each hop is checked again

fetch.max_text_chars

20000

Of extracted text per page

fetch.robots_cache_ms

3600000

Per site

fetch.rate_limit.interval_ms / burst / max_wait_ms

1000 / 2 / 5000

Per host

fetch.user_agent

search-gateway/0.1.0

A contact address is good practice

audit.sink

none

none, file or http

Unknown keys, values out of range, patterns that do not compile, a selected backend that is not configured, and an engine the SearXNG adapter refuses are all configuration errors: the gateway does not start.

Backends

SearXNG

The adapter calls the instance's JSON API (/search?format=json) and passes the engine allowlist with every request. It keeps only hits produced by allow-listed engines. The JSON output format must be enabled on the instance (search.formats in its settings.yml); otherwise the instance answers 403, and the gateway reports that as the cause.

The adapter never requests a results page itself, and it refuses to configure an engine that obtains results by doing so: google, bing, baidu, yandex and duckduckgo are rejected as engine names. Other engines are your responsibility; choose ones whose terms you can meet.

Brave and Kagi

Of the commercial APIs, prefer these two. Both adapters call the vendor's documented HTTP interface with a bearer or subscription token read from the environment. Redirects are never followed with credentials attached, responses are size-bounded, calls are time-bounded, and error messages carry neither the key nor the query.

Tavily, and the training default

Tavily's Search API has no per-request switch that controls whether queries are used for training or service improvement. Tavily's published privacy policy states that query data may be used to improve responses to future queries unless the contract provides otherwise. Whether queries are so used is therefore settled by contract, not by a request field, and no request the gateway could send would change it.

So the default guarantees the only thing it can: the Tavily adapter is closed and sends nothing. backends.tavily.training_opt_out_confirmed defaults to false, and while it stands a request for the Tavily backend fails closed with a message that says why. No query, minimized or otherwise, leaves the process.

To open it, set training_opt_out_confirmed: true, which is your confirmation that your Tavily agreement excludes the use of queries for training and service improvement. Review the current terms before you do. Once open, the adapter also leaves every optional request feature that would derive more than raw results from the query switched off: include_answer, include_raw_content, include_images and auto_parameters are all false.

Local index

A JSON file, either a bare array or an object with a documents array:

{
  "documents": [
    { "url": "https://intranet.example/docs/cache", "title": "Cache", "text": "…", "keywords": ["cache", "ttl"] }
  ]
}

title, text and keywords are matched against the query terms; url is required. The index is loaded when the backend is built, and a file that cannot be read or parsed stops the gateway from starting. Results pass through the same policy, fetch and audit stages as any other backend. local-index.example.json shows the shape.

Audit sinks

audit.sink

Behavior

none (default)

Records are written nowhere

file

One JSON record per line at audit.file.path, created with owner-only permissions; concurrent writes are serialized

http

Each record posted as JSON to audit.http.url, with optional headers and a timeout

A record that cannot be written or delivered fails the request that produced it. To use a sink of your own, pass an object with a write(record) method as auditSink when you create the gateway in code.

Using it from code

After npm run build, npm install /path/to/search-gateway makes the library importable from another project. The same functions can be imported from src/ directly inside this repository.

import { buildGateway, loadConfigFile } from "search-gateway";

const gateway = buildGateway(await loadConfigFile("config.yaml"));
const result = await gateway.search({ query: "caching guide for the reverse proxy", fetch: true });

if (result.ok) {
  for (const citation of result.citations) {
    console.log(citation.url, citation.fetchedAt, citation.contentHash);
  }
} else {
  console.error(result.error.code, result.error.message, result.policy);
}

Every dependency is injectable at this level: backends, the page fetcher, the audit sink, the clock, and the environment and HTTP implementation used by backends. That is how the tests run with no network access.

Tests

npm test type-checks everything and then runs the suite with the built-in Node.js test runner. Backends and page fetches are mocked; no test needs a network connection or an API key.

Requirement

Where it is covered

A. Policy allow

test/policy.test.ts, test/pipeline.test.ts

B. Policy deny, with the backend never called

test/policy.test.ts, test/pipeline.test.ts

C. Query redaction before the backend

test/redaction.test.ts, test/pipeline.test.ts

D. Audit hygiene

test/audit.test.ts, test/pipeline.test.ts

E. Citations with url, fetch time and content hash

test/pipeline.test.ts, test/fetch.test.ts, test/mcp.test.ts

F. SSRF refusal, failing closed

test/ssrf.test.ts, test/fetch.test.ts

G. Tavily training default

test/tavily.test.ts

H. No results-page scraping provider

test/registry.test.ts

The suite also covers the bounded fetch (robots.txt, rate limits, byte and time limits, redirects), every audit sink, configuration validation, the MCP tool surface end to end, and this repository's own hygiene.

What this is not

  • A scraper. It never requests the results pages of Google, Bing, Baidu, Yandex or any other search engine, it exposes no such backend, and it refuses the SearXNG engines that work that way.

  • A way around bot protection. It performs no CAPTCHA solving and no anti-bot circumvention, and it honors robots.txt rather than working around it.

  • A promise about installation. The claim that "just installing locally means queries never leave the machine" is false, and this project does not make it. Queries leave for whichever backend answers them, and result pages are fetched from their hosts. What stays on the machine is the original query: only its minimized form is sent, and only to the backend you configured.

  • A search engine. It does not crawl, build or host a global web index, and it is not a replacement for one. The local index holds whatever you put in it.

  • A fork. It contains no code from mcp-searxng-relay or Wigolo, and no AGPL-licensed code. The implementation is original and MIT-licensed.

One more limitation belongs here: the vendor adapters are implemented against the documented HTTP interfaces of Brave, Kagi and Tavily and are covered by tests that mock the HTTP layer. They have not been exercised against the live services in this release.

License

MIT. See LICENSE.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      A
      quality
      C
      maintenance
      An MCP server for SearXNG that provides web search capabilities with concise model-visible output while preserving full result payloads in metadata. It supports search, parallel fetching, URL extraction, and research workflows through both local stdio and streamable HTTP transports.
      2
      7
      4
      -
    • A
      license
      A
      quality
      B
      maintenance
      MCP server for private web search via self-hosted SearXNG with local reranking, full-page content fetching via Firecrawl, and optional Ollama-powered query expansion and summaries.
      7
      606 npm
      30
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      MCP server for internet search via direct Google and DuckDuckGo HTML scraping with AI-powered result normalization and optional summarization, requiring no API keys for search.
      MIT