diff --git a/src/BraveAPI/types.ts b/src/BraveAPI/types.ts index ddd4188..81e8153 100644 --- a/src/BraveAPI/types.ts +++ b/src/BraveAPI/types.ts @@ -1,5 +1,5 @@ import type { QueryParams as WebQueryParams } from '../tools/web/params.js'; -import type { QueryParams as ImageQueryParams } from '../tools/images/params.js'; +import type { QueryParams as ImageQueryParams } from '../tools/images/schemas/input.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'; diff --git a/src/server.ts b/src/server.ts index 54dc29d..28ae8e2 100644 --- a/src/server.ts +++ b/src/server.ts @@ -39,7 +39,7 @@ export default function createMcpServer(options?: CreateMcpServerOptions): McpSe } for (const tool of Object.values(tools)) { - mcpServer.tool(tool.name, tool.description, tool.inputSchema, tool.annotations, tool.execute); + tool.register(mcpServer); } return mcpServer; diff --git a/src/tools/images/index.ts b/src/tools/images/index.ts index cb5d517..31c4e72 100644 --- a/src/tools/images/index.ts +++ b/src/tools/images/index.ts @@ -1,11 +1,10 @@ -import type { - ImageContent, - TextContent, - ToolAnnotations, -} from '@modelcontextprotocol/sdk/types.js'; -import params, { type QueryParams } from './params.js'; +import type { TextContent, ToolAnnotations } from '@modelcontextprotocol/sdk/types.js'; +import params, { type QueryParams } from './schemas/input.js'; import API from '../../BraveAPI/index.js'; -import { stringify } from '../../utils.js'; +import type { ImageResult } from './types.js'; +import OutputSchema, { SimplifiedImageResultSchema } from './schemas/output.js'; +import { z } from 'zod'; +import { type McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; export const name = 'brave_image_search'; @@ -15,45 +14,61 @@ export const annotations: ToolAnnotations = { }; 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: ![Image Description](image_url). + Performs an image search using the Brave Search API. Helpful for when you need pictures of people, places, things, graphic design ideas, art inspiration, and more. When relaying results in a markdown environment, it may be helpful to include images in the results (e.g., ![image.title](image.properties.url)). `; export const execute = async (params: QueryParams) => { - const content: (TextContent | ImageContent)[] = []; const response = await API.issueRequest<'images'>('images', params); + const items = response.results.map(simplifySchemaForLLM).filter((o) => o !== null); - for (const { url: page_url, title, thumbnail, properties } of response.results) { - // Skip results without an image - if (!thumbnail?.src) continue; + const structuredContent = OutputSchema.safeParse({ + type: 'object', + items, + count: items.length, + might_be_offensive: response.extra.might_be_offensive, + }); - // Prefer property URL as it is the shortest-possible URL - const image_url = properties?.url ?? thumbnail.src; - const fetched_image = await fetchImage(image_url); + const payload = structuredContent.success + ? structuredContent.data + : structuredContent.error.flatten(); - 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 }; + return { + content: [{ type: 'text', text: JSON.stringify(payload) } as TextContent], + isError: !structuredContent.success, + structuredContent: payload, + }; }; -async function fetchImage(url: string): Promise<{ mimeType: string; data: string } | null> { - 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) { - return null; - } +export const register = (mcpServer: McpServer) => { + mcpServer.registerTool( + name, + { + title: name, + description: description, + inputSchema: params.shape, + outputSchema: OutputSchema.shape, + annotations: annotations, + }, + execute + ); +}; + +function simplifySchemaForLLM( + result: ImageResult +): z.infer | null { + const parsed = SimplifiedImageResultSchema.safeParse({ + title: result.title, + url: result.url, + page_fetched: result.page_fetched, + confidence: result.confidence, + properties: { + url: result.properties?.url, + width: result.properties?.width, + height: result.properties?.height, + }, + }); + + return parsed.success ? parsed.data : null; } export default { @@ -61,5 +76,7 @@ export default { description, annotations, inputSchema: params.shape, + outputSchema: OutputSchema.shape, execute, + register, }; diff --git a/src/tools/images/params.ts b/src/tools/images/schemas/input.ts similarity index 100% rename from src/tools/images/params.ts rename to src/tools/images/schemas/input.ts diff --git a/src/tools/images/schemas/output.ts b/src/tools/images/schemas/output.ts new file mode 100644 index 0000000..86e9303 --- /dev/null +++ b/src/tools/images/schemas/output.ts @@ -0,0 +1,23 @@ +import { z } from 'zod'; +import { ConfidenceSchema, ExtraSchema } from './response.js'; + +export const SimplifiedImageResultSchema = z.object({ + title: z.string(), + url: z.string().url(), + page_fetched: z.string().datetime(), + confidence: ConfidenceSchema, + properties: z.object({ + url: z.string().url(), + width: z.number().int().positive(), + height: z.number().int().positive(), + }), +}); + +const OutputSchema = z.object({ + type: z.literal('object'), + items: z.array(SimplifiedImageResultSchema), + count: z.number().int().nonnegative(), + might_be_offensive: ExtraSchema.shape.might_be_offensive, +}); + +export default OutputSchema; diff --git a/src/tools/images/schemas/response.ts b/src/tools/images/schemas/response.ts new file mode 100644 index 0000000..36eeaa1 --- /dev/null +++ b/src/tools/images/schemas/response.ts @@ -0,0 +1,69 @@ +import { z } from 'zod'; + +/** + * https://api-dashboard.search.brave.com/app/documentation/image-search/responses + */ + +const QuerySchema = z.object({ + original: z.string().describe('The original query string.'), + altered: z.string().optional().describe('The altered query string.'), + spellcheck_off: z.boolean().optional().describe('Whether spellcheck was disabled.'), + show_strict_warning: z + .boolean() + .optional() + .describe('When true, some results were blocked by safesearch.'), +}); + +const ThumbnailSchema = z.object({ + src: z.string().url().optional().describe('The URL of the thumbnail.'), + width: z.number().int().positive().optional().describe('The width of the thumbnail.'), + height: z.number().int().positive().optional().describe('The height of the thumbnail.'), +}); + +const PropertiesSchema = z.object({ + url: z.string().url().optional().describe('The URL of the image.'), + placeholder: z.string().url().optional().describe('The lower resolution placeholder image.'), + width: z.number().int().positive().optional().describe('The width of the image.'), + height: z.number().int().positive().optional().describe('The height of the image.'), +}); + +const MetaUrlSchema = z.object({ + scheme: z.enum(['https', 'http']).optional().describe('The scheme of the URL.'), + netloc: z.string().optional().describe('The network location of the URL.'), + hostname: z.string().optional().describe('The lowercased hostname of the URL.'), + favicon: z.string().url().optional().describe('The URL of the favicon of the URL.'), + path: z.string().optional().describe('The path of the URL (useful as a display string).'), +}); + +export const ConfidenceSchema = z + .enum(['low', 'medium', 'high']) + .describe('The confidence level of the result.'); + +const ImageResultSchema = z.object({ + type: z.literal('image_result').describe('The type of result.'), + title: z.string().optional().describe('The title of the image.'), + url: z.string().url().optional().describe('The URL of the image.'), + source: z.string().url().optional().describe('The source URL of the image.'), + page_fetched: z + .string() + .datetime() + .optional() + .describe('The date and time the page was fetched.'), + thumbnail: ThumbnailSchema.optional().describe('The thumbnail of the image.'), + properties: PropertiesSchema.optional().describe('The metadata for the image.'), + meta_url: MetaUrlSchema.optional().describe( + 'Information about the URL associated with the image.' + ), + confidence: ConfidenceSchema.optional(), +}); + +export const ExtraSchema = z.object({ + might_be_offensive: z.boolean().describe('Whether the image might be offensive.'), +}); + +export const ImageSearchApiResponseSchema = z.object({ + type: z.literal('images').describe('The type of API response.'), + query: QuerySchema.describe('The query used to generate the results.'), + results: z.array(ImageResultSchema).describe('The results of the image search.'), + extra: ExtraSchema.describe('Extra information about the search.'), +}); diff --git a/src/tools/images/types.ts b/src/tools/images/types.ts index 2ebe3c3..3f0c99a 100644 --- a/src/tools/images/types.ts +++ b/src/tools/images/types.ts @@ -44,13 +44,21 @@ export interface ImageResult { interface Thumbnail { /** The served URL of the image. */ src?: string; + /** The width of the thumbnail. */ + width?: number; + /** The height of the thumbnail. */ + height?: number; } -interface Properties { +export interface Properties { /** The image URL. */ url?: string; /** The lower resolution placeholder image URL. */ placeholder?: string; + /** The width of the image. */ + width?: number; + /** The height of the image. */ + height?: number; } interface MetaUrl { diff --git a/src/tools/local/index.ts b/src/tools/local/index.ts index 5f8339a..ee81f2b 100644 --- a/src/tools/local/index.ts +++ b/src/tools/local/index.ts @@ -9,7 +9,8 @@ import type { CallToolResult, ToolAnnotations } from '@modelcontextprotocol/sdk/ import API from '../../BraveAPI/index.js'; import { formatWebResults } from '../web/index.js'; import { stringify } from '../../utils.js'; -import { WebSearchApiResponse } from '../web/types.js'; +import { type WebSearchApiResponse } from '../web/types.js'; +import { type McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; export const name = 'brave_local_search'; @@ -72,6 +73,19 @@ export const execute = async (params: WebQueryParams) => { }; }; +export const register = (mcpServer: McpServer) => { + mcpServer.registerTool( + name, + { + title: name, + description: description, + inputSchema: webParams.shape, + annotations: annotations, + }, + execute + ); +}; + const buildFallbackWebResponse = (web_fallback: WebSearchApiResponse['web']): CallToolResult => { if (!web_fallback || web_fallback.results.length === 0) throw new Error('No web results found'); @@ -164,4 +178,5 @@ export default { annotations, inputSchema: webParams.shape, execute, + register, }; diff --git a/src/tools/news/index.ts b/src/tools/news/index.ts index 9eed780..73aa793 100644 --- a/src/tools/news/index.ts +++ b/src/tools/news/index.ts @@ -2,6 +2,7 @@ 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'; +import { type McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; export const name = 'brave_news_search'; @@ -51,10 +52,24 @@ export const execute = async (params: QueryParams) => { }; }; +export const register = (mcpServer: McpServer) => { + mcpServer.registerTool( + name, + { + title: name, + description: description, + inputSchema: params.shape, + annotations: annotations, + }, + execute + ); +}; + export default { name, description, annotations, inputSchema: params.shape, execute, + register, }; diff --git a/src/tools/summarizer/index.ts b/src/tools/summarizer/index.ts index f082c0a..412dd56 100644 --- a/src/tools/summarizer/index.ts +++ b/src/tools/summarizer/index.ts @@ -1,7 +1,8 @@ import type { CallToolResult, ToolAnnotations } from '@modelcontextprotocol/sdk/types.js'; import { summarizerQueryParams, type SummarizerQueryParams } from './params.js'; import API from '../../BraveAPI/index.js'; -import { SummarizerSearchApiResponse } from './types.js'; +import { type SummarizerSearchApiResponse } from './types.js'; +import { type McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; export const name = 'brave_summarizer'; @@ -66,6 +67,19 @@ export const execute = async (params: SummarizerQueryParams) => { return response; }; +export const register = (mcpServer: McpServer) => { + mcpServer.registerTool( + name, + { + title: name, + description: description, + inputSchema: summarizerQueryParams.shape, + annotations: annotations, + }, + execute + ); +}; + const pollForSummary = async ( params: SummarizerQueryParams, pollInterval: number = 50, @@ -99,4 +113,5 @@ export default { annotations, inputSchema: summarizerQueryParams.shape, execute, + register, }; diff --git a/src/tools/videos/index.ts b/src/tools/videos/index.ts index 7fa66d3..b356dba 100644 --- a/src/tools/videos/index.ts +++ b/src/tools/videos/index.ts @@ -2,6 +2,7 @@ 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'; +import { type McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; export const name = 'brave_video_search'; @@ -36,10 +37,24 @@ export const execute = async (params: QueryParams) => { }; }; +export const register = (mcpServer: McpServer) => { + mcpServer.registerTool( + name, + { + title: name, + description: description, + inputSchema: params.shape, + annotations: annotations, + }, + execute + ); +}; + export default { name, description, annotations, inputSchema: params.shape, execute, + register, }; diff --git a/src/tools/web/index.ts b/src/tools/web/index.ts index 11c457e..c2b6aaa 100644 --- a/src/tools/web/index.ts +++ b/src/tools/web/index.ts @@ -14,6 +14,7 @@ import type { FormattedWebResults, } from './types.js'; import { stringify } from '../../utils.js'; +import { type McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; export const name = 'brave_web_search'; @@ -119,6 +120,19 @@ export const formatWebResults = (web: Search): FormattedWebResults => { })); }; +export const register = (mcpServer: McpServer) => { + mcpServer.registerTool( + name, + { + title: name, + description: description, + inputSchema: params.shape, + annotations: annotations, + }, + execute + ); +}; + const formatFAQResults = (faq: FAQ): FormattedFAQResults => { return (faq.results || []).map(({ question, answer, title, url }) => ({ question, @@ -174,4 +188,5 @@ export default { annotations, inputSchema: params.shape, execute, + register, };