From 81f1c0d6dbd8e7015245d4a3937579e99d5ce0dc Mon Sep 17 00:00:00 2001 From: Sampson Date: Wed, 18 Jun 2025 12:14:04 -0500 Subject: [PATCH] adds http streaming support to server HTTP streaming is the default. To launch with STDIO the user must pass the `--transport stdio` CLI arguments. This has been documented in the README.md file. --- README.md | 21 ++++- package-lock.json | 101 +++++++++++++++++++++-- package.json | 6 +- src/constants.ts | 2 +- src/index.ts | 202 +++++++++++++++++++++++++++------------------ src/tools/local.ts | 56 ++++--------- src/tools/web.ts | 58 ++++--------- 7 files changed, 274 insertions(+), 172 deletions(-) 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..fcb288a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,7 +9,11 @@ "version": "1.0", "license": "MIT", "dependencies": { - "@modelcontextprotocol/sdk": "^1.12.3" + "@modelcontextprotocol/sdk": "^1.12.3", + "@types/express": "^5.0.3", + "commander": "^14.0.0", + "express": "^5.1.0", + "zod": "^3.25.67" }, "bin": { "brave-search-mcp-server": "dist/index.js" @@ -76,16 +80,92 @@ "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==", + "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==", + "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==", + "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==", + "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==" + }, + "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==" + }, "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==" + }, + "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==" + }, + "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==", + "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==", + "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 +259,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", @@ -1452,8 +1540,7 @@ "node_modules/undici-types": { "version": "7.8.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.8.0.tgz", - "integrity": "sha512-9UJ2xGDvQ43tYyVMpuHlsgApydB8ZKfVYTsLDhXkFL/6gfkp+U8xTGdh8pMJv1SpZna0zxG1DwsKZsreLbXBxw==", - "dev": true + "integrity": "sha512-9UJ2xGDvQ43tYyVMpuHlsgApydB8ZKfVYTsLDhXkFL/6gfkp+U8xTGdh8pMJv1SpZna0zxG1DwsKZsreLbXBxw==" }, "node_modules/unpipe": { "version": "1.0.0", @@ -1499,9 +1586,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..2a2fdc9 100644 --- a/package.json +++ b/package.json @@ -19,7 +19,11 @@ "watch": "tsc --watch" }, "dependencies": { - "@modelcontextprotocol/sdk": "^1.12.3" + "@modelcontextprotocol/sdk": "^1.12.3", + "@types/express": "^5.0.3", + "commander": "^14.0.0", + "express": "^5.1.0", + "zod": "^3.25.67" }, "devDependencies": { "@types/node": "24.0.3", diff --git a/src/constants.ts b/src/constants.ts index bba0eb5..6a0fe5b 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -2,5 +2,5 @@ export const BRAVE_API_KEY = process.env.BRAVE_API_KEY!; export const RATE_LIMIT = { perSecond: 1, - perMonth: 15000 + perMonth: 2000 } as const; diff --git a/src/index.ts b/src/index.ts index bffbe58..722e489 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,97 +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 { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; -import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js"; import { BRAVE_API_KEY } from "./constants.js"; -import WEB_SEARCH_TOOL, { validateArgs as isBraveWebSearchArgs, performSearch as performWebSearch } from "./tools/web.js"; -import LOCAL_SEARCH_TOOL, { validateArgs as isBraveLocalSearchArgs, performSearch as performLocalSearch } from "./tools/local.js"; +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"; -// Server implementation -const server = new Server( - { - name: "brave-search-mcp-server", - version: "0.1.0", - }, - { - capabilities: { - tools: {}, - }, - }, -); - -// Check for API key if (!BRAVE_API_KEY) { console.error("Error: BRAVE_API_KEY environment variable is required"); process.exit(1); } -// Tool handlers -server.setRequestHandler(ListToolsRequestSchema, async () => ({ - tools: [WEB_SEARCH_TOOL, LOCAL_SEARCH_TOOL], -})); +const program = new Command() + .option("--transport ", "transport type", "http") + .option("--port ", "desired port for HTTP transport", "3000") + .allowUnknownOption() + .parse(process.argv); -server.setRequestHandler(CallToolRequestSchema, async (request) => { - try { - const { name, arguments: args } = request.params; +const TRANSPORT_TYPES = ["stdio", "http"] as const; - if (!args) { - throw new Error("No arguments provided"); - } +const CLI_OPTIONS = program.opts<{ transport: "stdio" | "http"; port: string }>(); - 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, - }; - } - - 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() { - const transport = new StdioServerTransport(); - await server.connect(transport); - console.error("Brave Search MCP Server running on stdio"); +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); } -runServer().catch((error) => { - console.error("Fatal error running server:", error); - process.exit(1); -}); +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; +} + +async function createNewHttpTransport(transports: Map): Promise { + const transport = new StreamableHTTPServerTransport({ + eventStore: new InMemoryEventStore(), + sessionIdGenerator: () => randomUUID(), + onsessioninitialized: (sessionId) => { + transports.set(sessionId, transport); + } + }); + + transport.onclose = () => { + const sessionId = transport.sessionId; + if (sessionId && transports.has(sessionId)) { + transports.delete(sessionId); + } + }; + + return transport; +} + +async function getHttpTransportForRequest(req: Request, transports: Map): Promise { + const sessionId = req.headers['mcp-session-id'] as string | undefined; + + if (sessionId && transports.has(sessionId)) { + return transports.get(sessionId) as StreamableHTTPServerTransport; + } + + if (!sessionId && isInitializeRequest(req.body)) { + const server = createServer(); + const transport = await createNewHttpTransport(transports); + await server.connect(transport); + + return transport; + } + + throw new Error('Invalid request - no session ID or not initialization request'); +} + +function startHttpServer(port: string, transports: Map) { + const app = express(); + + app.use(express.json()); + + 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' }, + }); + } + } + }); + + 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); +} + +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 index 19d8163..1c4b122 100644 --- a/src/tools/local.ts +++ b/src/tools/local.ts @@ -1,47 +1,17 @@ -import { type Tool } from "@modelcontextprotocol/sdk/types.js"; +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 default { - 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"] - } -} as Tool; +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 function validateArgs(args: unknown): args is { query: string; count?: number } { - return ( - typeof args === "object" && - args !== null && - "query" in args && - typeof (args as { query: string }).query === "string" - ); -} - -export async function performSearch(query: string, count: number = 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'); @@ -66,7 +36,7 @@ export async function performSearch(query: string, count: number = 5) { 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 + return performWebSearch({ query, count, offset: 0 }); // Fallback to web search with default offset } // Get POI details and descriptions in parallel @@ -75,7 +45,13 @@ export async function performSearch(query: string, count: number = 5) { getDescriptionsData(locationIds) ]); - return formatLocalResults(poisData, descriptionsData); + return { + content: [{ + type: "text" as const, + text: formatLocalResults(poisData, descriptionsData) + }], + isError: false, + }; } async function getPoisData(ids: string[]): Promise { diff --git a/src/tools/web.ts b/src/tools/web.ts index a4515d2..018215b 100644 --- a/src/tools/web.ts +++ b/src/tools/web.ts @@ -1,47 +1,17 @@ -import { type Tool } from "@modelcontextprotocol/sdk/types.js"; import { type WebResponse } from "../types/index.js"; import { BRAVE_API_KEY } from "../constants.js"; import { checkRateLimit } from "../utils.js"; +import { z } from "zod"; -export default { - 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"], - }, -} as Tool; +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 function validateArgs(args: unknown): args is { query: string; count?: number } { - return ( - typeof args === "object" && - args !== null && - "query" in args && - typeof (args as { query: string }).query === "string" - ); -} - -export async function performSearch(query: string, count: number = 10, offset: number = 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); @@ -69,7 +39,11 @@ export async function performSearch(query: string, count: number = 10, offset: n url: result.url || '' })); - return results.map(r => - `Title: ${r.title}\nDescription: ${r.description}\nURL: ${r.url}` - ).join('\n\n'); + return { + content: results.map(r => ({ + type: "text" as const, + text: `Title: ${r.title}\nDescription: ${r.description}\nURL: ${r.url}` + })), + isError: false, + }; }