improve response structure of image tool (#52)

Tool now more closely resembles the documented response shape of the image API endpoint. This tool also no longer preemptively loads base64-encoded image data. The images tool now uses a structured content response. Following the suggestion in https://modelcontextprotocol.io/specification/2025-06-18/server/tools#output-schema, we also provide an Output Schema, enabling clients to validate the response. As a result of this work, the Images tool requires a slightly different registration approach. For this reason, registration can now be handled via a local "register" method in each tool module. When tools were registered externally in a for-loop, the type system was unable to infer the shape of each tool due to the overloaded union (resulting from only the Image tool having an OutputSchema export).
This commit is contained in:
Sampson authored and GitHub committed 2025-09-06 10:35:08 -05:00
1 parent 398e88ffb8
commit 4fb81fb605
12 files changed
+234 -42

No files matched your search

+1 -1
View File
@@ -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';
+1 -1
View File
@@ -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;
+54 -37
View File
@@ -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<typeof SimplifiedImageResultSchema> | 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,
};
File renamed without changes.
+23
View File
@@ -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;
+69
View File
@@ -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.'),
});
+9 -1
View File
@@ -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 {
+16 -1
View File
@@ -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,
};
+15
View File
@@ -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,
};
+16 -1
View File
@@ -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,
};
+15
View File
@@ -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,
};
+15
View File
@@ -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,
};