@bratcliffe909/mcp-server-segmind
Version:
Model Context Protocol server for Segmind API - Generate images and videos using AI models
104 lines • 4.03 kB
JavaScript
import * as fs from 'fs/promises';
import * as path from 'path';
import { z } from 'zod';
import { logger } from '../utils/logger.js';
import { BaseTool } from './base.js';
const ReadLocalImageSchema = z.object({
file_path: z.string().describe('Absolute path to the image file'),
return_format: z.enum(['base64', 'data_uri']).default('base64').describe('Format to return: base64 string or data URI'),
});
export class ReadLocalImageTool extends BaseTool {
name = 'read_local_image';
description = 'Read a local image file and convert it to base64 for use with other tools';
async execute(params) {
try {
const validated = ReadLocalImageSchema.parse(params);
if (!path.isAbsolute(validated.file_path)) {
return {
content: [{
type: 'text',
text: `Error: File path must be absolute. Got: ${validated.file_path}`,
}],
isError: true,
};
}
try {
await fs.access(validated.file_path);
}
catch {
return {
content: [{
type: 'text',
text: `Error: File not found: ${validated.file_path}`,
}],
isError: true,
};
}
const ext = path.extname(validated.file_path).toLowerCase();
const mimeTypes = {
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.png': 'image/png',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.bmp': 'image/bmp',
};
const mimeType = mimeTypes[ext];
if (!mimeType) {
return {
content: [{
type: 'text',
text: `Error: Unsupported image format: ${ext}. Supported: jpg, jpeg, png, gif, webp, bmp`,
}],
isError: true,
};
}
const imageBuffer = await fs.readFile(validated.file_path);
const base64String = imageBuffer.toString('base64');
const fileSizeMB = imageBuffer.length / (1024 * 1024);
if (fileSizeMB > 10) {
logger.warn(`Large image file: ${fileSizeMB.toFixed(2)}MB. Consider resizing.`);
}
let result;
if (validated.return_format === 'data_uri') {
result = `data:${mimeType};base64,${base64String}`;
}
else {
result = base64String;
}
const content = [
{
type: 'text',
text: `Successfully read image: ${path.basename(validated.file_path)}`,
},
{
type: 'text',
text: `Format: ${ext.substring(1).toUpperCase()}, Size: ${fileSizeMB.toFixed(2)}MB`,
},
{
type: 'text',
text: `\nBase64 string (${validated.return_format}):`,
},
{
type: 'text',
text: result,
},
{
type: 'text',
text: `\nUsage example with transform_image:`,
},
{
type: 'text',
text: `transform_image({ image: "<copy-base64-above>", prompt: "your transformation", strength: 0.75 })`,
},
];
return { content };
}
catch (error) {
logger.error('Failed to read local image', { error });
return this.createErrorResponse(error);
}
}
}
export const readLocalImageTool = new ReadLocalImageTool();
//# sourceMappingURL=read-local-image.js.map