Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f9d75aa18c |
No files matched your search
@@ -1,7 +0,0 @@
|
||||
.git
|
||||
node_modules
|
||||
dist
|
||||
.env
|
||||
.env.*
|
||||
secrets
|
||||
.cursor
|
||||
@@ -1 +0,0 @@
|
||||
* @jonathansampson
|
||||
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
||||
"extends": [
|
||||
"local>brave/renovate-config"
|
||||
]
|
||||
}
|
||||
@@ -1,273 +0,0 @@
|
||||
name: Build Release
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: >
|
||||
Optional explicit release semver (e.g. 2.1.0). Must be greater than the
|
||||
version currently published to npm. Leave empty to bump patch from package.json.
|
||||
required: false
|
||||
default: ''
|
||||
type: string
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
permissions:
|
||||
# Give the default GITHUB_TOKEN write permission to commit and push the
|
||||
# added or changed files to the repository.
|
||||
contents: write
|
||||
# Allow the job to send a JWT token request to the OIDC provider
|
||||
id-token: write
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
with:
|
||||
ref: ${{ github.head_ref }}
|
||||
|
||||
- uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0
|
||||
with:
|
||||
node-version: '24.x'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
|
||||
- name: Configure Git
|
||||
run: |
|
||||
git config --global user.name "github-actions[bot]"
|
||||
git config --global user.email "github-actions[bot]@users.noreply.github.com"
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
# Install latest version of jq
|
||||
- name: Install latest version of jq to populate Marketplace Catalog StartChangeSet to publish new revision
|
||||
uses: vegardit/gha-setup-jq@fae9c6aa0b21dbe5bd3b77d280cf142e0a0a65b4 # 1.1.0
|
||||
with:
|
||||
version: "latest"
|
||||
|
||||
- name: Bump version
|
||||
id: bump-version
|
||||
env:
|
||||
EXPLICIT_VERSION: ${{ inputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
PKG=$(node -p "require('./package.json').name")
|
||||
PKG_JSON_VERSION=$(node -p "require('./package.json').version")
|
||||
EXPLICIT_RAW=$(printf '%s' "${EXPLICIT_VERSION:-}" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
|
||||
|
||||
if [ -z "$EXPLICIT_RAW" ]; then
|
||||
TAG=$(npm version patch --no-git-tag-version)
|
||||
VERSION=${TAG#v}
|
||||
else
|
||||
NPM_LATEST=$(npm view "$PKG" version) || {
|
||||
printf 'Package name (raw): %q\n' "$PKG" >&2
|
||||
echo "::error::Could not read the published version for comparison from npm (see log for package name)."
|
||||
exit 1
|
||||
}
|
||||
CLEANED=$(node -e "const semver=require('semver');const c=semver.clean(process.argv[1]);if(!c){process.exit(1)};process.stdout.write(c)" "$EXPLICIT_RAW") || {
|
||||
printf 'Received explicit version input (raw): %q\n' "$EXPLICIT_RAW" >&2
|
||||
echo "::error::Invalid semver for explicit version (see log for raw value)."
|
||||
exit 1
|
||||
}
|
||||
node -e "const semver=require('semver');const exp=process.argv[1];const latest=process.argv[2];const pkg=process.argv[3];\
|
||||
if(!semver.gt(exp,latest)){console.error('Explicit version',exp,'must be greater than npm latest',latest);process.exit(1);}\
|
||||
if(semver.lt(exp,pkg)){console.error('Explicit version',exp,'must not be less than package.json version',pkg);process.exit(1);}" \
|
||||
"$CLEANED" "$NPM_LATEST" "$PKG_JSON_VERSION"
|
||||
npm version "$CLEANED" --no-git-tag-version --allow-same-version
|
||||
VERSION="$CLEANED"
|
||||
TAG="v${VERSION}"
|
||||
fi
|
||||
|
||||
jq --arg v "$VERSION" '(.version,.packages[].version) = $v' server.json > tmp && mv tmp server.json
|
||||
echo "tag=${TAG}" >> $GITHUB_OUTPUT
|
||||
echo "version=${VERSION}" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Build assets
|
||||
run: npm run build
|
||||
|
||||
- name: Commit build assets
|
||||
run: |
|
||||
git add package.json package-lock.json server.json
|
||||
git commit -m "ci: update build assets (${{ steps.bump-version.outputs.tag }})"
|
||||
git push
|
||||
|
||||
- name: Generate Changelog
|
||||
id: changelog
|
||||
run: |
|
||||
COMMIT_MESSAGE=$(git log -1 --pretty=format:'%s')
|
||||
echo "# Changelog for ${{ steps.bump-version.outputs.tag }}" > ${{ github.workspace }}/RELEASE_NOTES.md
|
||||
echo "* Updated version" >> ${{ github.workspace }}/RELEASE_NOTES.md
|
||||
echo "${COMMIT_MESSAGE}" >> ${{ github.workspace }}/RELEASE_NOTES.md
|
||||
echo "release_notes<<EOF" >> $GITHUB_OUTPUT
|
||||
cat ${{ github.workspace }}/RELEASE_NOTES.md >> $GITHUB_OUTPUT
|
||||
echo "EOF" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Create release
|
||||
uses: softprops/action-gh-release@153bb8e04406b158c6c84fc1615b65b24149a1fe # v2.6.1
|
||||
id: create_release
|
||||
with:
|
||||
body_path: ${{ github.workspace }}/RELEASE_NOTES.md
|
||||
tag_name: ${{ steps.bump-version.outputs.tag }}
|
||||
generate_release_notes: true
|
||||
make_latest: true
|
||||
|
||||
- name: Publish NPM package
|
||||
run: npm publish --access public
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
|
||||
# DockerHub authentication
|
||||
- name: Login to Docker Hub
|
||||
id: login-docker
|
||||
uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0
|
||||
with:
|
||||
username: ${{ vars.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
# AWS Marketplace ECR authentication
|
||||
- name: Configure AWS Credentials to deploy to AWS Marketplace ECR
|
||||
uses: aws-actions/configure-aws-credentials@ec61189d14ec14c8efccab744f656cffd0e33f37 # v6.1.0
|
||||
with:
|
||||
role-to-assume: ${{ secrets.MARKETPL_AWS_IAM_ROLE_ARN }}
|
||||
aws-region: us-east-1
|
||||
|
||||
- name: Login to Amazon ECR
|
||||
id: login-ecr
|
||||
uses: aws-actions/amazon-ecr-login@f2e9fc6c2b355c1890b65e6f6f0e2ac3e6e22f78 # v2.1.2
|
||||
with:
|
||||
registries: ${{ secrets.MARKETPL_ECR_AWS_ACCOUNT_ID }}
|
||||
|
||||
# Build docker image to support multi-architecture (https://aws.amazon.com/blogs/containers/introducing-multi-architecture-container-images-for-amazon-ecr/)
|
||||
# Extend Docker build capabilities by using Buildx (https://github.com/docker/buildx)
|
||||
- name: Set up QEMU to support multi-architecute builds
|
||||
uses: docker/setup-qemu-action@ce360397dd3f832beb865e1373c09c0e9f86d70a # v4.0.0
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@4d04d5d9486b7bd6fa91e7baf45bbb4f8b9deedd # v4.0.0
|
||||
|
||||
- name: Set GitHub short SHA Tag
|
||||
id: vars
|
||||
run: echo "short_sha=${GITHUB_SHA::7}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Validate Docker Build Configuration
|
||||
uses: docker/build-push-action@d08e5c354a6adb9ed34480a06d141179aa583294 # v7.0.0
|
||||
with:
|
||||
call: check
|
||||
|
||||
# Push to DockerHub (per production best practice, remove 'latest' tag)
|
||||
# Push to AWS Marketplace-owned ECR Repository (https://docs.aws.amazon.com/marketplace/latest/userguide/container-product-policies.html)
|
||||
- name: Build, tag and push to Docker Hub and AWS Marketplace ECR
|
||||
env:
|
||||
DOCKER_REGISTRY: ${{ github.repository }}
|
||||
MARKETPL_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
|
||||
MARKETPL_REPOSITORY: brave/brave-search-mcp
|
||||
IMAGE_RELEASE_TAG: ${{ steps.bump-version.outputs.tag }}
|
||||
uses: docker/build-push-action@d08e5c354a6adb9ed34480a06d141179aa583294 # v7.0.0
|
||||
with:
|
||||
platforms: linux/amd64,linux/aarch64
|
||||
push: true
|
||||
sbom: false
|
||||
provenance: false
|
||||
tags: |
|
||||
${{ env.DOCKER_REGISTRY }}:${{ env.IMAGE_RELEASE_TAG }}
|
||||
${{ env.DOCKER_REGISTRY }}:${{ github.sha }}
|
||||
${{ env.DOCKER_REGISTRY }}:${{ steps.vars.outputs.short_sha }}
|
||||
${{ env.MARKETPL_REGISTRY }}/${{ env.MARKETPL_REPOSITORY }}:${{ env.IMAGE_RELEASE_TAG }}
|
||||
${{ env.MARKETPL_REGISTRY }}/${{ env.MARKETPL_REPOSITORY }}:${{ github.sha }}
|
||||
${{ env.MARKETPL_REGISTRY }}/${{ env.MARKETPL_REPOSITORY }}:${{ steps.vars.outputs.short_sha }}
|
||||
|
||||
# Publish to MCP Registry
|
||||
# Reference: https://github.com/modelcontextprotocol/registry/blob/main/docs/guides/publishing/publish-server.md
|
||||
- name: Install MCP Publisher
|
||||
env:
|
||||
MCP_PUBLISHER_VERSION: v1.7.9
|
||||
run: |
|
||||
set -euo pipefail
|
||||
FILENAME="mcp-publisher_$(uname -s | tr '[:upper:]' '[:lower:]')_$(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/').tar.gz"
|
||||
CHECKSUMS_FILE="registry_${MCP_PUBLISHER_VERSION#v}_checksums.txt"
|
||||
BASE_URL="https://github.com/modelcontextprotocol/registry/releases/download/${MCP_PUBLISHER_VERSION}"
|
||||
curl -fSL "${BASE_URL}/${FILENAME}" -o "${FILENAME}"
|
||||
curl -fSL "${BASE_URL}/${CHECKSUMS_FILE}" -o checksums.txt
|
||||
grep -E " ${FILENAME}$" checksums.txt | sha256sum -c
|
||||
tar xzf "${FILENAME}" mcp-publisher
|
||||
|
||||
- name: Login to MCP Registry
|
||||
run: ./mcp-publisher login github-oidc
|
||||
|
||||
- name: Publish to MCP Registry
|
||||
run: ./mcp-publisher publish
|
||||
|
||||
# Update JSON template to deploy Brave Search MCP Server to AWS Marketplace Management Portal
|
||||
# Update Release Version
|
||||
- name: Update Release Version Title in marketplace-revision-release.json
|
||||
env:
|
||||
IMAGE_RELEASE_TAG: ${{ steps.bump-version.outputs.tag }}
|
||||
run: |
|
||||
jq --arg tag "$IMAGE_RELEASE_TAG" '.ChangeSet[].DetailsDocument.Version.VersionTitle = "Release Version \($tag)"' marketplace-revision-release.json > tmp.json && mv tmp.json marketplace-revision-release.json
|
||||
jq --arg tag "$IMAGE_RELEASE_TAG" '.ChangeSetTags[] |= (if .Key == "Release" then .Value = $tag else . end)' marketplace-revision-release.json > tmp.json && mv tmp.json marketplace-revision-release.json
|
||||
# Update Release Notes
|
||||
- name: Update Release Notes in marketplace-revision-release.json
|
||||
env:
|
||||
RELEASE_NOTES: ${{ steps.changelog.outputs.release_notes }}
|
||||
run: |
|
||||
jq --arg notes "$RELEASE_NOTES" '.ChangeSet[].DetailsDocument.Version.ReleaseNotes = $notes' marketplace-revision-release.json > tmp.json && mv tmp.json marketplace-revision-release.json
|
||||
|
||||
# Update Version Title
|
||||
- name: Update Version Title in marketplace-revision-release.json
|
||||
env:
|
||||
TITLE: 'Release ${{ steps.bump-version.outputs.tag }}'
|
||||
run: |
|
||||
jq --arg title "$TITLE" '.ChangeSet[].DetailsDocument.Version.VersionTitle = $title' marketplace-revision-release.json > tmp.json && mv tmp.json marketplace-revision-release.json
|
||||
|
||||
# Generate ClientRequestToken
|
||||
# See https://docs.aws.amazon.com/marketplace/latest/APIReference/API_StartChangeSet.html
|
||||
- name: Generate UUID for ClientRequestToken used with StartChangeSet
|
||||
id: custom_token
|
||||
run: echo "client_request_token=$(uuidgen)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Update ClientRequestToken in marketplace-revision-release.json
|
||||
env:
|
||||
TOKEN: ${{ steps.custom_token.outputs.client_request_token }}
|
||||
run: |
|
||||
jq --arg token "$TOKEN" '.ClientRequestToken = $token' marketplace-revision-release.json > tmp.json && mv tmp.json marketplace-revision-release.json
|
||||
|
||||
# Update DeliveryOptions
|
||||
- name: Update DeliveryOptions images in marketplace-revision-release.json
|
||||
env:
|
||||
IMAGES: '["${{ steps.login-ecr.outputs.registry }}/brave/brave-search-mcp:${{ steps.bump-version.outputs.tag }}"]'
|
||||
run: |
|
||||
jq --argjson imgs "$IMAGES" '.ChangeSet[].DetailsDocument.DeliveryOptions[].Details.EcrDeliveryOptionDetails.ContainerImages = $imgs' marketplace-revision-release.json > tmp.json && mv tmp.json marketplace-revision-release.json
|
||||
|
||||
- name: Update DeliveryOptions Description for Brave Search MCP Server option in marketplace-revision-release.json
|
||||
env:
|
||||
DESCRIPTION: "docker pull ${{ steps.login-ecr.outputs.registry }}/brave/brave-search-mcp:${{ steps.bump-version.outputs.tag }}"
|
||||
run: |
|
||||
jq --arg desc "$DESCRIPTION" '.ChangeSet[].DetailsDocument.DeliveryOptions[] |= (if .DeliveryOptionTitle == "Brave Search MCP Server" then .Details.EcrDeliveryOptionDetails.Description = $desc else . end)' marketplace-revision-release.json > tmp.json && mv tmp.json marketplace-revision-release.json
|
||||
|
||||
- name: Update DeliveryOptions Usage Instructions for Docker Image option in marketplace-revision-release.json
|
||||
env:
|
||||
USAGE: 'docker run --rm -ti -p 8080:8080 --cap-drop all --read-only -e BRAVE_API_KEY=\"XXXX\" -e BRAVE_MCP_TRANSPORT=http -e BRAVE_MCP_PORT=8080 -e BRAVE_MCP_HOST=0.0.0.0 ${{ steps.login-ecr.outputs.registry }}/brave/brave-search-mcp:${{ steps.bump-version.outputs.tag }}'
|
||||
run: |
|
||||
jq --arg usage "$USAGE" '.ChangeSet[].DetailsDocument.DeliveryOptions[] |= (if .DeliveryOptionTitle == "Docker Image" then .Details.EcrDeliveryOptionDetails.UsageInstructions = $usage else . end)' marketplace-revision-release.json > tmp.json && mv tmp.json marketplace-revision-release.json
|
||||
|
||||
- name: Update DeliveryOptions Description for Docker Image option in marketplace-revision-release.json
|
||||
env:
|
||||
DESCRIPTION: 'To obtain a Brave Search API key, go to https://aws.amazon.com/marketplace/pp/prodview-qjlabherxghtq and purchase a subscription within the AWS account where Brave Search MCP Server will be used. \n\nPlease refer to AWS ECS or EKS documentation for configuring workloads to provide the environment variables referenced in the Usage Instructions.'
|
||||
run: |
|
||||
jq --arg desc "$DESCRIPTION" '.ChangeSet[].DetailsDocument.DeliveryOptions[] |= (if .DeliveryOptionTitle == "Docker Image" then .Details.EcrDeliveryOptionDetails.Description = $desc else . end)' marketplace-revision-release.json > tmp.json && mv tmp.json marketplace-revision-release.json
|
||||
|
||||
- name: Update ChangeSetName in marketplace-revision-release.json
|
||||
env:
|
||||
NAME: 'Add Version ${{ steps.bump-version.outputs.tag }} Release'
|
||||
run: |
|
||||
jq --arg name "$NAME" '.ChangeSetName = $name' marketplace-revision-release.json > tmp.json && mv tmp.json marketplace-revision-release.json
|
||||
|
||||
- name: Validate marketplace-revision-release.json contents
|
||||
run:
|
||||
jq . marketplace-revision-release.json
|
||||
|
||||
- name: Publish New Release to AWS Marketplace Catalog Management Portal
|
||||
run: |
|
||||
aws marketplace-catalog start-change-set \
|
||||
--cli-input-json file://marketplace-revision-release.json
|
||||
@@ -1,33 +0,0 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
- uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0
|
||||
with:
|
||||
node-version: '24.x'
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Check formatting
|
||||
run: npm run format:check
|
||||
|
||||
- name: Build (typecheck)
|
||||
run: npm run build
|
||||
|
||||
- name: Test
|
||||
run: npm test
|
||||
@@ -1,6 +0,0 @@
|
||||
/node_modules
|
||||
/dist
|
||||
/scratch
|
||||
.env
|
||||
secrets/*
|
||||
!secrets/brave_api_key.txt.example
|
||||
@@ -1,23 +0,0 @@
|
||||
# Dependencies
|
||||
node_modules/
|
||||
|
||||
# Build outputs
|
||||
dist/
|
||||
build/
|
||||
*.d.ts
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
|
||||
# OS generated files
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/
|
||||
.idea/
|
||||
|
||||
# Package files
|
||||
package-lock.json
|
||||
yarn.lock
|
||||
-10
@@ -1,10 +0,0 @@
|
||||
{
|
||||
"semi": true,
|
||||
"singleQuote": true,
|
||||
"tabWidth": 2,
|
||||
"trailingComma": "es5",
|
||||
"printWidth": 100,
|
||||
"useTabs": false,
|
||||
"bracketSpacing": true,
|
||||
"arrowParens": "always"
|
||||
}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
FROM node:alpine@sha256:5209bcaca9836eb3448b650396213dbe9d9a34d31840c2ae1f206cb2986a8543 AS builder
|
||||
|
||||
RUN apk add --no-cache openssl=3.5.8-r0
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY ./package.json ./package.json
|
||||
COPY ./package-lock.json ./package-lock.json
|
||||
|
||||
RUN npm ci --ignore-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.8-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"]
|
||||
@@ -1,22 +0,0 @@
|
||||
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.
|
||||
@@ -1,461 +1,3 @@
|
||||
# Brave Search MCP Server
|
||||
# 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, and AI-powered 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).
|
||||
|
||||
## 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 AI summarization
|
||||
|
||||
### 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
|
||||
|
||||
### Summarizer Search (`brave_summarizer`)
|
||||
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 URL references (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 Docker secrets and similar mounted-secret setups.
|
||||
- `BRAVE_MCP_TRANSPORT`: Transport mode ("http" or "stdio", default: "stdio")
|
||||
- `BRAVE_MCP_PORT`: HTTP server port (default: 8080)
|
||||
- `BRAVE_MCP_HOST`: HTTP server host (default: "127.0.0.1"). Binds to loopback only by default; set to "0.0.0.0" to expose the server on all interfaces (required inside containers and on Amazon Bedrock AgentCore). Only do this on a trusted network, since the HTTP endpoint is unauthenticated.
|
||||
- `BRAVE_MCP_ALLOWED_ORIGINS`: Space- or comma-separated list of additional `Origin` header values permitted for the HTTP transport. Loopback origins are always allowed; browser requests carrying any other `Origin` are rejected with HTTP 403 to guard against DNS rebinding. Set this when a browser-based client on a real domain needs access.
|
||||
- `BRAVE_MCP_ALLOWED_HOSTS`: Space- or comma-separated list of hostnames permitted in the `Host` header of the HTTP transport. Matching is on the hostname only and is case-insensitive; a numeric port in an entry (e.g. `mcp.example.com:8080`) is accepted but ignored for matching. Optional, opt-in defense-in-depth: when unset (default) the `Host` header is not validated, so reverse-proxy and custom-domain deployments are unaffected. When set, only loopback hosts and the listed hostnames are accepted; any other `Host` (including malformed/non-numeric ports) is rejected with HTTP 403.
|
||||
- `BRAVE_MCP_LOG_LEVEL`: Desired logging level("debug", "info", "notice", "warning", "error", "critical", "alert", or "emergency", default: "info")
|
||||
- `BRAVE_MCP_ENABLED_TOOLS`: When used, specifies a space-separated whitelist for supported tools
|
||||
- `BRAVE_MCP_DISABLED_TOOLS`: When used, specifies a space-separated blacklist for supported tools
|
||||
- `BRAVE_MCP_STATELESS`: HTTP stateless mode (default: "true"). When running on Amazon Bedrock Agentcore, set to "true".
|
||||
|
||||
### Command Line Options
|
||||
|
||||
```bash
|
||||
node dist/index.js [options]
|
||||
|
||||
Options:
|
||||
--brave-api-key <string> Brave API key
|
||||
--brave-api-key-file <string> Path to file containing Brave API key
|
||||
--transport <stdio|http> Transport type (default: stdio)
|
||||
--port <number> HTTP server port (default: 8080)
|
||||
--host <string> HTTP server host (default: 127.0.0.1)
|
||||
--allowed-origins <origins...> Allowed Origin header values for HTTP transport (DNS rebinding protection)
|
||||
--allowed-hosts <hosts...> Allowed Host header values for HTTP transport (opt-in DNS rebinding protection)
|
||||
--logging-level <string> Desired logging level (one of _debug_, _info_, _notice_, _warning_, _error_, _critical_, _alert_, or _emergency_)
|
||||
--enabled-tools Tools whitelist (only the specified tools will be enabled)
|
||||
--disabled-tools Tools blacklist (included tools will be disabled)
|
||||
--stateless <boolean> HTTP Stateless flag
|
||||
```
|
||||
|
||||
## Installation
|
||||
|
||||
### Usage with Claude Desktop
|
||||
|
||||
Add this to your `claude_desktop_config.json`:
|
||||
|
||||
#### Docker
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"brave-search": {
|
||||
"command": "docker",
|
||||
"args": ["run", "-i", "--rm", "-e", "BRAVE_API_KEY", "docker.io/mcp/brave-search"],
|
||||
"env": {
|
||||
"BRAVE_API_KEY": "YOUR_API_KEY_HERE"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### NPX
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"brave-search": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@brave/brave-search-mcp-server", "--transport", "http"],
|
||||
"env": {
|
||||
"BRAVE_API_KEY": "YOUR_API_KEY_HERE"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Usage with VS Code
|
||||
|
||||
For quick installation, use the one-click installation buttons below:
|
||||
|
||||
[](https://insiders.vscode.dev/redirect/mcp/install?name=brave-search&inputs=%5B%7B%22password%22%3Atrue%2C%22id%22%3A%22brave-api-key%22%2C%22type%22%3A%22promptString%22%2C%22description%22%3A%22Brave+Search+API+Key%22%7D%5D&config=%7B%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22%40brave%2Fbrave-search-mcp-server%22%2C%22--transport%22%2C%22stdio%22%5D%2C%22env%22%3A%7B%22BRAVE_API_KEY%22%3A%22%24%7Binput%3Abrave-api-key%7D%22%7D%7D) [](https://insiders.vscode.dev/redirect/mcp/install?name=brave-search&inputs=%5B%7B%22password%22%3Atrue%2C%22id%22%3A%22brave-api-key%22%2C%22type%22%3A%22promptString%22%2C%22description%22%3A%22Brave+Search+API+Key%22%7D%5D&config=%7B%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22%40brave%2Fbrave-search-mcp-server%22%2C%22--transport%22%2C%22stdio%22%5D%2C%22env%22%3A%7B%22BRAVE_API_KEY%22%3A%22%24%7Binput%3Abrave-api-key%7D%22%7D%7D&quality=insiders)
|
||||
[](https://insiders.vscode.dev/redirect/mcp/install?name=brave-search&inputs=%5B%7B%22password%22%3Atrue%2C%22id%22%3A%22brave-api-key%22%2C%22type%22%3A%22promptString%22%2C%22description%22%3A%22Brave+Search+API+Key%22%7D%5D&config=%7B%22command%22%3A%22docker%22%2C%22args%22%3A%5B%22run%22%2C%22-i%22%2C%22--rm%22%2C%22-e%22%2C%22BRAVE_API_KEY%22%2C%22mcp%2Fbrave-search%22%5D%2C%22env%22%3A%7B%22BRAVE_API_KEY%22%3A%22%24%7Binput%3Abrave-api-key%7D%22%7D%7D) [](https://insiders.vscode.dev/redirect/mcp/install?name=brave-search&inputs=%5B%7B%22password%22%3Atrue%2C%22id%22%3A%22brave-api-key%22%2C%22type%22%3A%22promptString%22%2C%22description%22%3A%22Brave+Search+API+Key%22%7D%5D&config=%7B%22command%22%3A%22docker%22%2C%22args%22%3A%5B%22run%22%2C%22-i%22%2C%22--rm%22%2C%22-e%22%2C%22BRAVE_API_KEY%22%2C%22mcp%2Fbrave-search%22%5D%2C%22env%22%3A%7B%22BRAVE_API_KEY%22%3A%22%24%7Binput%3Abrave-api-key%7D%22%7D%7D&quality=insiders)
|
||||
|
||||
For manual installation, add the following to your User Settings (JSON) or `.vscode/mcp.json`:
|
||||
|
||||
#### Docker
|
||||
|
||||
```json
|
||||
{
|
||||
"inputs": [
|
||||
{
|
||||
"password": true,
|
||||
"id": "brave-api-key",
|
||||
"type": "promptString",
|
||||
"description": "Brave Search API Key",
|
||||
}
|
||||
],
|
||||
"servers": {
|
||||
"brave-search": {
|
||||
"command": "docker",
|
||||
"args": ["run", "-i", "--rm", "-e", "BRAVE_API_KEY", "mcp/brave-search"],
|
||||
"env": {
|
||||
"BRAVE_API_KEY": "${input:brave-api-key}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### NPX
|
||||
|
||||
```json
|
||||
{
|
||||
"inputs": [
|
||||
{
|
||||
"password": true,
|
||||
"id": "brave-api-key",
|
||||
"type": "promptString",
|
||||
"description": "Brave Search API Key",
|
||||
}
|
||||
],
|
||||
"servers": {
|
||||
"brave-search-mcp-server": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@brave/brave-search-mcp-server", "--transport", "stdio"],
|
||||
"env": {
|
||||
"BRAVE_API_KEY": "${input:brave-api-key}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Usage with fx
|
||||
|
||||
Add this to your `~/.fx/mcp.json`, creating the file if it does not exist:
|
||||
|
||||
#### Docker
|
||||
|
||||
```json
|
||||
{
|
||||
"mcp": {
|
||||
"brave-search": {
|
||||
"command": "docker",
|
||||
"args": ["run", "-i", "--rm", "-e", "BRAVE_API_KEY", "docker.io/mcp/brave-search"],
|
||||
"env": {
|
||||
"BRAVE_API_KEY": "YOUR_API_KEY_HERE"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### NPX
|
||||
|
||||
```json
|
||||
{
|
||||
"mcp": {
|
||||
"brave-search": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@brave/brave-search-mcp-server", "--transport", "stdio"],
|
||||
"env": {
|
||||
"BRAVE_API_KEY": "YOUR_API_KEY_HERE"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Start fx, or type `/mcp reload` if it is already running. To verify the connection, type `/mcp list`.
|
||||
|
||||
## Build
|
||||
|
||||
### Docker
|
||||
|
||||
```bash
|
||||
docker build -t mcp/brave-search:latest .
|
||||
```
|
||||
|
||||
### Local Build
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm run build
|
||||
```
|
||||
|
||||
## Development
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Node.js 22.x or higher
|
||||
- npm
|
||||
- Brave Search API key
|
||||
|
||||
### Setup
|
||||
|
||||
1. Clone the repository:
|
||||
```bash
|
||||
git clone https://github.com/brave/brave-search-mcp-server.git
|
||||
cd brave-search-mcp-server
|
||||
```
|
||||
|
||||
2. Install dependencies:
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
3. Build the project:
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
|
||||
### Testing via Claude Desktop
|
||||
|
||||
Add a reference to your local build in `claude_desktop_config.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"brave-search-dev": {
|
||||
"command": "node",
|
||||
"args": ["C:\\GitHub\\brave-search-mcp-server\\dist\\index.js"], // Verify your path
|
||||
"env": {
|
||||
"BRAVE_API_KEY": "YOUR_API_KEY_HERE"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Testing via MCP Inspector
|
||||
|
||||
The Inspector requires Node 22.19 or newer.
|
||||
|
||||
**STDIO** — the Inspector launches the server itself, so one terminal is enough:
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
npx @modelcontextprotocol/inspector node dist/index.js
|
||||
```
|
||||
|
||||
**HTTP** — the Inspector connects to a URL, so the server must already be listening:
|
||||
|
||||
```bash
|
||||
# terminal 1
|
||||
npm run serve:http
|
||||
|
||||
# terminal 2
|
||||
npm run inspector:http
|
||||
```
|
||||
|
||||
`serve:http` builds, binds `127.0.0.1:8080`, and reads `BRAVE_API_KEY` from `.env`.
|
||||
|
||||
### Available Scripts
|
||||
|
||||
- `npm run build`: Build the TypeScript project
|
||||
- `npm run watch`: Watch for changes and rebuild
|
||||
- `npm test`: Run the test suite
|
||||
- `npm run format`: Format code with Prettier
|
||||
- `npm run format:check`: Check code formatting
|
||||
- `npm run prepare`: Format and build (runs automatically on npm install)
|
||||
|
||||
- `npm run serve:http`: Build, then serve over HTTP at `http://127.0.0.1:8080/mcp`
|
||||
- `npm run inspector`: Launch an instance of MCP Inspector
|
||||
- `npm run inspector:http`: Launch MCP Inspector against `http://127.0.0.1:8080/mcp`
|
||||
|
||||
### Docker Compose
|
||||
|
||||
For local development with Docker:
|
||||
|
||||
```bash
|
||||
docker-compose up --build
|
||||
```
|
||||
|
||||
Set `BRAVE_API_KEY` (or `BRAVE_API_KEY_FILE`) in your shell or a `.env` file before starting the stack. The default `docker-compose.yml` also accepts `BRAVE_API_KEY_FILE` when the path is valid inside the container (for example, from a bind mount or Docker secret).
|
||||
|
||||
#### Docker Compose secrets (optional)
|
||||
|
||||
To avoid putting the API key in an environment variable, you can use [Docker Compose secrets](https://docs.docker.com/compose/how-tos/use-secrets/). The server reads the key from the path in `BRAVE_API_KEY_FILE`, which must exist inside the container.
|
||||
|
||||
1. Copy the example secret file and add your key:
|
||||
|
||||
```bash
|
||||
cp secrets/brave_api_key.txt.example secrets/brave_api_key.txt
|
||||
```
|
||||
|
||||
2. Start the stack with the optional secrets override:
|
||||
|
||||
```bash
|
||||
docker compose -f docker-compose.yml -f docker-compose.secrets.example.yml up --build
|
||||
```
|
||||
|
||||
The override mounts the secret at `/run/secrets/brave_api_key` and sets `BRAVE_API_KEY_FILE` accordingly. See `docker-compose.secrets.example.yml` for the full configuration.
|
||||
|
||||
## License
|
||||
|
||||
This MCP server is licensed under the MIT License. This means you are free to use, modify, and distribute the software, subject to the terms and conditions of the MIT License. For more details, please see the LICENSE file in the project repository.
|
||||
Brave Search MCP server for LLM integration
|
||||
@@ -1,19 +0,0 @@
|
||||
# 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
|
||||
@@ -1,24 +0,0 @@
|
||||
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
|
||||
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"$schema": "https://glama.ai/mcp/schemas/server.json",
|
||||
"maintainers": [
|
||||
"jonathansampson"
|
||||
]
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
{
|
||||
"Catalog": "AWSMarketplace",
|
||||
"ChangeSet": [
|
||||
{
|
||||
"ChangeType": "AddDeliveryOptions",
|
||||
"Entity": {
|
||||
"Type": "ContainerProduct@1.0",
|
||||
"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 searchapi-support@brave.com.",
|
||||
"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"
|
||||
}
|
||||
]
|
||||
}
|
||||
Generated
-2234
File diff suppressed because it is too large.
Load diff
@@ -1,56 +0,0 @@
|
||||
{
|
||||
"name": "@brave/brave-search-mcp-server",
|
||||
"mcpName": "io.github.brave/brave-search-mcp-server",
|
||||
"version": "2.1.4",
|
||||
"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": "shx rm -rf dist && tsc && shx chmod +x dist/*.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\"",
|
||||
"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.30.0",
|
||||
"commander": "14.0.3",
|
||||
"dotenv": "17.3.1",
|
||||
"express": "5.2.1",
|
||||
"zod": "4.3.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/express": "5.0.6",
|
||||
"@types/node": "24.10.13",
|
||||
"ajv": "8.20.0",
|
||||
"prettier": "3.8.1",
|
||||
"semver": "7.7.3",
|
||||
"shx": "0.4.0",
|
||||
"tsx": "4.22.4",
|
||||
"typescript": "5.9.3"
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
YOUR_BRAVE_API_KEY_HERE
|
||||
-30
@@ -1,30 +0,0 @@
|
||||
{
|
||||
"$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.1.4",
|
||||
"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.1.4",
|
||||
"transport": {
|
||||
"type": "stdio"
|
||||
},
|
||||
"environmentVariables": [
|
||||
{
|
||||
"name": "BRAVE_API_KEY",
|
||||
"description": "Your API key for the service",
|
||||
"format": "string",
|
||||
"isRequired": true,
|
||||
"isSecret": true
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,141 +0,0 @@
|
||||
import type { Endpoints } from './types.js';
|
||||
import config from '../config.js';
|
||||
import { stringify } from '../utils.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 getDefaultRequestHeaders = (): Record<string, string> => {
|
||||
return {
|
||||
Accept: 'application/json',
|
||||
'Accept-Encoding': 'gzip',
|
||||
'X-Subscription-Token': config.braveApiKey,
|
||||
};
|
||||
};
|
||||
|
||||
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(`https://api.search.brave.com${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 headers = new Headers(getDefaultRequestHeaders());
|
||||
for (const [key, value] of Object.entries(requestHeaders)) {
|
||||
if (value === undefined || value === null) continue;
|
||||
headers.set(key, String(value));
|
||||
}
|
||||
|
||||
const response = await fetch(urlWithParams, { headers });
|
||||
|
||||
// Handle Error
|
||||
if (!response.ok) {
|
||||
let errorMessage = `${response.status} ${response.statusText}`;
|
||||
|
||||
try {
|
||||
const responseBody = await response.json();
|
||||
errorMessage += `\n${stringify(responseBody, true)}`;
|
||||
} catch {
|
||||
errorMessage += `\n${await response.text()}`;
|
||||
}
|
||||
|
||||
// TODO (Sampson): Setup proper error handling, updating state, etc.
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
// Return Response
|
||||
const responseBody = await response.json();
|
||||
|
||||
return responseBody as Endpoints[T]['response'];
|
||||
}
|
||||
|
||||
export default {
|
||||
issueRequest,
|
||||
};
|
||||
@@ -1,70 +0,0 @@
|
||||
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';
|
||||
|
||||
export type Endpoints = {
|
||||
web: {
|
||||
params: WebQueryParams;
|
||||
response: WebSearchApiResponse;
|
||||
requestHeaders: Headers;
|
||||
};
|
||||
images: {
|
||||
params: ImageQueryParams;
|
||||
response: ImageSearchApiResponse;
|
||||
requestHeaders: Headers;
|
||||
};
|
||||
videos: {
|
||||
params: VideoQueryParams;
|
||||
response: VideoSearchApiResponse;
|
||||
requestHeaders: Headers;
|
||||
};
|
||||
news: {
|
||||
params: NewsQueryParams;
|
||||
response: NewsSearchApiResponse;
|
||||
requestHeaders: Headers;
|
||||
};
|
||||
localPois: {
|
||||
params: LocalPoisParams;
|
||||
response: LocalPoiSearchApiResponse;
|
||||
requestHeaders: Headers;
|
||||
};
|
||||
localDescriptions: {
|
||||
params: LocalDescriptionsParams;
|
||||
response: LocalDescriptionsSearchApiResponse;
|
||||
requestHeaders: Headers;
|
||||
};
|
||||
summarizer: {
|
||||
params: SummarizerQueryParams;
|
||||
response: SummarizerSearchApiResponse;
|
||||
requestHeaders: Headers;
|
||||
};
|
||||
llmContext: {
|
||||
params: LlmQueryParams;
|
||||
response: LlmContextSearchApiResponse;
|
||||
requestHeaders: LlmRequestHeaders;
|
||||
};
|
||||
placeSearch: {
|
||||
params: PlaceSearchQueryParams;
|
||||
response: PlaceSearchApiResponse;
|
||||
requestHeaders: PlaceSearchRequestHeaders;
|
||||
};
|
||||
};
|
||||
@@ -1,200 +0,0 @@
|
||||
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 } from 'node:test';
|
||||
import { getOptions } from './config.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', () => {
|
||||
process.argv = ['node', 'index.js', '--brave-api-key', ' '];
|
||||
|
||||
assert.equal(getOptions(), false);
|
||||
});
|
||||
|
||||
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']);
|
||||
}
|
||||
});
|
||||
});
|
||||
-203
@@ -1,203 +0,0 @@
|
||||
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;
|
||||
@@ -1,25 +0,0 @@
|
||||
#!/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);
|
||||
});
|
||||
@@ -1,82 +0,0 @@
|
||||
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 ToolSchemaShapes = {
|
||||
inputSchema?: ZodRawShape;
|
||||
outputSchema?: ZodRawShape;
|
||||
};
|
||||
|
||||
const schemaShapesByTool = new Map<string, ToolSchemaShapes>(
|
||||
Object.values(tools).map((tool) => [tool.name, tool as ToolSchemaShapes])
|
||||
);
|
||||
|
||||
const toJsonSchema2020 = (shape: ZodRawShape, io: 'input' | 'output'): Tool['inputSchema'] =>
|
||||
z.toJSONSchema(z.object(shape), {
|
||||
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 shapes = schemaShapesByTool.get(tool.name);
|
||||
|
||||
if (!shapes) continue;
|
||||
|
||||
if (shapes.inputSchema && needsRetargeting(tool.inputSchema)) {
|
||||
tool.inputSchema = toJsonSchema2020(shapes.inputSchema, 'input');
|
||||
}
|
||||
|
||||
if (shapes.outputSchema && tool.outputSchema && needsRetargeting(tool.outputSchema)) {
|
||||
tool.outputSchema = toJsonSchema2020(shapes.outputSchema, 'output');
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
});
|
||||
}
|
||||
@@ -1,288 +0,0 @@
|
||||
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 config from '../config.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();
|
||||
});
|
||||
|
||||
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'];
|
||||
const app = httpServer.createApp();
|
||||
server = app.listen(0);
|
||||
await new Promise<void>((resolve) => server.once('listening', resolve));
|
||||
port = (server.address() as AddressInfo).port;
|
||||
baseUrl = `http://127.0.0.1:${port}`;
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
config.allowedOrigins = originalAllowedOrigins;
|
||||
await new Promise<void>((resolve, reject) =>
|
||||
server.close((err) => (err ? reject(err) : resolve()))
|
||||
);
|
||||
});
|
||||
|
||||
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 () => {
|
||||
const app = httpServer.createApp();
|
||||
server = app.listen(0);
|
||||
await new Promise<void>((resolve) => server.once('listening', resolve));
|
||||
port = (server.address() as AddressInfo).port;
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
await new Promise<void>((resolve, reject) =>
|
||||
server.close((err) => (err ? reject(err) : resolve()))
|
||||
);
|
||||
});
|
||||
|
||||
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'];
|
||||
const app = httpServer.createApp();
|
||||
server = app.listen(0);
|
||||
await new Promise<void>((resolve) => server.once('listening', resolve));
|
||||
port = (server.address() as AddressInfo).port;
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
config.allowedHosts = originalAllowedHosts;
|
||||
await new Promise<void>((resolve, reject) =>
|
||||
server.close((err) => (err ? reject(err) : resolve()))
|
||||
);
|
||||
});
|
||||
|
||||
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 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/);
|
||||
});
|
||||
});
|
||||
@@ -1,116 +0,0 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import express, { type Request, type Response } from 'express';
|
||||
import config from '../config.js';
|
||||
import createMcpServer from '../server.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`);
|
||||
});
|
||||
|
||||
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 };
|
||||
@@ -1,2 +0,0 @@
|
||||
export { default as stdioServer } from './stdio.js';
|
||||
export { default as httpServer } from './http.js';
|
||||
@@ -1,76 +0,0 @@
|
||||
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('evil.com@example.com'), null);
|
||||
assert.equal(normalizeHost('example.com/path'), null);
|
||||
assert.equal(normalizeHost('example.com?q=1'), null);
|
||||
assert.equal(normalizeHost('example.com#frag'), null);
|
||||
});
|
||||
});
|
||||
@@ -1,138 +0,0 @@
|
||||
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();
|
||||
};
|
||||
};
|
||||
@@ -1,59 +0,0 @@
|
||||
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 tools from '../tools/index.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(
|
||||
listedTools.map((tool) => tool.name).sort(),
|
||||
Object.values(tools)
|
||||
.map((tool) => tool.name)
|
||||
.sort(),
|
||||
stderr
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,10 +0,0 @@
|
||||
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 };
|
||||
@@ -1,54 +0,0 @@
|
||||
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 } from './testUtils/mcpTestHarness.js';
|
||||
import tools from './tools/index.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();
|
||||
const expectedNames = Object.values(tools)
|
||||
.map((tool) => tool.name)
|
||||
.sort();
|
||||
|
||||
assert.deepEqual(listedTools.map((tool) => tool.name).sort(), expectedNames);
|
||||
|
||||
for (const tool of listedTools) {
|
||||
assert.ok(tool.inputSchema, `${tool.name} is missing an inputSchema`);
|
||||
}
|
||||
});
|
||||
|
||||
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`
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,33 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
||||
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
|
||||
import { after, before } from 'node:test';
|
||||
import createMcpServer from '../server.js';
|
||||
|
||||
/**
|
||||
* 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' });
|
||||
|
||||
await Promise.all([mcpServer.connect(serverTransport), client.connect(clientTransport)]);
|
||||
|
||||
return client;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces global.fetch with a stub that resolves requests via `handler`,
|
||||
* keyed on the request's pathname. Returns a restore function.
|
||||
*/
|
||||
function stubFetch(handler: (url: URL) => unknown): () => void {
|
||||
const originalFetch = globalThis.fetch;
|
||||
|
||||
globalThis.fetch = (async (input: RequestInfo | URL) => {
|
||||
const url = new URL(input instanceof Request ? input.url : input.toString());
|
||||
const body = handler(url);
|
||||
|
||||
if (body === undefined) {
|
||||
throw new Error(`Unmocked Brave API request: ${url.pathname}`);
|
||||
}
|
||||
|
||||
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: (url: URL) => unknown): () => Client {
|
||||
let client: Client;
|
||||
let restoreFetch: () => void;
|
||||
|
||||
before(async () => {
|
||||
restoreFetch = stubFetch(responder);
|
||||
client = await connectTestClient();
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
restoreFetch();
|
||||
await client.close();
|
||||
});
|
||||
|
||||
return () => client;
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
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)
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,82 +0,0 @@
|
||||
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',
|
||||
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.shape,
|
||||
execute,
|
||||
register,
|
||||
};
|
||||
@@ -1,51 +0,0 @@
|
||||
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;
|
||||
@@ -1,23 +0,0 @@
|
||||
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;
|
||||
@@ -1,13 +0,0 @@
|
||||
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.'),
|
||||
});
|
||||
@@ -1,80 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
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';
|
||||
|
||||
export default {
|
||||
WebSearchTool,
|
||||
LocalSearchTool,
|
||||
VideoSearchTool,
|
||||
ImageSearchTool,
|
||||
NewsSearchTool,
|
||||
SummarizerTool,
|
||||
LlmContextTool,
|
||||
PlaceSearchTool,
|
||||
};
|
||||
@@ -1,66 +0,0 @@
|
||||
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));
|
||||
});
|
||||
});
|
||||
@@ -1,70 +0,0 @@
|
||||
import type { TextContent, ToolAnnotations } from '@modelcontextprotocol/sdk/types.js';
|
||||
import { z } from 'zod';
|
||||
import API from '../../BraveAPI/index.js';
|
||||
import { type McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
||||
import {
|
||||
RequestParamsSchema,
|
||||
RequestHeadersSchema,
|
||||
LlmContextInputSchema,
|
||||
type LlmContextInput as QueryParams,
|
||||
} from './schemas/input.js';
|
||||
import { LlmContextSearchApiResponseSchema } from './schemas/output.js';
|
||||
|
||||
export const name = 'brave_llm_context';
|
||||
|
||||
export const annotations: ToolAnnotations = {
|
||||
title: 'Brave LLM Context',
|
||||
openWorldHint: true,
|
||||
};
|
||||
|
||||
export const description = `
|
||||
Retrieves pre-extracted, relevance-ranked web content using Brave's LLM Context API, optimized for AI agents, LLM grounding, and RAG pipelines. Unlike a traditional web search that returns links and short descriptions, this tool returns the actual substance of matching pages — text chunks, tables, code blocks, and structured data — so the model can reason over it directly.
|
||||
|
||||
When to use:
|
||||
- Grounding answers in fresh, relevant web content (RAG)
|
||||
- Giving an AI agent ready-to-use page content from a single search call
|
||||
- Question answering and fact-checking against current sources
|
||||
- Gathering source material for research without manually fetching pages
|
||||
- When you need the contents of pages, not just titles, descriptions, and URLs
|
||||
|
||||
When relaying results in markdown-supporting environments, cite the source URLs from the "sources" map.
|
||||
`.trim();
|
||||
|
||||
export const execute = async (params: QueryParams) => {
|
||||
const parsedParams = RequestParamsSchema.parse(params);
|
||||
const parsedHeaders = RequestHeadersSchema.parse(params);
|
||||
|
||||
const response = await API.issueRequest<'llmContext'>('llmContext', parsedParams, parsedHeaders);
|
||||
const { success, data, error } = LlmContextSearchApiResponseSchema.safeParse(response);
|
||||
const payload = success ? data : z.treeifyError(error);
|
||||
|
||||
return {
|
||||
content: [{ type: 'text', text: JSON.stringify(payload) } as TextContent],
|
||||
isError: !success,
|
||||
structuredContent: payload,
|
||||
};
|
||||
};
|
||||
|
||||
export const register = (mcpServer: McpServer) => {
|
||||
mcpServer.registerTool(
|
||||
name,
|
||||
{
|
||||
title: name,
|
||||
description: description,
|
||||
inputSchema: LlmContextInputSchema,
|
||||
outputSchema: LlmContextSearchApiResponseSchema,
|
||||
annotations: annotations,
|
||||
},
|
||||
execute
|
||||
);
|
||||
};
|
||||
|
||||
export default {
|
||||
name,
|
||||
description,
|
||||
annotations,
|
||||
inputSchema: LlmContextInputSchema.shape,
|
||||
outputSchema: LlmContextSearchApiResponseSchema.shape,
|
||||
execute,
|
||||
register,
|
||||
};
|
||||
@@ -1,284 +0,0 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
/**
|
||||
* Keep up-to-date with documentation:
|
||||
* https://api-dashboard.search.brave.com/api-reference/summarizer/llm_context/get
|
||||
*/
|
||||
|
||||
const CountryCodesSchema = z.enum([
|
||||
'AR',
|
||||
'AU',
|
||||
'AT',
|
||||
'BE',
|
||||
'BR',
|
||||
'CA',
|
||||
'CL',
|
||||
'DK',
|
||||
'FI',
|
||||
'FR',
|
||||
'DE',
|
||||
'GR',
|
||||
'HK',
|
||||
'IN',
|
||||
'ID',
|
||||
'IT',
|
||||
'JP',
|
||||
'KR',
|
||||
'MY',
|
||||
'MX',
|
||||
'NL',
|
||||
'NZ',
|
||||
'NO',
|
||||
'CN',
|
||||
'PL',
|
||||
'PT',
|
||||
'PH',
|
||||
'RU',
|
||||
'SA',
|
||||
'ZA',
|
||||
'ES',
|
||||
'SE',
|
||||
'CH',
|
||||
'TW',
|
||||
'TR',
|
||||
'GB',
|
||||
'US',
|
||||
'ALL',
|
||||
]);
|
||||
|
||||
const SearchLangCodesSchema = z.enum([
|
||||
'ar',
|
||||
'eu',
|
||||
'bn',
|
||||
'bg',
|
||||
'ca',
|
||||
'zh-hans',
|
||||
'zh-hant',
|
||||
'hr',
|
||||
'cs',
|
||||
'da',
|
||||
'nl',
|
||||
'en',
|
||||
'en-gb',
|
||||
'et',
|
||||
'fi',
|
||||
'fr',
|
||||
'gl',
|
||||
'de',
|
||||
'el',
|
||||
'gu',
|
||||
'he',
|
||||
'hi',
|
||||
'hu',
|
||||
'is',
|
||||
'it',
|
||||
'jp',
|
||||
'kn',
|
||||
'ko',
|
||||
'lv',
|
||||
'lt',
|
||||
'ms',
|
||||
'ml',
|
||||
'mr',
|
||||
'nb',
|
||||
'pl',
|
||||
'pt-br',
|
||||
'pt-pt',
|
||||
'pa',
|
||||
'ro',
|
||||
'ru',
|
||||
'sr',
|
||||
'sk',
|
||||
'sl',
|
||||
'es',
|
||||
'sv',
|
||||
'ta',
|
||||
'te',
|
||||
'th',
|
||||
'tr',
|
||||
'uk',
|
||||
'vi',
|
||||
]);
|
||||
|
||||
const FreshnessSchema = z
|
||||
.union([
|
||||
z.enum(['pd', 'pw', 'pm', 'py']),
|
||||
z
|
||||
.string()
|
||||
.regex(
|
||||
/^\d{4}-\d{2}-\d{2}to\d{4}-\d{2}-\d{2}$/,
|
||||
"Use 'pd', 'pw', 'pm', 'py', or a custom range as YYYY-MM-DDtoYYYY-MM-DD."
|
||||
),
|
||||
])
|
||||
.describe(
|
||||
"Filters search results by when they were discovered. The following values are supported: 'pd' - Discovered within the last 24 hours. 'pw' - Discovered within the last 7 days. 'pm' - Discovered within the last 31 days. 'py' - Discovered within the last 365 days. 'YYYY-MM-DDtoYYYY-MM-DD' - Timeframe is also supported by specifying the date range e.g. 2022-04-01to2022-07-30."
|
||||
);
|
||||
|
||||
export const RequestParamsSchema = z.object({
|
||||
query: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(400)
|
||||
.refine((str) => str.split(/\s+/).length <= 50, 'Query cannot exceed 50 words')
|
||||
.describe(
|
||||
"The user's search query term. Query can not be empty. Maximum of 400 characters and 50 words in the query."
|
||||
),
|
||||
country: CountryCodesSchema.describe(
|
||||
'The search query country, where the results come from. The country string is limited to 2 character country codes of supported countries.'
|
||||
).optional(),
|
||||
search_lang: SearchLangCodesSchema.describe(
|
||||
'The search language preference. The 2 or more character language code for which the search results are provided.'
|
||||
).optional(),
|
||||
count: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(50)
|
||||
.describe(
|
||||
'The maximum number of search results considered to select the LLM context data. The default is 20 and the maximum is 50.'
|
||||
)
|
||||
.optional(),
|
||||
spellcheck: z.boolean().describe('Whether to enable spellcheck on the query.').optional(),
|
||||
maximum_number_of_urls: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(50)
|
||||
.describe('Maximum number of different URLs to include in LLM context.')
|
||||
.optional(),
|
||||
maximum_number_of_tokens: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1024)
|
||||
.max(32768)
|
||||
.describe(
|
||||
'Approximate maximum number of tokens to include in context. The default is 8192 and maximum is 32768.'
|
||||
)
|
||||
.optional(),
|
||||
maximum_number_of_snippets: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(256)
|
||||
.describe(
|
||||
'Maximum number of different snippets (or chunks of text) to include in LLM context. The default is 50 and maximum is 256.'
|
||||
)
|
||||
.optional(),
|
||||
context_threshold_mode: z
|
||||
.enum(['disabled', 'strict', 'lenient', 'balanced'])
|
||||
.describe(
|
||||
'The mode to use to determine the threshold for including content in context. Default is balanced.'
|
||||
)
|
||||
.optional(),
|
||||
maximum_number_of_tokens_per_url: z
|
||||
.number()
|
||||
.int()
|
||||
.min(512)
|
||||
.max(8192)
|
||||
.describe(
|
||||
'Maximum number of tokens to include per URL. The default is 4096 and maximum is 8192.'
|
||||
)
|
||||
.optional(),
|
||||
maximum_number_of_snippets_per_url: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(100)
|
||||
.describe(
|
||||
'Maximum number of snippets to include per URL. The default is 50 and maximum is 100.'
|
||||
)
|
||||
.optional(),
|
||||
goggles: z
|
||||
.union([z.string(), z.array(z.string())])
|
||||
.describe(
|
||||
"Goggles act as a custom re-ranking on top of Brave's search index. The parameter supports both a url where the Goggle is hosted or the definition of the Goggle. Multiple goggle URLs and/or definitions can be provided in an array. For more details, refer to the Goggles repository (i.e., https://github.com/brave/goggles-quickstart)."
|
||||
)
|
||||
.optional(),
|
||||
freshness: FreshnessSchema.optional(),
|
||||
enable_local: z
|
||||
.boolean()
|
||||
.describe(
|
||||
'Whether to enable local recall. Not setting this value means auto-detect and uses local recall if any of the localization headers are provided.'
|
||||
)
|
||||
.optional(),
|
||||
enable_source_metadata: z
|
||||
.boolean()
|
||||
.describe(
|
||||
'Enable source metadata enrichment (site_name, favicon) in the sources attribute of the response.'
|
||||
)
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export const RequestHeadersSchema = z.object({
|
||||
'x-loc-lat': z
|
||||
.number()
|
||||
.min(-90)
|
||||
.max(90)
|
||||
.describe(
|
||||
"The latitude of the client's geographical location in degrees, to provide relevant local results. The latitude must be greater than or equal to -90.0 degrees and less than or equal to +90.0 degrees."
|
||||
)
|
||||
.optional(),
|
||||
'x-loc-long': z
|
||||
.number()
|
||||
.min(-180)
|
||||
.max(180)
|
||||
.describe(
|
||||
"The longitude of the client's geographical location in degrees, to provide relevant local results. The longitude must be greater than or equal to -180.0 and less than or equal to +180.0 degrees."
|
||||
)
|
||||
.optional(),
|
||||
'x-loc-city': z.string().describe('The generic name of the client city').optional(),
|
||||
'x-loc-state': z
|
||||
.string()
|
||||
.max(3)
|
||||
.describe(
|
||||
"A code which could be up to three characters, that represent the client's state/region. The region is the first-level subdivision (the broadest or least specific) of the ISO 3166-2 code."
|
||||
)
|
||||
.optional(),
|
||||
'x-loc-state-name': z
|
||||
.string()
|
||||
.describe(
|
||||
'The name of the client’s state/region. The region is the first-level subdivision (the broadest or least specific) of the ISO 3166-2 code.'
|
||||
)
|
||||
.optional(),
|
||||
'x-loc-country': z
|
||||
.string()
|
||||
.length(2)
|
||||
.describe(
|
||||
'The two letter country code for the client’s country. For a list of country codes, see ISO 3166-1 alpha-2'
|
||||
)
|
||||
.optional(),
|
||||
'x-loc-postal-code': z.string().describe('The client’s postal code').optional(),
|
||||
'api-version': z
|
||||
.string()
|
||||
.regex(/^\d{4}-\d{2}-\d{2}$/)
|
||||
.describe(
|
||||
'The API version to use. This is denoted by the format YYYY-MM-DD. Default is the latest that is available. Read more about API versioning at https://api-dashboard.search.brave.com/documentation/guides/versioning.'
|
||||
)
|
||||
.optional(),
|
||||
accept: z
|
||||
.enum(['application/json', '*/*'])
|
||||
.describe('The default supported media type is application/json.')
|
||||
.optional(),
|
||||
'cache-control': z
|
||||
.literal('no-cache')
|
||||
.describe(
|
||||
'Brave Search will return cached content by default. To prevent caching set the Cache-Control header to no-cache. This is currently done as best effort.'
|
||||
)
|
||||
.optional(),
|
||||
'user-agent': z
|
||||
.string()
|
||||
.describe(
|
||||
'The user agent originating the request. Brave search can utilize the user agent to provide a different experience depending on the device as described by the string. The user agent should follow the commonly used browser agent strings on each platform. For more information on curating user agents, see RFC 9110.'
|
||||
)
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export const LlmContextInputSchema = z.object({
|
||||
...RequestParamsSchema.shape,
|
||||
...RequestHeadersSchema.shape,
|
||||
});
|
||||
|
||||
export type LlmContextInput = z.input<typeof LlmContextInputSchema>;
|
||||
export type LlmQueryParams = z.infer<typeof RequestParamsSchema>;
|
||||
export type LlmRequestHeaders = z.infer<typeof RequestHeadersSchema>;
|
||||
@@ -1,84 +0,0 @@
|
||||
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>;
|
||||
@@ -1,125 +0,0 @@
|
||||
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',
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,91 +0,0 @@
|
||||
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.",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,190 +0,0 @@
|
||||
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',
|
||||
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,
|
||||
};
|
||||
@@ -1,12 +0,0 @@
|
||||
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>;
|
||||
@@ -1,264 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,75 +0,0 @@
|
||||
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',
|
||||
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,
|
||||
};
|
||||
@@ -1,87 +0,0 @@
|
||||
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;
|
||||
@@ -1,66 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
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/local/place_search') {
|
||||
return { type: 'locations' };
|
||||
}
|
||||
});
|
||||
|
||||
it('returns a locations response for a simple location query', async () => {
|
||||
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, { type: 'locations' });
|
||||
});
|
||||
});
|
||||
@@ -1,75 +0,0 @@
|
||||
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',
|
||||
openWorldHint: true,
|
||||
};
|
||||
|
||||
export const description = `
|
||||
Searches Brave's Place Search API. A single call may populate any combination of 'results' (POIs), 'cities', 'addresses', 'streets', 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.shape,
|
||||
execute,
|
||||
register,
|
||||
};
|
||||
@@ -1,254 +0,0 @@
|
||||
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',
|
||||
'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>;
|
||||
@@ -1,294 +0,0 @@
|
||||
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.').optional(),
|
||||
height: z.number().describe('The height of the thumbnail.').optional(),
|
||||
width: z.number().describe('The width of the thumbnail.').optional(),
|
||||
bg_color: z.string().describe('The background color of the thumbnail.').optional(),
|
||||
original: z.url().describe('The original URL of the image.').optional(),
|
||||
logo: z.boolean().describe('Whether the thumbnail is a logo.').optional(),
|
||||
duplicated: z.boolean().describe('Whether the thumbnail is duplicated.').optional(),
|
||||
theme: z.string().describe('The theme of the thumbnail (e.g. "light", "dark").').optional(),
|
||||
});
|
||||
|
||||
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 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(),
|
||||
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>;
|
||||
@@ -1,23 +0,0 @@
|
||||
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/summarizer/search') {
|
||||
return {
|
||||
type: 'summarizer',
|
||||
status: 'complete',
|
||||
summary: [{ type: 'token', data: 'Brave is a privacy-focused browser.' }],
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
it('returns a summary for a completed key', async () => {
|
||||
const result = await getClient().callTool({ name, arguments: { key: 'test-key' } });
|
||||
|
||||
assert.equal(result.isError ?? false, false, JSON.stringify(result.content));
|
||||
assert.ok(Array.isArray(result.content) && result.content.length > 0);
|
||||
});
|
||||
});
|
||||
@@ -1,117 +0,0 @@
|
||||
import type { CallToolResult, ToolAnnotations } from '@modelcontextprotocol/sdk/types.js';
|
||||
import { summarizerQueryParams, type SummarizerQueryParams } from './params.js';
|
||||
import API from '../../BraveAPI/index.js';
|
||||
import { type SummarizerSearchApiResponse } from './types.js';
|
||||
import { type McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
||||
|
||||
export const name = 'brave_summarizer';
|
||||
|
||||
export const annotations: ToolAnnotations = {
|
||||
title: 'Brave Summarizer',
|
||||
openWorldHint: true,
|
||||
};
|
||||
|
||||
export const description = `
|
||||
Retrieves AI-generated summaries of web search results using Brave's Summarizer API. This tool processes search results to create concise, coherent summaries of information gathered from multiple sources.
|
||||
|
||||
When to use:
|
||||
|
||||
- When you need a concise overview of complex topics from multiple sources
|
||||
- For quick fact-checking or getting key points without reading full articles
|
||||
- When providing users with summarized information that synthesizes various perspectives
|
||||
- For research tasks requiring distilled information from web searches
|
||||
|
||||
Returns a text summary that consolidates information from the search results. Optional features include inline references to source URLs and additional entity information.
|
||||
|
||||
Requirements: Must first perform a web search using brave_web_search with summary=true parameter. Requires a Pro AI subscription to access the summarizer functionality.
|
||||
`.trim();
|
||||
|
||||
export const execute = async (params: SummarizerQueryParams) => {
|
||||
const response: CallToolResult = { content: [], isError: false };
|
||||
|
||||
try {
|
||||
const { summary } = await pollForSummary(params);
|
||||
|
||||
if (!summary || summary.length === 0) {
|
||||
response.isError = true;
|
||||
response.content.push({
|
||||
type: 'text' as const,
|
||||
text: 'Unable to retrieve a Summarizer summary.',
|
||||
});
|
||||
} else {
|
||||
const summaryText = summary
|
||||
.map((summary_part) => {
|
||||
if (summary_part.type === 'token') {
|
||||
return summary_part.data;
|
||||
} else if (summary_part.type === 'inline_reference') {
|
||||
return ` (${summary_part.data?.url})`;
|
||||
} else {
|
||||
return '';
|
||||
}
|
||||
})
|
||||
.join('');
|
||||
|
||||
response.content.push({
|
||||
type: 'text' as const,
|
||||
text: summaryText,
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
response.isError = true;
|
||||
response.content.push({
|
||||
type: 'text' as const,
|
||||
text: 'Unable to retrieve a Summarizer summary.',
|
||||
});
|
||||
}
|
||||
|
||||
return response;
|
||||
};
|
||||
|
||||
export const register = (mcpServer: McpServer) => {
|
||||
mcpServer.registerTool(
|
||||
name,
|
||||
{
|
||||
title: name,
|
||||
description: description,
|
||||
inputSchema: summarizerQueryParams,
|
||||
annotations: annotations,
|
||||
},
|
||||
execute
|
||||
);
|
||||
};
|
||||
|
||||
const pollForSummary = async (
|
||||
params: SummarizerQueryParams,
|
||||
pollInterval: number = 50,
|
||||
attempts: number = 20
|
||||
): Promise<SummarizerSearchApiResponse> => {
|
||||
let result: SummarizerSearchApiResponse | null = null;
|
||||
|
||||
while (!result && attempts > 0) {
|
||||
try {
|
||||
const response = await API.issueRequest<'summarizer'>('summarizer', params);
|
||||
if (response.status === 'complete') {
|
||||
result = response;
|
||||
}
|
||||
} catch {
|
||||
await new Promise((resolve) => setTimeout(resolve, pollInterval));
|
||||
}
|
||||
|
||||
attempts--;
|
||||
}
|
||||
|
||||
if (!result) {
|
||||
throw new Error('Summarizer summary could not be retrieved after multiple attempts.');
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
export default {
|
||||
name,
|
||||
description,
|
||||
annotations,
|
||||
inputSchema: summarizerQueryParams.shape,
|
||||
execute,
|
||||
register,
|
||||
};
|
||||
@@ -1,19 +0,0 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const summarizerQueryParams = z.object({
|
||||
key: z
|
||||
.string()
|
||||
.describe('The key is equal to value of field key as part of the Summarizer response model.'),
|
||||
entity_info: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
.describe('Returns extra entities info with the summary response.')
|
||||
.optional(),
|
||||
inline_references: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
.describe('Adds inline references to the summary response.')
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export type SummarizerQueryParams = z.infer<typeof summarizerQueryParams>;
|
||||
@@ -1,139 +0,0 @@
|
||||
export interface SummarizerSearchApiResponse {
|
||||
/** The type of summarizer search API result. The value is always summarizer. */
|
||||
type: 'summarizer';
|
||||
/** The current status of summarizer for the given key. The value can be either failed or complete. */
|
||||
status: string;
|
||||
/** The title for the summary. */
|
||||
title?: string;
|
||||
/** Details for the summary message. */
|
||||
summary?: SummaryMessage[];
|
||||
/** Enrichments that can be added to the summary message. */
|
||||
enrichments?: SummaryEnrichments;
|
||||
/** Followup queries relevant to the current query. */
|
||||
followups?: string[];
|
||||
/** Details on the entities in the summary message. */
|
||||
entities_infos?: Record<string, SummaryEntityInfo>;
|
||||
}
|
||||
|
||||
interface SummaryMessage {
|
||||
/** The type of subset of a summary message. The value can be token (a text excerpt from the summary), enum_item (a summary entity), enum_start (describes the beginning of summary entities, which means the following item(s) in the summary list will be entities), enum_end (the end of summary entities) or inline_reference (an inline reference to the summary, requires inline_references query param to be set). */
|
||||
type: string;
|
||||
/** The summary entity or the explanation for the type field. For type enum_start the value can be ol or ul, which means an ordered list or an unordered list of entities follows respectively. For type enum_end there is no value. For type token the value is a text excerpt. For type enum_item the value is the SummaryEntity response model. For type inline_reference the value is the SummaryInlineReference response model. */
|
||||
data?: SummaryEntity | SummaryInlineReference;
|
||||
}
|
||||
|
||||
interface TextLocation {
|
||||
/** The 0-based index, where the important part of the text starts. */
|
||||
start: number;
|
||||
/** The 0-based index, where the important part of the text ends. */
|
||||
end: number;
|
||||
}
|
||||
|
||||
interface SummaryEntity {
|
||||
/** A unique identifier for the entity. */
|
||||
uuid: string;
|
||||
/** The name of the entity. */
|
||||
name: string;
|
||||
/** The URL where further details on the entity can be found. */
|
||||
url?: string;
|
||||
/** A text message describing the entity. */
|
||||
text?: string;
|
||||
/** The image associated with the entity. */
|
||||
images?: SummaryImage[];
|
||||
/** The location of the entity in the summary message. */
|
||||
highlight?: TextLocation[];
|
||||
}
|
||||
|
||||
interface SummaryInlineReference {
|
||||
/** The type of inline reference. The value is always inline_reference. */
|
||||
type: string;
|
||||
/** The URL that is being referenced. */
|
||||
url: string;
|
||||
/** The start index of the inline reference in the summary message. */
|
||||
start_index: number;
|
||||
/** The end index of the inline reference in the summary message. */
|
||||
end_index: number;
|
||||
/** The ordinal number of the inline reference. */
|
||||
number: number;
|
||||
/** The favicon of the URL that is being referenced. */
|
||||
favicon?: string;
|
||||
/** The reference text snippet. */
|
||||
snippet?: string;
|
||||
}
|
||||
|
||||
interface Thumbnail {
|
||||
/** The served URL of the picture thumbnail. */
|
||||
src: string;
|
||||
/** The original URL of the image. */
|
||||
original?: string;
|
||||
}
|
||||
|
||||
interface ImageProperties {
|
||||
/** The image URL. */
|
||||
url: string;
|
||||
}
|
||||
|
||||
interface Image {
|
||||
/** The thumbnail associated with the image. */
|
||||
thumbnail: Thumbnail;
|
||||
/** The URL of the image. */
|
||||
url?: string;
|
||||
/** Metadata on the image. */
|
||||
properties?: ImageProperties;
|
||||
}
|
||||
|
||||
interface SummaryImage extends Image {
|
||||
/** Text associated with the image. */
|
||||
text?: string;
|
||||
}
|
||||
|
||||
interface SummaryEnrichments {
|
||||
/** The raw summary message. */
|
||||
raw: string;
|
||||
/** The images associated with the summary. */
|
||||
images?: SummaryImage[];
|
||||
/** The answers in the summary message. */
|
||||
qa?: SummaryAnswer[];
|
||||
/** The entities in the summary message. */
|
||||
entities?: SummaryEntity[];
|
||||
/** References based on which the summary was built. */
|
||||
context?: SummaryContext[];
|
||||
}
|
||||
|
||||
interface SummaryAnswer {
|
||||
/** The answer text. */
|
||||
answer: string;
|
||||
/** A score associated with the answer. */
|
||||
score?: number;
|
||||
/** The location of the answer in the summary message. */
|
||||
highlight?: TextLocation;
|
||||
}
|
||||
|
||||
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 SummaryContext {
|
||||
/** The title of the reference. */
|
||||
title: string;
|
||||
/** The URL where the reference can be found. */
|
||||
url: string;
|
||||
/** Details on the URL associated with the reference. */
|
||||
meta_url?: MetaUrl;
|
||||
}
|
||||
|
||||
interface SummaryEntityInfo {
|
||||
/** The name of the provider. */
|
||||
provider?: string;
|
||||
/** Description of the entity. */
|
||||
description?: string;
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
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/videos/search') {
|
||||
return {
|
||||
results: [
|
||||
{
|
||||
url: 'https://example.com/video',
|
||||
title: 'Introducing Brave',
|
||||
description: 'A video about the Brave browser.',
|
||||
age: '1 day ago',
|
||||
video: {
|
||||
duration: '5:00',
|
||||
views: '1000',
|
||||
creator: 'Brave Software',
|
||||
publisher: 'Brave Software',
|
||||
tags: ['browser'],
|
||||
},
|
||||
thumbnail: { src: 'https://example.com/thumb.jpg' },
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
it('returns video 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);
|
||||
});
|
||||
});
|
||||
@@ -1,60 +0,0 @@
|
||||
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_video_search';
|
||||
|
||||
export const annotations: ToolAnnotations = {
|
||||
title: 'Brave Video Search',
|
||||
openWorldHint: true,
|
||||
};
|
||||
|
||||
export const description = `
|
||||
Searches for videos using Brave's Video Search API and returns structured video results with metadata.
|
||||
|
||||
When to use:
|
||||
- When you need to find videos related to a specific topic, keyword, or query.
|
||||
- Useful for discovering video content, getting video metadata, or finding videos from specific creators/publishers.
|
||||
|
||||
Returns a JSON list of video-related results with title, url, description, duration, and thumbnail_url.
|
||||
`.trim();
|
||||
|
||||
export const execute = async (params: QueryParams) => {
|
||||
const response = await API.issueRequest<'videos'>('videos', params);
|
||||
|
||||
return {
|
||||
content: response.results.map(({ url, title, description, video, thumbnail }) => {
|
||||
const duration = video?.duration;
|
||||
const thumbnail_url = thumbnail?.src;
|
||||
|
||||
return {
|
||||
type: 'text' as const,
|
||||
text: stringify({ url, title, description, duration, thumbnail_url }),
|
||||
};
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
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,
|
||||
};
|
||||
@@ -1,81 +0,0 @@
|
||||
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(),
|
||||
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). Combine this parameter with `offset` to paginate search results.'
|
||||
)
|
||||
.optional(),
|
||||
offset: z
|
||||
.int()
|
||||
.min(0)
|
||||
.max(9)
|
||||
.default(0)
|
||||
.describe(
|
||||
'Pagination offset (max 9, default 0). Combine this parameter with `count` to paginate search results.'
|
||||
)
|
||||
.optional(),
|
||||
spellcheck: z
|
||||
.boolean()
|
||||
.describe('Whether to spellcheck provided query.')
|
||||
.default(true)
|
||||
.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(),
|
||||
});
|
||||
|
||||
export type QueryParams = z.infer<typeof params>;
|
||||
|
||||
export default params;
|
||||
@@ -1,99 +0,0 @@
|
||||
export interface VideoSearchApiResponse {
|
||||
/** The type of search API result. The value is always video. */
|
||||
type: 'videos';
|
||||
/** Video search query string. */
|
||||
query: Query;
|
||||
/** The list of video results for the given query. */
|
||||
results: VideoResult[];
|
||||
/** Additional information about the video 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 if any. */
|
||||
altered?: string;
|
||||
/** The cleaned noramlized 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?: string;
|
||||
}
|
||||
|
||||
interface Thumbnail {
|
||||
/** The served URL of the thumbnail associated with the video. */
|
||||
src: string;
|
||||
/** The original URL of the thumbnail associated with the video. */
|
||||
original?: string;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
interface VideoData {
|
||||
/** A time string representing the duration of the video. */
|
||||
duration?: string;
|
||||
/** The number of views of the video. */
|
||||
views?: number;
|
||||
/** The creator of the video. */
|
||||
creator?: string;
|
||||
/** The publisher of the video. */
|
||||
publisher?: string;
|
||||
/** Whether the video requires a subscription. */
|
||||
requires_subscription?: boolean;
|
||||
/** A list of tags relevant to the video. */
|
||||
tags?: string[];
|
||||
/** A list of profiles associated with the video. */
|
||||
author?: Profile;
|
||||
}
|
||||
|
||||
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 VideoResult {
|
||||
/** The type of video search API result. The value is always video_result. */
|
||||
type: 'video_result';
|
||||
/** The source URL of the video. */
|
||||
url: string;
|
||||
/** The title of the video. */
|
||||
title: string;
|
||||
/** The description for the video. */
|
||||
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;
|
||||
/** The thumbnail for the video. */
|
||||
thumbnail?: Thumbnail;
|
||||
/** Metadata for the video. */
|
||||
video?: VideoData;
|
||||
/** Aggregated information on the URL associated with the video search result. */
|
||||
meta_url?: MetaUrl;
|
||||
}
|
||||
|
||||
interface Extra {
|
||||
/** Indicates whether the video search results might contain offensive content. */
|
||||
might_be_offensive: boolean;
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
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',
|
||||
web: {
|
||||
results: [
|
||||
{
|
||||
url: 'https://search.brave.com/',
|
||||
title: 'Brave Search',
|
||||
description: 'A privacy-focused search engine.',
|
||||
extra_snippets: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
it('returns web 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);
|
||||
});
|
||||
});
|
||||
@@ -1,190 +0,0 @@
|
||||
import type { TextContent, ToolAnnotations } from '@modelcontextprotocol/sdk/types.js';
|
||||
import params, { type QueryParams } from './params.js';
|
||||
import API from '../../BraveAPI/index.js';
|
||||
import type {
|
||||
Discussions,
|
||||
FAQ,
|
||||
News,
|
||||
Search,
|
||||
Videos,
|
||||
FormattedFAQResults,
|
||||
FormattedDiscussionsResults,
|
||||
FormattedNewsResults,
|
||||
FormattedVideoResults,
|
||||
FormattedWebResults,
|
||||
} from './types.js';
|
||||
import { stringify } from '../../utils.js';
|
||||
import { type McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
||||
|
||||
export const name = 'brave_web_search';
|
||||
|
||||
export const annotations: ToolAnnotations = {
|
||||
title: 'Brave Web Search',
|
||||
openWorldHint: true,
|
||||
};
|
||||
|
||||
export const description = `
|
||||
Performs web searches using the Brave Search API and returns comprehensive search results with rich metadata.
|
||||
|
||||
When to use:
|
||||
- General web searches for information, facts, or current topics
|
||||
- Location-based queries (restaurants, businesses, points of interest)
|
||||
- News searches for recent events or breaking stories
|
||||
- Finding videos, discussions, or FAQ content
|
||||
- Research requiring diverse result types (web pages, images, reviews, etc.)
|
||||
|
||||
Returns a JSON list of web results with title, description, and URL.
|
||||
|
||||
When the "results_filter" parameter is empty, JSON results may also contain FAQ, Discussions, News, and Video results.
|
||||
`.trim();
|
||||
|
||||
export const execute = async (params: QueryParams) => {
|
||||
const response = { content: [] as TextContent[], isError: false };
|
||||
const { web, faq, discussions, news, videos, summarizer } = await API.issueRequest<'web'>(
|
||||
'web',
|
||||
params
|
||||
);
|
||||
|
||||
if (summarizer) {
|
||||
response.content.push({
|
||||
type: 'text' as const,
|
||||
text: `Summarizer key: ${summarizer.key}`,
|
||||
});
|
||||
}
|
||||
|
||||
if (!web || !Array.isArray(web.results) || web.results.length < 1) {
|
||||
response.isError = true;
|
||||
response.content.push({
|
||||
type: 'text' as const,
|
||||
text: 'No web results found',
|
||||
});
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
// TODO (Sampson): The following is unnecessarily repetitive.
|
||||
for (const entry of formatWebResults(web)) {
|
||||
response.content.push({
|
||||
type: 'text' as const,
|
||||
text: stringify(entry),
|
||||
});
|
||||
}
|
||||
|
||||
if (faq && faq.results?.length > 0) {
|
||||
for (const entry of formatFAQResults(faq)) {
|
||||
response.content.push({
|
||||
type: 'text' as const,
|
||||
text: stringify(entry),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (discussions && discussions.results?.length > 0) {
|
||||
for (const entry of formatDiscussionsResults(discussions)) {
|
||||
response.content.push({
|
||||
type: 'text' as const,
|
||||
text: stringify(entry),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (news && news.results?.length > 0) {
|
||||
for (const entry of formatNewsResults(news)) {
|
||||
response.content.push({
|
||||
type: 'text' as const,
|
||||
text: stringify(entry),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (videos && videos.results?.length > 0) {
|
||||
for (const entry of formatVideoResults(videos)) {
|
||||
response.content.push({
|
||||
type: 'text' as const,
|
||||
text: stringify(entry),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return response;
|
||||
};
|
||||
|
||||
export const formatWebResults = (web: Search): FormattedWebResults => {
|
||||
return (web.results || []).map(({ url, title, description, extra_snippets }) => ({
|
||||
url,
|
||||
title,
|
||||
description,
|
||||
extra_snippets,
|
||||
}));
|
||||
};
|
||||
|
||||
export const register = (mcpServer: McpServer) => {
|
||||
mcpServer.registerTool(
|
||||
name,
|
||||
{
|
||||
title: name,
|
||||
description: description,
|
||||
inputSchema: params,
|
||||
annotations: annotations,
|
||||
},
|
||||
execute
|
||||
);
|
||||
};
|
||||
|
||||
const formatFAQResults = (faq: FAQ): FormattedFAQResults => {
|
||||
return (faq.results || []).map(({ question, answer, title, url }) => ({
|
||||
question,
|
||||
answer,
|
||||
title,
|
||||
url,
|
||||
}));
|
||||
};
|
||||
|
||||
const formatDiscussionsResults = (discussions: Discussions): FormattedDiscussionsResults => {
|
||||
return (discussions.results || []).map(({ url, data }) => ({
|
||||
mutated_by_goggles: discussions.mutated_by_goggles,
|
||||
url,
|
||||
data,
|
||||
}));
|
||||
};
|
||||
|
||||
const formatNewsResults = (news: News): FormattedNewsResults => {
|
||||
return (news.results || []).map(
|
||||
({ source, breaking, is_live, age, url, title, description, extra_snippets }) => ({
|
||||
mutated_by_goggles: news.mutated_by_goggles,
|
||||
source,
|
||||
breaking,
|
||||
is_live,
|
||||
age,
|
||||
url,
|
||||
title,
|
||||
description,
|
||||
extra_snippets,
|
||||
})
|
||||
);
|
||||
};
|
||||
|
||||
const formatVideoResults = (videos: Videos): FormattedVideoResults => {
|
||||
return (videos.results || []).map(({ url, age, title, description, video, thumbnail }) => ({
|
||||
mutated_by_goggles: videos.mutated_by_goggles,
|
||||
url,
|
||||
title,
|
||||
description,
|
||||
age,
|
||||
thumbnail_url: thumbnail?.src,
|
||||
duration: video.duration,
|
||||
view_count: video.views,
|
||||
creator: video.creator,
|
||||
publisher: video.publisher,
|
||||
tags: video.tags,
|
||||
}));
|
||||
};
|
||||
|
||||
export default {
|
||||
name,
|
||||
description,
|
||||
annotations,
|
||||
inputSchema: params.shape,
|
||||
execute,
|
||||
register,
|
||||
};
|
||||
@@ -1,251 +0,0 @@
|
||||
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
|
||||
.enum([
|
||||
'ALL',
|
||||
'AR',
|
||||
'AU',
|
||||
'AT',
|
||||
'BE',
|
||||
'BR',
|
||||
'CA',
|
||||
'CL',
|
||||
'DK',
|
||||
'FI',
|
||||
'FR',
|
||||
'DE',
|
||||
'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',
|
||||
])
|
||||
.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
|
||||
.enum([
|
||||
'ar',
|
||||
'eu',
|
||||
'bn',
|
||||
'bg',
|
||||
'ca',
|
||||
'zh-hans',
|
||||
'zh-hant',
|
||||
'hr',
|
||||
'cs',
|
||||
'da',
|
||||
'nl',
|
||||
'en',
|
||||
'en-gb',
|
||||
'et',
|
||||
'fi',
|
||||
'fr',
|
||||
'gl',
|
||||
'de',
|
||||
'gu',
|
||||
'he',
|
||||
'hi',
|
||||
'hu',
|
||||
'is',
|
||||
'it',
|
||||
'jp',
|
||||
'kn',
|
||||
'ko',
|
||||
'lv',
|
||||
'lt',
|
||||
'ms',
|
||||
'ml',
|
||||
'mr',
|
||||
'nb',
|
||||
'pl',
|
||||
'pt-br',
|
||||
'pt-pt',
|
||||
'pa',
|
||||
'ro',
|
||||
'ru',
|
||||
'sr',
|
||||
'sk',
|
||||
'sl',
|
||||
'es',
|
||||
'sv',
|
||||
'ta',
|
||||
'te',
|
||||
'th',
|
||||
'tr',
|
||||
'uk',
|
||||
'vi',
|
||||
])
|
||||
.default('en')
|
||||
.describe(
|
||||
'Search language preference. The 2 or more character language code for which the search results are provided.'
|
||||
)
|
||||
.optional(),
|
||||
ui_lang: 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',
|
||||
])
|
||||
.default('en-US')
|
||||
.describe(
|
||||
'The language of the UI. The 2 or more character language code for which the search results are provided.'
|
||||
)
|
||||
.optional(),
|
||||
count: z
|
||||
.int()
|
||||
.min(1)
|
||||
.max(20)
|
||||
.default(10)
|
||||
.describe(
|
||||
'Number of results (1-20, default 10). Applies only to web search results (i.e., has no effect on locations, news, videos, etc.)'
|
||||
)
|
||||
.optional(),
|
||||
offset: z
|
||||
.int()
|
||||
.min(0)
|
||||
.max(9)
|
||||
.default(0)
|
||||
.describe('Pagination offset (max 9, default 0)')
|
||||
.optional(),
|
||||
safesearch: z
|
||||
.enum(['off', 'moderate', 'strict'])
|
||||
.default('moderate')
|
||||
.describe(
|
||||
"Filters search results for adult content. The following values are supported: 'off' - No filtering. 'moderate' - Filters explicit content (e.g., images and videos), but allows adult domains in search results. 'strict' - Drops all adult content from search results. 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(),
|
||||
text_decorations: z
|
||||
.boolean()
|
||||
.default(true)
|
||||
.describe(
|
||||
'Whether display strings (e.g. result snippets) should include decoration markers (e.g. highlighting characters).'
|
||||
)
|
||||
.optional(),
|
||||
spellcheck: z
|
||||
.boolean()
|
||||
.default(true)
|
||||
.describe('Whether to spellcheck the provided query.')
|
||||
.optional(),
|
||||
result_filter: z
|
||||
.array(
|
||||
z.enum([
|
||||
'discussions',
|
||||
'faq',
|
||||
'infobox',
|
||||
'news',
|
||||
'query',
|
||||
'summarizer',
|
||||
'videos',
|
||||
'web',
|
||||
'locations',
|
||||
'rich',
|
||||
])
|
||||
)
|
||||
.default(['web', 'query'])
|
||||
.describe("Result filter (default ['web', 'query'])")
|
||||
.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(),
|
||||
units: z
|
||||
.union([z.literal('metric'), z.literal('imperial')])
|
||||
.describe('The measurement units. If not provided, units are derived from search country.')
|
||||
.optional(),
|
||||
extra_snippets: z
|
||||
.boolean()
|
||||
.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(),
|
||||
summary: z
|
||||
.boolean()
|
||||
.describe(
|
||||
'This parameter enables summary key generation in web search results. This is required for summarizer to be enabled.'
|
||||
)
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export type QueryParams = z.infer<typeof params>;
|
||||
|
||||
export default params;
|
||||
@@ -1,956 +0,0 @@
|
||||
export type FormattedWebResults = {
|
||||
url: string;
|
||||
title: string;
|
||||
description?: string;
|
||||
extra_snippets?: string[];
|
||||
}[];
|
||||
|
||||
export type FormattedFAQResults = {
|
||||
question: string;
|
||||
answer: string;
|
||||
title: string;
|
||||
url: string;
|
||||
}[];
|
||||
|
||||
export type FormattedDiscussionsResults = {
|
||||
mutated_by_goggles?: boolean;
|
||||
url: string;
|
||||
data?: ForumData;
|
||||
}[];
|
||||
|
||||
export type FormattedNewsResults = {
|
||||
mutated_by_goggles?: boolean;
|
||||
source?: string;
|
||||
breaking: boolean;
|
||||
is_live: boolean;
|
||||
age?: string;
|
||||
url: string;
|
||||
title: string;
|
||||
description?: string;
|
||||
extra_snippets?: string[];
|
||||
}[];
|
||||
|
||||
export type FormattedVideoResults = {
|
||||
mutated_by_goggles?: boolean;
|
||||
url: string;
|
||||
title: string;
|
||||
description?: string;
|
||||
age?: string;
|
||||
thumbnail_url?: string;
|
||||
duration?: string;
|
||||
view_count?: string;
|
||||
creator?: string;
|
||||
publisher?: string;
|
||||
tags?: string[];
|
||||
}[];
|
||||
|
||||
export interface WebSearchApiResponse {
|
||||
/** The type of web search API result. The value is always search. */
|
||||
type: 'search';
|
||||
/** Discussions clusters aggregated from forum posts that are relevant to the query. */
|
||||
discussions?: Discussions;
|
||||
/** Frequently asked questions that are relevant to the search query. */
|
||||
faq?: FAQ;
|
||||
/** Aggregated information on an entity showable as an infobox. */
|
||||
infobox?: GraphInfobox;
|
||||
/** Places of interest (POIs) relevant to location sensitive queries. */
|
||||
locations?: Locations;
|
||||
/** Preferred ranked order of search results. */
|
||||
mixed?: MixedResponse;
|
||||
/** News results relevant to the query. */
|
||||
news?: News;
|
||||
/** Search query string and its modifications that are used for search. */
|
||||
query?: Query;
|
||||
/** Videos relevant to the query. */
|
||||
videos?: Videos;
|
||||
/** Web search results relevant to the query. */
|
||||
web?: Search;
|
||||
/** Summary key to get summary results for the query. */
|
||||
summarizer?: Summarizer;
|
||||
/** Callback information for rich results. */
|
||||
rich?: RichCallbackInfo;
|
||||
}
|
||||
|
||||
interface Query {
|
||||
/** The original query that was requested. */
|
||||
original: string;
|
||||
/** Whether there is more content available for query, but the response was restricted due to safesearch. */
|
||||
show_strict_warning?: boolean;
|
||||
/** The altered query for which the search was performed. */
|
||||
altered?: string;
|
||||
/** Whether safesearch was enabled. */
|
||||
safesearch?: boolean;
|
||||
/** Whether the query is a navigational query to a domain. */
|
||||
is_navigational?: boolean;
|
||||
/** Whether the query has location relevance. */
|
||||
is_geolocal?: boolean;
|
||||
/** Whether the query was decided to be location sensitive. */
|
||||
local_decision?: string;
|
||||
/** The index of the location. */
|
||||
local_locations_idx?: number;
|
||||
/** Whether the query is trending. */
|
||||
is_trending?: boolean;
|
||||
/** Whether the query has news breaking articles relevant to it. */
|
||||
is_news_breaking?: boolean;
|
||||
/** Whether the query requires location information for better results. */
|
||||
ask_for_location?: boolean;
|
||||
/** The language information gathered from the query. */
|
||||
language?: Language;
|
||||
/** Whether the spellchecker was off. */
|
||||
spellcheck_off?: boolean;
|
||||
/** The country that was used. */
|
||||
country?: string;
|
||||
/** Whether there are bad results for the query. */
|
||||
bad_results?: boolean;
|
||||
/** Whether the query should use a fallback. */
|
||||
should_fallback?: boolean;
|
||||
/** The gathered location latitutde associated with the query. */
|
||||
lat?: string;
|
||||
/** The gathered location longitude associated with the query. */
|
||||
long?: string;
|
||||
/** The gathered postal code associated with the query. */
|
||||
postal_code?: string;
|
||||
/** The gathered city associated with the query. */
|
||||
city?: string;
|
||||
/** The gathered state associated with the query. */
|
||||
state?: string;
|
||||
/** The country for the request origination. */
|
||||
header_country?: string;
|
||||
/** Whether more results are available for the given query. */
|
||||
more_results_available?: boolean;
|
||||
/** Any custom location labels attached to the query. */
|
||||
custom_location_label?: string;
|
||||
/** Any reddit cluster associated with the query. */
|
||||
reddit_cluster?: string;
|
||||
}
|
||||
|
||||
export interface Discussions {
|
||||
/** The type identifying a discussion cluster. Currently the value is always search. */
|
||||
type: 'search';
|
||||
/** A list of discussion results. */
|
||||
results: DiscussionResult[];
|
||||
/** Whether the discussion results are changed by a Goggle. The value is false by default. */
|
||||
mutated_by_goggles: boolean;
|
||||
}
|
||||
|
||||
interface DiscussionResult extends Omit<SearchResult, 'type'> {
|
||||
/** The discussion result type identifier. The value is always discussion. */
|
||||
type: 'discussion';
|
||||
/** The enriched aggregated data for the relevant forum post. */
|
||||
data?: ForumData;
|
||||
}
|
||||
|
||||
interface ForumData {
|
||||
/** The name of the forum. */
|
||||
forum_name: string;
|
||||
/** The number of answers to the post. */
|
||||
num_answers?: number;
|
||||
/** The score of the post on the forum. */
|
||||
score?: string;
|
||||
/** The title of the post on the forum. */
|
||||
title?: string;
|
||||
/** The question asked in the forum post. */
|
||||
question?: string;
|
||||
/** The top-rated comment under the forum post. */
|
||||
top_comment?: string;
|
||||
}
|
||||
|
||||
export interface FAQ {
|
||||
/** The FAQ result type identifier. The value is always faq. */
|
||||
type: 'faq';
|
||||
/** A list of aggregated question answer results relevant to the query. */
|
||||
results: QA[];
|
||||
}
|
||||
|
||||
interface QA {
|
||||
/** The question being asked. */
|
||||
question: string;
|
||||
/** The answer to the question. */
|
||||
answer: string;
|
||||
/** The title of the post. */
|
||||
title: string;
|
||||
/** The URL pointing to the post. */
|
||||
url: string;
|
||||
/** 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 Search {
|
||||
/** A type identifying web search results. The value is always search. */
|
||||
type: 'search';
|
||||
/** A list of search results. */
|
||||
results: SearchResult[];
|
||||
/** Whether the results are family friendly. */
|
||||
family_friendly: boolean;
|
||||
}
|
||||
|
||||
interface SearchResult extends Result {
|
||||
/** A type identifying a web search result. The value is always search_result. */
|
||||
type: 'search_result';
|
||||
/** A sub type identifying the web search result type. */
|
||||
subtype: 'generic';
|
||||
/** Whether the web search result is currently live. Default value is false. */
|
||||
is_live: boolean;
|
||||
/** Gathered information on a web search result. */
|
||||
deep_results?: DeepResult;
|
||||
/** A list of schemas (structured data) extracted from the page. The schemas try to follow schema.org and will return anything we can extract from the HTML that can fit into these models. */
|
||||
schemas?: [][];
|
||||
/** Aggregated information on the URL associated with the web search result. */
|
||||
meta_url?: MetaUrl;
|
||||
/** The thumbnail of the web search result. */
|
||||
thumbnail?: Thumbnail;
|
||||
/** A string representing the age of the web search result. */
|
||||
age?: string;
|
||||
/** The main language on the web search result. */
|
||||
language: string;
|
||||
/** The location details if the query relates to a restaurant. */
|
||||
location?: LocationResult;
|
||||
/** The video associated with the web search result. */
|
||||
video?: VideoData;
|
||||
/** The movie associated with the web search result. */
|
||||
movie?: MovieData;
|
||||
/** Any frequently asked questions associated with the web search result. */
|
||||
faq?: FAQ;
|
||||
/** Any question answer information associated with the web search result page. */
|
||||
qa?: QAPage;
|
||||
/** Any book information associated with the web search result page. */
|
||||
book?: Book;
|
||||
/** Rating found for the web search result page. */
|
||||
rating?: Rating;
|
||||
/** An article found for the web search result page. */
|
||||
article?: Article;
|
||||
/** The main product and a review that is found on the web search result page. */
|
||||
product?: Product | Review;
|
||||
/** A list of products and reviews that are found on the web search result page. */
|
||||
product_cluster?: Product | Review[];
|
||||
/** A type representing a cluster. The value can be product_cluster. */
|
||||
cluster_type?: string;
|
||||
/** A list of web search results. */
|
||||
cluster?: Result[];
|
||||
/** Aggregated information on the creative work found on the web search result. */
|
||||
creative_work?: CreativeWork;
|
||||
/** Aggregated information on music recording found on the web search result. */
|
||||
music_recording?: MusicRecording;
|
||||
/** Aggregated information on the review found on the web search result. */
|
||||
review?: Review;
|
||||
/** Aggregated information on a software product found on the web search result page. */
|
||||
software?: Software;
|
||||
/** Aggregated information on a recipe found on the web search result page. */
|
||||
recipe?: Recipe;
|
||||
/** Aggregated information on a organization found on the web search result page. */
|
||||
organization?: Organization;
|
||||
/** The content type associated with the search result page. */
|
||||
content_type?: string;
|
||||
/** A list of extra alternate snippets for the web search result. */
|
||||
extra_snippets?: 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 AbstractGraphInfobox extends Result {
|
||||
/** The infobox result type identifier. The value is always infobox. */
|
||||
type: 'infobox';
|
||||
/** The position on a search result page. */
|
||||
position: number;
|
||||
/** Any label associated with the entity. */
|
||||
label?: string;
|
||||
/** Category classification for the entity. */
|
||||
category?: string;
|
||||
/** A longer description for the entity. */
|
||||
long_desc?: string;
|
||||
/** The thumbnail associated with the entity. */
|
||||
thumbnail?: Thumbnail;
|
||||
/** A list of attributes about the entity. */
|
||||
attributes?: string[][];
|
||||
/** The profiles associated with the entity. */
|
||||
profiles?: Profile[] | DataProvider[];
|
||||
/** The official website pertaining to the entity. */
|
||||
website_url?: string;
|
||||
/** Any ratings given to the entity. */
|
||||
ratings?: Rating[];
|
||||
/** A list of data sources for the entity. */
|
||||
providers?: DataProvider[];
|
||||
/** A unit representing quantity relevant to the entity. */
|
||||
distance?: Unit;
|
||||
/** A list of images relevant to the entity. */
|
||||
images?: Thumbnail[];
|
||||
/** Any movie data relevant to the entity. Appears only when the result is a movie. */
|
||||
movie?: MovieData;
|
||||
}
|
||||
|
||||
interface GenericInfobox extends AbstractGraphInfobox {
|
||||
/** The infobox subtype identifier. The value is always generic. */
|
||||
subtype: 'generic';
|
||||
/** List of URLs where the entity was found. */
|
||||
found_in_urls?: string[];
|
||||
}
|
||||
|
||||
interface EntityInfobox extends AbstractGraphInfobox {
|
||||
/** The infobox subtype identifier. The value is always entity. */
|
||||
subtype: 'entity';
|
||||
}
|
||||
|
||||
interface QAInfobox extends AbstractGraphInfobox {
|
||||
/** The infobox subtype identifier. The value is always code. */
|
||||
subtype: 'code';
|
||||
/** The question and relevant answer. */
|
||||
data: QAPage;
|
||||
/** Detailed information on the page containing the question and relevant answer. */
|
||||
meta_url?: MetaUrl;
|
||||
}
|
||||
|
||||
interface InfoboxWithLocation extends AbstractGraphInfobox {
|
||||
/** The infobox subtype identifier. The value is always location. */
|
||||
subtype: 'location';
|
||||
/** Whether the entity a location. */
|
||||
is_location: boolean;
|
||||
/** The coordinates of the location. */
|
||||
coordinates?: number[];
|
||||
/** The map zoom level. */
|
||||
zoom_level: number;
|
||||
/** The location result. */
|
||||
location?: LocationResult;
|
||||
}
|
||||
|
||||
interface InfoboxPlace extends AbstractGraphInfobox {
|
||||
/** The infobox subtype identifier. The value is always place. */
|
||||
subtype: 'place';
|
||||
/** The location result. */
|
||||
location: LocationResult;
|
||||
}
|
||||
|
||||
interface GraphInfobox {
|
||||
/** The type identifier for infoboxes. The value is always graph. */
|
||||
type: 'graph';
|
||||
/** A list of infoboxes associated with the query. */
|
||||
results: GenericInfobox | QAInfobox | InfoboxPlace | InfoboxWithLocation | EntityInfobox;
|
||||
}
|
||||
|
||||
interface QAPage {
|
||||
/** The question that is being asked. */
|
||||
question: string;
|
||||
/** An answer to the question. */
|
||||
answer: Answer;
|
||||
}
|
||||
|
||||
interface Answer {
|
||||
/** The main content of the answer. */
|
||||
text: string;
|
||||
/** The name of the author of the answer. */
|
||||
author?: string;
|
||||
/** Number of upvotes on the answer. */
|
||||
upvoteCount?: number;
|
||||
/** The number of downvotes on the answer. */
|
||||
downvoteCount?: number;
|
||||
}
|
||||
|
||||
interface Thumbnail {
|
||||
/** The served URL of the picture thumbnail. */
|
||||
src: string;
|
||||
/** The original URL of the image. */
|
||||
original?: string;
|
||||
}
|
||||
|
||||
interface LocationWebResult extends Result {
|
||||
/** Aggregated information about the URL. */
|
||||
meta_url: MetaUrl;
|
||||
}
|
||||
|
||||
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 from UTC. */
|
||||
timezone_offset?: number;
|
||||
}
|
||||
|
||||
interface Locations {
|
||||
/** Location type identifier. The value is always locations. */
|
||||
type: 'locations';
|
||||
/** An aggregated list of location sensitive results. */
|
||||
results: LocationResult[];
|
||||
}
|
||||
|
||||
interface MixedResponse {
|
||||
/** The type representing the model mixed. The value is always mixed. */
|
||||
type: 'mixed';
|
||||
/** The ranking order for the main section of the search result page. */
|
||||
main?: ResultReference[];
|
||||
/** The ranking order for the top section of the search result page. */
|
||||
top?: ResultReference[];
|
||||
/** The ranking order for the side section of the search result page. */
|
||||
side?: ResultReference[];
|
||||
}
|
||||
|
||||
interface ResultReference {
|
||||
/** The type of the result. */
|
||||
type: string;
|
||||
/** The 0th based index where the result should be placed. */
|
||||
index?: number;
|
||||
/** Whether to put all the results from the type at specific position. */
|
||||
all: boolean;
|
||||
}
|
||||
|
||||
export interface Videos {
|
||||
/** The type representing the videos. The value is always videos. */
|
||||
type: 'videos';
|
||||
/** A list of video results. */
|
||||
results: VideoResult[];
|
||||
/** Whether the video results are changed by a Goggle. The value is false by default. */
|
||||
mutated_by_goggles?: boolean;
|
||||
}
|
||||
|
||||
export interface News {
|
||||
/** The type representing the news. The value is always news. */
|
||||
type: 'news';
|
||||
/** A list of news results. */
|
||||
results: NewsResult[];
|
||||
/** Whether the news results are changed by a Goggle. The value is false by default. */
|
||||
mutated_by_goggles?: boolean;
|
||||
}
|
||||
|
||||
interface NewsResult extends Result {
|
||||
/** The aggregated information on the URL representing a news result. */
|
||||
meta_url?: MetaUrl;
|
||||
/** The source of the news. */
|
||||
source?: string;
|
||||
/** Whether the news result is currently a breaking news. */
|
||||
breaking: boolean;
|
||||
/** Whether the news result is currently live. */
|
||||
is_live: boolean;
|
||||
/** The thumbnail associated with the news result. */
|
||||
thumbnail?: Thumbnail;
|
||||
/** A string representing the age of the news article. */
|
||||
age?: string;
|
||||
/** A list of extra alternate snippets for the news search result. */
|
||||
extra_snippets?: string[];
|
||||
}
|
||||
|
||||
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 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;
|
||||
}
|
||||
|
||||
interface OpeningHours {
|
||||
/** The current day opening hours. Can have two sets of opening hours. */
|
||||
current_day?: DayOpeningHours[];
|
||||
/** The opening hours for the whole week. */
|
||||
days?: DayOpeningHours[] | [DayOpeningHours][];
|
||||
}
|
||||
|
||||
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 Contact {
|
||||
/** The email address. */
|
||||
email?: string;
|
||||
/** The telephone number. */
|
||||
telephone?: 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 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;
|
||||
}
|
||||
|
||||
interface Unit {
|
||||
/** The quantity of the unit. */
|
||||
value: number;
|
||||
/** The name of the unit associated with the quantity. */
|
||||
units: string;
|
||||
}
|
||||
|
||||
interface MovieData {
|
||||
/** Name of the movie. */
|
||||
name?: string;
|
||||
/** A short plot summary for the movie. */
|
||||
description?: string;
|
||||
/** A URL serving a movie profile page. */
|
||||
url?: string;
|
||||
/** A thumbnail for a movie poster. */
|
||||
thumbnail?: Thumbnail;
|
||||
/** The release date for the movie. */
|
||||
release?: string;
|
||||
/** A list of people responsible for directing the movie. */
|
||||
directors?: Person[];
|
||||
/** A list of actors in the movie. */
|
||||
actors?: Person[];
|
||||
/** Rating provided to the movie from various sources. */
|
||||
rating?: Rating;
|
||||
/** The runtime of the movie. The format is HH:MM:SS. */
|
||||
duration?: string;
|
||||
/** List of genres in which the movie can be classified. */
|
||||
genre?: string[];
|
||||
/** The query that resulted in the movie result. */
|
||||
query?: 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;
|
||||
}
|
||||
|
||||
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 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 Book {
|
||||
/** The title of the book. */
|
||||
title: string;
|
||||
/** The author of the book. */
|
||||
author: Person[];
|
||||
/** The publishing date of the book. */
|
||||
date?: string;
|
||||
/** The price of the book. */
|
||||
price?: Price;
|
||||
/** The number of pages in the book. */
|
||||
pages?: number;
|
||||
/** The publisher of the book. */
|
||||
publisher?: Person;
|
||||
/** A gathered rating from different sources associated with the book. */
|
||||
rating?: Rating;
|
||||
}
|
||||
|
||||
interface Price {
|
||||
/** The price value in a given currency. */
|
||||
price: string;
|
||||
/** The current of the price value. */
|
||||
price_currency: string;
|
||||
}
|
||||
|
||||
interface Article {
|
||||
/** The author of the article. */
|
||||
author?: Person[];
|
||||
/** The date when the article was published. */
|
||||
date?: string;
|
||||
/** The name of the publisher for the article. */
|
||||
publisher?: Organization;
|
||||
/** A thumbnail associated with the article. */
|
||||
thumbnail?: Thumbnail;
|
||||
/** Whether the article is free to read or is behind a paywall. */
|
||||
isAccessibleForFree?: boolean;
|
||||
}
|
||||
|
||||
interface ContactPoint extends Omit<Thing, 'type'> {
|
||||
/** A type string identifying a contact point. The value is always contact_point. */
|
||||
type: 'contact_point';
|
||||
/** The telephone number of the entity. */
|
||||
telephone?: string;
|
||||
/** The email address of the entity. */
|
||||
email?: string;
|
||||
}
|
||||
|
||||
interface Organization extends Omit<Thing, 'type'> {
|
||||
/** A type string identifying an organization. The value is always organization. */
|
||||
type: 'organization';
|
||||
/** A list of contact points for the organization. */
|
||||
contact_points?: ContactPoint[];
|
||||
}
|
||||
|
||||
interface HowTo {
|
||||
/** The how to text. */
|
||||
text: string;
|
||||
/** A name for the how to. */
|
||||
name?: string;
|
||||
/** A URL associated with the how to. */
|
||||
url?: string;
|
||||
/** A list of image URLs associated with the how to. */
|
||||
image?: string[];
|
||||
}
|
||||
|
||||
interface Recipe {
|
||||
/** The title of the recipe. */
|
||||
title: string;
|
||||
/** The description of the recipe. */
|
||||
description: string;
|
||||
/** A thumbnail associated with the recipe. */
|
||||
thumbnail: Thumbnail;
|
||||
/** The URL of the web page where the recipe was found. */
|
||||
url: string;
|
||||
/** The domain of the web page where the recipe was found. */
|
||||
domain: string;
|
||||
/** The URL for the favicon of the web page where the recipe was found. */
|
||||
favicon: string;
|
||||
/** The total time required to cook the recipe. */
|
||||
time?: string;
|
||||
/** The preparation time for the recipe. */
|
||||
prep_time?: string;
|
||||
/** The cooking time for the recipe. */
|
||||
cook_time?: string;
|
||||
/** Ingredients required for the recipe. */
|
||||
ingredients?: string;
|
||||
/** List of instructions for the recipe. */
|
||||
instructions?: HowTo[];
|
||||
/** How many people the recipe serves. */
|
||||
servings?: number;
|
||||
/** Calorie count for the recipe. */
|
||||
calories?: number;
|
||||
/** Aggregated information on the ratings associated with the recipe. */
|
||||
rating?: Rating;
|
||||
/** The category of the recipe. */
|
||||
recipeCategory?: string;
|
||||
/** The cuisine classification for the recipe. */
|
||||
recipeCuisine?: string;
|
||||
/** Aggregated information on the cooking video associated with the recipe. */
|
||||
video?: VideoData;
|
||||
}
|
||||
|
||||
interface Product {
|
||||
/** A string representing a product type. The value is always product. */
|
||||
type: 'Product';
|
||||
/** The name of the product. */
|
||||
name: string;
|
||||
/** The category of the product. */
|
||||
category?: string;
|
||||
/** The price of the product. */
|
||||
price: string;
|
||||
/** A thumbnail associated with the product. */
|
||||
thumbnail: Thumbnail;
|
||||
/** The description of the product. */
|
||||
description?: string;
|
||||
/** A list of offers available on the product. */
|
||||
offers?: Offer[];
|
||||
/** A rating associated with the product. */
|
||||
rating?: Rating;
|
||||
}
|
||||
|
||||
interface Offer {
|
||||
/** The URL where the offer can be found. */
|
||||
url: string;
|
||||
/** The currency in which the offer is made. */
|
||||
priceCurrency: string;
|
||||
/** The price of the product currently on offer. */
|
||||
price: string;
|
||||
}
|
||||
|
||||
interface Review {
|
||||
/** A string representing review type. This is always review. */
|
||||
type: 'review';
|
||||
/** The review title for the review. */
|
||||
name: string;
|
||||
/** The thumbnail associated with the reviewer. */
|
||||
thumbnail: Thumbnail;
|
||||
/** A description of the review (the text of the review itself). */
|
||||
description: string;
|
||||
/** The ratings associated with the review. */
|
||||
rating: Rating;
|
||||
}
|
||||
|
||||
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 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 CreativeWork {
|
||||
/** The name of the creative work. */
|
||||
name: string;
|
||||
/** A thumbnail associated with the creative work. */
|
||||
thumbnail: Thumbnail;
|
||||
/** A rating that is given to the creative work. */
|
||||
rating?: Rating;
|
||||
}
|
||||
|
||||
interface MusicRecording {
|
||||
/** The name of the song or album. */
|
||||
name: string;
|
||||
/** A thumbnail associated with the music. */
|
||||
thumbnail?: Thumbnail;
|
||||
/** The rating of the music. */
|
||||
rating?: Rating;
|
||||
}
|
||||
|
||||
interface Software {
|
||||
/** The name of the software product. */
|
||||
name?: string;
|
||||
/** The author of software product. */
|
||||
author?: string;
|
||||
/** The latest version of the software product. */
|
||||
version?: string;
|
||||
/** The code repository where the software product is currently available or maintained. */
|
||||
codeRepository?: string;
|
||||
/** The home page of the software product. */
|
||||
homepage?: string;
|
||||
/** The date when the software product was published. */
|
||||
datePublisher?: string;
|
||||
/** Whether the software product is available on npm. */
|
||||
is_npm?: boolean;
|
||||
/** Whether the software product is available on pypi. */
|
||||
is_pypi?: boolean;
|
||||
/** The number of stars on the repository. */
|
||||
stars?: number;
|
||||
/** The numbers of forks of the repository. */
|
||||
forks?: number;
|
||||
/** The programming language spread on the software product. */
|
||||
ProgrammingLanguage?: string;
|
||||
}
|
||||
|
||||
interface DeepResult {
|
||||
/** A list of news results associated with the result. */
|
||||
news?: NewsResult[];
|
||||
/** A list of buttoned results associated with the result. */
|
||||
buttons?: ButtonResult[];
|
||||
/** Videos associated with the result. */
|
||||
videos?: VideoResult[];
|
||||
/** Images associated with the result. */
|
||||
images?: Image[];
|
||||
}
|
||||
|
||||
interface VideoResult extends Result {
|
||||
/** The type identifying the video result. The value is always video_result. */
|
||||
type: 'video_result';
|
||||
/** Meta data for the video. */
|
||||
video: VideoData;
|
||||
/** Aggregated information on the URL. */
|
||||
meta_url?: MetaUrl;
|
||||
/** The thumbnail of the video. */
|
||||
thumbnail?: Thumbnail;
|
||||
/** A string representing the age of the video. */
|
||||
age?: string;
|
||||
}
|
||||
|
||||
interface VideoData {
|
||||
/** A time string representing the duration of the video. The format can be HH:MM:SS or MM:SS. */
|
||||
duration?: string;
|
||||
/** The number of views of the video. */
|
||||
views?: string;
|
||||
/** The creator of the video. */
|
||||
creator?: string;
|
||||
/** The publisher of the video. */
|
||||
publisher?: string;
|
||||
/** A thumbnail associated with the video. */
|
||||
thumbnail?: Thumbnail;
|
||||
/** A list of tags associated with the video. */
|
||||
tags?: string[];
|
||||
/** Author of the video. */
|
||||
author?: Profile;
|
||||
/** Whether the video requires a subscription to watch. */
|
||||
requires_subscription?: boolean;
|
||||
}
|
||||
|
||||
interface ButtonResult {
|
||||
/** A type identifying button result. The value is always button_result. */
|
||||
type: 'button_result';
|
||||
/** The title of the result. */
|
||||
title: string;
|
||||
/** The URL for the button result. */
|
||||
url: string;
|
||||
}
|
||||
|
||||
interface Image {
|
||||
/** The thumbnail associated with the image. */
|
||||
thumbnail: Thumbnail;
|
||||
/** The URL of the image. */
|
||||
url?: string;
|
||||
/** Metadata on the image. */
|
||||
properties?: ImageProperties;
|
||||
}
|
||||
|
||||
interface Language {
|
||||
/** The main language seen in the string. */
|
||||
main: string;
|
||||
}
|
||||
|
||||
interface ImageProperties {
|
||||
/** The original image URL. */
|
||||
url: string;
|
||||
/** The URL for a better quality resized image. */
|
||||
resized: string;
|
||||
/** The placeholder image URL. */
|
||||
placeholder: string;
|
||||
/** The image height. */
|
||||
height?: number;
|
||||
/** The image width. */
|
||||
width?: number;
|
||||
/** The image format. */
|
||||
format?: string;
|
||||
/** The image size. */
|
||||
content_size?: string;
|
||||
}
|
||||
|
||||
interface Summarizer {
|
||||
/** The value is always summarizer. */
|
||||
type: 'summarizer';
|
||||
/** The key for the summarizer API. */
|
||||
key: string;
|
||||
}
|
||||
|
||||
interface RichCallbackInfo {
|
||||
/** The value is always rich. */
|
||||
type: 'rich';
|
||||
/** The hint for the rich result. */
|
||||
hint?: RichCallbackHint;
|
||||
}
|
||||
|
||||
interface RichCallbackHint {
|
||||
/** The name of the vertical of the rich result. */
|
||||
vertical: string;
|
||||
/** The callback key for the rich result. */
|
||||
callback_key: string;
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtempSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { describe, it } from 'node:test';
|
||||
import { isLoopbackHostname, parsePort, readBraveApiKeyFromFile } from './utils.js';
|
||||
|
||||
describe('parsePort', () => {
|
||||
it('accepts valid integer ports', () => {
|
||||
assert.equal(parsePort(8080), 8080);
|
||||
assert.equal(parsePort('8080'), 8080);
|
||||
assert.equal(parsePort(1), 1);
|
||||
assert.equal(parsePort(65535), 65535);
|
||||
});
|
||||
|
||||
it('rejects non-numeric and out-of-range values', () => {
|
||||
assert.equal(parsePort('abc'), null);
|
||||
assert.equal(parsePort('8080abc'), null);
|
||||
assert.equal(parsePort('8080.5'), null);
|
||||
assert.equal(parsePort(0), null);
|
||||
assert.equal(parsePort(65536), null);
|
||||
assert.equal(parsePort(-1), null);
|
||||
assert.equal(parsePort(''), null);
|
||||
assert.equal(parsePort(null), null);
|
||||
assert.equal(parsePort(undefined), null);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isLoopbackHostname', () => {
|
||||
it('accepts localhost and the IPv6 loopback', () => {
|
||||
assert.equal(isLoopbackHostname('localhost'), true);
|
||||
assert.equal(isLoopbackHostname('::1'), true);
|
||||
});
|
||||
|
||||
it('accepts addresses across the whole IPv4 127.0.0.0/8 range', () => {
|
||||
assert.equal(isLoopbackHostname('127.0.0.1'), true);
|
||||
assert.equal(isLoopbackHostname('127.0.0.0'), true);
|
||||
assert.equal(isLoopbackHostname('127.1.2.3'), true);
|
||||
assert.equal(isLoopbackHostname('127.255.255.255'), true);
|
||||
assert.equal(isLoopbackHostname('127.0.0.255'), true);
|
||||
});
|
||||
|
||||
it('rejects non-loopback IPv4 addresses', () => {
|
||||
assert.equal(isLoopbackHostname('128.0.0.1'), false);
|
||||
assert.equal(isLoopbackHostname('126.255.255.255'), false);
|
||||
assert.equal(isLoopbackHostname('0.0.0.0'), false);
|
||||
assert.equal(isLoopbackHostname('192.168.0.1'), false);
|
||||
assert.equal(isLoopbackHostname('10.0.0.1'), false);
|
||||
});
|
||||
|
||||
it('rejects IPv4 octets outside 0-255', () => {
|
||||
assert.equal(isLoopbackHostname('127.0.0.256'), false);
|
||||
assert.equal(isLoopbackHostname('127.0.0.999'), false);
|
||||
});
|
||||
|
||||
it('rejects addresses without exactly four octets', () => {
|
||||
assert.equal(isLoopbackHostname('127'), false);
|
||||
assert.equal(isLoopbackHostname('127.0.0'), false);
|
||||
assert.equal(isLoopbackHostname('127.0.0.1.2'), false);
|
||||
assert.equal(isLoopbackHostname(''), false);
|
||||
});
|
||||
|
||||
it('rejects non-numeric or malformed IPv4 octets', () => {
|
||||
assert.equal(isLoopbackHostname('127.0.0.x'), false);
|
||||
assert.equal(isLoopbackHostname('127.0.0.-1'), false);
|
||||
assert.equal(isLoopbackHostname('127.0.0.1abc'), false);
|
||||
assert.equal(isLoopbackHostname('127.0.0. 1'), false);
|
||||
assert.equal(isLoopbackHostname('0127.0.0.1'), false);
|
||||
});
|
||||
|
||||
it('rejects non-loopback hostnames and non-normalized input', () => {
|
||||
assert.equal(isLoopbackHostname('example.com'), false);
|
||||
// Callers normalize (lowercase) before calling, so uppercase is not matched.
|
||||
assert.equal(isLoopbackHostname('LOCALHOST'), false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('readBraveApiKeyFromFile', () => {
|
||||
it('reads and trims API keys from a file', () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'brave-api-key-'));
|
||||
const filePath = join(dir, 'key.txt');
|
||||
writeFileSync(filePath, 'test-api-key\n');
|
||||
|
||||
const result = readBraveApiKeyFromFile(filePath);
|
||||
|
||||
assert.equal(result.ok, true);
|
||||
if (result.ok) {
|
||||
assert.equal(result.key, 'test-api-key');
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects empty files', () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'brave-api-key-'));
|
||||
const filePath = join(dir, 'empty.txt');
|
||||
writeFileSync(filePath, '\n');
|
||||
|
||||
const result = readBraveApiKeyFromFile(filePath);
|
||||
|
||||
assert.equal(result.ok, false);
|
||||
if (!result.ok) {
|
||||
assert.match(result.error, /empty/i);
|
||||
}
|
||||
});
|
||||
|
||||
it('reports missing files with the path and reason', () => {
|
||||
const result = readBraveApiKeyFromFile('definitely-not-a-real-api-key-file');
|
||||
|
||||
assert.equal(result.ok, false);
|
||||
if (!result.ok) {
|
||||
assert.match(result.error, /definitely-not-a-real-api-key-file/);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,81 +0,0 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
export function stringify(data: any, pretty = false) {
|
||||
return pretty ? JSON.stringify(data, null, 2) : JSON.stringify(data);
|
||||
}
|
||||
|
||||
type ReadBraveApiKeyFromFileResult = { ok: true; key: string } | { ok: false; error: string };
|
||||
|
||||
export function readBraveApiKeyFromFile(filePath: string): ReadBraveApiKeyFromFileResult {
|
||||
try {
|
||||
const key = readFileSync(filePath, 'utf8').trim();
|
||||
if (key.length === 0) {
|
||||
return { ok: false, error: `API key file is empty: ${filePath}` };
|
||||
}
|
||||
|
||||
return { ok: true, key };
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : String(error);
|
||||
return { ok: false, error: `Unable to read API key file '${filePath}': ${reason}` };
|
||||
}
|
||||
}
|
||||
|
||||
export function parseDelimitedList(value: string | string[] | undefined | null): string[] {
|
||||
if (value == null) return [];
|
||||
|
||||
// Value may be variadic as string[]. Normalize to a single string first.
|
||||
const raw = Array.isArray(value) ? value.join(' ') : value;
|
||||
|
||||
return raw
|
||||
.split(/[\s,]+/)
|
||||
.map((o: string) => o.trim())
|
||||
.filter((o: string) => o.length > 0);
|
||||
}
|
||||
|
||||
function isIpv4Loopback(value: string): boolean {
|
||||
// Check complete range of loopback addresses: 127.0.0.0/8
|
||||
const parts = value.split('.');
|
||||
return (
|
||||
parts.length === 4 &&
|
||||
parts[0] === '127' &&
|
||||
parts.every((part: string) => {
|
||||
if (!/^\d+$/.test(part)) return false;
|
||||
// Leading zeros are not allowed.
|
||||
if (part.length > 1 && part.startsWith('0')) return false;
|
||||
// Parse the part as an integer and check if it's in the range 0-255.
|
||||
const num = Number.parseInt(part, 10);
|
||||
return num >= 0 && num <= 255;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// Determines whether a bare hostname refers to the loopback interface: any
|
||||
// IPv4 127.0.0.0/8 address, the IPv6 loopback (::1), or "localhost".
|
||||
export function isLoopbackHostname(value: string): boolean {
|
||||
return value === 'localhost' || value === '::1' || isIpv4Loopback(value);
|
||||
}
|
||||
|
||||
export function parsePort(value: unknown): number | null {
|
||||
if (value === undefined || value === null || value === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (typeof value === 'number') {
|
||||
if (!Number.isInteger(value) || value < 1 || value > 65535) {
|
||||
return null;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
const text = String(value).trim();
|
||||
if (!/^\d+$/.test(text)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const parsed = Number.parseInt(text, 10);
|
||||
if (parsed < 1 || parsed > 65535) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return parsed;
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"outDir": "./dist",
|
||||
"rootDir": "src",
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"resolveJsonModule": true
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
Reference in new issue
Block a user