improved structure and implementation

This commit is contained in:
Sampson committed 2025-06-25 16:09:59 -05:00
1 parent bde68396e8
commit 5f29ef8a47
12 files changed
+300 -154

No files matched your search

+44
View File
@@ -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 <string>", "Brave API key", process.env.BRAVE_API_KEY ?? "")
.option("--transport <stdio|http>", "transport type", process.env.BRAVE_MCP_TRANSPORT ?? "http")
.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 ?? "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 };
+14
View File
@@ -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<string, StdioServerTransport | StreamableHTTPServerTransport>) {
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);
});
}
+24 -132
View File
@@ -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 <stdio|http>", "transport type", process.env.BRAVE_MCP_TRANSPORT ?? "stdio")
.option("--port <number>", "desired port for HTTP transport", process.env.BRAVE_MCP_PORT ?? "3000")
.option("--host <string>", "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<string, StreamableHTTPServerTransport>): Promise<StreamableHTTPServerTransport> {
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<string, StreamableHTTPServerTransport>): Promise<StreamableHTTPServerTransport> {
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<string, StreamableHTTPServerTransport>) {
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<string, StreamableHTTPServerTransport>) {
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<string, StreamableHTTPServerTransport>();
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();
});
+84
View File
@@ -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<string, StreamableHTTPServerTransport>,
sessionId?: string | string[]
): Promise<StreamableHTTPServerTransport> => {
// 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<string, StreamableHTTPServerTransport>();
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 };
+2
View File
@@ -0,0 +1,2 @@
export { default as stdioServer } from "./stdio.js";
export { default as httpServer } from "./http.js";
+10
View File
@@ -0,0 +1,10 @@
import { server } from "../server.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
export const start = async (): Promise<void> => {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("Stdio server started");
};
export default { start }
+29
View File
@@ -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
);
}
+4
View File
@@ -0,0 +1,4 @@
import WebSearchTool from "./web/index.js";
import LocalSearchTool from "./local/index.js";
export default { WebSearchTool, LocalSearchTool };
+16
View File
@@ -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<typeof params>;
export default params;
+25 -11
View File
@@ -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<typeof paramsSchema>) {
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
};
+24
View File
@@ -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<typeof params>;
export default params;
+24 -11
View File
@@ -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<typeof paramsSchema>) {
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<typeof par
isError: false,
};
}
export default {
name,
description,
annotations,
inputSchema: params.shape,
execute
};