-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathwebcam-server-factory.ts
More file actions
311 lines (272 loc) · 8.35 KB
/
webcam-server-factory.ts
File metadata and controls
311 lines (272 loc) · 8.35 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
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import {
ListResourcesRequestSchema,
ReadResourceRequestSchema,
InitializeRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import type { ServerFactory } from "./transport/base-transport.js";
import { Logger } from "./utils/logger.js";
// Store clients with their resolve functions, grouped by user
export let clients = new Map<string, Map<string, any>>(); // user -> clientId -> response
export let captureCallbacks = new Map<
string,
Map<string, (response: string | { error: string }) => void>
>(); // user -> clientId -> callback
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],
};
}
function getPort(): number {
// Check command line argument first (from process.argv)
const args = process.argv.slice(2);
const portArgIndex = args.findIndex(arg => arg === '-p' || arg === '--port');
if (portArgIndex !== -1 && portArgIndex + 1 < args.length) {
const portValue = parseInt(args[portArgIndex + 1]);
if (!isNaN(portValue)) {
return portValue;
}
}
// Check positional argument for backward compatibility
const lastArg = args[args.length - 1];
if (lastArg && !lastArg.startsWith('-') && !isNaN(Number(lastArg))) {
return Number(lastArg);
}
// Check environment variable
if (process.env.PORT) {
return parseInt(process.env.PORT);
}
return 3333;
}
function getMcpHost(): string {
return process.env.MCP_HOST || `http://localhost:${getPort()}`;
}
// Helper functions for user-scoped client management
export function getUserClients(user: string): Map<string, any> {
if (!clients.has(user)) {
clients.set(user, new Map());
}
return clients.get(user)!;
}
export function getUserCallbacks(user: string): Map<string, (response: string | { error: string }) => void> {
if (!captureCallbacks.has(user)) {
captureCallbacks.set(user, new Map());
}
return captureCallbacks.get(user)!;
}
/**
* Factory function to create and configure an MCP server instance with webcam capabilities
*/
export const createWebcamServer: ServerFactory = async (user: string = 'default') => {
const mcpServer = new McpServer(
{
name: "mcp-webcam",
version: "0.1.0",
},
{
capabilities: {
tools: {},
resources: {},
sampling: {}, // Enable sampling capability
},
}
);
// Set up resource handlers
mcpServer.server.setRequestHandler(ListResourcesRequestSchema, async () => {
const userClients = getUserClients(user);
if (userClients.size === 0) return { resources: [] };
return {
resources: [
{
uri: "webcam://current",
name: "Current view from the Webcam",
mimeType: "image/jpeg", // probably :)
},
],
};
});
mcpServer.server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
// Check if we have any connected clients for this user
const userClients = getUserClients(user);
if (userClients.size === 0) {
throw new Error(
`No clients connected for user '${user}'. Please visit ${getMcpHost()}${user !== 'default' ? `?user=${user}` : ''} 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(userClients.keys())[0];
const userCallbacks = getUserCallbacks(user);
// Capture image
const result = await new Promise<string | { error: string }>((resolve) => {
userCallbacks.set(clientId, resolve);
userClients
.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,
},
],
};
});
// Define tools using the modern McpServer tool method
mcpServer.tool(
"capture",
"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.",
{},
{
openWorldHint: true,
readOnlyHint: true,
title: "Take a Picture from the webcam",
},
async () => {
const userClients = getUserClients(user);
if (userClients.size === 0) {
return {
isError: true,
content: [
{
type: "text",
text: `Have you opened your web browser?. Direct the human to go to ${getMcpHost()}${user !== 'default' ? `?user=${user}` : ''}, switch on their webcam and try again.`,
},
],
};
}
const clientId = Array.from(userClients.keys())[0];
if (!clientId) {
throw new Error("No clients connected");
}
const userCallbacks = getUserCallbacks(user);
// Modified promise to handle both success and error cases
const result = await new Promise<string | { error: string }>(
(resolve) => {
Logger.info(`Capturing for ${clientId} (user: ${user}`);
userCallbacks.set(clientId, resolve);
userClients
.get(clientId)
?.write(`data: ${JSON.stringify({ type: "capture" })}\n\n`);
}
);
// Handle error case
if (typeof result === "object" && "error" in result) {
return {
isError: true,
content: [
{
type: "text",
text: `Failed to capture: ${result.error}`,
},
],
};
}
const { mimeType, base64Data } = parseDataUrl(result);
return {
content: [
{
type: "text",
text: "Here is the latest image from the Webcam",
},
{
type: "image",
data: base64Data,
mimeType: mimeType,
},
],
};
}
);
mcpServer.tool(
"screenshot",
"Gets a screenshot of the current screen or window",
{},
{
openWorldHint: true,
readOnlyHint: true,
title: "Take a Screenshot",
},
async () => {
const userClients = getUserClients(user);
if (userClients.size === 0) {
return {
isError: true,
content: [
{
type: "text",
text: `Have you opened your web browser?. Direct the human to go to ${getMcpHost()}?user=${user}, switch on their webcam and try again.`,
},
],
};
}
const clientId = Array.from(userClients.keys())[0];
if (!clientId) {
throw new Error("No clients connected");
}
const userCallbacks = getUserCallbacks(user);
// Modified promise to handle both success and error cases
const result = await new Promise<string | { error: string }>(
(resolve) => {
Logger.info(`Taking screenshot for ${clientId} (user: ${user}`);
userCallbacks.set(clientId, resolve);
userClients
.get(clientId)
?.write(`data: ${JSON.stringify({ type: "screenshot" })}\n\n`);
}
);
// Handle error case
if (typeof result === "object" && "error" in result) {
return {
isError: true,
content: [
{
type: "text",
text: `Failed to capture screenshot: ${result.error}`,
},
],
};
}
const { mimeType, base64Data } = parseDataUrl(result);
return {
content: [
{
type: "text",
text: "Here is the requested screenshot",
},
{
type: "image",
data: base64Data,
mimeType: mimeType,
},
],
};
}
);
return mcpServer;
};