-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathserver.ts
385 lines (324 loc) · 9.76 KB
/
server.ts
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
#!/usr/bin/env node
import express from "express";
import path from "path";
import { fileURLToPath } from "url";
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListResourcesRequestSchema,
ListToolsRequestSchema,
ReadResourceRequestSchema,
ToolSchema,
SamplingMessageSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { z } from "zod";
/** EXPRESS SERVER SETUP */
let clients = new Map<string, express.Response>();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
function getPort(): number {
const portArg = process.argv[2];
if (portArg && !isNaN(Number(portArg))) {
return Number(portArg);
}
return 3333;
}
const PORT = process.env.PORT || getPort();
// Important: Serve the dist directory directly
app.use(express.static(__dirname));
// Simple health check
app.get("/api/health", (_, res) => {
res.json({ status: "ok" });
});
// Store clients with their resolve functions
let captureCallbacks = new Map<
string,
(response: string | { error: string }) => void
>();
// We don't need a separate sampling callbacks map since we're using the SDK directly
app.get("/api/events", (req, res) => {
console.error("New SSE connection request");
// SSE setup
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
// Generate a unique client ID
const clientId = Math.random().toString(36).substring(7);
// Add this client to our connected clients
clients.set(clientId, res);
console.error("Client connected - DEBUG INFO:", clientId);
// Send initial connection message
const connectMessage = JSON.stringify({ type: "connected", clientId });
res.write(`data: ${connectMessage}\n\n`);
// Remove client when they disconnect
req.on("close", () => {
clients.delete(clientId);
console.error("Client disconnected - DEBUG INFO:", clientId);
});
});
app.post("/api/capture-result", express.json({ limit: "50mb" }), (req, res) => {
const { clientId, image } = req.body;
const callback = captureCallbacks.get(clientId);
if (callback) {
callback(image);
captureCallbacks.delete(clientId);
}
res.json({ success: true });
});
// Add this near other endpoint definitions
app.post("/api/capture-error", express.json(), (req, res) => {
const { clientId, error } = req.body;
const callback = captureCallbacks.get(clientId);
if (callback) {
callback({ error: error.message || "Unknown error occurred" });
captureCallbacks.delete(clientId);
}
res.json({ success: true });
});
// We don't need these endpoints as we're using the SDK's built-in sampling capabilities
// For any other route, send the index.html file
app.get("*", (_, res) => {
// Important: Send the built index.html
res.sendFile(path.join(__dirname, "index.html"));
});
app.listen(PORT, () => {
console.error(`Server is running on port ${PORT}`);
});
/** MCP Server Setup */
const ToolInputSchema = ToolSchema.shape.inputSchema;
type ToolInput = z.infer<typeof ToolInputSchema>;
const server = new Server(
{
name: "mcp-webcam",
version: "0.1.0",
},
{
capabilities: {
tools: {},
resources: {},
},
}
);
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: "capture",
description:
"Gets the latest picture from the webcam. You can use this " +
" if the human asks questions about their immediate environment, " +
"if you want to see the human or to examine an object they may be " +
"referring to or showing you.",
inputSchema: { type: "object", parameters: {} } as ToolInput,
},
{
name: "screenshot",
description: "Gets a screenshot of the current screen or window",
inputSchema: { type: "object", parameters: {} } as ToolInput,
},
],
};
});
server.setRequestHandler(CallToolRequestSchema, async (request) => {
if (0 === clients.size) {
return {
isError: true,
content: [
{
type: "text",
text: `Have you opened your web browser?. Direct the human to go to http://localhost:${getPort()}, switch on their webcam and try again.`,
},
],
};
}
const clientId = Array.from(clients.keys())[0];
if (!clientId) {
throw new Error("No clients connected");
}
// Modified promise to handle both success and error cases
const result = await new Promise<string | { error: string }>((resolve) => {
console.error(`Capturing for ${clientId}`);
captureCallbacks.set(clientId, resolve);
clients
.get(clientId)
?.write(`data: ${JSON.stringify({ type: request.params.name })}\n\n`);
});
// Handle error case
if (typeof result === "object" && "error" in result) {
return {
isError: true,
content: [
{
type: "text",
text: `Failed to capture ${request.params.name}: ${result.error}`,
},
],
};
}
const { mimeType, base64Data } = parseDataUrl(result);
const message =
request.params.name === "screenshot"
? "Here is the requested screenshot"
: "Here is the latest image from the Webcam";
return {
content: [
{
type: "text",
text: message,
},
{
type: "image",
data: base64Data,
mimeType: mimeType,
},
],
};
});
// Process sampling request from the web UI
async function processSamplingRequest(imageDataUrl: string): Promise<any> {
const { mimeType, base64Data } = parseDataUrl(imageDataUrl);
try {
// Create a sampling request to the client using the SDK's types
const result = await server.createMessage({
messages: [
{
role: "user",
content: {
type: "text",
text: "What is the user holding?"
}
},
{
role: "user",
content: {
type: "image",
data: base64Data,
mimeType: mimeType
}
}
],
maxTokens: 1000, // Reasonable limit for the response
});
return result;
} catch (error) {
console.error("Error during sampling:", error);
throw error;
}
}
// Handle SSE 'sample' event from WebcamCapture component
app.post("/api/process-sample", express.json({ limit: "50mb" }), async (req, res) => {
const { image } = req.body;
if (!image) {
res.status(400).json({ error: "Missing image data" });
return;
}
try {
const result = await processSamplingRequest(image);
res.json({ success: true, result });
} catch (error) {
console.error("Sampling processing error:", error);
res.status(500).json({
error: String(error),
errorDetail: error instanceof Error ? error.stack : undefined
});
}
});
server.setRequestHandler(ListResourcesRequestSchema, async () => {
if (clients.size === 0) return { resources: [] };
return {
resources: [
{
uri: "webcam://current",
name: "Current view from the Webcam",
mimeType: "image/jpeg", // probably :)
},
],
};
});
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
// Check if we have any connected clients
if (0 === clients.size) {
throw new Error(
`No clients connected. Please visit http://localhost:${getPort()} and enable your Webcam.`
);
}
// Validate URI
if (request.params.uri !== "webcam://current") {
throw new Error(
"Invalid resource URI. Only webcam://current is supported."
);
}
const clientId = Array.from(clients.keys())[0];
// Capture image
const result = await new Promise<string | { error: string }>((resolve) => {
captureCallbacks.set(clientId, resolve);
clients
.get(clientId)
?.write(`data: ${JSON.stringify({ type: "capture" })}\n\n`);
});
// Handle error case
if (typeof result === "object" && "error" in result) {
throw new Error(`Failed to capture image: ${result.error}`);
}
// Parse the data URL
const { mimeType, base64Data } = parseDataUrl(result);
// Return in the blob format
return {
contents: [
{
uri: request.params.uri,
mimeType,
blob: base64Data,
},
],
};
});
interface ParsedDataUrl {
mimeType: string;
base64Data: string;
}
function parseDataUrl(dataUrl: string): ParsedDataUrl {
const matches = dataUrl.match(/^data:([^;]+);base64,(.+)$/);
if (!matches) {
throw new Error("Invalid data URL format");
}
return {
mimeType: matches[1],
base64Data: matches[2],
};
}
async function main() {
const transport = new StdioServerTransport();
async function handleShutdown(reason = 'unknown') {
console.error(`Initiating shutdown (reason: ${reason})`);
try {
await transport.close();
process.exit(0);
} catch (error) {
console.error('Error during shutdown:', error);
process.exit(1);
}
}
// Handle transport closure (not called by Claude Desktop)
transport.onclose = () => {
handleShutdown('transport closed');
};
// Handle stdin/stdout events
process.stdin.on('end', () => handleShutdown('stdin ended')); // claude desktop on os x does this
process.stdin.on('close', () => handleShutdown('stdin closed'));
process.stdout.on('error', () => handleShutdown('stdout error'));
process.stdout.on('close', () => handleShutdown('stdout closed'));
try {
await server.connect(transport);
console.error('Server connected');
} catch (error) {
console.error('Failed to connect server:', error);
handleShutdown('connection failed');
}
}
main().catch((error) => {
console.error("Fatal error in main():", error);
process.exit(1);
});