|
| 1 | +""" |
| 2 | +Image generation MCP tools service. |
| 3 | +
|
| 4 | +Generates images via Azure OpenAI's images/generations endpoint (gpt-5-mini), |
| 5 | +uploads the resulting PNG to Azure Blob Storage, and returns a public URL that |
| 6 | +Foundry-hosted agents can embed in their markdown responses. |
| 7 | +""" |
| 8 | + |
| 9 | +import base64 |
| 10 | +import logging |
| 11 | +import uuid |
| 12 | + |
| 13 | +import httpx |
| 14 | +from azure.identity import DefaultAzureCredential, ManagedIdentityCredential, get_bearer_token_provider |
| 15 | +from azure.storage.blob import BlobServiceClient, ContentSettings, PublicAccess |
| 16 | + |
| 17 | +from config.settings import config |
| 18 | +from core.factory import Domain, MCPToolBase |
| 19 | + |
| 20 | +logger = logging.getLogger(__name__) |
| 21 | + |
| 22 | +_IMAGE_API_VERSION = "2025-04-01-preview" |
| 23 | + |
| 24 | + |
| 25 | +def _get_credential(): |
| 26 | + """Return a credential, preferring user-assigned MI when a client id is set.""" |
| 27 | + if config.azure_client_id: |
| 28 | + return ManagedIdentityCredential(client_id=config.azure_client_id) |
| 29 | + return DefaultAzureCredential() |
| 30 | + |
| 31 | + |
| 32 | +def _ensure_public_container(blob_service: BlobServiceClient, container_name: str) -> None: |
| 33 | + """Create the container with blob-level public read access if missing.""" |
| 34 | + container_client = blob_service.get_container_client(container_name) |
| 35 | + try: |
| 36 | + container_client.create_container(public_access=PublicAccess.BLOB) |
| 37 | + logger.info("Created public blob container '%s'", container_name) |
| 38 | + except Exception: |
| 39 | + # Container already exists — leave its access level alone. |
| 40 | + pass |
| 41 | + |
| 42 | + |
| 43 | +def _upload_png_and_get_url(png_bytes: bytes) -> str: |
| 44 | + """Upload PNG bytes to blob storage, return the public URL.""" |
| 45 | + if not config.azure_storage_blob_url: |
| 46 | + raise RuntimeError("AZURE_STORAGE_BLOB_URL is not configured on the MCP server") |
| 47 | + |
| 48 | + account_url = config.azure_storage_blob_url.rstrip("/") |
| 49 | + container_name = config.azure_storage_images_container |
| 50 | + blob_name = f"{uuid.uuid4()}.png" |
| 51 | + |
| 52 | + credential = _get_credential() |
| 53 | + blob_service = BlobServiceClient(account_url=account_url, credential=credential) |
| 54 | + _ensure_public_container(blob_service, container_name) |
| 55 | + |
| 56 | + blob_client = blob_service.get_blob_client(container=container_name, blob=blob_name) |
| 57 | + blob_client.upload_blob( |
| 58 | + png_bytes, |
| 59 | + overwrite=True, |
| 60 | + content_settings=ContentSettings(content_type="image/png"), |
| 61 | + ) |
| 62 | + return f"{account_url}/{container_name}/{blob_name}" |
| 63 | + |
| 64 | + |
| 65 | +class ImageService(MCPToolBase): |
| 66 | + """Image-generation tools backed by Azure OpenAI gpt-5-mini.""" |
| 67 | + |
| 68 | + def __init__(self): |
| 69 | + super().__init__(Domain.IMAGE) |
| 70 | + |
| 71 | + def register_tools(self, mcp) -> None: |
| 72 | + @mcp.tool(tags={self.domain.value}) |
| 73 | + async def generate_marketing_image(prompt: str, size: str = "1024x1024") -> str: |
| 74 | + """Generate a marketing image from a text prompt. |
| 75 | +
|
| 76 | + Use this tool whenever the user asks for an image, picture, photo, banner, |
| 77 | + or visual asset. Pass a detailed description of the scene, subject, style, |
| 78 | + lighting, and composition. The tool returns a public HTTPS URL to the |
| 79 | + generated PNG. Embed the URL in your response using markdown image syntax, |
| 80 | + for example: . |
| 81 | +
|
| 82 | + Args: |
| 83 | + prompt: A detailed description of the image to generate. |
| 84 | + size: One of "1024x1024", "1024x1792", or "1792x1024". Defaults to square. |
| 85 | +
|
| 86 | + Returns: |
| 87 | + A public HTTPS URL to the generated PNG image. |
| 88 | + """ |
| 89 | + if not config.azure_openai_endpoint: |
| 90 | + raise RuntimeError("AZURE_OPENAI_ENDPOINT is not configured on the MCP server") |
| 91 | + |
| 92 | + deployment = config.azure_openai_image_deployment |
| 93 | + endpoint = config.azure_openai_endpoint.rstrip("/") |
| 94 | + url = ( |
| 95 | + f"{endpoint}/openai/deployments/{deployment}" |
| 96 | + f"/images/generations?api-version={_IMAGE_API_VERSION}" |
| 97 | + ) |
| 98 | + |
| 99 | + token_provider = get_bearer_token_provider( |
| 100 | + _get_credential(), "https://cognitiveservices.azure.com/.default" |
| 101 | + ) |
| 102 | + headers = { |
| 103 | + "Authorization": f"Bearer {token_provider()}", |
| 104 | + "Content-Type": "application/json", |
| 105 | + } |
| 106 | + body = {"prompt": prompt, "n": 1, "size": size} |
| 107 | + |
| 108 | + logger.info("Generating image (deployment=%s, size=%s, prompt_len=%d)", deployment, size, len(prompt)) |
| 109 | + async with httpx.AsyncClient(timeout=120.0) as client: |
| 110 | + resp = await client.post(url, json=body, headers=headers) |
| 111 | + if resp.status_code >= 400: |
| 112 | + raise RuntimeError(f"Image generation failed: {resp.status_code} {resp.text}") |
| 113 | + result_json = resp.json() |
| 114 | + |
| 115 | + data = result_json.get("data") or [] |
| 116 | + if not data: |
| 117 | + raise RuntimeError(f"Image generation returned no data: {result_json}") |
| 118 | + b64_data = data[0].get("b64_json") or data[0].get("b64") |
| 119 | + if not b64_data: |
| 120 | + raise RuntimeError(f"Image generation returned no b64 data: {result_json}") |
| 121 | + |
| 122 | + png_bytes = base64.b64decode(b64_data) |
| 123 | + public_url = _upload_png_and_get_url(png_bytes) |
| 124 | + logger.info("Image uploaded: %s", public_url) |
| 125 | + return public_url |
| 126 | + |
| 127 | + @property |
| 128 | + def tool_count(self) -> int: |
| 129 | + return 1 |
0 commit comments