From fd28e3e7b3e1911b4a2ba87a199feb86ec173c60 Mon Sep 17 00:00:00 2001 From: Sampson Date: Wed, 24 Jun 2026 13:53:51 -0500 Subject: [PATCH] feat(config): support reading Brave API key from a file (#313) * feat: support reading Brave API key from a file * chore: add secret file template and gitignore local keys * docs: document optional Docker Compose secrets workflow * fix: trim whitespace API keys and exclude secrets from Docker build * docs: clarify container paths for BRAVE_API_KEY_FILE * test: cover API key file config and expand Docker build context ignores * test: isolate getOptions tests from local env vars * docs: clarify optional use of BRAVE_API_KEY_FILE * docs: document BRAVE_API_KEY_FILE in AWS Marketplace catalog template --- .dockerignore | 7 +++ .gitignore | 2 + README.md | 26 +++++++++- docker-compose.secrets.example.yml | 19 +++++++ docker-compose.yml | 1 + marketplace-revision-release.json | 8 ++- secrets/brave_api_key.txt.example | 1 + src/config.test.ts | 81 ++++++++++++++++++++++++++++++ src/config.ts | 28 +++++++++-- src/utils.test.ts | 42 +++++++++++++++- src/utils.ts | 19 +++++++ 11 files changed, 225 insertions(+), 9 deletions(-) create mode 100644 .dockerignore create mode 100644 docker-compose.secrets.example.yml create mode 100644 secrets/brave_api_key.txt.example create mode 100644 src/config.test.ts diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..255b533 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,7 @@ +.git +node_modules +dist +.env +.env.* +secrets +.cursor diff --git a/.gitignore b/.gitignore index 8cec517..f843222 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ /node_modules /dist .env +secrets/* +!secrets/brave_api_key.txt.example diff --git a/README.md b/README.md index 5052830..e2ed588 100644 --- a/README.md +++ b/README.md @@ -169,7 +169,8 @@ Retrieves pre-extracted web content optimized for AI agents, LLM grounding, and The server supports the following environment variables: -- `BRAVE_API_KEY`: Your Brave Search API key (required) +- `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: "0.0.0.0") @@ -184,7 +185,8 @@ The server supports the following environment variables: node dist/index.js [options] Options: - --brave-api-key Brave API key + --brave-api-key Brave API key + --brave-api-key-file Path to file containing Brave API key --transport Transport type (default: stdio) --port HTTP server port (default: 8080) --host HTTP server host (default: 0.0.0.0) @@ -382,6 +384,26 @@ For local development with Docker: 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. diff --git a/docker-compose.secrets.example.yml b/docker-compose.secrets.example.yml new file mode 100644 index 0000000..bc46ea7 --- /dev/null +++ b/docker-compose.secrets.example.yml @@ -0,0 +1,19 @@ +# 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 diff --git a/docker-compose.yml b/docker-compose.yml index 40cbfa0..eab6b5f 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -9,6 +9,7 @@ services: delay: 5s environment: - BRAVE_API_KEY + - BRAVE_API_KEY_FILE - BRAVE_MCP_TRANSPORT=http - BRAVE_MCP_PORT=8080 - BRAVE_MCP_STATELESS diff --git a/marketplace-revision-release.json b/marketplace-revision-release.json index 0d95cfd..656cc8f 100644 --- a/marketplace-revision-release.json +++ b/marketplace-revision-release.json @@ -17,7 +17,7 @@ "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```json\n\"environmentVariables\": { \"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.", + "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\": \"\", \"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" ], @@ -35,7 +35,11 @@ "EnvironmentVariables": [ { "Name": "BRAVE_API_KEY", - "Description": "*Required* Brave Search API Key. Obtain Brave Search API Key through AWS Marketplace Product (https://aws.amazon.com/marketplace/pp/prodview-qjlabherxghtq)" + "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", diff --git a/secrets/brave_api_key.txt.example b/secrets/brave_api_key.txt.example new file mode 100644 index 0000000..5c6e0c5 --- /dev/null +++ b/secrets/brave_api_key.txt.example @@ -0,0 +1 @@ +YOUR_BRAVE_API_KEY_HERE diff --git a/src/config.test.ts b/src/config.test.ts new file mode 100644 index 0000000..60d916d --- /dev/null +++ b/src/config.test.ts @@ -0,0 +1,81 @@ +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_STATELESS', +] as const; + +describe('getOptions', () => { + const originalArgv = process.argv; + const originalEnv = Object.fromEntries(CONFIG_ENV_VARS.map((key) => [key, process.env[key]])); + + beforeEach(() => { + for (const key of CONFIG_ENV_VARS) { + delete process.env[key]; + } + }); + + afterEach(() => { + process.argv = originalArgv; + 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'); + } + }); +}); diff --git a/src/config.ts b/src/config.ts index 82c7d1f..ef3b60f 100644 --- a/src/config.ts +++ b/src/config.ts @@ -2,7 +2,7 @@ import { LoggingLevel, LoggingLevelSchema } from '@modelcontextprotocol/sdk/type import { Command } from 'commander'; import dotenv from 'dotenv'; import tools from './tools/index.js'; -import { parsePort } from './utils.js'; +import { parsePort, readBraveApiKeyFromFile } from './utils.js'; dotenv.config({ debug: false, quiet: true }); @@ -48,6 +48,11 @@ export function isToolPermittedByUser(toolName: string): boolean { export function getOptions(): Configuration | false { const program = new Command() .option('--brave-api-key ', 'Brave API key', process.env.BRAVE_API_KEY ?? '') + .option( + '--brave-api-key-file ', + 'Path to file containing Brave API key', + process.env.BRAVE_API_KEY_FILE ?? '' + ) .option('--logging-level ', 'Logging level', process.env.BRAVE_MCP_LOG_LEVEL ?? 'info') .option( '--transport ', @@ -118,9 +123,23 @@ export function getOptions(): Configuration | false { return false; } - if (!options.braveApiKey) { + 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: --brave-api-key is required. You can get one at https://brave.com/search/api/.' + '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; } @@ -143,9 +162,10 @@ export function getOptions(): Configuration | false { // Normalize stateless to boolean (CLI passes it as string) options.stateless = options.stateless === true || options.stateless === 'true'; + options.braveApiKey = braveApiKey; // Update state - state.braveApiKey = options.braveApiKey; + state.braveApiKey = braveApiKey; state.transport = options.transport; state.port = options.port; state.host = options.host; diff --git a/src/utils.test.ts b/src/utils.test.ts index 1c58b17..911e525 100644 --- a/src/utils.test.ts +++ b/src/utils.test.ts @@ -1,6 +1,9 @@ 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 { parsePort } from './utils.js'; +import { parsePort, readBraveApiKeyFromFile } from './utils.js'; describe('parsePort', () => { it('accepts valid integer ports', () => { @@ -22,3 +25,40 @@ describe('parsePort', () => { assert.equal(parsePort(undefined), null); }); }); + +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/); + } + }); +}); diff --git a/src/utils.ts b/src/utils.ts index 352597b..872a00a 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,3 +1,4 @@ +import { readFileSync } from 'node:fs'; import { RATE_LIMIT } from './constants.js'; let requestCount = { @@ -23,6 +24,24 @@ export function stringify(data: any, pretty = false) { return pretty ? JSON.stringify(data, null, 2) : JSON.stringify(data); } +export 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 parsePort(value: unknown): number | null { if (value === undefined || value === null || value === '') { return null;