Skip to main content
Glama

strapi_upload_media

Upload media files to Strapi's media library from URLs with format conversion, quality adjustment, and metadata management. Requires explicit user authorization for write operations.

Instructions

Upload media to Strapi's media library from a URL with format conversion, quality control, and metadata options. IMPORTANT: This is a write operation that REQUIRES explicit user authorization via the userAuthorized parameter.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
serverNoThe name of the server to connect to
urlNoURL of the image to upload
formatNoTarget format for the image. Use 'original' to keep the source format.original
qualityNoImage quality (1-100). Only applies when converting formats.
metadataNo
userAuthorizedNoREQUIRED for media upload operations. Client MUST obtain explicit user authorization before setting this to true.

Implementation Reference

  • Main execution handler for the 'strapi_upload_media' tool within the CallToolRequestSchema handler. Validates input, downloads image from URL, processes it (format/quality), uploads to Strapi /api/upload endpoint, and returns formatted response with usage instructions.
    // Validate input using Zod (includes authorization check) const validatedArgs = validateToolInput("strapi_upload_media", args, requestId); const { server, url, format, quality, metadata, userAuthorized } = validatedArgs; logger.startRequest(requestId, name, server); // Extract filename from URL const fileName = url.split('/').pop() || 'image'; // Download the image const imageBuffer = await downloadImage(url); // Process the image if format conversion is requested const processedBuffer = await processImage(imageBuffer, format, quality); // Upload to Strapi with metadata (with authorization check) const data = await uploadMedia(server, processedBuffer, fileName, format, metadata, userAuthorized, requestId); // Format response with helpful usage information const response = { success: true, data: data, image_info: { format: format === 'original' ? 'original (unchanged)' : format, quality: format === 'original' ? 'original (unchanged)' : quality, filename: data[0].name, size: data[0].size, mime: data[0].mime }, usage_guide: { file_id: data[0].id, url: data[0].url, how_to_use: { rest_api: "Use the file ID in your content type's media field", graphql: "Use the file ID in your GraphQL mutations", examples: { rest: "PUT /api/content-type/1 with body: { data: { image: " + data[0].id + " } }", graphql: "mutation { updateContentType(id: 1, data: { image: " + data[0].id + " }) { data { id } } }" } } } }; result = { content: [ { type: "text", text: JSON.stringify(response, null, 2) } ] }; } else {
  • Zod input validation schema for the strapi_upload_media tool, defining parameters like server, url, format, quality, metadata, and requiring userAuthorized for security.
    const UploadMediaSchema = z.object({ server: z.string().min(1, "Server name is required and cannot be empty"), url: z.string().url("Must be a valid URL"), format: z.enum(["jpeg", "png", "webp", "original"], { errorMap: () => ({ message: "Format must be one of: jpeg, png, webp, original" }) }).optional().default("original"), quality: z.union([ z.number().int().min(1, "Quality must be between 1 and 100").max(100, "Quality must be between 1 and 100"), z.string().transform((str, ctx) => { const num = parseInt(str); if (isNaN(num) || num < 1 || num > 100) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Quality must be between 1 and 100" }); return z.NEVER; } return num; }) ]).optional().default(80), metadata: MediaMetadataSchema.optional(), userAuthorized: z.union([ z.boolean(), z.string().transform((str, ctx) => { if (str === "true") return true; if (str === "false") return false; ctx.addIssue({ code: z.ZodIssueCode.custom, message: "userAuthorized must be boolean true/false or string 'true'/'false'" }); return z.NEVER; }) ]).optional().default(false) }).strict().refine( (data) => { // Media upload requires explicit user authorization if (!data.userAuthorized) { return false; } return true; }, { message: "Media upload operations require explicit user authorization (userAuthorized: true)", path: ["userAuthorized"] } );
  • src/index.ts:1347-1400 (registration)
    Tool registration in the ListToolsRequestSchema handler, defining the name, description, and JSON input schema for strapi_upload_media.
    name: "strapi_upload_media", description: "Upload media to Strapi's media library from a URL with format conversion, quality control, and metadata options. IMPORTANT: This is a write operation that REQUIRES explicit user authorization via the userAuthorized parameter.", inputSchema: { ...zodToJsonSchema(ToolSchemas.strapi_upload_media), properties: { ...zodToJsonSchema(ToolSchemas.strapi_upload_media).properties, server: { ...zodToJsonSchema(ToolSchemas.strapi_upload_media).properties.server, description: "The name of the server to connect to" }, url: { ...zodToJsonSchema(ToolSchemas.strapi_upload_media).properties.url, description: "URL of the image to upload" }, format: { ...zodToJsonSchema(ToolSchemas.strapi_upload_media).properties.format, description: "Target format for the image. Use 'original' to keep the source format.", default: "original" }, quality: { ...zodToJsonSchema(ToolSchemas.strapi_upload_media).properties.quality, description: "Image quality (1-100). Only applies when converting formats.", default: 80 }, metadata: { type: "object", properties: { name: { type: "string", description: "Name of the file" }, caption: { type: "string", description: "Caption for the image" }, alternativeText: { type: "string", description: "Alternative text for accessibility" }, description: { type: "string", description: "Detailed description of the image" } }, additionalProperties: false }, userAuthorized: { ...zodToJsonSchema(ToolSchemas.strapi_upload_media).properties.userAuthorized, description: "REQUIRED for media upload operations. Client MUST obtain explicit user authorization before setting this to true.", default: false } } } }
  • Key helper function that handles the actual FormData-based POST upload to Strapi's /api/upload endpoint, including authorization enforcement, filename adjustment, metadata attachment, logging, and error handling.
    async function uploadMedia(serverName: string, imageBuffer: Buffer, fileName: string, format: string, metadata?: Record<string, any>, userAuthorized: boolean = false, requestId?: string): Promise<any> { // Check for explicit user authorization for this upload operation if (!userAuthorized) { throw new McpError( ErrorCode.InvalidParams, `AUTHORIZATION REQUIRED: Media upload operations require explicit user authorization.\n\n` + `IMPORTANT: The client MUST:\n` + `1. Ask the user for explicit permission before uploading this media\n` + `2. Show the user what media will be uploaded\n` + `3. Receive clear confirmation from the user\n` + `4. Set userAuthorized=true when making the request\n\n` + `This is a security measure to prevent unauthorized uploads.` ); } const serverConfig = getServerConfig(serverName); const formData = new FormData(); // Update filename extension if format is changed if (format !== 'original') { fileName = fileName.replace(/\.[^/.]+$/, '') + '.' + format; } // Add the file formData.append('files', imageBuffer, { filename: fileName, contentType: `image/${format === 'original' ? 'jpeg' : format}` // Default to jpeg for original }); // Add metadata if provided if (metadata) { formData.append('fileInfo', JSON.stringify(metadata)); } const url = `${serverConfig.API_URL}/api/upload`; const startTime = Date.now(); logger.debug(`Uploading media to Strapi`, { requestId, server: serverName, fileName, format, hasMetadata: !!metadata, bufferSize: imageBuffer.length, userAuthorized }); const response = await fetch(url, { method: 'POST', headers: { 'Authorization': `Bearer ${serverConfig.JWT}`, ...formData.getHeaders() }, body: formData }); const duration = Date.now() - startTime; logger.logApiCall( requestId || 'unknown', 'POST', '/api/upload', duration, response.status, serverName ); return handleStrapiError(response, 'Media upload', requestId); }
  • Helper function using Sharp library to process image buffer: convert format (jpeg/png/webp) and apply quality settings, or pass original.
    async function processImage(buffer: Buffer, format: string, quality: number): Promise<Buffer> { let sharpInstance = sharp(buffer); if (format !== 'original') { switch (format) { case 'jpeg': sharpInstance = sharpInstance.jpeg({ quality }); break; case 'png': // PNG quality is 0-100 for zlib compression level sharpInstance = sharpInstance.png({ compressionLevel: Math.floor((100 - quality) / 100 * 9) }); break; case 'webp': sharpInstance = sharpInstance.webp({ quality }); break; } } return sharpInstance.toBuffer(); }

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/misterboe/strapi-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server