Skip to main content
Glama
stefanskiasan

Together AI Image MCP Server

generate_image

Create custom images from text descriptions using AI models, with options to adjust dimensions, format, and output location for integration into projects.

Instructions

Generate an image using Together AI

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
promptYesText description of the image to generate
modelNoModel to use for generationblack-forest-labs/FLUX.1.1-pro
widthNoImage width in pixels
heightNoImage height in pixels
stepsNoNumber of inference steps
nNoNumber of images to generate
outputDirNoFull absolute path where images will be saved (e.g., /Users/username/Projects/myapp/src/assets)
formatNoOutput format for the generated imagespng

Implementation Reference

  • The CallToolRequestSchema handler implementing the generate_image tool: validates args, calls Together AI API to generate images, processes/resizes with sharp, saves to specified directory, returns file paths.
    this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
      if (request.params.name !== 'generate_image') {
        throw new McpError(
          ErrorCode.MethodNotFound,
          `Unknown tool: ${request.params.name}`
        );
      }
    
      if (!request.params.arguments || !isValidGenerateImageArgs(request.params.arguments)) {
        throw new McpError(
          ErrorCode.InvalidParams,
          'Invalid generate_image arguments'
        );
      }
    
      try {
        const args = request.params.arguments as GenerateImageArgs;
        // Get requested dimensions
        const requestWidth = args.width || 1024;
        const requestHeight = args.height || 768;
    
        // Ensure dimensions are at least 256 pixels for the API request
        const apiWidth = Math.max(256, requestWidth);
        const apiHeight = Math.max(256, requestHeight);
    
        const response = await this.together.images.create({
          model: args.model || 'black-forest-labs/FLUX.1.1-pro',
          prompt: args.prompt,
          width: apiWidth,
          height: apiHeight,
          steps: args.steps || 28,
          n: args.n || 1,
          response_format: 'base64',
        });
    
        // Use provided output directory or default to 'output'
        const outputDir = args.outputDir 
          ? path.resolve(args.outputDir)
          : path.join(process.cwd(), 'output');
    
        // Create output directory if it doesn't exist
        if (!fs.existsSync(outputDir)) {
          fs.mkdirSync(outputDir, { recursive: true });
        }
    
        // Process each generated image
        const results = await Promise.all(response.data.map(async (result: any, index: number) => {
          const imageData = result.b64_json;
          let buffer = Buffer.from(imageData, 'base64');
          
          // Only resize if we need to scale down to match requested dimensions
          if (requestWidth < 256 || requestHeight < 256) {
            const metadata = await sharp(buffer).metadata();
            const originalWidth = metadata.width || 0;
            const originalHeight = metadata.height || 0;
    
            // Calculate target dimensions maintaining aspect ratio
            const aspectRatio = originalWidth / originalHeight;
            let targetWidth = requestWidth;
            let targetHeight = requestHeight;
    
            if (requestWidth < 256) {
              targetWidth = requestWidth;
              targetHeight = Math.round(requestWidth / aspectRatio);
            }
            if (requestHeight < 256) {
              targetHeight = requestHeight;
              targetWidth = Math.round(requestHeight * aspectRatio);
            }
    
            // Resize to match requested dimensions
            buffer = await sharp(buffer)
              .resize(targetWidth, targetHeight, {
                fit: 'contain',
                background: { r: 255, g: 255, b: 255, alpha: 1 }
              })
              .toBuffer();
          }
          
          // Save image with timestamp and index
          const timestamp = new Date().getTime();
          const format = args.format || 'png';
          const filename = `image_${timestamp}_${index}.${format}`;
          const filepath = path.join(outputDir, filename);
          
          let sharpInstance = sharp(buffer);
          
          switch (format) {
            case 'png':
              await sharpInstance.png().toFile(filepath);
              break;
            case 'jpg':
              await sharpInstance.jpeg({ quality: 90 }).toFile(filepath);
              break;
            case 'svg':
              // For SVG, we'll need to trace the bitmap to create a vector
              await sharpInstance
                .png()
                .toFile(filepath.replace('.svg', '.png'));
              // Note: Actual SVG conversion would require additional processing
              // Consider using potrace or similar library for proper SVG conversion
              console.warn('SVG output is not fully supported yet');
              break;
          }
          
          return {
            ...result,
            filepath,
            filename,
            dimensions: {
              original: { width: apiWidth, height: apiHeight },
              final: await sharp(filepath).metadata().then(m => ({ 
                width: m.width, 
                height: m.height 
              }))
            }
          };
        }));
    
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(results, null, 2),
            },
          ],
        };
      } catch (error: any) {
        console.error('Together AI API error:', error);
        throw new McpError(
          ErrorCode.InternalError,
          `Image generation failed: ${error?.message || 'Unknown error'}`
        );
      }
    });
  • src/index.ts:79-137 (registration)
    Registration of the generate_image tool in the ListToolsRequestSchema response, including name, description, uiSchema, and detailed inputSchema.
      name: 'generate_image',
      description: 'Generate an image using Together AI',
      uiSchema: {
        format: {
          "ui:widget": "select",
          "ui:options": {
            label: "Image Format",
            position: "above-chat"
          }
        }
      },
      inputSchema: {
        type: 'object',
        properties: {
          prompt: {
            type: 'string',
            description: 'Text description of the image to generate',
          },
          model: {
            type: 'string',
            description: 'Model to use for generation',
            default: 'black-forest-labs/FLUX.1.1-pro',
          },
          width: {
            type: 'number',
            description: 'Image width in pixels',
            default: 1024,
          },
          height: {
            type: 'number',
            description: 'Image height in pixels',
            default: 768,
          },
          steps: {
            type: 'number',
            description: 'Number of inference steps',
            default: 28,
          },
          n: {
            type: 'number',
            description: 'Number of images to generate',
            default: 1,
          },
          outputDir: {
            type: 'string',
            description: 'Full absolute path where images will be saved (e.g., /Users/username/Projects/myapp/src/assets)',
            pattern: '^/',
            examples: ['/Users/asanstefanski/Private Projekte/democline/src/assets'],
          },
          format: {
            type: 'string',
            enum: ['png', 'jpg', 'svg'],
            description: 'Output format for the generated images',
            default: 'png',
          },
        },
        required: ['prompt'],
      },
    },
  • Detailed input schema for generate_image tool parameters including prompt (required), model, dimensions, steps, number of images, output directory, and format.
    inputSchema: {
      type: 'object',
      properties: {
        prompt: {
          type: 'string',
          description: 'Text description of the image to generate',
        },
        model: {
          type: 'string',
          description: 'Model to use for generation',
          default: 'black-forest-labs/FLUX.1.1-pro',
        },
        width: {
          type: 'number',
          description: 'Image width in pixels',
          default: 1024,
        },
        height: {
          type: 'number',
          description: 'Image height in pixels',
          default: 768,
        },
        steps: {
          type: 'number',
          description: 'Number of inference steps',
          default: 28,
        },
        n: {
          type: 'number',
          description: 'Number of images to generate',
          default: 1,
        },
        outputDir: {
          type: 'string',
          description: 'Full absolute path where images will be saved (e.g., /Users/username/Projects/myapp/src/assets)',
          pattern: '^/',
          examples: ['/Users/asanstefanski/Private Projekte/democline/src/assets'],
        },
        format: {
          type: 'string',
          enum: ['png', 'jpg', 'svg'],
          description: 'Output format for the generated images',
          default: 'png',
        },
      },
      required: ['prompt'],
    },
  • TypeScript interface defining the expected arguments for generate_image.
    interface GenerateImageArgs {
      prompt: string;
      model?: string;
      width?: number;
      height?: number;
      steps?: number;
      n?: number;
      outputDir?: string;
      format?: 'png' | 'jpg' | 'svg';
    }
  • Type guard function to validate generate_image arguments matching GenerateImageArgs interface.
    const isValidGenerateImageArgs = (args: any): args is GenerateImageArgs => {
      return (
        typeof args === 'object' &&
        args !== null &&
        typeof args.prompt === 'string' &&
        (args.model === undefined || typeof args.model === 'string') &&
        (args.width === undefined || typeof args.width === 'number') &&
        (args.height === undefined || typeof args.height === 'number') &&
        (args.steps === undefined || typeof args.steps === 'number') &&
        (args.n === undefined || typeof args.n === 'number') &&
        (args.outputDir === undefined || typeof args.outputDir === 'string') &&
        (args.format === undefined || ['png', 'jpg', 'svg'].includes(args.format))
      );
    };
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It mentions 'Generate an image' which implies a creation/write operation, but provides no information about permissions needed, rate limits, costs, whether it's idempotent, or what happens with the generated images (e.g., are they saved locally as indicated by outputDir?). This is a significant gap for a tool with potentially complex behavior.

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?

The description is extremely concise - a single sentence that directly states the tool's purpose without any unnecessary words. It's perfectly front-loaded with the essential information, making it highly efficient for an agent to parse.

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

Completeness2/5

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

For an image generation tool with 8 parameters and no output schema, the description is insufficient. It doesn't explain what the tool returns (e.g., file paths, success status, error handling), doesn't mention the outputDir parameter's significance for file storage, and provides no behavioral context despite the complexity implied by multiple configuration parameters. The lack of annotations exacerbates these gaps.

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?

The schema description coverage is 100%, so the schema already documents all 8 parameters thoroughly. The description adds no additional parameter information beyond what's in the schema, which is acceptable given the comprehensive schema documentation. This meets the baseline expectation when schema coverage is high.

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

Purpose4/5

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

The description clearly states the verb ('Generate') and resource ('image') with the service provider ('using Together AI'), making the purpose immediately understandable. However, with no sibling tools mentioned, it doesn't need to differentiate from alternatives, so it falls short of a perfect 5.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives, prerequisites, or constraints. It simply states what the tool does without any context about appropriate use cases or limitations.

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/stefanskiasan/togetherai-image-mcp-server'

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