diff --git a/README.md b/README.md index bac1e5d..93ff2ee 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Brave Search MCP Server -An MCP server implementation that integrates the Brave Search API, providing both web and local search capabilities. +An MCP server implementation that integrates the Brave Search API, providing both web and local search capabilities. This project supports both HTTP and STDIO transports. By default the project will launch into HTTP Streaming mode. For STDIO support, pass `--transport stdio` via the CLI. ## Features @@ -148,6 +148,7 @@ docker build -t mcp/brave-search:latest . ## Development +### Testing via Claude Desktop Clone this repo to your machine, then add a reference to your `claude_desktop_config.json`: ```json @@ -164,6 +165,24 @@ Clone this repo to your machine, then add a reference to your `claude_desktop_co } ``` +### Testing via MCP Inspector + +To test within the MCP Inspector, you'll need to build the project, launch the HTTP server (if you intend to test the HTTP endpoint), and initialize MCP Inspector: + +```bash +npm install +npm run build +node dist/index.js # defaults to http-mode, use `node dist/index.js --transport stdio` for stdio-mode +``` + +From another terminal (within the `dist/` directory): + +```bash +npx @modelcontextprotocol/inspector node dist/index.js +``` + +In order to test STDIO via MCP Inspector, you will need to add `--transport stdio` to the arguments via the Inspector UI. + ## 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. diff --git a/package-lock.json b/package-lock.json index d78fb87..7a892f5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,12 +9,16 @@ "version": "1.0", "license": "MIT", "dependencies": { - "@modelcontextprotocol/sdk": "^1.12.3" + "@modelcontextprotocol/sdk": "1.12.3", + "commander": "14.0.0", + "express": "5.1.0", + "zod": "3.25.67" }, "bin": { "brave-search-mcp-server": "dist/index.js" }, "devDependencies": { + "@types/express": "5.0.3", "@types/node": "24.0.3", "shx": "0.4.0", "typescript": "5.8.3" @@ -76,16 +80,102 @@ "node": ">= 8" } }, + "node_modules/@types/body-parser": { + "version": "1.19.6", + "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz", + "integrity": "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==", + "dev": true, + "dependencies": { + "@types/connect": "*", + "@types/node": "*" + } + }, + "node_modules/@types/connect": { + "version": "3.4.38", + "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz", + "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==", + "dev": true, + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/express": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/@types/express/-/express-5.0.3.tgz", + "integrity": "sha512-wGA0NX93b19/dZC1J18tKWVIYWyyF2ZjT9vin/NRu0qzzvfVzWjs04iq2rQ3H65vCTQYlRqs3YHfY7zjdV+9Kw==", + "dev": true, + "dependencies": { + "@types/body-parser": "*", + "@types/express-serve-static-core": "^5.0.0", + "@types/serve-static": "*" + } + }, + "node_modules/@types/express-serve-static-core": { + "version": "5.0.6", + "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-5.0.6.tgz", + "integrity": "sha512-3xhRnjJPkULekpSzgtoNYYcTWgEZkp4myc+Saevii5JPnHNvHMRlBSHDbs7Bh1iPPoVTERHEZXyhyLbMEsExsA==", + "dev": true, + "dependencies": { + "@types/node": "*", + "@types/qs": "*", + "@types/range-parser": "*", + "@types/send": "*" + } + }, + "node_modules/@types/http-errors": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz", + "integrity": "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==", + "dev": true + }, + "node_modules/@types/mime": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.5.tgz", + "integrity": "sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w==", + "dev": true + }, "node_modules/@types/node": { "version": "24.0.3", "resolved": "https://registry.npmjs.org/@types/node/-/node-24.0.3.tgz", "integrity": "sha512-R4I/kzCYAdRLzfiCabn9hxWfbuHS573x+r0dJMkkzThEa7pbrcDWK+9zu3e7aBOouf+rQAciqPFMnxwr0aWgKg==", "dev": true, - "license": "MIT", "dependencies": { "undici-types": "~7.8.0" } }, + "node_modules/@types/qs": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.14.0.tgz", + "integrity": "sha512-eOunJqu0K1923aExK6y8p6fsihYEn/BYuQ4g0CxAAgFc4b/ZLN4CrsRZ55srTdqoiLzU2B2evC+apEIxprEzkQ==", + "dev": true + }, + "node_modules/@types/range-parser": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz", + "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==", + "dev": true + }, + "node_modules/@types/send": { + "version": "0.17.5", + "resolved": "https://registry.npmjs.org/@types/send/-/send-0.17.5.tgz", + "integrity": "sha512-z6F2D3cOStZvuk2SaP6YrwkNO65iTZcwA2ZkSABegdkAh/lf+Aa/YQndZVfmEXT5vgAp6zv06VQ3ejSVjAny4w==", + "dev": true, + "dependencies": { + "@types/mime": "^1", + "@types/node": "*" + } + }, + "node_modules/@types/serve-static": { + "version": "1.15.8", + "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.15.8.tgz", + "integrity": "sha512-roei0UY3LhpOJvjbIP6ZZFngyLKl5dskOtDhxY5THRSpO+ZI+nzJ+m5yUMzGrp89YRa7lvknKkMYjqQFGwA7Sg==", + "dev": true, + "dependencies": { + "@types/http-errors": "*", + "@types/node": "*", + "@types/send": "*" + } + }, "node_modules/accepts": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", @@ -179,6 +269,14 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/commander": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-14.0.0.tgz", + "integrity": "sha512-2uM9rYjPvyq39NwLRqaiLtWHyDC1FvryJDa2ATTVims5YAS4PupsEQsDvP14FqhFr0P49CYDugi59xaxJlTXRA==", + "engines": { + "node": ">=20" + } + }, "node_modules/content-disposition": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.0.tgz", @@ -1499,9 +1597,9 @@ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==" }, "node_modules/zod": { - "version": "3.25.65", - "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.65.tgz", - "integrity": "sha512-kMyE2qsXK1p+TAvO7zsf5wMFiCejU3obrUDs9bR1q5CBKykfvp7QhhXrycUylMoOow0iEUSyjLlZZdCsHwSldQ==", + "version": "3.25.67", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.67.tgz", + "integrity": "sha512-idA2YXwpCdqUSKRCACDE6ItZD9TZzy3OZMtpfLoh6oPR47lipysRrJfjzMqFxQ3uJuUPyUeWe1r9vLH33xO/Qw==", "funding": { "url": "https://github.com/sponsors/colinhacks" } diff --git a/package.json b/package.json index df1e9de..efae7f4 100644 --- a/package.json +++ b/package.json @@ -19,9 +19,13 @@ "watch": "tsc --watch" }, "dependencies": { - "@modelcontextprotocol/sdk": "^1.12.3" + "@modelcontextprotocol/sdk": "1.12.3", + "commander": "14.0.0", + "express": "5.1.0", + "zod": "3.25.67" }, "devDependencies": { + "@types/express": "5.0.3", "@types/node": "24.0.3", "shx": "0.4.0", "typescript": "5.8.3" diff --git a/src/constants.ts b/src/constants.ts new file mode 100644 index 0000000..bba0eb5 --- /dev/null +++ b/src/constants.ts @@ -0,0 +1,6 @@ +export const BRAVE_API_KEY = process.env.BRAVE_API_KEY!; + +export const RATE_LIMIT = { + perSecond: 1, + perMonth: 15000 +} as const; diff --git a/src/index.ts b/src/index.ts index 0bd7a42..722e489 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,376 +1,139 @@ #!/usr/bin/env node -import { Server } from "@modelcontextprotocol/sdk/server/index.js"; +import { Command } from "commander"; +import express, { type Request, type Response } from "express"; +import { randomUUID } from "node:crypto"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; -import { - CallToolRequestSchema, - ListToolsRequestSchema, - type Tool, -} from "@modelcontextprotocol/sdk/types.js"; +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; +import { BRAVE_API_KEY } from "./constants.js"; -const WEB_SEARCH_TOOL: Tool = { - name: "brave_web_search", - description: - "Performs a web search using the Brave Search API, ideal for general queries, news, articles, and online content. " + - "Use this for broad information gathering, recent events, or when you need diverse web sources. " + - "Supports pagination, content filtering, and freshness controls. " + - "Maximum 20 results per request, with offset for pagination. ", - inputSchema: { - type: "object", - properties: { - query: { - type: "string", - description: "Search query (max 400 chars, 50 words)" - }, - count: { - type: "number", - description: "Number of results (1-20, default 10)", - default: 10 - }, - offset: { - type: "number", - description: "Pagination offset (max 9, default 0)", - default: 0 - }, - }, - required: ["query"], - }, -}; +import { name as braveWebSearchName, paramsSchema as braveWebSearchParamsSchema, performSearch as performWebSearch } from "./tools/web.js"; +import { name as braveLocalSearchName, paramsSchema as braveLocalSearchParamsSchema, performSearch as performLocalSearch } from "./tools/local.js"; +import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js"; +import { InMemoryEventStore } from "@modelcontextprotocol/sdk/examples/shared/inMemoryEventStore.js"; -const LOCAL_SEARCH_TOOL: Tool = { - name: "brave_local_search", - description: - "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:\n" + - "- Business names and addresses\n" + - "- Ratings and review counts\n" + - "- Phone numbers and opening hours\n" + - "Use this when the query implies 'near me' or mentions specific locations. " + - "Automatically falls back to web search if no local results are found.", - inputSchema: { - type: "object", - properties: { - query: { - type: "string", - description: "Local search query (e.g. 'pizza near Central Park')" - }, - count: { - type: "number", - description: "Number of results (1-20, default 5)", - default: 5 - }, - }, - required: ["query"] - } -}; - -// Server implementation -const server = new Server( - { - name: "example-servers/brave-search", - version: "0.1.0", - }, - { - capabilities: { - tools: {}, - }, - }, -); - -// Check for API key -const BRAVE_API_KEY = process.env.BRAVE_API_KEY!; if (!BRAVE_API_KEY) { console.error("Error: BRAVE_API_KEY environment variable is required"); process.exit(1); } -const RATE_LIMIT = { - perSecond: 1, - perMonth: 15000 -}; +const program = new Command() + .option("--transport ", "transport type", "http") + .option("--port ", "desired port for HTTP transport", "3000") + .allowUnknownOption() + .parse(process.argv); -let requestCount = { - second: 0, - month: 0, - lastReset: Date.now() -}; +const TRANSPORT_TYPES = ["stdio", "http"] as const; -function checkRateLimit() { - const now = Date.now(); - if (now - requestCount.lastReset > 1000) { - requestCount.second = 0; - requestCount.lastReset = now; - } - if (requestCount.second >= RATE_LIMIT.perSecond || - requestCount.month >= RATE_LIMIT.perMonth) { - throw new Error('Rate limit exceeded'); - } - requestCount.second++; - requestCount.month++; +const CLI_OPTIONS = program.opts<{ transport: "stdio" | "http"; port: string }>(); + +if (!TRANSPORT_TYPES.includes(CLI_OPTIONS.transport)) { + console.error(`Invalid --transport value: '${CLI_OPTIONS.transport}'. Must be one of: ${TRANSPORT_TYPES.join(", ")}.`); + process.exit(1); } -interface BraveWeb { - web?: { - results?: Array<{ - title: string; - description: string; - url: string; - language?: string; - published?: string; - rank?: number; - }>; - }; - locations?: { - results?: Array<{ - id: string; // Required by API - title?: string; - }>; - }; +function createServer(): McpServer { + const server = new McpServer({ + version: "0.1.0", + name: "brave-search-mcp-server", + instructions: "Use this server to search the Web for various types of data via the Brave Search API.", + }, { capabilities: { logging: {} } }); + + server.tool(braveWebSearchName, braveWebSearchParamsSchema.shape, performWebSearch); + server.tool(braveLocalSearchName, braveLocalSearchParamsSchema.shape, performLocalSearch); + + return server; } -interface BraveLocation { - id: string; - name: string; - address: { - streetAddress?: string; - addressLocality?: string; - addressRegion?: string; - postalCode?: string; - }; - coordinates?: { - latitude: number; - longitude: number; - }; - phone?: string; - rating?: { - ratingValue?: number; - ratingCount?: number; - }; - openingHours?: string[]; - priceRange?: string; -} - -interface BravePoiResponse { - results: BraveLocation[]; -} - -interface BraveDescription { - descriptions: {[id: string]: string}; -} - -function isBraveWebSearchArgs(args: unknown): args is { query: string; count?: number } { - return ( - typeof args === "object" && - args !== null && - "query" in args && - typeof (args as { query: string }).query === "string" - ); -} - -function isBraveLocalSearchArgs(args: unknown): args is { query: string; count?: number } { - return ( - typeof args === "object" && - args !== null && - "query" in args && - typeof (args as { query: string }).query === "string" - ); -} - -async function performWebSearch(query: string, count: number = 10, offset: number = 0) { - checkRateLimit(); - const url = new URL('https://api.search.brave.com/res/v1/web/search'); - url.searchParams.set('q', query); - url.searchParams.set('count', Math.min(count, 20).toString()); // API limit - url.searchParams.set('offset', offset.toString()); - - const response = await fetch(url, { - headers: { - 'Accept': 'application/json', - 'Accept-Encoding': 'gzip', - 'X-Subscription-Token': BRAVE_API_KEY +async function createNewHttpTransport(transports: Map): Promise { + const transport = new StreamableHTTPServerTransport({ + eventStore: new InMemoryEventStore(), + sessionIdGenerator: () => randomUUID(), + onsessioninitialized: (sessionId) => { + transports.set(sessionId, transport); } }); - if (!response.ok) { - throw new Error(`Brave API error: ${response.status} ${response.statusText}\n${await response.text()}`); - } - - const data = await response.json() as BraveWeb; - - // Extract just web results - const results = (data.web?.results || []).map(result => ({ - title: result.title || '', - description: result.description || '', - url: result.url || '' - })); - - return results.map(r => - `Title: ${r.title}\nDescription: ${r.description}\nURL: ${r.url}` - ).join('\n\n'); -} - -async function performLocalSearch(query: string, count: number = 5) { - checkRateLimit(); - // Initial search to get location IDs - const webUrl = new URL('https://api.search.brave.com/res/v1/web/search'); - webUrl.searchParams.set('q', query); - webUrl.searchParams.set('search_lang', 'en'); - webUrl.searchParams.set('result_filter', 'locations'); - webUrl.searchParams.set('count', Math.min(count, 20).toString()); - - const webResponse = await fetch(webUrl, { - headers: { - 'Accept': 'application/json', - 'Accept-Encoding': 'gzip', - 'X-Subscription-Token': BRAVE_API_KEY + transport.onclose = () => { + const sessionId = transport.sessionId; + if (sessionId && transports.has(sessionId)) { + transports.delete(sessionId); } - }); + }; - if (!webResponse.ok) { - throw new Error(`Brave API error: ${webResponse.status} ${webResponse.statusText}\n${await webResponse.text()}`); - } - - const webData = await webResponse.json() as BraveWeb; - const locationIds = webData.locations?.results?.filter((r): r is {id: string; title?: string} => r.id != null).map(r => r.id) || []; - - if (locationIds.length === 0) { - return performWebSearch(query, count); // Fallback to web search - } - - // Get POI details and descriptions in parallel - const [poisData, descriptionsData] = await Promise.all([ - getPoisData(locationIds), - getDescriptionsData(locationIds) - ]); - - return formatLocalResults(poisData, descriptionsData); + return transport; } -async function getPoisData(ids: string[]): Promise { - checkRateLimit(); - const url = new URL('https://api.search.brave.com/res/v1/local/pois'); - ids.filter(Boolean).forEach(id => url.searchParams.append('ids', id)); - const response = await fetch(url, { - headers: { - 'Accept': 'application/json', - 'Accept-Encoding': 'gzip', - 'X-Subscription-Token': BRAVE_API_KEY - } - }); +async function getHttpTransportForRequest(req: Request, transports: Map): Promise { + const sessionId = req.headers['mcp-session-id'] as string | undefined; - if (!response.ok) { - throw new Error(`Brave API error: ${response.status} ${response.statusText}\n${await response.text()}`); + if (sessionId && transports.has(sessionId)) { + return transports.get(sessionId) as StreamableHTTPServerTransport; } - const poisResponse = await response.json() as BravePoiResponse; - return poisResponse; -} + if (!sessionId && isInitializeRequest(req.body)) { + const server = createServer(); + const transport = await createNewHttpTransport(transports); + await server.connect(transport); -async function getDescriptionsData(ids: string[]): Promise { - checkRateLimit(); - const url = new URL('https://api.search.brave.com/res/v1/local/descriptions'); - ids.filter(Boolean).forEach(id => url.searchParams.append('ids', id)); - const response = await fetch(url, { - headers: { - 'Accept': 'application/json', - 'Accept-Encoding': 'gzip', - 'X-Subscription-Token': BRAVE_API_KEY - } - }); - - if (!response.ok) { - throw new Error(`Brave API error: ${response.status} ${response.statusText}\n${await response.text()}`); + return transport; } - const descriptionsData = await response.json() as BraveDescription; - return descriptionsData; + throw new Error('Invalid request - no session ID or not initialization request'); } -function formatLocalResults(poisData: BravePoiResponse, descData: BraveDescription): string { - return (poisData.results || []).map(poi => { - const address = [ - poi.address?.streetAddress ?? '', - poi.address?.addressLocality ?? '', - poi.address?.addressRegion ?? '', - poi.address?.postalCode ?? '' - ].filter(part => part !== '').join(', ') || 'N/A'; +function startHttpServer(port: string, transports: Map) { + const app = express(); - return `Name: ${poi.name} -Address: ${address} -Phone: ${poi.phone || 'N/A'} -Rating: ${poi.rating?.ratingValue ?? 'N/A'} (${poi.rating?.ratingCount ?? 0} reviews) -Price Range: ${poi.priceRange || 'N/A'} -Hours: ${(poi.openingHours || []).join(', ') || 'N/A'} -Description: ${descData.descriptions[poi.id] || 'No description available'} -`; - }).join('\n---\n') || 'No local results found'; -} + app.use(express.json()); -// Tool handlers -server.setRequestHandler(ListToolsRequestSchema, async () => ({ - tools: [WEB_SEARCH_TOOL, LOCAL_SEARCH_TOOL], -})); - -server.setRequestHandler(CallToolRequestSchema, async (request) => { - try { - const { name, arguments: args } = request.params; - - if (!args) { - throw new Error("No arguments provided"); - } - - switch (name) { - case "brave_web_search": { - if (!isBraveWebSearchArgs(args)) { - throw new Error("Invalid arguments for brave_web_search"); - } - const { query, count = 10 } = args; - const results = await performWebSearch(query, count); - return { - content: [{ type: "text", text: results }], - isError: false, - }; + app.all('/mcp', async (req: Request, res: Response) => { + try { + const transport = await getHttpTransportForRequest(req, transports); + await transport.handleRequest(req, res, req.body); + } catch (error) { + if (!res.headersSent) { + res.status(500).json({ + id: null, jsonrpc: '2.0', + error: { code: -32603, message: 'Internal server error' }, + }); } - - case "brave_local_search": { - if (!isBraveLocalSearchArgs(args)) { - throw new Error("Invalid arguments for brave_local_search"); - } - const { query, count = 5 } = args; - const results = await performLocalSearch(query, count); - return { - content: [{ type: "text", text: results }], - isError: false, - }; - } - - default: - return { - content: [{ type: "text", text: `Unknown tool: ${name}` }], - isError: true, - }; } - } catch (error) { - return { - content: [ - { - type: "text", - text: `Error: ${error instanceof Error ? error.message : String(error)}`, - }, - ], - isError: true, - }; - } -}); + }); -async function runServer() { + app.listen(port, () => console.error(`Server is running on http://localhost:${port}/mcp`)); +} + +async function startStdioServer() { + const server = createServer(); const transport = new StdioServerTransport(); await server.connect(transport); - console.error("Brave Search MCP Server running on stdio"); } -runServer().catch((error) => { - console.error("Fatal error running server:", error); - process.exit(1); -}); +function registerSigIntHandler(transports: Map) { + process.on('SIGINT', async () => { + for (const sessionID of transports.keys()) { + await transports.get(sessionID)?.close(); + transports.delete(sessionID); + } + + console.error('Server shut down.'); + process.exit(0); + }); +} + +function main() { + const transports = new Map(); + + if (CLI_OPTIONS.transport === "http") { + startHttpServer(CLI_OPTIONS.port, transports); + } else { + startStdioServer(); + } + + registerSigIntHandler(transports); + console.error(`Server is running on ${CLI_OPTIONS.transport} mode`); +} + +main(); diff --git a/src/tools/local.ts b/src/tools/local.ts new file mode 100644 index 0000000..1c4b122 --- /dev/null +++ b/src/tools/local.ts @@ -0,0 +1,115 @@ +import { z } from "zod"; +import { type WebResponse as BraveWeb, type BravePoiResponse, type BraveDescription } from "../types/index.js"; +import { performSearch as performWebSearch } from "./web.js"; +import { BRAVE_API_KEY } from "../constants.js"; +import { checkRateLimit } from "../utils.js"; + +export const name = "brave_local_search"; +export const description = "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:\n- Business names and addresses\n- Ratings and review counts\n- Phone numbers and opening hours\nUse this when the query implies 'near me' or mentions specific locations. Automatically falls back to web search if no local results are found."; +export const paramsSchema = z.object({ + query: z.string().describe("Local search query (e.g. 'pizza near Central Park')"), + count: z.number().min(1).max(20).default(5).describe("Number of results (1-20, default 5)"), +}); + +export async function performSearch({ query, count }: z.infer) { + checkRateLimit(); + // Initial search to get location IDs + const webUrl = new URL('https://api.search.brave.com/res/v1/web/search'); + webUrl.searchParams.set('q', query); + webUrl.searchParams.set('search_lang', 'en'); + webUrl.searchParams.set('result_filter', 'locations'); + webUrl.searchParams.set('count', Math.min(count, 20).toString()); + + const webResponse = await fetch(webUrl, { + headers: { + 'Accept': 'application/json', + 'Accept-Encoding': 'gzip', + 'X-Subscription-Token': BRAVE_API_KEY + } + }); + + if (!webResponse.ok) { + throw new Error(`Brave API error: ${webResponse.status} ${webResponse.statusText}\n${await webResponse.text()}`); + } + + const webData = await webResponse.json() as BraveWeb; + const locationIds = webData.locations?.results?.filter((r): r is { id: string; title?: string } => r.id != null).map(r => r.id) || []; + + if (locationIds.length === 0) { + return performWebSearch({ query, count, offset: 0 }); // Fallback to web search with default offset + } + + // Get POI details and descriptions in parallel + const [poisData, descriptionsData] = await Promise.all([ + getPoisData(locationIds), + getDescriptionsData(locationIds) + ]); + + return { + content: [{ + type: "text" as const, + text: formatLocalResults(poisData, descriptionsData) + }], + isError: false, + }; +} + +async function getPoisData(ids: string[]): Promise { + checkRateLimit(); + const url = new URL('https://api.search.brave.com/res/v1/local/pois'); + ids.filter(Boolean).forEach(id => url.searchParams.append('ids', id)); + const response = await fetch(url, { + headers: { + 'Accept': 'application/json', + 'Accept-Encoding': 'gzip', + 'X-Subscription-Token': BRAVE_API_KEY + } + }); + + if (!response.ok) { + throw new Error(`Brave API error: ${response.status} ${response.statusText}\n${await response.text()}`); + } + + const poisResponse = await response.json() as BravePoiResponse; + return poisResponse; +} + +async function getDescriptionsData(ids: string[]): Promise { + checkRateLimit(); + const url = new URL('https://api.search.brave.com/res/v1/local/descriptions'); + ids.filter(Boolean).forEach(id => url.searchParams.append('ids', id)); + const response = await fetch(url, { + headers: { + 'Accept': 'application/json', + 'Accept-Encoding': 'gzip', + 'X-Subscription-Token': BRAVE_API_KEY + } + }); + + if (!response.ok) { + throw new Error(`Brave API error: ${response.status} ${response.statusText}\n${await response.text()}`); + } + + const descriptionsData = await response.json() as BraveDescription; + return descriptionsData; +} + +function formatLocalResults(poisData: BravePoiResponse, descData: BraveDescription): string { + return (poisData.results || []).map(poi => { + const address = [ + poi.address?.streetAddress ?? '', + poi.address?.addressLocality ?? '', + poi.address?.addressRegion ?? '', + poi.address?.postalCode ?? '' + ].filter(part => part !== '').join(', ') || 'N/A'; + + return `Name: ${poi.name} + Address: ${address} + Phone: ${poi.phone || 'N/A'} + Rating: ${poi.rating?.ratingValue ?? 'N/A'} (${poi.rating?.ratingCount ?? 0} reviews) + Price Range: ${poi.priceRange || 'N/A'} + Hours: ${(poi.openingHours || []).join(', ') || 'N/A'} + Description: ${descData.descriptions[poi.id] || 'No description available'} + `; + }).join('\n---\n') || 'No local results found'; +} diff --git a/src/tools/web.ts b/src/tools/web.ts new file mode 100644 index 0000000..018215b --- /dev/null +++ b/src/tools/web.ts @@ -0,0 +1,49 @@ +import { type WebResponse } from "../types/index.js"; +import { BRAVE_API_KEY } from "../constants.js"; +import { checkRateLimit } from "../utils.js"; +import { z } from "zod"; + +export const name = "brave_web_search"; +export const description = "Performs a web search using the Brave Search API, ideal for general queries, news, articles, and online content. Use this for broad information gathering, recent events, or when you need diverse web sources. Supports pagination, content filtering, and freshness controls. Maximum 20 results per request, with offset for pagination."; +export const paramsSchema = z.object({ + query: z.string().describe("Search query (max 400 chars, 50 words)"), + count: z.number().min(1).max(20).default(10).describe("Number of results (1-20, default 10)"), + offset: z.number().min(0).max(9).default(0).describe("Pagination offset (max 9, default 0)") +}); + +export async function performSearch({ query, count, offset }: z.infer) { + checkRateLimit(); + const url = new URL('https://api.search.brave.com/res/v1/web/search'); + url.searchParams.set('q', query); + url.searchParams.set('count', Math.min(count, 20).toString()); // API limit + url.searchParams.set('offset', offset.toString()); + + const response = await fetch(url, { + headers: { + 'Accept': 'application/json', + 'Accept-Encoding': 'gzip', + 'X-Subscription-Token': BRAVE_API_KEY + } + }); + + if (!response.ok) { + throw new Error(`Brave API error: ${response.status} ${response.statusText}\n${await response.text()}`); + } + + const data = await response.json() as WebResponse; + + // Extract just web results + const results = (data.web?.results || []).map(result => ({ + title: result.title || '', + description: result.description || '', + url: result.url || '' + })); + + return { + content: results.map(r => ({ + type: "text" as const, + text: `Title: ${r.title}\nDescription: ${r.description}\nURL: ${r.url}` + })), + isError: false, + }; +} diff --git a/src/types/index.ts b/src/types/index.ts new file mode 100644 index 0000000..8d4c49a --- /dev/null +++ b/src/types/index.ts @@ -0,0 +1,48 @@ +export interface WebResponse { + web?: { + results?: Array<{ + title: string; + description: string; + url: string; + language?: string; + published?: string; + rank?: number; + }>; + }; + locations?: { + results?: Array<{ + id: string; // Required by API + title?: string; + }>; + }; +} + +export interface BraveLocation { + id: string; + name: string; + address: { + streetAddress?: string; + addressLocality?: string; + addressRegion?: string; + postalCode?: string; + }; + coordinates?: { + latitude: number; + longitude: number; + }; + phone?: string; + rating?: { + ratingValue?: number; + ratingCount?: number; + }; + openingHours?: string[]; + priceRange?: string; +} + +export interface BravePoiResponse { + results: BraveLocation[]; +} + +export interface BraveDescription { + descriptions: { [id: string]: string }; +} diff --git a/src/utils.ts b/src/utils.ts new file mode 100644 index 0000000..ee7cbaf --- /dev/null +++ b/src/utils.ts @@ -0,0 +1,21 @@ +import { RATE_LIMIT } from "./constants.js"; + +let requestCount = { + second: 0, + month: 0, + lastReset: Date.now() +}; + +export function checkRateLimit() { + const now = Date.now(); + if (now - requestCount.lastReset > 1000) { + requestCount.second = 0; + requestCount.lastReset = now; + } + if (requestCount.second >= RATE_LIMIT.perSecond || + requestCount.month >= RATE_LIMIT.perMonth) { + throw new Error('Rate limit exceeded'); + } + requestCount.second++; + requestCount.month++; +}