# SKILL: ImageGen MCP + Semantic Kernel Integration Guide ## Purpose This guide defines how to use `ImageGenMcp.SemanticKernel.Plugin` correctly from both: - **Human developers** - **AI agents** (Copilot, autonomous coding agents, LLM workflows) It standardises responsibility boundaries, invocation patterns, safety rules, and expected implementation quality. --- ## Scope Applies to projects that: - target `.NET 10+` - use `Microsoft.SemanticKernel` - use AI image generation via the MCP server (`imagegen-mcp`, from `ImageGen.McpHost`) ## MCP Tool Surface The ImageGen MCP server exposes three tools: | Tool | Description | |------|-------------| | `image_gen_generate` | Generate an image from a text prompt | | `image_gen_get_credits` | Get remaining provider credits | | `image_gen_info` | Get provider/model/output-directory info | In expanded SK registration, each tool maps to a kernel function (e.g. `imagegen_image_gen_generate`). --- ## Core Mental Model Two valid execution modes: 1. **Manual invocation** — call `ImageGenPlugin.GenerateImageAsync(...)` directly. Deterministic and explicit. 2. **Automatic invocation (tool-calling)** — configure SK function calling (`FunctionChoiceBehavior.Auto()`). The model decides when to call image generation tools. ### Responsibility Boundary | Responsibility | Owner | |---|---| | Connect to MCP server | Plugin | | Discover and register tools | Plugin | | Validate and convert parameters | Plugin | | Invoke tools safely | Plugin | | Host/kernel/model configuration | Client | | Enable automatic function calling | Client | | Prompt/chat orchestration | Client | > The plugin exposes callable functions. The client decides orchestration mode. --- ## Required Runtime Preconditions Before invoking tools: 1. `imagegen-mcp` is on `PATH` (or `ExecutablePath` is set). 2. A provider key is set: `STABILITY_API_KEY` or `GEMINI_API_KEY`. 3. `ImageGenPlugin.InitializeAsync()` has completed successfully. --- ## Standard Setup (Developer) 1. Install the server: `dotnet tool install -g ImageGen.McpHost` 2. Set your API key environment variable. 3. Register services: `services.AddImageGenMcp(configuration)`. 4. Resolve `ImageGenPlugin` from DI. 5. Call `await plugin.InitializeAsync()`. 6. Choose invocation mode: - Direct: `await plugin.GenerateImageAsync("a cat")` - SK expanded: `await kernel.RegisterImageGenToolsAsync(services)` - SK router: `kernel.RegisterImageGenPlugin(services)` --- ## Standard Setup (AI Agent) When generating code: 1. Ensure DI registration exists (`AddImageGenMcp(...)`). 2. Ensure plugin initialization is present and awaited. 3. If the user asks for "automatic", configure SK execution settings for auto function calling in the **client** — not in the plugin. 4. Keep the manual path available as a deterministic fallback. Do not claim automatic invocation is plugin-only. --- ## Plugin Attribute Guidance `ImageGenPlugin` methods are decorated with `[KernelFunction]` and `[Description]`. If adding new callable methods: - Add `[KernelFunction("unique_name")]` - Add `[Description("...")]` to the method and all parameters - Delegate validation to `InputValidator` --- ## Safety and Validation Rules - Never bypass `InputValidator`. - Never hardcode API keys in source. - Treat tool inputs as untrusted; log through `LogSanitizer`. - Prefer the typed methods (`GenerateImageAsync`, etc.) over raw `InvokeToolAsync`. --- ## Error Handling Policy Catch and classify: - `ConfigurationException` — bad settings - `ProcessException` — `imagegen-mcp` process failure - `NetworkException` — transport failure - `TimeoutException` — operation exceeded deadline - `McpServerException` — server returned JSON-RPC error - `ProtocolException` — malformed JSON-RPC - `ImageGenMcpException` — any other plugin error Return actionable diagnostics. Do not expose API keys or internal paths. --- ## Reliability Rules - Use configurable timeouts (`ConnectionTimeoutSeconds`, `RequestTimeoutSeconds`). - Use retry for transient failures only (configure `MaxRetryAttempts`). - Support cancellation tokens on all async methods. - Keep `EnableMessageLogging: false` in production. --- ## Testing Expectations For any feature touching invocation: 1. Unit test parameter validation with `InputValidatorTests`. 2. Unit test failure paths using `NSubstitute` mocks of `IMcpClient`. 3. Integration test at least one end-to-end tool call (opt-in, tagged `[Trait("Category","Integration")]`). --- ## Anti-Patterns Avoid: - Assuming SK auto-calls tools without client function-calling config. - Calling tools before `InitializeAsync()`. - Logging raw API keys or prompt text at `Information` level. - Writing examples that cannot compile as shown. --- ## Quick Decision Table | Goal | Use | |---|---| | Deterministic image generation | `GenerateImageAsync(...)` direct call | | LLM decides when to generate | SK auto function-calling in client | | Dynamic tool discovery | `await kernel.RegisterImageGenToolsAsync(services)` | | Single plugin entry point | `kernel.RegisterImageGenPlugin(services)` | | Custom tool not yet wrapped | `InvokeToolAsync(toolName, args)` |