This repository was archived by the owner on Jan 3, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
237 lines (208 loc) · 10.7 KB
/
Program.cs
File metadata and controls
237 lines (208 loc) · 10.7 KB
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
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using ModelContextProtocol.Server;
using OpenAI.Images;
using System.ComponentModel;
using System.Text;
using System.Text.Json;
var builder = Host.CreateApplicationBuilder(args);
builder.Logging.AddConsole(consoleLogOptions =>
{
// Configure all logs to go to stderr
consoleLogOptions.LogToStandardErrorThreshold = LogLevel.Trace;
});
builder.Services
.AddMcpServer()
.WithStdioServerTransport()
.WithToolsFromAssembly();
builder.Services.AddSingleton(_ =>
{
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(
"Bearer",
Environment.GetEnvironmentVariable("OPENAI_API_KEY"));
return httpClient;
});
await builder.Build().RunAsync();
[McpServerToolType]
public static class OpenAITools
{
[McpServerTool, Description("Creates an image given a prompt.")]
public static async Task<string> CreateImage(
HttpClient httpClient,
[Description("A text description of the desired image. The maximum length is 32000 characters.")]
string prompt,
[Description("The path of the generated image. Must be absolute path.")]
string outputPath,
[Description("Allows to set transparency for the background of the generated image. Must be one of transparent, opaque or auto (default value). When auto is used, the model will automatically determine the best background for the image. If transparent, the output format needs to support transparency, so it should be set to either png (default value) or webp.")]
string background = "auto",
[Description("Control the content-moderation level for image. Must be either low for less (default value) restrictive filtering or auto.")]
string moderation = "low",
[Description("The compression level (0-100%) for the generated image. This parameter is only supported for the webp or jpeg output formats, and defaults to 100.")]
int outputCompression = 100,
[Description("The format in which the generated image is returned. Must be one of png, jpeg, or webp. Defaults to png.")]
string outputFormat = "png",
[Description("The quality of the image that will be generated. Must be one of auto (default value), high, medium or low.")]
string quality = "auto",
[Description("The size of the generated images. Must be one of 1024x1024, 1536x1024 (landscape), 1024x1536 (portrait), or auto (default value).")]
string size = "auto")
{
try
{
var apiEndpoint = "https://api.openai.com/v1/images/generations";
var model = "gpt-image-1";
var parameters = new Dictionary<string, object>
{
["prompt"] = prompt,
["background"] = background,
["model"] = model,
["moderation"] = moderation,
["output_compression"] = outputCompression,
["output_format"] = outputFormat,
["quality"] = quality,
["size"] = size,
};
var postContent = new StringContent(JsonSerializer.Serialize(parameters), Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync(apiEndpoint, postContent);
if (response.IsSuccessStatusCode)
{
var jsonDocument = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
using (var stream = new FileStream(outputPath, FileMode.Create))
{
var bytes = jsonDocument.RootElement
.GetProperty("data")[0]
.GetProperty("b64_json")
.GetBytesFromBase64();
stream.Write(bytes);
}
return $"Image is generated to {outputPath}";
}
else
{
var responseString = await response.Content.ReadAsStringAsync();
return $"An error occurred: {responseString}";
}
}
catch (Exception e)
{
return $"An error occurred: {e}";
}
}
[McpServerTool, Description("Creates an edited or extended image given one or more source images and a prompt. You can edit or modify image by using this tool.")]
public static async Task<string> CreateImageEdit(
HttpClient httpClient,
[Description("The paths of source images to edit. Must be a png, webp, or jpg file less than 25MB.")]
string[] inputPaths,
[Description("A text description of the desired image. The maximum length is 32000 characters.")]
string prompt,
[Description("The path of the generated image. Must be absolute path.")]
string outputPath,
[Description("The path of an additional image whose fully transparent areas (e.g. where alpha is zero) indicate where image should be edited. Must be a valid PNG file, less than 4MB, and have the same dimensions as image. Optional.")]
string maskPath = "",
[Description("The quality of the image that will be generated. Must be one of auto (default value), high, medium or low.")]
string quality = "auto",
[Description("The size of the generated images. Must be one of 1024x1024, 1536x1024 (landscape), 1024x1536 (portrait), or auto (default value).")]
string size = "auto")
{
try
{
var apiEndpoint = "https://api.openai.com/v1/images/edits";
var model = "gpt-image-1";
using var postContent = new MultipartFormDataContent();
foreach (var inputPath in inputPaths)
{
var inputStream = new FileStream(inputPath, FileMode.Open);
postContent.Add(new StreamContent(inputStream), "image[]", Path.GetFileName(inputPath));
}
using var maskStream = !string.IsNullOrEmpty(maskPath) ? new FileStream(maskPath, FileMode.Open) : null;
if (maskStream != null)
{
postContent.Add(new StreamContent(maskStream), "mask", Path.GetFileName(maskPath));
}
postContent.Add(new StringContent(prompt), "prompt");
postContent.Add(new StringContent(model), "model");
postContent.Add(new StringContent(quality), "quality");
postContent.Add(new StringContent(size), "size");
var response = await httpClient.PostAsync(apiEndpoint, postContent);
if (response.IsSuccessStatusCode)
{
var jsonDocument = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
using (var stream = new FileStream(outputPath, FileMode.Create))
{
var bytes = jsonDocument.RootElement
.GetProperty("data")[0]
.GetProperty("b64_json")
.GetBytesFromBase64();
stream.Write(bytes);
}
return $"Edited image is generated to {outputPath}";
}
else
{
var responseString = await response.Content.ReadAsStringAsync();
return $"An error occurred: {responseString}";
}
}
catch (Exception e)
{
return $"An error occurred: {e}";
}
}
[McpServerTool, Description("Creates an image given a prompt using legacy models.")]
public static async Task<string> CreateImageLegacy(
[Description("A text description of the desired image(s). The maximum length is 1000 characters for dall-e-2 and 4000 characters for dall-e-3.")]
string prompt,
[Description("The path of the generated image. Must be absolute path.")]
string outputPath,
[Description("The model to use for image generation. Must be dall-e-2 or dall-e-3. Defaults to dall-e-3.")]
string model = "dall-e-3",
[Description("The quality of the image that will be generated. hd creates images with finer details and greater consistency across the image. This param is only supported for dall-e-3. Must be hd or standard. Defaults to standard.")]
string quality = "standard",
[Description("The size of the generated images. Must be one of 256x256, 512x512, or 1024x1024 for dall-e-2. Must be one of 1024x1024, 1792x1024, or 1024x1792 for dall-e-3 models. Defaults to 1024x1024.")]
string size = "1024x1024",
[Description("The style of the generated images. Must be one of vivid or natural. Vivid causes the model to lean towards generating hyper-real and dramatic images. Natural causes the model to produce more natural, less hyper-real looking images. This param is only supported for dall-e-3. Defaults to vivid.")]
string style = "vivid")
{
try
{
var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY");
var client = new ImageClient(model, apiKey);
var options = new ImageGenerationOptions()
{
ResponseFormat = GeneratedImageFormat.Bytes,
};
switch (quality)
{
case "hd": options.Quality = GeneratedImageQuality.High; break;
case "standard": options.Quality = GeneratedImageQuality.Standard; break;
default: throw new ArgumentException("Invalid argument 'quality'.");
}
switch (size)
{
case "256x256": options.Size = GeneratedImageSize.W256xH256; break;
case "512x512": options.Size = GeneratedImageSize.W512xH512; break;
case "1024x1024": options.Size = GeneratedImageSize.W1024xH1024; break;
case "1792x1024": options.Size = GeneratedImageSize.W1792xH1024; break;
case "1024x1792": options.Size = GeneratedImageSize.W1024xH1792; break;
default: throw new ArgumentException("Invalid argument 'size'.");
}
switch (style)
{
case "vivid": options.Style = GeneratedImageStyle.Vivid; break;
case "natural": options.Style = GeneratedImageStyle.Natural; break;
default: throw new ArgumentException("Invalid argument 'style'.");
}
var response = await client.GenerateImageAsync(prompt, options);
using (var stream = new FileStream(outputPath, FileMode.Create))
{
response.Value.ImageBytes.ToStream().CopyTo(stream);
}
return $"Image is generated to {outputPath}";
}
catch (Exception e)
{
return $"An error occurred: {e}";
}
}
}