-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcamera_mcp_server.py
More file actions
executable file
·385 lines (328 loc) · 14.6 KB
/
camera_mcp_server.py
File metadata and controls
executable file
·385 lines (328 loc) · 14.6 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
383
384
385
#!/usr/bin/env python3
"""
Camera Management MCP Server
Provides PTZ camera controls, screenshot capture, and camera discovery.
Integrates with webcam-ptz executable and imagesnap for comprehensive camera operations.
Tools provided:
- list_cameras: Get list of connected cameras
- take_screenshot: Capture image from specified camera
- ptz_control: Send PTZ commands to camera
- get_camera_status: Get current camera position/settings
"""
import asyncio
import json
import logging
import subprocess
import sys
import os
import tempfile
import base64
from typing import Any, Dict, List, Optional
from pathlib import Path
from datetime import datetime
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(sys.stderr)
]
)
logger = logging.getLogger(__name__)
class CameraManager:
def __init__(self):
self.webcam_ptz_path = "/Users/j/Code/logi-ptz/webcam-ptz/webcam-ptz"
self.imagesnap_path = "/opt/homebrew/bin/imagesnap"
self.camera_cache = {}
self.last_camera_scan = 0
async def _run_command(self, command: List[str], timeout: int = 30, stdin_input: str = None) -> Dict[str, Any]:
"""Execute command and return result"""
try:
logger.debug(f"Executing command: {' '.join(command)}")
process = await asyncio.create_subprocess_exec(
*command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
stdin=asyncio.subprocess.PIPE if stdin_input else None
)
try:
if stdin_input:
stdout, stderr = await asyncio.wait_for(
process.communicate(input=stdin_input.encode()), timeout=timeout
)
else:
stdout, stderr = await asyncio.wait_for(
process.communicate(), timeout=timeout
)
return {
"success": process.returncode == 0,
"stdout": stdout.decode('utf-8', errors='replace'),
"stderr": stderr.decode('utf-8', errors='replace'),
"exit_code": process.returncode
}
except asyncio.TimeoutError:
process.kill()
await process.wait()
return {
"success": False,
"error": f"Command timed out after {timeout}s",
"stdout": "",
"stderr": "",
"exit_code": -1
}
except Exception as e:
return {
"success": False,
"error": str(e),
"stdout": "",
"stderr": "",
"exit_code": -1
}
async def discover_cameras(self) -> Dict[str, Any]:
"""Discover available cameras using system_profiler and imagesnap"""
try:
# Get USB camera info
usb_result = await self._run_command([
"system_profiler", "SPUSBDataType", "-json"
])
# Get imagesnap camera list
imagesnap_result = await self._run_command([
self.imagesnap_path, "-l"
])
cameras = []
if usb_result["success"]:
try:
usb_data = json.loads(usb_result["stdout"])
for item in usb_data.get("SPUSBDataType", []):
for device in item.get("_items", []):
if self._is_camera_device(device):
camera_info = {
"name": device.get("_name", "Unknown Camera"),
"vendor_id": device.get("vendor_id", ""),
"product_id": device.get("product_id", ""),
"type": "USB",
"ptz_capable": self._is_ptz_camera(device)
}
cameras.append(camera_info)
except json.JSONDecodeError:
pass
# Parse imagesnap output for additional camera names
if imagesnap_result["success"]:
for line in imagesnap_result["stdout"].split('\n'):
if line.strip() and not line.startswith('Video Devices:'):
camera_name = line.strip()
# Check if this camera is already in our list
if not any(cam["name"] == camera_name for cam in cameras):
cameras.append({
"name": camera_name,
"vendor_id": "",
"product_id": "",
"type": "Video",
"ptz_capable": "PTZ" in camera_name.upper()
})
self.camera_cache = {cam["name"]: cam for cam in cameras}
self.last_camera_scan = asyncio.get_event_loop().time()
return {
"success": True,
"cameras": cameras,
"count": len(cameras)
}
except Exception as e:
return {
"success": False,
"error": str(e),
"cameras": [],
"count": 0
}
def _is_camera_device(self, device: Dict) -> bool:
"""Check if USB device is a camera"""
name = device.get("_name", "").lower()
camera_keywords = ["camera", "webcam", "usb video", "ptz", "logitech"]
return any(keyword in name for keyword in camera_keywords)
def _is_ptz_camera(self, device: Dict) -> bool:
"""Check if camera supports PTZ"""
name = device.get("_name", "").lower()
vendor_id = device.get("vendor_id", "")
# Logitech PTZ cameras
return "ptz" in name or vendor_id == "0x046d"
async def take_screenshot(self, camera_name: str, output_path: Optional[str] = None) -> Dict[str, Any]:
"""Take screenshot from specified camera"""
try:
if not output_path:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
output_path = f"/tmp/camera_screenshot_{timestamp}.jpg"
# Kill any blocking processes first
await self._run_command(["sudo", "pkill", "cameracaptured"])
# Take screenshot with imagesnap
result = await self._run_command([
self.imagesnap_path, "-d", camera_name, output_path
], timeout=10)
if result["success"] and os.path.exists(output_path):
# Read image and encode as base64 for MCP response
with open(output_path, "rb") as f:
image_data = base64.b64encode(f.read()).decode('utf-8')
return {
"success": True,
"output_path": output_path,
"image_data": image_data,
"camera_name": camera_name,
"timestamp": datetime.now().isoformat()
}
else:
return {
"success": False,
"error": f"Screenshot failed: {result.get('stderr', 'Unknown error')}",
"output_path": output_path
}
except Exception as e:
return {
"success": False,
"error": str(e),
"output_path": output_path or ""
}
async def ptz_control(self, command: str, value: Optional[str] = None) -> Dict[str, Any]:
"""Send PTZ command to camera"""
try:
if not os.path.exists(self.webcam_ptz_path):
return {
"success": False,
"error": f"webcam-ptz executable not found at {self.webcam_ptz_path}"
}
# Validate command format
valid_commands = ["pan", "tilt", "zoom"]
valid_values = ["min", "max", "middle"]
if not command or command not in valid_commands:
return {
"success": False,
"error": f"Invalid command '{command}'. Must be one of: {', '.join(valid_commands)}"
}
if value is not None:
# Check if value is numeric (steps) or valid preset
if not (value in valid_values or (value.lstrip('-').isdigit())):
return {
"success": False,
"error": f"Invalid value '{value}'. Must be one of: {', '.join(valid_values)} or a number of steps"
}
# Validate step range for numeric values
if value.lstrip('-').isdigit():
steps = int(value)
if abs(steps) > 1000: # Reasonable limit for safety
return {
"success": False,
"error": f"Step value '{steps}' exceeds safe range (-1000 to 1000)"
}
else:
return {
"success": False,
"error": f"Command '{command}' requires a value parameter"
}
# Kill any blocking processes first
logger.info(f"PTZ Control: Killing blocking processes")
kill_result = await self._run_command(["sudo", "-S", "pkill", "cameracaptured"], timeout=5, stdin_input="jjjj\n")
logger.info(f"Kill result: {kill_result}")
# Build command
cmd = [self.webcam_ptz_path, command, value]
logger.info(f"PTZ Control: Executing command: {' '.join(cmd)}")
result = await self._run_command(cmd, timeout=10)
logger.info(f"PTZ Command result: success={result['success']}, stdout='{result['stdout']}', stderr='{result['stderr']}', exit_code={result['exit_code']}")
return {
"success": result["success"],
"command": command,
"value": value,
"output": result["stdout"],
"error": result.get("stderr", "") if not result["success"] else None
}
except Exception as e:
return {
"success": False,
"error": str(e),
"command": command,
"value": value
}
async def get_camera_status(self) -> Dict[str, Any]:
"""Get current camera status and position"""
try:
# For now, just return that we're connected to PTZ camera
# Could be extended to query actual position if webcam-ptz supports it
return {
"success": True,
"ptz_available": os.path.exists(self.webcam_ptz_path),
"imagesnap_available": os.path.exists(self.imagesnap_path),
"last_camera_scan": self.last_camera_scan,
"cached_cameras": len(self.camera_cache)
}
except Exception as e:
return {
"success": False,
"error": str(e)
}
class CameraMCPServer:
def __init__(self):
self.camera_manager = CameraManager()
async def handle_mcp_request(self, request: Dict[str, Any]) -> Dict[str, Any]:
"""Handle MCP protocol request"""
try:
method = request.get("method")
params = request.get("params", {})
if method == "list_cameras":
result = await self.camera_manager.discover_cameras()
return {"result": result}
elif method == "take_screenshot":
camera_name = params.get("camera_name", "PTZ Pro Camera")
output_path = params.get("output_path")
result = await self.camera_manager.take_screenshot(camera_name, output_path)
return {"result": result}
elif method == "ptz_control":
command = params.get("command", "")
value = params.get("value")
if not command:
return {
"error": {"code": -1, "message": "No PTZ command provided"}
}
result = await self.camera_manager.ptz_control(command, value)
return {"result": result}
elif method == "get_camera_status":
result = await self.camera_manager.get_camera_status()
return {"result": result}
else:
return {
"error": {"code": -1, "message": f"Unknown method: {method}"}
}
except Exception as e:
return {
"error": {"code": -1, "message": str(e)}
}
async def main():
"""Main Camera MCP server loop"""
server = CameraMCPServer()
print("Camera Management MCP Server starting...", file=sys.stderr)
print("Available tools: list_cameras, take_screenshot, ptz_control, get_camera_status", file=sys.stderr)
# Read JSON-RPC messages from stdin
while True:
try:
line = await asyncio.get_event_loop().run_in_executor(
None, sys.stdin.readline
)
if not line:
break
request = json.loads(line.strip())
response = await server.handle_mcp_request(request)
# Add request ID if present
if "id" in request:
response["id"] = request["id"]
print(json.dumps(response))
sys.stdout.flush()
except json.JSONDecodeError:
error_response = {
"error": {"code": -32700, "message": "Parse error"}
}
print(json.dumps(error_response))
sys.stdout.flush()
except Exception as e:
error_response = {
"error": {"code": -1, "message": str(e)}
}
print(json.dumps(error_response))
sys.stdout.flush()
if __name__ == "__main__":
asyncio.run(main())