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
This commit is contained in:
Sampson authored and GitHub committed 2026-06-24 13:53:51 -05:00
1 parent e3f77ced06
commit fd28e3e7b3
11 files changed
+225 -9

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
.git
node_modules
dist
.env
.env.*
secrets
.cursor
+2
View File
@@ -1,3 +1,5 @@
/node_modules
/dist
.env
secrets/*
!secrets/brave_api_key.txt.example
+24 -2
View File
@@ -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 <string> Brave API key
--brave-api-key <string> Brave API key
--brave-api-key-file <string> Path to file containing Brave API key
--transport <stdio|http> Transport type (default: stdio)
--port <number> HTTP server port (default: 8080)
--host <string> 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.
+19
View File
@@ -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
+1
View File
@@ -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
+6 -2
View File
@@ -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\": \"<YOUR_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\": \"<YOUR_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",
+1
View File
@@ -0,0 +1 @@
YOUR_BRAVE_API_KEY_HERE
+81
View File
@@ -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');
}
});
});
+24 -4
View File
@@ -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 <string>', 'Brave API key', process.env.BRAVE_API_KEY ?? '')
.option(
'--brave-api-key-file <string>',
'Path to file containing Brave API key',
process.env.BRAVE_API_KEY_FILE ?? ''
)
.option('--logging-level <string>', 'Logging level', process.env.BRAVE_MCP_LOG_LEVEL ?? 'info')
.option(
'--transport <stdio|http>',
@@ -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;
+41 -1
View File
@@ -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/);
}
});
});
+19
View File
@@ -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;