Refactor configuration and API; added endpoints for image, video, and news.

This commit is contained in:
Sampson committed 2025-07-02 17:04:22 -05:00
1 parent 7789f05087
commit 8f942b9eee
29 files changed
+2867 -490

No files matched your search

+12 -16
View File
@@ -1,16 +1,12 @@
import { z } from "zod";
export const params = z.object({
query: z.string()
.describe("Local search query (e.g. 'pizza near Central Park')"),
count: z.number()
.int()
.min(1)
.max(20)
.default(5)
.describe("Number of results (1-20, default 5)")
});
export type QueryParams = z.infer<typeof params>;
export default params;
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>;
+167 -129
View File
@@ -1,129 +1,167 @@
import { type WebResponse as BraveWeb, type BravePoiResponse, type BraveDescription } from "../../types/index.js";
import { execute as performWebSearch } from "../web/index.js";
import { BRAVE_API_KEY } from "../../constants.js";
import { checkRateLimit } from "../../utils.js";
import type { ToolAnnotations } from "@modelcontextprotocol/sdk/types.js";
import params, { type QueryParams } from "./QueryParams.js";
export const name = "brave_local_search";
export const annotations: ToolAnnotations = {
title: "Brave Local Search",
openWorldHint: true,
};
export const description = "Searches for local businesses and places using Brave's Local Search API. Best for queries related to physical locations, businesses, restaurants, services, etc. Returns detailed information including:\n- Business names and addresses\n- Ratings and review counts\n- Phone numbers and opening hours\nUse this when the query implies 'near me' or mentions specific locations. Automatically falls back to web search if no local results are found.";
// TODO (Sampson): Add output schema
// export const outputSchema = z.object({});
export async function execute({ query, count }: QueryParams) {
checkRateLimit();
// Initial search to get location IDs
const webUrl = new URL('https://api.search.brave.com/res/v1/web/search');
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';
}
export default {
name,
description,
annotations,
inputSchema: params.shape,
execute
};
import type {
LocationResult,
LocationDescription,
OpeningHours,
DayOpeningHours,
} from './types.js';
import webParams, { type QueryParams as WebQueryParams } from '../web/QueryParams.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,
};
+259
View File
@@ -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;
}