mcp-brave-search
Version:
Brave Search MCP Server - Web and News Search via stdio
70 lines • 2.35 kB
JavaScript
/**
* Brave Search API Client
*/
import { ProxyAgent } from 'undici';
export class BraveSearchAPI {
apiKey;
baseUrl;
proxyAgent;
constructor(config) {
this.apiKey = config.apiKey;
this.baseUrl = config.baseUrl || 'https://api.search.brave.com/res/v1';
// Setup proxy if configured via environment variables
const proxyUrl = process.env.HTTPS_PROXY || process.env.HTTP_PROXY ||
process.env.https_proxy || process.env.http_proxy;
if (proxyUrl) {
this.proxyAgent = new ProxyAgent(proxyUrl);
}
}
getFetchOptions() {
const options = {
method: 'GET',
headers: {
'Accept': 'application/json',
'Accept-Encoding': 'gzip',
'X-Subscription-Token': this.apiKey,
},
};
if (this.proxyAgent) {
options.dispatcher = this.proxyAgent;
}
return options;
}
/**
* Perform a web search
*/
async webSearch(params) {
const url = new URL(`${this.baseUrl}/web/search`);
// Add query parameters
Object.entries(params).forEach(([key, value]) => {
if (value !== undefined && value !== null) {
url.searchParams.append(key, String(value));
}
});
const response = await fetch(url.toString(), this.getFetchOptions());
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Brave API error (${response.status}): ${errorText}`);
}
return await response.json();
}
/**
* Perform a news search
*/
async newsSearch(params) {
const url = new URL(`${this.baseUrl}/news/search`);
// Add query parameters
Object.entries(params).forEach(([key, value]) => {
if (value !== undefined && value !== null) {
url.searchParams.append(key, String(value));
}
});
const response = await fetch(url.toString(), this.getFetchOptions());
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Brave API error (${response.status}): ${errorText}`);
}
return await response.json();
}
}
//# sourceMappingURL=brave-api.js.map