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();
    }
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden and does well by explicitly stating this is a 'write operation' and disclosing the critical authorization requirement ('REQUIRES explicit user authorization via the userAuthorized parameter'). It doesn't mention rate limits, error handling, or response format, but covers the essential safety and permission aspects.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two sentences with zero waste: the first covers purpose and capabilities, the second delivers the critical authorization warning. Every word earns its place, and the IMPORTANT warning is appropriately front-loaded.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a write operation with no annotations and no output schema, the description does well by covering the essential behavioral aspects (write operation, authorization requirement) and purpose. It could benefit from mentioning response format or error handling, but given the good parameter documentation in the schema, it's mostly complete.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 83% schema description coverage, the schema already documents most parameters well. The description adds value by emphasizing the authorization requirement for userAuthorized and mentioning format/quality/metadata capabilities, but doesn't provide additional semantic context beyond what's in the parameter descriptions.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific action ('Upload media'), target resource ('Strapi's media library'), source ('from a URL'), and key capabilities ('format conversion, quality control, and metadata options'). It distinguishes this as a media upload tool among siblings that include get/list operations.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description explicitly states this is for uploading media from URLs with format/quality/metadata options, providing clear context for when to use it. However, it doesn't mention when NOT to use it or name specific alternatives among the sibling tools (like strapi_rest for other operations).

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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