Merge pull request #11 from brave/sampson-cleanup
improved structure and implementation
This commit is contained in:
37 files changed
+3305
-379
No files matched your search
@@ -0,0 +1,23 @@
|
||||
# Dependencies
|
||||
node_modules/
|
||||
|
||||
# Build outputs
|
||||
dist/
|
||||
build/
|
||||
*.d.ts
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
|
||||
# OS generated files
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/
|
||||
.idea/
|
||||
|
||||
# Package files
|
||||
package-lock.json
|
||||
yarn.lock
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"semi": true,
|
||||
"singleQuote": true,
|
||||
"tabWidth": 2,
|
||||
"trailingComma": "es5",
|
||||
"printWidth": 100,
|
||||
"useTabs": false,
|
||||
"bracketSpacing": true,
|
||||
"arrowParens": "always"
|
||||
}
|
||||
Generated
+21
-5
@@ -9,7 +9,7 @@
|
||||
"version": "1.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/sdk": "1.13.2",
|
||||
"@modelcontextprotocol/sdk": "1.13.3",
|
||||
"commander": "14.0.0",
|
||||
"express": "5.1.0",
|
||||
"zod": "3.25.67"
|
||||
@@ -20,21 +20,22 @@
|
||||
"devDependencies": {
|
||||
"@types/express": "5.0.3",
|
||||
"@types/node": "24.0.3",
|
||||
"prettier": "3.6.2",
|
||||
"shx": "0.4.0",
|
||||
"typescript": "5.8.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@modelcontextprotocol/sdk": {
|
||||
"version": "1.13.2",
|
||||
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.13.2.tgz",
|
||||
"integrity": "sha512-Vx7qOcmoKkR3qhaQ9qf3GxiVKCEu+zfJddHv6x3dY/9P6+uIwJnmuAur5aB+4FDXf41rRrDnOEGkviX5oYZ67w==",
|
||||
"license": "MIT",
|
||||
"version": "1.13.3",
|
||||
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.13.3.tgz",
|
||||
"integrity": "sha512-bGwA78F/U5G2jrnsdRkPY3IwIwZeWUEfb5o764b79lb0rJmMT76TLwKhdNZOWakOQtedYefwIR4emisEMvInKA==",
|
||||
"dependencies": {
|
||||
"ajv": "^6.12.6",
|
||||
"content-type": "^1.0.5",
|
||||
"cors": "^2.8.5",
|
||||
"cross-spawn": "^7.0.5",
|
||||
"eventsource": "^3.0.2",
|
||||
"eventsource-parser": "^3.0.0",
|
||||
"express": "^5.0.1",
|
||||
"express-rate-limit": "^7.5.0",
|
||||
"pkce-challenge": "^5.0.0",
|
||||
@@ -1105,6 +1106,21 @@
|
||||
"node": ">=16.20.0"
|
||||
}
|
||||
},
|
||||
"node_modules/prettier": {
|
||||
"version": "3.6.2",
|
||||
"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.6.2.tgz",
|
||||
"integrity": "sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ==",
|
||||
"dev": true,
|
||||
"bin": {
|
||||
"prettier": "bin/prettier.cjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/prettier/prettier?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/proxy-addr": {
|
||||
"version": "2.0.7",
|
||||
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
|
||||
|
||||
+6
-3
@@ -15,11 +15,13 @@
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsc && shx chmod +x dist/*.js",
|
||||
"prepare": "npm run build",
|
||||
"watch": "tsc --watch"
|
||||
"prepare": "npm run format &&npm run build",
|
||||
"watch": "tsc --watch",
|
||||
"format": "prettier --write \"src/**/*.ts\"",
|
||||
"format:check": "prettier --check \"src/**/*.ts\""
|
||||
},
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/sdk": "1.13.2",
|
||||
"@modelcontextprotocol/sdk": "1.13.3",
|
||||
"commander": "14.0.0",
|
||||
"express": "5.1.0",
|
||||
"zod": "3.25.67"
|
||||
@@ -27,6 +29,7 @@
|
||||
"devDependencies": {
|
||||
"@types/express": "5.0.3",
|
||||
"@types/node": "24.0.3",
|
||||
"prettier": "3.6.2",
|
||||
"shx": "0.4.0",
|
||||
"typescript": "5.8.3"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import type { Endpoints } from './types.js';
|
||||
import config from '../config.js';
|
||||
import { checkRateLimit, log, stringify } from '../utils.js';
|
||||
|
||||
const typeToPathMap: Record<keyof Endpoints, string> = {
|
||||
images: '/res/v1/images/search',
|
||||
localPois: '/res/v1/local/pois',
|
||||
localDescriptions: '/res/v1/local/descriptions',
|
||||
news: '/res/v1/news/search',
|
||||
videos: '/res/v1/videos/search',
|
||||
web: '/res/v1/web/search',
|
||||
summarizer: '/res/v1/summarizer/search',
|
||||
};
|
||||
|
||||
const defaultRequestHeaders: Record<string, string> = {
|
||||
Accept: 'application/json',
|
||||
'Accept-Encoding': 'gzip',
|
||||
'X-Subscription-Token': config.braveApiKey,
|
||||
};
|
||||
|
||||
async function issueRequest<T extends keyof Endpoints>(
|
||||
endpoint: T,
|
||||
parameters: Endpoints[T]['params'],
|
||||
// TODO (Sampson): Implement support for custom request headers (helpful for POIs, etc.)
|
||||
requestHeaders: Endpoints[T]['requestHeaders'] = {} as Endpoints[T]['requestHeaders']
|
||||
): Promise<Endpoints[T]['response']> {
|
||||
// TODO (Sampson): Improve rate-limit logic to support self-throttling and n-keys
|
||||
// checkRateLimit();
|
||||
|
||||
// Determine URL, and setup parameters
|
||||
const url = new URL(`https://api.search.brave.com${typeToPathMap[endpoint]}`);
|
||||
const queryParams = new URLSearchParams();
|
||||
|
||||
await log('info', `Preparing to issue request to ${url.toString()}`);
|
||||
|
||||
// TODO (Sampson): Move param-construction/validation to modules
|
||||
for (const [key, value] of Object.entries(parameters)) {
|
||||
// The 'ids' parameter is expected to appear multiple times for multiple IDs
|
||||
if (['localPois', 'localDescriptions'].includes(endpoint)) {
|
||||
if (key === 'ids') {
|
||||
if (Array.isArray(value) && value.length > 0) {
|
||||
value.forEach((id) => queryParams.append(key, id));
|
||||
} else if (typeof value === 'string') {
|
||||
queryParams.set(key, value);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Handle result_filter parameter
|
||||
if (key === 'result_filter') {
|
||||
// Handle special behavior of 'summary' parameter:
|
||||
// Requires `result_filter` to be empty, or only contain 'summarizer'
|
||||
// see: https://bravesoftware.slack.com/archives/C01NNFM9XMM/p1751654841090929
|
||||
if ('summary' in parameters && parameters.summary === true) {
|
||||
queryParams.set(key, 'summarizer');
|
||||
} else if (Array.isArray(value) && value.length > 0) {
|
||||
queryParams.set(key, value.join(','));
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// Handle goggles parameters
|
||||
if (key === 'goggles') {
|
||||
if (typeof value === 'string') {
|
||||
queryParams.set(key, value);
|
||||
} else if (Array.isArray(value) && value.length > 0) {
|
||||
queryParams.set(key, value.join(','));
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (value !== undefined) {
|
||||
queryParams.set(key === 'query' ? 'q' : key, value.toString());
|
||||
}
|
||||
}
|
||||
|
||||
await log('debug', `Using parameters: ${queryParams.toString()}`);
|
||||
|
||||
// Issue Request
|
||||
const urlWithParams = url.toString() + '?' + queryParams.toString();
|
||||
const headers = { ...defaultRequestHeaders, ...requestHeaders } as Headers;
|
||||
const response = await fetch(urlWithParams, { headers });
|
||||
|
||||
await log('debug', `Received response from ${urlWithParams}`);
|
||||
|
||||
// Handle Error
|
||||
if (!response.ok) {
|
||||
let errorMessage = `${response.status} ${response.statusText}`;
|
||||
|
||||
try {
|
||||
const responseBody = await response.json();
|
||||
errorMessage += `\n${stringify(responseBody, true)}`;
|
||||
} catch (error) {
|
||||
errorMessage += `\n${await response.text()}`;
|
||||
}
|
||||
|
||||
await log('error', errorMessage);
|
||||
|
||||
// TODO (Sampson): Setup proper error handling, updating state, etc.
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
// Return Response
|
||||
const responseBody = await response.json();
|
||||
await log('debug', `Returning response: ${stringify(responseBody, true)}`);
|
||||
|
||||
return responseBody as Endpoints[T]['response'];
|
||||
}
|
||||
|
||||
export default {
|
||||
issueRequest,
|
||||
};
|
||||
@@ -0,0 +1,72 @@
|
||||
import type { QueryParams as WebQueryParams } from '../tools/web/params.js';
|
||||
import type { QueryParams as ImageQueryParams } from '../tools/images/params.js';
|
||||
import type { QueryParams as VideoQueryParams } from '../tools/videos/params.js';
|
||||
import type { QueryParams as NewsQueryParams } from '../tools/news/params.js';
|
||||
import type { LocalPoisParams, LocalDescriptionsParams } from '../tools/local/params.js';
|
||||
import type { SummarizerQueryParams } from '../tools/summarizer/params.js';
|
||||
import type { WebSearchApiResponse } from '../tools/web/types.js';
|
||||
import type { SummarizerSearchApiResponse } from '../tools/summarizer/types.js';
|
||||
import type { ImageSearchApiResponse } from '../tools/images/types.js';
|
||||
import type { VideoSearchApiResponse } from '../tools/videos/types.js';
|
||||
import type { NewsSearchApiResponse } from '../tools/news/types.js';
|
||||
import type {
|
||||
LocalPoiSearchApiResponse,
|
||||
LocalDescriptionsSearchApiResponse,
|
||||
} from '../tools/local/types.js';
|
||||
|
||||
export interface RateLimitErrorResponse {
|
||||
type: 'ErrorResponse';
|
||||
error: {
|
||||
id: string;
|
||||
status: number;
|
||||
code: 'RATE_LIMITED';
|
||||
detail: string;
|
||||
meta: {
|
||||
plan: string;
|
||||
rate_limit: number;
|
||||
rate_current: number;
|
||||
quota_limit: number;
|
||||
quota_current: number;
|
||||
component: 'rate_limiter';
|
||||
};
|
||||
};
|
||||
time: number;
|
||||
}
|
||||
|
||||
export type Endpoints = {
|
||||
web: {
|
||||
params: WebQueryParams;
|
||||
response: WebSearchApiResponse;
|
||||
requestHeaders: Headers;
|
||||
};
|
||||
images: {
|
||||
params: ImageQueryParams;
|
||||
response: ImageSearchApiResponse;
|
||||
requestHeaders: Headers;
|
||||
};
|
||||
videos: {
|
||||
params: VideoQueryParams;
|
||||
response: VideoSearchApiResponse;
|
||||
requestHeaders: Headers;
|
||||
};
|
||||
news: {
|
||||
params: NewsQueryParams;
|
||||
response: NewsSearchApiResponse;
|
||||
requestHeaders: Headers;
|
||||
};
|
||||
localPois: {
|
||||
params: LocalPoisParams;
|
||||
response: LocalPoiSearchApiResponse;
|
||||
requestHeaders: Headers;
|
||||
};
|
||||
localDescriptions: {
|
||||
params: LocalDescriptionsParams;
|
||||
response: LocalDescriptionsSearchApiResponse;
|
||||
requestHeaders: Headers;
|
||||
};
|
||||
summarizer: {
|
||||
params: SummarizerQueryParams;
|
||||
response: SummarizerSearchApiResponse;
|
||||
requestHeaders: Headers;
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,75 @@
|
||||
import { Command } from 'commander';
|
||||
|
||||
type Configuration = {
|
||||
transport: 'stdio' | 'http';
|
||||
port: number;
|
||||
host: string;
|
||||
braveApiKey: string;
|
||||
};
|
||||
|
||||
const state: Configuration & { ready: boolean } = {
|
||||
transport: 'http',
|
||||
port: 8080,
|
||||
host: '0.0.0.0',
|
||||
braveApiKey: process.env.BRAVE_API_KEY ?? '',
|
||||
ready: false,
|
||||
};
|
||||
|
||||
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.braveApiKey) {
|
||||
console.error(
|
||||
'Error: --brave-api-key is required. You can get one at https://brave.com/search/api/.'
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (options.transport === 'http') {
|
||||
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.host) {
|
||||
console.error('Error: --host is required');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Update state
|
||||
state.braveApiKey = options.braveApiKey;
|
||||
state.transport = options.transport;
|
||||
state.port = options.port;
|
||||
state.host = options.host;
|
||||
state.ready = true;
|
||||
|
||||
return options as Configuration;
|
||||
}
|
||||
|
||||
export default state;
|
||||
+4
-6
@@ -1,6 +1,4 @@
|
||||
export const BRAVE_API_KEY = process.env.BRAVE_API_KEY!;
|
||||
|
||||
export const RATE_LIMIT = {
|
||||
perSecond: 1,
|
||||
perMonth: 15000
|
||||
} as const;
|
||||
export const RATE_LIMIT = {
|
||||
perSecond: 1,
|
||||
perMonth: 15000,
|
||||
} as const;
|
||||
@@ -0,0 +1,16 @@
|
||||
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
@@ -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();
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import express, { type Request, type Response } from 'express';
|
||||
import config 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 = () => {
|
||||
if (!config.ready) {
|
||||
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.listen(config.port, config.host, () => {
|
||||
console.error(`Server is running on http://${config.host}:${config.port}/mcp`);
|
||||
});
|
||||
|
||||
// Register a SIGINT handler to close all transports when the server is shut down
|
||||
registerSigIntHandler(transports);
|
||||
};
|
||||
|
||||
export default { start };
|
||||
@@ -0,0 +1,2 @@
|
||||
export { default as stdioServer } from './stdio.js';
|
||||
export { default as httpServer } from './http.js';
|
||||
@@ -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 };
|
||||
@@ -0,0 +1,22 @@
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import type {
|
||||
ImageContent,
|
||||
TextContent,
|
||||
ToolAnnotations,
|
||||
} from '@modelcontextprotocol/sdk/types.js';
|
||||
import params, { type QueryParams } from './params.js';
|
||||
import API from '../../BraveAPI/index.js';
|
||||
import { log, stringify } from '../../utils.js';
|
||||
|
||||
export const name = 'brave_image_search';
|
||||
|
||||
export const annotations: ToolAnnotations = {
|
||||
title: 'Brave Image Search',
|
||||
openWorldHint: true,
|
||||
};
|
||||
|
||||
export const description = `
|
||||
Performs an image search using the Brave Search API. Helpful for when you need pictures of people, places, or things, ideas for graphic design, inspiration for art, or anything else where images are useful. When relaying the results in a markdown-supporting environment, it is helpful to include some/all of the images in the results. Example: .
|
||||
`;
|
||||
|
||||
export const execute = async (params: QueryParams) => {
|
||||
const content: (TextContent | ImageContent)[] = [];
|
||||
const response = await API.issueRequest<'images'>('images', params);
|
||||
|
||||
for (const { url: page_url, title, thumbnail, properties } of response.results) {
|
||||
// Skip results without an image
|
||||
if (!thumbnail?.src) continue;
|
||||
|
||||
// Prefer property URL as it is the shortest-possible URL
|
||||
const image_url = properties?.url ?? thumbnail.src;
|
||||
const fetched_image = await fetchImage(image_url);
|
||||
|
||||
if (fetched_image) {
|
||||
const { mimeType, data } = fetched_image;
|
||||
|
||||
content.push(
|
||||
{ type: 'text', text: stringify({ title, page_url, image_url }) },
|
||||
{ type: 'image', mimeType, data }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return { content, isError: false };
|
||||
};
|
||||
|
||||
async function fetchImage(url: string): Promise<{ mimeType: string; data: string } | null> {
|
||||
await log('info', `Fetching image data from ${url}`);
|
||||
try {
|
||||
const response = await fetch(url);
|
||||
const buffer = await response.arrayBuffer();
|
||||
return {
|
||||
data: Buffer.from(buffer).toString('base64'),
|
||||
mimeType: response.headers.get('content-type') ?? 'image/jpeg',
|
||||
};
|
||||
} catch (error) {
|
||||
await log('error', `Error fetching image data from ${url}: ${error}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export default {
|
||||
name,
|
||||
description,
|
||||
annotations,
|
||||
inputSchema: params.shape,
|
||||
execute,
|
||||
};
|
||||
@@ -0,0 +1,52 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const params = z.object({
|
||||
query: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(400)
|
||||
.refine((str) => str.split(/\s+/).length <= 50, 'Query cannot exceed 50 words')
|
||||
.describe(
|
||||
"The user's search query. Query cannot be empty. Limited to 400 characters and 50 words."
|
||||
),
|
||||
country: z
|
||||
.string()
|
||||
.default('US')
|
||||
.describe(
|
||||
'Search query country, where the results come from. The country string is limited to 2 character country codes of supported countries.'
|
||||
)
|
||||
.optional(),
|
||||
search_lang: z
|
||||
.string()
|
||||
.default('en')
|
||||
.describe(
|
||||
'Search language preference. The 2 or more character language code for which the search results are provided.'
|
||||
)
|
||||
.optional(),
|
||||
count: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(200)
|
||||
.default(50)
|
||||
.describe(
|
||||
'Number of results (1-200, default 50). Combine this parameter with `offset` to paginate search results.'
|
||||
)
|
||||
.optional(),
|
||||
safesearch: z
|
||||
.union([z.literal('off'), z.literal('strict')])
|
||||
.default('strict')
|
||||
.describe(
|
||||
"Filters search results for adult content. The following values are supported: 'off' - No filtering. 'strict' - Drops all adult content from search results."
|
||||
)
|
||||
.optional(),
|
||||
spellcheck: z
|
||||
.boolean()
|
||||
.default(true)
|
||||
.describe('Whether to spellcheck provided query.')
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export type QueryParams = z.infer<typeof params>;
|
||||
|
||||
export default params;
|
||||
@@ -0,0 +1,72 @@
|
||||
export interface ImageSearchApiResponse {
|
||||
/** The type of search API result. The value is always images. */
|
||||
type: 'images';
|
||||
/** Image search query string. */
|
||||
query: Query;
|
||||
/** The list of image results for the given query. */
|
||||
results: ImageResult[];
|
||||
/** Additional information about the image search results. */
|
||||
extra: Extra;
|
||||
}
|
||||
|
||||
interface Query {
|
||||
/** The original query that was requested. */
|
||||
original: string;
|
||||
/** The altered query by the spellchecker. This is the query that is used to search. */
|
||||
altered?: string;
|
||||
/** Whether the spellchecker is enabled or disabled. */
|
||||
spellcheck_off?: boolean;
|
||||
/** The value is true if the lack of results is due to a strict safesearch setting. Adult content relevant to the query was found, but was blocked by safesearch. */
|
||||
show_strict_warning?: string;
|
||||
}
|
||||
|
||||
export interface ImageResult {
|
||||
/** The type of image search API result. The value is always image_result. */
|
||||
type: 'image_result';
|
||||
/** The title of the image. */
|
||||
title?: string;
|
||||
/** The original page URL where the image was found. */
|
||||
url?: string;
|
||||
/** The source domain where the image was found. */
|
||||
source?: string;
|
||||
/** The ISO date time when the page was last fetched. The format is YYYY-MM-DDTHH:MM:SSZ. */
|
||||
page_fetched?: string;
|
||||
/** The thumbnail for the image. */
|
||||
thumbnail?: Thumbnail;
|
||||
/** Metadata for the image. */
|
||||
properties?: Properties;
|
||||
/** Aggregated information on the URL associated with the image search result. */
|
||||
meta_url?: MetaUrl;
|
||||
/** The confidence level for the image result. */
|
||||
confidence?: 'low' | 'medium' | 'high';
|
||||
}
|
||||
|
||||
interface Thumbnail {
|
||||
/** The served URL of the image. */
|
||||
src?: string;
|
||||
}
|
||||
|
||||
interface Properties {
|
||||
/** The image URL. */
|
||||
url?: string;
|
||||
/** The lower resolution placeholder image URL. */
|
||||
placeholder?: string;
|
||||
}
|
||||
|
||||
interface MetaUrl {
|
||||
/** The protocol scheme extracted from the URL. */
|
||||
scheme?: string;
|
||||
/** The network location part extracted from the URL. */
|
||||
netloc?: string;
|
||||
/** The lowercased domain name extracted from the URL. */
|
||||
hostname?: string;
|
||||
/** The favicon used for the URL. */
|
||||
favicon?: string;
|
||||
/** The hierarchical path of the URL useful as a display string. */
|
||||
path?: string;
|
||||
}
|
||||
|
||||
interface Extra {
|
||||
/** Indicates whether the image search results might contain offensive content. */
|
||||
might_be_offensive: boolean;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import WebSearchTool from './web/index.js';
|
||||
import LocalSearchTool from './local/index.js';
|
||||
import VideoSearchTool from './videos/index.js';
|
||||
import ImageSearchTool from './images/index.js';
|
||||
import NewsSearchTool from './news/index.js';
|
||||
import SummarizerTool from './summarizer/index.js';
|
||||
|
||||
export default {
|
||||
WebSearchTool,
|
||||
LocalSearchTool,
|
||||
VideoSearchTool,
|
||||
ImageSearchTool,
|
||||
NewsSearchTool,
|
||||
SummarizerTool,
|
||||
};
|
||||
@@ -1,115 +0,0 @@
|
||||
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";
|
||||
|
||||
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>) {
|
||||
checkRateLimit();
|
||||
// Initial search to get location IDs
|
||||
const webUrl = new URL('https://api.search.brave.com/res/v1/web/search');
|
||||
webUrl.searchParams.set('q', query);
|
||||
webUrl.searchParams.set('search_lang', 'en');
|
||||
webUrl.searchParams.set('result_filter', 'locations');
|
||||
webUrl.searchParams.set('count', Math.min(count, 20).toString());
|
||||
|
||||
const webResponse = await fetch(webUrl, {
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'Accept-Encoding': 'gzip',
|
||||
'X-Subscription-Token': BRAVE_API_KEY
|
||||
}
|
||||
});
|
||||
|
||||
if (!webResponse.ok) {
|
||||
throw new Error(`Brave API error: ${webResponse.status} ${webResponse.statusText}\n${await webResponse.text()}`);
|
||||
}
|
||||
|
||||
const webData = await webResponse.json() as BraveWeb;
|
||||
const locationIds = webData.locations?.results?.filter((r): r is { id: string; title?: string } => r.id != null).map(r => r.id) || [];
|
||||
|
||||
if (locationIds.length === 0) {
|
||||
return performWebSearch({ query, count, offset: 0 }); // Fallback to web search with default offset
|
||||
}
|
||||
|
||||
// Get POI details and descriptions in parallel
|
||||
const [poisData, descriptionsData] = await Promise.all([
|
||||
getPoisData(locationIds),
|
||||
getDescriptionsData(locationIds)
|
||||
]);
|
||||
|
||||
return {
|
||||
content: [{
|
||||
type: "text" as const,
|
||||
text: formatLocalResults(poisData, descriptionsData)
|
||||
}],
|
||||
isError: false,
|
||||
};
|
||||
}
|
||||
|
||||
async function getPoisData(ids: string[]): Promise<BravePoiResponse> {
|
||||
checkRateLimit();
|
||||
const url = new URL('https://api.search.brave.com/res/v1/local/pois');
|
||||
ids.filter(Boolean).forEach(id => url.searchParams.append('ids', id));
|
||||
const response = await fetch(url, {
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'Accept-Encoding': 'gzip',
|
||||
'X-Subscription-Token': BRAVE_API_KEY
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Brave API error: ${response.status} ${response.statusText}\n${await response.text()}`);
|
||||
}
|
||||
|
||||
const poisResponse = await response.json() as BravePoiResponse;
|
||||
return poisResponse;
|
||||
}
|
||||
|
||||
async function getDescriptionsData(ids: string[]): Promise<BraveDescription> {
|
||||
checkRateLimit();
|
||||
const url = new URL('https://api.search.brave.com/res/v1/local/descriptions');
|
||||
ids.filter(Boolean).forEach(id => url.searchParams.append('ids', id));
|
||||
const response = await fetch(url, {
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'Accept-Encoding': 'gzip',
|
||||
'X-Subscription-Token': BRAVE_API_KEY
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Brave API error: ${response.status} ${response.statusText}\n${await response.text()}`);
|
||||
}
|
||||
|
||||
const descriptionsData = await response.json() as BraveDescription;
|
||||
return descriptionsData;
|
||||
}
|
||||
|
||||
function formatLocalResults(poisData: BravePoiResponse, descData: BraveDescription): string {
|
||||
return (poisData.results || []).map(poi => {
|
||||
const address = [
|
||||
poi.address?.streetAddress ?? '',
|
||||
poi.address?.addressLocality ?? '',
|
||||
poi.address?.addressRegion ?? '',
|
||||
poi.address?.postalCode ?? ''
|
||||
].filter(part => part !== '').join(', ') || 'N/A';
|
||||
|
||||
return `Name: ${poi.name}
|
||||
Address: ${address}
|
||||
Phone: ${poi.phone || 'N/A'}
|
||||
Rating: ${poi.rating?.ratingValue ?? 'N/A'} (${poi.rating?.ratingCount ?? 0} reviews)
|
||||
Price Range: ${poi.priceRange || 'N/A'}
|
||||
Hours: ${(poi.openingHours || []).join(', ') || 'N/A'}
|
||||
Description: ${descData.descriptions[poi.id] || 'No description available'}
|
||||
`;
|
||||
}).join('\n---\n') || 'No local results found';
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import type {
|
||||
LocationResult,
|
||||
LocationDescription,
|
||||
OpeningHours,
|
||||
DayOpeningHours,
|
||||
} from './types.js';
|
||||
import webParams, { type QueryParams as WebQueryParams } from '../web/params.js';
|
||||
import type { CallToolResult, ToolAnnotations } from '@modelcontextprotocol/sdk/types.js';
|
||||
import API from '../../BraveAPI/index.js';
|
||||
import { formatWebResults } from '../web/index.js';
|
||||
import { log, stringify } from '../../utils.js';
|
||||
import { WebSearchApiResponse } from '../web/types.js';
|
||||
|
||||
export const name = 'brave_local_search';
|
||||
|
||||
export const annotations: ToolAnnotations = {
|
||||
title: 'Brave Local Search',
|
||||
openWorldHint: true,
|
||||
};
|
||||
|
||||
export const description = `
|
||||
Brave Local Search API provides enrichments for location search results. Access to this API is available only through the Brave Search API Pro plans; confirm the user's plan before using this tool (if the user does not have a Pro plan, use the brave_web_search tool). 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:
|
||||
- Business names and addresses
|
||||
- Ratings and review counts
|
||||
- Phone numbers and opening hours
|
||||
|
||||
Use this when the query implies 'near me', 'in my area', or mentions specific locations (e.g., 'in San Francisco'). This tool automatically falls back to brave_web_search if no local results are found.
|
||||
`;
|
||||
|
||||
// Access to Local API is available through the Pro plans.
|
||||
export const execute = async (params: WebQueryParams) => {
|
||||
// Make sure both 'web' and 'locations' are in the result_filter
|
||||
params = { ...params, result_filter: [...(params.result_filter || []), 'web', 'locations'] };
|
||||
|
||||
// Starts with a web search to retrieve potential location IDs
|
||||
const { locations, web: web_fallback } = await API.issueRequest<'web'>('web', params);
|
||||
|
||||
// We can send up to 20 location IDs at a time to the Local API
|
||||
// TODO (Sampson): Add support for multiple requests
|
||||
const locationIDs = (locations?.results || []).map((poi) => poi.id as string).slice(0, 20);
|
||||
|
||||
// No locations were found - user's plan may not include access to the Local API
|
||||
if (!locations || locationIDs.length === 0) {
|
||||
// If we have web results, but no locations, we'll fall back to the web results
|
||||
if (web_fallback && web_fallback.results.length > 0) {
|
||||
return buildFallbackWebResponse(web_fallback);
|
||||
}
|
||||
|
||||
// If we have no web results, we'll send a message to the user
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: 'text' as const,
|
||||
text: "No location data was returned. User's plan does not support local search, or the query may be unclear.",
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
// Fetch AI-generated descriptions
|
||||
const descriptions = await API.issueRequest<'localDescriptions'>('localDescriptions', {
|
||||
ids: locationIDs,
|
||||
});
|
||||
|
||||
return {
|
||||
content: formatLocalResults(locations.results, descriptions.results).map((formattedPOI) => ({
|
||||
type: 'text' as const,
|
||||
text: formattedPOI,
|
||||
})),
|
||||
};
|
||||
};
|
||||
|
||||
const buildFallbackWebResponse = (web_fallback: WebSearchApiResponse['web']): CallToolResult => {
|
||||
if (!web_fallback || web_fallback.results.length === 0) throw new Error('No web results found');
|
||||
|
||||
const fallback = {
|
||||
content: [
|
||||
{
|
||||
type: 'text' as const,
|
||||
text: "No location data was returned. Either the user's plan does not support local search, or the API was unable to find locations for the provided query. Falling back to general web search.",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
for (const web_result of formatWebResults(web_fallback)) {
|
||||
fallback.content.push({
|
||||
type: 'text' as const,
|
||||
text: stringify(web_result),
|
||||
});
|
||||
}
|
||||
|
||||
return fallback;
|
||||
};
|
||||
|
||||
const formatLocalResults = (
|
||||
poisData: LocationResult[],
|
||||
descData: LocationDescription[] = []
|
||||
): string[] => {
|
||||
return poisData.map((poi) => {
|
||||
return stringify({
|
||||
name: poi.title,
|
||||
price_range: poi.price_range,
|
||||
phone: poi.contact?.telephone,
|
||||
rating: poi.rating?.ratingValue,
|
||||
hours: formatOpeningHours(poi.opening_hours),
|
||||
rating_count: poi.rating?.reviewCount,
|
||||
description: descData.find(({ id }) => id === poi.id)?.description,
|
||||
address: poi.postal_address?.displayAddress,
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const formatOpeningHours = (openingHours?: OpeningHours): Record<string, string> | undefined => {
|
||||
if (!openingHours) return undefined;
|
||||
/**
|
||||
* Response will be something like {
|
||||
* 'sunday': '10:00-18:00',
|
||||
* 'monday': '10:00-18:00',
|
||||
* 'tuesday': '10:00-18:00',
|
||||
* 'wednesday': '10:00-18:00, 19:00-22:00',
|
||||
* 'thursday': '10:00-18:00',
|
||||
* 'friday': '10:00-18:00',
|
||||
* 'saturday': '12:00-18:00',
|
||||
* }
|
||||
*/
|
||||
const today: DayOpeningHours[] = openingHours.current_day || [];
|
||||
const response = {} as Record<string, string>;
|
||||
|
||||
const dayHours: [string, string[]][] = [
|
||||
[
|
||||
`today (${today[0].full_name.toLowerCase()})`,
|
||||
today.map(({ opens, closes }) => `${opens}-${closes}`),
|
||||
],
|
||||
];
|
||||
|
||||
// Add the rest of the days to the response
|
||||
for (let parts of openingHours.days || []) {
|
||||
// Not all days have arrays of hours, so normalize to an array
|
||||
if (!Array.isArray(parts)) parts = [parts];
|
||||
|
||||
// Add the hours for each day to the response
|
||||
for (const { full_name, opens, closes } of parts) {
|
||||
const dayName = full_name.toLowerCase();
|
||||
const existingEntry = dayHours.find(([name]) => name === dayName);
|
||||
|
||||
existingEntry
|
||||
? existingEntry[1].push(`${opens}-${closes}`)
|
||||
: dayHours.push([dayName, [`${opens}-${closes}`]]);
|
||||
}
|
||||
}
|
||||
|
||||
for (const [name, hours] of dayHours) {
|
||||
response[name] = hours.join(', ');
|
||||
}
|
||||
|
||||
return response;
|
||||
};
|
||||
|
||||
export default {
|
||||
name,
|
||||
description,
|
||||
annotations,
|
||||
inputSchema: webParams.shape,
|
||||
execute,
|
||||
};
|
||||
@@ -0,0 +1,12 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const LocalPoisParams = z.object({
|
||||
ids: z.array(z.string()).describe('List of location IDs for which to fetch POIs'),
|
||||
});
|
||||
|
||||
export const LocalDescriptionsParams = z.object({
|
||||
ids: z.array(z.string()).describe('List of location IDs for which to fetch descriptions'),
|
||||
});
|
||||
|
||||
export type LocalPoisParams = z.infer<typeof LocalPoisParams>;
|
||||
export type LocalDescriptionsParams = z.infer<typeof LocalDescriptionsParams>;
|
||||
@@ -0,0 +1,259 @@
|
||||
export interface LocalPoiSearchApiResponse {
|
||||
/** The type of local POI search API result. The value is always local_pois. */
|
||||
type: 'local_pois';
|
||||
/** Location results matching the ids in the request. */
|
||||
results?: LocationResult[];
|
||||
}
|
||||
|
||||
export interface LocalDescriptionsSearchApiResponse {
|
||||
/** The type of local description search API result. The value is always local_descriptions. */
|
||||
type: 'local_descriptions';
|
||||
/** Location descriptions matching the ids in the request. */
|
||||
results?: LocationDescription[];
|
||||
}
|
||||
|
||||
export interface LocationDescription {
|
||||
/** The type of a location description. The value is always local_description. */
|
||||
type: 'local_description';
|
||||
/** A Temporary id of the location with this description. */
|
||||
id: string;
|
||||
/** AI generated description of the location with the given id. */
|
||||
description?: string;
|
||||
}
|
||||
|
||||
interface Result {
|
||||
/** The title of the web page. */
|
||||
title: string;
|
||||
/** The URL where the page is served. */
|
||||
url: string;
|
||||
is_source_local: boolean;
|
||||
is_source_both: boolean;
|
||||
/** A description for the web page. */
|
||||
description?: string;
|
||||
/** A date representing the age of the web page. */
|
||||
page_age?: string;
|
||||
/** A date representing when the web page was last fetched. */
|
||||
page_fetched?: string;
|
||||
/** A profile associated with the web page. */
|
||||
profile?: Profile;
|
||||
/** A language classification for the web page. */
|
||||
language?: string;
|
||||
/** Whether the web page is family friendly. */
|
||||
family_friendly: boolean;
|
||||
}
|
||||
|
||||
interface Profile {
|
||||
/** The name of the profile. */
|
||||
name: string;
|
||||
/** The long name of the profile. */
|
||||
long_name: string;
|
||||
/** The original URL where the profile is available. */
|
||||
url?: string;
|
||||
/** The served image URL representing the profile. */
|
||||
img?: string;
|
||||
}
|
||||
|
||||
export interface LocationResult extends Result {
|
||||
/** Location result type identifier. The value is always location_result. */
|
||||
type: 'location_result';
|
||||
/** A Temporary id associated with this result, which can be used to retrieve extra information about the location. It remains valid for 8 hours… */
|
||||
id?: string;
|
||||
/** The complete URL of the provider. */
|
||||
provider_url: string;
|
||||
/** A list of coordinates associated with the location. This is a lat long represented as a floating point. */
|
||||
coordinates?: number[];
|
||||
/** The zoom level on the map. */
|
||||
zoom_level: number;
|
||||
/** The thumbnail associated with the location. */
|
||||
thumbnail?: Thumbnail;
|
||||
/** The postal address associated with the location. */
|
||||
postal_address?: PostalAddress;
|
||||
/** The opening hours, if it is a business, associated with the location . */
|
||||
opening_hours?: OpeningHours;
|
||||
/** The contact of the business associated with the location. */
|
||||
contact?: Contact;
|
||||
/** A display string used to show the price classification for the business. */
|
||||
price_range?: string;
|
||||
/** The ratings of the business. */
|
||||
rating?: Rating;
|
||||
/** The distance of the location from the client. */
|
||||
distance?: Unit;
|
||||
/** Profiles associated with the business. */
|
||||
profiles?: DataProvider[];
|
||||
/** Aggregated reviews from various sources relevant to the business. */
|
||||
reviews?: Reviews;
|
||||
/** A bunch of pictures associated with the business. */
|
||||
pictures?: PictureResults;
|
||||
/** An action to be taken. */
|
||||
action?: Action;
|
||||
/** A list of cuisine categories served. */
|
||||
serves_cuisine?: string[];
|
||||
/** A list of categories. */
|
||||
categories?: string[];
|
||||
/** An icon category. */
|
||||
icon_category?: string;
|
||||
/** Web results related to this location. */
|
||||
results?: LocationWebResult;
|
||||
/** IANA timezone identifier. */
|
||||
timezone?: string;
|
||||
/** The utc offset of the timezone. */
|
||||
timezone_offset?: string;
|
||||
}
|
||||
|
||||
interface Thumbnail {
|
||||
/** The served URL of the picture thumbnail. */
|
||||
src: string;
|
||||
/** The original URL of the image. */
|
||||
original?: string;
|
||||
}
|
||||
|
||||
interface PostalAddress {
|
||||
/** The type identifying a postal address. The value is always PostalAddress. */
|
||||
type: 'PostalAddress';
|
||||
/** The country associated with the location. */
|
||||
country?: string;
|
||||
/** The postal code associated with the location. */
|
||||
postalCode?: string;
|
||||
/** The street address associated with the location. */
|
||||
streetAddress?: string;
|
||||
/** The region associated with the location. This is usually a state. */
|
||||
addressRegion?: string;
|
||||
/** The address locality or subregion associated with the location. */
|
||||
addressLocality?: string;
|
||||
/** The displayed address string. */
|
||||
displayAddress: string;
|
||||
}
|
||||
|
||||
export interface OpeningHours {
|
||||
/** The current day opening hours. Can have two sets of opening hours. */
|
||||
current_day?: DayOpeningHours[];
|
||||
/** The opening hours for the whole week. */
|
||||
days?: DayOpeningHours[] | [DayOpeningHours][];
|
||||
}
|
||||
|
||||
interface Contact {
|
||||
/** The email address. */
|
||||
email?: string;
|
||||
/** The telephone number. */
|
||||
telephone?: string;
|
||||
}
|
||||
|
||||
interface Rating {
|
||||
/** The current value of the rating. */
|
||||
ratingValue: number;
|
||||
/** Best rating received. */
|
||||
bestRating: number;
|
||||
/** The number of reviews associated with the rating. */
|
||||
reviewCount?: number;
|
||||
/** The profile associated with the rating. */
|
||||
profile?: Profile;
|
||||
/** Whether the rating is coming from Tripadvisor. */
|
||||
is_tripadvisor: boolean;
|
||||
}
|
||||
|
||||
interface Unit {
|
||||
/** The quantity of the unit. */
|
||||
value: number;
|
||||
/** The name of the unit associated with the quantity. */
|
||||
units: string;
|
||||
}
|
||||
|
||||
interface DataProvider {
|
||||
/** The type representing the source of data. This is usually external. */
|
||||
type: 'external';
|
||||
/** The name of the data provider. This can be a domain. */
|
||||
name: string;
|
||||
/** The URL where the information is coming from. */
|
||||
url: string;
|
||||
/** The long name for the data provider. */
|
||||
long_name?: string;
|
||||
/** The served URL for the image data. */
|
||||
img?: string;
|
||||
}
|
||||
|
||||
interface Reviews {
|
||||
/** A list of trip advisor reviews for the entity. */
|
||||
results: TripAdvisorReview[];
|
||||
/** A URL to a web page where more information on the result can be seen. */
|
||||
viewMoreUrl: string;
|
||||
/** Any reviews available in a foreign language. */
|
||||
reviews_in_foreign_language: boolean;
|
||||
}
|
||||
|
||||
interface PictureResults {
|
||||
/** A URL to view more pictures. */
|
||||
viewMoreUrl?: string;
|
||||
/** A list of thumbnail results. */
|
||||
results: Thumbnail[];
|
||||
}
|
||||
|
||||
interface Action {
|
||||
/** The type representing the action. */
|
||||
type: string;
|
||||
/** A URL representing the action to be taken. */
|
||||
url: string;
|
||||
}
|
||||
|
||||
interface LocationWebResult extends Result {
|
||||
/** Aggregated information about the URL. */
|
||||
meta_url: MetaUrl;
|
||||
}
|
||||
|
||||
interface MetaUrl {
|
||||
/** The protocol scheme extracted from the URL. */
|
||||
scheme: string;
|
||||
/** The network location part extracted from the URL. */
|
||||
netloc: string;
|
||||
/** The lowercased domain name extracted from the URL. */
|
||||
hostname?: string;
|
||||
/** The favicon used for the URL. */
|
||||
favicon: string;
|
||||
/** The hierarchical path of the URL useful as a display string. */
|
||||
path: string;
|
||||
}
|
||||
|
||||
export interface DayOpeningHours {
|
||||
/** A short string representing the day of the week. */
|
||||
abbr_name: string;
|
||||
/** A full string representing the day of the week. */
|
||||
full_name: string;
|
||||
/** A 24 hr clock time string for the opening time of the business on a particular day. */
|
||||
opens: string;
|
||||
/** A 24 hr clock time string for the closing time of the business on a particular day. */
|
||||
closes: string;
|
||||
}
|
||||
|
||||
interface TripAdvisorReview {
|
||||
/** The title of the review. */
|
||||
title: string;
|
||||
/** A description seen in the review. */
|
||||
description: string;
|
||||
/** The date when the review was published. */
|
||||
date: string;
|
||||
/** A rating given by the reviewer. */
|
||||
rating: Rating;
|
||||
/** The author of the review. */
|
||||
author: Person;
|
||||
/** A URL link to the page where the review can be found. */
|
||||
review_url: string;
|
||||
/** The language of the review. */
|
||||
language: string;
|
||||
}
|
||||
|
||||
interface Person extends Omit<Thing, 'type'> {
|
||||
/** A type identifying a person. The value is always person. */
|
||||
type: 'person';
|
||||
/** Email address of the person. */
|
||||
email?: string;
|
||||
}
|
||||
|
||||
interface Thing {
|
||||
/** A type identifying a thing. The value is always thing. */
|
||||
type: 'thing';
|
||||
/** The name of the thing. */
|
||||
name: string;
|
||||
/** A URL for the thing. */
|
||||
url?: string;
|
||||
/** Thumbnail associated with the thing. */
|
||||
thumbnail?: Thumbnail;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import type { ToolAnnotations } from '@modelcontextprotocol/sdk/types.js';
|
||||
import params, { type QueryParams } from './params.js';
|
||||
import API from '../../BraveAPI/index.js';
|
||||
import { stringify } from '../../utils.js';
|
||||
|
||||
export const name = 'brave_news_search';
|
||||
|
||||
export const annotations: ToolAnnotations = {
|
||||
title: 'Brave News Search',
|
||||
openWorldHint: true,
|
||||
};
|
||||
|
||||
export const description = `
|
||||
This tool searches for news articles using Brave's News Search API based on the user's query. Use it when you need current news information, breaking news updates, or articles about specific topics, events, or entities.
|
||||
|
||||
When to use:
|
||||
- Finding recent news articles on specific topics
|
||||
- Getting breaking news updates
|
||||
- Researching current events or trending stories
|
||||
- Gathering news sources and headlines for analysis
|
||||
|
||||
Returns a JSON list of news-related results with title, url, and description. Some results may contain snippets of text from the article.
|
||||
|
||||
When relaying results in markdown-supporting environments, always cite sources with hyperlinks.
|
||||
|
||||
Examples:
|
||||
- "According to [Reuters](https://www.reuters.com/technology/china-bans/), China bans uncertified and recalled power banks on planes".
|
||||
- "The [New York Times](https://www.nytimes.com/2025/06/27/us/technology/ev-sales.html) reports that Tesla's EV sales have increased by 20%".
|
||||
- "According to [BBC News](https://www.bbc.com/news/world-europe-65910000), the UK government has announced a new policy to support renewable energy".
|
||||
`;
|
||||
|
||||
export const execute = async (params: QueryParams) => {
|
||||
const response = await API.issueRequest<'news'>('news', params);
|
||||
|
||||
return {
|
||||
content: response.results.map((newsResult) => {
|
||||
return {
|
||||
type: 'text' as const,
|
||||
text: stringify({
|
||||
url: newsResult.url,
|
||||
title: newsResult.title,
|
||||
age: newsResult.age,
|
||||
page_age: newsResult.page_age,
|
||||
breaking: newsResult.breaking ?? false,
|
||||
description: newsResult.description,
|
||||
extra_snippets: newsResult.extra_snippets,
|
||||
thumbnail: newsResult.thumbnail?.src,
|
||||
}),
|
||||
};
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
export default {
|
||||
name,
|
||||
description,
|
||||
annotations,
|
||||
inputSchema: params.shape,
|
||||
execute,
|
||||
};
|
||||
@@ -0,0 +1,82 @@
|
||||
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)'),
|
||||
country: z
|
||||
.string()
|
||||
.default('US')
|
||||
.describe(
|
||||
'Search query country, where the results come from. The country string is limited to 2 character country codes of supported countries.'
|
||||
)
|
||||
.optional(),
|
||||
search_lang: z
|
||||
.string()
|
||||
.default('en')
|
||||
.describe(
|
||||
'Search language preference. The 2 or more character language code for which the search results are provided.'
|
||||
)
|
||||
.optional(),
|
||||
ui_lang: z
|
||||
.string()
|
||||
.default('en-US')
|
||||
.describe(
|
||||
'User interface language preferred in response. Usually of the format <language_code>-<country_code>. For more, see RFC 9110.'
|
||||
)
|
||||
.optional(),
|
||||
count: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(50)
|
||||
.default(20)
|
||||
.describe('Number of results (1-50, default 20)')
|
||||
.optional(),
|
||||
offset: z
|
||||
.number()
|
||||
.int()
|
||||
.min(0)
|
||||
.max(9)
|
||||
.default(0)
|
||||
.describe('Pagination offset (max 9, default 0)')
|
||||
.optional(),
|
||||
spellcheck: z
|
||||
.boolean()
|
||||
.default(true)
|
||||
.describe('Whether to spellcheck provided query.')
|
||||
.optional(),
|
||||
safesearch: z
|
||||
.union([z.literal('off'), z.literal('moderate'), z.literal('strict')])
|
||||
.default('moderate')
|
||||
.describe(
|
||||
"Filters search results for adult content. The following values are supported: 'off' - No filtering. 'moderate' - Filter out explicit content. 'strict' - Filter out explicit and suggestive content. The default value is 'moderate'."
|
||||
)
|
||||
.optional(),
|
||||
freshness: z
|
||||
.union([z.literal('pd'), z.literal('pw'), z.literal('pm'), z.literal('py'), z.string()])
|
||||
.default('pd')
|
||||
.describe(
|
||||
"Filters search results by when they were discovered. The following values are supported: 'pd' - Discovered within the last 24 hours. 'pw' - Discovered within the last 7 Days. 'pm' - Discovered within the last 31 Days. 'py' - Discovered within the last 365 Days. 'YYYY-MM-DDtoYYYY-MM-DD' - Timeframe is also supported by specifying the date range e.g. 2022-04-01to2022-07-30."
|
||||
)
|
||||
.optional(),
|
||||
extra_snippets: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
.describe(
|
||||
'A snippet is an excerpt from a page you get as a result of the query, and extra_snippets allow you to get up to 5 additional, alternative excerpts. Only available under Free AI, Base AI, Pro AI, Base Data, Pro Data and Custom plans.'
|
||||
)
|
||||
.optional(),
|
||||
goggles: z
|
||||
.array(z.string())
|
||||
.describe(
|
||||
"Goggles act as a custom re-ranking on top of Brave's search index. The parameter supports both a url where the Goggle is hosted or the definition of the Goggle. For more details, refer to the Goggles repository (i.e., https://github.com/brave/goggles-quickstart)."
|
||||
)
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export type QueryParams = z.infer<typeof params>;
|
||||
|
||||
export default params;
|
||||
@@ -0,0 +1,66 @@
|
||||
export interface NewsSearchApiResponse {
|
||||
/** The type of search API result. The value is always news. */
|
||||
type: 'news';
|
||||
/** News search query string. */
|
||||
query: Query;
|
||||
/** The list of news results for the given query. */
|
||||
results: NewsResult[];
|
||||
}
|
||||
|
||||
interface Query {
|
||||
/** The original query that was requested. */
|
||||
original: string;
|
||||
/** The altered query by the spellchecker. This is the query that is used to search if any. */
|
||||
altered?: string;
|
||||
/** The cleaned normalized query by the spellchecker. This is the query that is used to search if any. */
|
||||
cleaned?: string;
|
||||
/** Whether the spellchecker is enabled or disabled. */
|
||||
spellcheck_off?: boolean;
|
||||
/** The value is true if the lack of results is due to a strict safesearch setting. Adult content relevant to the query was found, but was blocked by safesearch. */
|
||||
show_strict_warning?: boolean;
|
||||
}
|
||||
|
||||
export interface NewsResult {
|
||||
/** The type of news search API result. The value is always news_result. */
|
||||
type: 'news_result';
|
||||
/** The source URL of the news article. */
|
||||
url: string;
|
||||
/** The title of the news article. */
|
||||
title: string;
|
||||
/** The description for the news article. */
|
||||
description?: string;
|
||||
/** A human readable representation of the page age. */
|
||||
age?: string;
|
||||
/** The page age found from the source web page. */
|
||||
page_age?: string;
|
||||
/** The ISO date time when the page was last fetched. The format is YYYY-MM-DDTHH:MM:SSZ. */
|
||||
page_fetched?: string;
|
||||
/** Whether the result includes breaking news. */
|
||||
breaking?: boolean;
|
||||
/** The thumbnail for the news article. */
|
||||
thumbnail?: Thumbnail;
|
||||
/** Aggregated information on the URL associated with the news search result. */
|
||||
meta_url?: MetaUrl;
|
||||
/** A list of extra alternate snippets for the news search result. */
|
||||
extra_snippets?: string[];
|
||||
}
|
||||
|
||||
interface Thumbnail {
|
||||
/** The served URL of the thumbnail associated with the news article. */
|
||||
src: string;
|
||||
/** The original URL of the thumbnail associated with the news article. */
|
||||
original?: string;
|
||||
}
|
||||
|
||||
interface MetaUrl {
|
||||
/** The protocol scheme extracted from the URL. */
|
||||
scheme?: string;
|
||||
/** The network location part extracted from the URL. */
|
||||
netloc?: string;
|
||||
/** The lowercased domain name extracted from the URL. */
|
||||
hostname?: string;
|
||||
/** The favicon used for the URL. */
|
||||
favicon?: string;
|
||||
/** The hierarchical path of the URL useful as a display string. */
|
||||
path?: string;
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import type { CallToolResult, ToolAnnotations } from '@modelcontextprotocol/sdk/types.js';
|
||||
import { summarizerQueryParams, type SummarizerQueryParams } from './params.js';
|
||||
import API from '../../BraveAPI/index.js';
|
||||
import { type QueryParams as WebQueryParams } from '../web/params.js';
|
||||
import { SummarizerSearchApiResponse } from './types.js';
|
||||
import { log } from '../../utils.js';
|
||||
|
||||
export const name = 'brave_summarizer';
|
||||
|
||||
export const annotations: ToolAnnotations = {
|
||||
title: 'Brave Summarizer',
|
||||
openWorldHint: true,
|
||||
};
|
||||
|
||||
export const description = `
|
||||
Retrieves AI-generated summaries of web search results using Brave's Summarizer API. This tool processes search results to create concise, coherent summaries of information gathered from multiple sources.
|
||||
|
||||
When to use:
|
||||
|
||||
- When you need a concise overview of complex topics from multiple sources
|
||||
- For quick fact-checking or getting key points without reading full articles
|
||||
- When providing users with summarized information that synthesizes various perspectives
|
||||
- For research tasks requiring distilled information from web searches
|
||||
|
||||
Returns a text summary that consolidates information from the search results. Optional features include inline references to source URLs and additional entity information.
|
||||
|
||||
Requirements: Must first perform a web search using brave_web_search with summary=true parameter. Requires a Pro AI subscription to access the summarizer functionality.
|
||||
`;
|
||||
|
||||
export const execute = async (params: SummarizerQueryParams) => {
|
||||
const response: CallToolResult = { content: [], isError: false };
|
||||
|
||||
try {
|
||||
const { summary } = await pollForSummary(params);
|
||||
|
||||
if (!summary || summary.length === 0) {
|
||||
response.isError = true;
|
||||
response.content.push({
|
||||
type: 'text' as const,
|
||||
text: 'Unable to retrieve a Summarizer summary.',
|
||||
});
|
||||
} else {
|
||||
const summaryText = summary
|
||||
.map((summary_part) => {
|
||||
if (summary_part.type === 'token') {
|
||||
return summary_part.data;
|
||||
} else if (summary_part.type === 'inline_reference') {
|
||||
return ` (${summary_part.data?.url})`;
|
||||
} else {
|
||||
return '';
|
||||
}
|
||||
})
|
||||
.join('');
|
||||
|
||||
response.content.push({
|
||||
type: 'text' as const,
|
||||
text: summaryText,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
response.isError = true;
|
||||
response.content.push({
|
||||
type: 'text' as const,
|
||||
text: 'Unable to retrieve a Summarizer summary.',
|
||||
});
|
||||
}
|
||||
|
||||
return response;
|
||||
};
|
||||
|
||||
const pollForSummary = async (
|
||||
params: SummarizerQueryParams,
|
||||
pollInterval: number = 50,
|
||||
attempts: number = 20
|
||||
): Promise<SummarizerSearchApiResponse> => {
|
||||
let result: SummarizerSearchApiResponse | null = null;
|
||||
|
||||
while (!result && attempts > 0) {
|
||||
try {
|
||||
const response = await API.issueRequest<'summarizer'>('summarizer', params);
|
||||
if (response.status === 'complete') {
|
||||
result = response;
|
||||
}
|
||||
} catch (error) {
|
||||
await log('error', `Error polling for summarizer results: ${error}`);
|
||||
await new Promise((resolve) => setTimeout(resolve, pollInterval));
|
||||
}
|
||||
|
||||
attempts--;
|
||||
}
|
||||
|
||||
if (!result) {
|
||||
throw new Error('Summarizer summary could not be retrieved after multiple attempts.');
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
export default {
|
||||
name,
|
||||
description,
|
||||
annotations,
|
||||
inputSchema: summarizerQueryParams.shape,
|
||||
execute,
|
||||
};
|
||||
@@ -0,0 +1,83 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const summarizerQueryParams = z.object({
|
||||
key: z
|
||||
.string()
|
||||
.describe('The key is equal to value of field key as part of the Summarizer response model.'),
|
||||
entity_info: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
.describe('Returns extra entities info with the summary response.')
|
||||
.optional(),
|
||||
inline_references: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
.describe('Adds inline references to the summary response.')
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export type SummarizerQueryParams = z.infer<typeof summarizerQueryParams>;
|
||||
|
||||
export const chatCompletionsMessage = z.object({
|
||||
role: z
|
||||
.enum(['user'])
|
||||
.default('user')
|
||||
.describe('The role of the message. Only "user" is supported for now.'),
|
||||
content: z
|
||||
.string()
|
||||
.describe('The content of the message. The value is the question to be answered.'),
|
||||
});
|
||||
|
||||
export type ChatCompletionsMessage = z.infer<typeof chatCompletionsMessage>;
|
||||
|
||||
export const chatCompletionParams = z.object({
|
||||
messages: z
|
||||
.array(chatCompletionsMessage)
|
||||
.describe(
|
||||
'The messages to use for the chat completion. The value is a list of ChatCompletionsMessage response models.'
|
||||
),
|
||||
model: z
|
||||
.enum(['brave-pro', 'brave'])
|
||||
.default('brave-pro')
|
||||
.optional()
|
||||
.describe(
|
||||
'The model to use for the chat completion. The value can be "brave-pro" (default) or "brave".'
|
||||
),
|
||||
stream: z
|
||||
.boolean()
|
||||
.default(true)
|
||||
.optional()
|
||||
.describe(
|
||||
'Whether to stream the response. The value is `true` by default. When using the OpenAI CLI, use `openai.AsyncOpenAI` for streaming and `openai.OpenAI` for blocking mode.'
|
||||
),
|
||||
country: z
|
||||
.string()
|
||||
.default('us')
|
||||
.optional()
|
||||
.describe(
|
||||
'The country backend to use for the chat completion. The value is "us" by default. Note: This parameter is passed in extra_body field when using the OpenAI CLI.'
|
||||
),
|
||||
language: z
|
||||
.string()
|
||||
.default('en')
|
||||
.optional()
|
||||
.describe(
|
||||
'The language to use for the chat completion. The value is "en" by default. Note: This parameter is passed in extra_body field when using the OpenAI CLI.'
|
||||
),
|
||||
enable_entities: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
.optional()
|
||||
.describe(
|
||||
'Whether to enable entities in the chat completion. The value is `false` by default. Note: This parameter is passed in extra_body field when using the OpenAI CLI.'
|
||||
),
|
||||
enable_citations: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
.optional()
|
||||
.describe(
|
||||
'Whether to enable citations in the chat completion. The value is `false` by default. Note: This parameter is passed in extra_body field when using the OpenAI CLI.'
|
||||
),
|
||||
});
|
||||
|
||||
export type ChatCompletionParams = z.infer<typeof chatCompletionParams>;
|
||||
@@ -0,0 +1,139 @@
|
||||
export interface SummarizerSearchApiResponse {
|
||||
/** The type of summarizer search API result. The value is always summarizer. */
|
||||
type: 'summarizer';
|
||||
/** The current status of summarizer for the given key. The value can be either failed or complete. */
|
||||
status: string;
|
||||
/** The title for the summary. */
|
||||
title?: string;
|
||||
/** Details for the summary message. */
|
||||
summary?: SummaryMessage[];
|
||||
/** Enrichments that can be added to the summary message. */
|
||||
enrichments?: SummaryEnrichments;
|
||||
/** Followup queries relevant to the current query. */
|
||||
followups?: string[];
|
||||
/** Details on the entities in the summary message. */
|
||||
entities_infos?: Record<string, SummaryEntityInfo>;
|
||||
}
|
||||
|
||||
interface SummaryMessage {
|
||||
/** The type of subset of a summary message. The value can be token (a text excerpt from the summary), enum_item (a summary entity), enum_start (describes the beginning of summary entities, which means the following item(s) in the summary list will be entities), enum_end (the end of summary entities) or inline_reference (an inline reference to the summary, requires inline_references query param to be set). */
|
||||
type: string;
|
||||
/** The summary entity or the explanation for the type field. For type enum_start the value can be ol or ul, which means an ordered list or an unordered list of entities follows respectively. For type enum_end there is no value. For type token the value is a text excerpt. For type enum_item the value is the SummaryEntity response model. For type inline_reference the value is the SummaryInlineReference response model. */
|
||||
data?: SummaryEntity | SummaryInlineReference;
|
||||
}
|
||||
|
||||
interface TextLocation {
|
||||
/** The 0-based index, where the important part of the text starts. */
|
||||
start: number;
|
||||
/** The 0-based index, where the important part of the text ends. */
|
||||
end: number;
|
||||
}
|
||||
|
||||
interface SummaryEntity {
|
||||
/** A unique identifier for the entity. */
|
||||
uuid: string;
|
||||
/** The name of the entity. */
|
||||
name: string;
|
||||
/** The URL where further details on the entity can be found. */
|
||||
url?: string;
|
||||
/** A text message describing the entity. */
|
||||
text?: string;
|
||||
/** The image associated with the entity. */
|
||||
images?: SummaryImage[];
|
||||
/** The location of the entity in the summary message. */
|
||||
highlight?: TextLocation[];
|
||||
}
|
||||
|
||||
interface SummaryInlineReference {
|
||||
/** The type of inline reference. The value is always inline_reference. */
|
||||
type: string;
|
||||
/** The URL that is being referenced. */
|
||||
url: string;
|
||||
/** The start index of the inline reference in the summary message. */
|
||||
start_index: number;
|
||||
/** The end index of the inline reference in the summary message. */
|
||||
end_index: number;
|
||||
/** The ordinal number of the inline reference. */
|
||||
number: number;
|
||||
/** The favicon of the URL that is being referenced. */
|
||||
favicon?: string;
|
||||
/** The reference text snippet. */
|
||||
snippet?: string;
|
||||
}
|
||||
|
||||
interface Thumbnail {
|
||||
/** The served URL of the picture thumbnail. */
|
||||
src: string;
|
||||
/** The original URL of the image. */
|
||||
original?: string;
|
||||
}
|
||||
|
||||
interface ImageProperties {
|
||||
/** The image URL. */
|
||||
url: string;
|
||||
}
|
||||
|
||||
interface Image {
|
||||
/** The thumbnail associated with the image. */
|
||||
thumbnail: Thumbnail;
|
||||
/** The URL of the image. */
|
||||
url?: string;
|
||||
/** Metadata on the image. */
|
||||
properties?: ImageProperties;
|
||||
}
|
||||
|
||||
interface SummaryImage extends Image {
|
||||
/** Text associated with the image. */
|
||||
text?: string;
|
||||
}
|
||||
|
||||
interface SummaryEnrichments {
|
||||
/** The raw summary message. */
|
||||
raw: string;
|
||||
/** The images associated with the summary. */
|
||||
images?: SummaryImage[];
|
||||
/** The answers in the summary message. */
|
||||
qa?: SummaryAnswer[];
|
||||
/** The entities in the summary message. */
|
||||
entities?: SummaryEntity[];
|
||||
/** References based on which the summary was built. */
|
||||
context?: SummaryContext[];
|
||||
}
|
||||
|
||||
interface SummaryAnswer {
|
||||
/** The answer text. */
|
||||
answer: string;
|
||||
/** A score associated with the answer. */
|
||||
score?: number;
|
||||
/** The location of the answer in the summary message. */
|
||||
highlight?: TextLocation;
|
||||
}
|
||||
|
||||
interface MetaUrl {
|
||||
/** The protocol scheme extracted from the URL. */
|
||||
scheme?: string;
|
||||
/** The network location part extracted from the URL. */
|
||||
netloc?: string;
|
||||
/** The lowercased domain name extracted from the URL. */
|
||||
hostname?: string;
|
||||
/** The favicon used for the URL. */
|
||||
favicon?: string;
|
||||
/** The hierarchical path of the URL useful as a display string. */
|
||||
path?: string;
|
||||
}
|
||||
|
||||
interface SummaryContext {
|
||||
/** The title of the reference. */
|
||||
title: string;
|
||||
/** The URL where the reference can be found. */
|
||||
url: string;
|
||||
/** Details on the URL associated with the reference. */
|
||||
meta_url?: MetaUrl;
|
||||
}
|
||||
|
||||
interface SummaryEntityInfo {
|
||||
/** The name of the provider. */
|
||||
provider?: string;
|
||||
/** Description of the entity. */
|
||||
description?: string;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { ToolAnnotations } from '@modelcontextprotocol/sdk/types.js';
|
||||
import params, { type QueryParams } from './params.js';
|
||||
import API from '../../BraveAPI/index.js';
|
||||
import { stringify } from '../../utils.js';
|
||||
|
||||
export const name = 'brave_video_search';
|
||||
|
||||
export const annotations: ToolAnnotations = {
|
||||
title: 'Brave Video Search',
|
||||
openWorldHint: true,
|
||||
};
|
||||
|
||||
export const description = `
|
||||
Searches for videos using Brave's Video Search API and returns structured video results with metadata.
|
||||
|
||||
When to use:
|
||||
- When you need to find videos related to a specific topic, keyword, or query.
|
||||
- Useful for discovering video content, getting video metadata, or finding videos from specific creators/publishers.
|
||||
|
||||
Returns a JSON list of video-related results with title, url, description, duration, and thumbnail_url.
|
||||
`;
|
||||
|
||||
export const execute = async (params: QueryParams) => {
|
||||
const response = await API.issueRequest<'videos'>('videos', params);
|
||||
|
||||
return {
|
||||
content: response.results.map(({ url, title, description, video, thumbnail }) => {
|
||||
const duration = video?.duration;
|
||||
const thumbnail_url = thumbnail?.src;
|
||||
|
||||
return {
|
||||
type: 'text' as const,
|
||||
text: stringify({ url, title, description, duration, thumbnail_url }),
|
||||
};
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
export default {
|
||||
name,
|
||||
description,
|
||||
annotations,
|
||||
inputSchema: params.shape,
|
||||
execute,
|
||||
};
|
||||
@@ -0,0 +1,75 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const params = z.object({
|
||||
query: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(400)
|
||||
.refine((str) => str.split(/\s+/).length <= 50, 'Query cannot exceed 50 words')
|
||||
.describe(
|
||||
"The user's search query. Query cannot be empty. Limited to 400 characters and 50 words."
|
||||
),
|
||||
country: z
|
||||
.string()
|
||||
.default('US')
|
||||
.describe(
|
||||
'Search query country, where the results come from. The country string is limited to 2 character country codes of supported countries.'
|
||||
)
|
||||
.optional(),
|
||||
search_lang: z
|
||||
.string()
|
||||
.default('en')
|
||||
.describe(
|
||||
'Search language preference. The 2 or more character language code for which the search results are provided.'
|
||||
)
|
||||
.optional(),
|
||||
ui_lang: z
|
||||
.string()
|
||||
.default('en-US')
|
||||
.describe(
|
||||
'User interface language preferred in response. Usually of the format <language_code>-<country_code>. For more, see RFC 9110.'
|
||||
)
|
||||
.optional(),
|
||||
count: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(50)
|
||||
.default(20)
|
||||
.describe(
|
||||
'Number of results (1-50, default 20). Combine this parameter with `offset` to paginate search results.'
|
||||
)
|
||||
.optional(),
|
||||
offset: z
|
||||
.number()
|
||||
.int()
|
||||
.min(0)
|
||||
.max(9)
|
||||
.default(0)
|
||||
.describe(
|
||||
'Pagination offset (max 9, default 0). Combine this parameter with `count` to paginate search results.'
|
||||
)
|
||||
.optional(),
|
||||
spellcheck: z
|
||||
.boolean()
|
||||
.describe('Whether to spellcheck provided query.')
|
||||
.default(true)
|
||||
.optional(),
|
||||
safesearch: z
|
||||
.union([z.literal('off'), z.literal('moderate'), z.literal('strict')])
|
||||
.default('moderate')
|
||||
.describe(
|
||||
"Filters search results for adult content. The following values are supported: 'off' - No filtering. 'moderate' - Filter out explicit content. 'strict' - Filter out explicit and suggestive content. The default value is 'moderate'."
|
||||
)
|
||||
.optional(),
|
||||
freshness: z
|
||||
.union([z.literal('pd'), z.literal('pw'), z.literal('pm'), z.literal('py'), z.string()])
|
||||
.describe(
|
||||
"Filters search results by when they were discovered. The following values are supported: 'pd' - Discovered within the last 24 hours. 'pw' - Discovered within the last 7 days. 'pm' - Discovered within the last 31 days. 'py' - Discovered within the last 365 days. 'YYYY-MM-DDtoYYYY-MM-DD' - timeframe is also supported by specifying the date range (e.g. '2022-04-01to2022-07-30')."
|
||||
)
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export type QueryParams = z.infer<typeof params>;
|
||||
|
||||
export default params;
|
||||
@@ -0,0 +1,99 @@
|
||||
export interface VideoSearchApiResponse {
|
||||
/** The type of search API result. The value is always video. */
|
||||
type: 'videos';
|
||||
/** Video search query string. */
|
||||
query: Query;
|
||||
/** The list of video results for the given query. */
|
||||
results: VideoResult[];
|
||||
/** Additional information about the video search results. */
|
||||
extra: Extra;
|
||||
}
|
||||
|
||||
interface Query {
|
||||
/** The original query that was requested. */
|
||||
original: string;
|
||||
/** The altered query by the spellchecker. This is the query that is used to search if any. */
|
||||
altered?: string;
|
||||
/** The cleaned noramlized query by the spellchecker. This is the query that is used to search if any. */
|
||||
cleaned?: string;
|
||||
/** Whether the spellchecker is enabled or disabled. */
|
||||
spellcheck_off?: boolean;
|
||||
/** The value is true if the lack of results is due to a strict safesearch setting. Adult content relevant to the query was found, but was blocked by safesearch. */
|
||||
show_strict_warning?: string;
|
||||
}
|
||||
|
||||
interface Thumbnail {
|
||||
/** The served URL of the thumbnail associated with the video. */
|
||||
src: string;
|
||||
/** The original URL of the thumbnail associated with the video. */
|
||||
original?: string;
|
||||
}
|
||||
|
||||
interface Profile {
|
||||
/** The name of the profile. */
|
||||
name: string;
|
||||
/** The long name of the profile. */
|
||||
long_name?: string;
|
||||
/** The original URL where the profile is available. */
|
||||
url: string;
|
||||
/** The served image URL representing the profile. */
|
||||
img?: string;
|
||||
}
|
||||
|
||||
interface VideoData {
|
||||
/** A time string representing the duration of the video. */
|
||||
duration?: string;
|
||||
/** The number of views of the video. */
|
||||
views?: number;
|
||||
/** The creator of the video. */
|
||||
creator?: string;
|
||||
/** The publisher of the video. */
|
||||
publisher?: string;
|
||||
/** Whether the video requires a subscription. */
|
||||
requires_subscription?: boolean;
|
||||
/** A list of tags relevant to the video. */
|
||||
tags?: string[];
|
||||
/** A list of profiles associated with the video. */
|
||||
author?: Profile;
|
||||
}
|
||||
|
||||
interface MetaUrl {
|
||||
/** The protocol scheme extracted from the URL. */
|
||||
scheme?: string;
|
||||
/** The network location part extracted from the URL. */
|
||||
netloc?: string;
|
||||
/** The lowercased domain name extracted from the URL. */
|
||||
hostname?: string;
|
||||
/** The favicon used for the URL. */
|
||||
favicon?: string;
|
||||
/** The hierarchical path of the URL useful as a display string. */
|
||||
path?: string;
|
||||
}
|
||||
|
||||
export interface VideoResult {
|
||||
/** The type of video search API result. The value is always video_result. */
|
||||
type: 'video_result';
|
||||
/** The source URL of the video. */
|
||||
url: string;
|
||||
/** The title of the video. */
|
||||
title: string;
|
||||
/** The description for the video. */
|
||||
description?: string;
|
||||
/** A human readable representation of the page age. */
|
||||
age?: string;
|
||||
/** The page age found from the source web page. */
|
||||
page_age?: string;
|
||||
/** The ISO date time when the page was last fetched. The format is YYYY-MM-DDTHH:MM:SSZ. */
|
||||
page_fetched?: string;
|
||||
/** The thumbnail for the video. */
|
||||
thumbnail?: Thumbnail;
|
||||
/** Metadata for the video. */
|
||||
video?: VideoData;
|
||||
/** Aggregated information on the URL associated with the video search result. */
|
||||
meta_url?: MetaUrl;
|
||||
}
|
||||
|
||||
interface Extra {
|
||||
/** Indicates whether the video search results might contain offensive content. */
|
||||
might_be_offensive: boolean;
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
import { type WebResponse } from "../types/index.js";
|
||||
import { BRAVE_API_KEY } from "../constants.js";
|
||||
import { checkRateLimit } from "../utils.js";
|
||||
import { z } from "zod";
|
||||
|
||||
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>) {
|
||||
checkRateLimit();
|
||||
const url = new URL('https://api.search.brave.com/res/v1/web/search');
|
||||
url.searchParams.set('q', query);
|
||||
url.searchParams.set('count', Math.min(count, 20).toString()); // API limit
|
||||
url.searchParams.set('offset', offset.toString());
|
||||
|
||||
const response = await fetch(url, {
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'Accept-Encoding': 'gzip',
|
||||
'X-Subscription-Token': BRAVE_API_KEY
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Brave API error: ${response.status} ${response.statusText}\n${await response.text()}`);
|
||||
}
|
||||
|
||||
const data = await response.json() as WebResponse;
|
||||
|
||||
// Extract just web results
|
||||
const results = (data.web?.results || []).map(result => ({
|
||||
title: result.title || '',
|
||||
description: result.description || '',
|
||||
url: result.url || ''
|
||||
}));
|
||||
|
||||
return {
|
||||
content: results.map(r => ({
|
||||
type: "text" as const,
|
||||
text: `Title: ${r.title}\nDescription: ${r.description}\nURL: ${r.url}`
|
||||
})),
|
||||
isError: false,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import type { TextContent, ToolAnnotations } from '@modelcontextprotocol/sdk/types.js';
|
||||
import params, { type QueryParams } from './params.js';
|
||||
import API from '../../BraveAPI/index.js';
|
||||
import type {
|
||||
Discussions,
|
||||
FAQ,
|
||||
News,
|
||||
Search,
|
||||
Videos,
|
||||
FormattedFAQResults,
|
||||
FormattedDiscussionsResults,
|
||||
FormattedNewsResults,
|
||||
FormattedVideoResults,
|
||||
FormattedWebResults,
|
||||
} from './types.js';
|
||||
import { stringify } from '../../utils.js';
|
||||
|
||||
export const name = 'brave_web_search';
|
||||
|
||||
export const annotations: ToolAnnotations = {
|
||||
title: 'Brave Web Search',
|
||||
openWorldHint: true,
|
||||
};
|
||||
|
||||
export const description = `
|
||||
Performs web searches using the Brave Search API and returns comprehensive search results with rich metadata.
|
||||
|
||||
When to use:
|
||||
- General web searches for information, facts, or current topics
|
||||
- Location-based queries (restaurants, businesses, points of interest)
|
||||
- News searches for recent events or breaking stories
|
||||
- Finding videos, discussions, or FAQ content
|
||||
- Research requiring diverse result types (web pages, images, reviews, etc.)
|
||||
|
||||
Returns a JSON list of web results with title, description, and URL.
|
||||
|
||||
When the "results_filter" parameter is empty, JSON results may also contain FAQ, Discussions, News, and Video results.
|
||||
`;
|
||||
|
||||
export const execute = async (params: QueryParams) => {
|
||||
const response = { content: [] as TextContent[], isError: false };
|
||||
const { web, faq, discussions, news, videos, summarizer } = await API.issueRequest<'web'>(
|
||||
'web',
|
||||
params
|
||||
);
|
||||
|
||||
if (summarizer) {
|
||||
response.content.push({
|
||||
type: 'text' as const,
|
||||
text: `Summarizer key: ${summarizer.key}`,
|
||||
});
|
||||
}
|
||||
|
||||
if (!web || !Array.isArray(web.results) || web.results.length < 1) {
|
||||
response.isError = true;
|
||||
response.content.push({
|
||||
type: 'text' as const,
|
||||
text: 'No web results found',
|
||||
});
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
// TODO (Sampson): The following is unnecessarily repetitive.
|
||||
if (web && web.results?.length > 0) {
|
||||
for (const entry of formatWebResults(web)) {
|
||||
response.content.push({
|
||||
type: 'text' as const,
|
||||
text: stringify(entry),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (faq && faq.results?.length > 0) {
|
||||
for (const entry of formatFAQResults(faq)) {
|
||||
response.content.push({
|
||||
type: 'text' as const,
|
||||
text: stringify(entry),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (discussions && discussions.results?.length > 0) {
|
||||
for (const entry of formatDiscussionsResults(discussions)) {
|
||||
response.content.push({
|
||||
type: 'text' as const,
|
||||
text: stringify(entry),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (news && news.results?.length > 0) {
|
||||
for (const entry of formatNewsResults(news)) {
|
||||
response.content.push({
|
||||
type: 'text' as const,
|
||||
text: stringify(entry),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (videos && videos.results?.length > 0) {
|
||||
for (const entry of formatVideoResults(videos)) {
|
||||
response.content.push({
|
||||
type: 'text' as const,
|
||||
text: stringify(entry),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return response;
|
||||
};
|
||||
|
||||
export const formatWebResults = (web: Search): FormattedWebResults => {
|
||||
return (web.results || []).map(({ url, title, description, extra_snippets }) => ({
|
||||
url,
|
||||
title,
|
||||
description,
|
||||
extra_snippets,
|
||||
}));
|
||||
};
|
||||
|
||||
const formatFAQResults = (faq: FAQ): FormattedFAQResults => {
|
||||
return (faq.results || []).map(({ question, answer, title, url }) => ({
|
||||
question,
|
||||
answer,
|
||||
title,
|
||||
url,
|
||||
}));
|
||||
};
|
||||
|
||||
const formatDiscussionsResults = (discussions: Discussions): FormattedDiscussionsResults => {
|
||||
return (discussions.results || []).map(({ url, data }) => ({
|
||||
mutated_by_goggles: discussions.mutated_by_goggles,
|
||||
url,
|
||||
data,
|
||||
}));
|
||||
};
|
||||
|
||||
const formatNewsResults = (news: News): FormattedNewsResults => {
|
||||
return (news.results || []).map(
|
||||
({ source, breaking, is_live, age, url, title, description, extra_snippets }) => ({
|
||||
mutated_by_goggles: news.mutated_by_goggles,
|
||||
source,
|
||||
breaking,
|
||||
is_live,
|
||||
age,
|
||||
url,
|
||||
title,
|
||||
description,
|
||||
extra_snippets,
|
||||
})
|
||||
);
|
||||
};
|
||||
|
||||
const formatVideoResults = (videos: Videos): FormattedVideoResults => {
|
||||
return (videos.results || []).map(({ url, age, title, description, video, thumbnail }) => ({
|
||||
mutated_by_goggles: videos.mutated_by_goggles,
|
||||
url,
|
||||
title,
|
||||
description,
|
||||
age,
|
||||
thumbnail_url: thumbnail?.src,
|
||||
duration: video.duration,
|
||||
view_count: video.views,
|
||||
creator: video.creator,
|
||||
publisher: video.publisher,
|
||||
tags: video.tags,
|
||||
}));
|
||||
};
|
||||
|
||||
export default {
|
||||
name,
|
||||
description,
|
||||
annotations,
|
||||
inputSchema: params.shape,
|
||||
execute,
|
||||
};
|
||||
@@ -0,0 +1,246 @@
|
||||
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)'),
|
||||
country: z
|
||||
.enum([
|
||||
'ALL',
|
||||
'AR',
|
||||
'AU',
|
||||
'AT',
|
||||
'BE',
|
||||
'BR',
|
||||
'CA',
|
||||
'CL',
|
||||
'DK',
|
||||
'FI',
|
||||
'FR',
|
||||
'DE',
|
||||
'HK',
|
||||
'IN',
|
||||
'ID',
|
||||
'IT',
|
||||
'JP',
|
||||
'KR',
|
||||
'MY',
|
||||
'MX',
|
||||
'NL',
|
||||
'NZ',
|
||||
'NO',
|
||||
'CN',
|
||||
'PL',
|
||||
'PT',
|
||||
'PH',
|
||||
'RU',
|
||||
'SA',
|
||||
'ZA',
|
||||
'ES',
|
||||
'SE',
|
||||
'CH',
|
||||
'TW',
|
||||
'TR',
|
||||
'GB',
|
||||
'US',
|
||||
])
|
||||
.default('US')
|
||||
.describe(
|
||||
'Search query country, where the results come from. The country string is limited to 2 character country codes of supported countries.'
|
||||
)
|
||||
.optional(),
|
||||
search_lang: z
|
||||
.enum([
|
||||
'ar',
|
||||
'eu',
|
||||
'bn',
|
||||
'bg',
|
||||
'ca',
|
||||
'zh-hans',
|
||||
'zh-hant',
|
||||
'hr',
|
||||
'cs',
|
||||
'da',
|
||||
'nl',
|
||||
'en',
|
||||
'en-gb',
|
||||
'et',
|
||||
'fi',
|
||||
'fr',
|
||||
'gl',
|
||||
'de',
|
||||
'gu',
|
||||
'he',
|
||||
'hi',
|
||||
'hu',
|
||||
'is',
|
||||
'it',
|
||||
'jp',
|
||||
'kn',
|
||||
'ko',
|
||||
'lv',
|
||||
'lt',
|
||||
'ms',
|
||||
'ml',
|
||||
'mr',
|
||||
'nb',
|
||||
'pl',
|
||||
'pt-br',
|
||||
'pt-pt',
|
||||
'pa',
|
||||
'ro',
|
||||
'ru',
|
||||
'sr',
|
||||
'sk',
|
||||
'sl',
|
||||
'es',
|
||||
'sv',
|
||||
'ta',
|
||||
'te',
|
||||
'th',
|
||||
'tr',
|
||||
'uk',
|
||||
'vi',
|
||||
])
|
||||
.default('en')
|
||||
.describe(
|
||||
'Search language preference. The 2 or more character language code for which the search results are provided.'
|
||||
)
|
||||
.optional(),
|
||||
ui_lang: z
|
||||
.enum([
|
||||
'es-AR',
|
||||
'en-AU',
|
||||
'de-AT',
|
||||
'nl-BE',
|
||||
'fr-BE',
|
||||
'pt-BR',
|
||||
'en-CA',
|
||||
'fr-CA',
|
||||
'es-CL',
|
||||
'da-DK',
|
||||
'fi-FI',
|
||||
'fr-FR',
|
||||
'de-DE',
|
||||
'zh-HK',
|
||||
'en-IN',
|
||||
'en-ID',
|
||||
'it-IT',
|
||||
'ja-JP',
|
||||
'ko-KR',
|
||||
'en-MY',
|
||||
'es-MX',
|
||||
'nl-NL',
|
||||
'en-NZ',
|
||||
'no-NO',
|
||||
'zh-CN',
|
||||
'pl-PL',
|
||||
'en-PH',
|
||||
'ru-RU',
|
||||
'en-ZA',
|
||||
'es-ES',
|
||||
'sv-SE',
|
||||
'fr-CH',
|
||||
'de-CH',
|
||||
'zh-TW',
|
||||
'tr-TR',
|
||||
'en-GB',
|
||||
'en-US',
|
||||
'es-US',
|
||||
])
|
||||
.default('en-US')
|
||||
.describe(
|
||||
'The language of the UI. The 2 or more character language code for which the search results are provided.'
|
||||
)
|
||||
.optional(),
|
||||
count: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(20)
|
||||
.default(10)
|
||||
.describe(
|
||||
'Number of results (1-20, default 10). Applies only to web search results (i.e., has no effect on locations, news, videos, etc.)'
|
||||
)
|
||||
.optional(),
|
||||
offset: z
|
||||
.number()
|
||||
.int()
|
||||
.min(0)
|
||||
.max(9)
|
||||
.default(0)
|
||||
.describe('Pagination offset (max 9, default 0)')
|
||||
.optional(),
|
||||
safesearch: z
|
||||
.enum(['off', 'moderate', 'strict'])
|
||||
.default('moderate')
|
||||
.describe(
|
||||
"Filters search results for adult content. The following values are supported: 'off' - No filtering. 'moderate' - Filters explicit content (e.g., images and videos), but allows adult domains in search results. 'strict' - Drops all adult content from search results. The default value is 'moderate'."
|
||||
)
|
||||
.optional(),
|
||||
freshness: z
|
||||
.enum(['pd', 'pw', 'pm', 'py', 'YYYY-MM-DDtoYYYY-MM-DD'])
|
||||
.describe(
|
||||
"Filters search results by when they were discovered. The following values are supported: 'pd' - Discovered within the last 24 hours. 'pw' - Discovered within the last 7 days. 'pm' - Discovered within the last 31 days. 'py' - Discovered within the last 365 days. 'YYYY-MM-DDtoYYYY-MM-DD' - Timeframe is also supported by specifying the date range e.g. 2022-04-01to2022-07-30."
|
||||
)
|
||||
.optional(),
|
||||
text_decorations: z
|
||||
.boolean()
|
||||
.default(true)
|
||||
.describe(
|
||||
'Whether display strings (e.g. result snippets) should include decoration markers (e.g. highlighting characters).'
|
||||
)
|
||||
.optional(),
|
||||
spellcheck: z
|
||||
.boolean()
|
||||
.default(true)
|
||||
.describe('Whether to spellcheck the provided query.')
|
||||
.optional(),
|
||||
result_filter: z
|
||||
.array(
|
||||
z.enum([
|
||||
'discussions',
|
||||
'faq',
|
||||
'infobox',
|
||||
'news',
|
||||
'query',
|
||||
'summarizer',
|
||||
'videos',
|
||||
'web',
|
||||
'summarizer',
|
||||
'locations',
|
||||
'rich',
|
||||
])
|
||||
)
|
||||
.default(['web', 'query'])
|
||||
.describe("Result filter (default ['web', 'query'])")
|
||||
.optional(),
|
||||
goggles: z
|
||||
.array(z.string())
|
||||
.describe(
|
||||
"Goggles act as a custom re-ranking on top of Brave's search index. The parameter supports both a url where the Goggle is hosted or the definition of the Goggle. For more details, refer to the Goggles repository (i.e., https://github.com/brave/goggles-quickstart)."
|
||||
)
|
||||
.optional(),
|
||||
units: z
|
||||
.union([z.literal('metric'), z.literal('imperial')])
|
||||
.describe('The measurement units. If not provided, units are derived from search country.')
|
||||
.optional(),
|
||||
extra_snippets: z
|
||||
.boolean()
|
||||
.describe(
|
||||
'A snippet is an excerpt from a page you get as a result of the query, and extra_snippets allow you to get up to 5 additional, alternative excerpts. Only available under Free AI, Base AI, Pro AI, Base Data, Pro Data and Custom plans.'
|
||||
)
|
||||
.optional(),
|
||||
summary: z
|
||||
.boolean()
|
||||
.describe(
|
||||
'This parameter enables summary key generation in web search results. This is required for summarizer to be enabled.'
|
||||
)
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export type QueryParams = z.infer<typeof params>;
|
||||
|
||||
export default params;
|
||||
@@ -0,0 +1,979 @@
|
||||
export type FormattedWebResults = {
|
||||
url: string;
|
||||
title: string;
|
||||
description?: string;
|
||||
extra_snippets?: string[];
|
||||
}[];
|
||||
|
||||
export type FormattedFAQResults = {
|
||||
question: string;
|
||||
answer: string;
|
||||
title: string;
|
||||
url: string;
|
||||
}[];
|
||||
|
||||
export type FormattedDiscussionsResults = {
|
||||
mutated_by_goggles?: boolean;
|
||||
url: string;
|
||||
data?: ForumData;
|
||||
}[];
|
||||
|
||||
export type FormattedNewsResults = {
|
||||
mutated_by_goggles?: boolean;
|
||||
source?: string;
|
||||
breaking: boolean;
|
||||
is_live: boolean;
|
||||
age?: string;
|
||||
url: string;
|
||||
title: string;
|
||||
description?: string;
|
||||
extra_snippets?: string[];
|
||||
}[];
|
||||
|
||||
export type FormattedVideoResults = {
|
||||
mutated_by_goggles?: boolean;
|
||||
url: string;
|
||||
title: string;
|
||||
description?: string;
|
||||
age?: string;
|
||||
thumbnail_url?: string;
|
||||
duration?: string;
|
||||
view_count?: string;
|
||||
creator?: string;
|
||||
publisher?: string;
|
||||
tags?: string[];
|
||||
}[];
|
||||
|
||||
export interface WebSearchApiResponse {
|
||||
/** The type of web search API result. The value is always search. */
|
||||
type: 'search';
|
||||
/** Discussions clusters aggregated from forum posts that are relevant to the query. */
|
||||
discussions?: Discussions;
|
||||
/** Frequently asked questions that are relevant to the search query. */
|
||||
faq?: FAQ;
|
||||
/** Aggregated information on an entity showable as an infobox. */
|
||||
infobox?: GraphInfobox;
|
||||
/** Places of interest (POIs) relevant to location sensitive queries. */
|
||||
locations?: Locations;
|
||||
/** Preferred ranked order of search results. */
|
||||
mixed?: MixedResponse;
|
||||
/** News results relevant to the query. */
|
||||
news?: News;
|
||||
/** Search query string and its modifications that are used for search. */
|
||||
query?: Query;
|
||||
/** Videos relevant to the query. */
|
||||
videos?: Videos;
|
||||
/** Web search results relevant to the query. */
|
||||
web?: Search;
|
||||
/** Summary key to get summary results for the query. */
|
||||
summarizer?: Summarizer;
|
||||
/** Callback information for rich results. */
|
||||
rich?: RichCallbackInfo;
|
||||
}
|
||||
|
||||
export interface LocalPoiSearchApiResponse {
|
||||
/** The type of local POI search API result. The value is always local_pois. */
|
||||
type: 'local_pois';
|
||||
/** Location results matching the ids in the request. */
|
||||
results?: LocationResult[];
|
||||
}
|
||||
|
||||
export interface LocalDescriptionsSearchApiResponse {
|
||||
/** The type of local description search API result. The value is always local_descriptions. */
|
||||
type: 'local_descriptions';
|
||||
/** Location descriptions matching the ids in the request. */
|
||||
results?: LocationDescription[];
|
||||
}
|
||||
|
||||
interface Query {
|
||||
/** The original query that was requested. */
|
||||
original: string;
|
||||
/** Whether there is more content available for query, but the response was restricted due to safesearch. */
|
||||
show_strict_warning?: boolean;
|
||||
/** The altered query for which the search was performed. */
|
||||
altered?: string;
|
||||
/** Whether safesearch was enabled. */
|
||||
safesearch?: boolean;
|
||||
/** Whether the query is a navigational query to a domain. */
|
||||
is_navigational?: boolean;
|
||||
/** Whether the query has location relevance. */
|
||||
is_geolocal?: boolean;
|
||||
/** Whether the query was decided to be location sensitive. */
|
||||
local_decision?: string;
|
||||
/** The index of the location. */
|
||||
local_locations_idx?: number;
|
||||
/** Whether the query is trending. */
|
||||
is_trending?: boolean;
|
||||
/** Whether the query has news breaking articles relevant to it. */
|
||||
is_news_breaking?: boolean;
|
||||
/** Whether the query requires location information for better results. */
|
||||
ask_for_location?: boolean;
|
||||
/** The language information gathered from the query. */
|
||||
language?: Language;
|
||||
/** Whether the spellchecker was off. */
|
||||
spellcheck_off?: boolean;
|
||||
/** The country that was used. */
|
||||
country?: string;
|
||||
/** Whether there are bad results for the query. */
|
||||
bad_results?: boolean;
|
||||
/** Whether the query should use a fallback. */
|
||||
should_fallback?: boolean;
|
||||
/** The gathered location latitutde associated with the query. */
|
||||
lat?: string;
|
||||
/** The gathered location longitude associated with the query. */
|
||||
long?: string;
|
||||
/** The gathered postal code associated with the query. */
|
||||
postal_code?: string;
|
||||
/** The gathered city associated with the query. */
|
||||
city?: string;
|
||||
/** The gathered state associated with the query. */
|
||||
state?: string;
|
||||
/** The country for the request origination. */
|
||||
header_country?: string;
|
||||
/** Whether more results are available for the given query. */
|
||||
more_results_available?: boolean;
|
||||
/** Any custom location labels attached to the query. */
|
||||
custom_location_label?: string;
|
||||
/** Any reddit cluster associated with the query. */
|
||||
reddit_cluster?: string;
|
||||
}
|
||||
|
||||
export interface Discussions {
|
||||
/** The type identifying a discussion cluster. Currently the value is always search. */
|
||||
type: 'search';
|
||||
/** A list of discussion results. */
|
||||
results: DiscussionResult[];
|
||||
/** Whether the discussion results are changed by a Goggle. The value is false by default. */
|
||||
mutated_by_goggles: boolean;
|
||||
}
|
||||
|
||||
interface DiscussionResult extends Omit<SearchResult, 'type'> {
|
||||
/** The discussion result type identifier. The value is always discussion. */
|
||||
type: 'discussion';
|
||||
/** The enriched aggregated data for the relevant forum post. */
|
||||
data?: ForumData;
|
||||
}
|
||||
|
||||
export interface ForumData {
|
||||
/** The name of the forum. */
|
||||
forum_name: string;
|
||||
/** The number of answers to the post. */
|
||||
num_answers?: number;
|
||||
/** The score of the post on the forum. */
|
||||
score?: string;
|
||||
/** The title of the post on the forum. */
|
||||
title?: string;
|
||||
/** The question asked in the forum post. */
|
||||
question?: string;
|
||||
/** The top-rated comment under the forum post. */
|
||||
top_comment?: string;
|
||||
}
|
||||
|
||||
export interface FAQ {
|
||||
/** The FAQ result type identifier. The value is always faq. */
|
||||
type: 'faq';
|
||||
/** A list of aggregated question answer results relevant to the query. */
|
||||
results: QA[];
|
||||
}
|
||||
|
||||
interface QA {
|
||||
/** The question being asked. */
|
||||
question: string;
|
||||
/** The answer to the question. */
|
||||
answer: string;
|
||||
/** The title of the post. */
|
||||
title: string;
|
||||
/** The URL pointing to the post. */
|
||||
url: string;
|
||||
/** Aggregated information about the URL. */
|
||||
meta_url?: MetaUrl;
|
||||
}
|
||||
|
||||
interface MetaUrl {
|
||||
/** The protocol scheme extracted from the URL. */
|
||||
scheme: string;
|
||||
/** The network location part extracted from the URL. */
|
||||
netloc: string;
|
||||
/** The lowercased domain name extracted from the URL. */
|
||||
hostname?: string;
|
||||
/** The favicon used for the URL. */
|
||||
favicon: string;
|
||||
/** The hierarchical path of the URL useful as a display string. */
|
||||
path: string;
|
||||
}
|
||||
|
||||
export interface Search {
|
||||
/** A type identifying web search results. The value is always search. */
|
||||
type: 'search';
|
||||
/** A list of search results. */
|
||||
results: SearchResult[];
|
||||
/** Whether the results are family friendly. */
|
||||
family_friendly: boolean;
|
||||
}
|
||||
|
||||
export interface SearchResult extends Result {
|
||||
/** A type identifying a web search result. The value is always search_result. */
|
||||
type: 'search_result';
|
||||
/** A sub type identifying the web search result type. */
|
||||
subtype: 'generic';
|
||||
/** Whether the web search result is currently live. Default value is false. */
|
||||
is_live: boolean;
|
||||
/** Gathered information on a web search result. */
|
||||
deep_results?: DeepResult;
|
||||
/** A list of schemas (structured data) extracted from the page. The schemas try to follow schema.org and will return anything we can extract from the HTML that can fit into these models. */
|
||||
schemas?: [][];
|
||||
/** Aggregated information on the URL associated with the web search result. */
|
||||
meta_url?: MetaUrl;
|
||||
/** The thumbnail of the web search result. */
|
||||
thumbnail?: Thumbnail;
|
||||
/** A string representing the age of the web search result. */
|
||||
age?: string;
|
||||
/** The main language on the web search result. */
|
||||
language: string;
|
||||
/** The location details if the query relates to a restaurant. */
|
||||
location?: LocationResult;
|
||||
/** The video associated with the web search result. */
|
||||
video?: VideoData;
|
||||
/** The movie associated with the web search result. */
|
||||
movie?: MovieData;
|
||||
/** Any frequently asked questions associated with the web search result. */
|
||||
faq?: FAQ;
|
||||
/** Any question answer information associated with the web search result page. */
|
||||
qa?: QAPage;
|
||||
/** Any book information associated with the web search result page. */
|
||||
book?: Book;
|
||||
/** Rating found for the web search result page. */
|
||||
rating?: Rating;
|
||||
/** An article found for the web search result page. */
|
||||
article?: Article;
|
||||
/** The main product and a review that is found on the web search result page. */
|
||||
product?: Product | Review;
|
||||
/** A list of products and reviews that are found on the web search result page. */
|
||||
product_cluster?: Product | Review[];
|
||||
/** A type representing a cluster. The value can be product_cluster. */
|
||||
cluster_type?: string;
|
||||
/** A list of web search results. */
|
||||
cluster?: Result[];
|
||||
/** Aggregated information on the creative work found on the web search result. */
|
||||
creative_work?: CreativeWork;
|
||||
/** Aggregated information on music recording found on the web search result. */
|
||||
music_recording?: MusicRecording;
|
||||
/** Aggregated information on the review found on the web search result. */
|
||||
review?: Review;
|
||||
/** Aggregated information on a software product found on the web search result page. */
|
||||
software?: Software;
|
||||
/** Aggregated information on a recipe found on the web search result page. */
|
||||
recipe?: Recipe;
|
||||
/** Aggregated information on a organization found on the web search result page. */
|
||||
organization?: Organization;
|
||||
/** The content type associated with the search result page. */
|
||||
content_type?: string;
|
||||
/** A list of extra alternate snippets for the web search result. */
|
||||
extra_snippets?: string[];
|
||||
}
|
||||
|
||||
interface Result {
|
||||
/** The title of the web page. */
|
||||
title: string;
|
||||
/** The URL where the page is served. */
|
||||
url: string;
|
||||
is_source_local: boolean;
|
||||
is_source_both: boolean;
|
||||
/** A description for the web page. */
|
||||
description?: string;
|
||||
/** A date representing the age of the web page. */
|
||||
page_age?: string;
|
||||
/** A date representing when the web page was last fetched. */
|
||||
page_fetched?: string;
|
||||
/** A profile associated with the web page. */
|
||||
profile?: Profile;
|
||||
/** A language classification for the web page. */
|
||||
language?: string;
|
||||
/** Whether the web page is family friendly. */
|
||||
family_friendly: boolean;
|
||||
}
|
||||
|
||||
interface AbstractGraphInfobox extends Result {
|
||||
/** The infobox result type identifier. The value is always infobox. */
|
||||
type: 'infobox';
|
||||
/** The position on a search result page. */
|
||||
position: number;
|
||||
/** Any label associated with the entity. */
|
||||
label?: string;
|
||||
/** Category classification for the entity. */
|
||||
category?: string;
|
||||
/** A longer description for the entity. */
|
||||
long_desc?: string;
|
||||
/** The thumbnail associated with the entity. */
|
||||
thumbnail?: Thumbnail;
|
||||
/** A list of attributes about the entity. */
|
||||
attributes?: string[][];
|
||||
/** The profiles associated with the entity. */
|
||||
profiles?: Profile[] | DataProvider[];
|
||||
/** The official website pertaining to the entity. */
|
||||
website_url?: string;
|
||||
/** Any ratings given to the entity. */
|
||||
ratings?: Rating[];
|
||||
/** A list of data sources for the entity. */
|
||||
providers?: DataProvider[];
|
||||
/** A unit representing quantity relevant to the entity. */
|
||||
distance?: Unit;
|
||||
/** A list of images relevant to the entity. */
|
||||
images?: Thumbnail[];
|
||||
/** Any movie data relevant to the entity. Appears only when the result is a movie. */
|
||||
movie?: MovieData;
|
||||
}
|
||||
|
||||
interface GenericInfobox extends AbstractGraphInfobox {
|
||||
/** The infobox subtype identifier. The value is always generic. */
|
||||
subtype: 'generic';
|
||||
/** List of URLs where the entity was found. */
|
||||
found_in_urls?: string[];
|
||||
}
|
||||
|
||||
interface EntityInfobox extends AbstractGraphInfobox {
|
||||
/** The infobox subtype identifier. The value is always entity. */
|
||||
subtype: 'entity';
|
||||
}
|
||||
|
||||
interface QAInfobox extends AbstractGraphInfobox {
|
||||
/** The infobox subtype identifier. The value is always code. */
|
||||
subtype: 'code';
|
||||
/** The question and relevant answer. */
|
||||
data: QAPage;
|
||||
/** Detailed information on the page containing the question and relevant answer. */
|
||||
meta_url?: MetaUrl;
|
||||
}
|
||||
|
||||
interface InfoboxWithLocation extends AbstractGraphInfobox {
|
||||
/** The infobox subtype identifier. The value is always location. */
|
||||
subtype: 'location';
|
||||
/** Whether the entity a location. */
|
||||
is_location: boolean;
|
||||
/** The coordinates of the location. */
|
||||
coordinates?: number[];
|
||||
/** The map zoom level. */
|
||||
zoom_level: number;
|
||||
/** The location result. */
|
||||
location?: LocationResult;
|
||||
}
|
||||
|
||||
interface InfoboxPlace extends AbstractGraphInfobox {
|
||||
/** The infobox subtype identifier. The value is always place. */
|
||||
subtype: 'place';
|
||||
/** The location result. */
|
||||
location: LocationResult;
|
||||
}
|
||||
|
||||
interface GraphInfobox {
|
||||
/** The type identifier for infoboxes. The value is always graph. */
|
||||
type: 'graph';
|
||||
/** A list of infoboxes associated with the query. */
|
||||
results: GenericInfobox | QAInfobox | InfoboxPlace | InfoboxWithLocation | EntityInfobox;
|
||||
}
|
||||
|
||||
interface QAPage {
|
||||
/** The question that is being asked. */
|
||||
question: string;
|
||||
/** An answer to the question. */
|
||||
answer: Answer;
|
||||
}
|
||||
|
||||
interface Answer {
|
||||
/** The main content of the answer. */
|
||||
text: string;
|
||||
/** The name of the author of the answer. */
|
||||
author?: string;
|
||||
/** Number of upvotes on the answer. */
|
||||
upvoteCount?: number;
|
||||
/** The number of downvotes on the answer. */
|
||||
downvoteCount?: number;
|
||||
}
|
||||
|
||||
interface Thumbnail {
|
||||
/** The served URL of the picture thumbnail. */
|
||||
src: string;
|
||||
/** The original URL of the image. */
|
||||
original?: string;
|
||||
}
|
||||
|
||||
interface LocationWebResult extends Result {
|
||||
/** Aggregated information about the URL. */
|
||||
meta_url: MetaUrl;
|
||||
}
|
||||
|
||||
interface LocationResult extends Result {
|
||||
/** Location result type identifier. The value is always location_result. */
|
||||
type: 'location_result';
|
||||
/** A Temporary id associated with this result, which can be used to retrieve extra information about the location. It remains valid for 8 hours… */
|
||||
id?: string;
|
||||
/** The complete URL of the provider. */
|
||||
provider_url: string;
|
||||
/** A list of coordinates associated with the location. This is a lat long represented as a floating point. */
|
||||
coordinates?: number[];
|
||||
/** The zoom level on the map. */
|
||||
zoom_level: number;
|
||||
/** The thumbnail associated with the location. */
|
||||
thumbnail?: Thumbnail;
|
||||
/** The postal address associated with the location. */
|
||||
postal_address?: PostalAddress;
|
||||
/** The opening hours, if it is a business, associated with the location . */
|
||||
opening_hours?: OpeningHours;
|
||||
/** The contact of the business associated with the location. */
|
||||
contact?: Contact;
|
||||
/** A display string used to show the price classification for the business. */
|
||||
price_range?: string;
|
||||
/** The ratings of the business. */
|
||||
rating?: Rating;
|
||||
/** The distance of the location from the client. */
|
||||
distance?: Unit;
|
||||
/** Profiles associated with the business. */
|
||||
profiles?: DataProvider[];
|
||||
/** Aggregated reviews from various sources relevant to the business. */
|
||||
reviews?: Reviews;
|
||||
/** A bunch of pictures associated with the business. */
|
||||
pictures?: PictureResults;
|
||||
/** An action to be taken. */
|
||||
action?: Action;
|
||||
/** A list of cuisine categories served. */
|
||||
serves_cuisine?: string[];
|
||||
/** A list of categories. */
|
||||
categories?: string[];
|
||||
/** An icon category. */
|
||||
icon_category?: string;
|
||||
/** Web results related to this location. */
|
||||
results?: LocationWebResult;
|
||||
/** IANA timezone identifier. */
|
||||
timezone?: string;
|
||||
/** The utc offset of the timezone. */
|
||||
timezone_offset?: string;
|
||||
}
|
||||
|
||||
interface LocationDescription {
|
||||
/** The type of a location description. The value is always local_description. */
|
||||
type: 'local_description';
|
||||
/** A Temporary id of the location with this description. */
|
||||
id: string;
|
||||
/** AI generated description of the location with the given id. */
|
||||
description?: string;
|
||||
}
|
||||
|
||||
interface Locations {
|
||||
/** Location type identifier. The value is always locations. */
|
||||
type: 'locations';
|
||||
/** An aggregated list of location sensitive results. */
|
||||
results: LocationResult[];
|
||||
}
|
||||
|
||||
interface MixedResponse {
|
||||
/** The type representing the model mixed. The value is always mixed. */
|
||||
type: 'mixed';
|
||||
/** The ranking order for the main section of the search result page. */
|
||||
main?: ResultReference[];
|
||||
/** The ranking order for the top section of the search result page. */
|
||||
top?: ResultReference[];
|
||||
/** The ranking order for the side section of the search result page. */
|
||||
side?: ResultReference[];
|
||||
}
|
||||
|
||||
interface ResultReference {
|
||||
/** The type of the result. */
|
||||
type: string;
|
||||
/** The 0th based index where the result should be placed. */
|
||||
index?: number;
|
||||
/** Whether to put all the results from the type at specific position. */
|
||||
all: boolean;
|
||||
}
|
||||
|
||||
export interface Videos {
|
||||
/** The type representing the videos. The value is always videos. */
|
||||
type: 'videos';
|
||||
/** A list of video results. */
|
||||
results: VideoResult[];
|
||||
/** Whether the video results are changed by a Goggle. The value is false by default. */
|
||||
mutated_by_goggles?: boolean;
|
||||
}
|
||||
|
||||
export interface News {
|
||||
/** The type representing the news. The value is always news. */
|
||||
type: 'news';
|
||||
/** A list of news results. */
|
||||
results: NewsResult[];
|
||||
/** Whether the news results are changed by a Goggle. The value is false by default. */
|
||||
mutated_by_goggles?: boolean;
|
||||
}
|
||||
|
||||
interface NewsResult extends Result {
|
||||
/** The aggregated information on the URL representing a news result. */
|
||||
meta_url?: MetaUrl;
|
||||
/** The source of the news. */
|
||||
source?: string;
|
||||
/** Whether the news result is currently a breaking news. */
|
||||
breaking: boolean;
|
||||
/** Whether the news result is currently live. */
|
||||
is_live: boolean;
|
||||
/** The thumbnail associated with the news result. */
|
||||
thumbnail?: Thumbnail;
|
||||
/** A string representing the age of the news article. */
|
||||
age?: string;
|
||||
/** A list of extra alternate snippets for the news search result. */
|
||||
extra_snippets?: string[];
|
||||
}
|
||||
|
||||
interface PictureResults {
|
||||
/** A URL to view more pictures. */
|
||||
viewMoreUrl?: string;
|
||||
/** A list of thumbnail results. */
|
||||
results: Thumbnail[];
|
||||
}
|
||||
|
||||
interface Action {
|
||||
/** The type representing the action. */
|
||||
type: string;
|
||||
/** A URL representing the action to be taken. */
|
||||
url: string;
|
||||
}
|
||||
|
||||
interface PostalAddress {
|
||||
/** The type identifying a postal address. The value is always PostalAddress. */
|
||||
type: 'PostalAddress';
|
||||
/** The country associated with the location. */
|
||||
country?: string;
|
||||
/** The postal code associated with the location. */
|
||||
postalCode?: string;
|
||||
/** The street address associated with the location. */
|
||||
streetAddress?: string;
|
||||
/** The region associated with the location. This is usually a state. */
|
||||
addressRegion?: string;
|
||||
/** The address locality or subregion associated with the location. */
|
||||
addressLocality?: string;
|
||||
/** The displayed address string. */
|
||||
displayAddress: string;
|
||||
}
|
||||
|
||||
interface OpeningHours {
|
||||
/** The current day opening hours. Can have two sets of opening hours. */
|
||||
current_day?: DayOpeningHours[];
|
||||
/** The opening hours for the whole week. */
|
||||
days?: DayOpeningHours[] | [DayOpeningHours][];
|
||||
}
|
||||
|
||||
interface DayOpeningHours {
|
||||
/** A short string representing the day of the week. */
|
||||
abbr_name: string;
|
||||
/** A full string representing the day of the week. */
|
||||
full_name: string;
|
||||
/** A 24 hr clock time string for the opening time of the business on a particular day. */
|
||||
opens: string;
|
||||
/** A 24 hr clock time string for the closing time of the business on a particular day. */
|
||||
closes: string;
|
||||
}
|
||||
|
||||
interface Contact {
|
||||
/** The email address. */
|
||||
email?: string;
|
||||
/** The telephone number. */
|
||||
telephone?: string;
|
||||
}
|
||||
|
||||
interface DataProvider {
|
||||
/** The type representing the source of data. This is usually external. */
|
||||
type: 'external';
|
||||
/** The name of the data provider. This can be a domain. */
|
||||
name: string;
|
||||
/** The URL where the information is coming from. */
|
||||
url: string;
|
||||
/** The long name for the data provider. */
|
||||
long_name?: string;
|
||||
/** The served URL for the image data. */
|
||||
img?: string;
|
||||
}
|
||||
|
||||
interface Profile {
|
||||
/** The name of the profile. */
|
||||
name: string;
|
||||
/** The long name of the profile. */
|
||||
long_name: string;
|
||||
/** The original URL where the profile is available. */
|
||||
url?: string;
|
||||
/** The served image URL representing the profile. */
|
||||
img?: string;
|
||||
}
|
||||
|
||||
interface Unit {
|
||||
/** The quantity of the unit. */
|
||||
value: number;
|
||||
/** The name of the unit associated with the quantity. */
|
||||
units: string;
|
||||
}
|
||||
|
||||
interface MovieData {
|
||||
/** Name of the movie. */
|
||||
name?: string;
|
||||
/** A short plot summary for the movie. */
|
||||
description?: string;
|
||||
/** A URL serving a movie profile page. */
|
||||
url?: string;
|
||||
/** A thumbnail for a movie poster. */
|
||||
thumbnail?: Thumbnail;
|
||||
/** The release date for the movie. */
|
||||
release?: string;
|
||||
/** A list of people responsible for directing the movie. */
|
||||
directors?: Person[];
|
||||
/** A list of actors in the movie. */
|
||||
actors?: Person[];
|
||||
/** Rating provided to the movie from various sources. */
|
||||
rating?: Rating;
|
||||
/** The runtime of the movie. The format is HH:MM:SS. */
|
||||
duration?: string;
|
||||
/** List of genres in which the movie can be classified. */
|
||||
genre?: string[];
|
||||
/** The query that resulted in the movie result. */
|
||||
query?: string;
|
||||
}
|
||||
|
||||
interface Thing {
|
||||
/** A type identifying a thing. The value is always thing. */
|
||||
type: 'thing';
|
||||
/** The name of the thing. */
|
||||
name: string;
|
||||
/** A URL for the thing. */
|
||||
url?: string;
|
||||
/** Thumbnail associated with the thing. */
|
||||
thumbnail?: Thumbnail;
|
||||
}
|
||||
|
||||
interface Person extends Omit<Thing, 'type'> {
|
||||
/** A type identifying a person. The value is always person. */
|
||||
type: 'person';
|
||||
/** Email address of the person. */
|
||||
email?: string;
|
||||
}
|
||||
|
||||
interface Rating {
|
||||
/** The current value of the rating. */
|
||||
ratingValue: number;
|
||||
/** Best rating received. */
|
||||
bestRating: number;
|
||||
/** The number of reviews associated with the rating. */
|
||||
reviewCount?: number;
|
||||
/** The profile associated with the rating. */
|
||||
profile?: Profile;
|
||||
/** Whether the rating is coming from Tripadvisor. */
|
||||
is_tripadvisor: boolean;
|
||||
}
|
||||
|
||||
interface Book {
|
||||
/** The title of the book. */
|
||||
title: string;
|
||||
/** The author of the book. */
|
||||
author: Person[];
|
||||
/** The publishing date of the book. */
|
||||
date?: string;
|
||||
/** The price of the book. */
|
||||
price?: Price;
|
||||
/** The number of pages in the book. */
|
||||
pages?: number;
|
||||
/** The publisher of the book. */
|
||||
publisher?: Person;
|
||||
/** A gathered rating from different sources associated with the book. */
|
||||
rating?: Rating;
|
||||
}
|
||||
|
||||
interface Price {
|
||||
/** The price value in a given currency. */
|
||||
price: string;
|
||||
/** The current of the price value. */
|
||||
price_currency: string;
|
||||
}
|
||||
|
||||
interface Article {
|
||||
/** The author of the article. */
|
||||
author?: Person[];
|
||||
/** The date when the article was published. */
|
||||
date?: string;
|
||||
/** The name of the publisher for the article. */
|
||||
publisher?: Organization;
|
||||
/** A thumbnail associated with the article. */
|
||||
thumbnail?: Thumbnail;
|
||||
/** Whether the article is free to read or is behind a paywall. */
|
||||
isAccessibleForFree?: boolean;
|
||||
}
|
||||
|
||||
interface ContactPoint extends Omit<Thing, 'type'> {
|
||||
/** A type string identifying a contact point. The value is always contact_point. */
|
||||
type: 'contact_point';
|
||||
/** The telephone number of the entity. */
|
||||
telephone?: string;
|
||||
/** The email address of the entity. */
|
||||
email?: string;
|
||||
}
|
||||
|
||||
interface Organization extends Omit<Thing, 'type'> {
|
||||
/** A type string identifying an organization. The value is always organization. */
|
||||
type: 'organization';
|
||||
/** A list of contact points for the organization. */
|
||||
contact_points?: ContactPoint[];
|
||||
}
|
||||
|
||||
interface HowTo {
|
||||
/** The how to text. */
|
||||
text: string;
|
||||
/** A name for the how to. */
|
||||
name?: string;
|
||||
/** A URL associated with the how to. */
|
||||
url?: string;
|
||||
/** A list of image URLs associated with the how to. */
|
||||
image?: string[];
|
||||
}
|
||||
|
||||
interface Recipe {
|
||||
/** The title of the recipe. */
|
||||
title: string;
|
||||
/** The description of the recipe. */
|
||||
description: string;
|
||||
/** A thumbnail associated with the recipe. */
|
||||
thumbnail: Thumbnail;
|
||||
/** The URL of the web page where the recipe was found. */
|
||||
url: string;
|
||||
/** The domain of the web page where the recipe was found. */
|
||||
domain: string;
|
||||
/** The URL for the favicon of the web page where the recipe was found. */
|
||||
favicon: string;
|
||||
/** The total time required to cook the recipe. */
|
||||
time?: string;
|
||||
/** The preparation time for the recipe. */
|
||||
prep_time?: string;
|
||||
/** The cooking time for the recipe. */
|
||||
cook_time?: string;
|
||||
/** Ingredients required for the recipe. */
|
||||
ingredients?: string;
|
||||
/** List of instructions for the recipe. */
|
||||
instructions?: HowTo[];
|
||||
/** How many people the recipe serves. */
|
||||
servings?: number;
|
||||
/** Calorie count for the recipe. */
|
||||
calories?: number;
|
||||
/** Aggregated information on the ratings associated with the recipe. */
|
||||
rating?: Rating;
|
||||
/** The category of the recipe. */
|
||||
recipeCategory?: string;
|
||||
/** The cuisine classification for the recipe. */
|
||||
recipeCuisine?: string;
|
||||
/** Aggregated information on the cooking video associated with the recipe. */
|
||||
video?: VideoData;
|
||||
}
|
||||
|
||||
interface Product {
|
||||
/** A string representing a product type. The value is always product. */
|
||||
type: 'Product';
|
||||
/** The name of the product. */
|
||||
name: string;
|
||||
/** The category of the product. */
|
||||
category?: string;
|
||||
/** The price of the product. */
|
||||
price: string;
|
||||
/** A thumbnail associated with the product. */
|
||||
thumbnail: Thumbnail;
|
||||
/** The description of the product. */
|
||||
description?: string;
|
||||
/** A list of offers available on the product. */
|
||||
offers?: Offer[];
|
||||
/** A rating associated with the product. */
|
||||
rating?: Rating;
|
||||
}
|
||||
|
||||
interface Offer {
|
||||
/** The URL where the offer can be found. */
|
||||
url: string;
|
||||
/** The currency in which the offer is made. */
|
||||
priceCurrency: string;
|
||||
/** The price of the product currently on offer. */
|
||||
price: string;
|
||||
}
|
||||
|
||||
interface Review {
|
||||
/** A string representing review type. This is always review. */
|
||||
type: 'review';
|
||||
/** The review title for the review. */
|
||||
name: string;
|
||||
/** The thumbnail associated with the reviewer. */
|
||||
thumbnail: Thumbnail;
|
||||
/** A description of the review (the text of the review itself). */
|
||||
description: string;
|
||||
/** The ratings associated with the review. */
|
||||
rating: Rating;
|
||||
}
|
||||
|
||||
interface Reviews {
|
||||
/** A list of trip advisor reviews for the entity. */
|
||||
results: TripAdvisorReview[];
|
||||
/** A URL to a web page where more information on the result can be seen. */
|
||||
viewMoreUrl: string;
|
||||
/** Any reviews available in a foreign language. */
|
||||
reviews_in_foreign_language: boolean;
|
||||
}
|
||||
|
||||
interface TripAdvisorReview {
|
||||
/** The title of the review. */
|
||||
title: string;
|
||||
/** A description seen in the review. */
|
||||
description: string;
|
||||
/** The date when the review was published. */
|
||||
date: string;
|
||||
/** A rating given by the reviewer. */
|
||||
rating: Rating;
|
||||
/** The author of the review. */
|
||||
author: Person;
|
||||
/** A URL link to the page where the review can be found. */
|
||||
review_url: string;
|
||||
/** The language of the review. */
|
||||
language: string;
|
||||
}
|
||||
|
||||
interface CreativeWork {
|
||||
/** The name of the creative work. */
|
||||
name: string;
|
||||
/** A thumbnail associated with the creative work. */
|
||||
thumbnail: Thumbnail;
|
||||
/** A rating that is given to the creative work. */
|
||||
rating?: Rating;
|
||||
}
|
||||
|
||||
interface MusicRecording {
|
||||
/** The name of the song or album. */
|
||||
name: string;
|
||||
/** A thumbnail associated with the music. */
|
||||
thumbnail?: Thumbnail;
|
||||
/** The rating of the music. */
|
||||
rating?: Rating;
|
||||
}
|
||||
|
||||
interface Software {
|
||||
/** The name of the software product. */
|
||||
name?: string;
|
||||
/** The author of software product. */
|
||||
author?: string;
|
||||
/** The latest version of the software product. */
|
||||
version?: string;
|
||||
/** The code repository where the software product is currently available or maintained. */
|
||||
codeRepository?: string;
|
||||
/** The home page of the software product. */
|
||||
homepage?: string;
|
||||
/** The date when the software product was published. */
|
||||
datePublisher?: string;
|
||||
/** Whether the software product is available on npm. */
|
||||
is_npm?: boolean;
|
||||
/** Whether the software product is available on pypi. */
|
||||
is_pypi?: boolean;
|
||||
/** The number of stars on the repository. */
|
||||
stars?: number;
|
||||
/** The numbers of forks of the repository. */
|
||||
forks?: number;
|
||||
/** The programming language spread on the software product. */
|
||||
ProgrammingLanguage?: string;
|
||||
}
|
||||
|
||||
interface DeepResult {
|
||||
/** A list of news results associated with the result. */
|
||||
news?: NewsResult[];
|
||||
/** A list of buttoned results associated with the result. */
|
||||
buttons?: ButtonResult[];
|
||||
/** Videos associated with the result. */
|
||||
videos?: VideoResult[];
|
||||
/** Images associated with the result. */
|
||||
images?: Image[];
|
||||
}
|
||||
|
||||
interface VideoResult extends Result {
|
||||
/** The type identifying the video result. The value is always video_result. */
|
||||
type: 'video_result';
|
||||
/** Meta data for the video. */
|
||||
video: VideoData;
|
||||
/** Aggregated information on the URL. */
|
||||
meta_url?: MetaUrl;
|
||||
/** The thumbnail of the video. */
|
||||
thumbnail?: Thumbnail;
|
||||
/** A string representing the age of the video. */
|
||||
age?: string;
|
||||
}
|
||||
|
||||
interface VideoData {
|
||||
/** A time string representing the duration of the video. The format can be HH:MM:SS or MM:SS. */
|
||||
duration?: string;
|
||||
/** The number of views of the video. */
|
||||
views?: string;
|
||||
/** The creator of the video. */
|
||||
creator?: string;
|
||||
/** The publisher of the video. */
|
||||
publisher?: string;
|
||||
/** A thumbnail associated with the video. */
|
||||
thumbnail?: Thumbnail;
|
||||
/** A list of tags associated with the video. */
|
||||
tags?: string[];
|
||||
/** Author of the video. */
|
||||
author?: Profile;
|
||||
/** Whether the video requires a subscription to watch. */
|
||||
requires_subscription?: boolean;
|
||||
}
|
||||
|
||||
interface ButtonResult {
|
||||
/** A type identifying button result. The value is always button_result. */
|
||||
type: 'button_result';
|
||||
/** The title of the result. */
|
||||
title: string;
|
||||
/** The URL for the button result. */
|
||||
url: string;
|
||||
}
|
||||
|
||||
interface Image {
|
||||
/** The thumbnail associated with the image. */
|
||||
thumbnail: Thumbnail;
|
||||
/** The URL of the image. */
|
||||
url?: string;
|
||||
/** Metadata on the image. */
|
||||
properties?: ImageProperties;
|
||||
}
|
||||
|
||||
interface Language {
|
||||
/** The main language seen in the string. */
|
||||
main: string;
|
||||
}
|
||||
|
||||
interface ImageProperties {
|
||||
/** The original image URL. */
|
||||
url: string;
|
||||
/** The URL for a better quality resized image. */
|
||||
resized: string;
|
||||
/** The placeholder image URL. */
|
||||
placeholder: string;
|
||||
/** The image height. */
|
||||
height?: number;
|
||||
/** The image width. */
|
||||
width?: number;
|
||||
/** The image format. */
|
||||
format?: string;
|
||||
/** The image size. */
|
||||
content_size?: string;
|
||||
}
|
||||
|
||||
interface Summarizer {
|
||||
/** The value is always summarizer. */
|
||||
type: 'summarizer';
|
||||
/** The key for the summarizer API. */
|
||||
key: string;
|
||||
}
|
||||
|
||||
interface RichCallbackInfo {
|
||||
/** The value is always rich. */
|
||||
type: 'rich';
|
||||
/** The hint for the rich result. */
|
||||
hint?: RichCallbackHint;
|
||||
}
|
||||
|
||||
interface RichCallbackHint {
|
||||
/** The name of the vertical of the rich result. */
|
||||
vertical: string;
|
||||
/** The callback key for the rich result. */
|
||||
callback_key: string;
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
export interface WebResponse {
|
||||
web?: {
|
||||
results?: Array<{
|
||||
title: string;
|
||||
description: string;
|
||||
url: string;
|
||||
language?: string;
|
||||
published?: string;
|
||||
rank?: number;
|
||||
}>;
|
||||
};
|
||||
locations?: {
|
||||
results?: Array<{
|
||||
id: string; // Required by API
|
||||
title?: string;
|
||||
}>;
|
||||
};
|
||||
}
|
||||
|
||||
export interface BraveLocation {
|
||||
id: string;
|
||||
name: string;
|
||||
address: {
|
||||
streetAddress?: string;
|
||||
addressLocality?: string;
|
||||
addressRegion?: string;
|
||||
postalCode?: string;
|
||||
};
|
||||
coordinates?: {
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
};
|
||||
phone?: string;
|
||||
rating?: {
|
||||
ratingValue?: number;
|
||||
ratingCount?: number;
|
||||
};
|
||||
openingHours?: string[];
|
||||
priceRange?: string;
|
||||
}
|
||||
|
||||
export interface BravePoiResponse {
|
||||
results: BraveLocation[];
|
||||
}
|
||||
|
||||
export interface BraveDescription {
|
||||
descriptions: { [id: string]: string };
|
||||
}
|
||||
+31
-21
@@ -1,21 +1,31 @@
|
||||
import { RATE_LIMIT } from "./constants.js";
|
||||
|
||||
let requestCount = {
|
||||
second: 0,
|
||||
month: 0,
|
||||
lastReset: Date.now()
|
||||
};
|
||||
|
||||
export function checkRateLimit() {
|
||||
const now = Date.now();
|
||||
if (now - requestCount.lastReset > 1000) {
|
||||
requestCount.second = 0;
|
||||
requestCount.lastReset = now;
|
||||
}
|
||||
if (requestCount.second >= RATE_LIMIT.perSecond ||
|
||||
requestCount.month >= RATE_LIMIT.perMonth) {
|
||||
throw new Error('Rate limit exceeded');
|
||||
}
|
||||
requestCount.second++;
|
||||
requestCount.month++;
|
||||
}
|
||||
import type { LoggingLevel } from '@modelcontextprotocol/sdk/types.js';
|
||||
import { RATE_LIMIT } from './constants.js';
|
||||
import { server } from './server.js';
|
||||
|
||||
let requestCount = {
|
||||
second: 0,
|
||||
month: 0,
|
||||
lastReset: Date.now(),
|
||||
};
|
||||
|
||||
export async function log(level: LoggingLevel, message: string) {
|
||||
const time = new Date().toISOString();
|
||||
await server.server.sendLoggingMessage({ level, data: { message, time } });
|
||||
}
|
||||
|
||||
export function checkRateLimit() {
|
||||
const now = Date.now();
|
||||
if (now - requestCount.lastReset > 1000) {
|
||||
requestCount.second = 0;
|
||||
requestCount.lastReset = now;
|
||||
}
|
||||
if (requestCount.second >= RATE_LIMIT.perSecond || requestCount.month >= RATE_LIMIT.perMonth) {
|
||||
throw new Error('Rate limit exceeded');
|
||||
}
|
||||
requestCount.second++;
|
||||
requestCount.month++;
|
||||
}
|
||||
|
||||
export function stringify(data: any, pretty = false) {
|
||||
return pretty ? JSON.stringify(data, null, 2) : JSON.stringify(data);
|
||||
}
|
||||
Reference in new issue
Block a user