### Start SearXNG MCP with Default Transport Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/quick-reference.md Starts the SearXNG MCP server using the default stdio transport. This is the simplest way to get started. ```bash python searxng_mcp.py ``` -------------------------------- ### Docker Compose for SearXNG and MCP Server Source: https://github.com/aicrafted/searxng-mcp/blob/main/README.md Example `compose.yml` to run SearXNG with the MCP server. Ensures SearXNG starts before the MCP server and configures environment variables. ```yaml services: searxng: image: searxng/searxng:latest ports: - "${SEARXNG_PORT:-8080}:8080" volumes: - "${SEARXNG_VOL_CONFIG:-searxng-config}:/etc/searxng/" - "${SEARXNG_VOL_DATA:-searxng-data}:/var/cache/searxng/" restart: always searxng-mcp: image: ghcr.io/aicrafted/searxng-mcp:latest restart: unless-stopped depends_on: # Ensure SearXNG starts before the MCP server - searxng environment: SEARXNG_URL: "${SEARXNG_URL:-http://searxng:8080}" MCP_HOST: "${MCP_HOST:-127.0.0.1}" MCP_PORT: "${MCP_PORT:-32123}" MCP_TRANSPORT: "${MCP_TRANSPORT:-http}" MCP_ALLOWED_HOSTS: "${MCP_ALLOWED_HOSTS:-localhost:*,127.0.0.1:*}" MCP_ALLOWED_ORIGINS: "${MCP_ALLOWED_ORIGINS:-http://localhost:*,http://127.0.0.1:*}" MCP_DISABLE_DNS_REBINDING_PROTECTION: "${MCP_DISABLE_DNS_REBINDING_PROTECTION:-false}" ports: - "${MCP_PORT:-32123}:${MCP_PORT:-32123}" volumes: searxng-config: searxng-data: ``` -------------------------------- ### SearXNG Instance Info Response Example Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/api-reference-tools.md This is an example of the JSON response structure returned by the searxng_get_info function. It details the instance URL, available categories, and configured search engines. ```json { "instance_url": "http://localhost:8080", "standard_categories": [ "general", "images", "videos", "news", "it", "science", "map", "files", "music", "social_media" ], "configured_engines": [ "bing", "brave", "ddg", "duckduckgo", "ecosia", "google", "wikipedia", "wikidata" ], "message": "To use a specific category, pass it to the 'categories' parameter in searxng_search." } ``` -------------------------------- ### SearXNG-MCP Startup Command Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/api-reference-overview.md Command to start the searxng-mcp server. Optional arguments allow specifying the SearXNG URL, transport protocol, host, and port. ```bash python searxng_mcp.py [--searxng URL] [--transport {stdio|sse|http}] [--host HOST] [--port PORT] ``` -------------------------------- ### Python Example: Basic Web Search Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/api-reference-tools.md Demonstrates a basic web search using the `searxng_search` function with a simple query string. ```python # Basic search result = await searxng_search("Python tutorials") ``` -------------------------------- ### Specific Configuration Example Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/configuration.md This invocation demonstrates setting a specific SearXNG URL, host, port, and transport protocol for detailed control over the server's configuration. ```bash # Specific configuration python searxng_mcp.py --searxng http://localhost:8080 --host 127.0.0.1 --port 3000 --transport http ``` -------------------------------- ### Python - using httpx Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/quick-reference.md Example of how to make a web search request using the Python `httpx` library with the HTTP transport. ```APIDOC ## Python - using httpx ### Description Example of making a web search request using `httpx`. ### Code Example ```python import httpx async def search(): async with httpx.AsyncClient() as client: response = await client.post( "http://localhost:32123/mcp", json={ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "web_search", "arguments": {"query": "Python"} } } ) return response.json() ``` ``` -------------------------------- ### HTTP POST /mcp Request Example Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/endpoints.md This is an example of a JSON-RPC 2.0 request to the /mcp endpoint for calling the 'web_search' tool. Ensure the Content-Type is set to application/json. ```json { "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "web_search", "arguments": { "query": "python tutorial", "categories": "general", "language": "en", "pageno": 1, "response_format": "markdown" } } } ``` -------------------------------- ### Install Python Dependencies Source: https://github.com/aicrafted/searxng-mcp/blob/main/README.md Command to install project dependencies using pip. Assumes `requirements.txt` is present. ```bash pip install -r requirements.txt ``` -------------------------------- ### Example SearXNG Response Without Stats Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/errors.md This JSON example shows the structure of a response from the web_search_info tool when the SearXNG stats endpoint is unavailable. The 'configured_engines' field may be omitted or empty. ```json { "instance_url": "http://localhost:8080", "standard_categories": ["general", "images", "videos", ...], "message": "To use a specific category, pass it to the 'categories' parameter in searxng_search." } ``` -------------------------------- ### JavaScript - using fetch Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/quick-reference.md Example of how to make a web search request using JavaScript's `fetch` API with the HTTP transport. ```APIDOC ## JavaScript - using fetch ### Description Example of making a web search request using `fetch`. ### Code Example ```javascript async function search() { const response = await fetch('http://localhost:32123/mcp', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'web_search', arguments: {query: 'Python'} } }) }); return await response.json(); } ``` ``` -------------------------------- ### Python Example: News Search with Filters Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/api-reference-tools.md Shows how to perform a news-specific search, filtering by category, language, and time range. ```python # News search with language filter result = await searxng_search( query="climate change", categories="news", language="de", time_range="month" ) ``` -------------------------------- ### Usage Example for Health Check Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/internals.md Demonstrates how to run the asynchronous `check_searxng_health` function using asyncio and print the reachability status. ```python import asyncio result = asyncio.run(check_searxng_health("http://localhost:8080")) if result: print("SearXNG is reachable") else: print("SearXNG is not reachable") ``` -------------------------------- ### Start SearXNG MCP with SSE Transport Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/quick-reference.md Starts the SearXNG MCP server using the SSE (Server-Sent Events) transport. Useful for real-time updates. Specify the port. ```bash python searxng_mcp.py --transport sse --port 8000 ``` -------------------------------- ### Markdown Response Example for Web Search Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/api-reference-tools.md Provides an example of the human-readable Markdown output format for web search results. ```markdown # Search Results for: Python tutorials ### [Real Python - Python Tutorials](https://realpython.com/) Thousands of hours in video courses and tutorials covering everything from the basics to advanced topics. ### [The Official Python Tutorial](https://docs.python.org/3/tutorial/) This tutorial introduces readers informally to the basic concepts and features of the Python language and system. ... ``` -------------------------------- ### Python Example: Search Specific Engines and JSON Output Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/api-reference-tools.md Illustrates searching only specific engines and requesting the response in JSON format. ```python # Search specific engines and return JSON result = await searxng_search( query="numpy documentation", engines="github,stackoverflow", response_format=ResponseFormat.JSON ) ``` -------------------------------- ### Python HTTP Transport Example Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/quick-reference.md Demonstrates how to make a POST request to the MCP HTTP endpoint using the httpx library in Python. ```python import httpx import json async def search(): async with httpx.AsyncClient() as client: response = await client.post( "http://localhost:32123/mcp", json={ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "web_search", "arguments": {"query": "Python"} } } ) return response.json() ``` -------------------------------- ### Start SearXNG MCP Server with HTTP Transport Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/README.md Starts the SearXNG MCP server using HTTP transport on a specified port. This is a common way to expose the server for web-based clients. ```bash python searxng_mcp.py --transport http --port 32123 ``` -------------------------------- ### SSE POST /sse Response Stream Example Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/endpoints.md This example shows a Server-Sent Events stream response from the /sse endpoint. It includes a 'message' event with the JSON-RPC result and a 'done' event to signal completion. ```text event: message data: {"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"# Search Results..."}]}} event: done data: {} ``` -------------------------------- ### Main Entry Point and Argument Parsing Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/internals.md This snippet demonstrates the main entry point of the SearXNG MCP server. It parses command-line arguments for SearXNG URL, transport type, host, and port, then performs a health check before starting the server. ```python if __name__ == "__main__": import argparse import asyncio import sys parser = argparse.ArgumentParser(description="SearXNG MCP Server") parser.add_argument("--searxng", default=SEARXNG_URL, help="SearXNG url") parser.add_argument("--transport", default=DEFAULT_TRANSPORT, choices=["stdio", "sse", "http"], help="Transport type") parser.add_argument("--host", default=DEFAULT_HOST, help="Host to bind to for mcp network transports") parser.add_argument("--port", type=int, default=DEFAULT_PORT, help="Port for mcp network transports") args = parser.parse_args() # Configure settings mcp.settings.host = args.host mcp.settings.port = args.port # Map 'http' to 'streamable-http' as required by FastMCP transport = args.transport if transport == "http": transport = "streamable-http" logger.info("Starting SearXNG MCP Server") logger.info("SearXNG URL: %s", args.searxng) logger.info("Transport: %s", transport) if transport != "stdio": logger.info("Bind address: %s:%s", args.host, args.port) # Perform startup health check if not asyncio.run(check_searxng_health(args.searxng)): logger.error("Backend health check failed. Please check your SEARXNG_URL and network connectivity.") sys.exit(1) logger.info("Running in %s mode", transport) try: mcp.run(transport=transport) except KeyboardInterrupt: logger.info("Server stopped by user") except Exception as e: logger.error("Server error: %s", str(e)) ``` -------------------------------- ### Run MCP with HTTP Transport Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/quick-reference.md Starts the SearXNG MCP service using the HTTP transport. ```bash python searxng_mcp.py --transport http ``` -------------------------------- ### Logging Configuration Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/configuration.md Configures basic logging for the SearXNG MCP server at the INFO level. This setup is performed at module load time. ```python logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" ) ``` -------------------------------- ### Adding a New Tool Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/internals.md Example demonstrating how to add a new tool by defining an async function decorated with @mcp.tool(). It includes basic error handling by logging exceptions and returning a user-friendly error message. ```python import logging from mcp import mcp logger = logging.getLogger(__name__) @mcp.tool(name="my_tool") async def my_tool(param: str) -> str: """Tool description.""" try: result = await do_something(param) return result except Exception as e: logger.error("Error: %s", str(e)) return f"Error: {str(e)}" ``` -------------------------------- ### JavaScript HTTP Transport Example Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/quick-reference.md Demonstrates how to make a POST request to the MCP HTTP endpoint using the fetch API in JavaScript. ```javascript async function search() { const response = await fetch('http://localhost:32123/mcp', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'web_search', arguments: {query: 'Python'} } }) }); return await response.json(); } ``` -------------------------------- ### Default Values Used in Code Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/configuration.md These examples show how default configuration values are retrieved and processed within the application code. They demonstrate the fallback mechanism from environment variables to hardcoded defaults. ```python SEARXNG_URL: Retrieved via os.environ.get("SEARXNG_URL", "http://localhost:8080").rstrip("/") MCP_PORT: Retrieved via int(os.environ.get("MCP_PORT", "8000")) MCP_HOST: Retrieved via os.environ.get("MCP_HOST", "127.0.0.1") MCP_TRANSPORT: Retrieved via os.environ.get("MCP_TRANSPORT", "stdio").lower() ``` -------------------------------- ### Example: Custom Allowlist for Transport Security Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/internals.md Shows how to configure custom allowed hosts and origins using MCP_ALLOWED_HOSTS and MCP_ALLOWED_ORIGINS environment variables. This enables DNS rebinding protection with the specified whitelists. ```python # Case 2: Custom allowlist os.environ["MCP_ALLOWED_HOSTS"] = "localhost:*,127.0.0.1:*" os.environ["MCP_ALLOWED_ORIGINS"] = "http://localhost:*" settings = _transport_security_from_env() # Returns: TransportSecuritySettings( # enable_dns_rebinding_protection=True, # allowed_hosts=["localhost:*", "127.0.0.1:*"], # allowed_origins=["http://localhost:*"] # ) ``` -------------------------------- ### cURL HTTP Transport Example Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/quick-reference.md Demonstrates how to make a POST request to the MCP HTTP endpoint using cURL. ```bash curl -X POST http://localhost:32123/mcp \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"web_search","arguments":{"query":"Python"}}}' ``` -------------------------------- ### Custom SearXNG URL and HTTP Transport Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/configuration.md This example shows how to specify a custom SearXNG URL and use the HTTP transport protocol on a non-default port. ```bash # Custom SearXNG URL and HTTP transport python searxng_mcp.py --searxng http://searx.example.com --transport http --port 32123 ``` -------------------------------- ### HTTP POST /mcp Response Example Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/endpoints.md This is an example of a successful JSON-RPC 2.0 response from the /mcp endpoint, containing search results in markdown format. The 'id' field correlates with the request. ```json { "jsonrpc": "2.0", "id": 1, "result": { "content": [ { "type": "text", "text": "# Search Results for: python tutorial\n\n### [Python.org - The Official Python Tutorial](https://docs.python.org/3/tutorial/)\nThis tutorial introduces readers informally to the basic concepts and features of the Python language...\n" } ] } } ``` -------------------------------- ### Environment Variables for MCP Server Source: https://github.com/aicrafted/searxng-mcp/blob/main/README.md Example `.env` file for configuring the SearXNG and MCP server, including URLs, ports, and DNS rebinding protection settings. ```env # SearXNG url should be visible by the MCP server inside docker, so use internal service port here SEARXNG_URL=http://searxng:8080 # Public SearXNG port SEARXNG_PORT=8080 # Searxng config and data volumes, start with "./" if You want to bind dir instead using volume SEARXNG_VOL_CONFIG=searxng-config SEARXNG_VOL_DATA=searxng-data # MCP server host, port and transport ("stdio", "sse", "http") MCP_HOST=127.0.0.1 MCP_PORT=32123 MCP_TRANSPORT=http # MCP DNS rebinding protection (see https://github.com/modelcontextprotocol/python-sdk/issues/1798 for details) MCP_ALLOWED_HOSTS=localhost:*,127.0.0.1:* MCP_ALLOWED_ORIGINS=http://localhost:*,http://127.0.0.1:* # MCP_DISABLE_DNS_REBINDING_PROTECTION=true ``` -------------------------------- ### SearXNG-MCP Dependencies Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/api-reference-overview.md List of Python package dependencies required for the searxng-mcp project. Ensure these are installed before running the server. ```text mcp[server]>=1.23.0 # Model Context Protocol framework httpx # Async HTTP client python-dotenv # Environment file support pydantic>=2.11.0 # Data validation uvicorn # ASGI server (for HTTP/SSE transport) ``` -------------------------------- ### Perform Web Search with Different Query Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/quick-reference.md Example of performing a web search using the 'web_search' tool with a different query. ```python await web_search("Python programming") ``` -------------------------------- ### Configure SearXNG MCP with Command-line Arguments Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/quick-reference.md Configures SearXNG MCP settings directly via command-line arguments when starting the server. This allows for dynamic configuration without modifying files or environment variables. ```bash python searxng_mcp.py \ --searxng http://searxng.example.com \ --transport http \ --host 0.0.0.0 \ --port 32123 ``` -------------------------------- ### cURL Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/quick-reference.md Example of making a web search request using `curl` with the HTTP transport. ```APIDOC ## cURL ### Description Example of making a web search request using `curl`. ### Command Example ```bash curl -X POST http://localhost:32123/mcp \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"web_search","arguments":{"query":"Python"}}}' ``` ``` -------------------------------- ### Python: Search StackOverflow for Python Solutions Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/quick-reference.md Shows how to search Stack Overflow for Python programming solutions. This example specifies the 'it' category and the 'stackoverflow' engine. ```python await web_search( query="pandas dataframe", categories="it", engines="stackoverflow" ) ``` -------------------------------- ### SSE POST /sse Request Example Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/endpoints.md This is an initial JSON-RPC 2.0 request to the SSE endpoint for calling the 'web_search' tool. The 'Accept' header must be set to 'text/event-stream'. ```json { "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "web_search", "arguments": { "query": "python tutorial" } } } ``` -------------------------------- ### Get Search Information Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/quick-reference.md Retrieve general information about the web search capabilities. ```python info = await web_search_info() ``` -------------------------------- ### Example: Default Transport Security Settings Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/internals.md Illustrates the scenario where no specific transport security environment variables are set. In this case, _transport_security_from_env() returns None, indicating that the SDK's default settings will be used. ```python # Case 3: No configuration del os.environ["MCP_DISABLE_DNS_REBINDING_PROTECTION"] del os.environ["MCP_ALLOWED_HOSTS"] del os.environ["MCP_ALLOWED_ORIGINS"] settings = _transport_security_from_env() # Returns: None (use SDK defaults) ``` -------------------------------- ### Python Example: Paginated Search Results Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/api-reference-tools.md Demonstrates how to retrieve results from a specific page number using the `pageno` parameter. ```python # Paginated results result = await searxng_search( query="machine learning", pageno=2 ) ``` -------------------------------- ### Perform Web Search with Specific Category Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/quick-reference.md Example of performing a web search using the 'web_search' tool, specifying a category. ```python await web_search("test", categories="general") ``` -------------------------------- ### JSON Response Example for Web Search Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/api-reference-tools.md Illustrates the structure of the raw aggregated JSON data returned when `response_format` is set to `ResponseFormat.JSON`. ```json { "results": [ { "title": "Real Python - Python Tutorials", "url": "https://realpython.com/", "content": "Thousands of hours in video courses and tutorials...", "engines": ["google", "bing"], "publishedDate": "2024-01-15" } ], "search_time": 0.234, "number_of_results": 1234567 } ``` -------------------------------- ### Configure SearXNG MCP with Environment Variables Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/quick-reference.md Sets environment variables to configure SearXNG MCP. This method is useful for scripting and automated deployments. After setting variables, start the server. ```bash export SEARXNG_URL=http://searxng.example.com export MCP_PORT=32123 export MCP_TRANSPORT=http python searxng_mcp.py ``` -------------------------------- ### Troubleshoot: Use a Different Port Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/quick-reference.md Starts the SearXNG MCP server on a different port when the default port is already in use. This is a simple workaround for port conflicts. ```bash # Use different port python searxng_mcp.py --port 32124 ``` -------------------------------- ### Example: Disable DNS Rebinding Protection Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/internals.md Demonstrates setting the MCP_DISABLE_DNS_REBINDING_PROTECTION environment variable to 'true' to disable DNS rebinding protection, resulting in TransportSecuritySettings with protection disabled. ```python # Case 1: Disable protection os.environ["MCP_DISABLE_DNS_REBINDING_PROTECTION"] = "true" settings = _transport_security_from_env() # Returns: TransportSecuritySettings(enable_dns_rebinding_protection=False) ``` -------------------------------- ### Get SearXNG Instance Info Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/api-reference-tools.md Retrieves instance information, including standard categories and configured engines. Use this to understand the capabilities of a SearXNG instance. The result is a JSON string that needs to be parsed. ```python # Get instance information info = await searxng_get_info() print(info) # Parse the result import json config = json.loads(info) print(f"Instance: {config['instance_url']}") print(f"Categories: {', '.join(config['standard_categories'])}") if 'configured_engines' in config: print(f"Engines: {', '.join(config['configured_engines'][:5])}...") ``` -------------------------------- ### Basic Command-Line Invocation Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/configuration.md This command demonstrates the simplest way to run the SearXNG MCP server, relying entirely on default configuration values. ```bash # Use default configuration python searxng_mcp.py ``` -------------------------------- ### Development Deployment (stdio) Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/internals.md Use this command to run the application in development mode using standard input/output for transport. Ensure the SearXNG instance is accessible at the specified URL. ```bash python searxng_mcp.py --transport stdio --searxng http://localhost:8080 ``` -------------------------------- ### Run SearXNG MCP with Command-Line Arguments Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/api-reference-overview.md Use this command to launch the SearXNG MCP server with specific configurations for SearXNG URL, transport, host, and port. Ensure these arguments align with your deployment needs. ```bash python searxng_mcp.py \ --searxng http://searxng.local:8080 \ --transport http \ --host 0.0.0.0 \ --port 32123 ``` -------------------------------- ### Display Command-Line Help Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/errors.md Shows available command-line arguments and their usage for the searxng_mcp.py script. Useful for verifying correct syntax and argument values. ```bash python searxng_mcp.py --help ``` -------------------------------- ### Run MCP Server from Source Source: https://github.com/aicrafted/searxng-mcp/blob/main/README.md Command to run the MCP server directly using `uv`. Allows specifying transport, port, and SearXNG URL. ```bash python searxng_mcp.py --transport http --port 32123 --searxng http://searx.lan ``` -------------------------------- ### FastMCP Initialization Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/internals.md Initializes the FastMCP server with specific configurations for the SearXNG MCP. Key parameters include server name, instructions, host, port, stateless HTTP mode, JSON responses, and streamable HTTP path. ```python mcp = FastMCP( "searxng_mcp", instructions=( "This server provides web search capabilities by querying multiple search engines simultaneously. " "Use the `web_search` tool to search the web across categories such as general web, news, social media, " "academic/science, images, videos, IT/developer resources, and more. " "You can target specific search engines, filter by language or time range, and paginate results. " "Use `web_search_info` to discover available categories and engines on this instance." ), host=DEFAULT_HOST, port=DEFAULT_PORT, stateless_http=True, json_response=True, streamable_http_path="/mcp", transport_security=_transport_security_from_env(), ) ``` -------------------------------- ### FastMCP Server Initialization Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/configuration.md Initializes the FastMCP server instance with specified parameters for SearXNG integration. Ensure necessary environment variables are set for transport security. ```python mcp = FastMCP( "searxng_mcp", instructions="...", host=DEFAULT_HOST, port=DEFAULT_PORT, stateless_http=True, json_response=True, streamable_http_path="/mcp", transport_security=_transport_security_from_env(), ) ``` -------------------------------- ### Get Search Engine Information Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/quick-reference.md Retrieves information about available search categories and engines supported by the MCP. This tool is useful for discovering search capabilities. ```bash curl -X POST http://localhost:32123/mcp \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "web_search_info" } }' ``` -------------------------------- ### Build and Run SearXNG MCP with Docker Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/quick-reference.md Builds a Docker image for SearXNG MCP and runs it as a container. This is useful for isolated deployments. Ensure the SEARXNG_URL environment variable is set correctly. ```bash docker build -t searxng-mcp . docker run -p 32123:32123 -e SEARXNG_URL=http://searxng:8080 searxng-mcp ``` -------------------------------- ### Build MCP Server Docker Image Source: https://github.com/aicrafted/searxng-mcp/blob/main/README.md Command to build the Docker image for the searxng-mcp server from the current directory. ```bash docker build -t searxng-mcp . ``` -------------------------------- ### Load SearXNG URL and Server Defaults Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/internals.md Loads default configuration values for SearXNG URL, server port, host, and transport from environment variables. It normalizes the SEARXNG_URL by stripping trailing slashes and ensures the port is an integer. ```python SEARXNG_URL = os.environ.get("SEARXNG_URL", "http://localhost:8080").rstrip("/") DEFAULT_PORT = int(os.environ.get("MCP_PORT", "8000")) DEFAULT_HOST = os.environ.get("MCP_HOST", "127.0.0.1") DEFAULT_TRANSPORT = os.environ.get("MCP_TRANSPORT", "stdio").lower() ``` -------------------------------- ### Python: Get JSON Results for Processing Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/quick-reference.md Shows how to obtain search results in JSON format and parse them using Python's `json` library. This is useful for further data manipulation. ```python result = await web_search( query="weather", response_format=ResponseFormat.JSON ) data = json.loads(result) ``` -------------------------------- ### Troubleshoot: Test SearXNG Connection with Explicit URL Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/quick-reference.md Tests the connection to SearXNG by explicitly providing the URL as a command-line argument. This helps isolate issues related to environment variable configuration. ```bash # Test with explicit URL python searxng_mcp.py --searxng http://searxng.example.com ``` -------------------------------- ### Get Raw JSON Response from Web Search Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/quick-reference.md Requests the raw JSON output from a web search instead of the default markdown format. This is useful for programmatic processing of search results. ```bash # Get raw JSON instead of markdown curl -X POST http://localhost:32123/mcp \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "web_search", "arguments": { "query": "python", "response_format": "json" } } }' ``` -------------------------------- ### Troubleshoot: Verify SearXNG is Running Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/quick-reference.md Checks if the SearXNG instance is running and accessible by making a simple HTTP request. This is a first step in diagnosing connection issues. ```bash # Check SearXNG is running curl http://localhost:8080/ ``` -------------------------------- ### Check SearXNG Health Function Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/api-reference-overview.md Python function to verify the reachability of a SearXNG instance. It sends a GET request and checks for a 200 status code. Logs warnings or errors based on the response. ```python def check_searxng_health(url: str) -> bool: ``` -------------------------------- ### Troubleshoot: Verify SEARXNG_URL Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/quick-reference.md Verifies that the SEARXNG_URL environment variable is correctly set to the address of your SearXNG instance. An incorrect URL is a common cause of connection errors. ```bash # Verify SEARXNG_URL is correct echo $SEARXNG_URL ``` -------------------------------- ### Local Testing Deployment (HTTP) Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/internals.md Command for local testing using HTTP transport. It binds to the loopback interface and specifies the port for the application. ```bash python searxng_mcp.py --transport http --host 127.0.0.1 --port 32123 ``` -------------------------------- ### Production Deployment (HTTP in Docker) Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/internals.md This command is for deploying the application in a production environment using HTTP transport, typically within a Docker container. It binds to all network interfaces and specifies the SearXNG instance URL. ```bash python searxng_mcp.py --transport http --host 0.0.0.0 --port 32123 --searxng http://searxng:8080 ``` -------------------------------- ### Asynchronous SearXNG Health Check Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/internals.md Checks if a SearXNG instance is reachable via an asynchronous HTTP GET request. It handles URL normalization, sets a 5-second timeout, and logs connection status. Returns True for a 200 status code, False otherwise or on exception. ```python async def check_searxng_health(url: str): """Check if SearXNG is reachable.""" try: async with httpx.AsyncClient(timeout=5.0) as client: response = await client.get(f"{url.rstrip('/')}/") if response.status_code == 200: logger.info("Successfully connected to SearXNG at %s", url) return True else: logger.warning("SearXNG returned status %s at %s", response.status_code, url) return False except Exception as e: logger.error("Could not reach SearXNG at %s %s", url, str(e)) return False ``` -------------------------------- ### MCP Client-Server Interaction Diagram Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/README.md Illustrates the communication flow between an MCP Client, the SearXNG MCP Server, a SearXNG Instance, and multiple Search Engines. ```text MCP Client ↓ (JSON-RPC) MCP Server (searxng-mcp) ↓ (HTTP) SearXNG Instance ↓ Multiple Search Engines (Google, DuckDuckGo, Wikipedia, etc.) ``` -------------------------------- ### Call web_search_info via HTTP using JavaScript fetch Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/endpoints.md This JavaScript snippet shows how to retrieve instance information using the web_search_info tool via HTTP with the fetch API. It logs the text content of the first search result. ```javascript const response = await fetch('http://localhost:32123/mcp', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'web_search_info', arguments: {} } }) }); const data = await response.json(); console.log(data.result.content[0].text); ``` -------------------------------- ### Initialize Application Logger Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/errors.md Initializes the application logger for SearXNG MCP. Errors are logged at the ERROR level and warnings at the WARNING level. ```python import logging logger = logging.getLogger("searxng_mcp") # Errors logged at ERROR level # Warnings logged at WARNING level ``` -------------------------------- ### Basic Logging Configuration Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/internals.md Configures the root logger for the application with INFO level and a specific format including timestamp, logger name, level, and message. It also creates a named logger 'searxng_mcp'. ```python logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" ) logger = logging.getLogger("searxng_mcp") ``` -------------------------------- ### Register web_search_info Tool with FastMCP Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/api-reference-tools.md Registers the 'web_search_info' tool using the @mcp.tool() decorator. This tool provides metadata for discoverability. ```python @mcp.tool() def web_search_info(): """Returns information about the SearXNG instance. Returns: A JSON string containing instance information. """ pass ``` -------------------------------- ### web_search_info Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/api-reference-tools.md Retrieves available search categories and configured engines for the SearXNG instance. Returns a JSON-formatted string with instance details. ```APIDOC ## web_search_info ### Description Retrieves available search categories and configured engines for the SearXNG instance. Returns a JSON-formatted string with instance details. ### Signature ```python async def searxng_get_info() ``` ### Parameters None ### Return Type **str** — JSON-formatted string containing instance information. Object fields: - `instance_url` (str): The configured SearXNG instance URL - `standard_categories` (list[str]): List of standard search categories supported by SearXNG - `configured_engines` (list[str], optional): Active search engines available on this instance, if the stats endpoint is accessible - `message` (str): Usage guidance for the returned information ``` -------------------------------- ### Enable Debug Logging for MCP Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/quick-reference.md Run the MCP service with debug logging enabled and redirect output to a file for analysis. ```bash python -u searxng_mcp.py 2>&1 | tee server.log ``` -------------------------------- ### Verify SearXNG settings.yml Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/quick-reference.md Ensure that the SearXNG configuration file (settings.yml) has JSON output enabled. ```bash # Verify SearXNG settings.yml has JSON enabled ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/internals.md This Python snippet shows how to enable debug-level logging for the 'searxng_mcp' logger. This is useful for detailed monitoring and debugging. ```python import logging logging.getLogger("searxng_mcp").setLevel(logging.DEBUG) ``` -------------------------------- ### Configure SearXNG MCP with .env file Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/quick-reference.md Configures SearXNG MCP settings by defining environment variables in a .env file. This is a convenient way to manage configuration for local development. ```env SEARXNG_URL=http://localhost:8080 MCP_HOST=127.0.0.1 MCP_PORT=32123 MCP_TRANSPORT=http ``` -------------------------------- ### Python Function Signature for SearXNG Instance Info Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/api-reference-tools.md Defines the signature for the `searxng_get_info` function, used to retrieve details about the SearXNG instance. ```python async def searxng_get_info() -> str ``` -------------------------------- ### Set Allowed Hosts for MCP Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/quick-reference.md Configure the allowed hosts for the MCP client to connect from. This is essential for security. ```bash export MCP_ALLOWED_HOSTS=localhost:*,127.0.0.1:*,my-host:* ``` -------------------------------- ### Call web_search via HTTP using Python httpx Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/endpoints.md This Python snippet demonstrates how to perform a web search using the web_search tool via HTTP with the httpx library. It sends a JSON-RPC request to the MCP server. ```python import httpx import json async with httpx.AsyncClient() as client: response = await client.post( "http://localhost:32123/mcp", json={ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "web_search", "arguments": { "query": "python tutorial", "categories": "general", "language": "en" } } } ) print(response.json()) ``` -------------------------------- ### Check SearXNG Health Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/errors.md Verifies the SearXNG URL by attempting to fetch its root. Ensure SEARXNG_URL is correctly set and the SearXNG instance is running and accessible. ```bash # Correct SEARXNG_URL export SEARXNG_URL=http://searxng.example.com python searxng_mcp.py ``` -------------------------------- ### SearXNG Settings for JSON Responses Source: https://github.com/aicrafted/searxng-mcp/blob/main/README.md Configuration snippet for SearXNG's `settings.yml` to enable JSON responses, which are required for the MCP server to read search results. ```yaml search: formats: - html - json ``` -------------------------------- ### Transport Security Settings from Environment Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/api-reference-overview.md Configures DNS rebinding protection for HTTP/SSE transports based on environment variables like MCP_DISABLE_DNS_REBINDING_PROTECTION, MCP_ALLOWED_HOSTS, or MCP_ALLOWED_ORIGINS. ```python def _transport_security_from_env() -> TransportSecuritySettings | None: ``` -------------------------------- ### SSE Transport on All Network Interfaces Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/configuration.md This command configures the server to use Server-Sent Events (SSE) transport and bind to all available network interfaces, which is common for Docker deployments. ```bash # Use SSE transport on all network interfaces (Docker) python searxng_mcp.py --transport sse --host 0.0.0.0 --port 8000 ``` -------------------------------- ### Call web_search via HTTP using cURL Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/endpoints.md Use this snippet to execute a web search using the web_search tool over HTTP with cURL. Ensure the MCP server is running and accessible at the specified local port. ```bash curl -X POST http://localhost:32123/mcp \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "web_search", "arguments": { "query": "python tutorial", "response_format": "markdown" } } }' ``` -------------------------------- ### Python: Search for News about AI Source: https://github.com/aicrafted/searxng-mcp/blob/main/_autodocs/quick-reference.md Demonstrates how to perform a news search for AI-related topics using the Python client library. Specifies the query, category, and time range. ```python await web_search( query="artificial intelligence", categories="news", time_range="month" ) ```