### Install @plust/search-sdk Source: https://github.com/plustorg/search-sdk/blob/main/README.md Install the package using npm. ```bash npm install @plust/search-sdk ``` -------------------------------- ### Quick Start with Google Search Source: https://github.com/plustorg/search-sdk/blob/main/README.md Configure the Google search provider with your API key and Search Engine ID, then perform a web search. ```typescript import { google, webSearch } from '@plust/search-sdk'; // Configure the Google search provider with your API key and Search Engine ID const configuredGoogle = google.configure({ apiKey: 'YOUR_GOOGLE_API_KEY', cx: 'YOUR_SEARCH_ENGINE_ID' }); // Search using the configured provider async function search() { const results = await webSearch({ query: 'TypeScript SDK', maxResults: 5, provider: [configuredGoogle] // Provider is now an array }); console.log(results); } search(); ``` -------------------------------- ### Usage Example: createSerpApiProvider Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/api-reference-serpapi.md Demonstrates how to create a SerpAPI provider for Google search and use it with the webSearch function to find results. ```typescript import { createSerpApiProvider, webSearch } from '@plust/search-sdk'; const serpProvider = createSerpApiProvider({ apiKey: 'YOUR_SERPAPI_KEY', engine: 'google' }); const results = await webSearch({ query: 'TypeScript performance tips', maxResults: 10, provider: [serpProvider] }); console.log(`Got ${results.length} results from SerpAPI`); ``` -------------------------------- ### Usage Example: serpapi.configure Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/api-reference-serpapi.md Shows how to configure SerpAPI providers for both Google and Bing engines and perform a web search using the configured provider. ```typescript import { serpapi, webSearch } from '@plust/search-sdk'; // Google engine const googleSerpProvider = serpapi.configure({ apiKey: process.env.SERPAPI_KEY, engine: 'google' }); // Or Bing engine const bingSerpProvider = serpapi.configure({ apiKey: process.env.SERPAPI_KEY, engine: 'bing' }); // Perform search const results = await webSearch({ query: 'web development frameworks', maxResults: 15, language: 'en', region: 'US', safeSearch: 'moderate', page: 1, provider: [googleSerpProvider] }); results.forEach(r => { console.log(`${r.title}`); console.log(` Domain: ${r.domain}`); console.log(` Date: ${r.publishedDate || 'N/A'}`); }); ``` -------------------------------- ### Export MCP Configuration Environment Variable Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/mcp-integration.md Example of how to export the `SEARCH_SDK_MCP_CONFIG` environment variable with a JSON string containing provider configurations. ```bash export SEARCH_SDK_MCP_CONFIG='{"providers":[{"name":"google","config":{"apiKey":"YOUR_KEY","cx":"YOUR_CX"}},{"name":"brave","config":{"apiKey":"YOUR_KEY"}}]}' ``` -------------------------------- ### Usage Example for createBraveProvider Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/api-reference-brave.md Demonstrates how to create a Brave provider instance and use it with the `webSearch` function. Requires an API key and shows basic result iteration. ```typescript import { createBraveProvider, webSearch } from '@plust/search-sdk'; const braveProvider = createBraveProvider({ apiKey: 'YOUR_BRAVE_API_TOKEN' }); const results = await webSearch({ query: 'privacy browsers', maxResults: 10, provider: [braveProvider] }); results.forEach(r => { console.log(`${r.title} (${r.domain})`); }); ``` -------------------------------- ### Usage Example for brave.configure Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/api-reference-brave.md Shows how to configure the Brave provider using `brave.configure` with an API key from environment variables and then perform a web search with various options like `maxResults`, `safeSearch`, `region`, and `language`. ```typescript import { brave, webSearch } from '@plust/search-sdk'; const braveProvider = brave.configure({ apiKey: process.env.BRAVE_API_KEY }); const results = await webSearch({ query: 'open source projects', maxResults: 20, safeSearch: 'moderate', region: 'US', language: 'en', provider: [braveProvider] }); results.forEach(r => { console.log(`${r.title}`); console.log(` URL: ${r.url}`); console.log(` Domain: ${r.domain}`); if (r.publishedDate) { console.log(` Published: ${r.publishedDate}`); } }); ``` -------------------------------- ### Directly Spawn MCP Server Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/mcp-integration.md Low-level example demonstrating how to spawn the MCP server process directly using Node.js `child_process.spawn` and communicate with it via stdio. Requires configuring at least one provider. ```typescript import { spawn } from 'child_process'; import { asMcp, google } from '@plust/search-sdk'; const provider = google.configure({ apiKey: process.env.GOOGLE_API_KEY, cx: process.env.GOOGLE_CX_ID }); const mcpConfig = asMcp([provider]); // Spawn the MCP server const server = spawn(mcpConfig.command, mcpConfig.args, { env: { ...process.env, ...mcpConfig.env } }); // Communicate over stdio server.stdout.on('data', (data) => { console.log('MCP:', data.toString()); }); server.on('error', (error) => { console.error('MCP Error:', error); }); ``` -------------------------------- ### Configure Claude Desktop MCP Server Source: https://github.com/plustorg/search-sdk/blob/main/README.md Add MCP server configuration for the search SDK to your Claude Desktop settings. Adjust the path to `cli.js` if your installation differs. ```json { "mcpServers": { "search-sdk": { "command": "node", "args": ["node_modules/@plust/search-sdk/dist/mcp/cli.js"], "env": { "SEARCH_SDK_MCP_CONFIG": "{\"providers\":[{\"name\":\"brave\",\"config\":{\"apiKey\":\"YOUR_API_KEY\"}}]}" } } } } ``` -------------------------------- ### Import Core Utilities from Main SDK Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/utilities.md Import core utilities like debug, HttpError, get, post, and webSearch from the main SDK entry point. ```typescript import { debug, HttpError, get, post, webSearch } from '@plust/search-sdk'; ``` -------------------------------- ### Configure Providers with Environment Variables Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/configuration.md Store sensitive credentials like API keys and CX IDs in environment variables for secure access. This example shows configuration for Google and Brave providers. ```typescript const providers = [ google.configure({ apiKey: process.env.GOOGLE_API_KEY, cx: process.env.GOOGLE_CX_ID }), brave.configure({ apiKey: process.env.BRAVE_API_KEY }), // ... more providers ]; ``` -------------------------------- ### MCP Stdio Protocol Request/Response Examples Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/mcp-integration.md Illustrates the JSON-RPC messages exchanged over stdio for listing resources and calling tools. Ensure messages are newline-delimited JSON. ```json Client Request: {"jsonrpc":"2.0","id":1,"method":"resources/list"} ``` ```json MCP Response: {"jsonrpc":"2.0","id":1,"result":{"resources":[...]}} ``` ```json Tool Call: {"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"webSearch","arguments":{"query":"test"}}} ``` ```json Tool Result: {"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"[...]"}]}} ``` -------------------------------- ### get Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/utilities.md Makes a GET request to the specified URL with optional headers and timeout. ```APIDOC ## get ### Description Makes a GET request to the specified URL. ### Method Signature ```typescript export async function get(url: string, options: Omit = {}): Promise ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Options - **url** (string) - Required - URL to request. - **options.headers** (Record) - Optional - Request headers. Defaults to {}. - **options.timeout** (number) - Optional - Timeout in milliseconds. Defaults to 15000. ### Return Type `Promise` — Parsed JSON response ### Throws - `HttpError` if status code is not 2xx - `Error` if request times out ### Usage Example ```typescript import { get } from '@plust/search-sdk/dist/utils/http'; interface SearchResponse { results: any[]; count: number; } const response = await get( 'https://api.search.example.com/query?q=test' ); console.log(`Found ${response.count} results`); ``` ``` -------------------------------- ### Configure and Use DuckDuckGo Search (Images) Source: https://github.com/plustorg/search-sdk/blob/main/README.md Configure the DuckDuckGo provider for image search. This example demonstrates setting the search type to 'images'. ```typescript // Image search const imageProvider = duckduckgo.configure({ searchType: 'images' }); const imageResults = await webSearch({ query: 'landscape photography', maxResults: 10, provider: [imageProvider] }); ``` -------------------------------- ### Configure Arxiv Provider Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/api-reference-other-providers.md Configure the Arxiv provider with custom sorting options. This setup is used before making search requests. ```typescript import { arxiv, webSearch } from '@plust/search-sdk'; const arxivProvider = arxiv.configure({ sortBy: 'relevance', sortOrder: 'descending' }); ``` -------------------------------- ### Perplexity Country Configuration Example Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/INDEX.md Demonstrates how function parameters override provider-specific configuration. The `region` parameter in `webSearch` takes precedence over the `country` setting in `perplexity.configure`. ```typescript // Uses config value (US) because function param not provided const results = await webSearch({ query: 'term', provider: [perplexity.configure({ country: 'US' })] }); // Function param overrides config const results2 = await webSearch({ query: 'term', region: 'GB', // Overrides config.country provider: [perplexity.configure({ country: 'US' })] }); ``` -------------------------------- ### Configure and Use DuckDuckGo Search (News) Source: https://github.com/plustorg/search-sdk/blob/main/README.md Configure the DuckDuckGo provider for news search. This example shows how to set the search type to 'news'. ```typescript // News search const newsProvider = duckduckgo.configure({ searchType: 'news' }); const newsResults = await webSearch({ query: 'latest technology', maxResults: 10, provider: [newsProvider] }); ``` -------------------------------- ### Configure and Use DuckDuckGo Search (Text) Source: https://github.com/plustorg/search-sdk/blob/main/README.md Configure the DuckDuckGo provider for text search. Options include search type, lite mode, and region. This example performs a text search. ```typescript import { duckduckgo, webSearch } from '@plust/search-sdk'; // DuckDuckGo doesn't require an API key, but you can configure other options const duckduckgoProvider = duckduckgo.configure({ searchType: 'text', // Optional: 'text', 'images', or 'news' useLite: false, // Optional: use lite version for lower bandwidth region: 'wt-wt' // Optional: region code }); // Text search const textResults = await webSearch({ query: 'privacy focused search', maxResults: 10, provider: [duckduckgoProvider] }); ``` -------------------------------- ### Handle Partial Provider Failure Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/errors.md This example shows the behavior when using multiple providers where some may fail but at least one succeeds. The function returns results from successful providers and logs errors from failed ones without throwing an exception. ```typescript const results = await webSearch({ query: 'test', provider: [googleProvider, braveProvider], debug: { enabled: true, logRequests: true } }); // If Google fails but Brave succeeds: // - results contains only Brave results // - Google error is logged to console // - No exception is thrown ``` -------------------------------- ### Make GET Request Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/utilities.md Use `get` for simple GET requests. It automatically handles JSON parsing and includes default timeout settings. Specify the expected response type using generics. ```typescript export async function get(url: string, options: Omit = {}): Promise ``` ```typescript import { get } from '@plust/search-sdk/dist/utils/http'; interface SearchResponse { results: any[]; count: number; } const response = await get( 'https://api.search.example.com/query?q=test' ); console.log(`Found ${response.count} results`); ``` -------------------------------- ### Configure Multiple Search Providers and Execute Search Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/README.md Demonstrates how to configure multiple search providers (Google, Brave, Exa, Perplexity) with their respective API keys and settings. It then shows how to execute a web search query across all configured providers, specifying search parameters like max results, language, region, and safety settings. Debugging options are also included. ```typescript import { google, brave, exa, perplexity, webSearch } from '@plust/search-sdk'; // Configure multiple providers const providers = [ // Google: Requires API key + Custom Search Engine ID google.configure({ apiKey: process.env.GOOGLE_API_KEY, cx: process.env.GOOGLE_CX_ID }), // Brave: Requires API token brave.configure({ apiKey: process.env.BRAVE_API_KEY }), // Exa: Semantic search with optional content extraction exa.configure({ apiKey: process.env.EXA_API_KEY, model: 'embeddings', includeContents: true }), // Perplexity: Advanced filtering options perplexity.configure({ apiKey: process.env.PERPLEXITY_API_KEY, maxTokens: 25000, country: 'US', searchLanguageFilter: ['en', 'fr'], searchRecencyFilter: 'week' }) ]; // Execute search across all providers const results = await webSearch({ query: 'artificial intelligence', maxResults: 10, language: 'en', region: 'US', safeSearch: 'moderate', provider: providers, timeout: 30000, debug: { enabled: true, logRequests: true, logResponses: false } }); console.log(`\nTotal results: ${results.length}`); console.log('Providers:', new Set(results.map(r => r.provider))); ``` -------------------------------- ### SerpAPI Provider Configuration Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/MANIFEST.txt Configuration details for the SerpAPI provider, including its specific configuration object and setup functions. ```typescript createSerpApiProvider(config: SerpApiSearchConfig): SearchProvider ``` ```typescript serpapi.configure(config: SerpApiSearchConfig): void ``` -------------------------------- ### Basic Search with Google Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/README.md Demonstrates how to configure the Google provider and perform a basic web search. Ensure your API key and CX ID are set as environment variables. ```typescript import { google, webSearch } from '@plust/search-sdk'; const provider = google.configure({ apiKey: process.env.GOOGLE_API_KEY, cx: process.env.GOOGLE_CX_ID }); const results = await webSearch({ query: 'TypeScript SDK', maxResults: 10, provider: [provider] }); console.log(`Found ${results.length} results`); results.forEach(r => console.log(`- ${r.title}`)); ``` -------------------------------- ### Generic HTTP Request Functions Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/MANIFEST.txt Generic functions for making HTTP requests, supporting GET and POST methods with type inference. ```typescript makeRequest(options: HttpRequestOptions): Promise ``` ```typescript get(url: string, options?: HttpRequestOptions): Promise ``` ```typescript post(url: string, data: any, options?: HttpRequestOptions): Promise ``` -------------------------------- ### Brave Search Provider Configuration Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/MANIFEST.txt Configuration details for the Brave Search provider, including its specific configuration object and setup functions. ```typescript createBraveProvider(config: BraveSearchConfig): SearchProvider ``` ```typescript brave.configure(config: BraveSearchConfig): void ``` -------------------------------- ### Web Search with Debugging Enabled Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/types.md Example of calling the webSearch function with detailed debugging options enabled, including a custom logger. ```typescript const results = await webSearch({ query: 'TypeScript', provider: [googleProvider], debug: { enabled: true, logRequests: true, logResponses: true, logger: (message, data) => { console.log(`[SDK] ${message}`, data); } } }); ``` -------------------------------- ### google.configure Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/api-reference-google.md Pre-configured Google provider object with a `configure()` method to set credentials and create a provider instance. ```APIDOC ## google.configure ### Description Creates and returns a configured Google Custom Search provider. ### Signature ```typescript google.configure(config: GoogleSearchConfig): SearchProvider ``` ### Parameters #### config - **config.apiKey** (string) - Required - Your Google Custom Search API key from Google Cloud Console. - **config.cx** (string) - Required - Your Custom Search Engine ID. - **config.baseUrl** (string) - Optional - Override the default API base URL. Defaults to `https://www.googleapis.com/customsearch/v1`. ### Return Type `SearchProvider` — A fully configured provider ready to use with `webSearch()`. ### Supported Search Options When using the Google provider, the following `webSearch` options are supported: - **query**: Full-text search query. - **maxResults**: Limited to 10 per request by Google API; pagination available via `page`. - **language**: Maps to `lr` parameter (e.g., 'en' → 'lang_en'). - **region**: Maps to `gl` parameter (e.g., 'us'). - **safeSearch**: 'off' or 'moderate'/'strict' map to Google's safe parameter. - **page**: Pagination support via start index calculation. ### Error Handling Google-specific errors include: - **400 Bad Request**: Invalid query parameters or Search Engine ID. Check `cx` value and query syntax. - **401/403 Unauthorized**: Invalid or missing API key. Verify credentials in Google Cloud Console. - **403 Forbidden (dailyLimit)**: Daily quota exceeded. Check quota in Google Cloud Console. - **403 Forbidden (userRateLimitExceeded)**: Rate limit hit. Implement backoff in your application. ### Usage Example ```typescript import { google, webSearch } from '@plust/search-sdk'; const googleProvider = google.configure({ apiKey: process.env.GOOGLE_API_KEY, cx: process.env.GOOGLE_CX_ID }); // Now use the provider const results = await webSearch({ query: 'machine learning tutorials', maxResults: 10, provider: [googleProvider] }); // Results include URL, title, snippet, domain, publishedDate, provider name, and raw data console.log(results[0].url); console.log(results[0].title); console.log(results[0].snippet); ``` ``` -------------------------------- ### Configure Google Provider with configure Method Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/api-reference-google.md The `google.configure` method provides a convenient way to set up the Google provider using environment variables for credentials. It returns a configured provider ready for use with `webSearch`. ```typescript import { google, webSearch } from '@plust/search-sdk'; const googleProvider = google.configure({ apiKey: process.env.GOOGLE_API_KEY, cx: process.env.GOOGLE_CX_ID }); // Now use the provider const results = await webSearch({ query: 'machine learning tutorials', maxResults: 10, provider: [googleProvider] }); // Results include URL, title, snippet, domain, publishedDate, provider name, and raw data console.log(results[0].url); console.log(results[0].title); console.log(results[0].snippet); ``` -------------------------------- ### Common HttpError Messages Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/utilities.md Provides examples of typical error messages generated by the HttpError class for various HTTP status codes. ```text Request failed with status: 400 Bad Request - Invalid Value Request failed with status: 401 Unauthorized - Authentication required Request failed with status: 429 Too Many Requests - Rate limit exceeded Request failed with status: 500 Internal Server Error - Server error ``` -------------------------------- ### Configure Brave Provider with API Key Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/api-reference-brave.md Use `brave.configure` to set up the Brave provider, optionally overriding the base URL. This method is convenient for initializing the provider with credentials, often from environment variables. ```typescript brave.configure(config: BraveSearchConfig): SearchProvider ``` -------------------------------- ### serpapi.configure Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/api-reference-serpapi.md Configures and returns a SerpAPI provider instance. This method allows setting credentials and search engine preferences. ```APIDOC ## serpapi.configure Pre-configured SerpAPI provider object with a `configure()` method to set credentials. ```typescript const serpapi: { name: 'serpapi', configure(config: SerpApiConfig): SearchProvider, search(options: SearchOptions): Promise } ``` ### configure Method ```typescript serpapi.configure(config: SerpApiConfig): SearchProvider ``` Creates and returns a configured SerpAPI provider. ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | config.apiKey | string | Yes | — | Your SerpAPI key from serpapi.com. | | config.engine | string | No | 'google' | Search engine: 'google', 'bing', 'yahoo', 'duckduckgo', etc. | | config.baseUrl | string | No | https://serpapi.com/search.json | Override the default API base URL. | ### Return Type `SearchProvider` — A fully configured provider ready to use with `webSearch()`. ### Usage Example ```typescript import { serpapi, webSearch } from '@plust/search-sdk'; // Google engine const googleSerpProvider = serpapi.configure({ apiKey: process.env.SERPAPI_KEY, engine: 'google' }); // Or Bing engine const bingSerpProvider = serpapi.configure({ apiKey: process.env.SERPAPI_KEY, engine: 'bing' }); // Perform search const results = await webSearch({ query: 'web development frameworks', maxResults: 15, language: 'en', region: 'US', safeSearch: 'moderate', page: 1, provider: [googleSerpProvider] }); results.forEach(r => { console.log(`${r.title}`); console.log(` Domain: ${r.domain}`); console.log(` Date: ${r.publishedDate || 'N/A'}`); }); ``` ### Supported Search Options When using the SerpAPI provider, the following `webSearch` options are supported: | Option | Support | Notes | |--------|---------|-------| | query | ✓ | Full-text search query. | | maxResults | ✓ | Maps to `num` parameter for Google engine. | | language | ✓ | Maps to `hl` parameter (interface language). | | region | ✓ | Maps to `gl` parameter (country/region). | | safeSearch | ✓ | Direct pass-through to `safe` parameter. | | page | ✓ | Pagination via start index calculation. | ### Response Structure Results from SerpAPI include: - **url**: The result URL - **title**: Page title - **snippet**: Snippet/description from organic results - **domain**: Extracted from `displayed_link` - **publishedDate**: Date field if available - **raw**: Raw SerpAPI result object ### Supported Engines SerpAPI supports multiple search engines via the `engine` config parameter: | Engine | Notes | |--------|-------| | google | Default; returns organic search results | | bing | Microsoft Bing search results | | yahoo | Yahoo search results | | duckduckgo | DuckDuckGo results | | baidu | Chinese search engine | | yandex | Russian search engine | ### Error Handling SerpAPI-specific errors include: - **400 Bad Request**: Invalid parameters or missing required field. Check engine name and parameter values. - **401/403 Unauthorized**: Invalid or missing API key. Verify credentials in SerpAPI account. - **429 Too Many Requests**: Rate limit or quota exceeded. Check subscription plan limits. - **500+ Server Error**: SerpAPI experiencing issues. ### API Response Structure The provider parses SerpAPI's standard response format which includes: - `search_metadata`: Information about the search request - `search_parameters`: Echo of the parameters sent - `search_information`: Metadata including total results and time taken - `organic_results`: Array of search results ``` -------------------------------- ### Google Custom Search Provider Configuration Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/MANIFEST.txt Configuration details for the Google Custom Search provider, including its specific configuration object and setup functions. ```typescript createGoogleProvider(config: GoogleSearchConfig): SearchProvider ``` ```typescript google.configure(config: GoogleSearchConfig): void ``` -------------------------------- ### Configure and Use SearXNG Source: https://github.com/plustorg/search-sdk/blob/main/README.md Configure the SearXNG provider with its base URL and optional additional parameters. An API key is not typically needed. ```typescript import { searxng, webSearch } from '@plust/search-sdk'; const searxngProvider = searxng.configure({ baseUrl: 'http://127.0.0.1:8080/search', additionalParams: { // Optional additional parameters for SearXNG categories: 'general', engines: 'google,brave,duckduckgo' }, apiKey: '' // Not needed for most SearXNG instances }); const results = await webSearch({ query: 'open source software', provider: [searxngProvider] }); ``` -------------------------------- ### createArxivProvider Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/api-reference-other-providers.md Initializes the Arxiv search provider with optional configuration. This provider queries the Arxiv preprint repository and does not require an API key. ```APIDOC ## createArxivProvider ### Description Initializes the Arxiv search provider with optional configuration. ### Signature ```typescript export function createArxivProvider(config: ArxivConfig = {}): SearchProvider ``` ### Configuration | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | config.baseUrl | string | No | http://export.arxiv.org/api/query | Custom API base URL. | | config.sortBy | 'relevance' \| 'lastUpdatedDate' \| 'submittedDate' | No | 'relevance' | Result sort field. | | config.sortOrder | 'ascending' \| 'descending' | No | 'descending' | Sort direction. | ### Supported Options for webSearch - `query`: Arxiv query with field prefixes (au:, ti:, cat:, etc.) - `idList`: Comma-separated Arxiv IDs - `maxResults`: Result limit - `start`: Pagination offset - `sortBy`: Sort field - `sortOrder`: Sort direction ### Query Syntax Arxiv queries support field-specific prefixes: | Prefix | Field | |--------|-------| | au: | Author | | ti: | Title | | cat: | Category | | abs: | Abstract | | all: | All fields | Example: `au:Einstein AND cat:physics` ### Response Structure Results include extended metadata: - **authors**: Array of author names - **categories**: Array of Arxiv category codes - **raw**: Full Atom entry object with additional metadata ### Usage Example ```typescript import { arxiv, webSearch } from '@plust/search-sdk'; const arxivProvider = arxiv.configure({ sortBy: 'relevance', sortOrder: 'descending' }); // Query by search terms const results = await webSearch({ query: 'cat:cs.AI AND ti:transformer', maxResults: 5, provider: [arxivProvider] }); // Query by Arxiv IDs const results2 = await webSearch({ idList: '2305.12345v1,2203.01234v2', maxResults: 2, provider: [arxivProvider] }); ``` ``` -------------------------------- ### Configure Search Timeout Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/configuration.md Adjust the request timeout duration to accommodate slower network connections. The default is 15 seconds; this example sets it to 30 seconds. ```typescript const results = await webSearch({ query: 'term', provider: [googleProvider], timeout: 30000 // 30 seconds }); ``` -------------------------------- ### Multiple Providers (Fail-Soft) Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/README.md Shows how to use multiple search providers simultaneously. The SDK will combine results and gracefully handle failures from individual providers. ```typescript import { google, brave, webSearch } from '@plust/search-sdk'; // Results from both providers combined // If one fails, returns results from the other const results = await webSearch({ query: 'machine learning', maxResults: 10, provider: [ google.configure({ apiKey: '...', cx: '...' }), brave.configure({ apiKey: '...' }) ] }); ``` -------------------------------- ### Full SDK Import Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/module-structure.md Import all available modules from the search SDK. This is useful when you need access to all providers and utilities. ```typescript import { webSearch, google, brave, serpapi, exa, tavily, searxng, arxiv, duckduckgo, perplexity, debug, asMcp } from '@plust/search-sdk'; ``` -------------------------------- ### Perform Web Search with Multiple Providers Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/api-reference-main.md Demonstrates how to configure and use multiple search providers (Google, Brave) with the webSearch function. Handles results and errors gracefully. Ensure API keys and IDs are correctly configured. ```typescript import { google, brave, webSearch } from '@plust/search-sdk'; const googleProvider = google.configure({ apiKey: 'YOUR_GOOGLE_API_KEY', cx: 'YOUR_SEARCH_ENGINE_ID' }); const braveProvider = brave.configure({ apiKey: 'YOUR_BRAVE_API_KEY' }); async function search() { try { const results = await webSearch({ query: 'TypeScript best practices', maxResults: 10, language: 'en', region: 'US', safeSearch: 'moderate', provider: [googleProvider, braveProvider], timeout: 30000 }); console.log(`Found ${results.length} results`); results.forEach(result => { console.log(`${result.title} (${result.provider})`); console.log(` ${result.url}`); console.log(` ${result.snippet}`); }); } catch (error) { console.error('Search failed:', error.message); } } search(); ``` -------------------------------- ### Deep Utility Imports Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/module-structure.md Import utility functions like 'get', 'post', and 'buildUrl' directly from their specific module paths. This is for advanced usage or when you need fine-grained control over dependencies. ```typescript // Utilities directly import { get, post, buildUrl } from '@plust/search-sdk/dist/utils/http'; import { debug } from '@plust/search-sdk/dist/utils/debug'; ``` -------------------------------- ### Create Brave Search Provider Instance Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/api-reference-brave.md Use `createBraveProvider` to instantiate a Brave Search provider. Ensure your API key is provided in the configuration. This is useful for direct integration into your application. ```typescript export function createBraveProvider(config: BraveSearchConfig): SearchProvider ``` -------------------------------- ### Configure Claude Desktop MCP Server Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/mcp-integration.md Add MCP server configuration to Claude Desktop settings. Ensure the path to the CLI and environment variables are correctly set. ```json { "mcpServers": { "search-sdk": { "command": "node", "args": ["node_modules/@plust/search-sdk/dist/mcp/cli.js"], "env": { "SEARCH_SDK_MCP_CONFIG": "{\"providers\":[{\"name\":\"google\",\"config\":{\"apiKey\":\"YOUR_KEY\",\"cx\":\"YOUR_CX\"}}]}" } } } } ``` -------------------------------- ### brave.configure Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/api-reference-brave.md Method to configure the Brave provider with credentials and an optional custom base URL. It returns a configured provider object. ```APIDOC ## brave.configure ### Description Pre-configured Brave provider object with a `configure()` method to set credentials. Creates and returns a configured Brave Search provider. ### Signature ```typescript brave.configure(config: BraveSearchConfig): SearchProvider ``` ### Parameters #### Path Parameters - **config.apiKey** (string) - Required - Your Brave Search subscription token from Brave Developer Hub. - **config.baseUrl** (string) - Optional - Override the default API base URL. Defaults to `https://api.search.brave.com/res/v1/web/search`. ### Return Type `SearchProvider` — A fully configured provider ready to use with `webSearch()`. ### Supported Search Options When using the Brave provider, the following `webSearch` options are supported: | Option | Support | Notes | |--------|---------|-------| | query | ✓ | Required. Full-text search query. | | maxResults | ✓ | Results per page (maps to `size` parameter). | | language | ✓ | Language code (maps to `language` parameter). | | region | ✓ | Country code (maps to `country` parameter). | | safeSearch | ✓ | 'off' (0), 'moderate' (1), 'strict' (2). | | page | ✓ | Pagination via offset calculation. | ### Response Structure Results from Brave include: - **url**: The result URL - **title**: Page title - **snippet**: Description (from `description` field) - **domain**: Hostname extracted from URL - **publishedDate**: Age indicator if available - **raw**: Raw Brave response object including `is_source_local`, `language`, `family_friendly` ### Error Handling Brave-specific errors include: - **400 Bad Request**: Invalid search parameters. Check query and optional filters. - **401/403 Unauthorized**: Invalid or missing API token. Verify subscription in Brave Developer Hub. - **429 Too Many Requests**: Rate limit exceeded. Implement backoff strategy. ### Error Codes and Diagnostics | Status | Meaning | Typical Cause | |--------|---------|---------------| | 401 | Unauthorized | Invalid API token; token expired | | 403 | Forbidden | Insufficient subscription level | | 429 | Rate Limited | Too many requests in short time | | 500+ | Server Error | Brave API experiencing issues | ### Usage Example ```typescript import { brave, webSearch } from '@plust/search-sdk'; const braveProvider = brave.configure({ apiKey: process.env.BRAVE_API_KEY }); const results = await webSearch({ query: 'open source projects', maxResults: 20, safeSearch: 'moderate', region: 'US', language: 'en', provider: [braveProvider] }); results.forEach(r => { console.log(`${r.title}`); console.log(` URL: ${r.url}`); console.log(` Domain: ${r.domain}`); if (r.publishedDate) { console.log(` Published: ${r.publishedDate}`); } }); ``` ``` -------------------------------- ### Import All HTTP Utilities from Utils Module Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/utilities.md Import all HTTP utilities, including buildUrl and makeRequest, from the SDK's utils module for more comprehensive HTTP handling. ```typescript import { debug, HttpError, get, post, buildUrl, makeRequest } from '@plust/search-sdk/dist/utils'; ``` -------------------------------- ### MCP Integration for AI Agents Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/README.md Shows how to integrate the search SDK with MCP (Multi-modal Communication Protocol) for use with AI agents like Stagehand or Claude Desktop. This allows AI agents to leverage web search capabilities. ```typescript import { asMcp, google } from '@plust/search-sdk'; const provider = google.configure({ apiKey: '...', cx: '...' }); const mcpConfig = asMcp([provider]); // Use with Stagehand or Claude Desktop const client = await connectToMCPServer(mcpConfig); const results = await client.callTool('webSearch', { query: 'AI developments', maxResults: 5 }); ``` -------------------------------- ### Exa Configuration Source: https://github.com/plustorg/search-sdk/blob/main/README.md Configure the Exa provider with your API key. You can specify the model and whether to include contents. ```APIDOC ## Exa Configuration ### Description Configure the Exa provider with your API key. You can specify the model and whether to include contents. ### Usage ```typescript import { exa, webSearch } from '@plust/search-sdk'; const exaProvider = exa.configure({ apiKey: 'YOUR_EXA_API_KEY', model: 'keyword', // Optional, defaults to 'keyword' includeContents: true // Optional, defaults to false }); const results = await webSearch({ query: 'machine learning papers', provider: [exaProvider] }); ``` ``` -------------------------------- ### Enable Detailed Debugging Logs Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/errors.md To get more insights into requests and responses, enable detailed debugging. This includes logging full request URLs, parameters (with masked API keys), response metadata, status codes, and raw response bodies for JSON errors. ```typescript const results = await webSearch({ query: 'test', provider: [googleProvider], debug: { enabled: true, logRequests: true, logResponses: true, logger: (msg, data) => { console.error(`[Search SDK] ${msg}`, data); } } }); ``` -------------------------------- ### createSearxNGProvider Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/api-reference-other-providers.md Creates a SearXNG search provider instance. This allows querying self-hosted or remote SearXNG instances. ```APIDOC ## createSearxNGProvider ### Description Creates a SearXNG search provider instance. This allows querying self-hosted or remote SearXNG instances. ### Method ```typescript export function createSearxNGProvider(config: SearxNGConfig): SearchProvider ``` ### Parameters #### Configuration - **config.baseUrl** (string) - Required - SearXNG instance URL (e.g., http://127.0.0.1:8080/search). - **config.apiKey** (string) - Optional - Optional API key if instance requires authentication. - **config.additionalParams** (Record) - Optional - Additional SearXNG parameters (categories, engines, etc.). ### Usage ```typescript import { searxng, webSearch } from '@plust/search-sdk'; const searxngProvider = searxng.configure({ baseUrl: 'http://127.0.0.1:8080/search', additionalParams: { categories: 'general', engines: 'google,brave,duckduckgo' } }); const results = await webSearch({ query: 'open source software', maxResults: 10, provider: [searxngProvider] }); ``` ### Supported Options - `query`: Search query - `maxResults`: Result limit (maps to `count`) - `language`: Language filter - `safeSearch`: Safe search setting (0=off, 1=moderate, 2=strict) ``` -------------------------------- ### Create Google Provider Instance Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/api-reference-google.md Use `createGoogleProvider` to instantiate a Google Custom Search provider. Ensure you provide your API key and Search Engine ID (cx). ```typescript import { createGoogleProvider, webSearch } from '@plust/search-sdk'; const googleProvider = createGoogleProvider({ apiKey: 'YOUR_API_KEY', cx: 'YOUR_CX_ID' }); const results = await webSearch({ query: 'artificial intelligence', maxResults: 5, provider: [googleProvider] }); results.forEach(r => console.log(r.title)); ``` -------------------------------- ### Configure MCP Server with asMcp() Source: https://github.com/plustorg/search-sdk/blob/main/README.md Use the `asMcp()` function to convert search providers into an MCP server configuration. This configuration can then be used with MCP clients like Stagehand. ```typescript import { google, brave, asMcp } from '@plust/search-sdk'; // Configure your search providers const googleProvider = google.configure({ apiKey: 'YOUR_GOOGLE_API_KEY', cx: 'YOUR_SEARCH_ENGINE_ID' }); const braveProvider = brave.configure({ apiKey: 'YOUR_BRAVE_API_KEY' }); // Create MCP server configuration const mcpConfig = asMcp([googleProvider, braveProvider]); // Use with an MCP client (e.g., Stagehand) // The mcpConfig object can be passed to connectToMCPServer() or similar console.log(mcpConfig); // { // command: 'node', // args: ['node_modules/@plust/search-sdk/dist/mcp/cli.js'], // env: { // SEARCH_SDK_MCP_CONFIG: '{"providers":[...]}' // } // } ``` -------------------------------- ### Configure and Use SerpAPI Source: https://github.com/plustorg/search-sdk/blob/main/README.md Configure the SerpAPI provider with your API key. The 'engine' parameter is optional and defaults to 'google'. ```typescript import { serpapi, webSearch } from '@plust/search-sdk'; const serpProvider = serpapi.configure({ apiKey: 'YOUR_SERPAPI_KEY', engine: 'google' // Optional, defaults to 'google' }); const results = await webSearch({ query: 'TypeScript best practices', maxResults: 10, provider: [serpProvider] }); ``` -------------------------------- ### Dependency Graph Visualization Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/module-structure.md Illustrates the relationships between different modules and functions within the search SDK. Shows how `webSearch` interacts with various `SearchProvider` implementations and HTTP utilities. ```plaintext webSearch() → providers[] → SearchProvider ├── google ├── brave ├── serpapi ├── exa ├── tavily ├── searxng ├── arxiv ├── duckduckgo └── perplexity └── HTTP utilities (get, post, makeRequest) └── HttpError debug → DebugOptions asMcp() → SearchProvider[] → McpProcessConfig ``` -------------------------------- ### Main SDK Exports Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/module-structure.md Exports the main search function, type definitions, various search provider implementations, and utility functions from the SDK's entry point. Use this to import core functionalities. ```typescript // Main function export async function webSearch(options: WebSearchOptions): Promise // Type definitions export interface SearchResult { ... } export interface SearchOptions { ... } export interface WebSearchOptions { ... } export interface DebugOptions { ... } export interface SearchProvider { ... } export interface ProviderConfig { ... } // Providers (objects with configure methods) export { google, createGoogleProvider, GoogleSearchConfig } export { serpapi, createSerpApiProvider, SerpApiConfig } export { brave, createBraveProvider, BraveSearchConfig } export { exa, createExaProvider, ExaConfig } export { tavily, createTavilyProvider, TavilyConfig } export { searxng, createSearxNGProvider, SearxNGConfig } export { arxiv, createArxivProvider, ArxivConfig } export { duckduckgo, createDuckDuckGoProvider, DuckDuckGoConfig } export { perplexity, createPerplexityProvider, PerplexityConfig } // Utilities export { debug } from './utils/debug' // MCP export { asMcp } from './mcp' ``` -------------------------------- ### Configure SearXNG Provider Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/configuration.md Configure the SearXNG provider with your instance's base URL. An API key is optional if your instance requires authentication. Additional parameters can be provided. ```typescript const searxngProvider = searxng.configure({ baseUrl: string, apiKey?: string, additionalParams?: Record }); ``` ```typescript const searxngProvider = searxng.configure({ baseUrl: 'http://127.0.0.1:8080/search', additionalParams: { categories: 'general', engines: 'google,brave,duckduckgo' } }); ``` -------------------------------- ### SerpAPI Configuration Source: https://github.com/plustorg/search-sdk/blob/main/README.md Configure the SerpAPI provider with your API key. You can optionally specify the search engine. ```APIDOC ## SerpAPI Configuration ### Description Configure the SerpAPI provider with your API key. You can optionally specify the search engine. ### Usage ```typescript import { serpapi, webSearch } from '@plust/search-sdk'; const serpProvider = serpapi.configure({ apiKey: 'YOUR_SERPAPI_KEY', engine: 'google' // Optional, defaults to 'google' }); const results = await webSearch({ query: 'TypeScript best practices', maxResults: 10, provider: [serpProvider] }); ``` ``` -------------------------------- ### Configure Method for SerpAPI Provider Source: https://github.com/plustorg/search-sdk/blob/main/_autodocs/api-reference-serpapi.md Creates and returns a configured SerpAPI provider instance. Accepts API key, engine, and an optional custom base URL. ```typescript serpapi.configure(config: SerpApiConfig): SearchProvider ```