### Initialize and Start MCP HTTP Server Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/api-reference.md Example of how to initialize and start the MCP HTTP server using the `createHttpServer` and `createMcpServer` functions. Ensure the server is listening on the desired port. ```typescript import { createHttpServer, createMcpServer } from "mcp-searxng"; const app = await createHttpServer(createMcpServer); const server = app.listen(3000, "0.0.0.0", () => { console.log("MCP HTTP server running on http://0.0.0.0:3000"); }); ``` -------------------------------- ### Start MCP SearXNG with Authentication Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/README.md Starts the MCP SearXNG server with authentication enabled. Set SEARXNG_URL, AUTH_USERNAME, AUTH_PASSWORD, and MCP_HTTP_PORT environment variables. ```bash export SEARXNG_URL=https://searxng.example.com export AUTH_USERNAME=user export AUTH_PASSWORD=pass export MCP_HTTP_PORT=3000 npx mcp-searxng ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/CONTRIBUTING.md Clone the repository, set up the upstream remote, and install project dependencies. ```bash git clone https://github.com/YOUR_USERNAME/mcp-searxng.git cd mcp-searxng git remote add upstream https://github.com/ihor-sokoliuk/mcp-searxng.git npm install ``` -------------------------------- ### Start Production-Hardened MCP SearXNG Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/README.md Starts the MCP SearXNG server with production hardening configurations, including HTTP port, authentication token, and allowed origins. Ensure all relevant environment variables are correctly set. ```bash export SEARXNG_URL=https://searxng.example.com export MCP_HTTP_PORT=3000 export MCP_HTTP_HARDEN=true export MCP_HTTP_AUTH_TOKEN=your-secret-token export MCP_HTTP_ALLOWED_ORIGINS=https://app.example.com npx mcp-searxng ``` -------------------------------- ### Example: Logging Messages Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/api-reference.md Provides examples of logging messages with different levels and including additional context data. Ensure the McpServer instance and necessary imports are available. ```typescript import { logMessage } from "mcp-searxng/logging"; logMessage(mcpServer, "info", "Search started", { query: "TypeScript" }); logMessage(mcpServer, "warning", "Slow response", { duration: 5000 }); ``` -------------------------------- ### Local Development (STDIO Mode) Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/README.md Starts MCP SearXNG in STDIO mode for local development. SEARXNG_URL must be configured. ```bash export SEARXNG_URL=http://localhost:8080 # No HTTP_PORT, runs in STDIO mode npx mcp-searxng ``` -------------------------------- ### Start MCP SearXNG in STDIO Mode Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/README.md Starts the MCP SearXNG server in its default Standard Input/Output mode. Ensure the SEARXNG_URL environment variable is set to your SearXNG instance. ```bash export SEARXNG_URL=http://localhost:8080 npx mcp-searxng ``` -------------------------------- ### Start MCP SearXNG in HTTP Mode Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/README.md Starts the MCP SearXNG server in HTTP mode, listening on a specified port. Requires SEARXNG_URL and MCP_HTTP_PORT environment variables to be set. ```bash export SEARXNG_URL=http://localhost:8080 export MCP_HTTP_PORT=3000 npx mcp-searxng ``` -------------------------------- ### Example: Create and use ProxyAgent with fetch Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/api-reference.md Demonstrates how to create proxy agents for SearXNG search and URL reading, and then use them with the fetch API. Ensure necessary imports are included. ```typescript import { createProxyAgent, ProxyType } from "mcp-searxng/proxy"; // Create proxy for SearXNG search const searchProxy = createProxyAgent( "https://searxng.example.com/search", ProxyType.SEARCH ); // Create proxy for URL reader (different proxy) const urlReaderProxy = createProxyAgent( "https://example.com/article", ProxyType.URL_READER ); // Use in fetch const response = await fetch(url, { dispatcher: searchProxy || createDefaultAgent() }); ``` -------------------------------- ### MCP Tool Call Request Example Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/endpoints.md Example of a subsequent POST request to the /mcp endpoint for executing a tool call. Requires an 'mcp-session-id' header. ```json {"jsonrpc":"2.0","id":2,"method":"tools/call",...} ``` -------------------------------- ### Install MCP SearXNG Globally via NPM Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/README.md Use this command to install the MCP SearXNG package globally on your system using npm. ```bash npm install -g mcp-searxng ``` -------------------------------- ### main() Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/api-reference.md The main entry point for the MCP SearXNG server. This function starts either an HTTP server or a STDIO transport based on configuration, handling server startup and graceful shutdown. ```APIDOC ## main() ### Description Entry point for the MCP SearXNG server. Starts either an HTTP server (if `MCP_HTTP_PORT` is set) or a STDIO transport (default). ### Method Not applicable (Async Function Call) ### Parameters None ### Behavior - **HTTP Mode**: If `MCP_HTTP_PORT` is set, parses the port, resolves the bind host, creates an Express HTTP server with MCP endpoints, and listens for incoming connections - **STDIO Mode** (default): Creates a single `McpServer`, wraps it with `StdioServerTransport`, and waits for MCP client connections via stdin/stdout - Displays helpful startup messages to stderr when running in a terminal - Handles graceful shutdown on `SIGINT` and `SIGTERM` (HTTP mode only) ### Port Validation Port must be an integer between 1 and 65535. Invalid values cause `process.exit(1)`. ### Example ```typescript import { main } from "mcp-searxng"; // Start server in default STDIO mode await main(); // Or with MCP_HTTP_PORT=3000, starts HTTP server on port 3000 ``` ``` -------------------------------- ### Configure Search Proxies and Bypass Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/configuration.md Set HTTP and HTTPS proxies for SearxNG search requests and define hosts/domains to bypass proxying. This example demonstrates setting specific search proxies and a no-proxy list. ```bash export SEARCH_HTTP_PROXY=http://proxy.company.com:8080 export SEARCH_HTTPS_PROXY=http://proxy.company.com:8080 export NO_PROXY="localhost,127.0.0.1,.company.internal" ``` -------------------------------- ### Full MCP SearxNG Configuration Example Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/CONFIGURATION.md This JSON snippet shows a complete configuration for an MCP SearxNG client, including all optional environment variables for SearxNG integration, proxy settings, and HTTP transport hardening. Use this as a template to customize your deployment. ```json { "mcpServers": { "searxng": { "command": "npx", "args": ["-y", "mcp-searxng"], "env": { "SEARXNG_URL": "YOUR_SEARXNG_INSTANCE_URL", "SEARXNG_TIMEOUT_MS": "10000", "FETCH_TIMEOUT_MS": "10000", "SEARXNG_LITE_TOOLS": "false", "SEARXNG_DEFAULT_LANGUAGE": "en", "SEARXNG_DEFAULT_SAFESEARCH": "0", "SEARXNG_MAX_RESULTS": "10", "SEARXNG_MAX_RESULT_CHARS": "500", "URL_READ_MAX_CHARS": "2000", "URL_READ_MAX_CONTENT_LENGTH_BYTES": "5242880", "CACHE_TTL_MS": "86400000", "CACHE_MAX_ENTRIES": "500", "AUTH_USERNAME": "your_username", "AUTH_PASSWORD": "your_password", "USER_AGENT": "MyBot/1.0", "URL_READER_USER_AGENT": "Mozilla/5.0 (compatible; MyBot/1.0)", "SEARCH_HTTP_PROXY": "http://search-proxy.company.com:8080", "SEARCH_HTTPS_PROXY": "http://search-proxy.company.com:8080", "URL_READER_HTTP_PROXY": "http://reader-proxy.company.com:8080", "URL_READER_HTTPS_PROXY": "http://reader-proxy.company.com:8080", "HTTP_PROXY": "http://global-proxy.company.com:8080", "HTTPS_PROXY": "http://global-proxy.company.com:8080", "NO_PROXY": "localhost,127.0.0.1,.local,.internal", "MCP_HTTP_PORT": "3000", "MCP_HTTP_HOST": "0.0.0.0", "MCP_HTTP_HARDEN": "true", "MCP_HTTP_AUTH_TOKEN": "replace-me", "MCP_HTTP_ALLOWED_ORIGINS": "https://app.example.com", "MCP_HTTP_ALLOWED_HOSTS": "app.example.com", "MCP_HTTP_ALLOW_PRIVATE_URLS": "false", "MCP_HTTP_EXPOSE_FULL_CONFIG": "false" } } } } ``` -------------------------------- ### Example: Use Default Agent with fetch Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/api-reference.md Shows how to use the createDefaultAgent function with the fetch API. If no system CAs are found, it falls back to Node's default behavior. ```typescript import { createDefaultAgent } from "mcp-searxng/proxy"; const response = await fetch(url, { dispatcher: createDefaultAgent() // or undefined, falls back to Node defaults }); ``` -------------------------------- ### Use HTTP Security Configuration Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/api-reference.md Example of how to retrieve and use the HTTP security configuration. Check the `harden` property to determine if security hardening is enabled and log allowed origins. ```typescript import { getHttpSecurityConfig } from "mcp-searxng/http-security"; const config = getHttpSecurityConfig(); if (config.harden) { console.log("Security hardening enabled"); console.log("Allowed origins:", config.allowedOrigins); } ``` -------------------------------- ### Start MCP SearXNG Server Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/api-reference.md Serves as the main entry point for the MCP SearXNG server, initiating either an HTTP server or a STDIO transport based on environment configuration. Handles graceful shutdown in HTTP mode. ```typescript export async function main(): Promise ``` ```typescript import { main } from "mcp-searxng"; // Start server in default STDIO mode await main(); // Or with MCP_HTTP_PORT=3000, starts HTTP server on port 3000 ``` -------------------------------- ### Kubernetes/Docker Health Check Usage Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/endpoints.md Examples for integrating the /health endpoint into Kubernetes liveness/readiness probes or Docker health checks. ```bash # Kubernetes liveness/readiness probe curl -f http://localhost:3000/health || exit 1 # Docker health check HEALTHCHECK CMD curl -f http://localhost:3000/health || exit 1 ``` -------------------------------- ### Start MCP SearXNG in HTTP Mode and Test Health Check Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/README.md This bash script demonstrates how to start MCP SearXNG in HTTP mode and then test its health check endpoint using curl. ```bash MCP_HTTP_PORT=3000 SEARXNG_URL=http://localhost:8080 mcp-searxng curl http://localhost:3000/health ``` -------------------------------- ### Set SEARXNG_URL Environment Variable Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/errors.md Provides an example of how to set the `SEARXNG_URL` environment variable, which is required for the MCP SearXNG server to function. This is a common fix for configuration errors. ```bash export SEARXNG_URL=http://localhost:8080 # or https://search.example.com ``` -------------------------------- ### Set User-Agent for Web Scraping Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/errors.md Example of setting the USER_AGENT environment variable to mimic a browser. This can help bypass bot detection or geo-restriction issues when reading website content. ```bash export USER_AGENT="Mozilla/5.0 (Windows NT 10.0; Win64; x64)" ``` -------------------------------- ### MCP Server-Sent Events Notifications Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/endpoints.md Example of Server-Sent Events (SSE) stream from the GET /mcp endpoint. Each event contains a JSON-RPC notification. ```text event: message data: {"jsonrpc":"2.0","method":"notifications/logging","params":{...}} event: message data: {"jsonrpc":"2.0","method":"notifications/resources/list_changed"} ``` -------------------------------- ### Development Configuration (STDIO, insecure) Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/index.md Sets up the SearXNG URL for development environments using STDIO for communication, which is not recommended for production due to security implications. ```bash export SEARXNG_URL=http://localhost:8080 ``` -------------------------------- ### For Small Context Windows Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/configuration.md Optimizes Searxng for environments with limited context windows by reducing results and character limits. ```bash export SEARXNG_URL=http://localhost:8080 export SEARXNG_LITE_TOOLS=true export SEARXNG_MAX_RESULTS=5 export SEARXNG_MAX_RESULT_CHARS=300 export URL_READ_MAX_CHARS=1000 ``` -------------------------------- ### Handle MCPSearXNGError Exception Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/types.md Example of catching and logging a custom MCPSearXNGError. This pattern ensures specific handling for library-related issues. ```typescript try { await performWebSearch(mcpServer, query); } catch (error) { if (error instanceof MCPSearXNGError) { console.error("MCP SearXNG error:", error.message); } } ``` -------------------------------- ### GET /mcp Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/endpoints.md Receives MCP server-to-client notifications via Server-Sent Events (SSE). Requires an active session ID. ```APIDOC ## GET /mcp ### Description Receives MCP server-to-client notifications via Server-Sent Events (SSE). Requires an active session ID. ### Method GET ### Endpoint /mcp ### Headers - **mcp-session-id** (string) - Required - Session identifier (must match active session) - **Authorization** (string) - Optional - Bearer token (required in hardened mode) ### Response Server-Sent Events stream (Content-Type: `text/event-stream`). ``` event: message data: {"jsonrpc":"2.0","method":"notifications/logging","params":{...}} event: message data: {"jsonrpc":"2.0","method":"notifications/resources/list_changed"} ``` ### Status Codes - **200** - Stream opened successfully - **400** - Invalid or missing session ID - **401** - Unauthorized (invalid token in hardened mode) - **429** - Rate limit exceeded (`MCP_RATE_SESSION_MAX`) ### Request Example ```bash curl -X GET http://localhost:3000/mcp \ -H "mcp-session-id: session-uuid-here" \ -H "Authorization: Bearer your-token" ``` ``` -------------------------------- ### HTTP with Defaults Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/configuration.md Configures HTTP access to Searxng with default host and port settings. ```bash export SEARXNG_URL=https://searxng.example.com export MCP_HTTP_PORT=3000 export MCP_HTTP_HOST=0.0.0.0 ``` -------------------------------- ### Reuse MCP Session with cURL Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/endpoints.md Example cURL command for making subsequent requests to an active MCP session. Requires the 'mcp-session-id' header. ```bash curl -X POST http://localhost:3000/mcp \ -H "Content-Type: application/json" \ -H "mcp-session-id: session-uuid-here" \ -H "Authorization: Bearer your-token" \ -d '{"jsonrpc":"2.0","id":2,"method":"tools/call",...}' ``` -------------------------------- ### Mock External Dependencies Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/__tests__/README.md Example of using `FetchMocker` to mock external HTTP requests within tests. Remember to restore the mocks after the test. ```typescript const fetchMocker = new FetchMocker(); fetchMocker.mock(createMockFetch({ json: { results: [] } })); // ... test code ... fetchMocker.restore(); ``` -------------------------------- ### Small Context Windows Configuration Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/index.md Optimizes SearXNG for environments with limited context window sizes by enabling lite tools and reducing the maximum number of results and characters per result. ```bash export SEARXNG_LITE_TOOLS=true export SEARXNG_MAX_RESULTS=5 export SEARXNG_MAX_RESULT_CHARS=300 ``` -------------------------------- ### Get SearXNG Categories Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/api-reference.md Retrieves all available SearXNG category names from the instance's /config endpoint. This function shares caching with getKnownEngines. ```typescript export async function getKnownCategories( mcpServer: McpServer, refresh: boolean = false ): Promise | null> ``` ```typescript const categories = await getKnownCategories(mcpServer); if (categories) { console.log("Available categories:", [...categories].sort().join(", ")); } ``` -------------------------------- ### Create Network Error with Context Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/types.md Example of throwing a network error with detailed context. The ErrorContext helps differentiate between SearXNG and target website errors. ```typescript const context: ErrorContext = { url: "https://example.com", searxngUrl: undefined, // indicates this is a web_url_read error proxyAgent: true, timeout: 10000 }; throw createNetworkError(error, context); ``` -------------------------------- ### Get HTTP Security Configuration Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/api-reference.md Reads HTTP security settings from environment variables. This function is useful for understanding and applying security configurations to your server. ```typescript export function getHttpSecurityConfig(): HttpSecurityConfig ``` -------------------------------- ### Local HTTP Server Configuration Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/README.md Configures MCP SearXNG to run as an HTTP server on localhost. Sets the port and host for the server. ```bash export SEARXNG_URL=http://localhost:8080 export MCP_HTTP_PORT=3000 export MCP_HTTP_HOST=127.0.0.1 npx mcp-searxng ``` -------------------------------- ### MCP SearXNG NPM Configuration Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/README.md This JSON configuration is used when MCP SearXNG is installed globally via NPM. It specifies the command to run and environment variables. ```json { "mcpServers": { "searxng": { "command": "mcp-searxng", "env": { "SEARXNG_URL": "YOUR_SEARXNG_INSTANCE_URL" } } } } ``` -------------------------------- ### createHttpServer() Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/api-reference.md Creates an Express application with MCP endpoints, rate limiting, CORS, and session management. The caller is responsible for calling `.listen()` on the returned application. ```APIDOC ## createHttpServer() Creates an Express application with MCP endpoints, rate limiting, CORS, and session management. ### Method Signature ```typescript export async function createHttpServer(createMcpServer: () => McpServer): Promise ``` ### Parameters #### Function Parameter * **createMcpServer** (Function) - Factory function that creates a new `McpServer` instance ### Return Type `Promise` — Configured Express app (not listening; caller must call `.listen()`) ### Endpoints #### POST /mcp - **Purpose**: MCP protocol (initialization and tool calls) #### GET /mcp - **Purpose**: MCP protocol (server-to-client via SSE) #### DELETE /mcp - **Purpose**: Session termination #### GET /health - **Purpose**: Health check ### Session Management - Session ID passed via `mcp-session-id` header. - New session created on initialize request (no session ID). - Existing session reused if session ID matches. - Session cleaned up on DELETE or transport close. ### Rate Limiting - POST `/mcp`: `MCP_RATE_INIT_MAX` (default 20) per `MCP_RATE_WINDOW_MS` (default 60s) - GET/DELETE `/mcp`: `MCP_RATE_SESSION_MAX` (default 300) per window - `/health`: 60 per minute (fixed) - All limits return HTTP 429 with JSON-RPC error `code: -32029` ### Security - CORS support with origin checking (respects `MCP_HTTP_ALLOWED_ORIGINS`). - Bearer token auth in hardened mode (`MCP_HTTP_HARDEN=true`). - DNS rebinding protection when hardened. - Invalid requests logged to console with client info. ### Response Headers - `Mcp-Session-Id`: Session identifier on responses - `RateLimit-*`: Standard rate limit headers ### Example ```typescript import { createHttpServer, createMcpServer } from "mcp-searxng"; const app = await createHttpServer(createMcpServer); const server = app.listen(3000, "0.0.0.0", () => { console.log("MCP HTTP server running on http://0.0.0.0:3000"); }); ``` ``` -------------------------------- ### Get SearXNG Engines Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/api-reference.md Fetches the list of all available SearXNG engine names from the instance's /config endpoint. Caching is enabled by default with a 5-second timeout. ```typescript export async function getKnownEngines( mcpServer: McpServer, refresh: boolean = false ): Promise | null> ``` ```typescript const engines = await getKnownEngines(mcpServer); if (engines) { console.log("Available engines:", [...engines].join(", ")); } else { console.log("Cannot discover engines: /config unavailable"); } ``` -------------------------------- ### Small Context Window Configuration Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/README.md Optimizes MCP SearXNG for environments with small context windows by limiting results and characters. Adjusts URL read character limits as well. ```bash export SEARXNG_URL=http://localhost:8080 export SEARXNG_LITE_TOOLS=true export SEARXNG_MAX_RESULTS=5 export SEARXNG_MAX_RESULT_CHARS=300 export URL_READ_MAX_CHARS=1000 npx mcp-searxng ``` -------------------------------- ### Build MCP SearXNG Docker Image Locally Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/README.md Use this command to build the MCP SearXNG Docker image from the Dockerfile in the current directory. ```bash docker build -t mcp-searxng:latest -f Dockerfile . ``` -------------------------------- ### Check Content Length Before Fetching Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/api-reference.md Performs a HEAD request to check the Content-Length header before fetching a full URL. Returns null on failure and proceeds with GET. ```typescript export async function checkContentLength( mcpServer: McpServer, url: string, timeoutMs: number, dispatcher?: Dispatcher, baseRequestOptions: RequestInit = {} ): Promise ``` ```typescript const length = await checkContentLength( mcpServer, "https://example.com/large-file.pdf", 10000, dispatcher ); if (length && length > MAX_SIZE) { console.log("Content too large"); } else { // Proceed with GET } ``` -------------------------------- ### fetchInstanceInfo Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/api-reference.md Discovers capabilities of the configured SearXNG instance via the /config endpoint. It returns a JSON string containing instance configuration on success or an error message on failure. Caching is employed unless the 'refresh' parameter is set to true. ```APIDOC ## fetchInstanceInfo() ### Description Discovers capabilities of the configured SearXNG instance via the `/config` endpoint. It returns a JSON string containing instance configuration on success or an error message on failure. Caching is employed unless the `refresh` parameter is set to true. ### Method `POST` (Assumed, as it's a function call in code, typically mapped to POST for operations that might have side effects or complex parameters, though GET could also be argued if purely informational. The source does not specify HTTP method.) ### Endpoint `/config` (Derived from description) ### Parameters #### Path Parameters None #### Query Parameters - **includeEngines** (boolean) - Optional - Include enabled engine names in response. Defaults to `false`. - **includeDisabled** (boolean) - Optional - Include disabled engine names (only when `includeEngines: true`). Defaults to `false`. - **category** (string) - Optional - Filter categories and engines to a single category name. - **refresh** (boolean) - Optional - Bypass process-level cache and fetch fresh `/config`. Defaults to `false`. #### Request Body None explicitly defined for the API call itself, but the function signature implies parameters are passed directly. ### Request Example ```typescript // This is a code example, not a direct HTTP request example const info = await fetchInstanceInfo( mcpServer, true, // includeEngines false, // includeDisabled "news", // category (optional) false // refresh ); const parsed = JSON.parse(info); console.log(parsed.categories); // ["news"] console.log(parsed.engines.enabled); // engines in "news" category ``` ### Response #### Success Response (200) - **available** (boolean) - Indicates if the SearXNG instance is available. - **categories** (string[]) - List of available categories. - **defaults** (object) - Default settings for the instance (e.g., safesearch, locale). - **locales** (string[]) - List of supported locales. - **plugins** (string[]) - List of available plugins. - **engines** (object) - Information about enabled and disabled engines. - **enabled** (string[]) - List of enabled engine names. - **disabled** (string[]) - List of disabled engine names (if `includeDisabled: true`). #### Response Example (Success) ```json { "available": true, "categories": ["general", "social media", "news"], "defaults": { "safesearch": 0, "locale": "en-US", "language": "all", "theme": "simple" }, "locales": ["en", "fr", "de", ...], "plugins": ["plugin-name", ...], "engines": { "enabled": ["google", "bing", "ddg"], "disabled": ["baidu"] // if includeDisabled: true } } ``` #### Failure Response (e.g., 503) - **available** (boolean) - Always `false` on failure. - **message** (string) - Error message describing the failure. - **status** (number) - HTTP status code of the error. #### Response Example (Failure) ```json { "available": false, "message": "SearXNG /config is unavailable: HTTP 503 Service Unavailable", "status": 503 } ``` ### Caching - Process-level cache stores `/config` response keyed by `SEARXNG_URL`. - Cache is reused across calls unless `refresh: true` is passed. - Timeout: 5 seconds for `/config` fetch. ``` -------------------------------- ### Fetch SearXNG Instance Info with Engines Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/errors.md Call `fetchInstanceInfo` with `includeEngines: true` to retrieve a list of available SearXNG engines. This is useful for validating engine names before performing a search. ```typescript // Get engines const info = await fetchInstanceInfo(mcpServer, true, false); const parsed = JSON.parse(info); console.log(parsed.engines.enabled); ``` -------------------------------- ### Get Search Suggestions from SearXNG Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/api-reference.md Retrieves autocomplete suggestions from the SearXNG instance's /autocompleter endpoint. Returns an empty array on failure or if SearXNG URL is not configured. ```typescript export async function performSearchSuggestions( mcpServer: McpServer, query: string, language: string = "all" ): Promise ``` ```typescript const suggestions = await performSearchSuggestions( mcpServer, "python", "en" ); console.log(suggestions); // ["python", "python docs", "python tutorial", ...] ``` -------------------------------- ### Set Mismatched AUTH Credentials Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/errors.md Shows how to correctly set authentication credentials by providing both `AUTH_USERNAME` and `AUTH_PASSWORD` environment variables. This resolves errors related to missing or mismatched credentials. ```bash export AUTH_USERNAME=searxng_user export AUTH_PASSWORD=searxng_pass ``` -------------------------------- ### createMcpServer() Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/api-reference.md Creates and configures a new Model Context Protocol server. This function initializes an MCP server instance with all necessary tool and resource handlers, making it ready to process requests. It's typically called once per HTTP session or process. ```APIDOC ## createMcpServer() ### Description Creates and configures a new Model Context Protocol server with all tool and resource handlers registered. Called once per HTTP session in HTTP mode, or once per process in STDIO mode. ### Method Not applicable (Function Call) ### Parameters None ### Return Type McpServer - A fully initialized MCP server instance with tool, resource, and logging handlers installed and ready to process requests. ### Example ```typescript import { createMcpServer } from "mcp-searxng"; const server = createMcpServer(); // Server is now ready to accept MCP protocol requests ``` ``` -------------------------------- ### Proxy Configuration Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/index.md Sets up HTTP proxy and bypass rules for network requests. Use this when your environment requires a proxy to access external services. ```bash export HTTP_PROXY=http://proxy.company.com:8080 export NO_PROXY=localhost,.internal ``` -------------------------------- ### Initialize MCP Session with cURL Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/endpoints.md Use this cURL command to initialize an MCP session via the HTTP POST endpoint. Include necessary headers like Content-Type and Authorization. ```bash curl -X POST http://localhost:3000/mcp \ -H "Content-Type: application/json" \ -H "Authorization: Bearer your-token" \ -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{...}}' ``` -------------------------------- ### MCP SearxNG Health Check Response Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/endpoints.md The GET /health endpoint returns a JSON object indicating the server's status. This is useful for load balancers and readiness probes. ```json { "status": "healthy", "server": "ihor-sokoliuk/mcp-searxng", "version": "1.5.0", "transport": "http" } ``` -------------------------------- ### Development Build Commands Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/CONTRIBUTING.md Commands for running the development server in watch mode or performing a one-off build. ```bash npm run watch # Watch mode — rebuilds on file changes ``` ```bash npm run build # One-off build ``` -------------------------------- ### searxng_instance_info Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/MANIFEST.txt Discovers and returns information about the capabilities of the SearXNG instance. ```APIDOC ## GET /searxng/instance_info ### Description Discover SearXNG capabilities. ### Method GET ### Endpoint /searxng/instance_info ### Parameters None ### Response #### Success Response (200) - **instance_info** (object) - An object containing details about the SearXNG instance, such as supported engines, categories, and language settings. #### Response Example ```json { "instance_info": { "engines": ["google", "duckduckgo"], "categories": ["general", "images"], "languages": ["en", "de"] } } ``` ``` -------------------------------- ### Extract Content by Paragraph Range Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/api-reference.md Fetches content from a URL and extracts a specific range of paragraphs. The `paragraphRange` option specifies the start and end paragraphs, e.g., "2-5". A timeout of 10000ms is used. ```typescript import { fetchAndConvertToMarkdown } from "mcp-searxng/url-reader"; // Paragraphs 2–5 const excerpt = await fetchAndConvertToMarkdown( mcpServer, "https://example.com/article", 10000, { paragraphRange: "2-5" } ); ``` -------------------------------- ### Create Proxy Agents with ProxyType Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/types.md Demonstrates how to create proxy agents for different types using the createProxyAgent function and the ProxyType enum. Ensure 'mcp-searxng/proxy' is imported. ```typescript import { createProxyAgent, ProxyType } from "mcp-searxng/proxy"; const searchProxy = createProxyAgent(url, ProxyType.SEARCH); const urlProxy = createProxyAgent(url, ProxyType.URL_READER); ``` -------------------------------- ### Enable Lite Tool Schemas Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/configuration.md When set to true, registers minimal tool schemas with only required parameters to reduce per-call token overhead. This is useful for LLMs with smaller context windows. ```bash export SEARXNG_LITE_TOOLS=true ``` -------------------------------- ### MCP Initialization Request Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/endpoints.md Use this JSON structure for the initial POST request to establish an MCP session. Ensure 'Content-Type' is 'application/json' and include client capabilities. ```json { "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": "2024-11-05", "capabilities": { ... }, "clientInfo": { "name": "...", "version": "..." } } } ``` -------------------------------- ### Set Authentication Credentials for SearXNG Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/errors.md How to set environment variables for username and password if SearXNG requires HTTP Basic Authentication. This is a common fix for 403 Forbidden errors. ```bash export AUTH_USERNAME=user AUTH_PASSWORD=pass ``` -------------------------------- ### Create MCP Server Instance Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/api-reference.md Initializes and configures a new MCP server with all necessary handlers. This function is typically called once per session or process. ```typescript export function createMcpServer(): McpServer ``` ```typescript import { createMcpServer } from "mcp-searxng"; const server = createMcpServer(); // Server is now ready to accept MCP protocol requests ``` -------------------------------- ### searxng_instance_info Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/README.md Discovers and returns information about the SearXNG instance, including available categories, engines, locales, and plugins. Supports filtering and refreshing data. ```APIDOC ## searxng_instance_info ### Description Discover SearXNG instance capabilities (categories, engines, locales, plugins). ### Parameters - `includeEngines` (boolean) - Optional - `includeDisabled` (boolean) - Optional - `category` (string) - Optional - `refresh` (boolean) - Optional ### Returns JSON with available categories, engines, defaults, locales, plugins ``` -------------------------------- ### Docker Deployment Configuration Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/README.md Sets environment variables for deploying MCP SearXNG in a Docker container. Includes HTTP hardening, authentication, and CORS settings. ```bash export SEARXNG_URL=http://searxng:8080 export MCP_HTTP_PORT=3000 export MCP_HTTP_HOST=0.0.0.0 export MCP_HTTP_HARDEN=true export MCP_HTTP_AUTH_TOKEN=your-token export MCP_HTTP_ALLOWED_ORIGINS=https://app.example.com npx mcp-searxng ``` -------------------------------- ### SearXNG Instance Information Arguments Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/types.md Arguments for the `searxng_instance_info` tool. Control whether to include engine details, disabled engines, filter by category, or refresh data. ```typescript interface SearXNGInstanceInfoArgs { includeEngines?: boolean; includeDisabled?: boolean; category?: string; refresh?: boolean; } ``` -------------------------------- ### Testing Commands Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/CONTRIBUTING.md Commands for running tests, generating coverage reports, and running tests in watch mode. ```bash npm test # Run all tests ``` ```bash npm run test:coverage # Generate coverage report ``` ```bash npm run test:watch # Watch mode ``` -------------------------------- ### Add CA Certificate on Windows Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/errors.md Illustrates setting the `NODE_EXTRA_CA_CERTS` environment variable on Windows to include a custom CA certificate bundle, resolving SSL/TLS certificate verification issues. ```cmd # Windows set NODE_EXTRA_CA_CERTS=C:\path\to\ca-bundle.pem ``` -------------------------------- ### Configure Proxies for SearXNG and URL Reader Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/README.md Sets environment variables for HTTP proxies used by the search and URL reader components. NO_PROXY can be used to bypass proxies for specific hosts. ```bash export SEARCH_HTTP_PROXY=http://proxy.company.com:8080 export URL_READER_HTTP_PROXY=http://other-proxy.company.com:8080 export NO_PROXY=localhost,.internal ``` -------------------------------- ### SearXNG Search Suggestions Arguments Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/types.md Arguments for the `searxng_search_suggestions` tool. Specify the query and optionally the language for autocomplete suggestions. ```typescript interface SearXNGSearchSuggestionsArgs { query: string; language?: string; } ``` -------------------------------- ### Add SearXNG MCP Server to Client Configuration Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/README.md Configure your MCP client to use the mcp-searxng server. Ensure you replace YOUR_SEARXNG_INSTANCE_URL with the actual URL of your SearXNG instance. ```json { "mcpServers": { "searxng": { "command": "npx", "args": ["-y", "mcp-searxng"], "env": { "SEARXNG_URL": "YOUR_SEARXNG_INSTANCE_URL" } } } } ``` -------------------------------- ### Environment Variable Cheat Sheet Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/index.md A comprehensive list of environment variables for configuring MCP SearXNG, including core settings, authentication, timeouts, schema, search defaults, URL reading, user-agent, proxy, HTTP transport, rate limiting, and security hardening. ```bash # Core (required) SEARXNG_URL=http://localhost:8080 # Authentication (optional, must be paired) AUTH_USERNAME=user AUTH_PASSWORD=pass # Timeouts (optional) SEARXNG_TIMEOUT_MS=10000 FETCH_TIMEOUT_MS=10000 # Schema (optional) SEARXNG_LITE_TOOLS=false # Search defaults (optional) SEARXNG_DEFAULT_LANGUAGE=all SEARXNG_DEFAULT_SAFESEARCH=0 SEARXNG_MAX_RESULTS=20 SEARXNG_MAX_RESULT_CHARS=500 # URL reading (optional) URL_READ_MAX_CHARS=2000 URL_READ_MAX_CONTENT_LENGTH_BYTES=5242880 CACHE_TTL_MS=86400000 CACHE_MAX_ENTRIES=500 # User-Agent (optional) USER_AGENT="MyBot/1.0" URL_READER_USER_AGENT="Mozilla/5.0" # Proxy (optional) HTTP_PROXY=http://proxy:8080 HTTPS_PROXY=http://proxy:8080 SEARCH_HTTP_PROXY=http://search-proxy:8080 URL_READER_HTTP_PROXY=http://url-proxy:8080 NO_PROXY=localhost,.internal # HTTP transport (optional, omit for STDIO) MCP_HTTP_PORT=3000 MCP_HTTP_HOST=127.0.0.1 # Rate limiting (optional) MCP_RATE_WINDOW_MS=60000 MCP_RATE_INIT_MAX=20 MCP_RATE_SESSION_MAX=300 # Security hardening (optional, all or nothing) MCP_HTTP_HARDEN=true MCP_HTTP_AUTH_TOKEN=secret-token MCP_HTTP_ALLOWED_ORIGINS=https://app.example.com MCP_HTTP_ALLOWED_HOSTS=app.example.com MCP_HTTP_ALLOW_PRIVATE_URLS=false MCP_HTTP_EXPOSE_FULL_CONFIG=false ``` -------------------------------- ### Manage Environment Variables Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/__tests__/README.md Demonstrates how to temporarily set environment variables for testing using `EnvManager`. Ensure to restore the original environment after the test. ```typescript const envManager = new EnvManager(); envManager.set('SEARXNG_URL', 'https://test.com'); // ... test code ... envManager.restore(); ``` -------------------------------- ### Configure Proxy with Credentials Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/configuration.md Set an HTTP proxy by including user credentials directly in the proxy URL. This is a common method for authenticating with proxy servers. ```bash export HTTP_PROXY=http://user:password@proxy.example.com:8080 ``` -------------------------------- ### getKnownEngines() Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/api-reference.md Retrieves the set of all available SearXNG engine names from the instance's /config endpoint. This function helps in discovering and utilizing the search engines configured within a SearXNG instance. ```APIDOC ## getKnownEngines() ### Description Retrieves the set of all available SearXNG engine names from the instance `/config`. ### Method ```typescript export async function getKnownEngines( mcpServer: McpServer, refresh: boolean = false ): Promise | null> ``` ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Parameters - **mcpServer** (McpServer) - Server instance for logging - **refresh** (boolean) - Bypass cache and fetch fresh `/config` ### Return Type `Promise | null>` — Set of engine names (enabled and disabled), or `null` if `/config` is unavailable. ### Behavior - Fetches `/config` from SearXNG instance (cached by default) - Extracts all engine names from `config.engines[].name` - Returns `null` if fetch fails; errors are logged at warning level ### Caching - Cache key: `SEARXNG_URL` - Cleared on `refresh: true` - 5-second fetch timeout ### Example ```typescript const engines = await getKnownEngines(mcpServer); if (engines) { console.log("Available engines:", [...engines].join(", ")); } else { console.log("Cannot discover engines: /config unavailable"); } ``` ``` -------------------------------- ### Fetch SearXNG Instance Information Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/api-reference.md Retrieves instance configuration, optionally including enabled/disabled engines and filtering by category. Cache is used by default but can be bypassed with `refresh: true`. Use this to understand the capabilities and available engines of a SearXNG instance. ```typescript export async function fetchInstanceInfo( mcpServer: McpServer, includeEngines: boolean = false, includeDisabled: boolean = false, category?: string, refresh: boolean = false ): Promise ``` ```json { "available": true, "categories": ["general", "social media", "news"], "defaults": { "safesearch": 0, "locale": "en-US", "language": "all", "theme": "simple" }, "locales": ["en", "fr", "de", ...], "plugins": ["plugin-name", ...], "engines": { "enabled": ["google", "bing", "ddg"], "disabled": ["baidu"] // if includeDisabled: true } } ``` ```json { "available": false, "message": "SearXNG /config is unavailable: HTTP 503 Service Unavailable", "status": 503 } ``` ```typescript const info = await fetchInstanceInfo( mcpServer, true, // includeEngines false, // includeDisabled "news", // category (optional) false // refresh ); const parsed = JSON.parse(info); console.log(parsed.categories); // ["news"] console.log(parsed.engines.enabled); // engines in "news" category ``` -------------------------------- ### Production Configuration (HTTP, hardened) Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/index.md Configures SearXNG for production use with HTTP transport, enabling security hardening features like authentication and origin allowlisting. ```bash export SEARXNG_URL=https://searxng.example.com export MCP_HTTP_PORT=3000 export MCP_HTTP_HARDEN=true export MCP_HTTP_AUTH_TOKEN=secret export MCP_HTTP_ALLOWED_ORIGINS=https://app.example.com ``` -------------------------------- ### Run All Tests Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/__tests__/README.md Commands to execute the test suite, including coverage and watch modes. Use `npx tsx` to run a single test file. ```bash npm test # Run all tests npm run test:coverage # Run with coverage report npm run test:watch # Watch mode (auto-rerun) npx tsx __tests__/unit/logging.test.ts # Run single test file ``` -------------------------------- ### Public Internet-Facing HTTP Configuration Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/SECURITY.md Recommended configuration for public-facing HTTP deployments, including hardened mode, authentication, allowed origins, and host validation. A reverse proxy is advised. ```bash MCP_HTTP_HARDEN=true MCP_HTTP_HOST=127.0.0.1 # put a reverse proxy in front MCP_HTTP_AUTH_TOKEN= MCP_HTTP_ALLOWED_ORIGINS=https://your-app.example.com MCP_HTTP_ALLOWED_HOSTS=your-app.example.com MCP_HTTP_ALLOW_PRIVATE_URLS=false # default, keep this off ``` -------------------------------- ### Fetch and Convert Full Page Content Source: https://github.com/ihor-sokoliuk/mcp-searxng/blob/main/_autodocs/api-reference.md Fetches the entire content of a given URL and converts it to Markdown format. Ensure the `mcp-searxng/url-reader` module is imported. ```typescript import { fetchAndConvertToMarkdown } from "mcp-searxng/url-reader"; // Full page const content = await fetchAndConvertToMarkdown( mcpServer, "https://example.com/article" ); ```