AIStoreHub Package Vault: Brave Web Search MCP
Package Slug: brave-search-mcp
Archetype: mcp_server
Upstream Repository: https://github.com/brave/brave-search-mcp-server
Workspace Files & Specifications (67 files)
- aistorehub.json (525 bytes)
{ "name": "Brave Web Search MCP", "slug": "brave-search-mcp", "version": "1.0.0", "type": "mcp_server", "description": "Official Brave Search Model Context Protocol server enabling AI assistants to perform web, local, and news searches with privacy preservation.", "owner": "community", "repository": "catalog", "github_repo_url": "https://github.com/brave/brave-search-mcp-server", "tags": [ "brave", "mcp", "search", "web", "research" ], "imported_at": "2026-11-22T00:08:39.077Z" } - docker-compose.secrets.example.yml (531 bytes)
# Optional Compose override for Docker secrets. # # Usage: # 1. cp secrets/brave_api_key.txt.example secrets/brave_api_key.txt # 2. Add your API key to secrets/brave_api_key.txt # 3. docker compose -f docker-compose.yml -f docker-compose.secrets.example.yml up --build # # See https://docs.docker.com/compose/how-tos/use-secrets/ services: mcp-server: environment: BRAVE_API_KEY_FILE: /run/secrets/brave_api_key secrets: - brave_api_key secrets: brave_api_key: file: ./secrets/brave_api_key.txt - docker-compose.yml (515 bytes)
services: mcp-server: build: . cap_drop: - all deploy: restart_policy: condition: any delay: 5s environment: - BRAVE_API_KEY - BRAVE_API_KEY_FILE - BRAVE_MCP_TRANSPORT=http - BRAVE_MCP_PORT=8080 - BRAVE_MCP_STATELESS - BRAVE_MCP_HOST=0.0.0.0 - BRAVE_MCP_LOG_LEVEL=info - BRAVE_MCP_ENABLED_TOOLS - BRAVE_MCP_DISABLED_TOOLS init: true ports: - 8080:8080 security_opt: - no-new-privileges:true - Dockerfile (1054 bytes)
FROM node:alpine@sha256:5209bcaca9836eb3448b650396213dbe9d9a34d31840c2ae1f206cb2986a8543 AS builder RUN apk add --no-cache openssl=3.5.9-r0 WORKDIR /app COPY ./package.json ./package.json COPY ./package-lock.json ./package-lock.json RUN npm ci --ignore-scripts COPY ./scripts ./scripts COPY ./src ./src COPY ./tsconfig.json ./tsconfig.json RUN npm run build FROM node:alpine@sha256:5209bcaca9836eb3448b650396213dbe9d9a34d31840c2ae1f206cb2986a8543 AS release RUN apk add --no-cache openssl=3.5.9-r0 WORKDIR /app COPY --from=builder /app/dist /app/dist COPY --from=builder /app/package.json /app/package.json COPY --from=builder /app/package-lock.json /app/package-lock.json ENV NODE_ENV=production # The server defaults to binding 127.0.0.1 for safe local execution. Inside a # container the port must be reachable through the published mapping, so bind to # all interfaces here. Deployments can still override BRAVE_MCP_HOST. ENV BRAVE_MCP_HOST=0.0.0.0 RUN npm ci --ignore-scripts --omit=dev USER node ENTRYPOINT ["node", "dist/index.js"]
- glama.json (122 bytes)
{ "$schema": "https://glama.ai/mcp/schemas/server.json", "maintainers": [ "jonathansampson" ] } - INSTRUCTIONS.md (239 bytes)
Configure in Claude Desktop or Cursor: ```json { "mcpServers": { "brave-search": { "command": "npx", "args": ["-y", "@brave/brave-search-mcp-server"], "env": { "BRAVE_API_KEY": "YOUR_BRAVE_API_KEY" } } } } ``` - LICENSE (1110 bytes)
MIT License Copyright (c) 2024 Anthropic, PBC Copyright (c) 2025 Brave Software, Inc Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- marketplace-revision-release.json (10295 bytes)
{ "Catalog": "AWSMarketplace", "ChangeSet": [ { "ChangeType": "AddDeliveryOptions", "Entity": { "Type": "[email protected]", "Identifier": "prod-ixigokshzjrpw" }, "DetailsDocument": { "Version": { "ReleaseNotes": "", "VersionTitle": "" }, "DeliveryOptions": [ { "DeliveryOptionTitle": "Brave Search MCP Server", "Details": { "EcrDeliveryOptionDetails": { "UsageInstructions": "The Brave Search MCP Server provides a powerful REST API proxy to access Brave Search capabilities through a standardized interface. This container allows you to integrate Brave's comprehensive search services into your AI applications, with features ranging from web search to image search and summarization.\n\n\n\n## Key Features\n- Brave LLM Context API delivers pre-extracted, relevance-scored web content optimized for grounding LLM responses in real-time search results.\n- Web search with comprehensive results and metadata\n- Local business and location search\n- Image and video search capabilities\n- News search for current events and trending stories\n- AI-optimized results with extra snippets\n- Content summarization across search results\n\n\n\n## Usage and limits\n- Cost: $5 CPM (cost per thousand) / $0.005 per request\n- Rate: Maximum of 50 requests per second\n- Volume: Unlimited requests\n\n\n\n## Getting started\n\n### Prerequisites\n1. **Brave Search API Key**: Create an AWS Marketplace Subscription for [Brave Search API](https://aws.amazon.com/marketplace/pp/prodview-qjlabherxghtq) \n2. **Container Configuration**: Configure your MCP Server with the required environment variables \n\n#### Container Configuration\n\n##### Environment Variables\n\nProvide the Brave Search API key using either `BRAVE_API_KEY` or `BRAVE_API_KEY_FILE`. When `BRAVE_API_KEY_FILE` is set, it must point to a path inside the container (for example a mounted secret at `/run/secrets/brave_api_key`) and takes precedence over `BRAVE_API_KEY`.\n\n```json\n\"environmentVariables\": { \"BRAVE_API_KEY\": \"<YOUR_BRAVE_API_KEY>\", \"BRAVE_MCP_TRANSPORT\": \"http\", \"BRAVE_MCP_STATELESS\": \"true\", \"BRAVE_MCP_PORT\": \"8000\", \"BRAVE_MCP_HOST\": \"0.0.0.0\" }\n```\n\nExample using a mounted secret file instead of an inline API key:\n\n```json\n\"environmentVariables\": { \"BRAVE_API_KEY_FILE\": \"/run/secrets/brave_api_key\", \"BRAVE_MCP_TRANSPORT\": \"http\", \"BRAVE_MCP_STATELESS\": \"true\", \"BRAVE_MCP_PORT\": \"8000\", \"BRAVE_MCP_HOST\": \"0.0.0.0\" }\n```\n\n##### Network Configuration \n```json\n\"networkConfiguration\": { \"networkMode\": \"PUBLIC\" }\n```\n\n##### Protocol Configuration\n```json\n\"protocolConfiguration\": { \"serverProtocol\": \"MCP\" }\n```\n\n\n\n## Example\n\n### [`brave_web_search`](https://api.search.brave.com/res/v1/web/search)\n\nPerforms general web searches with rich metadata. Best for general information queries, research, and finding diverse content types.\n\n#### Example\n\n```json\n{\n \"query\": \"climate change solutions\",\n \"count\": 10,\n \"extra_snippets\": true\n}\n```\n\n\n\n\nReference documentation for additional endpoints:\n\n- [`brave_local_search`](https://api-dashboard.search.brave.com/documentation/services/place-search)\n- [`brave_image_search`](https://api-dashboard.search.brave.com/documentation/services/image-search)\n- [`brave_video_search`](https://api-dashboard.search.brave.com/documentation/services/video-search)\n- [`brave_news_search`](https://api-dashboard.search.brave.com/documentation/services/news-search)\n- [`brave_summarizer`](https://api-dashboard.search.brave.com/documentation/services/summarizer)\n\n\n\n## Best Practices\n1. Use specific queries to get more relevant results\n2. Leverage `extra_snippets` for AI applications that need more context\n3. Use appropriate `result_filter` values to focus on specific content types\n4. Consider `safesearch` settings based on your application's audience\n5. Utilize the summarizer for efficient information extraction\n\n## Support\nFor detailed API documentation, visit the [Brave Search API Documentation](https://api-dashboard.search.brave.com/app/documentation/web-search/get-started). For all general inquiries and support, please contact us at [email protected].", "AgenticType": [ "MCP_SERVER" ], "CompatibleServices": [ "Bedrock-AgentCore" ], "Description": "", "DeploymentResources": [ { "Url": "https://brave-marketplace-artifacts-prod.s3.us-west-2.amazonaws.com/brave-search-mcp-server/MCP_Server_Usage_Instructions_md.md", "Name": "Brave Search MCP Usage Instructions" } ], "ContainerImages": "", "EnvironmentVariables": [ { "Name": "BRAVE_API_KEY", "Description": "*Required unless BRAVE_API_KEY_FILE is set* Brave Search API Key. Obtain Brave Search API Key through AWS Marketplace Product (https://aws.amazon.com/marketplace/pp/prodview-qjlabherxghtq)" }, { "Name": "BRAVE_API_KEY_FILE", "Description": "*Optional* Path inside the container to a file containing the Brave Search API Key. When set, takes precedence over BRAVE_API_KEY. Use with mounted secrets (for example ECS task secrets or Kubernetes secret volumes)." }, { "DefaultValue": "http", "Name": "BRAVE_MCP_TRANSPORT", "Description": "MCP protocol transport mode. Supported values are \"http\" or \"stdio\", however Bedrock Agentcore only supports \"http\" (reference https://docs.aws.amazon.com/marketplace/latest/userguide/bedrock-agentcore-runtime.html#agentcore-container-requirements)." }, { "DefaultValue": "8000", "Name": "BRAVE_MCP_PORT", "Description": "HTTP server port (default: 8000). Mandatory port for Bedrock Agentcore is 8000 (reference https://docs.aws.amazon.com/marketplace/latest/userguide/bedrock-agentcore-runtime.html#agentcore-container-requirements)." }, { "DefaultValue": "0.0.0.0", "Name": "BRAVE_MCP_HOST", "Description": "HTTP server host (default: 0.0.0.0). Mandatory host value is 0.0.0.0 for Bedrock Agentcore (reference https://docs.aws.amazon.com/marketplace/latest/userguide/bedrock-agentcore-runtime.html#agentcore-container-requirements)." }, { "DefaultValue": "info", "Name": "BRAVE_MCP_LOG_LEVEL", "Description": "MCP supported logging level (reference https://modelcontextprotocol.io/specification/2025-03-26/server/utilities/logging#log-levels)" }, { "Name": "BRAVE_MCP_ENABLED_TOOLS", "Description": "*Optional* When used, specifies a whitelist for supported tools" }, { "Name": "BRAVE_MCP_DISABLED_TOOLS", "Description": "*Optional* When used, specifies a blacklist for supported tools" }, { "DefaultValue": "true", "Name": "BRAVE_MCP_STATELESS", "Description": "Sets HTTP Stateless mode (default: true). When deploying on Bedrock Agentcore, this should be set to true." } ] } } }, { "DeliveryOptionTitle": "Docker Image", "Details": { "EcrDeliveryOptionDetails": { "UsageInstructions": "", "CompatibleServices": [ "ECS", "ECS-Anywhere", "EKS", "EKS-Anywhere" ], "Description": "", "DeploymentResources": [], "ContainerImages": "" } } } ] } } ], "ChangeSetName": "", "ClientRequestToken": "", "ChangeSetTags": [ { "Key": "Release", "Value": "" }, { "Key": "CostEntity", "Value": "SEZC" }, { "Key": "IPGroup", "Value": "KY BAT Ledger Service" } ] } - package.json (1838 bytes)
{ "name": "@brave/brave-search-mcp-server", "mcpName": "io.github.brave/brave-search-mcp-server", "version": "2.2.0", "description": "Brave Search MCP Server: web results, images, videos, rich results, AI summaries, and more.", "keywords": [ "api", "brave", "mcp", "search" ], "license": "MIT", "author": "Brave Software, Inc. (https://brave.com)", "homepage": "https://github.com/brave/brave-search-mcp-server", "bugs": "https://github.com/brave/brave-search-mcp-server/issues", "repository": { "type": "git", "url": "git+https://github.com/brave/brave-search-mcp-server.git" }, "type": "module", "module": "dist/server.js", "bin": { "brave-search-mcp-server": "dist/index.js" }, "files": [ "dist" ], "scripts": { "build": "node scripts/build.js", "prepare": "npm run format && npm run build", "watch": "tsc --watch", "format": "prettier --write \"src/**/*.ts\"", "format:check": "prettier --check \"src/**/*.ts\"", "test": "node --import tsx --test \"src/**/*.test.ts\"", "test:docker": "docker build -t brave-search-mcp-server:test . && node --import tsx --test src/docker.e2e.ts", "serve:http": "npm run build && node dist/index.js --transport http", "inspector": "npx @modelcontextprotocol/inspector", "inspector:http": "npx @modelcontextprotocol/inspector --transport http --server-url http://127.0.0.1:8080/mcp" }, "dependencies": { "@modelcontextprotocol/sdk": "1.32.2", "commander": "14.0.3", "dotenv": "17.3.1", "eventsource-parser": "3.1.1", "express": "5.2.1", "zod": "4.6.7" }, "devDependencies": { "@types/express": "5.0.6", "@types/node": "24.10.13", "ajv": "8.20.0", "prettier": "3.8.1", "semver": "7.7.3", "tsx": "4.22.4", "typescript": "5.9.3" } } - README.md (26251 bytes)
# Brave Search MCP Server An MCP server implementation that integrates the Brave Search API, providing comprehensive search capabilities including web search, local business search, place search, image search, video search, news search, LLM context, grounded Answers, and legacy AI summarization. This project supports both STDIO and HTTP transports, with STDIO as the default mode. [](https://deepwiki.com/brave/brave-search-mcp-server) ## Migration ### 1.x to 2.x #### Default transport now STDIO To follow established MCP conventions, the server now defaults to STDIO. If you would like to continue using HTTP, you will need to set the `BRAVE_MCP_TRANSPORT` environment variable to `http`, or provide the runtime argument `--transport http` when launching the server. #### Response structure of `brave_image_search` Version 1.x of the MCP server would return base64-encoded image data along with image URLs. This dramatically slowed down the response, as well as consumed unnecessarily context in the session. Version 2.x removes the base64-encoded data, and returns a response object that more closely reflects the original Brave Search API response. The updated output schema is defined in [`src/tools/images/schemas/output.ts`](https://github.com/brave/brave-search-mcp-server/blob/main/src/tools/images/schemas/output.ts). ### Summarizer to Answers `brave_summarizer` is **deprecated**. It remains available for existing Pro AI subscribers, but new integrations should use [`brave_answers`](#answers-brave_answers) instead. **Why migrate to Answers:** - Single request — no `brave_web_search` + summary key + `brave_summarizer` polling workflow - Optional inline citations (`enable_citations`) and multi-search research mode (`enable_research`) - Returns a finished, web-grounded answer rather than raw search results to summarize **Before (2 calls):** 1. `brave_web_search({ query: "...", summary: true })` — extract the summarizer key from the response 2. `brave_summarizer({ key: "..." })` **After (1 call):** ```json { "query": "...", "enable_citations": true } ``` **Parameter mapping:** | Summarizer | Answers | |---|---| | `inline_references: true` | `enable_citations: true` | **Subscription note:** Summarizer requires a **Pro AI** plan. Answers requires an [**Answers plan**](https://api-dashboard.search.brave.com/app/subscriptions/subscribe). ## Tools ### Web Search (`brave_web_search`) Performs comprehensive web searches with rich result types and advanced filtering options. **Parameters:** - `query` (string, required): Search terms (max 400 chars, 50 words) - `country` (string, optional): Country code (default: "US") - `search_lang` (string, optional): Search language (default: "en") - `ui_lang` (string, optional): UI language (default: "en-US") - `count` (number, optional): Results per page (1-20, default: 10) - `offset` (number, optional): Pagination offset (max 9, default: 0) - `safesearch` (string, optional): Content filtering ("off", "moderate", "strict", default: "moderate") - `freshness` (string, optional): Time filter ("pd", "pw", "pm", "py", or date range) - `text_decorations` (boolean, optional): Include highlighting markers (default: true) - `spellcheck` (boolean, optional): Enable spell checking (default: true) - `result_filter` (array, optional): Filter result types (default: ["web", "query"]) - `goggles` (array, optional): Custom re-ranking definitions - `units` (string, optional): Measurement units ("metric" or "imperial") - `extra_snippets` (boolean, optional): Get additional excerpts (Pro plans only) - `summary` (boolean, optional): Enable summary key generation for the deprecated `brave_summarizer` workflow; prefer `brave_answers` for new integrations ### Local Search (`brave_local_search`) Searches for local businesses and places with detailed information including ratings, hours, and AI-generated descriptions. **Parameters:** - Same as `brave_web_search` with automatic location filtering - Automatically includes "web" and "locations" in result_filter **Note:** Requires Pro plan for full local search capabilities. Falls back to web search otherwise. ### Video Search (`brave_video_search`) Searches for videos with comprehensive metadata and thumbnail information. **Parameters:** - `query` (string, required): Search terms (max 400 chars, 50 words) - `country` (string, optional): Country code (default: "US") - `search_lang` (string, optional): Search language (default: "en") - `ui_lang` (string, optional): UI language (default: "en-US") - `count` (number, optional): Results per page (1-50, default: 20) - `offset` (number, optional): Pagination offset (max 9, default: 0) - `spellcheck` (boolean, optional): Enable spell checking (default: true) - `safesearch` (string, optional): Content filtering ("off", "moderate", "strict", default: "moderate") - `freshness` (string, optional): Time filter ("pd", "pw", "pm", "py", or date range) ### Image Search (`brave_image_search`) Searches for images with metadata including URLs, dimensions, and confidence scores. **Parameters:** - `query` (string, required): Search terms (max 400 chars, 50 words) - `country` (string, optional): Country code (default: "US") - `search_lang` (string, optional): Search language (default: "en") - `count` (number, optional): Results per page (1-200, default: 50) - `safesearch` (string, optional): Content filtering ("off", "strict", default: "strict") - `spellcheck` (boolean, optional): Enable spell checking (default: true) ### News Search (`brave_news_search`) Searches for current news articles with freshness controls and breaking news indicators. **Parameters:** - `query` (string, required): Search terms (max 400 chars, 50 words) - `country` (string, optional): Country code (default: "US") - `search_lang` (string, optional): Search language (default: "en") - `ui_lang` (string, optional): UI language (default: "en-US") - `count` (number, optional): Results per page (1-50, default: 20) - `offset` (number, optional): Pagination offset (max 9, default: 0) - `spellcheck` (boolean, optional): Enable spell checking (default: true) - `safesearch` (string, optional): Content filtering ("off", "moderate", "strict", default: "moderate") - `freshness` (string, optional): Time filter (default: "pd" for last 24 hours) - `extra_snippets` (boolean, optional): Get additional excerpts (Pro plans only) - `goggles` (array, optional): Custom re-ranking definitions ### Answers (`brave_answers`) Generates AI-grounded answers backed by real-time Brave Search using the [Answers API](https://api-dashboard.search.brave.com/api-reference/ai/answers) (`POST /res/v1/chat/completions`). Returns a finished answer as markdown rather than raw search results. **Preferred replacement for the deprecated `brave_summarizer` tool** — see [Summarizer to Answers](#summarizer-to-answers). **Parameters:** See the [Answers API reference](https://api-dashboard.search.brave.com/api-reference/ai/answers). Key fields include: - `query` (string, required): The question to answer. Sent to the API as the single user message - `model` (string, optional): Answers model (`brave` or `brave-pro`; omit to use the API default) - `country` (string, optional): Search country (2-letter code or `ALL`) - `language` (string, optional): Response language code (e.g. `en`) - `safesearch` (string, optional): `off`, `moderate`, or `strict` - `max_completion_tokens` (integer, optional): Upper bound on completion tokens. An answer cut off at this limit ends with a note saying so - `enable_citations` (boolean, optional): Inline citations, returned as markdown footnotes (not supported in research mode) - `enable_entities` (boolean, optional): Requests inline entity tags (not supported in research mode). The API has not been observed to return any, so this may have no effect - `enable_research` (boolean, optional): Multi-search research mode - `web_search_options` (object, optional): OpenAI-compatible options such as `search_context_size` (`low`, `medium`, `high`) and `user_location` **Research tuning** (when `enable_research=true`): - `research_maximum_number_of_tokens_per_query` (integer, optional, range: 1024-16384) - `research_maximum_number_of_queries` (integer, optional, range: 1-50) - `research_maximum_number_of_iterations` (integer, optional, range: 1-5) - `research_maximum_number_of_seconds` (integer, optional, range: 1-300) - `research_maximum_number_of_results_per_query` (integer, optional, range: 1-60) **Notes:** - Requires an Answers plan subscription. - The tool always requests a streamed (Server-Sent Events) response and returns the completed answer once the stream signals it is done. A stream that ends early or sends an error event is reported as an error. Unsupported option combinations are reported by the API as errors. - Research can take minutes. The tool sends MCP progress notifications while it waits, but clients that cap total request time (for example around 60 seconds) may need a lower `research_maximum_number_of_seconds`. ### Summarizer Search (`brave_summarizer`) — Deprecated > **Deprecated:** Prefer [`brave_answers`](#answers-brave_answers) for new integrations. See [Summarizer to Answers](#summarizer-to-answers). This tool remains available for existing Pro AI subscribers. Generates AI-powered summaries from web search results using Brave's summarization API. **Parameters:** - `key` (string, required): Summary key from web search results (use `summary: true` in web search) - `entity_info` (boolean, optional): Include entity information (default: false) - `inline_references` (boolean, optional): Add source references, rendered as markdown footnotes (default: false) **Usage:** First perform a web search with `summary: true`, then use the returned summary key with this tool. ### Place Search (`brave_place_search`) Searches for points of interest (POIs) in a specified geographic area using Brave's Place Search API. Returns rich, structured place data including name, address, opening hours, contact info, ratings, photos, categories, and timezone. **Parameters:** - `query` (string, optional): Query string used to refine the POI search (max 400 chars, 50 words). When omitted, returns general points of interest in the supplied area. - `latitude` (number, optional): Latitude of the search center (-90 to 90). Typically paired with `longitude`. - `longitude` (number, optional): Longitude of the search center (-180 to 180). Typically paired with `latitude`. - `location` (string, optional): Location string used as an alternative to `latitude`/`longitude`. For US locations prefer the form `<city> <state> <country name>` (e.g., `san francisco ca united states`); for non-US locations use `<city> <country name>` (e.g., `tokyo japan`). - `radius` (number, optional): Search radius around the supplied coordinates, in meters. If omitted, the search is performed globally. - `count` (number, optional): Number of results to return (1-50, default 20). - `country` (string, optional): Two-letter country code (default `US`). - `search_lang` (string, optional): Search language (default `en`). - `ui_lang` (string, optional): UI language (default `en-US`). - `units` (string, optional): Distance units (`metric` or `imperial`, default `metric`). - `safesearch` (string, optional): Safe search level (`off`, `moderate`, `strict`, default `strict`). - `spellcheck` (boolean, optional): Whether to spellcheck the query (default `true`). - `geoloc` (string, optional): Optional geolocation token used to refine results. **Optional request headers:** - `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 ### 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 1. Sign up for a [Brave Search API account](https://brave.com/search/api/) 2. Choose a plan: - **Search**: The real-time search data your chatbots & agents need to generate answers. Complete search results (URLs, text, news, images, and more), with additional LLM context optimized for AI. - **Answers**: Summarized, completed answers to any question. Answers grounded on a single search or multiple searches for better accuracy & reduced hallucinations. 3. Generate your API key from the [developer dashboard](https://api-dashboard.search.brave.com/app/keys) ### Environment Variables The server supports the following environment variables: - `BRAVE_API_KEY`: Your Brave Search API key (required unless `BRAVE_API_KEY_FILE` is set) - `BRAVE_API_KEY_FILE`: Path to a file containing your Brave Search API key. When set, this takes precedence over `BRAVE_API_KEY`. Useful for Docke - server.json (882 bytes)
{ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json", "name": "io.github.brave/brave-search-mcp-server", "description": "Brave Search MCP Server: web results, images, videos, rich results, AI summaries, and more.", "version": "2.2.0", "repository": { "url": "https://github.com/brave/brave-search-mcp-server", "source": "github" }, "packages": [ { "registryType": "npm", "registryBaseUrl": "https://registry.npmjs.org", "identifier": "@brave/brave-search-mcp-server", "version": "2.2.0", "transport": { "type": "stdio" }, "environmentVariables": [ { "name": "BRAVE_API_KEY", "description": "Your API key for the service", "format": "string", "isRequired": true, "isSecret": true } ] } ] } - src/BraveAPI/chatCompletions.test.ts (4337 bytes)
import assert from 'node:assert/strict'; import { createServer, type IncomingHttpHeaders, type Server } from 'node:http'; import type { AddressInfo } from 'node:net'; import { after, before, describe, it } from 'node:test'; import { streamChatCompletion, type StreamChatCompletionOptions } from './chatCompletions.js'; const chunk = (content: string) => `data: ${JSON.stringify({ choices: [{ delta: { content } }] })}\n\n`; type ReceivedRequest = { method?: string; url?: string; headers: IncomingHttpHeaders; body: Record<string, unknown>; }; /** Requests a completion whose `scenario` tells the local server how to respond. */ const stream = (scenario: string, options: StreamChatCompletionOptions = { timeoutMs: 5_000 }) => streamChatCompletion({ scenario }, options); describe('streamChatCompletion', () => { const received: ReceivedRequest[] = []; let server: Server; let restoreFetch: () => void; before(async () => { server = createServer(async (request, response) => { let text = ''; for await (const part of request) text += part; const body = JSON.parse(text) as Record<string, unknown>; received.push({ method: request.method, url: request.url, headers: request.headers, body }); if (body.scenario === 'error') { response.writeHead(422, 'Unprocessable Entity', { 'content-type': 'application/json' }); response.end(JSON.stringify({ error: { detail: 'Unsupported option' } })); return; } response.writeHead(200, { 'content-type': 'text/event-stream' }); response.write(chunk('partial')); // 'stall' never finishes its stream. if (body.scenario === 'ok') { response.end(`${chunk(' answer')}data: [DONE]\n\n`); } else if (body.scenario === 'truncated') { response.end(); } else if (body.scenario === 'open-after-done') { response.write('data: [DONE]\n\n'); } }); await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve)); // streamChatCompletion always targets the Brave API origin; route it to the local server. const { port } = server.address() as AddressInfo; const originalFetch = globalThis.fetch; globalThis.fetch = ((input: RequestInfo | URL, init?: RequestInit) => { const { pathname } = new URL(input instanceof Request ? input.url : input.toString()); return originalFetch(`http://127.0.0.1:${port}${pathname}`, init); }) as typeof fetch; restoreFetch = () => { globalThis.fetch = originalFetch; }; }); after(async () => { restoreFetch(); server.closeAllConnections(); await new Promise((resolve) => server.close(resolve)); }); it('POSTs the body as a streaming JSON request to the chat completions endpoint', async () => { await stream('ok'); const request = received.at(-1); assert.equal(request?.method, 'POST'); assert.equal(request?.url, '/res/v1/chat/completions'); assert.equal(request?.headers.accept, 'text/event-stream'); assert.equal(request?.headers['content-type'], 'application/json'); assert.deepEqual(request?.body, { scenario: 'ok', stream: true }); }); it('returns the streamed content chunks in order', async () => { const { deltas } = await stream('ok'); assert.deepEqual(deltas, ['partial', ' answer']); }); it('returns at [DONE] even if the server keeps the stream open', async () => { const { deltas } = await stream('open-after-done'); assert.deepEqual(deltas, ['partial']); }); it('reports a stream that closes before [DONE]', async () => { await assert.rejects(stream('truncated'), /ended before completion/); }); it('reports a timeout when the stream outlives timeoutMs', async () => { await assert.rejects(stream('stall', { timeoutMs: 200 }), /timed out/); }); it('reports a cancellation when the client signal aborts', async () => { const controller = new AbortController(); setTimeout(() => controller.abort(), 200); await assert.rejects( stream('stall', { timeoutMs: 5_000, signal: controller.signal }), /cancelled/ ); }); it('includes the error body for non-OK responses', async () => { await assert.rejects( stream('error'), /^Error: 422 Unprocessable Entity\n[\s\S]*Unsupported option/ ); }); }); - src/BraveAPI/chatCompletions.ts (1636 bytes)
import { BASE_URL, buildErrorMessage, mergeRequestHeaders } from './request.js'; import { readChatCompletionStream, type StreamedChatCompletion } from './sse.js'; const CHAT_COMPLETIONS_PATH = '/res/v1/chat/completions'; export type StreamChatCompletionOptions = { timeoutMs: number; /** Client cancellation signal, combined with the timeout. */ signal?: AbortSignal; }; /** * POSTs `body` to the Answers chat completions endpoint as a streaming * request and returns each streamed `choices[0].delta.content`, in order, * with the reported finish reason. */ export async function streamChatCompletion( body: Record<string, unknown>, { timeoutMs, signal: clientSignal }: StreamChatCompletionOptions ): Promise<StreamedChatCompletion> { const timeoutSignal = AbortSignal.timeout(timeoutMs); const signal = clientSignal ? AbortSignal.any([timeoutSignal, clientSignal]) : timeoutSignal; try { const response = await fetch(`${BASE_URL}${CHAT_COMPLETIONS_PATH}`, { method: 'POST', headers: mergeRequestHeaders({ Accept: 'text/event-stream', 'Content-Type': 'application/json', }), body: JSON.stringify({ ...body, stream: true }), signal, }); if (!response.ok) { throw new Error(await buildErrorMessage(response)); } return await readChatCompletionStream(response); } catch (error) { if (timeoutSignal.aborted) { throw new Error(`Streaming request timed out after ${Math.round(timeoutMs / 1000)} seconds`); } if (clientSignal?.aborted) { throw new Error('Streaming request was cancelled'); } throw error; } } - src/BraveAPI/index.ts (3922 bytes)
import type { Endpoints } from './types.js'; import { BASE_URL, buildErrorMessage, mergeRequestHeaders } from './request.js'; const typeToPathMap: Record<keyof Endpoints, string> = { images: '/res/v1/images/search', localPois: '/res/v1/local/pois', localDescriptions: '/res/v1/local/descriptions', news: '/res/v1/news/search', videos: '/res/v1/videos/search', web: '/res/v1/web/search', summarizer: '/res/v1/summarizer/search', llmContext: '/res/v1/llm/context', placeSearch: '/res/v1/local/place_search', }; const isValidGoggleURL = (url: string): boolean => { try { // Only allow HTTPS URLs return new URL(url).protocol === 'https:'; } catch { return false; } }; 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<T extends keyof Endpoints>( endpoint: T, parameters: Endpoints[T]['params'], requestHeaders: Endpoints[T]['requestHeaders'] = {} as Endpoints[T]['requestHeaders'] ): Promise<Endpoints[T]['response']> { // TODO (Sampson): Add rate-limit logic supporting self-throttling and n-keys // Determine URL, and setup parameters const url = new URL(`${BASE_URL}${typeToPathMap[endpoint]}`); const queryParams = new URLSearchParams(); // TODO (Sampson): Move param-construction/validation to modules for (const [key, value] of Object.entries(parameters)) { // The 'ids' parameter is expected to appear multiple times for multiple IDs if (['localPois', 'localDescriptions'].includes(endpoint)) { if (key === 'ids') { if (Array.isArray(value) && value.length > 0) { value.forEach((id) => queryParams.append(key, id)); } else if (typeof value === 'string') { queryParams.set(key, value); } continue; } } // Handle `result_filter` parameter if (key === 'result_filter') { /** * Handle special behavior of 'summary' parameter: * When 'summary' is true, we need to either set result_filter to * 'summarizer', or leave it excluded entirely. This is due to a known * bug in the now-deprecated Summarizer endpoint. Setting it to * 'summarizer' will result in no web results being returned, which is * not ideal. As such, we skip the parameter entirely. * See https://github.com/brave/brave-search-mcp-server/issues/272 and * https://bravesoftware.slack.com/archives/C01NNFM9XMM/p1751654841090929 */ if ('summary' in parameters && parameters.summary === true) { continue; } else if (Array.isArray(value) && value.length > 0) { queryParams.set(key, value.join(',')); } continue; } // Handle `goggles` parameter(s) if (key === 'goggles') { 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 && value !== null) { queryParams.set(key === 'query' ? 'q' : key, value.toString()); } } // Issue Request const urlWithParams = url.toString() + '?' + queryParams.toString(); const response = await fetch(urlWithParams, { headers: mergeRequestHeaders(requestHeaders), }); // Handle Error if (!response.ok) { // TODO (Sampson): Setup proper error handling, updating state, etc. throw new Error(await buildErrorMessage(response)); } // Return Response const responseBody = await response.json(); return responseBody as Endpoints[T]['response']; } export default { issueRequest, }; - src/BraveAPI/request.test.ts (1400 bytes)
import assert from 'node:assert/strict'; import { describe, it } from 'node:test'; import { buildErrorMessage } from './request.js'; function errorResponse(body: string, status = 400, statusText = 'Bad Request'): Response { return new Response(body, { status, statusText }); } describe('buildErrorMessage', () => { it('formats JSON error bodies', async () => { const message = await buildErrorMessage( errorResponse(JSON.stringify({ error: 'invalid_request', message: 'Bad input' })) ); assert.match(message, /^400 Bad Request\n/); assert.match(message, /"error": "invalid_request"/); assert.match(message, /"message": "Bad input"/); }); it('includes plain-text error bodies when JSON parsing fails', async () => { const message = await buildErrorMessage(errorResponse('upstream service unavailable')); assert.equal(message, '400 Bad Request\nupstream service unavailable'); }); it('includes malformed JSON as raw text without attempting a second body read', async () => { const message = await buildErrorMessage(errorResponse('{"error": "truncated')); assert.equal(message, '400 Bad Request\n{"error": "truncated'); }); it('returns only the status line when the body is empty', async () => { const message = await buildErrorMessage(errorResponse('', 502, 'Bad Gateway')); assert.equal(message, '502 Bad Gateway'); }); }); - src/BraveAPI/request.ts (1260 bytes)
import config from '../config.js'; import { stringify } from '../utils.js'; export const BASE_URL = 'https://api.search.brave.com'; function getDefaultRequestHeaders(): Record<string, string> { return { Accept: 'application/json', 'Accept-Encoding': 'gzip', 'X-Subscription-Token': config.braveApiKey, }; } export async function buildErrorMessage(response: Response): Promise<string> { let errorMessage = `${response.status} ${response.statusText}`; try { const bodyText = await response.text(); if (bodyText.length === 0) { return errorMessage; } try { errorMessage += `\n${stringify(JSON.parse(bodyText), true)}`; } catch { errorMessage += `\n${bodyText}`; } } catch { // Body unavailable; status line only. } return errorMessage; } /** Layers request-specific headers over the defaults, skipping unset values. */ export function mergeRequestHeaders( requestHeaders: Record<string, string | number | undefined | null> = {} ): 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)); } return headers; } - src/BraveAPI/sse.test.ts (4196 bytes)
import assert from 'node:assert/strict'; import { describe, it } from 'node:test'; import { readChatCompletionStream } from './sse.js'; const event = (content: string) => `data: ${JSON.stringify({ choices: [{ delta: { content } }] })}\n\n`; /** A response whose body delivers each chunk as a separate read; strings are UTF-8 encoded. */ function createSseResponse(chunks: Array<string | Uint8Array>): Response { const encoder = new TextEncoder(); let index = 0; const stream = new ReadableStream({ pull(controller) { if (index < chunks.length) { const chunk = chunks[index++]; controller.enqueue(typeof chunk === 'string' ? encoder.encode(chunk) : chunk); } else { controller.close(); } }, }); return new Response(stream); } describe('readChatCompletionStream', () => { it('returns delta content from each event in order', async () => { const sse = [ 'data: {"choices":[{"delta":{"content":"Hello"}}]}', '', 'data: {"choices":[{"delta":{"content":" world"}}]}', '', 'data: [DONE]', '', '', ].join('\r\n'); const { deltas } = await readChatCompletionStream(createSseResponse([sse])); assert.deepEqual(deltas, ['Hello', ' world']); }); it('reports the last finish_reason, or none when the stream omits it', async () => { const finished = createSseResponse([ 'data: {"choices":[{"delta":{"content":"Cut"},"finish_reason":null}]}\n\n', 'data: {"choices":[{"delta":{"content":""},"finish_reason":"length"}]}\n\n', 'data: [DONE]\n\n', ]); const unfinished = createSseResponse([event('Hello'), 'data: [DONE]\n\n']); assert.deepEqual(await readChatCompletionStream(finished), { deltas: ['Cut'], finishReason: 'length', }); assert.equal((await readChatCompletionStream(unfinished)).finishReason, undefined); }); it('ignores malformed JSON, empty data, comments, and other fields', async () => { const sse = [ 'event: ping', '', 'data:', '', 'data: not-json', '', ': keep-alive', '', event('ok'), 'data: [DONE]\n\n', ].join('\n'); assert.deepEqual((await readChatCompletionStream(createSseResponse([sse]))).deltas, ['ok']); }); it('joins an event whose data spans several lines', async () => { const response = createSseResponse([ 'data: {"choices":[{"delta":\ndata: {"content":"joined"}}]}\n\n', 'data: [DONE]\n\n', ]); assert.deepEqual((await readChatCompletionStream(response)).deltas, ['joined']); }); it('decodes UTF-8 split across byte chunks', async () => { const bytes = new TextEncoder().encode(event('世界')); const worldCharStart = bytes.indexOf(0xe4); // first byte of 世 (3-byte UTF-8) assert.notEqual(worldCharStart, -1); const response = createSseResponse([ bytes.slice(0, worldCharStart + 1), bytes.slice(worldCharStart + 1), 'data: [DONE]\n\n', ]); assert.deepEqual((await readChatCompletionStream(response)).deltas, ['世界']); }); it('rejects a stream that ends before [DONE]', async () => { const response = createSseResponse([ event('complete'), 'data: {"choices":[{"delta":{"content":" lost', ]); await assert.rejects(readChatCompletionStream(response), /ended before completion/); }); it('rejects an error event in the stream', async () => { const response = createSseResponse([ event('Partial'), 'data: {"error":{"message":"upstream failure"}}\n\n', 'data: [DONE]\n\n', ]); await assert.rejects(readChatCompletionStream(response), /reported an error: upstream failure/); }); it('stops at [DONE] and cancels a stream that stays open', { timeout: 2_000 }, async () => { let cancelled = false; const stream = new ReadableStream({ start(controller) { controller.enqueue(new TextEncoder().encode(`${event('done')}data: [DONE]\n\n`)); }, cancel() { cancelled = true; }, }); assert.deepEqual((await readChatCompletionStream(new Response(stream))).deltas, ['done']); assert.equal(cancelled, true); }); }); - src/BraveAPI/sse.ts (2527 bytes)
import { EventSourceParserStream } from 'eventsource-parser/stream'; /** * Reads a streamed chat completion from a Server-Sent Events response. * * Brave Answers returns OpenAI-compatible events whose data is a JSON chunk * with `choices[0].delta.content`, terminated by a `[DONE]` event. */ type SseChunk = { choices?: Array<{ delta?: { content?: unknown }; finish_reason?: unknown }>; error?: unknown; }; export type StreamedChatCompletion = { /** Each delta's content, in order. */ deltas: string[]; /** The last `choices[0].finish_reason` reported, such as "stop" or "length". */ finishReason?: string; }; function describeError(error: unknown): string { const message = (error as { message?: unknown } | null)?.message; if (typeof message === 'string') return message; return typeof error === 'string' ? error : JSON.stringify(error); } /** The event's JSON chunk, or null for empty and malformed payloads. */ function parseChunk(data: string): SseChunk | null { try { return JSON.parse(data) as SseChunk | null; } catch { return null; } } /** * Reads the stream until the `[DONE]` event and returns each delta's content, * in order, with the reported finish reason. Throws if the stream ends before * [DONE] or sends an error event. Aborting the fetch that produced `response` * rejects the pending read with the abort reason. */ export async function readChatCompletionStream( response: Response ): Promise<StreamedChatCompletion> { if (!response.body) { throw new Error('Streaming response has no body'); } const events = response.body .pipeThrough(new TextDecoderStream()) .pipeThrough(new EventSourceParserStream()); const deltas: string[] = []; let finishReason: string | undefined; // Leaving the loop cancels the stream, which the server may keep open after [DONE] or an error event. for await (const { data } of events) { if (data === '[DONE]') return { deltas, finishReason }; const chunk = parseChunk(data); if (chunk?.error !== undefined && chunk.error !== null) { throw new Error(`Streaming response reported an error: ${describeError(chunk.error)}`); } const choice = chunk?.choices?.[0]; const content = choice?.delta?.content; if (typeof content === 'string' && content.length > 0) { deltas.push(content); } if (typeof choice?.finish_reason === 'string') { finishReason = choice.finish_reason; } } throw new Error('Streaming response ended before completion'); } - src/BraveAPI/types.ts (2665 bytes)
import type { QueryParams as WebQueryParams } from '../tools/web/params.js'; import type { QueryParams as ImageQueryParams } from '../tools/images/schemas/input.js'; import type { QueryParams as VideoQueryParams } from '../tools/videos/params.js'; import type { QueryParams as NewsQueryParams } from '../tools/news/params.js'; import type { LocalPoisParams, LocalDescriptionsParams } from '../tools/local/params.js'; import type { SummarizerQueryParams } from '../tools/summarizer/params.js'; import type { WebSearchApiResponse } from '../tools/web/types.js'; import type { SummarizerSearchApiResponse } from '../tools/summarizer/types.js'; import type { ImageSearchApiResponse } from '../tools/images/types.js'; import type { VideoSearchApiResponse } from '../tools/videos/types.js'; import type { NewsSearchApiResponse } from '../tools/news/types.js'; 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'; import type { PlaceSearchQueryParams, PlaceSearchRequestHeaders, } from '../tools/place_search/schemas/input.js'; import type { PlaceSearchApiResponse } from '../tools/place_search/schemas/output.js'; /** Request headers for endpoints that take none. */ type NoRequestHeaders = Record<string, never>; export type Endpoints = { web: { params: WebQueryParams; response: WebSearchApiResponse; requestHeaders: NoRequestHeaders; }; images: { params: ImageQueryParams; response: ImageSearchApiResponse; requestHeaders: NoRequestHeaders; }; videos: { params: VideoQueryParams; response: VideoSearchApiResponse; requestHeaders: NoRequestHeaders; }; news: { params: NewsQueryParams; response: NewsSearchApiResponse; requestHeaders: NoRequestHeaders; }; localPois: { params: LocalPoisParams; response: LocalPoiSearchApiResponse; requestHeaders: NoRequestHeaders; }; localDescriptions: { params: LocalDescriptionsParams; response: LocalDescriptionsSearchApiResponse; requestHeaders: NoRequestHeaders; }; summarizer: { params: SummarizerQueryParams; response: SummarizerSearchApiResponse; requestHeaders: NoRequestHeaders; }; llmContext: { params: LlmQueryParams; response: LlmContextSearchApiResponse; requestHeaders: LlmRequestHeaders; }; placeSearch: { params: PlaceSearchQueryParams; response: PlaceSearchApiResponse; requestHeaders: PlaceSearchRequestHeaders; }; }; - src/config.test.ts (6679 bytes)
import assert from 'node:assert/strict'; import { mkdtempSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { afterEach, beforeEach, describe, it, mock } from 'node:test'; import { getOptions } from './config.js'; import { AGENTCORE_PORT, agentCoreEnvironment } from './testUtils/agentCore.js'; const CONFIG_ENV_VARS = [ 'BRAVE_API_KEY', 'BRAVE_API_KEY_FILE', 'BRAVE_MCP_LOG_LEVEL', 'BRAVE_MCP_TRANSPORT', 'BRAVE_MCP_ENABLED_TOOLS', 'BRAVE_MCP_DISABLED_TOOLS', 'BRAVE_MCP_PORT', 'BRAVE_MCP_HOST', 'BRAVE_MCP_ALLOWED_ORIGINS', 'BRAVE_MCP_ALLOWED_HOSTS', 'BRAVE_MCP_STATELESS', ] as const; describe('getOptions', () => { const originalArgv = process.argv; const originalEnv = Object.fromEntries(CONFIG_ENV_VARS.map((key) => [key, process.env[key]])); const originalConsoleError = console.error; beforeEach(() => { for (const key of CONFIG_ENV_VARS) { delete process.env[key]; } // getOptions() logs validation failures via console.error; silence it so the // expected-failure cases don't add noise to the test output. console.error = () => {}; }); afterEach(() => { process.argv = originalArgv; console.error = originalConsoleError; for (const key of CONFIG_ENV_VARS) { if (originalEnv[key] === undefined) { delete process.env[key]; } else { process.env[key] = originalEnv[key]; } } }); it('rejects whitespace-only API keys', () => { const error = mock.method(console, 'error', () => {}); try { process.argv = ['node', 'index.js', '--brave-api-key', ' ']; assert.equal(getOptions(), false); assert.equal(error.mock.callCount(), 1); } finally { mock.restoreAll(); } }); it('reads API key from --brave-api-key-file', () => { const dir = mkdtempSync(join(tmpdir(), 'brave-api-key-')); const filePath = join(dir, 'key.txt'); writeFileSync(filePath, 'from-file\n'); process.argv = ['node', 'index.js', '--brave-api-key-file', filePath]; const options = getOptions(); assert.notEqual(options, false); if (options) { assert.equal(options.braveApiKey, 'from-file'); } }); it('prefers file key over --brave-api-key', () => { const dir = mkdtempSync(join(tmpdir(), 'brave-api-key-')); const filePath = join(dir, 'key.txt'); writeFileSync(filePath, 'from-file\n'); process.argv = [ 'node', 'index.js', '--brave-api-key', 'from-env', '--brave-api-key-file', filePath, ]; const options = getOptions(); assert.notEqual(options, false); if (options) { assert.equal(options.braveApiKey, 'from-file'); } }); it('defaults host to loopback (127.0.0.1)', () => { process.argv = ['node', 'index.js', '--brave-api-key', 'key', '--transport', 'http']; const options = getOptions(); assert.notEqual(options, false); if (options) { assert.equal(options.host, '127.0.0.1'); } }); it('honors BRAVE_MCP_HOST override', () => { process.env.BRAVE_MCP_HOST = '0.0.0.0'; process.argv = ['node', 'index.js', '--brave-api-key', 'key', '--transport', 'http']; const options = getOptions(); assert.notEqual(options, false); if (options) { assert.equal(options.host, '0.0.0.0'); } }); it('defaults allowedOrigins to an empty list', () => { process.argv = ['node', 'index.js', '--brave-api-key', 'key']; const options = getOptions(); assert.notEqual(options, false); if (options) { assert.deepEqual(options.allowedOrigins, []); } }); it('parses BRAVE_MCP_ALLOWED_ORIGINS (comma/space separated)', () => { process.env.BRAVE_MCP_ALLOWED_ORIGINS = 'https://a.example, https://b.example https://c.example'; process.argv = ['node', 'index.js', '--brave-api-key', 'key']; const options = getOptions(); assert.notEqual(options, false); if (options) { assert.deepEqual(options.allowedOrigins, [ 'https://a.example', 'https://b.example', 'https://c.example', ]); } }); it('parses --allowed-origins from the CLI', () => { process.argv = [ 'node', 'index.js', '--brave-api-key', 'key', '--allowed-origins', 'https://a.example', 'https://b.example', ]; const options = getOptions(); assert.notEqual(options, false); if (options) { assert.deepEqual(options.allowedOrigins, ['https://a.example', 'https://b.example']); } }); it('defaults allowedHosts to an empty list', () => { process.argv = ['node', 'index.js', '--brave-api-key', 'key']; const options = getOptions(); assert.notEqual(options, false); if (options) { assert.deepEqual(options.allowedHosts, []); } }); it('parses BRAVE_MCP_ALLOWED_HOSTS (comma/space separated)', () => { process.env.BRAVE_MCP_ALLOWED_HOSTS = 'a.example:8080, b.example c.example'; process.argv = ['node', 'index.js', '--brave-api-key', 'key']; const options = getOptions(); assert.notEqual(options, false); if (options) { assert.deepEqual(options.allowedHosts, ['a.example:8080', 'b.example', 'c.example']); } }); it('parses --allowed-hosts from the CLI', () => { process.argv = [ 'node', 'index.js', '--brave-api-key', 'key', '--allowed-hosts', 'a.example', 'b.example', ]; const options = getOptions(); assert.notEqual(options, false); if (options) { assert.deepEqual(options.allowedHosts, ['a.example', 'b.example']); } }); // AgentCore buyers deploy with whatever the AWS Marketplace listing pre-fills, // and the release job sets those defaults from marketplace-revision-release.json. // Renaming a variable here (or editing that file) must not drift from what // AgentCore requires. it('yields an AgentCore-compliant config from the AWS Marketplace defaults', () => { for (const [name, value] of Object.entries(agentCoreEnvironment())) { assert.ok( (CONFIG_ENV_VARS as readonly string[]).includes(name), `marketplace-revision-release.json sets ${name}, which the server does not read` ); process.env[name] = value; } process.argv = ['node', 'index.js', '--brave-api-key', 'key']; const options = getOptions(); assert.notEqual(options, false); if (options) { assert.equal(options.transport, 'http'); assert.equal(options.host, '0.0.0.0'); assert.equal(options.port, AGENTCORE_PORT); assert.equal(options.stateless, true); } }); }); - src/config.ts (6327 bytes)
import { LoggingLevel, LoggingLevelSchema } from '@modelcontextprotocol/sdk/types.js'; import { Command } from 'commander'; import dotenv from 'dotenv'; import tools from './tools/index.js'; import { parseDelimitedList, parsePort, readBraveApiKeyFromFile } from './utils.js'; dotenv.config({ debug: false, quiet: true }); function parseToolNameList(value: string | string[] | undefined | null): string[] { if (value == null) return []; if (Array.isArray(value)) return value.map((t: string) => t.trim()).filter((t: string) => t.length > 0); return value .trim() .split(/\s+/) .filter((t: string) => t.length > 0); } type Configuration = { transport: 'stdio' | 'http'; port: number; host: string; braveApiKey: string; loggingLevel: LoggingLevel; enabledTools: string[]; disabledTools: string[]; stateless: boolean; allowedOrigins: string[]; allowedHosts: string[]; }; const state: Configuration & { ready: boolean } = { transport: 'stdio', port: 8080, host: '127.0.0.1', braveApiKey: process.env.BRAVE_API_KEY ?? '', loggingLevel: 'info', ready: false, enabledTools: [], disabledTools: [], stateless: false, allowedOrigins: [], allowedHosts: [], }; export function isToolPermittedByUser(toolName: string): boolean { return state.enabledTools.length > 0 ? state.enabledTools.includes(toolName) : state.disabledTools.includes(toolName) === false; } export function getOptions(): Configuration | false { const program = new Command() .option('--brave-api-key <string>', 'Brave API key', process.env.BRAVE_API_KEY ?? '') .option( '--brave-api-key-file <string>', 'Path to file containing Brave API key', process.env.BRAVE_API_KEY_FILE ?? '' ) .option('--logging-level <string>', 'Logging level', process.env.BRAVE_MCP_LOG_LEVEL ?? 'info') .option( '--transport <stdio|http>', 'transport type', process.env.BRAVE_MCP_TRANSPORT ?? 'stdio' ) .option( '--enabled-tools <names...>', 'tools to enable', process.env.BRAVE_MCP_ENABLED_TOOLS?.trim().split(' ') ?? [] ) .option( '--disabled-tools <names...>', 'tools to disable', process.env.BRAVE_MCP_DISABLED_TOOLS?.trim().split(' ') ?? [] ) .option( '--port <number>', 'desired port for HTTP transport', process.env.BRAVE_MCP_PORT ?? '8080' ) .option( '--host <string>', 'desired host for HTTP transport', process.env.BRAVE_MCP_HOST ?? '127.0.0.1' ) .option( '--allowed-origins <origins...>', 'allowed Origin header values for HTTP transport (DNS rebinding protection)', process.env.BRAVE_MCP_ALLOWED_ORIGINS ?? '' ) .option( '--allowed-hosts <hosts...>', 'allowed Host header values for HTTP transport (opt-in DNS rebinding protection)', process.env.BRAVE_MCP_ALLOWED_HOSTS ?? '' ) .option( '--stateless <boolean>', 'whether the server should be stateless', process.env.BRAVE_MCP_STATELESS === 'true' ? true : false ) .allowUnknownOption() .parse(process.argv); const options = program.opts(); const toolNames = Object.values(tools).map((tool) => tool.name); // Validate tool inclusion configuration const enabledTools = parseToolNameList(options.enabledTools); const disabledTools = parseToolNameList(options.disabledTools); if (enabledTools.length > 0 && disabledTools.length > 0) { console.error('Error: --enabled-tools and --disabled-tools cannot be used together'); return false; } const invalidToolNames = [...enabledTools, ...disabledTools].filter( (t: string) => !toolNames.includes(t) ); if (invalidToolNames.length > 0) { console.error(`Invalid tool name(s) used: ${invalidToolNames.join(', ')}`); console.error(`Valid tool names are: ${toolNames.join(', ')}`); return false; } // Validate all other options if (!['stdio', 'http'].includes(options.transport)) { console.error( `Invalid --transport value: '${options.transport}'. Must be one of: stdio, http.` ); return false; } if (!LoggingLevelSchema.options.includes(options.loggingLevel)) { console.error( `Invalid --logging-level value: '${options.loggingLevel}'. Must be one of: ${LoggingLevelSchema.options.join(', ')}` ); return false; } const apiKeyFile = typeof options.braveApiKeyFile === 'string' ? options.braveApiKeyFile.trim() : ''; let braveApiKey = typeof options.braveApiKey === 'string' ? options.braveApiKey.trim() : ''; if (apiKeyFile) { const apiKeyFromFile = readBraveApiKeyFromFile(apiKeyFile); if (!apiKeyFromFile.ok) { console.error(`Error: ${apiKeyFromFile.error}`); return false; } braveApiKey = apiKeyFromFile.key; } if (!braveApiKey) { console.error( 'Error: A Brave API key is required via --brave-api-key, BRAVE_API_KEY, --brave-api-key-file, or BRAVE_API_KEY_FILE. You can get one at https://brave.com/search/api/.' ); return false; } if (options.transport === 'http') { const port = parsePort(options.port); if (port === null) { console.error( `Invalid --port value: '${options.port}'. Must be a valid port number between 1 and 65535.` ); return false; } options.port = port; if (!options.host) { console.error('Error: --host is required'); return false; } } // Normalize stateless to boolean (CLI passes it as string) options.stateless = options.stateless === true || options.stateless === 'true'; options.braveApiKey = braveApiKey; const allowedOrigins = parseDelimitedList(options.allowedOrigins); options.allowedOrigins = allowedOrigins; const allowedHosts = parseDelimitedList(options.allowedHosts); options.allowedHosts = allowedHosts; // Update state state.braveApiKey = braveApiKey; state.transport = options.transport; state.port = options.port; state.host = options.host; state.loggingLevel = options.loggingLevel; state.enabledTools = enabledTools; state.disabledTools = disabledTools; state.stateless = options.stateless; state.allowedOrigins = allowedOrigins; state.allowedHosts = allowedHosts; state.ready = true; return options as Configuration; } export default state; - src/docker.e2e.ts (8192 bytes)
import assert from 'node:assert/strict'; import { execFile } from 'node:child_process'; import { chmodSync, mkdtempSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { after, before, describe, it } from 'node:test'; import { promisify } from 'node:util'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; import { AGENTCORE_PORT, agentCoreEnvironment, agentCoreRpc, initializeParams, } from './testUtils/agentCore.js'; import { expectedToolNames, toolNames } from './testUtils/mcpTestHarness.js'; import { name as webSearchToolName } from './tools/web/index.js'; /** * End-to-end tests for the container image, run the way each distribution * channel runs it. Not part of `npm test`: `npm run test:docker` builds the * image and runs these. To test an existing image (e.g. one pulled from Docker * Hub), set BRAVE_MCP_TEST_IMAGE and run this file directly. * * The API key is fake, so tool calls hit the real Brave API and come back as * error results; these tests assert the MCP round trip, not search results. */ const IMAGE = process.env.BRAVE_MCP_TEST_IMAGE ?? 'brave-search-mcp-server:test'; const LABEL = 'brave-search-mcp-server-e2e'; const API_KEY = 'test-key'; // The hardening flags from our documented `docker run` and compose usage. const HARDENING = ['--read-only', '--cap-drop', 'all', '--security-opt', 'no-new-privileges']; const execFileAsync = promisify(execFile); const docker = async (...args: string[]): Promise<string> => (await execFileAsync('docker', args)).stdout.trim(); const containerLogs = async (id: string): Promise<string> => { const { stdout, stderr } = await execFileAsync('docker', ['logs', id]); return stdout + stderr; }; // Launches the image the way an MCP host does: `docker run -i` as a child // process speaking JSON-RPC over stdin/stdout. const connectStdio = async (dockerArgs: string[], env: Record<string, string> = {}) => { const transport = new StdioClientTransport({ command: 'docker', args: ['run', '--interactive', '--rm', '--label', LABEL, ...dockerArgs, IMAGE], env: { ...(process.env as Record<string, string>), ...env }, stderr: 'pipe', }); const client = new Client({ name: 'docker-e2e', version: '0.0.0' }); await client.connect(transport); return client; }; // Starts a detached HTTP container on a random loopback port and resolves once // it answers /ping. const startHttpContainer = async ( env: Record<string, string>, containerPort: number ): Promise<string> => { const envArgs = Object.entries(env).flatMap(([name, value]) => ['--env', `${name}=${value}`]); const id = await docker( 'run', '--detach', '--label', LABEL, ...HARDENING, '--publish', `127.0.0.1::${containerPort}`, ...envArgs, IMAGE ); const deadline = Date.now() + 30_000; while (Date.now() < deadline) { try { const [binding] = (await docker('port', id, `${containerPort}/tcp`)).split('\n'); const baseUrl = `http://${binding}`; if ((await fetch(`${baseUrl}/ping`)).ok) return baseUrl; } catch { // Not listening yet (or exited; the logs below will say which). } await new Promise((resolve) => setTimeout(resolve, 250)); } throw new Error( `Container never answered /ping on ${containerPort}:\n${await containerLogs(id)}` ); }; after(async () => { const ids = await docker('ps', '--all', '--quiet', '--filter', `label=${LABEL}`); if (ids) await docker('rm', '--force', ...ids.split(/\s+/)); }); describe('stdio (Docker MCP Catalog, Claude Desktop, VS Code)', () => { it('serves tools via `docker run -i --rm -e BRAVE_API_KEY` as in the README', async () => { const client = await connectStdio(['--env', 'BRAVE_API_KEY'], { BRAVE_API_KEY: API_KEY }); try { const { tools: listed } = await client.listTools(); assert.deepEqual(toolNames(listed), expectedToolNames); } finally { await client.close(); } }); it('serves tool calls with the Docker MCP Catalog configuration', async () => { const client = await connectStdio([ ...HARDENING, '--env', `BRAVE_API_KEY=${API_KEY}`, '--env', 'BRAVE_MCP_TRANSPORT=stdio', ]); try { const result = await client.callTool({ name: webSearchToolName, arguments: { query: 'brave' }, }); assert.ok(Array.isArray(result.content) && result.content.length > 0); } finally { await client.close(); } }); it('reads the API key from a mounted secret via BRAVE_API_KEY_FILE', async () => { const keyFile = join(mkdtempSync(join(tmpdir(), 'brave-api-key-')), 'brave_api_key'); writeFileSync(keyFile, `${API_KEY}\n`); // The image runs as the unprivileged `node` user. chmodSync(keyFile, 0o644); const client = await connectStdio([ ...HARDENING, '--mount', `type=bind,source=${keyFile},target=/run/secrets/brave_api_key,readonly`, '--env', 'BRAVE_API_KEY_FILE=/run/secrets/brave_api_key', ]); try { const { tools: listed } = await client.listTools(); assert.deepEqual(toolNames(listed), expectedToolNames); } finally { await client.close(); } }); }); describe('HTTP (Docker Hub, docker compose, ECS/EKS)', () => { let client: Client; let transport: StreamableHTTPClientTransport; before(async () => { // Relies on the image's own BRAVE_MCP_HOST=0.0.0.0 to be reachable. const baseUrl = await startHttpContainer( { BRAVE_API_KEY: API_KEY, BRAVE_MCP_TRANSPORT: 'http' }, 8080 ); transport = new StreamableHTTPClientTransport(new URL(`${baseUrl}/mcp`)); client = new Client({ name: 'docker-e2e', version: '0.0.0' }); await client.connect(transport); }); after(() => client?.close()); it('serves tools/list and tools/call over a session on port 8080', async () => { assert.ok(transport.sessionId); const { tools: listed } = await client.listTools(); assert.deepEqual(toolNames(listed), expectedToolNames); const result = await client.callTool({ name: webSearchToolName, arguments: { query: 'brave' }, }); assert.ok(Array.isArray(result.content) && result.content.length > 0); }); }); describe('Amazon Bedrock AgentCore (defaults from marketplace-revision-release.json)', () => { let baseUrl: string; before(async () => { baseUrl = await startHttpContainer( { ...agentCoreEnvironment(), BRAVE_API_KEY: API_KEY }, AGENTCORE_PORT ); }); it('accepts initialize carrying a platform-generated session id', async () => { const { status, body } = await agentCoreRpc(baseUrl, 1, 'initialize', initializeParams); assert.equal(status, 200, JSON.stringify(body)); assert.equal(body.result.serverInfo.name, 'brave-search-mcp-server'); }); it('serves tools/list with no prior initialize', async () => { const { status, body } = await agentCoreRpc(baseUrl, 2, 'tools/list'); assert.equal(status, 200, JSON.stringify(body)); assert.deepEqual(toolNames(body.result.tools), expectedToolNames); }); it('serves tools/call with no prior initialize', async () => { const { status, body } = await agentCoreRpc(baseUrl, 3, 'tools/call', { name: webSearchToolName, arguments: { query: 'brave' }, }); assert.equal(status, 200, JSON.stringify(body)); assert.ok(body.result.content.length > 0, JSON.stringify(body)); }); }); describe('misconfiguration', () => { it('exits non-zero with a clear error when no API key is set', async () => { await assert.rejects( execFileAsync( 'docker', ['run', '--rm', '--label', LABEL, '--env', 'BRAVE_MCP_TRANSPORT=http', IMAGE], { timeout: 30_000 } ), (error: { code?: number; stderr?: string }) => { assert.equal(error.code, 1); assert.match(error.stderr ?? '', /API key is required/); return true; } ); }); }); - src/index.ts (521 bytes)
#!/usr/bin/env node import { getOptions } from './config.js'; import { stdioServer, httpServer } from './protocols/index.js'; async function main() { const options = getOptions(); if (!options) { console.error('Invalid configuration'); process.exit(1); } // default to stdio server unless http is explicitly requested if (options.transport === 'http') { httpServer.start(); return; } await stdioServer.start(); } main().catch((error) => { console.error(error); process.exit(1); }); - src/jsonSchemaDialect.ts (3232 bytes)
import { type McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import { ListToolsRequestSchema, type ListToolsResult, type Tool, } from '@modelcontextprotocol/sdk/types.js'; import { z, type ZodRawShape } from 'zod'; import tools from './tools/index.js'; /** * The dialect servers MUST emit by default, per SEP-1613 §5. * https://modelcontextprotocol.io/seps/1613-establish-json-schema-2020-12-as-default-dialect-f */ const JSON_SCHEMA_2020_12 = 'https://json-schema.org/draft/2020-12/schema'; type ToolSchemas = { inputSchema?: ZodRawShape; outputSchema?: z.ZodObject; }; const schemasByTool = new Map<string, ToolSchemas>( Object.values(tools).map((tool) => [tool.name, tool as ToolSchemas]) ); const toJsonSchema2020 = (schema: z.ZodObject, io: 'input' | 'output'): Tool['inputSchema'] => z.toJSONSchema(schema, { target: 'draft-2020-12', io, }) as unknown as Tool['inputSchema']; type ListToolsHandler = (request: unknown, extra: unknown) => Promise<ListToolsResult>; // An absent `$schema` defaults to 2020-12, but says nothing about which dialect's // keywords were emitted, so only an explicit declaration counts as correct. const needsRetargeting = (schema?: Tool['inputSchema'] | Tool['outputSchema']): boolean => (schema as { $schema?: string } | undefined)?.$schema !== JSON_SCHEMA_2020_12; /** * Re-emits advertised tool schemas as 2020-12, skipping any the SDK already got * right - so this decays to a string comparison once the SDK is fixed, and can * then be deleted. * * The SDK hardcodes draft-07 (`mcp.js` calls `toJsonSchemaCompat()` with no * `target`), which 2020-12-only clients reject outright, and whose array-form * `items` is invalid 2020-12 (`brave_place_search`'s coordinates tuple). * Wrapping its handler preserves the other fields it emits. * * https://github.com/modelcontextprotocol/typescript-sdk/issues/2084 (PR #2085) * * Must be called after all tools are registered. */ export default function enforce2020Dialect(mcpServer: McpServer): void { const requestHandlers = ( mcpServer.server as unknown as { _requestHandlers?: Map<string, ListToolsHandler> } )._requestHandlers; const listTools = requestHandlers?.get('tools/list'); // Only reachable through SDK internals; if a future version moves it, leave its // output alone rather than failing to start - server.test.ts catches regressions. if (!listTools) return; mcpServer.server.setRequestHandler(ListToolsRequestSchema, async (request, extra) => { const result = await listTools(request, extra); for (const tool of result.tools) { const schemas = schemasByTool.get(tool.name); if (!schemas) continue; if (schemas.inputSchema && needsRetargeting(tool.inputSchema)) { tool.inputSchema = toJsonSchema2020(z.object(schemas.inputSchema), 'input'); } if (schemas.outputSchema && tool.outputSchema && needsRetargeting(tool.outputSchema)) { // Keep the original object's unknown-key policy; rebuilding from .shape // would turn loose response schemas into closed output schemas. tool.outputSchema = toJsonSchema2020(schemas.outputSchema, 'output'); } } return result; }); } - src/protocols/http.test.ts (12915 bytes)
import assert from 'node:assert/strict'; import { spawn } from 'node:child_process'; import http, { type Server } from 'node:http'; import net, { type AddressInfo } from 'node:net'; import { after, before, describe, it } from 'node:test'; import { fileURLToPath } from 'node:url'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; import config from '../config.js'; import { agentCoreRpc, initializeParams, readJsonRpc } from '../testUtils/agentCore.js'; import { expectedToolNames, stubFetch, toolNames } from '../testUtils/mcpTestHarness.js'; import { name as webSearchToolName } from '../tools/web/index.js'; import httpServer from './http.js'; // Raw HTTP client so we can set the Host header (fetch/undici forbids overriding it). const rawRequest = ( port: number, headers: Record<string, string> ): Promise<{ status: number; body: string }> => new Promise((resolve, reject) => { const body = JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }); const req = http.request( { host: '127.0.0.1', port, path: '/mcp', method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', 'content-length': Buffer.byteLength(body), ...headers, }, }, (res) => { let data = ''; res.on('data', (chunk) => (data += chunk)); res.on('end', () => resolve({ status: res.statusCode ?? 0, body: data })); } ); req.on('error', reject); req.write(body); req.end(); }); const listen = async (): Promise<{ server: Server; port: number; baseUrl: string }> => { const server = httpServer.createApp().listen(0); await new Promise<void>((resolve) => server.once('listening', resolve)); const { port } = server.address() as AddressInfo; return { server, port, baseUrl: `http://127.0.0.1:${port}` }; }; // An SDK client holds a standalone SSE stream open, which `close()` alone // would wait on forever. const shutdown = (server: Server) => new Promise<void>((resolve, reject) => { server.closeAllConnections(); server.close((err) => (err ? reject(err) : resolve())); }); describe('http Origin validation', () => { let server: Server; let baseUrl: string; let port: number; const originalAllowedOrigins = [...config.allowedOrigins]; const post = (origin: string | undefined) => fetch(`${baseUrl}/mcp`, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', ...(origin ? { origin } : {}), }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }), }); before(async () => { config.allowedOrigins = ['https://allowed.example']; ({ server, port, baseUrl } = await listen()); }); after(async () => { config.allowedOrigins = originalAllowedOrigins; await shutdown(server); }); it('rejects a disallowed browser Origin with 403 and a JSON-RPC error', async () => { const res = await post('https://evil.example'); const body = await res.json(); assert.equal(res.status, 403); assert.deepEqual(body, { jsonrpc: '2.0', error: { code: -32600, message: 'Forbidden: invalid Origin' }, id: null, }); }); it('allows loopback Origins', async () => { const res = await post('http://localhost:3000'); await res.text(); assert.notEqual(res.status, 403); }); it('allows explicitly allow-listed Origins', async () => { const res = await post('https://allowed.example'); await res.text(); assert.notEqual(res.status, 403); }); it('matches allow-listed Origins case-insensitively', async () => { const res = await post('https://ALLOWED.example'); await res.text(); assert.notEqual(res.status, 403); }); it('matches allow-listed Origins ignoring the default port', async () => { const res = await post('https://allowed.example:443'); await res.text(); assert.notEqual(res.status, 403); }); it('allows requests without an Origin header', async () => { const res = await post(undefined); await res.text(); assert.notEqual(res.status, 403); }); it('rejects a present but empty Origin header', async () => { const res = await rawRequest(port, { origin: '' }); assert.equal(res.status, 403); }); }); describe('http Host validation (disabled by default)', () => { let server: Server; let port: number; before(async () => { ({ server, port } = await listen()); }); after(() => shutdown(server)); it('allows an arbitrary Host when allowedHosts is empty', async () => { const res = await rawRequest(port, { host: 'anything.example.com' }); assert.notEqual(res.status, 403); }); }); describe('http Host validation (opt-in)', () => { let server: Server; let port: number; const originalAllowedHosts = [...config.allowedHosts]; before(async () => { config.allowedHosts = ['allowed.example.com']; ({ server, port } = await listen()); }); after(async () => { config.allowedHosts = originalAllowedHosts; await shutdown(server); }); it('rejects a disallowed Host with 403 and a JSON-RPC error', async () => { const res = await rawRequest(port, { host: 'evil.example.com' }); assert.equal(res.status, 403); assert.deepEqual(JSON.parse(res.body), { jsonrpc: '2.0', error: { code: -32600, message: 'Forbidden: invalid Host' }, id: null, }); }); it('allows loopback Hosts', async () => { const res = await rawRequest(port, { host: `127.0.0.1:${port}` }); assert.notEqual(res.status, 403); }); it('allows explicitly allow-listed Hosts', async () => { const res = await rawRequest(port, { host: 'allowed.example.com' }); assert.notEqual(res.status, 403); }); it('allows an allow-listed Host regardless of port', async () => { const res = await rawRequest(port, { host: 'allowed.example.com:9999' }); assert.notEqual(res.status, 403); }); it('matches allow-listed Hosts case-insensitively', async () => { const res = await rawRequest(port, { host: 'ALLOWED.EXAMPLE.COM' }); assert.notEqual(res.status, 403); }); it('rejects a malformed bracketed IPv6 Host that spoofs loopback', async () => { const res = await rawRequest(port, { host: '[::1]evil.example.com' }); assert.equal(res.status, 403); }); it('rejects an allow-listed Host with a malformed (non-numeric) port', async () => { const res = await rawRequest(port, { host: 'allowed.example.com:80evil' }); assert.equal(res.status, 403); }); }); const stubBraveApi = () => stubFetch((url) => { if (url.pathname === '/res/v1/web/search') { return { type: 'search', web: { results: [ { url: 'https://search.brave.com/', title: 'Brave Search', description: 'A privacy-focused search engine.', extra_snippets: [], }, ], }, }; } }); describe('http stateless mode (Amazon Bedrock AgentCore contract)', () => { let server: Server; let baseUrl: string; let restoreFetch: () => void; const originalStateless = config.stateless; before(async () => { config.stateless = true; restoreFetch = stubBraveApi(); ({ server, baseUrl } = await listen()); }); after(async () => { config.stateless = originalStateless; restoreFetch(); await shutdown(server); }); it('accepts initialize carrying a platform-generated session id', async () => { const { status, sessionId, body } = await agentCoreRpc( baseUrl, 1, 'initialize', initializeParams ); assert.equal(status, 200, JSON.stringify(body)); assert.equal(body.result.serverInfo.name, 'brave-search-mcp-server'); // The platform owns the session id; a stateless server must not mint one. assert.equal(sessionId, null); }); it('serves tools/list with no prior initialize', async () => { const { status, body } = await agentCoreRpc(baseUrl, 2, 'tools/list'); assert.equal(status, 200, JSON.stringify(body)); assert.deepEqual(toolNames(body.result.tools), expectedToolNames); }); it('serves tools/call with no prior initialize', async () => { const { status, body } = await agentCoreRpc(baseUrl, 3, 'tools/call', { name: webSearchToolName, arguments: { query: 'brave browser' }, }); assert.equal(status, 200, JSON.stringify(body)); assert.equal(body.result.isError ?? false, false, JSON.stringify(body.result)); assert.ok(body.result.content.length > 0); }); it('answers GET /ping', async () => { const res = await fetch(`${baseUrl}/ping`); assert.equal(res.status, 200); assert.deepEqual(await res.json(), { message: 'pong' }); }); }); describe('http stateful sessions (default)', () => { let server: Server; let baseUrl: string; let restoreFetch: () => void; let client: Client; let transport: StreamableHTTPClientTransport; before(async () => { restoreFetch = stubBraveApi(); ({ server, baseUrl } = await listen()); transport = new StreamableHTTPClientTransport(new URL(`${baseUrl}/mcp`)); client = new Client({ name: 'http-test-client', version: '0.0.0' }); await client.connect(transport); }); after(async () => { await client.close(); restoreFetch(); await shutdown(server); }); it('issues a session id on initialize', () => { assert.ok(transport.sessionId); }); it('serves tools/list within the session', async () => { const { tools: listedTools } = await client.listTools(); assert.deepEqual(toolNames(listedTools), expectedToolNames); }); it('serves tools/call within the session', async () => { const result = await client.callTool({ name: webSearchToolName, arguments: { query: 'brave browser' }, }); assert.equal(result.isError ?? false, false, JSON.stringify(result.content)); assert.ok(Array.isArray(result.content) && result.content.length > 0); }); it('serves tools/list without a session id', async () => { const res = await fetch(`${baseUrl}/mcp`, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }), }); const body = await readJsonRpc(res); assert.equal(res.status, 200, JSON.stringify(body)); assert.deepEqual(toolNames(body.result.tools), expectedToolNames); }); }); const entrypoint = fileURLToPath(new URL('../index.ts', import.meta.url)); const STARTUP_HOST = '127.0.0.1'; const EXIT_TIMEOUT_MS = 15_000; // `start()` exits the process on a bind failure, so drive it from a child. // The host is pinned to match the blocker, since BRAVE_MCP_HOST would otherwise // send the child to a different interface and let it bind. const startServer = (port: number): Promise<{ code: number | null; out: string; err: string }> => { const child = spawn( process.execPath, [ '--import', 'tsx', entrypoint, '--transport', 'http', '--host', STARTUP_HOST, '--port', String(port), ], { env: { ...process.env, BRAVE_API_KEY: 'test-key' } } ); let out = ''; let err = ''; child.stdout.on('data', (chunk: Buffer) => (out += chunk.toString())); child.stderr.on('data', (chunk: Buffer) => (err += chunk.toString())); return new Promise((resolve, reject) => { // A child that never exits is the regression under test; fail rather than hang. const timer = setTimeout(() => { child.kill(); reject(new Error(`Server did not exit within ${EXIT_TIMEOUT_MS}ms.\n${out}\n${err}`)); }, EXIT_TIMEOUT_MS); child.on('error', (error) => { clearTimeout(timer); reject(error); }); child.on('exit', (code) => { clearTimeout(timer); resolve({ code, out, err }); }); }); }; describe('HTTP transport startup', () => { let blocker: net.Server; let takenPort: number; before(async () => { blocker = net.createServer(); await new Promise<void>((resolve) => blocker.listen(0, STARTUP_HOST, () => resolve())); takenPort = (blocker.address() as AddressInfo).port; }); after(() => new Promise<void>((resolve) => blocker.close(() => resolve()))); it('exits with an error when the port is already in use', async () => { const { code, out, err } = await startServer(takenPort); assert.equal(code, 1, err); assert.match(err, /already in use/); assert.doesNotMatch(out, /Server is running/); }); }); - src/protocols/http.ts (3770 bytes)
import { randomUUID } from 'node:crypto'; import express, { type Request, type Response } from 'express'; import config from '../config.js'; import createMcpServer from '../server.js'; import { isLoopbackHostname } from '../utils.js'; import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; import { ListToolsRequest, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js'; import { createDnsRebindingGuard } from './rebinding.js'; const yieldGenericServerError = (res: Response) => { res.status(500).json({ id: null, jsonrpc: '2.0', error: { code: -32603, message: 'Internal server error' }, }); }; const transports = new Map<string, StreamableHTTPServerTransport>(); const isListToolsRequest = (value: unknown): value is ListToolsRequest => ListToolsRequestSchema.safeParse(value).success; const getTransport = async (request: Request): Promise<StreamableHTTPServerTransport> => { // Check for an existing session const sessionId = request.headers['mcp-session-id'] as string; if (sessionId && transports.has(sessionId)) { return transports.get(sessionId)!; } // We have a special case where we'll permit ListToolsRequest w/o a session ID if (!sessionId && isListToolsRequest(request.body)) { const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, }); const mcpServer = createMcpServer(); await mcpServer.connect(transport); return transport; } let transport: StreamableHTTPServerTransport; if (config.stateless) { // Some contexts (e.g. AgentCore) may prefer or require a stateless transport transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, }); } else { // Otherwise, start a new transport/session transport = new StreamableHTTPServerTransport({ sessionIdGenerator: () => randomUUID(), onsessioninitialized: (sessionId) => { transports.set(sessionId, transport); }, }); } const mcpServer = createMcpServer(); await mcpServer.connect(transport); return transport; }; const createApp = () => { const app = express(); app.use( '/mcp', createDnsRebindingGuard({ allowedHosts: config.allowedHosts, allowedOrigins: config.allowedOrigins, }) ); app.use('/mcp', express.json()); app.all('/mcp', async (req: Request, res: Response) => { try { const transport = await getTransport(req); await transport.handleRequest(req, res, req.body); } catch (error) { console.error(error); if (!res.headersSent) { yieldGenericServerError(res); } } }); app.all('/ping', (req: Request, res: Response) => { res.status(200).json({ message: 'pong' }); }); return app; }; const start = () => { if (!config.ready) { console.error('Invalid configuration'); process.exit(1); } const app = createApp(); const server = app.listen(config.port, config.host); server.on('listening', () => { console.log(`Server is running on http://${config.host}:${config.port}/mcp`); // /mcp has no auth today. Binding past loopback is an easy way to leak quota. if (!isLoopbackHostname(config.host)) { console.warn( `Warning: HTTP transport is bound to ${config.host} and /mcp is unauthenticated. Prefer 127.0.0.1 for local use, or put a reverse proxy with auth in front of this process.` ); } }); server.on('error', (error: NodeJS.ErrnoException) => { const detail = error.code === 'EADDRINUSE' ? `port ${config.port} is already in use` : error.message; console.error(`Unable to start HTTP server: ${detail}`); process.exit(1); }); }; export default { start, createApp }; - src/protocols/index.ts (104 bytes)
export { default as stdioServer } from './stdio.js'; export { default as httpServer } from './http.js'; - src/protocols/rebinding.test.ts (2990 bytes)
import assert from 'node:assert/strict'; import { describe, it } from 'node:test'; import { canonicalizeOrigin, normalizeHost } from './rebinding.js'; describe('canonicalizeOrigin', () => { it('returns the canonical scheme://host[:port] form', () => { assert.equal(canonicalizeOrigin('https://example.com'), 'https://example.com'); assert.equal(canonicalizeOrigin('https://example.com:8443'), 'https://example.com:8443'); assert.equal(canonicalizeOrigin('http://localhost:3000'), 'http://localhost:3000'); }); it('lowercases scheme and host', () => { assert.equal(canonicalizeOrigin('HTTPS://Example.COM'), 'https://example.com'); }); it('drops the default port for the scheme', () => { assert.equal(canonicalizeOrigin('https://example.com:443'), 'https://example.com'); assert.equal(canonicalizeOrigin('http://example.com:80'), 'http://example.com'); }); it('ignores path, query, and fragment', () => { assert.equal(canonicalizeOrigin('https://example.com/a/b?c=d#e'), 'https://example.com'); }); it('returns null for unparseable values', () => { assert.equal(canonicalizeOrigin(''), null); assert.equal(canonicalizeOrigin('not a url'), null); assert.equal(canonicalizeOrigin('example.com'), null); }); }); describe('normalizeHost', () => { it('returns the bare, lowercased hostname', () => { assert.equal(normalizeHost('example.com'), 'example.com'); assert.equal(normalizeHost('Example.COM'), 'example.com'); assert.equal(normalizeHost('127.0.0.1'), '127.0.0.1'); }); it('strips the port', () => { assert.equal(normalizeHost('example.com:8080'), 'example.com'); assert.equal(normalizeHost('example.com:443'), 'example.com'); }); it('unwraps bracketed IPv6 literals', () => { assert.equal(normalizeHost('[::1]'), '::1'); assert.equal(normalizeHost('[::1]:8080'), '::1'); assert.equal(normalizeHost('[2001:DB8::1]:443'), '2001:db8::1'); }); it('returns null for empty or whitespace-only values', () => { assert.equal(normalizeHost(''), null); assert.equal(normalizeHost(' '), null); }); it('returns null for a non-numeric port', () => { assert.equal(normalizeHost('example.com:80evil'), null); assert.equal(normalizeHost('example.com:99999999'), null); }); it('returns null for schemes', () => { assert.equal(normalizeHost('https://example.com'), null); assert.equal(normalizeHost('http://example.com'), null); }); it('returns null for malformed bracketed IPv6 with trailing junk', () => { assert.equal(normalizeHost('[::1]evil.example'), null); assert.equal(normalizeHost('[::1'), null); }); it('returns null when userinfo, path, query, or fragment is present', () => { assert.equal(normalizeHost('[email protected]'), null); assert.equal(normalizeHost('example.com/path'), null); assert.equal(normalizeHost('example.com?q=1'), null); assert.equal(normalizeHost('example.com#frag'), null); }); }); - src/protocols/rebinding.ts (5046 bytes)
import type { NextFunction, Request, RequestHandler, Response } from 'express'; import { isLoopbackHostname } from '../utils.js'; // 403 with a JSON-RPC error and no id, per the MCP Streamable HTTP spec. const sendForbidden = (res: Response, message: string): void => { res.status(403).json({ jsonrpc: '2.0', error: { code: -32600, message }, id: null }); }; const stripBrackets = (hostname: string): string => hostname.replace(/^\[|\]$/g, '').toLowerCase(); // Canonical origin ("scheme://host[:port]", lowercased with the default port // dropped) or null when the value is not a parseable origin. Using URL.origin // makes comparisons case- and default-port-insensitive. export const canonicalizeOrigin = (value: string): string | null => { const trimmed = value.trim(); if (trimmed.length === 0) return null; try { const origin = new URL(trimmed).origin; // URL.origin may be 'null' for opaque origins, e.g. 'blob:'. return origin === 'null' ? null : origin; } catch { return null; } }; /** * Returns the bare, lowercased hostname (port and IPv6 brackets removed), or * null when the value is not a clean "host[:port]". Parsing via URL rejects * malformed authorities (bad ports, embedded userinfo, paths, etc.) by * returning null so they fail closed. * @returns The canonicalized hostname, or null if the value is not a clean "host[:port]". * @example normalizeHost('example.com:8080') === 'example.com' * @example normalizeHost('example.com') === 'example.com' * @example normalizeHost('example.com/path') === null * @example normalizeHost('example.com?q=1') === null * @example normalizeHost('example.com#frag') === null * @example normalizeHost('example.com@user:pass') === null * @example normalizeHost('example.com:80evil') === null * @example normalizeHost('example.com:99999999') === null * @example normalizeHost('[::1]') === '::1' */ export const normalizeHost = (value: string): string | null => { const trimmed = value.trim(); if (trimmed.length === 0) return null; // A Host header carries only "host[:port]"; any path delimiter is malformed. if (trimmed.includes('/') || trimmed.includes('\\')) return null; let url: URL; try { url = new URL(`http://${trimmed}`); } catch { return null; } // A Host header carries only "host[:port]"; anything else is malformed. if (url.username || url.password || url.search || url.hash || url.pathname !== '/') { return null; } return stripBrackets(url.hostname); }; const toNormalizedSet = ( values: string[], normalize: (value: string) => string | null ): Set<string> => { const set = new Set<string>(); for (const value of values) { const normalized = normalize(value); if (normalized !== null) set.add(normalized); } return set; }; const isOriginAllowed = (origin: string, allowedOrigins: Set<string>): boolean => { const trimmed = origin.trim(); if (trimmed.length === 0) return false; let url: URL; try { url = new URL(trimmed); // URL.origin may be 'null' for opaque origins, e.g. 'blob:'. if (url.origin === 'null') return false; } catch { return false; } return isLoopbackHostname(stripBrackets(url.hostname)) || allowedOrigins.has(url.origin); }; const isHostAllowed = (hostHeader: string, allowedHosts: Set<string>): boolean => { const host = normalizeHost(hostHeader); if (host === null) return false; return isLoopbackHostname(host) || allowedHosts.has(host); }; // Builds Express middleware that guards against DNS rebinding: // - Origin is always validated. A request with no Origin header passes through // (non-browser MCP clients omit it), but any present Origin must be loopback // or explicitly allow-listed. // - Host is validated only when allowedHosts is configured (opt-in), so // reverse-proxy / custom-domain deployments are unaffected by default. export const createDnsRebindingGuard = (options: { allowedOrigins: string[]; allowedHosts: string[]; }): RequestHandler => { const allowedOrigins = toNormalizedSet(options.allowedOrigins, canonicalizeOrigin); const allowedHosts = toNormalizedSet(options.allowedHosts, normalizeHost); const enforceHost = allowedHosts.size > 0; return (req: Request, res: Response, next: NextFunction) => { const origin = req.headers.origin; if (origin !== undefined) { // Origin may be undefined (non-browser MCP clients omit it), but any // present Origin must be validated. if (typeof origin !== 'string' || !isOriginAllowed(origin, allowedOrigins)) { sendForbidden(res, 'Forbidden: invalid Origin'); return; } } if (enforceHost) { // Host is validated only when allowedHosts is configured (opt-in), so // reverse-proxy / custom-domain deployments are unaffected by default. const host = req.headers.host; if (typeof host !== 'string' || !isHostAllowed(host, allowedHosts)) { sendForbidden(res, 'Forbidden: invalid Host'); return; } } next(); }; }; - src/protocols/stdio.test.ts (1755 bytes)
import assert from 'node:assert/strict'; import { after, before, describe, it } from 'node:test'; import { fileURLToPath } from 'node:url'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StdioClientTransport, getDefaultEnvironment, } from '@modelcontextprotocol/sdk/client/stdio.js'; import { expectedToolNames, toolNames } from '../testUtils/mcpTestHarness.js'; const entrypoint = fileURLToPath(new URL('../index.ts', import.meta.url)); /** * Spawns the real CLI over stdio, covering argument parsing, server wiring, and * JSON-RPC framing. Runs the source through tsx, so `npm test` needs no build. * * `tools/list` keeps this hermetic: it reaches the API client without issuing a * request. */ describe('stdio transport (real child process)', () => { let client: Client; let transport: StdioClientTransport; let stderr = ''; before(async () => { transport = new StdioClientTransport({ command: process.execPath, args: ['--import', 'tsx', entrypoint], // Startup requires a key. env: { ...getDefaultEnvironment(), BRAVE_API_KEY: 'test-key' }, stderr: 'pipe', }); transport.stderr?.on('data', (chunk: Buffer) => { stderr += chunk.toString(); }); client = new Client({ name: 'stdio-test-client', version: '0.0.0' }); await client.connect(transport); }); after(async () => { await client.close(); }); it('serves the registered tools over stdin/stdout', async () => { const { tools: listedTools } = await client.listTools(); // Both sides read the same registry; guard against an empty one. assert.ok(listedTools.length > 0, stderr); assert.deepEqual(toolNames(listedTools), expectedToolNames, stderr); }); }); - src/protocols/stdio.ts (319 bytes)
import newMcpServer from '../server.js'; import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; const start = async (): Promise<void> => { const transport = new StdioServerTransport(); const mcpServer = newMcpServer(); await mcpServer.connect(transport); }; export default { start }; - src/server.test.ts (2844 bytes)
import assert from 'node:assert/strict'; import { after, before, describe, it } from 'node:test'; import type { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { Ajv2020 } from 'ajv/dist/2020.js'; import { connectTestClient, expectedToolNames, toolNames } from './testUtils/mcpTestHarness.js'; describe('MCP server <-> SDK Client wiring (in-memory)', () => { let client: Client; before(async () => { client = await connectTestClient(); }); after(() => client.close()); it('lists every registered tool with a valid input schema', async () => { const { tools: listedTools } = await client.listTools(); assert.deepEqual(toolNames(listedTools), expectedToolNames); for (const tool of listedTools) { assert.ok(tool.inputSchema, `${tool.name} is missing an inputSchema`); } }); // Asserts ToolAnnotations behavior hints advertised across registered tools. // https://modelcontextprotocol.io/specification/2026-07-28/schema#toolannotations it('marks every tool as a read-only, non-destructive search', async () => { const { tools: listedTools } = await client.listTools(); for (const tool of listedTools) { assert.equal(tool.annotations?.readOnlyHint, true, `${tool.name} should be read-only`); assert.equal( tool.annotations?.destructiveHint, false, `${tool.name} should not be destructive` ); assert.equal(tool.annotations?.idempotentHint, true, `${tool.name} should be idempotent`); assert.equal(tool.annotations?.openWorldHint, true, `${tool.name} should be open-world`); } }); it('advertises valid JSON Schema 2020-12 schemas', async () => { const { tools: listedTools } = await client.listTools(); // Compiling resolves the declared dialect, so a draft-07 tag fails here as // readily as invalid 2020-12 keywords. The SDK does the Zod conversion, so // only the wire format is worth asserting. const ajv = new Ajv2020({ strict: false, validateFormats: false }); for (const tool of listedTools) { assert.doesNotThrow( () => ajv.compile(tool.inputSchema), `${tool.name} has an invalid inputSchema` ); const { outputSchema } = tool; if (outputSchema) { assert.doesNotThrow( () => ajv.compile(outputSchema), `${tool.name} has an invalid outputSchema` ); } } }); it("preserves each output schema's unknown-property policy", async () => { const { tools: listedTools } = await client.listTools(); const additionalProperties = (name: string) => listedTools.find((tool) => tool.name === name)?.outputSchema?.additionalProperties; assert.deepEqual(additionalProperties('brave_place_search'), {}); assert.equal(additionalProperties('brave_image_search'), false); }); }); - src/server.ts (1025 bytes)
import tools from './tools/index.js'; import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import pkg from '../package.json' with { type: 'json' }; import { isToolPermittedByUser } from './config.js'; import enforce2020Dialect from './jsonSchemaDialect.js'; export default function createMcpServer(): McpServer { const mcpServer = new McpServer( { version: pkg.version, name: 'brave-search-mcp-server', title: 'Brave Search MCP Server', }, { capabilities: { logging: {}, tools: { listChanged: false }, }, instructions: `Use this server to search the Web for various types of data via the Brave Search API.`, } ); for (const tool of Object.values(tools)) { // The user may have enabled/disabled this tool at runtime if (!isToolPermittedByUser(tool.name)) continue; tool.register(mcpServer); } // Advertise 2020-12 schemas; the SDK would otherwise emit draft-07 enforce2020Dialect(mcpServer); return mcpServer; } - src/testUtils/agentCore.ts (3579 bytes)
import { readFileSync } from 'node:fs'; import { LATEST_PROTOCOL_VERSION } from '@modelcontextprotocol/sdk/types.js'; /** * Helpers for simulating Amazon Bedrock AgentCore Runtime, which hosts the * image we list on AWS Marketplace. The contract: a stateless streamable-HTTP * server on 0.0.0.0:8000/mcp that accepts a platform-generated Mcp-Session-Id * on every request, including the first. * https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-mcp-protocol-contract.html */ export const AGENTCORE_PORT = 8000; const PLATFORM_SESSION_ID = 'agentcore-0123456789abcdef0123456789abcdef'; type MarketplaceChangeSet = { ChangeSet: { DetailsDocument: { DeliveryOptions: { Details: { EcrDeliveryOptionDetails: { CompatibleServices?: string[]; EnvironmentVariables?: { Name: string; DefaultValue?: string }[]; }; }; }[]; }; }[]; }; /** * The environment variable defaults for the AgentCore delivery option, read from * marketplace-revision-release.json in this repo. That file is the change-set * template Build Release submits to AWS Marketplace after the tests pass, so these * are the defaults the listing will pre-fill. Nothing is fetched from Marketplace or ECR. */ export function agentCoreEnvironment(): Record<string, string> { const changeSet: MarketplaceChangeSet = JSON.parse( readFileSync(new URL('../../marketplace-revision-release.json', import.meta.url), 'utf8') ); const details = changeSet.ChangeSet.flatMap((change) => change.DetailsDocument.DeliveryOptions) .map((option) => option.Details.EcrDeliveryOptionDetails) .find((option) => option.CompatibleServices?.includes('Bedrock-AgentCore')); if (!details) { throw new Error('marketplace-revision-release.json has no Bedrock-AgentCore delivery option'); } return Object.fromEntries( (details.EnvironmentVariables ?? []).flatMap(({ Name, DefaultValue }) => DefaultValue === undefined ? [] : [[Name, DefaultValue]] ) ); } /** * Parses a Streamable HTTP response, which may be plain JSON or an SSE stream * whose last `data:` line carries the JSON-RPC message. */ export async function readJsonRpc(res: Response): Promise<any> { const text = await res.text(); if (!res.headers.get('content-type')?.includes('text/event-stream')) { return JSON.parse(text); } const data = text.split('\n').filter((line) => line.startsWith('data:')); return JSON.parse(data.at(-1)!.slice('data:'.length)); } /** * POSTs a JSON-RPC request to `${baseUrl}/mcp` the way AgentCore forwards it: * carrying a session id the server never issued, and with no assumption that * the server instance has seen an initialize request. */ export async function agentCoreRpc( baseUrl: string, id: number, method: string, params: object = {} ): Promise<{ status: number; sessionId: string | null; body: any }> { const res = await fetch(`${baseUrl}/mcp`, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', 'mcp-session-id': PLATFORM_SESSION_ID, 'mcp-protocol-version': LATEST_PROTOCOL_VERSION, }, body: JSON.stringify({ jsonrpc: '2.0', id, method, params }), }); return { status: res.status, sessionId: res.headers.get('mcp-session-id'), body: await readJsonRpc(res), }; } export const initializeParams = { protocolVersion: LATEST_PROTOCOL_VERSION, capabilities: {}, clientInfo: { name: 'agentcore-test', version: '0.0.0' }, }; - src/testUtils/mcpTestHarness.ts (3366 bytes)
import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv-provider.js'; import { Ajv2020 } from 'ajv/dist/2020.js'; import { after, before } from 'node:test'; import createMcpServer from '../server.js'; import tools from '../tools/index.js'; /** * Sorts the names of `listed` tools (e.g. a `tools/list` result) for an * order-independent comparison against `expectedToolNames`. */ export function toolNames(listed: { name: string }[]): string[] { return listed.map((tool) => tool.name).sort(); } /** The sorted names of every registered tool. */ export const expectedToolNames = toolNames(Object.values(tools)); type FetchHandler = (url: URL, init?: RequestInit) => unknown; /** * Connects a real SDK Client to a fresh McpServer over an in-memory transport * pair, exercising the real registerTool/callTool wiring. * * Tear down with `client.close()`; it cascades to the server. */ export async function connectTestClient(): Promise<Client> { const mcpServer = createMcpServer(); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); const client = new Client( { name: 'test-client', version: '0.0.0' }, { // Match the server's advertised dialect, including coordinate prefixItems. jsonSchemaValidator: new AjvJsonSchemaValidator( new Ajv2020({ strict: false, validateFormats: false }) ), } ); await Promise.all([mcpServer.connect(serverTransport), client.connect(clientTransport)]); return client; } /** * Replaces global.fetch with a stub that resolves Brave API requests via * `handler`, keyed on the request's pathname. A returned `Response` is used * as-is; anything else is served as a 200 JSON body. Requests to any other * origin (e.g. a local HTTP server under test) pass through to the real fetch. * Returns a restore function. */ export function stubFetch(handler: FetchHandler): () => void { const originalFetch = globalThis.fetch; globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { const url = new URL(input instanceof Request ? input.url : input.toString()); if (url.origin !== 'https://api.search.brave.com') { return originalFetch(input, init); } const body = handler(url, init); if (body === undefined) { throw new Error(`Unmocked Brave API request: ${url.pathname}`); } if (body instanceof Response) { return body; } return new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' }, }); }) as typeof fetch; return () => { globalThis.fetch = originalFetch; }; } /** * Registers before/after hooks on the enclosing `describe` block that stub * the Brave API via `responder` and connect a fresh test client, tearing * both down afterward. Returns a getter for the connected client. */ export function useTestClient(responder: FetchHandler): () => Client { let client: Client; let restoreFetch: () => void; before(async () => { restoreFetch = stubFetch(responder); client = await connectTestClient(); }); after(async () => { restoreFetch(); await client.close(); }); return () => client; } - src/tools/answers/format.test.ts (4168 bytes)
import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import { describe, it } from 'node:test'; import { readChatCompletionStream } from '../../BraveAPI/sse.js'; import { formatAnswer } from './format.js'; const fixtureDeltas = async (file: string) => ( await readChatCompletionStream( new Response(readFileSync(new URL(`./fixtures/${file}`, import.meta.url), 'utf8')) ) ).deltas; const singleSearch = { research: false }; const research = { research: true }; describe('formatAnswer', () => { it('strips usage metadata', () => { assert.equal( formatAnswer(['Hello world ', '<usage>{"X-Request-Total-Cost":0}</usage>'], singleSearch), 'Hello world' ); }); it('returns null when only metadata remains', () => { assert.equal( formatAnswer([' ', '<usage>{"X-Request-Total-Cost":0}</usage>'], singleSearch), null ); }); it('keeps tags written inside single-search answer text', () => { const deltas = [ 'Use `<answer>42</answer>` as the XML value. Ask the model to wrap it: `<ans', 'wer>42</answer>`.\n```html\n<progress>50%</progress>\n<thinking>{"step":1}</thinking>\n```', ]; assert.equal(formatAnswer(deltas, singleSearch), deltas.join('')); }); it('returns the last research answer, unwrapped from its JSON payload', () => { const deltas = [ '<queries>{"queries":["q"]}</queries>', '<answer>{"answer":"Draft."}</answer>', '<answer>{"answer":"Final."}</answer>', '<usage>{}</usage>', '<progress>{}</progress>', ]; assert.equal(formatAnswer(deltas, research), 'Final.'); }); it('returns a research answer as written, keeping tags inside it', () => { const answer = 'Wrap the result as `<answer>42</answer>`; <progress>50%</progress> shows a bar.'; const deltas = [`<answer>${JSON.stringify({ answer })}</answer>`, '<usage>{}</usage>']; assert.equal(formatAnswer(deltas, research), answer); }); it('returns a non-JSON answer block as-is', () => { assert.equal(formatAnswer(['<answer>Final answer.</answer>'], research), 'Final answer.'); }); it('returns null for research scaffolding without an answer', () => { const deltas = [ '<queries>{"queries":["q"]}</queries>', '<analyzing>{"urls":3}</analyzing>', '<thinking>{"urls_selected":[]}</thinking>', '<blindspots>{}</blindspots>', '<progress>{}</progress>', ]; assert.equal(formatAnswer(deltas, research), null); }); it('converts citations to footnotes with snippets on one line', () => { const deltas = [ 'Claim.', '<citation>{"number":1,"url":"https://www.a.com/x","snippet":"First\\n## line."}</citation>', '<citation>{"number":2,"url":"https://b.com"}</citation>', ' More.', ]; assert.equal( formatAnswer(deltas, singleSearch), 'Claim.[^1][^2] More.\n\n[^1]: [a.com](https://www.a.com/x) — First ## line.\n[^2]: [b.com](https://b.com)' ); }); it('drops citations without a number or web URL', () => { const deltas = [ 'Claim.', '<citation>{"number":1,"url":"javascript:alert(1)"}</citation>', '<citation>{"url":"https://a.com"}</citation>', '<citation>not json</citation>', ]; assert.equal(formatAnswer(deltas, singleSearch), 'Claim.'); }); it('percent-encodes unmatched parentheses in citation links', () => { const deltas = ['Claim.', '<citation>{"number":1,"url":"https://a.com/x)y"}</citation>']; assert.equal( formatAnswer(deltas, singleSearch), 'Claim.[^1]\n\n[^1]: [a.com](https://a.com/x%29y)' ); }); it('gives every citation marker in a real response a footnote', async () => { const text = formatAnswer(await fixtureDeltas('citations.sse'), singleSearch) ?? ''; const markers = new Set([...text.matchAll(/\[\^(\d+)\](?!:)/g)].map((match) => match[1])); const definitions = text.split('\n').filter((line) => /^\[\^\d+\]: /.test(line)); assert.equal(markers.size, 3); assert.deepEqual( definitions.map((line) => line.match(/^\[\^(\d+)\]/)?.[1]), [...markers].sort() ); }); }); - src/tools/answers/format.ts (4011 bytes)
import { encodeUnmatchedParentheses, getDisplayHostname } from '../urls.js'; /** * Answers streams interleave answer text with tagged payloads such as * <usage>{...}</usage>. Each tag arrives as its own delta, while answer text is * split across deltas at arbitrary points, so only a delta that is exactly one * known tag is read as markup; tags written in the answer text are kept. * Research mode wraps its final answer in <answer>; single-search mode streams * the answer directly, with <citation> tags inline. */ const TAG_PATTERN = /^<(answer|citation|usage|queries|analyzing|thinking|progress|blindspots)>([\s\S]*)<\/\1>$/; type Tag = { name: string; payload: string }; type CitationPayload = { number?: unknown; url?: unknown; snippet?: unknown }; function parseJson<T>(text: string): T | undefined { try { return JSON.parse(text) as T; } catch { return undefined; } } /** The trimmed value if it is an http(s) URL, so links never carry other schemes. */ function parseWebUrl(value: unknown): string | undefined { const url = typeof value === 'string' ? value.trim() : ''; return /^https?:\/\//i.test(url) ? url : undefined; } /** Collapses whitespace so payload text stays on one markdown line. */ function collapseWhitespace(value: unknown): string { return typeof value === 'string' ? value.replace(/\s+/g, ' ').trim() : ''; } /** The tag a delta consists of, or undefined when the delta is answer text. */ function parseTag(delta: string): Tag | undefined { const match = TAG_PATTERN.exec(delta); return match ? { name: match[1], payload: match[2].trim() } : undefined; } /** The last <answer> payload, unwrapped from its `{"answer": ...}` JSON. */ function findLastResearchAnswer(deltas: string[]): string | undefined { let answer: string | undefined; for (const delta of deltas) { const tag = parseTag(delta); if (tag?.name !== 'answer') continue; const payload = parseJson<{ answer?: unknown }>(tag.payload); answer = typeof payload?.answer === 'string' ? payload.answer : tag.payload; } return answer; } /** Records a citation's footnote and returns its marker; drops citations lacking a number or web URL. */ function addCitationFootnote(payload: string, footnotes: Map<number, string>): string { const { number, url, snippet }: CitationPayload = parseJson<CitationPayload>(payload) ?? {}; const href = parseWebUrl(url); if (typeof number !== 'number' || href === undefined) return ''; const link = `[${getDisplayHostname(href)}](${encodeUnmatchedParentheses(href)})`; const excerpt = collapseWhitespace(snippet); footnotes.set(number, `[^${number}]: ${link}${excerpt ? ` — ${excerpt}` : ''}`); return `[^${number}]`; } /** Joins the streamed text as markdown, rendering citations as footnotes. */ function formatStreamedText(deltas: string[]): string { const footnotes = new Map<number, string>(); let body = ''; for (const delta of deltas) { const tag = parseTag(delta); switch (tag?.name) { // <answer> only wraps research answers; anywhere else it is answer text. case undefined: case 'answer': body += delta; break; case 'citation': body += addCitationFootnote(tag.payload, footnotes); break; // The remaining tags are metadata such as <usage>. } } if (footnotes.size === 0) return body; const definitions = [...footnotes.entries()] .sort(([a], [b]) => a - b) .map(([, footnote]) => footnote); return `${body.trimEnd()}\n\n${definitions.join('\n')}`; } /** * Formats the streamed deltas as markdown, or returns null if no answer remains. * In research mode the last <answer> is returned as written. */ export function formatAnswer(deltas: string[], { research }: { research: boolean }): string | null { const answer = (research ? findLastResearchAnswer(deltas) : undefined) ?? formatStreamedText(deltas); const formatted = answer.trim(); return formatted.length > 0 ? formatted : null; } - src/tools/answers/index.test.ts (5761 bytes)
import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import { describe, it } from 'node:test'; import { useTestClient } from '../../testUtils/mcpTestHarness.js'; import { name } from './index.js'; // Real Answers API responses, trimmed to a few chunks with their framing and // payload shapes left intact. research-incomplete.sse is research.sse without // its <answer> chunk. const fixture = (file: string) => readFileSync(new URL(`./fixtures/${file}`, import.meta.url), 'utf8'); const sse = (body: string) => new Response(body, { headers: { 'content-type': 'text/event-stream; charset=utf-8' }, }); const K2_ANSWER = '**K2** is the second highest mountain in the world, standing at **8,611 meters (28,251 feet)** above sea level.'; // Each test asks a question naming the upstream response it should receive. const upstream: Record<string, () => Response> = { 'single-search': () => sse(fixture('single-search.sse')), truncated: () => sse(fixture('single-search.sse').replace('"finish_reason":"stop"', '"finish_reason":"length"')), citations: () => sse(fixture('citations.sse')), research: () => sse(fixture('research.sse')), 'research-incomplete': () => sse(fixture('research-incomplete.sse')), 'api-error': () => new Response(fixture('error-research-citations.json'), { status: 422, statusText: 'Unprocessable Entity', headers: { 'content-type': 'application/json' }, }), }; const ask = (query: string) => ({ query }); const textOf = (result: Record<string, unknown>) => (result.content as Array<{ type: string; text: string }>)[0]?.text ?? ''; describe(name, () => { const requests: Record<string, unknown>[] = []; const getClient = useTestClient((url, init) => { if (url.pathname !== '/res/v1/chat/completions') return undefined; const body = JSON.parse(String(init?.body)) as { messages: Array<{ content: string }> }; requests.push(body); return upstream[body.messages[0].content]?.(); }); it('returns a single-search answer without usage metadata', async () => { const result = await getClient().callTool({ name, arguments: ask('single-search') }); assert.equal(result.isError, false, textOf(result)); assert.equal(textOf(result), K2_ANSWER); }); it('notes an answer cut off at the completion token limit', async () => { const result = await getClient().callTool({ name, arguments: ask('truncated') }); const text = textOf(result); assert.equal(result.isError, false, text); assert.ok(text.startsWith(`${K2_ANSWER}\n\n`), text); assert.match(text, /\n\nNote: This answer was cut off at the completion token limit\./); }); it('forwards options and sends the query as the single user message', async () => { await getClient().callTool({ name, arguments: { ...ask('single-search'), enable_citations: true, country: 'US' }, }); // Exact, so the query field and an unset model never reach the API. assert.deepEqual(requests.at(-1), { enable_citations: true, country: 'US', messages: [{ role: 'user', content: 'single-search' }], stream: true, }); }); it('sends progress notifications while waiting for the answer', async () => { const progress: unknown[] = []; const result = await getClient().callTool( { name, arguments: ask('single-search') }, undefined, { onprogress: (notification) => progress.push(notification), } ); assert.equal(result.isError, false, textOf(result)); assert.equal(progress.length, 1); }); // Footnote structure is covered in format.test.ts; this checks the tool renders it. it('renders citations as markdown footnotes', async () => { const result = await getClient().callTool({ name, arguments: { ...ask('citations'), enable_citations: true }, }); const text = textOf(result); assert.equal(result.isError, false, text); assert.doesNotMatch(text, /<citation>|<usage>/); assert.match(text, /\*\*11 times\*\* as of mid-2026\.\[\^1\]/); assert.match( text, /\n\[\^1\]: \[energy-solutions\.co\]\(https:\/\/energy-solutions\.co\/articles\/sub\/fusion-energy-breakthroughs-2026\) — / ); }); it('returns only the synthesized research answer', async () => { const result = await getClient().callTool({ name, arguments: { ...ask('research'), enable_research: true }, }); const text = textOf(result); assert.equal(result.isError, false, text); assert.match(text, /^Tokamak and stellarator are two primary designs/); assert.match(text, /\n### 1\. Geometry and Magnetic Field Generation\n/); assert.doesNotMatch(text, /<\w+>/); }); it('reports research that ends without an answer', async () => { const result = await getClient().callTool({ name, arguments: { ...ask('research-incomplete'), enable_research: true }, }); assert.equal(result.isError, true); assert.match(textOf(result), /^Research did not complete/); }); it("passes the API's validation errors through", async () => { const result = await getClient().callTool({ name, arguments: { ...ask('api-error'), enable_research: true, enable_citations: true }, }); assert.equal(result.isError, true); assert.match(textOf(result), /^422 Unprocessable Entity\n/); assert.match(textOf(result), /Research mode doesn't support 'enable_citations' option/); }); it('rejects a missing query before calling the API', async () => { const before = requests.length; const result = await getClient().callTool({ name, arguments: {} }); assert.equal(result.isError, true); assert.equal(requests.length, before); }); }); - src/tools/answers/index.ts (4679 bytes)
import type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js'; import type { CallToolResult, ServerNotification, ServerRequest, ToolAnnotations, } from '@modelcontextprotocol/sdk/types.js'; import { type McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import { streamChatCompletion } from '../../BraveAPI/chatCompletions.js'; import { AnswersInputSchema, MAX_RESEARCH_SECONDS, type AnswersInput } from './schemas/input.js'; import { formatAnswer } from './format.js'; export const name = 'brave_answers'; const SINGLE_SEARCH_TIMEOUT_MS = 90_000; // A minute of headroom above the largest research budget the API accepts. const RESEARCH_TIMEOUT_MS = (MAX_RESEARCH_SECONDS + 60) * 1000; const PROGRESS_INTERVAL_MS = 5_000; const NO_ANSWER_MESSAGE = 'No answer content was returned by the Answers API.'; const INCOMPLETE_RESEARCH_MESSAGE = 'Research did not complete with a synthesized answer. Try lowering research_maximum_number_of_iterations or increasing research_maximum_number_of_seconds.'; const TRUNCATED_ANSWER_NOTE = 'Note: This answer was cut off at the completion token limit. Increase max_completion_tokens for a complete answer.'; type ToolExtra = RequestHandlerExtra<ServerRequest, ServerNotification>; export const annotations: ToolAnnotations = { title: 'Brave Answers', readOnlyHint: true, // destructiveHint and idempotentHint are meaningful only when readOnlyHint is false. // https://modelcontextprotocol.io/specification/2026-07-28/schema#toolannotations destructiveHint: false, idempotentHint: true, openWorldHint: true, }; export const description = ` Generates AI-grounded answers backed by real-time Brave Search using the Answers API. Returns the finished answer as markdown. Preferred replacement for brave_summarizer: Pass your question in query instead of chaining brave_web_search (summary: true) + brave_summarizer. When to use: - When you need a finished, web-grounded answer rather than raw search results - For quick factual Q&A with optional citations (enable_citations), returned as markdown footnotes - For deeper multi-search research on complex topics (enable_research) Two modes: - Single-search (default): Fast grounded answer from one search. Supports enable_citations. - Research (enable_research=true): Iterative multi-search synthesis. Slower; may take up to several minutes. Requires an Answers plan. See https://api-dashboard.search.brave.com/app/subscriptions/subscribe `.trim(); /** * Sends a progress notification now and every few seconds until stopped, so * clients that reset their request timeout on progress keep waiting. */ function startProgressPings(extra: ToolExtra): () => void { const progressToken = extra._meta?.progressToken; if (progressToken === undefined) return () => {}; let progress = 0; const ping = () => { progress += 1; // Runs on a timer, so a rejection here would be unhandled and stop the process. extra .sendNotification({ method: 'notifications/progress', params: { progressToken, progress, message: 'Waiting for answer…' }, }) .catch(() => {}); }; ping(); const interval = setInterval(ping, PROGRESS_INTERVAL_MS); return () => clearInterval(interval); } export const execute = async (params: AnswersInput, extra: ToolExtra): Promise<CallToolResult> => { const stopProgressPings = startProgressPings(extra); const { query, ...options } = params; const research = params.enable_research === true; try { const { deltas, finishReason } = await streamChatCompletion( { ...options, messages: [{ role: 'user', content: query }] }, { timeoutMs: research ? RESEARCH_TIMEOUT_MS : SINGLE_SEARCH_TIMEOUT_MS, signal: extra.signal, } ); const answer = formatAnswer(deltas, { research }); if (answer === null) { const message = research ? INCOMPLETE_RESEARCH_MESSAGE : NO_ANSWER_MESSAGE; return { content: [{ type: 'text', text: message }], isError: true }; } const text = finishReason === 'length' ? `${answer}\n\n${TRUNCATED_ANSWER_NOTE}` : answer; return { content: [{ type: 'text', text }], isError: false }; } finally { stopProgressPings(); } }; export const register = (mcpServer: McpServer) => { mcpServer.registerTool( name, { title: name, description: description, inputSchema: AnswersInputSchema, annotations: annotations, }, execute ); }; export default { name, description, annotations, inputSchema: AnswersInputSchema.shape, execute, register, }; - src/tools/answers/schemas/input.ts (4427 bytes)
import { z } from 'zod'; /** * Keep up-to-date with documentation: * https://api-dashboard.search.brave.com/api-reference/ai/answers */ /** The largest research time budget the API accepts. */ export const MAX_RESEARCH_SECONDS = 300; const UserLocationApproximateSchema = z.object({ city: z .string() .optional() .describe('Free text input for the city of the user, e.g. "San Francisco".'), country: z .string() .optional() .describe('The two-letter ISO country code of the user, e.g. "US".'), region: z .string() .optional() .describe('Free text input for the region of the user, e.g. "California".'), timezone: z .string() .optional() .describe('The IANA timezone of the user, e.g. "America/Los_Angeles".'), }); const UserLocationSchema = z.object({ type: z .literal('approximate') .optional() .describe('The type of location approximation. Only "approximate" is supported.'), approximate: UserLocationApproximateSchema, }); const WebSearchOptionsSchema = z .object({ search_context_size: z .enum(['low', 'medium', 'high']) .describe('Amount of search context to retrieve for grounding.') .optional(), user_location: UserLocationSchema.optional().describe( 'Approximate location parameters to refine search results based on geography.' ), }) .describe( 'OpenAI-compatible web search options: search context size and approximate user location.' ); export const AnswersInputSchema = z.object({ query: z .string() .min(1) .describe('The question to answer. Sent to the Answers API as the single user message.'), model: z .enum(['brave-pro', 'brave']) .optional() .describe('The Answers model to use. Omit to use the API default.'), max_completion_tokens: z .number() .int() .positive() .describe( 'Upper bound on completion tokens. An answer cut off at this limit ends with a note saying so.' ) .optional(), web_search_options: WebSearchOptionsSchema.optional(), country: z.string().optional().describe('Search country (2-letter country code or "ALL").'), language: z.string().optional().describe('Response language code, e.g. "en".'), safesearch: z.enum(['off', 'moderate', 'strict']).optional().describe('Search safety level.'), // Accepted because the API documents it, but no response to a request with // enable_entities, across varied list-style queries, has contained entity // markup, so the response is not parsed for it. The Summarizer's entities // (enum_start/enum_item/enum_end) suggest a shape, but nothing confirms that // Answers would use it; build any handling from a real response. enable_entities: z .boolean() .optional() .describe( 'Request inline entity tags in the answer. Not supported in research mode. The API has not been observed to return entity tags, so this may have no effect.' ), enable_citations: z .boolean() .optional() .describe( 'Include inline citations, rendered as markdown footnotes. Not supported in research mode.' ), enable_research: z .boolean() .optional() .describe( 'Answer with iterative multi-search research instead of a single search. Slower; may take several minutes.' ), research_maximum_number_of_tokens_per_query: z .number() .int() .min(1024) .max(16384) .describe('Research mode only. Maximum tokens per research query (1024-16384).') .optional(), research_maximum_number_of_queries: z .number() .int() .min(1) .max(50) .describe('Research mode only. Maximum total search queries during research (1-50).') .optional(), research_maximum_number_of_iterations: z .number() .int() .min(1) .max(5) .describe('Research mode only. Maximum research iterations (1-5).') .optional(), research_maximum_number_of_seconds: z .number() .int() .min(1) .max(MAX_RESEARCH_SECONDS) .describe(`Research mode only. Research time budget in seconds (1-${MAX_RESEARCH_SECONDS}).`) .optional(), research_maximum_number_of_results_per_query: z .number() .int() .min(1) .max(60) .describe( 'Research mode only. Maximum results per search query during research (1-60). The API default is 30.' ) .optional(), }); export type AnswersInput = z.infer<typeof AnswersInputSchema>; - src/tools/images/index.test.ts (2393 bytes)
import assert from 'node:assert/strict'; import { describe, it } from 'node:test'; import { useTestClient } from '../../testUtils/mcpTestHarness.js'; import { name } from './index.js'; describe(name, () => { const getClient = useTestClient((url) => { if (url.pathname === '/res/v1/images/search') { return { type: 'images', query: { original: 'brave browser' }, results: [ { type: 'image_result', title: 'Brave Browser Logo', url: 'https://example.com/logo.png', page_fetched: '2024-01-01T00:00:00Z', confidence: 'high', properties: { url: 'https://example.com/logo-full.png', width: 512, height: 512, }, }, ], extra: { might_be_offensive: false }, }; } }); it('returns image results for a simple query', async () => { const result = await getClient().callTool({ name, arguments: { query: 'brave browser' } }); assert.equal(result.isError ?? false, false, JSON.stringify(result.content)); assert.deepEqual(result.structuredContent, { type: 'object', items: [ { title: 'Brave Browser Logo', url: 'https://example.com/logo.png', page_fetched: '2024-01-01T00:00:00Z', confidence: 'high', properties: { url: 'https://example.com/logo-full.png', width: 512, height: 512, }, }, ], count: 1, might_be_offensive: false, }); }); }); describe(`${name} (malformed upstream response)`, () => { const getClient = useTestClient((url) => { if (url.pathname === '/res/v1/images/search') { return { type: 'images', query: { original: 'brave browser' }, results: [], // `might_be_offensive` is required by the output schema; omitting it // simulates an upstream response that fails validation. extra: {}, }; } }); it('surfaces the validation failure as an error result', async () => { const result = await getClient().callTool({ name, arguments: { query: 'brave browser' } }); assert.equal(result.isError, true); assert.ok( JSON.stringify(result.content).includes('might_be_offensive'), JSON.stringify(result.content) ); }); }); - src/tools/images/index.ts (2725 bytes)
import type { TextContent, ToolAnnotations } from '@modelcontextprotocol/sdk/types.js'; import params, { type QueryParams } from './schemas/input.js'; import API from '../../BraveAPI/index.js'; import type { ImageResult } from './types.js'; import OutputSchema, { SimplifiedImageResultSchema } from './schemas/output.js'; import { z } from 'zod'; import { type McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; export const name = 'brave_image_search'; export const annotations: ToolAnnotations = { title: 'Brave Image Search', readOnlyHint: true, // destructiveHint and idempotentHint are meaningful only when readOnlyHint is false. // https://modelcontextprotocol.io/specification/2026-07-28/schema#toolannotations destructiveHint: false, idempotentHint: true, openWorldHint: true, }; export const description = ` Performs an image search using the Brave Search API. Helpful for when you need pictures of people, places, things, graphic design ideas, art inspiration, and more. When relaying results in a markdown environment, it may be helpful to include images in the results (e.g., ). `; export const execute = async (params: QueryParams) => { const response = await API.issueRequest<'images'>('images', params); const items = response.results.map(simplifySchemaForLLM).filter((o) => o !== null); const structuredContent = OutputSchema.safeParse({ type: 'object', items, count: items.length, might_be_offensive: response.extra.might_be_offensive, }); const payload = structuredContent.success ? structuredContent.data : structuredContent.error.flatten(); return { content: [{ type: 'text', text: JSON.stringify(payload) } as TextContent], isError: !structuredContent.success, structuredContent: payload, }; }; export const register = (mcpServer: McpServer) => { mcpServer.registerTool( name, { title: name, description: description, inputSchema: params, outputSchema: OutputSchema, annotations: annotations, }, execute ); }; function simplifySchemaForLLM( result: ImageResult ): z.infer<typeof SimplifiedImageResultSchema> | null { const parsed = SimplifiedImageResultSchema.safeParse({ title: result.title, url: result.url, page_fetched: result.page_fetched, confidence: result.confidence, properties: { url: result.properties?.url, width: result.properties?.width, height: result.properties?.height, }, }); return parsed.success ? parsed.data : null; } export default { name, description, annotations, inputSchema: params.shape, outputSchema: OutputSchema, execute, register, }; - src/tools/images/schemas/input.ts (1493 bytes)
import { z } from 'zod'; export const params = z.object({ query: z .string() .min(1) .max(400) .refine((str) => str.split(/\s+/).length <= 50, 'Query cannot exceed 50 words') .describe( "The user's search query. Query cannot be empty. Limited to 400 characters and 50 words." ), country: z .string() .default('US') .describe( 'Search query country, where the results come from. The country string is limited to 2 character country codes of supported countries.' ) .optional(), search_lang: z .string() .default('en') .describe( 'Search language preference. The 2 or more character language code for which the search results are provided.' ) .optional(), count: z .int() .min(1) .max(200) .default(50) .describe( 'Number of results (1-200, default 50). Image Search is not paginated — raise `count` if you need more results. There is no `offset` parameter.' ) .optional(), safesearch: z .union([z.literal('off'), z.literal('strict')]) .default('strict') .describe( "Filters search results for adult content. The following values are supported: 'off' - No filtering. 'strict' - Drops all adult content from search results." ) .optional(), spellcheck: z .boolean() .default(true) .describe('Whether to spellcheck provided query.') .optional(), }); export type QueryParams = z.infer<typeof params>; export default params; - src/tools/images/schemas/output.ts (597 bytes)
import { z } from 'zod'; import { ConfidenceSchema, ExtraSchema } from './response.js'; export const SimplifiedImageResultSchema = z.object({ title: z.string(), url: z.url(), page_fetched: z.iso.datetime(), confidence: ConfidenceSchema, properties: z.object({ url: z.url(), width: z.int().positive(), height: z.int().positive(), }), }); const OutputSchema = z.object({ type: z.literal('object'), items: z.array(SimplifiedImageResultSchema), count: z.int().nonnegative(), might_be_offensive: ExtraSchema.shape.might_be_offensive, }); export default OutputSchema; - src/tools/images/schemas/response.ts (367 bytes)
import { z } from 'zod'; /** * https://api-dashboard.search.brave.com/app/documentation/image-search/responses */ export const ConfidenceSchema = z .enum(['low', 'medium', 'high']) .describe('The confidence level of the result.'); export const ExtraSchema = z.object({ might_be_offensive: z.boolean().describe('Whether the image might be offensive.'), }); - src/tools/images/types.ts (2582 bytes)
export interface ImageSearchApiResponse { /** The type of search API result. The value is always images. */ type: 'images'; /** Image search query string. */ query: Query; /** The list of image results for the given query. */ results: ImageResult[]; /** Additional information about the image search results. */ extra: Extra; } interface Query { /** The original query that was requested. */ original: string; /** The altered query by the spellchecker. This is the query that is used to search. */ altered?: string; /** Whether the spellchecker is enabled or disabled. */ spellcheck_off?: boolean; /** The value is true if the lack of results is due to a strict safesearch setting. Adult content relevant to the query was found, but was blocked by safesearch. */ show_strict_warning?: string; } export interface ImageResult { /** The type of image search API result. The value is always image_result. */ type: 'image_result'; /** The title of the image. */ title?: string; /** The original page URL where the image was found. */ url?: string; /** The source domain where the image was found. */ source?: string; /** The ISO date time when the page was last fetched. The format is YYYY-MM-DDTHH:MM:SSZ. */ page_fetched?: string; /** The thumbnail for the image. */ thumbnail?: Thumbnail; /** Metadata for the image. */ properties?: Properties; /** Aggregated information on the URL associated with the image search result. */ meta_url?: MetaUrl; /** The confidence level for the image result. */ confidence?: 'low' | 'medium' | 'high'; } interface Thumbnail { /** The served URL of the image. */ src?: string; /** The width of the thumbnail. */ width?: number; /** The height of the thumbnail. */ height?: number; } interface Properties { /** The image URL. */ url?: string; /** The lower resolution placeholder image URL. */ placeholder?: string; /** The width of the image. */ width?: number; /** The height of the image. */ height?: number; } interface MetaUrl { /** The protocol scheme extracted from the URL. */ scheme?: string; /** The network location part extracted from the URL. */ netloc?: string; /** The lowercased domain name extracted from the URL. */ hostname?: string; /** The favicon used for the URL. */ favicon?: string; /** The hierarchical path of the URL useful as a display string. */ path?: string; } interface Extra { /** Indicates whether the image search results might contain offensive content. */ might_be_offensive: boolean; } - src/tools/index.ts (625 bytes)
import WebSearchTool from './web/index.js'; import LocalSearchTool from './local/index.js'; 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'; import PlaceSearchTool from './place_search/index.js'; import AnswersTool from './answers/index.js'; export default { WebSearchTool, LocalSearchTool, VideoSearchTool, ImageSearchTool, NewsSearchTool, SummarizerTool, LlmContextTool, PlaceSearchTool, AnswersTool, }; - src/tools/llm_context/index.test.ts (2067 bytes)
import assert from 'node:assert/strict'; import { describe, it } from 'node:test'; import { useTestClient } from '../../testUtils/mcpTestHarness.js'; import { name } from './index.js'; describe(name, () => { const getClient = useTestClient((url) => { if (url.pathname === '/res/v1/llm/context') { return { grounding: { generic: [ { url: 'https://search.brave.com/', title: 'Brave Search', snippets: ['Brave is a privacy-focused browser and search engine.'], }, ], map: [], }, sources: { 'https://search.brave.com/': { title: 'Brave Search' }, }, }; } }); it('returns grounding content for a simple query', async () => { const result = await getClient().callTool({ name, arguments: { query: 'brave browser' } }); assert.equal(result.isError ?? false, false, JSON.stringify(result.content)); assert.deepEqual(result.structuredContent, { grounding: { generic: [ { url: 'https://search.brave.com/', title: 'Brave Search', snippets: ['Brave is a privacy-focused browser and search engine.'], }, ], map: [], }, sources: { 'https://search.brave.com/': { title: 'Brave Search' }, }, }); }); }); describe(`${name} (malformed upstream response)`, () => { const getClient = useTestClient((url) => { if (url.pathname === '/res/v1/llm/context') { // `sources` is required by the output schema; omitting it simulates // an upstream response that fails validation. return { grounding: { generic: [], map: [] }, }; } }); it('surfaces the validation failure as an error result', async () => { const result = await getClient().callTool({ name, arguments: { query: 'brave browser' } }); assert.equal(result.isError, true); assert.ok(JSON.stringify(result.content).includes('sources'), JSON.stringify(result.content)); }); }); - src/tools/llm_context/index.ts (2835 bytes)
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', readOnlyHint: true, // destructiveHint and idempotentHint are meaningful only when readOnlyHint is false. // https://modelcontextprotocol.io/specification/2026-07-28/schema#toolannotations destructiveHint: false, idempotentHint: true, 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, outputSchema: LlmContextSearchApiResponseSchema, annotations: annotations, }, execute ); }; export default { name, description, annotations, inputSchema: LlmContextInputSchema.shape, outputSchema: LlmContextSearchApiResponseSchema, execute, register, }; - src/tools/llm_context/schemas/input.ts (7856 bytes)
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', 'ja', '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<typeof LlmContextInputSchema>; export type LlmQueryParams = z.infer<typeof RequestParamsSchema>; export type LlmRequestHeaders = z.infer<typeof RequestHeadersSchema>; - src/tools/llm_context/schemas/output.ts (2981 bytes)
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<typeof LlmContextSearchApiResponseSchema>; - src/tools/local/formatOpeningHours.test.ts (4660 bytes)
import assert from 'node:assert/strict'; import { describe, it } from 'node:test'; import { formatOpeningHours } from './index.js'; import type { DayOpeningHours, OpeningHours } from './types.js'; const day = (full_name: string, opens: string, closes: string): DayOpeningHours => ({ abbr_name: full_name.slice(0, 3), full_name, opens, closes, }); /** * Captured from a real `/res/v1/local/pois` response (Zuni Café, San Francisco). * Exercises the two properties that matter most in production payloads: * - `current_day` holding two intervals (lunch service and dinner service) * - `days` being an array-of-arrays, where a day may hold multiple intervals * Note that `days` excludes whichever day is reported as `current_day`, and * omits closed days entirely (Zuni Café is closed Mondays). */ const splitServiceHours: OpeningHours = { current_day: [day('Friday', '11:00', '15:00'), day('Friday', '17:00', '21:30')], days: [ [day('Tuesday', '17:00', '21:30')], [day('Wednesday', '17:00', '21:30')], [day('Thursday', '17:00', '21:30')], [day('Saturday', '11:00', '15:00'), day('Saturday', '17:00', '21:30')], [day('Sunday', '11:00', '15:00'), day('Sunday', '17:00', '21:30')], ], }; describe('formatOpeningHours', () => { it('formats a real split-service payload', () => { assert.deepEqual(formatOpeningHours(splitServiceHours), { 'today (friday)': '11:00-15:00, 17:00-21:30', tuesday: '17:00-21:30', wednesday: '17:00-21:30', thursday: '17:00-21:30', saturday: '11:00-15:00, 17:00-21:30', sunday: '11:00-15:00, 17:00-21:30', }); }); it('labels the current day distinctly from the rest of the week', () => { const result = formatOpeningHours(splitServiceHours)!; assert.ok('today (friday)' in result, 'current day should be labelled "today (<day>)"'); assert.ok(!('friday' in result), 'current day should not also appear under its bare name'); }); it('lowercases day names supplied in title case', () => { const result = formatOpeningHours({ current_day: [day('Monday', '09:00', '17:00')], days: [[day('Tuesday', '09:00', '17:00')]], })!; assert.deepEqual(Object.keys(result), ['today (monday)', 'tuesday']); }); it('joins multiple intervals for the same day with a comma', () => { const result = formatOpeningHours({ current_day: [day('Monday', '09:00', '12:00')], days: [[day('Tuesday', '09:00', '12:00'), day('Tuesday', '13:00', '17:00')]], })!; assert.equal(result.tuesday, '09:00-12:00, 13:00-17:00'); }); it('accepts a flat `days` array as well as an array of arrays', () => { // `OpeningHours['days']` is typed as `DayOpeningHours[] | DayOpeningHours[][]`, // so both shapes must produce the same result. const nested = formatOpeningHours(splitServiceHours); const flat = formatOpeningHours({ current_day: splitServiceHours.current_day, days: (splitServiceHours.days as DayOpeningHours[][]).flat(), }); assert.deepEqual(flat, nested); }); it('preserves the order in which days are returned by the API', () => { const result = formatOpeningHours(splitServiceHours)!; assert.deepEqual(Object.keys(result), [ 'today (friday)', 'tuesday', 'wednesday', 'thursday', 'saturday', 'sunday', ]); }); describe('when data is missing', () => { it('returns undefined when opening hours are absent', () => { assert.equal(formatOpeningHours(undefined), undefined); }); it('returns undefined for an empty opening hours object', () => { // Both `current_day` and `days` are optional on the API type, so `{}` is // a legal payload and must not throw. assert.equal(formatOpeningHours({}), undefined); }); it('omits the current day when `current_day` is absent', () => { const result = formatOpeningHours({ days: splitServiceHours.days })!; assert.ok(!Object.keys(result).some((key) => key.startsWith('today'))); assert.equal(result.tuesday, '17:00-21:30'); }); it('omits the current day when `current_day` is an empty array', () => { const result = formatOpeningHours({ current_day: [], days: splitServiceHours.days })!; assert.ok(!Object.keys(result).some((key) => key.startsWith('today'))); assert.equal(result.saturday, '11:00-15:00, 17:00-21:30'); }); it('returns only the current day when `days` is absent', () => { assert.deepEqual(formatOpeningHours({ current_day: splitServiceHours.current_day }), { 'today (friday)': '11:00-15:00, 17:00-21:30', }); }); }); }); - src/tools/local/index.test.ts (2716 bytes)
import assert from 'node:assert/strict'; import { describe, it } from 'node:test'; import { useTestClient } from '../../testUtils/mcpTestHarness.js'; import { name } from './index.js'; describe(name, () => { const getClient = useTestClient((url) => { if (url.pathname === '/res/v1/web/search') { return { type: 'search', locations: { results: [{ id: 'poi-1', title: 'Brave Coffee Shop' }], }, }; } if (url.pathname === '/res/v1/local/descriptions') { return { type: 'local_descriptions', results: [{ type: 'local_description', id: 'poi-1', description: 'A cozy coffee shop.' }], }; } }); it('returns enriched location results for a simple query', async () => { const result = await getClient().callTool({ name, arguments: { query: 'coffee shops in san francisco' }, }); assert.equal(result.isError ?? false, false, JSON.stringify(result.content)); assert.ok(Array.isArray(result.content) && result.content.length > 0); }); }); describe(`${name} (no locations, web fallback available)`, () => { const getClient = useTestClient((url) => { if (url.pathname === '/res/v1/web/search') { return { type: 'search', web: { results: [ { url: 'https://example.com/cafe', title: 'Local Cafe', description: 'A nice cafe.', extra_snippets: [], }, ], }, }; } }); it('falls back to formatted web results', async () => { const result = await getClient().callTool({ name, arguments: { query: 'coffee shops in san francisco' }, }); assert.equal(result.isError ?? false, false, JSON.stringify(result.content)); const content = result.content as { text: string }[]; assert.equal(content.length, 2); assert.match(content[0].text, /Falling back to general web search/); assert.match(content[1].text, /Local Cafe/); }); }); describe(`${name} (no locations, no web results)`, () => { const getClient = useTestClient((url) => { if (url.pathname === '/res/v1/web/search') { return { type: 'search' }; } }); it('reports that no location data was found', async () => { const result = await getClient().callTool({ name, arguments: { query: 'coffee shops in san francisco' }, }); assert.equal(result.isError ?? false, false, JSON.stringify(result.content)); assert.deepEqual(result.content, [ { type: 'text', text: "No location data was returned. User's plan does not support local search, or the query may be unclear.", }, ]); }); }); - src/tools/local/index.ts (6682 bytes)
import type { LocationResult, LocationDescription, OpeningHours, DayOpeningHours, } from './types.js'; import webParams, { type QueryParams as WebQueryParams } from '../web/params.js'; import type { CallToolResult, ToolAnnotations } from '@modelcontextprotocol/sdk/types.js'; import API from '../../BraveAPI/index.js'; import { formatWebResults } from '../web/index.js'; import { stringify } from '../../utils.js'; import { type WebSearchApiResponse } from '../web/types.js'; import { type McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; export const name = 'brave_local_search'; export const annotations: ToolAnnotations = { title: 'Brave Local Search', readOnlyHint: true, // destructiveHint and idempotentHint are meaningful only when readOnlyHint is false. // https://modelcontextprotocol.io/specification/2026-07-28/schema#toolannotations destructiveHint: false, idempotentHint: true, openWorldHint: true, }; export const description = ` Brave Local Search API provides enrichments for location search results. Access to this API is available only through the Brave Search API Pro plans; confirm the user's plan before using this tool (if the user does not have a Pro plan, use the brave_web_search tool). Searches for local businesses and places using Brave's Local Search API. Best for queries related to physical locations, businesses, restaurants, services, etc. Returns detailed information including: - Business names and addresses - Ratings and review counts - 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) => { // Make sure both 'web' and 'locations' are in the result_filter params = { ...params, result_filter: [...(params.result_filter || []), 'web', 'locations'] }; // Starts with a web search to retrieve potential location IDs const { locations, web: web_fallback } = await API.issueRequest<'web'>('web', params); // We can send up to 20 location IDs at a time to the Local API // TODO (Sampson): Add support for multiple requests const locationIDs = (locations?.results || []).map((poi) => poi.id as string).slice(0, 20); // No locations were found - user's plan may not include access to the Local API if (!locations || locationIDs.length === 0) { // If we have web results, but no locations, we'll fall back to the web results if (web_fallback && web_fallback.results.length > 0) { return buildFallbackWebResponse(web_fallback); } // If we have no web results, we'll send a message to the user return { content: [ { type: 'text' as const, text: "No location data was returned. User's plan does not support local search, or the query may be unclear.", }, ], }; } // Fetch AI-generated descriptions const descriptions = await API.issueRequest<'localDescriptions'>('localDescriptions', { ids: locationIDs, }); return { content: formatLocalResults(locations.results, descriptions.results).map((formattedPOI) => ({ type: 'text' as const, text: formattedPOI, })), }; }; export const register = (mcpServer: McpServer) => { mcpServer.registerTool( name, { title: name, description: description, inputSchema: webParams, annotations: annotations, }, execute ); }; const buildFallbackWebResponse = ( web_fallback: NonNullable<WebSearchApiResponse['web']> ): CallToolResult => { const fallback = { content: [ { type: 'text' as const, text: "No location data was returned. Either the user's plan does not support local search, or the API was unable to find locations for the provided query. Falling back to general web search.", }, ], }; for (const web_result of formatWebResults(web_fallback)) { fallback.content.push({ type: 'text' as const, text: stringify(web_result), }); } return fallback; }; const formatLocalResults = ( poisData: LocationResult[], descData: LocationDescription[] = [] ): string[] => { return poisData.map((poi) => { return stringify({ name: poi.title, price_range: poi.price_range, phone: poi.contact?.telephone, rating: poi.rating?.ratingValue, hours: formatOpeningHours(poi.opening_hours), rating_count: poi.rating?.reviewCount, description: descData.find(({ id }) => id === poi.id)?.description, address: poi.postal_address?.displayAddress, }); }); }; export const formatOpeningHours = ( openingHours?: OpeningHours ): Record<string, string> | undefined => { if (!openingHours) return undefined; /** * Response will be something like { * 'sunday': '10:00-18:00', * 'monday': '10:00-18:00', * 'tuesday': '10:00-18:00', * 'wednesday': '10:00-18:00, 19:00-22:00', * 'thursday': '10:00-18:00', * 'friday': '10:00-18:00', * 'saturday': '12:00-18:00', * } */ const today: DayOpeningHours[] = openingHours.current_day || []; const response = {} as Record<string, string>; const dayHours: [string, string[]][] = []; // `current_day` is optional, and is omitted when the location is closed // today, so only seed the "today" entry when the API actually provided one. if (today.length > 0) { dayHours.push([ `today (${today[0].full_name.toLowerCase()})`, today.map(({ opens, closes }) => `${opens}-${closes}`), ]); } // Add the rest of the days to the response for (let parts of openingHours.days || []) { // Not all days have arrays of hours, so normalize to an array if (!Array.isArray(parts)) parts = [parts]; // Add the hours for each day to the response for (const { full_name, opens, closes } of parts) { const dayName = full_name.toLowerCase(); const existingEntry = dayHours.find(([name]) => name === dayName); existingEntry ? existingEntry[1].push(`${opens}-${closes}`) : dayHours.push([dayName, [`${opens}-${closes}`]]); } } // Nothing usable was provided; omit the field rather than emitting `{}`. if (dayHours.length === 0) return undefined; for (const [name, hours] of dayHours) { response[name] = hours.join(', '); } return response; }; export default { name, description, annotations, inputSchema: webParams.shape, execute, register, }; - src/tools/local/params.ts (448 bytes)
import { z } from 'zod'; export const LocalPoisParams = z.object({ ids: z.array(z.string()).describe('List of location IDs for which to fetch POIs'), }); export const LocalDescriptionsParams = z.object({ ids: z.array(z.string()).describe('List of location IDs for which to fetch descriptions'), }); export type LocalPoisParams = z.infer<typeof LocalPoisParams>; export type LocalDescriptionsParams = z.infer<typeof LocalDescriptionsParams>; - src/tools/local/types.ts (8488 bytes)
export interface LocalPoiSearchApiResponse { /** The type of local POI search API result. The value is always local_pois. */ type: 'local_pois'; /** Location results matching the ids in the request. */ results?: LocationResult[]; } export interface LocalDescriptionsSearchApiResponse { /** The type of local description search API result. The value is always local_descriptions. */ type: 'local_descriptions'; /** Location descriptions matching the ids in the request. */ results?: LocationDescription[]; } export interface LocationDescription { /** The type of a location description. The value is always local_description. */ type: 'local_description'; /** A Temporary id of the location with this description. */ id: string; /** AI generated description of the location with the given id. */ description?: string; } interface Result { /** The title of the web page. */ title: string; /** The URL where the page is served. */ url: string; is_source_local: boolean; is_source_both: boolean; /** A description for the web page. */ description?: string; /** A date representing the age of the web page. */ page_age?: string; /** A date representing when the web page was last fetched. */ page_fetched?: string; /** A profile associated with the web page. */ profile?: Profile; /** A language classification for the web page. */ language?: string; /** Whether the web page is family friendly. */ family_friendly: boolean; } interface Profile { /** The name of the profile. */ name: string; /** The long name of the profile. */ long_name: string; /** The original URL where the profile is available. */ url?: string; /** The served image URL representing the profile. */ img?: string; } export interface LocationResult extends Result { /** Location result type identifier. The value is always location_result. */ type: 'location_result'; /** A Temporary id associated with this result, which can be used to retrieve extra information about the location. It remains valid for 8 hours… */ id?: string; /** The complete URL of the provider. */ provider_url: string; /** A list of coordinates associated with the location. This is a lat long represented as a floating point. */ coordinates?: number[]; /** The zoom level on the map. */ zoom_level: number; /** The thumbnail associated with the location. */ thumbnail?: Thumbnail; /** The postal address associated with the location. */ postal_address?: PostalAddress; /** The opening hours, if it is a business, associated with the location . */ opening_hours?: OpeningHours; /** The contact of the business associated with the location. */ contact?: Contact; /** A display string used to show the price classification for the business. */ price_range?: string; /** The ratings of the business. */ rating?: Rating; /** The distance of the location from the client. */ distance?: Unit; /** Profiles associated with the business. */ profiles?: DataProvider[]; /** Aggregated reviews from various sources relevant to the business. */ reviews?: Reviews; /** A bunch of pictures associated with the business. */ pictures?: PictureResults; /** An action to be taken. */ action?: Action; /** A list of cuisine categories served. */ serves_cuisine?: string[]; /** A list of categories. */ categories?: string[]; /** An icon category. */ icon_category?: string; /** Web results related to this location. */ results?: LocationWebResult; /** IANA timezone identifier. */ timezone?: string; /** The UTC offset of the timezone, in minutes. */ timezone_offset?: number; } interface Thumbnail { /** The served URL of the picture thumbnail. */ src: string; /** The original URL of the image. */ original?: string; } interface PostalAddress { /** The type identifying a postal address. The value is always PostalAddress. */ type: 'PostalAddress'; /** The country associated with the location. */ country?: string; /** The postal code associated with the location. */ postalCode?: string; /** The street address associated with the location. */ streetAddress?: string; /** The region associated with the location. This is usually a state. */ addressRegion?: string; /** The address locality or subregion associated with the location. */ addressLocality?: string; /** The displayed address string. */ displayAddress: string; } export interface OpeningHours { /** The current day opening hours. Can have two sets of opening hours. */ current_day?: DayOpeningHours[]; /** * The opening hours for the rest of the week, excluding `current_day`. Days * on which the location is closed are omitted entirely. Each entry may be a * single day's hours or an array of them, since a day can have more than one * open/close interval (e.g. separate lunch and dinner service). */ days?: DayOpeningHours[] | DayOpeningHours[][]; } interface Contact { /** The email address. */ email?: string; /** The telephone number. */ telephone?: string; } interface Rating { /** The current value of the rating. */ ratingValue: number; /** Best rating received. */ bestRating: number; /** The number of reviews associated with the rating. */ reviewCount?: number; /** The profile associated with the rating. */ profile?: Profile; /** Whether the rating is coming from Tripadvisor. */ is_tripadvisor: boolean; } interface Unit { /** The quantity of the unit. */ value: number; /** The name of the unit associated with the quantity. */ units: string; } interface DataProvider { /** The type representing the source of data. This is usually external. */ type: 'external'; /** The name of the data provider. This can be a domain. */ name: string; /** The URL where the information is coming from. */ url: string; /** The long name for the data provider. */ long_name?: string; /** The served URL for the image data. */ img?: string; } interface Reviews { /** A list of trip advisor reviews for the entity. */ results: TripAdvisorReview[]; /** A URL to a web page where more information on the result can be seen. */ viewMoreUrl: string; /** Any reviews available in a foreign language. */ reviews_in_foreign_language: boolean; } interface PictureResults { /** A URL to view more pictures. */ viewMoreUrl?: string; /** A list of thumbnail results. */ results: Thumbnail[]; } interface Action { /** The type representing the action. */ type: string; /** A URL representing the action to be taken. */ url: string; } interface LocationWebResult extends Result { /** Aggregated information about the URL. */ meta_url: MetaUrl; } interface MetaUrl { /** The protocol scheme extracted from the URL. */ scheme: string; /** The network location part extracted from the URL. */ netloc: string; /** The lowercased domain name extracted from the URL. */ hostname?: string; /** The favicon used for the URL. */ favicon: string; /** The hierarchical path of the URL useful as a display string. */ path: string; } export interface DayOpeningHours { /** A short string representing the day of the week. */ abbr_name: string; /** A full string representing the day of the week. */ full_name: string; /** A 24 hr clock time string for the opening time of the business on a particular day. */ opens: string; /** A 24 hr clock time string for the closing time of the business on a particular day. */ closes: string; } interface TripAdvisorReview { /** The title of the review. */ title: string; /** A description seen in the review. */ description: string; /** The date when the review was published. */ date: string; /** A rating given by the reviewer. */ rating: Rating; /** The author of the review. */ author: Person; /** A URL link to the page where the review can be found. */ review_url: string; /** The language of the review. */ language: string; } interface Person extends Omit<Thing, 'type'> { /** A type identifying a person. The value is always person. */ type: 'person'; /** Email address of the person. */ email?: string; } interface Thing { /** A type identifying a thing. The value is always thing. */ type: 'thing'; /** The name of the thing. */ name: string; /** A URL for the thing. */ url?: string; /** Thumbnail associated with the thing. */ thumbnail?: Thumbnail; } - src/tools/news/index.test.ts (1097 bytes)
import assert from 'node:assert/strict'; import { describe, it } from 'node:test'; import { useTestClient } from '../../testUtils/mcpTestHarness.js'; import { name } from './index.js'; describe(name, () => { const getClient = useTestClient((url) => { if (url.pathname === '/res/v1/news/search') { return { results: [ { url: 'https://example.com/news', title: 'Brave ships a new release', description: 'News about Brave.', age: '1 hour ago', page_age: '2024-01-01T00:00:00Z', breaking: false, is_live: false, extra_snippets: [], thumbnail: { src: 'https://example.com/news-thumb.jpg' }, }, ], }; } }); it('returns news results for a simple query', async () => { const result = await getClient().callTool({ name, arguments: { query: 'brave browser' } }); assert.equal(result.isError ?? false, false, JSON.stringify(result.content)); assert.ok(Array.isArray(result.content) && result.content.length > 0); }); }); - src/tools/news/index.ts (2878 bytes)
import type { ToolAnnotations } from '@modelcontextprotocol/sdk/types.js'; import params, { type QueryParams } from './params.js'; import API from '../../BraveAPI/index.js'; import { stringify } from '../../utils.js'; import { type McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; export const name = 'brave_news_search'; export const annotations: ToolAnnotations = { title: 'Brave News Search', readOnlyHint: true, // destructiveHint and idempotentHint are meaningful only when readOnlyHint is false. // https://modelcontextprotocol.io/specification/2026-07-28/schema#toolannotations destructiveHint: false, idempotentHint: true, openWorldHint: true, }; export const description = ` This tool searches for news articles using Brave's News Search API based on the user's query. Use it when you need current news information, breaking news updates, or articles about specific topics, events, or entities. When to use: - Finding recent news articles on specific topics - Getting breaking news updates - Researching current events or trending stories - Gathering news sources and headlines for analysis Returns a JSON list of news-related results with title, url, and description. Some results may contain snippets of text from the article. When relaying results in markdown-supporting environments, always cite sources with hyperlinks. Examples: - "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); return { content: response.results.map((newsResult) => { return { type: 'text' as const, text: stringify({ url: newsResult.url, title: newsResult.title, age: newsResult.age, page_age: newsResult.page_age, breaking: newsResult.breaking ?? false, description: newsResult.description, extra_snippets: newsResult.extra_snippets, thumbnail: newsResult.thumbnail?.src, }), }; }), }; }; export const register = (mcpServer: McpServer) => { mcpServer.registerTool( name, { title: name, description: description, inputSchema: params, annotations: annotations, }, execute ); }; export default { name, description, annotations, inputSchema: params.shape, execute, register, }; - src/tools/news/params.ts (3275 bytes)
import { z } from 'zod'; export const params = z.object({ query: z .string() .max(400) .refine((str) => str.split(/\s+/).length <= 50, 'Query cannot exceed 50 words') .describe('Search query (max 400 chars, 50 words)'), country: z .string() .default('US') .describe( 'Search query country, where the results come from. The country string is limited to 2 character country codes of supported countries.' ) .optional(), search_lang: z .string() .default('en') .describe( 'Search language preference. The 2 or more character language code for which the search results are provided.' ) .optional(), ui_lang: z .string() .default('en-US') .describe( 'User interface language preferred in response. Usually of the format <language_code>-<country_code>. For more, see RFC 9110.' ) .optional(), count: z .int() .min(1) .max(50) .default(20) .describe('Number of results (1-50, default 20)') .optional(), offset: z .int() .min(0) .max(9) .default(0) .describe('Pagination offset (max 9, default 0)') .optional(), spellcheck: z .boolean() .default(true) .describe('Whether to spellcheck provided query.') .optional(), safesearch: z .union([z.literal('off'), z.literal('moderate'), z.literal('strict')]) .default('moderate') .describe( "Filters search results for adult content. The following values are supported: 'off' - No filtering. 'moderate' - Filter out explicit content. 'strict' - Filter out explicit and suggestive content. The default value is 'moderate'." ) .optional(), freshness: 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', or 'py' for a relative discovery window, or a custom range as YYYY-MM-DDtoYYYY-MM-DD (e.g. 2022-04-01to2022-07-30)." ), ]) .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." ) .optional(), extra_snippets: z .boolean() .default(false) .describe( 'A snippet is an excerpt from a page you get as a result of the query, and extra_snippets allow you to get up to 5 additional, alternative excerpts. Only available under Free AI, Base AI, Pro AI, Base Data, Pro Data and Custom plans.' ) .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(), }); export type QueryParams = z.infer<typeof params>; export default params; - src/tools/news/types.ts (2430 bytes)
export interface NewsSearchApiResponse { /** The type of search API result. The value is always news. */ type: 'news'; /** News search query string. */ query: Query; /** The list of news results for the given query. */ results: NewsResult[]; } interface Query { /** The original query that was requested. */ original: string; /** The altered query by the spellchecker. This is the query that is used to search if any. */ altered?: string; /** The cleaned normalized query by the spellchecker. This is the query that is used to search if any. */ cleaned?: string; /** Whether the spellchecker is enabled or disabled. */ spellcheck_off?: boolean; /** The value is true if the lack of results is due to a strict safesearch setting. Adult content relevant to the query was found, but was blocked by safesearch. */ show_strict_warning?: boolean; } export interface NewsResult { /** The type of news search API result. The value is always news_result. */ type: 'news_result'; /** The source URL of the news article. */ url: string; /** The title of the news article. */ title: string; /** The description for the news article. */ description?: string; /** A human readable representation of the page age. */ age?: string; /** The page age found from the source web page. */ page_age?: string; /** The ISO date time when the page was last fetched. The format is YYYY-MM-DDTHH:MM:SSZ. */ page_fetched?: string; /** Whether the result includes breaking news. */ breaking?: boolean; /** The thumbnail for the news article. */ thumbnail?: Thumbnail; /** Aggregated information on the URL associated with the news search result. */ meta_url?: MetaUrl; /** A list of extra alternate snippets for the news search result. */ extra_snippets?: string[]; } interface Thumbnail { /** The served URL of the thumbnail associated with the news article. */ src: string; /** The original URL of the thumbnail associated with the news article. */ original?: string; } interface MetaUrl { /** The protocol scheme extracted from the URL. */ scheme?: string; /** The network location part extracted from the URL. */ netloc?: string; /** The lowercased domain name extracted from the URL. */ hostname?: string; /** The favicon used for the URL. */ favicon?: string; /** The hierarchical path of the URL useful as a display string. */ path?: string; } - src/tools/place_search/index.test.ts (4463 bytes)
import assert from 'node:assert/strict'; import { describe, it } from 'node:test'; import { Ajv2020 } from 'ajv/dist/2020.js'; import { useTestClient } from '../../testUtils/mcpTestHarness.js'; import { name } from './index.js'; const geographicResult = (type: string) => ({ type, name: 'Example', country: 'US', coordinates: [37.77, -122.42], thumbnail: { src: 'https://example.com/thumbnail.jpg' }, }); const responses = { minimal: { type: 'locations' }, // Covers populated results, null thumbnail fields, and mixed ordering nullability. geographic: { type: 'locations', countries: [geographicResult('country')], regions: [geographicResult('region')], neighborhoods: [ geographicResult('neighborhood'), { ...geographicResult('neighborhood'), type: null, thumbnail: { src: 'https://example.com/thumbnail.jpg', alt: null, height: null, width: null, bg_color: null, original: null, logo: null, duplicated: null, theme: null, }, }, ], mixed: [ { type: 'countries', index: 0, all: false }, { type: 'regions', index: null, all: true }, { type: 'neighborhoods', index: 1, all: null }, { type: 'neighborhoods' }, ], }, nullable: { type: 'locations', countries: null, regions: null, neighborhoods: null, mixed: null, }, // "future" is an arbitrary name for a payload with a field the schema doesn't declare (future_results). // Regression guard: if the schema is tightened to reject unknown properties, validation fails. future: { type: 'locations', future_results: [{ name: 'Example' }] }, }; describe(name, () => { // 'q' selects a fixture by name; requests without a matching query return responses.minimal. const getClient = useTestClient((url) => { if (url.pathname === '/res/v1/local/place_search') { return responses[url.searchParams.get('q') as keyof typeof responses] ?? responses.minimal; } }); it('returns a locations response for a simple location query', async () => { // Listing tools loads the advertised output schema into the SDK client. await getClient().listTools(); const result = await getClient().callTool({ name, arguments: { location: 'san francisco ca united states' }, }); assert.equal(result.isError ?? false, false, JSON.stringify(result.content)); assert.deepEqual(result.structuredContent, responses.minimal); }); for (const query of ['geographic', 'nullable', 'future'] as const) { it(`preserves ${query} response fields through MCP output validation`, async () => { // Listing tools loads the advertised output schema into the SDK client. await getClient().listTools(); const result = await getClient().callTool({ name, arguments: { query } }); assert.equal(result.isError ?? false, false, JSON.stringify(result.content)); assert.deepEqual(result.structuredContent, responses[query]); assert.deepEqual(result.content, [{ type: 'text', text: JSON.stringify(responses[query]) }]); }); } it('advertises and validates the new fields while allowing unknown fields', async () => { const { tools } = await getClient().listTools(); const schema = tools.find((tool) => tool.name === name)?.outputSchema; assert.ok(schema); for (const field of ['countries', 'regions', 'neighborhoods', 'mixed']) { assert.ok(schema.properties?.[field], `${field} is missing from the output schema`); } const validate = new Ajv2020({ strict: false, validateFormats: false }).compile(schema); // The output schema stays open to unknown fields: the Brave API may add fields before this // server's schema is updated, and rejecting them would fail client validation. for (const response of Object.values(responses)) { assert.equal(validate(response), true, JSON.stringify(validate.errors)); } const invalidFields = [ { type: 'wrong' }, { countries: [geographicResult('city')] }, { regions: 'invalid' }, { neighborhoods: [{ type: 'neighborhood' }] }, { mixed: [{ type: 'countries', index: 0.5 }] }, { mixed: [{ type: 'countries', all: 'yes' }] }, ]; for (const invalid of invalidFields) { assert.equal(validate({ type: 'locations', ...invalid }), false, JSON.stringify(invalid)); } }); }); - src/tools/place_search/index.ts (3237 bytes)
import type { TextContent, ToolAnnotations } from '@modelcontextprotocol/sdk/types.js'; import API from '../../BraveAPI/index.js'; import { type McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import { RequestParamsSchema, RequestHeadersSchema, PlaceSearchInputSchema, type PlaceSearchInput as QueryParams, } from './schemas/input.js'; import { PlaceSearchApiResponseSchema } from './schemas/output.js'; export const name = 'brave_place_search'; export const annotations: ToolAnnotations = { title: 'Brave Place Search', readOnlyHint: true, // destructiveHint and idempotentHint are meaningful only when readOnlyHint is false. // https://modelcontextprotocol.io/specification/2026-07-28/schema#toolannotations destructiveHint: false, idempotentHint: true, openWorldHint: true, }; export const description = ` Searches Brave's Place Search API. A single call may populate any combination of 'results' (POIs), 'cities', 'countries', 'regions', 'neighborhoods', 'addresses', 'streets', 'mixed' (result ordering), and 'location' (the resolved search area), depending on the query's shape. When to use: - POIs near coordinates or a named area (e.g. "coffee shops in Paris") -> 'results', each with structured business data (postal address, hours, contact, ratings, photos, categories, timezone). - Browsing general POIs (omit 'query'; supply 'latitude'+'longitude' or 'location'). - Disambiguating a bare city name (e.g. "springfield") -> 'cities'. - Resolving a specific address (e.g. "350 5th avenue" with NYC coords) -> 'addresses' (often plus 'streets'). - Looking up a street by name (e.g. "michigan avenue" with Chicago coords) -> 'streets'. Inputs: - Anchor the search via 'latitude'+'longitude' or 'location' (or both). With neither, 'query' is required. - 'addresses' / 'streets' only surface when the query is address-/street-shaped AND geographically anchored. - 'location' format: US -- '<city> <state> <country>' (e.g. 'san francisco ca united states'); non-US -- '<city> <country>' (e.g. 'tokyo japan'). Capitalization and commas don't matter. - 'count' caps results (max 50, default 20). 'radius' (meters) biases toward closer results; it does NOT hard-limit the search area. `.trim(); export const execute = async (params: QueryParams) => { const parsedParams = RequestParamsSchema.parse(params); const parsedHeaders = RequestHeadersSchema.parse(params); const response = await API.issueRequest<'placeSearch'>( 'placeSearch', parsedParams, parsedHeaders ); return { content: [{ type: 'text', text: JSON.stringify(response) } as TextContent], isError: false, structuredContent: response, }; }; export const register = (mcpServer: McpServer) => { mcpServer.registerTool( name, { title: name, description: description, inputSchema: PlaceSearchInputSchema, outputSchema: PlaceSearchApiResponseSchema, annotations: annotations, }, execute ); }; export default { name, description, annotations, inputSchema: PlaceSearchInputSchema.shape, outputSchema: PlaceSearchApiResponseSchema, execute, register, }; - src/tools/place_search/schemas/input.ts (5920 bytes)
import { z } from 'zod'; /** * Keep up-to-date with documentation: * https://api-dashboard.search.brave.com/api-reference/web/place_search */ 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', ]); 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', 'ja', '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 UiLangCodesSchema = z.enum([ 'es-AR', 'en-AU', 'de-AT', 'nl-BE', 'fr-BE', 'pt-BR', 'en-CA', 'fr-CA', 'es-CL', 'da-DK', 'fi-FI', 'fr-FR', 'de-DE', 'zh-HK', 'en-IN', 'en-ID', 'it-IT', 'ja-JP', 'ko-KR', 'en-MY', 'es-MX', 'nl-NL', 'en-NZ', 'no-NO', 'zh-CN', 'pl-PL', 'en-PH', 'ru-RU', 'en-ZA', 'es-ES', 'sv-SE', 'fr-CH', 'de-CH', 'zh-TW', 'tr-TR', 'en-GB', 'en-US', 'es-US', ]); export const RequestParamsSchema = z.object({ query: z .string() .trim() .max(400) .refine( (str) => str.length === 0 || str.split(/\s+/).length <= 50, 'Query cannot exceed 50 words' ) .transform((str) => (str.length === 0 ? undefined : str)) .describe( 'Query string. Shape influences the response: POI-like queries -> `results`; bare/ambiguous city names -> `cities`; address- or street-shaped queries with a geographic anchor -> `addresses` and/or `streets`. If omitted, returns general POIs in the supplied area.' ) .optional(), radius: z .number() .min(0) .describe( 'Bias toward results closer to the supplied coordinates, in meters. NOT a hard cutoff -- the API may still return more distant results. If omitted, the search is performed globally.' ) .optional(), count: z .number() .int() .min(1) .max(50) .describe('Number of results to return. Maximum is 50. Default is 20.') .optional(), latitude: z .number() .min(-90) .max(90) .describe( 'Latitude of the geographical coordinates around which to search, in degrees (-90 to 90). Typically paired with `longitude`.' ) .optional(), longitude: z .number() .min(-180) .max(180) .describe( 'Longitude of the geographical coordinates around which to search, in degrees (-180 to 180). Typically paired with `latitude`.' ) .optional(), location: z .string() .trim() .min(1) .describe( "Location string to search around, used as an alternative to `latitude` and `longitude`. For US locations prefer the form '<city> <state> <country name>' (e.g. 'san francisco ca united states'); for non-US locations use '<city> <country name>' (e.g. 'tokyo japan'). No commas or special characters needed; capitalization does not matter." ) .optional(), country: CountryCodesSchema.describe( "Two-letter country code (ISO 3166-1 alpha-2) used to scope the search. Defaults to 'US'." ).optional(), search_lang: SearchLangCodesSchema.describe( "Language for the search results. Defaults to 'en'." ).optional(), ui_lang: UiLangCodesSchema.describe( "User interface language for the response, usually of the form '<language>-<region>'. Defaults to 'en-US'." ).optional(), units: z .enum(['metric', 'imperial']) .describe("Units of measurement for distance values. Defaults to 'metric'.") .optional(), safesearch: z .enum(['off', 'moderate', 'strict']) .describe( "Safe search level for the query results. 'off' - No filtering. 'moderate' - Filter out explicit content. 'strict' - Filter out explicit and suggestive content. Defaults to 'strict'." ) .optional(), spellcheck: z .boolean() .describe('Whether to apply spellcheck before executing the search. Defaults to true.') .optional(), geoloc: z.string().describe('Optional geolocation token used to refine results.').optional(), }); export const RequestHeadersSchema = z.object({ '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 PlaceSearchInputSchema = z.object({ ...RequestParamsSchema.shape, ...RequestHeadersSchema.shape, }); export type PlaceSearchInput = z.input<typeof PlaceSearchInputSchema>; export type PlaceSearchQueryParams = z.infer<typeof RequestParamsSchema>; export type PlaceSearchRequestHeaders = z.infer<typeof RequestHeadersSchema>; - src/tools/place_search/schemas/output.ts (14005 bytes)
import { z } from 'zod'; /** * Keep up to date with documentation: * https://api-dashboard.search.brave.com/api-reference/web/place_search#responses */ const CoordinatesSchema = z .tuple([z.number(), z.number()]) .describe('Latitude/longitude pair for the location, when available.'); const ThumbnailSchema = z.looseObject({ src: z.string().describe('The served URL of the picture thumbnail.'), alt: z.string().describe('The alt text for the thumbnail.').nullish(), height: z.number().describe('The height of the thumbnail.').nullish(), width: z.number().describe('The width of the thumbnail.').nullish(), bg_color: z.string().describe('The background color of the thumbnail.').nullish(), original: z.url().describe('The original URL of the image.').nullish(), logo: z.boolean().describe('Whether the thumbnail is a logo.').nullish(), duplicated: z.boolean().describe('Whether the thumbnail is duplicated.').nullish(), theme: z.string().describe('The theme of the thumbnail (e.g. "light", "dark").').nullish(), }); const PostalAddressSchema = z.looseObject({ type: z.literal('PostalAddress'), country: z.string().describe('The country associated with the location.').optional(), postalCode: z.string().describe('The postal code associated with the location.').optional(), streetAddress: z.string().describe('The street address associated with the location.').optional(), addressRegion: z .string() .describe('The region associated with the location. Usually a state.') .optional(), addressLocality: z .string() .describe('The address locality or subregion associated with the location.') .optional(), displayAddress: z.string().describe('The displayed address string.'), }); const DayOpeningHoursSchema = z.looseObject({ abbr_name: z.string().describe('Short name of the day of the week (e.g. "Mon").').optional(), full_name: z.string().describe('Full name of the day of the week (e.g. "Monday").').optional(), opens: z.string().describe('Opening time in 24h format (e.g. "09:00").').optional(), closes: z.string().describe('Closing time in 24h format (e.g. "17:00").').optional(), }); const OpeningHoursSchema = z.looseObject({ current_day: z .array(DayOpeningHoursSchema) .describe( 'Opening hours for the current day. May contain multiple entries when the location closes and reopens during the day.' ) .optional(), days: z .array(z.union([DayOpeningHoursSchema, z.array(DayOpeningHoursSchema)])) .describe( 'Opening hours for the rest of the week. Each entry may itself be either a single day-hours object or an array of day-hours objects (when a day has multiple open/close intervals).' ) .optional(), }); const ContactSchema = z.looseObject({ email: z.string().describe('Contact email for the business.').optional(), telephone: z.string().describe('Contact telephone number for the business.').optional(), }); const DistanceSchema = z.looseObject({ value: z.number().describe('The quantity of the unit.'), units: z.string().describe('The name of the unit associated with the quantity.'), }); const ProfileSchema = z.looseObject({ type: z.string().optional(), name: z.string().optional(), long_name: z.string().optional(), url: z.string().optional(), img: z.string().optional(), }); const RatingSchema = z.looseObject({ ratingValue: z.number().describe('The current value of the rating.').optional(), bestRating: z.number().describe('Highest possible rating value.').optional(), reviewCount: z.number().describe('Number of reviews backing the rating.').optional(), profile: ProfileSchema.optional(), is_tripadvisor: z .boolean() .describe('Whether the rating originates from Tripadvisor.') .optional(), }); const ReviewSchema = z.looseObject({ title: z.string().describe('The title of the review.'), description: z.string().describe('A description seen in the review.'), date: z.string().describe('The date when the review was published.'), rating: RatingSchema.optional(), author: ProfileSchema.optional(), }); const ReviewsSchema = z.looseObject({ results: z .array(ReviewSchema) .describe('A list of trip advisor reviews for the entity.') .optional(), viewMoreUrl: z .string() .describe('A URL to a web page where more information on the result can be seen.') .optional(), reviews_in_foreign_language: z .boolean() .describe('Any reviews available in a foreign language.') .optional(), }); const PicturesSchema = z.looseObject({ viewMoreUrl: z.string().describe('URL where additional pictures can be viewed.').optional(), results: z.array(ThumbnailSchema).describe('Thumbnail entries for the location.').optional(), }); const ActionSchema = z.looseObject({ type: z.string().describe('The type representing the action.'), url: z.string().describe('A URL representing the action to be taken.'), }); const MetaUrlSchema = z.looseObject({ scheme: z.string().describe('The protocol scheme extracted from the URL.'), netloc: z.string().describe('The network location part extracted from the URL.'), hostname: z.string().describe('The lowercased domain name extracted from the URL.').optional(), favicon: z.string().describe('The favicon used for the URL.').optional(), path: z .string() .describe('The hierarchical path of the URL useful as a display string.') .optional(), }); /** * Fields shared by every "web-style" result entry: both inline web results * (which decorate location results via `results`) and the location/POI * results themselves. Defined once and composed via `.extend()` below. */ const WebResultBaseSchema = z.looseObject({ title: z.string().describe('The display title of the location.'), url: z .union([z.url(), z.literal('')]) .describe('Primary URL associated with the location. May be an empty string.'), is_source_local: z.boolean().describe('Whether the result is from local sources.'), is_source_both: z.boolean().describe('Whether the result is from both local and global sources.'), description: z .string() .describe('Short description of the location (e.g. "Plaza", "Theater").') .optional(), page_age: z.string().describe('The age of the page as a date string.').optional(), page_fetched: z .string() .describe('The date the page was last fetched as a date string.') .optional(), fetched_content_timestamp: z .number() .describe('The timestamp of the content when it was fetched.') .optional(), profile: ProfileSchema.describe('The profile associated with the result.').optional(), language: z.string().describe('The language of the page.').optional(), family_friendly: z.boolean().describe('Whether the result is family friendly.').optional(), }); /** * An inline web result attached to a location (under `LocationResultSchema.results`). */ const WebResultSchema = WebResultBaseSchema.extend({ meta_url: MetaUrlSchema.optional(), }); /** * A location/POI result. Used both at the top level (`results[]`) and inside * addresses (`pois[]` / `pois_nearby[]`). */ const LocationResultSchema = WebResultBaseSchema.extend({ type: z.literal('location_result').describe('Result type identifier.'), provider_url: z .union([z.url(), z.literal('')]) .describe('URL of the upstream provider for this result. May be an empty string.'), coordinates: CoordinatesSchema.optional(), zoom_level: z.number().describe('Suggested zoom level when displaying on a map.'), thumbnail: ThumbnailSchema.describe('The thumbnail associated with the location.').optional(), postal_address: PostalAddressSchema.describe('The postal address of the location.').optional(), opening_hours: OpeningHoursSchema.describe('The opening hours of the location.').optional(), contact: ContactSchema.describe('The contact of the location.').optional(), price_range: z .string() .describe('Price classification string for the business (e.g. "$", "$$").') .optional(), rating: RatingSchema.describe('The rating of the result.').optional(), distance: DistanceSchema.describe( "Distance from the user's geolocation, if available." ).optional(), profiles: z .array(ProfileSchema) .describe('External profiles (e.g. data providers) associated with the result.') .optional(), reviews: ReviewsSchema.describe('Reviews associated with the result.').optional(), pictures: PicturesSchema.describe('Pictures associated with the result.').optional(), action: ActionSchema.describe('The action associated with the result.').optional(), serves_cuisine: z.array(z.string()).describe('List of cuisine categories served.').optional(), categories: z.array(z.string()).describe('List of category labels.').optional(), icon_category: z.string().describe('Suggested icon category (e.g. "cafe").').optional(), timezone: z.string().describe('IANA timezone identifier for the location.').optional(), timezone_offset: z .number() .describe("UTC offset of the location's timezone, in minutes.") .optional(), id: z .string() .describe( 'Temporary identifier for the location, valid for ~8 hours. Can be used with brave_local_search-style endpoints to fetch additional information.' ) .optional(), results: z.array(WebResultSchema).describe('Web results related to this location.').optional(), }); const QuerySchema = z.looseObject({ original: z .string() .describe('The original query string as supplied by the caller (may be empty).'), altered: z .string() .describe('The altered query string as supplied by the caller (may be empty).') .optional(), spellcheck_off: z.boolean().optional(), show_strict_warning: z.boolean().optional(), }); const AddressSchema = z.looseObject({ type: z .enum(['address', 'street']) .describe( 'Result is "address" when the result refers to an explicit street + number, but "street" when it refers only to the street itself.' ), name: z.string().describe('The name of the address.'), coordinates: CoordinatesSchema.describe('Latitude/longitude of the address'), pois: z.array(LocationResultSchema).describe('List of POIs located at this address.'), pois_nearby: z.array(LocationResultSchema).describe('List of POIs nearby this address.'), zoom_level: z.number().describe('Suggested zoom level when displaying on a map.'), distance: DistanceSchema.describe( "Distance from the user's geolocation, if available." ).optional(), postal_address: PostalAddressSchema.describe('The postal address of the address.').optional(), }); const CitySchema = z.looseObject({ type: z.literal('city'), name: z.string().describe('Name of the city'), country: z.string().describe('ISO country code for the city'), coordinates: CoordinatesSchema.describe('Latitude/longitude of the city'), thumbnail: ThumbnailSchema.describe('Primary image for the city'), }); const geographicResultSchema = <T extends string>(type: T) => z.looseObject({ type: z.literal(type).describe(`Always "${type}".`).nullish(), name: z.string().describe(`Name of the ${type}.`), country: z.string().describe(`Country code for the ${type}.`), coordinates: CoordinatesSchema.describe(`Latitude/longitude of the ${type}.`), thumbnail: ThumbnailSchema.describe(`Primary image for the ${type}.`), }); const MixedResultSchema = z.looseObject({ type: z.string().describe('The type of result referenced by this ordering entry.'), index: z .int() .describe('Zero-based index indicating where the result should be placed.') .nullish(), all: z .boolean() .describe('Whether to include all results of this type at this position.') .nullish(), }); const LocationSchema = z.looseObject({ coordinates: CoordinatesSchema.describe('Latitude/longitude of the resolved search area.'), name: z.string().describe('Human-readable name of the resolved search area.').optional(), country: z.string().describe('ISO country code for the resolved search area.').optional(), }); export const PlaceSearchApiResponseSchema = z.looseObject({ type: z .literal('locations') .describe('Top-level response discriminator. Always "locations" for Place Search.'), query: QuerySchema.optional(), results: z .array(LocationResultSchema) .describe('Points of interest matching the search. Populated for POI-shaped queries.') .optional(), cities: z .array(CitySchema) .describe( 'City matches for the query. Typically populated when the query is a bare or ambiguous city name (e.g. "springfield", "san francisco").' ) .optional(), countries: z .array(geographicResultSchema('country')) .describe('Country matches for the query.') .nullish(), regions: z .array(geographicResultSchema('region')) .describe('Region matches for the query.') .nullish(), neighborhoods: z .array(geographicResultSchema('neighborhood')) .describe('Neighborhood matches for the query.') .nullish(), mixed: z .array(MixedResultSchema) .describe('Ordering entries for combining results of different types.') .nullish(), addresses: z .array(AddressSchema) .describe( 'Address matches. Typically populated when the query is a street + number AND is geographically anchored via `latitude`+`longitude` or a specific `location`.' ) .optional(), streets: z .array(AddressSchema) .describe( 'Street matches. Typically populated when the query is a street name AND is geographically anchored via `latitude`+`longitude` or a specific `location`.' ) .optional(), location: LocationSchema.describe( 'The search area as resolved by the API (e.g. coordinates + city name). Useful for confirming the API interpreted the input as expected and for grounding follow-up queries.' ).optional(), }); export type PlaceSearchApiResponse = z.infer<typeof PlaceSearchApiResponseSchema>; - src/tools/summarizer/format.test.ts (6322 bytes)
import assert from 'node:assert/strict'; import { describe, it } from 'node:test'; import { formatSummary } from './format.js'; import type { SummaryMessage } from './types.js'; // Test data is shortened from real Summarizer responses, except in the minus // sign and parentheses tests. The ordered-list test also removes the line // breaks before its list, to check that they are added. /** An inline reference; the formatter does not use its text positions. */ const reference = (url: string, number: number): SummaryMessage => ({ type: 'inline_reference', data: { type: 'inline_reference', url, number, start_index: 0, end_index: 0 }, }); describe('formatSummary', () => { it('renders inline references as footnotes, one per source', () => { const civitatis = 'https://www.civitatis.com/blog/en/tallest-buildings-in-the-world/'; const britannica = 'https://www.britannica.com/technology/tallest-buildings-in-the-world-2226971'; const visualCapitalist = 'https://www.visualcapitalist.com/ranked-the-worlds-tallest-buildings/'; const cntraveler = 'https://www.cntraveler.com/story/the-tallest-buildings-in-the-world'; const summary: SummaryMessage[] = [ { type: 'token', data: "The Burj Khalifa remains the world's tallest building" }, reference(civitatis, 1), reference(britannica, 2), reference(visualCapitalist, 3), { type: 'token', data: '. It is followed closely by Merdeka 118' }, reference(visualCapitalist, 3), reference(cntraveler, 4), { type: 'token', data: '.' }, ]; assert.equal( formatSummary(summary), [ "The Burj Khalifa remains the world's tallest building[^1][^2][^3]. It is followed closely by Merdeka 118[^3][^4].", '', `[^1]: [civitatis.com](${civitatis})`, `[^2]: [britannica.com](${britannica})`, `[^3]: [visualcapitalist.com](${visualCapitalist})`, `[^4]: [cntraveler.com](${cntraveler})`, ].join('\n') ); }); it('renders an entity list set apart from the text that follows it', () => { const summary: SummaryMessage[] = [ { type: 'token', data: 'The core discography consists of 13 UK studio albums' }, { type: 'token', data: ':\n\n' }, { type: 'enum_start', data: 'ul' }, { type: 'enum_item', data: { uuid: '1eac89cec2ef4ba8bc4e31952c6324c1', name: 'Please Please Me', url: 'https://en.wikipedia.org/wiki/Please_Please_Me', text: 'Released March 22, 1963, this was their debut studio album.', }, }, { type: 'enum_item', data: { uuid: '9e5679cb92be4bea91750774bb0cae28', name: 'Revolver (Beatles album)', url: 'https://en.wikipedia.org/wiki/Revolver_(Beatles_album)', text: 'Released August 5, 1966, it introduced new recording techniques and styles.', }, }, { type: 'enum_end' }, { type: 'token', data: '**US-Specific Albums**\nCapitol Records released many albums' }, { type: 'token', data: '.' }, ]; assert.equal( formatSummary(summary), [ 'The core discography consists of 13 UK studio albums:', '', '- [Please Please Me](https://en.wikipedia.org/wiki/Please_Please_Me) – Released March 22, 1963, this was their debut studio album.', '- [Revolver (Beatles album)](https://en.wikipedia.org/wiki/Revolver_(Beatles_album)) – Released August 5, 1966, it introduced new recording techniques and styles.', '', '**US-Specific Albums**', 'Capitol Records released many albums.', ].join('\n') ); }); it('numbers an ordered list without repeating a description separator', () => { const summary: SummaryMessage[] = [ { type: 'token', data: 'The tallest buildings in the world are:' }, { type: 'enum_start', data: 'ol' }, { type: 'enum_item', data: { uuid: 'a', name: 'Burj Khalifa (Dubai, UAE)', url: 'https://en.wikipedia.org/wiki/Burj_Khalifa', text: '– 828 m (2,717 ft)', }, }, { type: 'enum_item', data: { uuid: 'b', name: 'Merdeka 118', url: 'https://en.wikipedia.org/wiki/Merdeka_118' }, }, { type: 'enum_item', data: { uuid: 'c', name: 'Makkah Royal Clock Tower (Mecca, Saudi Arabia)' }, }, { type: 'enum_end' }, { type: 'token', data: 'These rankings are based on official architectural height.' }, ]; assert.equal( formatSummary(summary), [ 'The tallest buildings in the world are:', '', '1. [Burj Khalifa (Dubai, UAE)](https://en.wikipedia.org/wiki/Burj_Khalifa) – 828 m (2,717 ft)', '2. [Merdeka 118](https://en.wikipedia.org/wiki/Merdeka_118)', '3. Makkah Royal Clock Tower (Mecca, Saudi Arabia)', '', 'These rankings are based on official architectural height.', ].join('\n') ); }); it('keeps a minus sign that begins a description', () => { const summary: SummaryMessage[] = [ { type: 'enum_start', data: 'ul' }, { type: 'enum_item', data: { uuid: 'a', name: 'Vostok Station', text: '-89.2 °C' } }, { type: 'enum_item', data: { uuid: 'b', name: 'Oymyakon', text: '– -67.7 °C' } }, { type: 'enum_end' }, ]; assert.equal(formatSummary(summary), '- Vostok Station – -89.2 °C\n- Oymyakon – -67.7 °C'); }); it('percent-encodes unmatched parentheses in link URLs', () => { const summary: SummaryMessage[] = [ { type: 'token', data: 'Sources' }, reference('https://example.com/a(b', 1), { type: 'enum_start', data: 'ul' }, { type: 'enum_item', data: { uuid: 'a', name: 'Unmatched', url: 'https://example.com/a)b' }, }, { type: 'enum_item', data: { uuid: 'b', name: 'Matched', url: 'https://example.com/(a)b' }, }, { type: 'enum_end' }, ]; assert.equal( formatSummary(summary), [ 'Sources[^1]', '', '- [Unmatched](https://example.com/a%29b)', '- [Matched](https://example.com/(a)b)', '', '[^1]: [example.com](https://example.com/a%28b)', ].join('\n') ); }); }); - src/tools/summarizer/format.ts (2462 bytes)
import { encodeUnmatchedParentheses, getDisplayHostname } from '../urls.js'; import type { SummaryEntity, SummaryMessage } from './types.js'; /** * An entity as a list item: its name, linked when it has a URL, then its * description. A description sometimes begins with its own separator * ("– 828 m"), which is dropped so every item uses the same one. A separator * is followed by a space, which tells it apart from a minus sign ("-10 °C"). */ function formatEntityItem({ name, url, text }: SummaryEntity): string { const label = url ? `[${name}](${encodeUnmatchedParentheses(url)})` : name; const description = text?.trim().replace(/^[:–—-]\s+/, ''); return description ? `${label} – ${description}` : label; } /** * Joins the parts of a summary message into markdown. Tokens are kept as * written, and the entities between enum_start and enum_end become a list. * The tokens around a list do not reliably end or begin with a line break, so * the list is set apart by blank lines. * * Inline references become footnote markers, with one footnote per source * URL listed after the summary. References often come several at a time and * cite the same sources repeatedly, so this keeps each URL out of the text. */ export function formatSummary(summary: SummaryMessage[]): string { let text = ''; let ordered = false; let itemNumber = 0; // Each source URL's footnote number, in order of first reference. const footnotes = new Map<string, number>(); for (const part of summary) { switch (part.type) { case 'token': text += part.data; break; case 'inline_reference': { const number = footnotes.get(part.data.url) ?? footnotes.size + 1; footnotes.set(part.data.url, number); text += `[^${number}]`; break; } case 'enum_start': ordered = part.data === 'ol'; itemNumber = 0; text = `${text.trimEnd()}\n\n`; break; case 'enum_item': itemNumber += 1; text += `${ordered ? `${itemNumber}.` : '-'} ${formatEntityItem(part.data)}\n`; break; case 'enum_end': text += '\n'; break; } } const body = text.trim(); if (footnotes.size === 0) return body; const definitions = [...footnotes].map( ([url, number]) => `[^${number}]: [${getDisplayHostname(url)}](${encodeUnmatchedParentheses(url)})` ); return `${body}\n\n${definitions.join('\n')}`; } - tsconfig.json (399 bytes)
{ "compilerOptions": { "outDir": "./dist", "rootDir": "src", "target": "ES2022", "module": "NodeNext", "moduleResolution": "NodeNext", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "resolveJsonModule": true, "noUnusedLocals": true }, "include": ["src/**/*"], "exclude": ["node_modules"] }