-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
382 lines (351 loc) · 11.5 KB
/
Copy pathindex.js
File metadata and controls
382 lines (351 loc) · 11.5 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
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
#!/usr/bin/env node
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import https from "https";
import http from "http";
const IMAGE_URL =
"https://i.natgeofe.com/n/548467d8-c5f1-4551-9f58-6817a8d2c45e/NationalGeographic_2572187_16x9.jpg?w=1200";
class ImageServer {
constructor() {
this.transports = new Map();
this.errorHandler();
}
createServer() {
const server = new Server(
{
name: "image-server",
version: "1.0.0",
},
{
capabilities: {
tools: {},
},
}
);
// List available tools
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: "get_image",
description: "Get image in binary format from the configured URL",
inputSchema: {
type: "object",
properties: {},
required: [],
},
},
{
name: "get_image_invalid",
description: "Get image in binary format from the configured URL",
inputSchema: {
type: "object",
properties: {},
required: [],
},
},
{
name: "dummy_tool",
description: "A dummy tool demonstrating all possible input types and schema features",
inputSchema: {
type: "object",
properties: {
// String types
stringField: {
type: "string",
description: "A simple string field",
default: "default value",
},
stringWithPattern: {
type: "string",
description: "String with regex pattern (email format)",
pattern: "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$",
},
stringWithLength: {
type: "string",
description: "String with min and max length",
minLength: 3,
maxLength: 100,
},
stringEnum: {
type: "string",
description: "String with enum values",
enum: ["option1", "option2", "option3"],
default: "option1",
},
// Number types
numberField: {
type: "number",
description: "A floating point number",
minimum: 0,
maximum: 100,
default: 42.5,
},
numberMultipleOf: {
type: "number",
description: "Number that must be a multiple of 2.5",
multipleOf: 2.5,
},
// Integer types
integerField: {
type: "integer",
description: "An integer field",
minimum: -100,
maximum: 100,
default: 0,
},
integerExclusive: {
type: "integer",
description: "Integer with exclusive minimum and maximum",
exclusiveMinimum: 0,
exclusiveMaximum: 100,
},
// Boolean type
booleanField: {
type: "boolean",
description: "A boolean field",
default: false,
},
// Array types
arrayOfStrings: {
type: "array",
description: "Array of strings",
items: {
type: "string",
},
minItems: 1,
maxItems: 10,
default: [],
},
arrayOfNumbers: {
type: "array",
description: "Array of numbers",
items: {
type: "number",
},
},
arrayOfObjects: {
type: "array",
description: "Array of objects",
items: {
type: "object",
properties: {
id: { type: "integer" },
name: { type: "string" },
},
required: ["id", "name"],
},
},
// Object types
objectField: {
type: "object",
description: "A nested object",
properties: {
nestedString: {
type: "string",
description: "Nested string property",
},
nestedNumber: {
type: "number",
description: "Nested number property",
},
deeplyNested: {
type: "object",
description: "Deeply nested object",
properties: {
value: { type: "string" },
},
},
},
required: ["nestedString"],
},
// Null type
nullableField: {
type: ["string", "null"],
description: "A field that can be string or null",
default: null,
},
// OneOf/AnyOf examples (using enum-like behavior)
choiceField: {
description: "Field that accepts multiple types",
oneOf: [
{ type: "string" },
{ type: "number" },
{ type: "boolean" },
],
},
// Additional constraints
urlField: {
type: "string",
description: "String that should be a URL",
format: "uri",
},
dateField: {
type: "string",
description: "String that should be a date",
format: "date",
},
dateTimeField: {
type: "string",
description: "String that should be a date-time",
format: "date-time",
},
},
required: [
"stringField",
"integerField",
"booleanField",
"arrayOfStrings",
"objectField",
],
},
},
],
};
});
// Handle tool calls
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
if (name === "get_image" || name === "get_image_invalid") {
try {
const imageData = await this.fetchImage(IMAGE_URL);
// Return the image as base64 encoded binary data in data URI format
const base64Data = imageData.toString("base64");
const dataUri = `${base64Data}`;
if (name === "get_image_invalid") {
return {
content: [
{
type: "image",
data: dataUri,
},
],
};
}
return {
content: [
{
type: "image",
data: dataUri,
mimeType: "image/jpeg",
},
],
};
} catch (error) {
console.error("Error fetching image:", error);
return {
content: [
{
type: "text",
text: `Error fetching image: ${error.message}`,
},
],
isError: true,
};
}
}
if (name === "dummy_tool") {
// Echo back the received arguments as a formatted response
return {
content: [
{
type: "text",
text: `Dummy tool called with arguments:\n${JSON.stringify(args, null, 2)}`,
},
],
};
}
throw new Error(`Unknown tool: ${name}`);
});
server.onerror = (error) => {
console.error("[MCP Error]", error);
};
return server;
}
async fetchImage(url) {
return new Promise((resolve, reject) => {
const protocol = url.startsWith("https") ? https : http;
protocol
.get(url, (response) => {
if (response.statusCode !== 200) {
reject(
new Error(
`Failed to fetch image: ${response.statusCode} ${response.statusMessage}`
)
);
return;
}
const chunks = [];
response.on("data", (chunk) => chunks.push(chunk));
response.on("end", () => {
resolve(Buffer.concat(chunks));
});
response.on("error", reject);
})
.on("error", reject);
});
}
errorHandler() {
process.on("SIGINT", async () => {
// Close all transports
for (const { transport, server } of this.transports.values()) {
await transport.close();
await server.close();
}
process.exit(0);
});
}
async run() {
const PORT = 6006;
const ENDPOINT = "/message";
// Create HTTP server
const httpServer = http.createServer(async (req, res) => {
// Handle CORS
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
if (req.method === "OPTIONS") {
res.writeHead(200).end();
return;
}
// Handle GET request for SSE connection
if (req.method === "GET" && req.url === "/sse") {
const transport = new SSEServerTransport(ENDPOINT, res);
const server = this.createServer();
// Store transport before connecting
this.transports.set(transport.sessionId, { transport, server });
// Set up cleanup on close
transport.onclose = () => {
this.transports.delete(transport.sessionId);
};
await server.connect(transport);
return;
}
// Handle POST request for messages
if (req.method === "POST" && req.url?.startsWith(ENDPOINT)) {
// Find the transport by session ID from query string
const url = new URL(req.url, `http://${req.headers.host}`);
const sessionId = url.searchParams.get("sessionId");
if (!sessionId || !this.transports.has(sessionId)) {
res.writeHead(404).end("Session not found");
return;
}
const { transport } = this.transports.get(sessionId);
await transport.handlePostMessage(req, res);
return;
}
res.writeHead(404).end("Not found");
});
httpServer.listen(PORT, () => {
console.error(`Image MCP server running on port ${PORT}`);
console.error(`SSE endpoint: http://localhost:${PORT}/sse`);
console.error(`Message endpoint: http://localhost:${PORT}${ENDPOINT}`);
});
}
}
const server = new ImageServer();
server.run().catch(console.error);