adk-rust-mcp-image 0.5.0

MCP server for image generation using Vertex AI Imagen
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
//! MCP Server implementation for the Image server.
//!
//! This module provides the MCP server handler that exposes:
//! - `image_generate` tool for text-to-image generation
//! - `image_upscale` tool for image upscaling
//! - Resources for models, segmentation classes, and providers

use crate::handler::{ImageGenerateParams, ImageGenerateResult, ImageHandler, ImageUpscaleParams, ImageUpscaleResult};
use crate::resources;
use adk_rust_mcp_common::config::Config;
use adk_rust_mcp_common::error::Error;
use rmcp::{
    model::{
        CallToolResult, Content, ListResourcesResult, ReadResourceResult,
        ResourceContents, ServerCapabilities, ServerInfo,
    },
    ErrorData as McpError, ServerHandler,
};
use schemars::JsonSchema;
use serde::Deserialize;
use std::borrow::Cow;
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::{debug, info};

/// MCP Server for image generation.
#[derive(Clone)]
pub struct ImageServer {
    /// Handler for image generation operations
    handler: Arc<RwLock<Option<ImageHandler>>>,
    /// Server configuration
    config: Config,
}

/// Tool parameters wrapper for image_generate.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct ImageGenerateToolParams {
    /// Text prompt describing the image to generate
    pub prompt: String,
    /// Negative prompt - what to avoid in the generated image
    #[serde(default)]
    pub negative_prompt: Option<String>,
    /// Model to use for generation (default: imagen-4.0-generate-preview-05-20)
    #[serde(default)]
    pub model: Option<String>,
    /// Aspect ratio (1:1, 3:4, 4:3, 9:16, 16:9)
    #[serde(default)]
    pub aspect_ratio: Option<String>,
    /// Number of images to generate (1-4)
    #[serde(default)]
    pub number_of_images: Option<u8>,
    /// Random seed for reproducibility
    #[serde(default)]
    pub seed: Option<i64>,
    /// Output file path for saving locally
    #[serde(default)]
    pub output_file: Option<String>,
    /// Output storage URI (e.g., gs://bucket/path)
    #[serde(default)]
    pub output_uri: Option<String>,
}

impl From<ImageGenerateToolParams> for ImageGenerateParams {
    fn from(params: ImageGenerateToolParams) -> Self {
        Self {
            prompt: params.prompt,
            negative_prompt: params.negative_prompt,
            model: params.model.unwrap_or_else(|| crate::handler::DEFAULT_MODEL.to_string()),
            aspect_ratio: params.aspect_ratio.unwrap_or_else(|| "1:1".to_string()),
            number_of_images: params.number_of_images.unwrap_or(1),
            seed: params.seed,
            output_file: params.output_file,
            output_uri: params.output_uri,
        }
    }
}

/// Tool parameters wrapper for image_upscale.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct ImageUpscaleToolParams {
    /// Source image to upscale (base64 data, local path, or GCS URI)
    pub image: String,
    /// Upscale factor: "x2" or "x4" (default: "x2")
    #[serde(default)]
    pub upscale_factor: Option<String>,
    /// Output file path for saving locally
    #[serde(default)]
    pub output_file: Option<String>,
    /// Output storage URI (e.g., gs://bucket/path)
    #[serde(default)]
    pub output_uri: Option<String>,
}

impl From<ImageUpscaleToolParams> for ImageUpscaleParams {
    fn from(params: ImageUpscaleToolParams) -> Self {
        Self {
            image: params.image,
            upscale_factor: params.upscale_factor.unwrap_or_else(|| "x2".to_string()),
            output_file: params.output_file,
            output_uri: params.output_uri,
        }
    }
}

impl ImageServer {
    /// Create a new ImageServer with the given configuration.
    pub fn new(config: Config) -> Self {
        Self {
            handler: Arc::new(RwLock::new(None)),
            config,
        }
    }

    /// Initialize the handler (called lazily on first use).
    async fn ensure_handler(&self) -> Result<(), Error> {
        let mut handler = self.handler.write().await;
        if handler.is_none() {
            *handler = Some(ImageHandler::new(self.config.clone()).await?);
        }
        Ok(())
    }

    /// Generate images from a text prompt.
    pub async fn generate_image(&self, params: ImageGenerateToolParams) -> Result<CallToolResult, McpError> {
        info!(prompt = %params.prompt, "Generating image");

        // Ensure handler is initialized
        self.ensure_handler().await.map_err(|e| {
            McpError::internal_error(format!("Failed to initialize handler: {}", e), None)
        })?;

        let handler_guard = self.handler.read().await;
        let handler = handler_guard.as_ref().ok_or_else(|| {
            McpError::internal_error("Handler not initialized", None)
        })?;

        let gen_params: ImageGenerateParams = params.into();
        let result = handler.generate_image(gen_params).await.map_err(|e| {
            McpError::internal_error(format!("Image generation failed: {}", e), None)
        })?;

        // Convert result to MCP content
        let content = match result {
            ImageGenerateResult::Base64(images) => {
                images
                    .into_iter()
                    .map(|img| Content::image(img.data, img.mime_type))
                    .collect()
            }
            ImageGenerateResult::LocalFiles(paths) => {
                vec![Content::text(format!("Images saved to: {}", paths.join(", ")))]
            }
            ImageGenerateResult::StorageUris(uris) => {
                vec![Content::text(format!("Images uploaded to: {}", uris.join(", ")))]
            }
        };

        Ok(CallToolResult::success(content))
    }

    /// Upscale an image.
    pub async fn upscale_image(&self, params: ImageUpscaleToolParams) -> Result<CallToolResult, McpError> {
        info!(upscale_factor = ?params.upscale_factor, "Upscaling image");

        // Ensure handler is initialized
        self.ensure_handler().await.map_err(|e| {
            McpError::internal_error(format!("Failed to initialize handler: {}", e), None)
        })?;

        let handler_guard = self.handler.read().await;
        let handler = handler_guard.as_ref().ok_or_else(|| {
            McpError::internal_error("Handler not initialized", None)
        })?;

        let upscale_params: ImageUpscaleParams = params.into();
        let result = handler.upscale_image(upscale_params).await.map_err(|e| {
            McpError::internal_error(format!("Image upscaling failed: {}", e), None)
        })?;

        // Convert result to MCP content
        let content = match result {
            ImageUpscaleResult::Base64(image) => {
                vec![Content::image(image.data, image.mime_type)]
            }
            ImageUpscaleResult::LocalFile(path) => {
                vec![Content::text(format!("Upscaled image saved to: {}", path))]
            }
            ImageUpscaleResult::StorageUri(uri) => {
                vec![Content::text(format!("Upscaled image uploaded to: {}", uri))]
            }
        };

        Ok(CallToolResult::success(content))
    }
}

impl ServerHandler for ImageServer {
    fn get_info(&self) -> ServerInfo {
        ServerInfo {
            instructions: Some(
                "Image generation and processing server using Google Vertex AI Imagen API. \
                 Use image_generate to create images from text prompts, \
                 and image_upscale to upscale existing images."
                    .to_string(),
            ),
            capabilities: ServerCapabilities::builder()
                .enable_tools()
                .enable_resources()
                .build(),
            ..Default::default()
        }
    }

    fn list_tools(
        &self,
        _params: Option<rmcp::model::PaginatedRequestParams>,
        _context: rmcp::service::RequestContext<rmcp::service::RoleServer>,
    ) -> impl std::future::Future<Output = Result<rmcp::model::ListToolsResult, McpError>> + Send + '_ {
        async move {
            use rmcp::model::{ListToolsResult, Tool};
            use schemars::schema_for;

            // image_generate tool
            let gen_schema = schema_for!(ImageGenerateToolParams);
            let gen_schema_value = serde_json::to_value(&gen_schema).unwrap_or_default();
            let gen_input_schema = match gen_schema_value {
                serde_json::Value::Object(map) => Arc::new(map),
                _ => Arc::new(serde_json::Map::new()),
            };

            // image_upscale tool
            let upscale_schema = schema_for!(ImageUpscaleToolParams);
            let upscale_schema_value = serde_json::to_value(&upscale_schema).unwrap_or_default();
            let upscale_input_schema = match upscale_schema_value {
                serde_json::Value::Object(map) => Arc::new(map),
                _ => Arc::new(serde_json::Map::new()),
            };

            Ok(ListToolsResult {
                tools: vec![
                    Tool {
                        name: Cow::Borrowed("image_generate"),
                        description: Some(Cow::Borrowed(
                            "Generate images from a text prompt using Google's Imagen API. \
                             Returns base64-encoded image data, local file paths, or storage URIs \
                             depending on output parameters."
                        )),
                        input_schema: gen_input_schema,
                        annotations: None,
                        icons: None,
                        meta: None,
                        output_schema: None,
                        title: None,
                    },
                    Tool {
                        name: Cow::Borrowed("image_upscale"),
                        description: Some(Cow::Borrowed(
                            "Upscale an image using Google's Imagen 4.0 Upscale API. \
                             Supports x2 and x4 upscale factors. \
                             Accepts base64 image data, local file path, or GCS URI as input. \
                             Returns base64-encoded image data, local file path, or storage URI."
                        )),
                        input_schema: upscale_input_schema,
                        annotations: None,
                        icons: None,
                        meta: None,
                        output_schema: None,
                        title: None,
                    },
                ],
                next_cursor: None,
                meta: None,
            })
        }
    }

    fn call_tool(
        &self,
        params: rmcp::model::CallToolRequestParams,
        _context: rmcp::service::RequestContext<rmcp::service::RoleServer>,
    ) -> impl std::future::Future<Output = Result<CallToolResult, McpError>> + Send + '_ {
        async move {
            match params.name.as_ref() {
                "image_generate" => {
                    let tool_params: ImageGenerateToolParams = params
                        .arguments
                        .map(|args| serde_json::from_value(serde_json::Value::Object(args)))
                        .transpose()
                        .map_err(|e| McpError::invalid_params(format!("Invalid parameters: {}", e), None))?
                        .ok_or_else(|| McpError::invalid_params("Missing parameters", None))?;

                    self.generate_image(tool_params).await
                }
                "image_upscale" => {
                    let tool_params: ImageUpscaleToolParams = params
                        .arguments
                        .map(|args| serde_json::from_value(serde_json::Value::Object(args)))
                        .transpose()
                        .map_err(|e| McpError::invalid_params(format!("Invalid parameters: {}", e), None))?
                        .ok_or_else(|| McpError::invalid_params("Missing parameters", None))?;

                    self.upscale_image(tool_params).await
                }
                _ => Err(McpError::invalid_params(format!("Unknown tool: {}", params.name), None)),
            }
        }
    }

    fn list_resources(
        &self,
        _params: Option<rmcp::model::PaginatedRequestParams>,
        _context: rmcp::service::RequestContext<rmcp::service::RoleServer>,
    ) -> impl std::future::Future<Output = Result<ListResourcesResult, McpError>> + Send + '_ {
        async move {
            debug!("Listing resources");
            
            // Build resources using the raw struct approach
            let models_resource = rmcp::model::Resource {
                raw: rmcp::model::RawResource {
                    uri: "image://models".to_string(),
                    name: "Available Image Models".to_string(),
                    title: None,
                    description: Some("List of available image generation models".to_string()),
                    mime_type: Some("application/json".to_string()),
                    size: None,
                    icons: None,
                    meta: None,
                },
                annotations: None,
            };

            let segmentation_resource = rmcp::model::Resource {
                raw: rmcp::model::RawResource {
                    uri: "image://segmentation_classes".to_string(),
                    name: "Segmentation Classes".to_string(),
                    title: None,
                    description: Some("List of segmentation classes for image editing (Google provider)".to_string()),
                    mime_type: Some("application/json".to_string()),
                    size: None,
                    icons: None,
                    meta: None,
                },
                annotations: None,
            };

            let providers_resource = rmcp::model::Resource {
                raw: rmcp::model::RawResource {
                    uri: "image://providers".to_string(),
                    name: "Available Providers".to_string(),
                    title: None,
                    description: Some("List of available image generation providers".to_string()),
                    mime_type: Some("application/json".to_string()),
                    size: None,
                    icons: None,
                    meta: None,
                },
                annotations: None,
            };

            Ok(ListResourcesResult {
                resources: vec![models_resource, segmentation_resource, providers_resource],
                next_cursor: None,
                meta: None,
            })
        }
    }

    fn read_resource(
        &self,
        params: rmcp::model::ReadResourceRequestParams,
        _context: rmcp::service::RequestContext<rmcp::service::RoleServer>,
    ) -> impl std::future::Future<Output = Result<ReadResourceResult, McpError>> + Send + '_ {
        async move {
            let uri = &params.uri;
            debug!(uri = %uri, "Reading resource");

            let content = match uri.as_str() {
                "image://models" => resources::models_resource_json(),
                "image://segmentation_classes" => resources::segmentation_classes_resource_json(),
                "image://providers" => resources::providers_resource_json(),
                _ => {
                    return Err(McpError::resource_not_found(
                        format!("Unknown resource: {}", uri),
                        None,
                    ));
                }
            };

            Ok(ReadResourceResult {
                contents: vec![ResourceContents::text(content, uri.clone())],
            })
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn test_config() -> Config {
        Config {
            project_id: "test-project".to_string(),
            location: "us-central1".to_string(),
            gcs_bucket: None,
            port: 8080,
        ..Default::default()
        }
    }

    #[test]
    fn test_server_info() {
        let server = ImageServer::new(test_config());
        let info = server.get_info();
        assert!(info.instructions.is_some());
    }

    #[test]
    fn test_tool_params_conversion() {
        let tool_params = ImageGenerateToolParams {
            prompt: "A cat".to_string(),
            negative_prompt: Some("blurry".to_string()),
            model: Some("imagen-4".to_string()),
            aspect_ratio: Some("16:9".to_string()),
            number_of_images: Some(2),
            seed: Some(42),
            output_file: None,
            output_uri: None,
        };

        let gen_params: ImageGenerateParams = tool_params.into();
        assert_eq!(gen_params.prompt, "A cat");
        assert_eq!(gen_params.negative_prompt, Some("blurry".to_string()));
        assert_eq!(gen_params.model, "imagen-4");
        assert_eq!(gen_params.aspect_ratio, "16:9");
        assert_eq!(gen_params.number_of_images, 2);
        assert_eq!(gen_params.seed, Some(42));
    }

    #[test]
    fn test_tool_params_defaults() {
        let tool_params = ImageGenerateToolParams {
            prompt: "A cat".to_string(),
            negative_prompt: None,
            model: None,
            aspect_ratio: None,
            number_of_images: None,
            seed: None,
            output_file: None,
            output_uri: None,
        };

        let gen_params: ImageGenerateParams = tool_params.into();
        assert_eq!(gen_params.model, crate::handler::DEFAULT_MODEL);
        assert_eq!(gen_params.aspect_ratio, "1:1");
        assert_eq!(gen_params.number_of_images, 1);
    }
}