mirror of
https://github.com/xlionjuan/searxng-mcp-go.git
synced 2026-11-16 19:40:03 +00:00
* chore(deps): update dependency go to v1.27.1 * Fixed all lints; just verify passes. Co-authored-by: xlionjuan <[email protected]> * Fixed `.golangci.yml` paths→path; `just verify` passes. Co-authored-by: xlionjuan <[email protected]> * Parallelized golden & error-path tests; verify passes. Co-authored-by: xlionjuan <[email protected]> * Verify passes; HTTPClient/Logger nil set; exhaustruct covers Config. Co-authored-by: xlionjuan <[email protected]> --------- Co-authored-by: xlion-bot-renovate[bot] <218815870+xlion-bot-renovate[bot]@users.noreply.github.com> Co-authored-by: opencode-agent[bot] <opencode-agent[bot]@users.noreply.github.com> Co-authored-by: xlionjuan <[email protected]>
205 lines
6.3 KiB
Go
205 lines
6.3 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"log/slog"
|
|
"os"
|
|
"strings"
|
|
|
|
"searxng-mcp-go/internal/searxng"
|
|
)
|
|
|
|
var (
|
|
errMultipleQueries = errors.New("only one query is accepted; use quotes for multi-word queries")
|
|
errSearchQueryRequired = errors.New(
|
|
`search query is required; use --query "..." to search, or run without arguments for MCP server mode`,
|
|
)
|
|
errConfigurationFailed = errors.New("configuration error")
|
|
errSearchValidation = errors.New("validation error")
|
|
errSearcherCreation = errors.New("failed to create searcher")
|
|
errSearchFailed = errors.New("search error")
|
|
errJSONEncodeFailed = errors.New("failed to encode json")
|
|
)
|
|
|
|
// cliHelpTemplate is the CLI help body. The search-parameter OPTIONS lines
|
|
// are injected via the %s placeholder between the SEARXNG_URL help line and
|
|
// the --debug help line.
|
|
const cliHelpTemplate = `SearXNG MCP Server - CLI Mode (%s)
|
|
A Model Context Protocol server that provides web search via SearXNG.
|
|
|
|
USAGE:
|
|
searxng-mcp-go [OPTIONS] [QUERY]
|
|
|
|
OPTIONS:
|
|
--json Output results as formatted JSON instead of human-readable text
|
|
--searxng-url URL SearXNG instance URL (required)
|
|
Can also be set via SEARXNG_URL environment variable
|
|
%s --debug Enable verbose HTTP request/response logging
|
|
Can also be enabled via DEBUG=1 environment variable
|
|
--timeout DURATION Per-request HTTP client timeout (e.g., 8s) [default: %s]
|
|
Must be positive; zero is rejected. Cannot be set to
|
|
disable the package-managed timeout.
|
|
Can also be set via SEARXNG_TIMEOUT environment variable
|
|
--max-retries N Max retries after initial search attempt [default: %d]
|
|
Can also be set via SEARXNG_MAX_RETRIES environment variable
|
|
--allow-get-fallback
|
|
Enable POST→GET fallback for 405/501 responses (CLI mode)
|
|
Can also be set via SEARXNG_ALLOW_GET_FALLBACK environment variable
|
|
--help Show this help message
|
|
--version Show version information
|
|
|
|
ARGUMENTS:
|
|
QUERY Search query string (alternative to --query)
|
|
|
|
OUTPUT:
|
|
Results include title, URL, summary, publication date (if available), and engine source.
|
|
|
|
RETRY:
|
|
Retries use exponential backoff with equal jitter. The base delay defaults
|
|
to 1s, doubles each attempt, and is capped at 30s. The effective wait after
|
|
jitter is always at least 1s. Setting RetryDelay or MaxRetryDelay below 1s
|
|
is rejected. RetryDelay and MaxRetryDelay are configurable only through the
|
|
Config struct for programmatic callers.
|
|
|
|
EXAMPLES:
|
|
searxng-mcp-go "golang programming"
|
|
searxng-mcp-go --query "web development" --json
|
|
searxng-mcp-go --searxng-url https://my-searxng.example.com "search terms"
|
|
searxng-mcp-go "news" --language en --time_range month --categories news
|
|
|
|
MCP MODE:
|
|
When launched without CLI arguments by an MCP client, the server runs in
|
|
MCP stdio mode. The client must send a supported MCP first message on stdin:
|
|
legacy initialize, server/discover, or a stateless request with protocol metadata.
|
|
|
|
EXIT CODES:
|
|
0 Success
|
|
1 Search error or invalid arguments
|
|
2 MCP server error (in MCP mode)
|
|
|
|
For more information, see: https://github.com/xlionjuan/searxng-mcp-go
|
|
`
|
|
|
|
// searchParamsHelpLines renders the per-parameter OPTIONS lines from the
|
|
// shared searxng.SearchParams table.
|
|
func searchParamsHelpLines() string {
|
|
var sb strings.Builder
|
|
|
|
for _, param := range searxng.SearchParams {
|
|
sb.WriteString(param.CLIHelpLine())
|
|
sb.WriteByte('\n')
|
|
}
|
|
|
|
return sb.String()
|
|
}
|
|
|
|
// printCLIHelp writes the help message to the given writer.
|
|
func printCLIHelp(w io.Writer) {
|
|
var sb strings.Builder
|
|
|
|
fmt.Fprintf(&sb, cliHelpTemplate, version, searchParamsHelpLines(), searxng.DefaultTimeout, searxng.DefaultMaxRetries)
|
|
|
|
_, err := w.Write([]byte(sb.String()))
|
|
if err != nil {
|
|
slog.Warn("failed to write help text", "error", err)
|
|
}
|
|
}
|
|
|
|
// runCLIMode executes the CLI-mode search flow.
|
|
func runCLIMode(debug bool, flags *CLIFlags, positionalArgs []string) error {
|
|
if flags.Help {
|
|
printCLIHelp(os.Stdout)
|
|
|
|
return nil
|
|
}
|
|
|
|
if flags.Version {
|
|
fmt.Printf("searxng-mcp-go version %s (commit: %s, built: %s)\n", version, commit, date)
|
|
fmt.Println("SearXNG MCP Server - CLI + MCP stdio dual-mode")
|
|
|
|
return nil
|
|
}
|
|
|
|
query := flags.Query
|
|
if query == "" {
|
|
if len(positionalArgs) > 1 {
|
|
return errMultipleQueries
|
|
}
|
|
|
|
if len(positionalArgs) > 0 {
|
|
query = positionalArgs[0]
|
|
}
|
|
}
|
|
|
|
if query == "" {
|
|
return errSearchQueryRequired
|
|
}
|
|
|
|
return runSearch(debug, flags, query)
|
|
}
|
|
|
|
// runSearch resolves the configuration, builds and validates the search
|
|
// arguments, performs the search, and writes the result to stdout.
|
|
func runSearch(debug bool, flags *CLIFlags, query string) error {
|
|
cfg, err := getConfig(flags, true)
|
|
if err != nil {
|
|
return fmt.Errorf("%w: %w", errConfigurationFailed, err)
|
|
}
|
|
|
|
args := searxng.NewSearchArgs(query)
|
|
args.Language = flags.Language
|
|
args.SafeSearch = flags.SafeSearch
|
|
args.TimeRange = flags.TimeRange
|
|
args.Categories = flags.Categories
|
|
args.Engines = flags.Engines
|
|
args.Pageno = flags.Pageno
|
|
// Limit is set by NewSearchArgs to DefaultResultLimit; override if
|
|
// the CLI flag was explicitly provided (flags.Limit is always non-nil
|
|
// after parseArgs because parseArgs fills the default when unset).
|
|
if flags.Limit != nil {
|
|
args.Limit = flags.Limit
|
|
}
|
|
|
|
args, err = searxng.ValidateSearchArgs(args)
|
|
if err != nil {
|
|
return fmt.Errorf("%w: %w", errSearchValidation, err)
|
|
}
|
|
|
|
searcher, err := searxng.NewSearXNGSearcher(cfg, debug)
|
|
if err != nil {
|
|
return fmt.Errorf("%w: %w", errSearcherCreation, err)
|
|
}
|
|
|
|
defer func() { _ = searcher.Close() }() //nolint:errcheck // cleanup in defer; error is non-actionable
|
|
|
|
resp, err := searcher.Search(context.Background(), args)
|
|
if err != nil {
|
|
return fmt.Errorf("%w: %w", errSearchFailed, err)
|
|
}
|
|
|
|
return outputSearchResult(resp, flags.JSON)
|
|
}
|
|
|
|
// outputSearchResult formats and writes the search result to stdout.
|
|
func outputSearchResult(resp *searxng.SearchResponse, jsonOutput bool) error {
|
|
if jsonOutput {
|
|
enc := json.NewEncoder(os.Stdout)
|
|
enc.SetIndent("", " ")
|
|
|
|
err := enc.Encode(resp)
|
|
if err != nil {
|
|
return fmt.Errorf("%w: %w", errJSONEncodeFailed, err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
logUnresponsiveEngines(slog.Default(), resp)
|
|
fmt.Print(formatResults(resp))
|
|
|
|
return nil
|
|
}
|