diff --git a/README.md b/README.md index e110b3e..17348dc 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Brave Search MCP Server -An MCP server implementation that integrates the Brave Search API, providing comprehensive search capabilities including web search, local business search, image search, video search, news search, and AI-powered summarization. This project supports both STDIO and HTTP transports, with STDIO as the default mode. +An MCP server implementation that integrates the Brave Search API, providing comprehensive search capabilities including web search, local business search, image search, video search, news search, LLM context, and AI-powered summarization. This project supports both STDIO and HTTP transports, with STDIO as the default mode. [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/brave/brave-search-mcp-server) @@ -98,6 +98,39 @@ Generates AI-powered summaries from web search results using Brave's summarizati **Usage:** First perform a web search with `summary: true`, then use the returned summary key with this tool. +### LLM Context (`brave_llm_context`) +Retrieves pre-extracted web content optimized for AI agents, LLM grounding, and RAG pipelines. + +**Parameters:** +- `query` (string, required): Search query (max 400 chars, 50 words) +- `country` (string, optional): Search country code +- `search_lang` (string, optional): Search language code +- `count` (number, optional): Maximum number of search results considered (1-50) +- `spellcheck` (boolean, optional): Enable spell checking +- `maximum_number_of_urls` (number, optional): Maximum number of URLs to include (1-50) +- `maximum_number_of_tokens` (number, optional): Approximate maximum number of context tokens (1024-32768) +- `maximum_number_of_snippets` (number, optional): Maximum number of snippets to include (1-256) +- `context_threshold_mode` (string, optional): Threshold mode ("disabled", "strict", "lenient", "balanced") +- `maximum_number_of_tokens_per_url` (number, optional): Maximum tokens per URL (512-8192) +- `maximum_number_of_snippets_per_url` (number, optional): Maximum snippets per URL (1-100) +- `goggles` (string or array, optional): Goggle URL or definition for custom re-ranking +- `freshness` (string, optional): Time filter ("pd", "pw", "pm", "py", or date range) +- `enable_local` (boolean, optional): Enable local recall +- `enable_source_metadata` (boolean, optional): Include source metadata enrichment + +**Optional request headers:** +- `x-loc-lat` (number, optional): Client latitude (-90 to 90) +- `x-loc-long` (number, optional): Client longitude (-180 to 180) +- `x-loc-city` (string, optional): Client city name +- `x-loc-state` (string, optional): Client state or region code +- `x-loc-state-name` (string, optional): Client state or region name +- `x-loc-country` (string, optional): Client country code +- `x-loc-postal-code` (string, optional): Client postal code +- `api-version` (string, optional): Brave API version (`YYYY-MM-DD`) +- `accept` (string, optional): Response media type ("application/json" or "*/*") +- `cache-control` (string, optional): Use `no-cache` to request fresh content +- `user-agent` (string, optional): User agent originating the request + ## Configuration ### Getting an API Key diff --git a/src/BraveAPI/index.ts b/src/BraveAPI/index.ts index 3fa6efa..7859715 100644 --- a/src/BraveAPI/index.ts +++ b/src/BraveAPI/index.ts @@ -10,6 +10,7 @@ const typeToPathMap: Record = { videos: '/res/v1/videos/search', web: '/res/v1/web/search', summarizer: '/res/v1/summarizer/search', + llmContext: '/res/v1/llm/context', }; const getDefaultRequestHeaders = (): Record => { @@ -20,7 +21,7 @@ const getDefaultRequestHeaders = (): Record => { }; }; -const isValidGoggleURL = (url: string) => { +const isValidGoggleURL = (url: string): boolean => { try { // Only allow HTTPS URLs return new URL(url).protocol === 'https:'; @@ -29,6 +30,16 @@ const isValidGoggleURL = (url: string) => { } }; +const normalizeGoggle = (value: unknown): string | null => { + if (typeof value !== 'string') return null; + const trimmed = value.trim(); + if (trimmed.length === 0) return null; + if (/^https?:\/\//i.test(trimmed)) { + return isValidGoggleURL(trimmed) ? trimmed : null; + } + return trimmed; +}; + async function issueRequest( endpoint: T, parameters: Endpoints[T]['params'], @@ -80,24 +91,29 @@ async function issueRequest( // Handle `goggles` parameter(s) if (key === 'goggles') { - if (typeof value === 'string') { - queryParams.set(key, value); - } else if (Array.isArray(value)) { - for (const url of value.filter(isValidGoggleURL)) { - queryParams.append(key, url); + const candidates = Array.isArray(value) ? value : [value]; + for (const candidate of candidates) { + const normalized = normalizeGoggle(candidate); + if (normalized !== null) { + queryParams.append(key, normalized); } } continue; } - if (value !== undefined) { + if (value !== undefined && value !== null) { queryParams.set(key === 'query' ? 'q' : key, value.toString()); } } // Issue Request const urlWithParams = url.toString() + '?' + queryParams.toString(); - const headers = { ...getDefaultRequestHeaders(), ...requestHeaders } as Headers; + const headers = new Headers(getDefaultRequestHeaders()); + for (const [key, value] of Object.entries(requestHeaders)) { + if (value === undefined || value === null) continue; + headers.set(key, String(value)); + } + const response = await fetch(urlWithParams, { headers }); // Handle Error diff --git a/src/BraveAPI/types.ts b/src/BraveAPI/types.ts index 81e8153..5bf1cd6 100644 --- a/src/BraveAPI/types.ts +++ b/src/BraveAPI/types.ts @@ -13,6 +13,8 @@ import type { LocalPoiSearchApiResponse, LocalDescriptionsSearchApiResponse, } from '../tools/local/types.js'; +import type { LlmQueryParams, LlmRequestHeaders } from '../tools/llm_context/schemas/input.js'; +import type { LlmContextSearchApiResponse } from '../tools/llm_context/schemas/output.js'; export interface RateLimitErrorResponse { type: 'ErrorResponse'; @@ -69,4 +71,9 @@ export type Endpoints = { response: SummarizerSearchApiResponse; requestHeaders: Headers; }; + llmContext: { + params: LlmQueryParams; + response: LlmContextSearchApiResponse; + requestHeaders: LlmRequestHeaders; + }; }; diff --git a/src/tools/index.ts b/src/tools/index.ts index 3f8f787..fbe7fd2 100644 --- a/src/tools/index.ts +++ b/src/tools/index.ts @@ -4,6 +4,7 @@ import VideoSearchTool from './videos/index.js'; import ImageSearchTool from './images/index.js'; import NewsSearchTool from './news/index.js'; import SummarizerTool from './summarizer/index.js'; +import LlmContextTool from './llm_context/index.js'; export default { WebSearchTool, @@ -12,4 +13,5 @@ export default { ImageSearchTool, NewsSearchTool, SummarizerTool, + LlmContextTool, }; diff --git a/src/tools/llm_context/index.ts b/src/tools/llm_context/index.ts new file mode 100644 index 0000000..84b6875 --- /dev/null +++ b/src/tools/llm_context/index.ts @@ -0,0 +1,70 @@ +import type { TextContent, ToolAnnotations } from '@modelcontextprotocol/sdk/types.js'; +import { z } from 'zod'; +import API from '../../BraveAPI/index.js'; +import { type McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { + RequestParamsSchema, + RequestHeadersSchema, + LlmContextInputSchema, + type LlmContextInput as QueryParams, +} from './schemas/input.js'; +import { LlmContextSearchApiResponseSchema } from './schemas/output.js'; + +export const name = 'brave_llm_context'; + +export const annotations: ToolAnnotations = { + title: 'Brave LLM Context', + openWorldHint: true, +}; + +export const description = ` + Retrieves pre-extracted, relevance-ranked web content using Brave's LLM Context API, optimized for AI agents, LLM grounding, and RAG pipelines. Unlike a traditional web search that returns links and short descriptions, this tool returns the actual substance of matching pages — text chunks, tables, code blocks, and structured data — so the model can reason over it directly. + + When to use: + - Grounding answers in fresh, relevant web content (RAG) + - Giving an AI agent ready-to-use page content from a single search call + - Question answering and fact-checking against current sources + - Gathering source material for research without manually fetching pages + - When you need the contents of pages, not just titles, descriptions, and URLs + + When relaying results in markdown-supporting environments, cite the source URLs from the "sources" map. +`.trim(); + +export const execute = async (params: QueryParams) => { + const parsedParams = RequestParamsSchema.parse(params); + const parsedHeaders = RequestHeadersSchema.parse(params); + + const response = await API.issueRequest<'llmContext'>('llmContext', parsedParams, parsedHeaders); + const { success, data, error } = LlmContextSearchApiResponseSchema.safeParse(response); + const payload = success ? data : z.treeifyError(error); + + return { + content: [{ type: 'text', text: JSON.stringify(payload) } as TextContent], + isError: !success, + structuredContent: payload, + }; +}; + +export const register = (mcpServer: McpServer) => { + mcpServer.registerTool( + name, + { + title: name, + description: description, + inputSchema: LlmContextInputSchema.shape, + outputSchema: LlmContextSearchApiResponseSchema.shape, + annotations: annotations, + }, + execute + ); +}; + +export default { + name, + description, + annotations, + inputSchema: LlmContextInputSchema.shape, + outputSchema: LlmContextSearchApiResponseSchema.shape, + execute, + register, +}; diff --git a/src/tools/llm_context/schemas/input.ts b/src/tools/llm_context/schemas/input.ts new file mode 100644 index 0000000..2dff31a --- /dev/null +++ b/src/tools/llm_context/schemas/input.ts @@ -0,0 +1,284 @@ +import { z } from 'zod'; + +/** + * Keep up-to-date with documentation: + * https://api-dashboard.search.brave.com/api-reference/summarizer/llm_context/get + */ + +const CountryCodesSchema = z.enum([ + 'AR', + 'AU', + 'AT', + 'BE', + 'BR', + 'CA', + 'CL', + 'DK', + 'FI', + 'FR', + 'DE', + 'GR', + 'HK', + 'IN', + 'ID', + 'IT', + 'JP', + 'KR', + 'MY', + 'MX', + 'NL', + 'NZ', + 'NO', + 'CN', + 'PL', + 'PT', + 'PH', + 'RU', + 'SA', + 'ZA', + 'ES', + 'SE', + 'CH', + 'TW', + 'TR', + 'GB', + 'US', + 'ALL', +]); + +const SearchLangCodesSchema = z.enum([ + 'ar', + 'eu', + 'bn', + 'bg', + 'ca', + 'zh-hans', + 'zh-hant', + 'hr', + 'cs', + 'da', + 'nl', + 'en', + 'en-gb', + 'et', + 'fi', + 'fr', + 'gl', + 'de', + 'el', + 'gu', + 'he', + 'hi', + 'hu', + 'is', + 'it', + 'jp', + 'kn', + 'ko', + 'lv', + 'lt', + 'ms', + 'ml', + 'mr', + 'nb', + 'pl', + 'pt-br', + 'pt-pt', + 'pa', + 'ro', + 'ru', + 'sr', + 'sk', + 'sl', + 'es', + 'sv', + 'ta', + 'te', + 'th', + 'tr', + 'uk', + 'vi', +]); + +const FreshnessSchema = z + .union([ + z.enum(['pd', 'pw', 'pm', 'py']), + z + .string() + .regex( + /^\d{4}-\d{2}-\d{2}to\d{4}-\d{2}-\d{2}$/, + "Use 'pd', 'pw', 'pm', 'py', or a custom range as YYYY-MM-DDtoYYYY-MM-DD." + ), + ]) + .describe( + "Filters search results by when they were discovered. The following values are supported: 'pd' - Discovered within the last 24 hours. 'pw' - Discovered within the last 7 days. 'pm' - Discovered within the last 31 days. 'py' - Discovered within the last 365 days. 'YYYY-MM-DDtoYYYY-MM-DD' - Timeframe is also supported by specifying the date range e.g. 2022-04-01to2022-07-30." + ); + +export const RequestParamsSchema = z.object({ + query: z + .string() + .trim() + .min(1) + .max(400) + .refine((str) => str.split(/\s+/).length <= 50, 'Query cannot exceed 50 words') + .describe( + "The user's search query term. Query can not be empty. Maximum of 400 characters and 50 words in the query." + ), + country: CountryCodesSchema.describe( + 'The search query country, where the results come from. The country string is limited to 2 character country codes of supported countries.' + ).optional(), + search_lang: SearchLangCodesSchema.describe( + 'The search language preference. The 2 or more character language code for which the search results are provided.' + ).optional(), + count: z + .number() + .int() + .min(1) + .max(50) + .describe( + 'The maximum number of search results considered to select the LLM context data. The default is 20 and the maximum is 50.' + ) + .optional(), + spellcheck: z.boolean().describe('Whether to enable spellcheck on the query.').optional(), + maximum_number_of_urls: z + .number() + .int() + .min(1) + .max(50) + .describe('Maximum number of different URLs to include in LLM context.') + .optional(), + maximum_number_of_tokens: z + .number() + .int() + .min(1024) + .max(32768) + .describe( + 'Approximate maximum number of tokens to include in context. The default is 8192 and maximum is 32768.' + ) + .optional(), + maximum_number_of_snippets: z + .number() + .int() + .min(1) + .max(256) + .describe( + 'Maximum number of different snippets (or chunks of text) to include in LLM context. The default is 50 and maximum is 256.' + ) + .optional(), + context_threshold_mode: z + .enum(['disabled', 'strict', 'lenient', 'balanced']) + .describe( + 'The mode to use to determine the threshold for including content in context. Default is balanced.' + ) + .optional(), + maximum_number_of_tokens_per_url: z + .number() + .int() + .min(512) + .max(8192) + .describe( + 'Maximum number of tokens to include per URL. The default is 4096 and maximum is 8192.' + ) + .optional(), + maximum_number_of_snippets_per_url: z + .number() + .int() + .min(1) + .max(100) + .describe( + 'Maximum number of snippets to include per URL. The default is 50 and maximum is 100.' + ) + .optional(), + goggles: z + .union([z.string(), z.array(z.string())]) + .describe( + "Goggles act as a custom re-ranking on top of Brave's search index. The parameter supports both a url where the Goggle is hosted or the definition of the Goggle. Multiple goggle URLs and/or definitions can be provided in an array. For more details, refer to the Goggles repository (i.e., https://github.com/brave/goggles-quickstart)." + ) + .optional(), + freshness: FreshnessSchema.optional(), + enable_local: z + .boolean() + .describe( + 'Whether to enable local recall. Not setting this value means auto-detect and uses local recall if any of the localization headers are provided.' + ) + .optional(), + enable_source_metadata: z + .boolean() + .describe( + 'Enable source metadata enrichment (site_name, favicon) in the sources attribute of the response.' + ) + .optional(), +}); + +export const RequestHeadersSchema = z.object({ + 'x-loc-lat': z + .number() + .min(-90) + .max(90) + .describe( + "The latitude of the client's geographical location in degrees, to provide relevant local results. The latitude must be greater than or equal to -90.0 degrees and less than or equal to +90.0 degrees." + ) + .optional(), + 'x-loc-long': z + .number() + .min(-180) + .max(180) + .describe( + "The longitude of the client's geographical location in degrees, to provide relevant local results. The longitude must be greater than or equal to -180.0 and less than or equal to +180.0 degrees." + ) + .optional(), + 'x-loc-city': z.string().describe('The generic name of the client city').optional(), + 'x-loc-state': z + .string() + .max(3) + .describe( + "A code which could be up to three characters, that represent the client's state/region. The region is the first-level subdivision (the broadest or least specific) of the ISO 3166-2 code." + ) + .optional(), + 'x-loc-state-name': z + .string() + .describe( + 'The name of the client’s state/region. The region is the first-level subdivision (the broadest or least specific) of the ISO 3166-2 code.' + ) + .optional(), + 'x-loc-country': z + .string() + .length(2) + .describe( + 'The two letter country code for the client’s country. For a list of country codes, see ISO 3166-1 alpha-2' + ) + .optional(), + 'x-loc-postal-code': z.string().describe('The client’s postal code').optional(), + 'api-version': z + .string() + .regex(/^\d{4}-\d{2}-\d{2}$/) + .describe( + 'The API version to use. This is denoted by the format YYYY-MM-DD. Default is the latest that is available. Read more about API versioning at https://api-dashboard.search.brave.com/documentation/guides/versioning.' + ) + .optional(), + accept: z + .enum(['application/json', '*/*']) + .describe('The default supported media type is application/json.') + .optional(), + 'cache-control': z + .literal('no-cache') + .describe( + 'Brave Search will return cached content by default. To prevent caching set the Cache-Control header to no-cache. This is currently done as best effort.' + ) + .optional(), + 'user-agent': z + .string() + .describe( + 'The user agent originating the request. Brave search can utilize the user agent to provide a different experience depending on the device as described by the string. The user agent should follow the commonly used browser agent strings on each platform. For more information on curating user agents, see RFC 9110.' + ) + .optional(), +}); + +export const LlmContextInputSchema = z.object({ + ...RequestParamsSchema.shape, + ...RequestHeadersSchema.shape, +}); + +export type LlmContextInput = z.input; +export type LlmQueryParams = z.infer; +export type LlmRequestHeaders = z.infer; diff --git a/src/tools/llm_context/schemas/output.ts b/src/tools/llm_context/schemas/output.ts new file mode 100644 index 0000000..56c8ccb --- /dev/null +++ b/src/tools/llm_context/schemas/output.ts @@ -0,0 +1,84 @@ +import { z } from 'zod'; + +/** + * Keep up to date with documentation: + * https://api-dashboard.search.brave.com/api-reference/summarizer/llm_context/get#responses + */ + +const SnippetsSchema = z + .array(z.string()) + .describe( + `Extracted content chunks. Entries can mix plain prose, markdown-formatted text, and JSON-encoded structured data (e.g., extracted tables, schemas, or page metadata serialized as a string), so consumers should be prepared to detect and parse JSON strings rather than assuming every entry is plain text.` + ); + +const SourceMetadataSchema = z + .object({ + title: z.string().optional().describe('The page title for the referenced URL.'), + hostname: z.string().optional().describe('The hostname extracted from the referenced URL.'), + age: z + .array(z.string()) + .optional() + .describe( + 'Discovery/age information for the source, typically formatted as human-readable, ISO date, and relative-age strings. May be an empty array when unavailable.' + ), + site_name: z + .string() + .optional() + .describe('Site name for the source (present when enable_source_metadata is true).'), + favicon: z + .string() + .optional() + .describe('Favicon URL for the source (present when enable_source_metadata is true).'), + thumbnail: z + .object({ + src: z.string().optional().describe('Cached/proxied thumbnail URL served by Brave.'), + original: z.string().optional().describe('Original thumbnail URL on the source site.'), + }) + .loose() + .optional() + .describe('Thumbnail image references (present when enable_source_metadata is true).'), + }) + .loose(); + +export const LlmContextSearchApiResponseSchema = z.object({ + grounding: z.object({ + generic: z + .array( + z.object({ + url: z.url(), + title: z.string(), + snippets: SnippetsSchema, + }) + ) + .describe(`Array of LLM context items with extracted web content.`), + poi: z + .object({ + name: z.string(), + url: z.url(), + title: z.string(), + snippets: SnippetsSchema, + }) + .nullable() + .optional() + .describe(`A point of interest item returned for local recall queries.`), + map: z + .array( + z.object({ + name: z.string(), + url: z.union([z.url(), z.literal('')]), + title: z.string(), + snippets: SnippetsSchema, + }) + ) + .describe( + `Map/place results. When enable_local is enabled, the response may include map data.` + ), + }), + sources: z + .record(z.url(), SourceMetadataSchema) + .describe( + `Metadata for each referenced URL, keyed by URL. Known fields include title, hostname, and age; site_name, favicon, and thumbnail are present when enable_source_metadata is true. Unknown fields are preserved as-is.` + ), +}); + +export type LlmContextSearchApiResponse = z.infer; diff --git a/src/tools/local/index.ts b/src/tools/local/index.ts index ee81f2b..97bbcc0 100644 --- a/src/tools/local/index.ts +++ b/src/tools/local/index.ts @@ -28,7 +28,7 @@ export const description = ` - Phone numbers and opening hours Use this when the query implies 'near me', 'in my area', or mentions specific locations (e.g., 'in San Francisco'). This tool automatically falls back to brave_web_search if no local results are found. -`; +`.trim(); // Access to Local API is available through the Pro plans. export const execute = async (params: WebQueryParams) => { diff --git a/src/tools/news/index.ts b/src/tools/news/index.ts index 73aa793..1d1a2fe 100644 --- a/src/tools/news/index.ts +++ b/src/tools/news/index.ts @@ -28,7 +28,7 @@ export const description = ` - "According to [Reuters](https://www.reuters.com/technology/china-bans/), China bans uncertified and recalled power banks on planes". - "The [New York Times](https://www.nytimes.com/2025/06/27/us/technology/ev-sales.html) reports that Tesla's EV sales have increased by 20%". - "According to [BBC News](https://www.bbc.com/news/world-europe-65910000), the UK government has announced a new policy to support renewable energy". -`; +`.trim(); export const execute = async (params: QueryParams) => { const response = await API.issueRequest<'news'>('news', params); diff --git a/src/tools/news/params.ts b/src/tools/news/params.ts index c2168f2..c85666d 100644 --- a/src/tools/news/params.ts +++ b/src/tools/news/params.ts @@ -75,9 +75,9 @@ export const params = z.object({ ) .optional(), goggles: z - .array(z.string()) + .union([z.string(), z.array(z.string())]) .describe( - "Goggles act as a custom re-ranking on top of Brave's search index. The parameter supports both a url where the Goggle is hosted or the definition of the Goggle. For more details, refer to the Goggles repository (i.e., https://github.com/brave/goggles-quickstart)." + "Goggles act as a custom re-ranking on top of Brave's search index. The parameter supports both a url where the Goggle is hosted or the definition of the Goggle. Multiple goggle URLs and/or definitions can be provided in an array. For more details, refer to the Goggles repository (i.e., https://github.com/brave/goggles-quickstart)." ) .optional(), }); diff --git a/src/tools/summarizer/index.ts b/src/tools/summarizer/index.ts index 412dd56..5c9f9b5 100644 --- a/src/tools/summarizer/index.ts +++ b/src/tools/summarizer/index.ts @@ -24,7 +24,7 @@ export const description = ` Returns a text summary that consolidates information from the search results. Optional features include inline references to source URLs and additional entity information. Requirements: Must first perform a web search using brave_web_search with summary=true parameter. Requires a Pro AI subscription to access the summarizer functionality. -`; +`.trim(); export const execute = async (params: SummarizerQueryParams) => { const response: CallToolResult = { content: [], isError: false }; diff --git a/src/tools/videos/index.ts b/src/tools/videos/index.ts index b356dba..019f615 100644 --- a/src/tools/videos/index.ts +++ b/src/tools/videos/index.ts @@ -19,7 +19,7 @@ export const description = ` - Useful for discovering video content, getting video metadata, or finding videos from specific creators/publishers. Returns a JSON list of video-related results with title, url, description, duration, and thumbnail_url. -`; +`.trim(); export const execute = async (params: QueryParams) => { const response = await API.issueRequest<'videos'>('videos', params); diff --git a/src/tools/web/index.ts b/src/tools/web/index.ts index c2b6aaa..f214112 100644 --- a/src/tools/web/index.ts +++ b/src/tools/web/index.ts @@ -36,7 +36,7 @@ export const description = ` Returns a JSON list of web results with title, description, and URL. When the "results_filter" parameter is empty, JSON results may also contain FAQ, Discussions, News, and Video results. -`; +`.trim(); export const execute = async (params: QueryParams) => { const response = { content: [] as TextContent[], isError: false }; diff --git a/src/tools/web/params.ts b/src/tools/web/params.ts index e474961..cd2df89 100644 --- a/src/tools/web/params.ts +++ b/src/tools/web/params.ts @@ -223,9 +223,9 @@ export const params = z.object({ .describe("Result filter (default ['web', 'query'])") .optional(), goggles: z - .array(z.string()) + .union([z.string(), z.array(z.string())]) .describe( - "Goggles act as a custom re-ranking on top of Brave's search index. The parameter supports both a url where the Goggle is hosted or the definition of the Goggle. For more details, refer to the Goggles repository (i.e., https://github.com/brave/goggles-quickstart)." + "Goggles act as a custom re-ranking on top of Brave's search index. The parameter supports both a url where the Goggle is hosted or the definition of the Goggle. Multiple goggle URLs and/or definitions can be provided in an array. For more details, refer to the Goggles repository (i.e., https://github.com/brave/goggles-quickstart)." ) .optional(), units: z