yuxh1996 commited on
Commit
d45a618
Β·
1 Parent(s): 63d8486

Implement official Gradio MCP server

Browse files

- Follow official Gradio MCP documentation
- Use gradio[mcp]>=5.0.0 with mcp_server=True
- Create official_app.py with proper MCP tool functions
- Add detailed docstrings for all AI tools
- Support background removal, image upscaling, generation, vectorization, extension, and video upscaling
- Update README.md to use official implementation

Files changed (5) hide show
  1. .env.example +0 -1
  2. README.md +2 -2
  3. minimal_app.py +132 -0
  4. official_app.py +206 -0
  5. requirements.txt +1 -1
.env.example CHANGED
@@ -4,7 +4,6 @@
4
  # A1D API Key (Required)
5
  # Get your API key from: https://a1d.ai/home/api
6
  A1D_API_KEY=z4Zl7OhAM5r-DxyVFDN1A
7
-
8
  # Optional: Gradio Configuration
9
  # GRADIO_SERVER_NAME=0.0.0.0
10
  # GRADIO_SERVER_PORT=7860
 
4
  # A1D API Key (Required)
5
  # Get your API key from: https://a1d.ai/home/api
6
  A1D_API_KEY=z4Zl7OhAM5r-DxyVFDN1A
 
7
  # Optional: Gradio Configuration
8
  # GRADIO_SERVER_NAME=0.0.0.0
9
  # GRADIO_SERVER_PORT=7860
README.md CHANGED
@@ -4,8 +4,8 @@ emoji: πŸ€–
4
  colorFrom: blue
5
  colorTo: purple
6
  sdk: gradio
7
- sdk_version: 4.32.0
8
- app_file: simple_app.py
9
  pinned: false
10
  license: mit
11
  tags:
 
4
  colorFrom: blue
5
  colorTo: purple
6
  sdk: gradio
7
+ sdk_version: 5.33.0
8
+ app_file: official_app.py
9
  pinned: false
10
  license: mit
11
  tags:
minimal_app.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Minimal A1D MCP Server with Gradio - Ultra-simple version to avoid all compatibility issues
4
+ """
5
+
6
+ import gradio as gr
7
+ import os
8
+ from utils import A1DAPIClient, prepare_request_data, format_response_with_preview
9
+ from config import TOOLS_CONFIG
10
+
11
+ def get_api_client():
12
+ """Get API client with current API key"""
13
+ api_key = os.getenv("A1D_API_KEY")
14
+ if not api_key:
15
+ raise ValueError("A1D_API_KEY environment variable is required")
16
+ return A1DAPIClient(api_key)
17
+
18
+ def process_remove_bg(image_url):
19
+ """Remove background from images using AI"""
20
+ try:
21
+ if not image_url or not image_url.strip():
22
+ return "❌ Error: Please provide an image URL"
23
+
24
+ client = get_api_client()
25
+ data = prepare_request_data("remove_bg", image_url=image_url)
26
+ response = client.make_request_with_result(
27
+ TOOLS_CONFIG["remove_bg"]["api_endpoint"],
28
+ data,
29
+ timeout=120
30
+ )
31
+ message, media_url = format_response_with_preview(response, "remove_bg")
32
+ return f"{message}\n\nResult URL: {media_url}" if media_url else message
33
+ except Exception as e:
34
+ return f"❌ Error: {str(e)}"
35
+
36
+ def process_upscale(image_url, scale):
37
+ """Upscale images using AI"""
38
+ try:
39
+ if not image_url or not image_url.strip():
40
+ return "❌ Error: Please provide an image URL"
41
+
42
+ client = get_api_client()
43
+ data = prepare_request_data("image_upscaler", image_url=image_url, scale=int(scale))
44
+ response = client.make_request_with_result(
45
+ TOOLS_CONFIG["image_upscaler"]["api_endpoint"],
46
+ data,
47
+ timeout=120
48
+ )
49
+ message, media_url = format_response_with_preview(response, "image_upscaler")
50
+ return f"{message}\n\nResult URL: {media_url}" if media_url else message
51
+ except Exception as e:
52
+ return f"❌ Error: {str(e)}"
53
+
54
+ def process_generate(prompt):
55
+ """Generate images using AI from text prompts"""
56
+ try:
57
+ if not prompt or not prompt.strip():
58
+ return "❌ Error: Please provide a text prompt"
59
+
60
+ client = get_api_client()
61
+ data = prepare_request_data("image_generator", prompt=prompt)
62
+ response = client.make_request_with_result(
63
+ TOOLS_CONFIG["image_generator"]["api_endpoint"],
64
+ data,
65
+ timeout=120
66
+ )
67
+ message, media_url = format_response_with_preview(response, "image_generator")
68
+ return f"{message}\n\nResult URL: {media_url}" if media_url else message
69
+ except Exception as e:
70
+ return f"❌ Error: {str(e)}"
71
+
72
+ # Create the minimal Gradio interface
73
+ def create_minimal_interface():
74
+ """Create minimal interface with basic components only"""
75
+
76
+ # Background Removal Interface
77
+ bg_interface = gr.Interface(
78
+ fn=process_remove_bg,
79
+ inputs=gr.Textbox(label="Image URL", placeholder="https://example.com/image.jpg"),
80
+ outputs=gr.Textbox(label="Result"),
81
+ title="🎭 Background Removal",
82
+ description="Remove background from images using AI"
83
+ )
84
+
85
+ # Image Upscaler Interface
86
+ upscale_interface = gr.Interface(
87
+ fn=process_upscale,
88
+ inputs=[
89
+ gr.Textbox(label="Image URL", placeholder="https://example.com/image.jpg"),
90
+ gr.Radio(choices=["2", "4", "8", "16"], value="2", label="Scale Factor")
91
+ ],
92
+ outputs=gr.Textbox(label="Result"),
93
+ title="πŸ” Image Upscaler",
94
+ description="Upscale images using AI"
95
+ )
96
+
97
+ # Image Generator Interface
98
+ gen_interface = gr.Interface(
99
+ fn=process_generate,
100
+ inputs=gr.Textbox(label="Text Prompt", placeholder="A beautiful sunset over mountains...", lines=3),
101
+ outputs=gr.Textbox(label="Result"),
102
+ title="🎨 Image Generator",
103
+ description="Generate images using AI from text prompts"
104
+ )
105
+
106
+ # Create tabbed interface
107
+ demo = gr.TabbedInterface(
108
+ [bg_interface, upscale_interface, gen_interface],
109
+ ["Background Removal", "Image Upscaler", "Image Generator"],
110
+ title="πŸ€– A1D MCP Server - Universal AI Tools"
111
+ )
112
+
113
+ return demo
114
+
115
+ if __name__ == "__main__":
116
+ # Check for API key
117
+ if not os.getenv("A1D_API_KEY"):
118
+ print("❌ Error: A1D_API_KEY environment variable is required")
119
+ print("Please set your API key in the Space settings")
120
+ exit(1)
121
+
122
+ print("πŸš€ Starting A1D MCP Server (Minimal Version)...")
123
+ print("βœ… API key found")
124
+ print("🌐 Server will be available at: http://0.0.0.0:7860")
125
+
126
+ # Create and launch the minimal app
127
+ demo = create_minimal_interface()
128
+ demo.launch(
129
+ server_name="0.0.0.0",
130
+ server_port=7860,
131
+ share=False
132
+ )
official_app.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ A1D MCP Server with Gradio - Official MCP Implementation
4
+ Following Gradio's official MCP documentation
5
+ """
6
+
7
+ import gradio as gr
8
+ import os
9
+ from utils import A1DAPIClient, prepare_request_data, format_response_with_preview
10
+ from config import TOOLS_CONFIG
11
+
12
+ def get_api_client():
13
+ """Get API client with current API key"""
14
+ api_key = os.getenv("A1D_API_KEY")
15
+ if not api_key:
16
+ raise ValueError("A1D_API_KEY environment variable is required")
17
+ return A1DAPIClient(api_key)
18
+
19
+ def remove_background(image_url: str) -> str:
20
+ """
21
+ Remove background from images using AI.
22
+
23
+ Args:
24
+ image_url (str): The URL of the image to remove background from. Must be a valid HTTP/HTTPS URL pointing to an image file.
25
+
26
+ Returns:
27
+ str: A message indicating the result and the URL of the processed image.
28
+ """
29
+ try:
30
+ if not image_url or not image_url.strip():
31
+ return "❌ Error: Please provide an image URL"
32
+
33
+ client = get_api_client()
34
+ data = prepare_request_data("remove_bg", image_url=image_url)
35
+ response = client.make_request_with_result(
36
+ TOOLS_CONFIG["remove_bg"]["api_endpoint"],
37
+ data,
38
+ timeout=120
39
+ )
40
+ message, media_url = format_response_with_preview(response, "remove_bg")
41
+ return f"{message}\n\nResult URL: {media_url}" if media_url else message
42
+ except Exception as e:
43
+ return f"❌ Error: {str(e)}"
44
+
45
+ def upscale_image(image_url: str, scale: str = "2") -> str:
46
+ """
47
+ Upscale images using AI.
48
+
49
+ Args:
50
+ image_url (str): The URL of the image to upscale. Must be a valid HTTP/HTTPS URL pointing to an image file.
51
+ scale (str): Scale factor for upscaling. Choose from "2", "4", "8", or "16". Higher values produce larger images but take longer to process.
52
+
53
+ Returns:
54
+ str: A message indicating the result and the URL of the processed image.
55
+ """
56
+ try:
57
+ if not image_url or not image_url.strip():
58
+ return "❌ Error: Please provide an image URL"
59
+
60
+ client = get_api_client()
61
+ data = prepare_request_data("image_upscaler", image_url=image_url, scale=int(scale))
62
+ response = client.make_request_with_result(
63
+ TOOLS_CONFIG["image_upscaler"]["api_endpoint"],
64
+ data,
65
+ timeout=120
66
+ )
67
+ message, media_url = format_response_with_preview(response, "image_upscaler")
68
+ return f"{message}\n\nResult URL: {media_url}" if media_url else message
69
+ except Exception as e:
70
+ return f"❌ Error: {str(e)}"
71
+
72
+ def generate_image(prompt: str) -> str:
73
+ """
74
+ Generate images using AI from text prompts.
75
+
76
+ Args:
77
+ prompt (str): Text description of the image to generate. Be descriptive and specific for better results. Example: "A beautiful sunset over mountains with vibrant orange and purple colors".
78
+
79
+ Returns:
80
+ str: A message indicating the result and the URL of the generated image.
81
+ """
82
+ try:
83
+ if not prompt or not prompt.strip():
84
+ return "❌ Error: Please provide a text prompt"
85
+
86
+ client = get_api_client()
87
+ data = prepare_request_data("image_generator", prompt=prompt)
88
+ response = client.make_request_with_result(
89
+ TOOLS_CONFIG["image_generator"]["api_endpoint"],
90
+ data,
91
+ timeout=120
92
+ )
93
+ message, media_url = format_response_with_preview(response, "image_generator")
94
+ return f"{message}\n\nResult URL: {media_url}" if media_url else message
95
+ except Exception as e:
96
+ return f"❌ Error: {str(e)}"
97
+
98
+ def vectorize_image(image_url: str) -> str:
99
+ """
100
+ Convert images to vector format using AI.
101
+
102
+ Args:
103
+ image_url (str): The URL of the image to convert to vector format. Must be a valid HTTP/HTTPS URL pointing to an image file.
104
+
105
+ Returns:
106
+ str: A message indicating the result and the URL of the vectorized image.
107
+ """
108
+ try:
109
+ if not image_url or not image_url.strip():
110
+ return "❌ Error: Please provide an image URL"
111
+
112
+ client = get_api_client()
113
+ data = prepare_request_data("image_vectorization", image_url=image_url)
114
+ response = client.make_request_with_result(
115
+ TOOLS_CONFIG["image_vectorization"]["api_endpoint"],
116
+ data,
117
+ timeout=120
118
+ )
119
+ message, media_url = format_response_with_preview(response, "image_vectorization")
120
+ return f"{message}\n\nResult URL: {media_url}" if media_url else message
121
+ except Exception as e:
122
+ return f"❌ Error: {str(e)}"
123
+
124
+ def extend_image(image_url: str) -> str:
125
+ """
126
+ Extend images using AI.
127
+
128
+ Args:
129
+ image_url (str): The URL of the image to extend. Must be a valid HTTP/HTTPS URL pointing to an image file.
130
+
131
+ Returns:
132
+ str: A message indicating the result and the URL of the extended image.
133
+ """
134
+ try:
135
+ if not image_url or not image_url.strip():
136
+ return "❌ Error: Please provide an image URL"
137
+
138
+ client = get_api_client()
139
+ data = prepare_request_data("image_extends", image_url=image_url)
140
+ response = client.make_request_with_result(
141
+ TOOLS_CONFIG["image_extends"]["api_endpoint"],
142
+ data,
143
+ timeout=120
144
+ )
145
+ message, media_url = format_response_with_preview(response, "image_extends")
146
+ return f"{message}\n\nResult URL: {media_url}" if media_url else message
147
+ except Exception as e:
148
+ return f"❌ Error: {str(e)}"
149
+
150
+ def upscale_video(video_url: str) -> str:
151
+ """
152
+ Upscale videos using AI.
153
+
154
+ Args:
155
+ video_url (str): The URL of the video to upscale. Must be a valid HTTP/HTTPS URL pointing to a video file (MP4, AVI, MOV, etc.).
156
+
157
+ Returns:
158
+ str: A message indicating the result and the URL of the upscaled video.
159
+ """
160
+ try:
161
+ if not video_url or not video_url.strip():
162
+ return "❌ Error: Please provide a video URL"
163
+
164
+ client = get_api_client()
165
+ data = prepare_request_data("video_upscaler", video_url=video_url)
166
+ response = client.make_request_with_result(
167
+ TOOLS_CONFIG["video_upscaler"]["api_endpoint"],
168
+ data,
169
+ timeout=300
170
+ )
171
+ message, media_url = format_response_with_preview(response, "video_upscaler")
172
+ return f"{message}\n\nResult URL: {media_url}" if media_url else message
173
+ except Exception as e:
174
+ return f"❌ Error: {str(e)}"
175
+
176
+ # Create the Gradio interface using the official MCP approach
177
+ demo = gr.Interface(
178
+ fn=remove_background,
179
+ inputs=[gr.Textbox(label="Image URL", placeholder="https://example.com/image.jpg", value="https://asset2.qieman.com/user-avatar/20240721/1071394_e15eb706-485d-4604-ad28-ac9830de1fe4.jpg")],
180
+ outputs=[gr.Textbox(label="Result")],
181
+ title="πŸ€– A1D MCP Server - Universal AI Tools",
182
+ description="Powerful AI image and video processing tools for any MCP-compatible client.",
183
+ examples=[
184
+ ["https://asset2.qieman.com/user-avatar/20240721/1071394_e15eb706-485d-4604-ad28-ac9830de1fe4.jpg"],
185
+ ["https://images.unsplash.com/photo-1506905925346-21bda4d32df4"]
186
+ ]
187
+ )
188
+
189
+ if __name__ == "__main__":
190
+ # Check for API key
191
+ if not os.getenv("A1D_API_KEY"):
192
+ print("❌ Error: A1D_API_KEY environment variable is required")
193
+ print("Please set your API key in the Space settings")
194
+ exit(1)
195
+
196
+ print("πŸš€ Starting A1D MCP Server (Official Implementation)...")
197
+ print("βœ… API key found")
198
+ print("🌐 MCP Server will be available at: /gradio_api/mcp/sse")
199
+
200
+ # Launch with MCP server enabled (official method)
201
+ demo.launch(
202
+ server_name="0.0.0.0",
203
+ server_port=7860,
204
+ share=False,
205
+ mcp_server=True # This is the official way to enable MCP
206
+ )
requirements.txt CHANGED
@@ -1,2 +1,2 @@
1
- gradio==4.32.0
2
  requests>=2.31.0
 
1
+ gradio[mcp]>=5.0.0
2
  requests>=2.31.0