ImageGenMcp.Server 2.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet tool install --global ImageGenMcp.Server --version 2.0.0
                    
This package contains a .NET tool you can call from the shell/command line.
dotnet new tool-manifest
                    
if you are setting up this repo
dotnet tool install --local ImageGenMcp.Server --version 2.0.0
                    
This package contains a .NET tool you can call from the shell/command line.
#tool dotnet:?package=ImageGenMcp.Server&version=2.0.0
                    
nuke :add-package ImageGenMcp.Server --version 2.0.0
                    

ImageGen MCP Server

A .NET/C# Model Context Protocol (MCP) server over stdio for creating and editing images through Azure AI Foundry / Azure OpenAI. It defaults to OpenAI's newer gpt-image-2 model name and returns actual MCP image content blocks (image/png, image/jpeg, or image/webp) instead of plain URLs.

What is included

  • generate_image MCP tool for image creation.
  • edit_image MCP tool for image editing from local file paths, with an optional mask and optional extra reference images.
  • Azure Foundry v1 image endpoint support: /openai/v1/images/{generations|edits}?api-version=preview.
  • Azure deployment endpoint compatibility: /openai/deployments/{deployment}/images/{generations|edits}?api-version=....
  • API key auth and Microsoft Entra ID auth with configurable token scope.
  • MCP image returns via ImageContentBlock.FromBytes(...), so clients receive properly base64-encoded image payloads.
  • Tests around request construction, response decoding, validation, and MCP content block creation.

Package baseline

The project was scaffolded with current NuGet packages resolved during setup:

Package Version Purpose
ModelContextProtocol 1.2.0 Official C# MCP SDK, stdio transport, tool attributes, image content blocks
Microsoft.Extensions.Hosting 10.0.7 Generic host for the stdio server
Microsoft.Extensions.Http 10.0.7 Typed HttpClient for Azure Foundry calls
Microsoft.Extensions.Options.ConfigurationExtensions 10.0.7 Configuration binding
Microsoft.Extensions.Configuration.UserSecrets 10.0.7 Local secret support
Microsoft.Extensions.Logging.Console 10.0.7 Logging to stderr for MCP stdio safety
Azure.Identity 1.21.0 Optional Entra ID auth with DefaultAzureCredential
SixLabors.ImageSharp 3.1.11 Managed PNG/JPEG/WebP decoding and mask metadata validation

Note: The OpenAI/Azure .NET SDKs expose image functionality, but the newest image model surfaces can lag in strongly typed SDK options. This server calls the Azure Foundry image REST endpoints directly and exposes only image-generation/editing controls that are useful to an MCP client.

Configuration

The server reads configuration from appsettings.json, environment variables, user-secrets, and a local .env file. A placeholder .env was created for local development and is ignored by git.

Required API key setup:

AzureFoundry__Endpoint=https://YOUR-RESOURCE-NAME.openai.azure.com/
AzureFoundry__ApiKey=YOUR_AZURE_OPENAI_API_KEY
AzureFoundry__Model=gpt-image-2
AzureFoundry__ModelFamily=gpt-image-2
AzureFoundry__ApiVersion=preview
AzureFoundry__EndpointMode=V1Images
AzureFoundry__Authentication=ApiKey

For Entra ID / managed identity:

AzureFoundry__Endpoint=https://YOUR-RESOURCE-NAME.openai.azure.com/
AzureFoundry__Model=gpt-image-2
AzureFoundry__ModelFamily=gpt-image-2
AzureFoundry__ApiVersion=preview
AzureFoundry__EndpointMode=V1Images
AzureFoundry__Authentication=EntraId
AzureFoundry__TokenScope=https://ai.azure.com/.default

If your Azure resource requires the classic Azure OpenAI audience instead, set:

AzureFoundry__TokenScope=https://cognitiveservices.azure.com/.default

Endpoint modes

Mode URL shape When to use
V1Images /openai/v1/images/generations?api-version=preview with model in body Preferred Azure Foundry/OpenAI-compatible v1 flow
DeploymentImages /openai/deployments/{deployment}/images/generations?api-version=2025-04-01-preview Older Azure OpenAI deployment-name flow

Model is the deployed model/deployment identifier sent to Azure or placed in the legacy deployment URL. ModelFamily selects local capability validation and should remain gpt-image-2 even when Model is a custom deployment alias.

Safety limits

Setting Default Purpose
MaxPromptCharacters 32000 Bounds prompt size
MaxImagesPerRequest 10 Bounds n
MaxInputImageBytes 52428800 Configured per-file ceiling; the provider's strict < 50 MiB hard limit still applies
MaxInputRequestBytes 209715200 Aggregate byte budget across primary, mask, and reference images
MaxOutputImageBytes 52428800 Bounds each decoded base64 image
MaxResponseBodyBytes 209715200 Bounds the complete Azure response body before JSON parsing
TimeoutSeconds 300 Bounds Azure Foundry calls

MCP client registration

Example stdio registration:

{
  "mcpServers": {
    "image-gen": {
      "command": "dotnet",
      "args": [
        "run",
        "--project",
        "D:\\git\\image-gen-mcp\\src\\ImageGenMcp.Server\\ImageGenMcp.Server.csproj"
      ]
    }
  }
}

For package-based usage with .NET SDK 10 or later, publish the tool package to NuGet.org or a private NuGet feed and run it with dnx:

{
  "mcpServers": {
    "image-gen": {
      "command": "dotnet",
      "args": [
        "dnx",
        "ImageGenMcp.Server"
      ]
    }
  }
}

If the package is on a private feed, add the feed either through nuget.config or as part of the command arguments:

{
  "mcpServers": {
    "image-gen": {
      "command": "dotnet",
      "args": [
        "dnx",
        "ImageGenMcp.Server",
        "--add-source",
        "https://YOUR-FEED-URL/index.json"
      ]
    }
  }
}

For pinned deployments, include the package version in the package reference, for example ImageGenMcp.Server@2.0.0. dnx downloads and runs the tool without permanently installing it.

The packaged tool command name is image-gen-mcp, which is used when installing the package as a global or local .NET tool.

Tools

generate_image

Use when a user wants a new image created from a text description. The tool returns image content directly.

Key parameters:

Parameter Default Notes
prompt required Describe subject, setting, style, composition, lighting, colors, mood, camera/framing, text, and constraints.
size auto Use auto unless exact dimensions/aspect ratio matter. Custom dimensions use WIDTHxHEIGHT; both edges must be multiples of 16, long edge ⇐ 3840px, aspect ratio ⇐ 3:1, and total pixels between 655,360 and 8,294,400.
quality high low for drafts, medium for balanced results, high for final/high-detail images, or auto to let the model choose.
n 1 Number of alternatives. Use 1 unless the user asks for multiple options.
outputFormat png png for crisp graphics/text/UI/lossless output; jpeg for photos or lower latency; webp for compact web assets.
outputCompression unset JPEG or WebP compression 0-100. Higher values apply more compression.

Example:

{
  "prompt": "A cinematic macro photograph of a crystal fox in a snowy pine forest, volumetric dawn light",
  "size": "3840x2160",
  "quality": "high",
  "outputFormat": "jpeg",
  "outputCompression": 90
}

edit_image

Use when a user provides an image and wants it changed, restyled, repaired, expanded, or combined with reference images. The tool returns image content directly.

Key edit-only parameters:

Parameter Default Notes
prompt required Describe what should change, what must remain unchanged, and any style/composition requirements.
imagePath required Absolute path to a local PNG, JPEG, or WebP image readable by the MCP server process. The MIME type is detected from file bytes, not trusted from the extension.
maskPath unset Absolute path to an optional PNG mask with an alpha channel. It must have the same dimensions as the first input image.
additionalImagePaths unset Up to 15 absolute paths to extra PNG, JPEG, or WebP references. Together with imagePath, an edit supports up to 16 input images.
size auto Use auto unless exact output dimensions/aspect ratio matter. Custom dimensions follow the same rules as generation.
quality high low for drafts, medium for balanced results, high for final/high-detail edits, or auto to let the model choose.
n 1 Number of edited alternatives. Use 1 unless the user asks for multiple options.
outputFormat png png for crisp graphics/text/UI/lossless output; jpeg for photos or lower latency; webp for compact web assets.
outputCompression unset JPEG or WebP compression 0-100. Higher values apply more compression.

Example:

{
  "prompt": "Change the mug to cobalt blue while preserving its logo, shape, lighting, and the rest of the scene",
  "imagePath": "C:/art/source-mug.png",
  "additionalImagePaths": [
    "C:/art/cobalt-reference.jpg"
  ],
  "outputFormat": "webp",
  "outputCompression": 50
}

The paths are resolved on the machine running the MCP server, not on a remote model host. Relative paths, Windows network shares, and Windows device paths are rejected. Files are fully decoded before upload; changing an unsupported file's extension does not make it valid.

Migration from base64 edit inputs

The path-based edit schema intentionally replaces the previous encoded transport and is a breaking MCP contract change. Publish it as a major package version for existing consumers.

Previous parameter Replacement
imageBase64 + imageMimeType imagePath
maskBase64 + maskMimeType maskPath
additionalImagesBase64 additionalImagePaths
inputFidelity Removed; gpt-image-2 always processes edit inputs at high fidelity

The server derives MIME types and image metadata from decoded local files. Callers no longer encode bytes or declare MIME types.

Current gpt-image-2 coverage

Implemented as AI-facing first-class parameters: prompt, arbitrary custom size validation, quality, n, PNG/JPEG/WebP output, JPEG/WebP compression, local edit image paths, masks, and up to 16 total edit inputs.

Deliberately not exposed as MCP tool parameters: model/deployment, user, response_format, raw stream, partial_images, background, and arbitrary JSON pass-through. Those are configuration, telemetry, transport, unsupported, or API escape-hatch details rather than reliable MCP image-creation controls. The server config chooses the model/deployment and the tool always returns MCP image blocks.

partial_images is not exposed because MCP tool calls return a final tool result, not incremental image-generation events. background is not exposed because gpt-image-2 does not currently support transparent backgrounds, and sending background controls creates confusing failure modes.

input_fidelity is intentionally not exposed or sent for gpt-image-2. The model always processes edit inputs at high fidelity and rejects attempts to change this parameter.

API contract validation

The implementation was checked against the current Azure OpenAI v1 preview image reference, Azure v1 API lifecycle guidance, Azure model availability, and the GPT Image 2 model/API documentation on 2026-07-14:

  • The preferred request paths are /openai/v1/images/generations and /openai/v1/images/edits; the v1 preview image reference currently shows ?api-version=preview for these image operations.
  • V1 requests identify the deployed model with the model body/form field. The older deployment URL remains available as a compatibility mode.
  • Generation uses JSON; edits use multipart/form-data. A single edit input uses image; multiple inputs use repeated image[] parts, each with its own detected MIME type.
  • GPT Image responses contain base64 image data, which the server decodes and returns as MCP image content.
  • gpt-image-2 supports arbitrary validated dimensions, low/medium/high/auto quality, png/jpeg/webp output, and compression for JPEG/WebP.
  • A mask applies to the first input image. It must be PNG, include an alpha channel, and match the first image's dimensions. The server decodes and validates these properties before the Azure request.
  • gpt-image-2 version 2026-04-21 is available only in selected Azure Global Standard regions. Check current Azure model region availability before deployment.

References: Azure v1 preview image REST API, Azure v1 API lifecycle, GPT Image generation guide, and GPT Image 2 model.

Development

Restore/build/test:

dotnet restore
dotnet build
dotnet test

Run locally as an MCP stdio server:

dotnet run --project src/ImageGenMcp.Server/ImageGenMcp.Server.csproj

The process waits for MCP JSON-RPC on stdin. Logs are written to stderr so stdout stays protocol-clean.

Package as a .NET tool:

dotnet pack src/ImageGenMcp.Server/ImageGenMcp.Server.csproj

The package is written to artifacts/packages/. To test the package locally with dnx, use that directory as an additional package source.

Security and operational notes

  • Do not commit real .env values. Use user-secrets, environment variables, managed identity, or a vault-backed deployment.
  • Prompt, aggregate input, response body, and decoded output image sizes are bounded to reduce accidental runaway cost and resource usage.
  • Local edit paths are required to be absolute and local to the machine. Files are size-checked before allocation, fully decoded as PNG/JPEG/WebP content, and uploaded with sanitized filenames.
  • The MCP server can read images using the operating-system permissions of its process. Only provide paths that the server is intended to access.
  • The server does not log prompts, image bytes, masks, or API keys.
  • GPT Image responses must contain b64_json; URL-only image results are rejected and are never fetched by the server.
  • NuGet audit is enabled in the server project for moderate-or-higher vulnerabilities across direct and transitive dependencies.
Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

This package has no dependencies.

Version Downloads Last Updated
3.0.0 206 9/12/2026
2.0.0 174 7/15/2026
1.0.0 164 6/23/2026

Breaking: edit_image now accepts absolute local image paths instead of base64 image payloads.