From 5f29ef8a47ce15dcb716948cd0fc6a195d5461fc Mon Sep 17 00:00:00 2001 From: Sampson Date: Wed, 25 Jun 2025 16:09:59 -0500 Subject: [PATCH] improved structure and implementation --- src/config.ts | 44 +++++++ src/helpers.ts | 14 +++ src/index.ts | 156 ++++--------------------- src/protocols/http.ts | 84 +++++++++++++ src/protocols/index.ts | 2 + src/protocols/stdio.ts | 10 ++ src/server.ts | 29 +++++ src/tools/index.ts | 4 + src/tools/local/QueryParams.ts | 16 +++ src/tools/{local.ts => local/index.ts} | 36 ++++-- src/tools/web/QueryParams.ts | 24 ++++ src/tools/{web.ts => web/index.ts} | 35 ++++-- 12 files changed, 300 insertions(+), 154 deletions(-) create mode 100644 src/config.ts create mode 100644 src/helpers.ts create mode 100644 src/protocols/http.ts create mode 100644 src/protocols/index.ts create mode 100644 src/protocols/stdio.ts create mode 100644 src/server.ts create mode 100644 src/tools/index.ts create mode 100644 src/tools/local/QueryParams.ts rename src/tools/{local.ts => local/index.ts} (83%) create mode 100644 src/tools/web/QueryParams.ts rename src/tools/{web.ts => web/index.ts} (67%) diff --git a/src/config.ts b/src/config.ts new file mode 100644 index 0000000..a461d99 --- /dev/null +++ b/src/config.ts @@ -0,0 +1,44 @@ +import { Command } from "commander"; + +type Configuration = { + transport: "stdio" | "http"; + port: number; + host: string; + braveApiKey: string; +} + +export function getOptions(): Configuration | false { + const program = new Command() + .option("--brave-api-key ", "Brave API key", process.env.BRAVE_API_KEY ?? "") + .option("--transport ", "transport type", process.env.BRAVE_MCP_TRANSPORT ?? "http") + .option("--port ", "desired port for HTTP transport", process.env.BRAVE_MCP_PORT ?? "8080") + .option("--host ", "desired host for HTTP transport", process.env.BRAVE_MCP_HOST ?? "0.0.0.0") + .allowUnknownOption() + .parse(process.argv); + + const options = program.opts(); + + if (!["stdio", "http"].includes(options.transport)) { + console.error(`Invalid --transport value: '${options.transport}'. Must be one of: stdio, http.`); + return false; + } + + if (options.port < 1 || options.port > 65535) { + console.error(`Invalid --port value: '${options.port}'. Must be a valid port number between 1 and 65535.`); + return false; + } + + if (!options.braveApiKey) { + console.error("Error: --brave-api-key is required"); + return false; + } + + if (!options.host) { + console.error("Error: --host is required"); + return false; + } + + return options as Configuration; +} + +export default { getOptions }; diff --git a/src/helpers.ts b/src/helpers.ts new file mode 100644 index 0000000..2d7004a --- /dev/null +++ b/src/helpers.ts @@ -0,0 +1,14 @@ +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; + +export 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); + }); +} diff --git a/src/index.ts b/src/index.ts index f542731..87d4d76 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,140 +1,32 @@ #!/usr/bin/env node +import { getOptions } from "./config.js"; +import { stdioServer, httpServer } from "./protocols/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 { BRAVE_API_KEY } from "./constants.js"; +async function main() { + const options = getOptions(); -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"; + if (!options) { + console.error("Invalid configuration"); + process.exit(1); + } -if (!BRAVE_API_KEY) { - console.error("Error: BRAVE_API_KEY environment variable is required"); + // default to http server + if (!options.transport || options.transport === "http") { + httpServer.start(); + return; + } + + // stdio requires explicit request + if (options.transport === "stdio") { + await stdioServer.start(); + return; + } + + console.error("Invalid transport"); process.exit(1); } -const program = new Command() - .option("--transport ", "transport type", process.env.BRAVE_MCP_TRANSPORT ?? "stdio") - .option("--port ", "desired port for HTTP transport", process.env.BRAVE_MCP_PORT ?? "3000") - .option("--host ", "host address to bind to for HTTP transport", process.env.BRAVE_MCP_HOST ?? "0.0.0.0") - .allowUnknownOption() - .parse(process.argv); - -const TRANSPORT_TYPES = ["stdio", "http"] as const; - -const CLI_OPTIONS = program.opts<{ transport: "stdio" | "http"; port: string; host: string }>(); - -if (!TRANSPORT_TYPES.includes(CLI_OPTIONS.transport)) { - console.error(`Invalid --transport value: '${CLI_OPTIONS.transport}'. Must be one of: ${TRANSPORT_TYPES.join(", ")}.`); +main().catch((error) => { + console.error(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, host: 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(parseInt(port), host, () => console.error(`Server is running on http://${host}:${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, CLI_OPTIONS.host, transports); - } else { - startStdioServer(); - } - - registerSigIntHandler(transports); - console.error(`Server is running on ${CLI_OPTIONS.transport} mode`); -} - -main(); +}); diff --git a/src/protocols/http.ts b/src/protocols/http.ts new file mode 100644 index 0000000..f44a2e0 --- /dev/null +++ b/src/protocols/http.ts @@ -0,0 +1,84 @@ +import { randomUUID } from "node:crypto"; +import express, { type Request, type Response } from "express"; +import { getOptions } from "../config.js"; +import { server } from "../server.js"; +import { registerSigIntHandler } from "../helpers.js"; +import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js"; +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; +import { InMemoryEventStore } from "@modelcontextprotocol/sdk/examples/shared/inMemoryEventStore.js"; + +const getTransport = async ( + req: Request, + transports: Map, + sessionId?: string | string[] +): Promise => { + // Belongs to an existing session; re-use the transport + if (sessionId && transports.has(sessionId as string)) { + return transports.get(sessionId as string) as StreamableHTTPServerTransport; + } + + // No session ID and this is an initialization request; create a new transport + if (!sessionId && isInitializeRequest(req.body)) { + const transport = new StreamableHTTPServerTransport({ + eventStore: new InMemoryEventStore(), + sessionIdGenerator: () => randomUUID(), + onsessioninitialized: (sessionId) => transports.set(sessionId, transport) + }); + + transport.onclose = () => transports.delete(transport.sessionId as string); + + await server.connect(transport); + + return transport; + } + + // No session ID and this is not an initialization request; throw an error + throw new Error('Invalid request - no session ID or not initialization request'); +} + +export const start = () => { + const options = getOptions(); + + if (!options) { + console.error("Invalid configuration"); + process.exit(1); + } + + const app = express(); + const transports = new Map(); + + app.use(express.json()); + + app.all('/mcp', async (req: Request, res: Response) => { + try { + const transport = await getTransport(req, transports, req.headers['mcp-session-id']); + 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.all('/ping', (req: Request, res: Response) => { + // TODO (Sampson): Implement ping endpoint + res.status(200).end(); + }); + + app.all('/invocations', (req: Request, res: Response) => { + // TODO (Sampson): Implement invocations endpoint + res.status(200).end(); + }); + + app.listen(options.port, options.host, () => { + console.error(`Server is running on http://${options.host}:${options.port}/mcp`); + }); + + // Register a SIGINT handler to close all transports when the server is shut down + registerSigIntHandler(transports); +} + +export default { start }; diff --git a/src/protocols/index.ts b/src/protocols/index.ts new file mode 100644 index 0000000..e0bf16c --- /dev/null +++ b/src/protocols/index.ts @@ -0,0 +1,2 @@ +export { default as stdioServer } from "./stdio.js"; +export { default as httpServer } from "./http.js"; diff --git a/src/protocols/stdio.ts b/src/protocols/stdio.ts new file mode 100644 index 0000000..ffea587 --- /dev/null +++ b/src/protocols/stdio.ts @@ -0,0 +1,10 @@ +import { server } from "../server.js"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; + +export const start = async (): Promise => { + const transport = new StdioServerTransport(); + await server.connect(transport); + console.error("Stdio server started"); +}; + +export default { start } diff --git a/src/server.ts b/src/server.ts new file mode 100644 index 0000000..d9e53d1 --- /dev/null +++ b/src/server.ts @@ -0,0 +1,29 @@ +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import tools from "./tools/index.js"; + +export const server = new McpServer( + { + version: "0.1.0", + 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)) { + server.tool( + tool.name, + tool.description, + tool.inputSchema, + tool.annotations, + tool.execute + ); +} diff --git a/src/tools/index.ts b/src/tools/index.ts new file mode 100644 index 0000000..ea3884a --- /dev/null +++ b/src/tools/index.ts @@ -0,0 +1,4 @@ +import WebSearchTool from "./web/index.js"; +import LocalSearchTool from "./local/index.js"; + +export default { WebSearchTool, LocalSearchTool }; diff --git a/src/tools/local/QueryParams.ts b/src/tools/local/QueryParams.ts new file mode 100644 index 0000000..e949a88 --- /dev/null +++ b/src/tools/local/QueryParams.ts @@ -0,0 +1,16 @@ +import { z } from "zod"; + +export const params = z.object({ + query: z.string() + .describe("Local search query (e.g. 'pizza near Central Park')"), + count: z.number() + .int() + .min(1) + .max(20) + .default(5) + .describe("Number of results (1-20, default 5)") +}); + +export type QueryParams = z.infer; + +export default params; diff --git a/src/tools/local.ts b/src/tools/local/index.ts similarity index 83% rename from src/tools/local.ts rename to src/tools/local/index.ts index 1c4b122..ef01a2a 100644 --- a/src/tools/local.ts +++ b/src/tools/local/index.ts @@ -1,17 +1,23 @@ -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"; +import { type WebResponse as BraveWeb, type BravePoiResponse, type BraveDescription } from "../../types/index.js"; +import { execute as performWebSearch } from "../web/index.js"; +import { BRAVE_API_KEY } from "../../constants.js"; +import { checkRateLimit } from "../../utils.js"; +import type { ToolAnnotations } from "@modelcontextprotocol/sdk/types.js"; +import params, { type QueryParams } from "./QueryParams.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) { +export const annotations: ToolAnnotations = { + title: "Brave Local Search", + openWorldHint: true, +}; + +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."; + +// TODO (Sampson): Add output schema +// export const outputSchema = z.object({}); + +export async function execute({ query, count }: QueryParams) { checkRateLimit(); // Initial search to get location IDs const webUrl = new URL('https://api.search.brave.com/res/v1/web/search'); @@ -113,3 +119,11 @@ function formatLocalResults(poisData: BravePoiResponse, descData: BraveDescripti `; }).join('\n---\n') || 'No local results found'; } + +export default { + name, + description, + annotations, + inputSchema: params.shape, + execute +}; diff --git a/src/tools/web/QueryParams.ts b/src/tools/web/QueryParams.ts new file mode 100644 index 0000000..3d17197 --- /dev/null +++ b/src/tools/web/QueryParams.ts @@ -0,0 +1,24 @@ +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)"), + count: z.number() + .int() + .min(1) + .max(20) + .default(10) + .describe("Number of results (1-20, default 10)"), + offset: z.number() + .int() + .min(0) + .max(9) + .default(0) + .describe("Pagination offset (max 9, default 0)") +}); + +export type QueryParams = z.infer; + +export default params; diff --git a/src/tools/web.ts b/src/tools/web/index.ts similarity index 67% rename from src/tools/web.ts rename to src/tools/web/index.ts index 018215b..33c7f83 100644 --- a/src/tools/web.ts +++ b/src/tools/web/index.ts @@ -1,17 +1,22 @@ -import { type WebResponse } from "../types/index.js"; -import { BRAVE_API_KEY } from "../constants.js"; -import { checkRateLimit } from "../utils.js"; -import { z } from "zod"; +import type { ToolAnnotations } 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 params, { type QueryParams } from "./QueryParams.js"; 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) { +export const annotations: ToolAnnotations = { + title: "Brave Web Search", + openWorldHint: true, +}; + +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."; + +// TODO (Sampson): Add output schema +// export const outputSchema = z.object({}); + +export async function execute({ query, count, offset }: QueryParams) { checkRateLimit(); const url = new URL('https://api.search.brave.com/res/v1/web/search'); url.searchParams.set('q', query); @@ -47,3 +52,11 @@ export async function performSearch({ query, count, offset }: z.infer