remote-pc-mcp 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,17 @@
1
+ """remote-pc-mcp — expose a PC's capabilities as MCP tools over streamable HTTP."""
2
+
3
+ import os
4
+ from pathlib import Path
5
+
6
+ __version__ = "0.5.0"
7
+
8
+
9
+ def app_dir() -> Path:
10
+ """Directory for this server's .env, logs, and .state.
11
+
12
+ REMOTE_PC_MCP_HOME when set (the root shims set it to the repo root, so a
13
+ git clone keeps today's file locations exactly), else the working
14
+ directory — which the Startup shortcut and the systemd unit both pin to
15
+ the install directory.
16
+ """
17
+ return Path(os.environ.get("REMOTE_PC_MCP_HOME") or Path.cwd())
@@ -0,0 +1,45 @@
1
+ """Centralized logging setup for the server and its supervisor.
2
+
3
+ One RotatingFileHandler writes to server.log for both this project's logger
4
+ and uvicorn's. Importing and calling configure() is safe to do multiple times
5
+ in the same process (logging.config.dictConfig replaces the prior config).
6
+ """
7
+
8
+ import logging
9
+ import logging.config
10
+
11
+ from remote_pc_mcp import app_dir
12
+
13
+ LOG_FILE = app_dir() / "server.log"
14
+
15
+ LOG_CONFIG: dict = {
16
+ "version": 1,
17
+ "disable_existing_loggers": False,
18
+ "formatters": {
19
+ "default": {"format": "%(asctime)s %(levelname)s %(name)s %(message)s"},
20
+ },
21
+ "handlers": {
22
+ "file": {
23
+ "class": "logging.handlers.RotatingFileHandler",
24
+ "filename": str(LOG_FILE),
25
+ "maxBytes": 10 * 1024 * 1024,
26
+ "backupCount": 5,
27
+ "encoding": "utf-8",
28
+ "formatter": "default",
29
+ },
30
+ },
31
+ "loggers": {
32
+ "remote-pc-mcp": {"handlers": ["file"], "level": "INFO", "propagate": False},
33
+ "uvicorn": {"handlers": ["file"], "level": "INFO", "propagate": False},
34
+ "uvicorn.error": {"handlers": ["file"], "level": "INFO", "propagate": False},
35
+ "uvicorn.access": {"handlers": ["file"], "level": "INFO", "propagate": False},
36
+ },
37
+ }
38
+
39
+
40
+ def configure() -> None:
41
+ logging.config.dictConfig(LOG_CONFIG)
42
+
43
+
44
+ def get_logger(name: str = "remote-pc-mcp") -> logging.Logger:
45
+ return logging.getLogger(name)
@@ -0,0 +1,100 @@
1
+ """Supervisor: run the server and restart with exponential backoff on crash.
2
+
3
+ Designed to be invoked via `pythonw daemon.py` (the repo-root shim) from a
4
+ Startup-folder shortcut (see install.bat / install.sh), or as the
5
+ `remote-pc-mcp-daemon` console script from a pip install. For an unsupervised
6
+ foreground run, execute the server entry point directly.
7
+
8
+ Logs to daemon.log (separate from server.log) so the supervisor's writes never
9
+ contend with the server's RotatingFileHandler for the same file.
10
+ """
11
+
12
+ import logging
13
+ import logging.handlers
14
+ import os
15
+ import subprocess
16
+ import sys
17
+ import time
18
+ import urllib.request
19
+ from pathlib import Path
20
+
21
+ from remote_pc_mcp import app_dir
22
+
23
+ _LOG_FILE = app_dir() / "daemon.log"
24
+
25
+ # The server runs as `python -m remote_pc_mcp.server`. Prepending this
26
+ # package's parent to PYTHONPATH makes that resolve in a plain git clone
27
+ # (where nothing is pip-installed); in an installed environment the entry is
28
+ # redundant but harmless.
29
+ _PKG_PARENT = Path(__file__).resolve().parents[1]
30
+
31
+ # Backoff after a crash: walk through this schedule, capped at the last value.
32
+ # Reset to the first value after the server stays up for LONG_RUN_SECONDS.
33
+ _BACKOFF_SCHEDULE = (5, 10, 20, 40, 60)
34
+ _LONG_RUN_SECONDS = 300
35
+
36
+
37
+ def _server_already_up() -> bool:
38
+ port = os.environ.get("REMOTE_PC_MCP_PORT", "8765")
39
+ try:
40
+ with urllib.request.urlopen(f"http://127.0.0.1:{port}/health", timeout=2):
41
+ return True
42
+ except Exception:
43
+ return False
44
+
45
+
46
+ def _configure_logging() -> logging.Logger:
47
+ handler = logging.handlers.RotatingFileHandler(
48
+ _LOG_FILE, maxBytes=2 * 1024 * 1024, backupCount=3, encoding="utf-8"
49
+ )
50
+ handler.setFormatter(
51
+ logging.Formatter("%(asctime)s %(levelname)s daemon %(message)s")
52
+ )
53
+ logger = logging.getLogger("remote-pc-mcp.daemon")
54
+ logger.setLevel(logging.INFO)
55
+ logger.addHandler(handler)
56
+ return logger
57
+
58
+
59
+ def main() -> int:
60
+ logger = _configure_logging()
61
+ if _server_already_up():
62
+ logger.info("server already healthy on configured port; daemon exiting")
63
+ return 0
64
+ logger.info("daemon starting (server=%s -m remote_pc_mcp.server)", sys.executable)
65
+ env = os.environ.copy()
66
+ env["PYTHONPATH"] = str(_PKG_PARENT) + os.pathsep + env.get("PYTHONPATH", "")
67
+ backoff_idx = 0
68
+ try:
69
+ while True:
70
+ started = time.monotonic()
71
+ try:
72
+ result = subprocess.run(
73
+ [sys.executable, "-m", "remote_pc_mcp.server"], env=env
74
+ )
75
+ except FileNotFoundError:
76
+ logger.error("interpreter not found at %s; exiting", sys.executable)
77
+ return 1
78
+ uptime = time.monotonic() - started
79
+
80
+ if result.returncode == 0:
81
+ logger.info("server exited cleanly after %.1fs; stopping daemon", uptime)
82
+ return 0
83
+
84
+ if uptime >= _LONG_RUN_SECONDS:
85
+ backoff_idx = 0
86
+
87
+ delay = _BACKOFF_SCHEDULE[min(backoff_idx, len(_BACKOFF_SCHEDULE) - 1)]
88
+ logger.warning(
89
+ "server crashed (exit=%d, uptime=%.1fs); restarting in %ds",
90
+ result.returncode, uptime, delay,
91
+ )
92
+ time.sleep(delay)
93
+ backoff_idx += 1
94
+ except KeyboardInterrupt:
95
+ logger.info("daemon interrupted; exiting")
96
+ return 0
97
+
98
+
99
+ if __name__ == "__main__":
100
+ sys.exit(main())
@@ -0,0 +1,699 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ remote-pc-mcp — expose a PC's capabilities as MCP tools over streamable HTTP.
4
+
5
+ Tools: shell_exec, read_file, write_file, list_directory, system_info,
6
+ start_process, get_process_output, kill_process, download_file,
7
+ take_screenshot, click, move_mouse, type_text, press_key, scroll.
8
+ """
9
+
10
+ # Set Windows event loop policy before any other asyncio import. ProactorEventLoop
11
+ # crashes uvicorn on certain transient socket errors; SelectorEventLoop is stable.
12
+ import platform
13
+ import sys
14
+
15
+ if platform.system() == "Windows":
16
+ import asyncio
17
+
18
+ asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
19
+
20
+ from pathlib import Path
21
+
22
+ import asyncio
23
+ import base64
24
+ import json
25
+ import os
26
+ import secrets
27
+ import subprocess
28
+ import tempfile
29
+ import threading
30
+ import time
31
+ from datetime import datetime, timezone
32
+ from typing import Optional
33
+
34
+ from remote_pc_mcp import __version__, app_dir
35
+ from remote_pc_mcp import _logging
36
+
37
+ _logging.configure()
38
+
39
+ import httpx
40
+ import psutil
41
+ import pyautogui
42
+ import uvicorn
43
+ from dotenv import load_dotenv
44
+ from mcp.server.fastmcp import FastMCP
45
+ from mcp.server.transport_security import TransportSecuritySettings
46
+ from starlette.applications import Starlette
47
+ from starlette.middleware.base import BaseHTTPMiddleware
48
+ from starlette.requests import Request
49
+ from starlette.responses import JSONResponse
50
+ from starlette.routing import Route
51
+
52
+ pyautogui.FAILSAFE = False # disable corner-hit abort; we're driving remotely
53
+
54
+ # .env lives in the app dir (repo root for a clone via the root shims'
55
+ # REMOTE_PC_MCP_HOME; the working directory otherwise), not wherever
56
+ # find_dotenv's frame-walk lands now that this module sits in a package.
57
+ _APP_DIR = app_dir()
58
+ load_dotenv(_APP_DIR / ".env")
59
+
60
+ # ── Config ─────────────────────────────────────────────────────────────────
61
+
62
+ _TOKEN = os.environ.get("REMOTE_PC_MCP_TOKEN", "")
63
+ _HOST = os.getenv("REMOTE_PC_MCP_HOST", "0.0.0.0")
64
+ _PORT = int(os.getenv("REMOTE_PC_MCP_PORT", "8765"))
65
+
66
+ # Resource caps. Override via env when a host needs different limits.
67
+ _MAX_SHELL_TIMEOUT = int(os.getenv("REMOTE_PC_MCP_MAX_SHELL_TIMEOUT", "600"))
68
+ _MAX_READ_BYTES = int(os.getenv("REMOTE_PC_MCP_MAX_READ_BYTES", str(50 * 1024 * 1024)))
69
+ _MAX_WRITE_BYTES = int(os.getenv("REMOTE_PC_MCP_MAX_WRITE_BYTES", str(50 * 1024 * 1024)))
70
+ _MAX_DOWNLOAD_BYTES = int(os.getenv("REMOTE_PC_MCP_MAX_DOWNLOAD_BYTES", str(2 * 1024**3)))
71
+
72
+ IS_WINDOWS = platform.system() == "Windows"
73
+ _STATE_DIR = _APP_DIR / ".state"
74
+ _STATE_DIR.mkdir(parents=True, exist_ok=True)
75
+ _PROCS_FILE = _STATE_DIR / "procs.json"
76
+
77
+ # ── Logging ────────────────────────────────────────────────────────────────
78
+
79
+ logger = _logging.get_logger()
80
+
81
+
82
+ # ── Error sanitization ─────────────────────────────────────────────────────
83
+
84
+
85
+ def _build_redactions() -> list[tuple[str, str]]:
86
+ r = [(str(Path.home()), "~"), (str(_APP_DIR), "<server-dir>")]
87
+ if _TOKEN:
88
+ r.append((_TOKEN, "<token>"))
89
+ return r
90
+
91
+
92
+ _REDACTIONS = _build_redactions()
93
+
94
+
95
+ def _safe_msg(msg: str) -> str:
96
+ for src, dst in _REDACTIONS:
97
+ if src:
98
+ msg = msg.replace(src, dst)
99
+ return msg[:500]
100
+
101
+
102
+ def _safe_error(e: Exception) -> str:
103
+ return _safe_msg(f"{type(e).__name__}: {e}")
104
+
105
+
106
+ # ── Process registry (persists across restarts) ────────────────────────────
107
+
108
+ _procs_lock = threading.Lock()
109
+
110
+
111
+ def _load_procs() -> dict[int, dict]:
112
+ try:
113
+ return {int(k): v for k, v in json.loads(_PROCS_FILE.read_text()).items()}
114
+ except (FileNotFoundError, json.JSONDecodeError):
115
+ return {}
116
+
117
+
118
+ def _save_procs() -> None:
119
+ """Atomic write: serialize to <file>.tmp, then os.replace into place. A
120
+ power loss between the write and the replace leaves the previous registry
121
+ intact instead of half-written JSON that _load_procs would discard."""
122
+ try:
123
+ tmp = _PROCS_FILE.with_suffix(".tmp")
124
+ tmp.write_text(json.dumps({str(k): v for k, v in _procs.items()}))
125
+ tmp.replace(_PROCS_FILE)
126
+ except Exception as e:
127
+ logger.error("Failed to persist process registry: %s", _safe_error(e))
128
+
129
+
130
+ def _gc_proc(pid: int) -> None:
131
+ """Drop a registry entry and delete its temp stdout/stderr files. Caller
132
+ must hold _procs_lock."""
133
+ info = _procs.pop(pid, None)
134
+ if not info:
135
+ return
136
+ for key in ("stdout_path", "stderr_path"):
137
+ path = info.get(key)
138
+ if path:
139
+ try:
140
+ Path(path).unlink(missing_ok=True)
141
+ except Exception:
142
+ pass
143
+
144
+
145
+ def _gc_dead_procs() -> None:
146
+ """Drop registry entries whose PIDs are no longer running. Idempotent."""
147
+ with _procs_lock:
148
+ dead = []
149
+ for pid in list(_procs):
150
+ try:
151
+ p = psutil.Process(pid)
152
+ if not p.is_running() or p.status() == psutil.STATUS_ZOMBIE:
153
+ dead.append(pid)
154
+ except psutil.NoSuchProcess:
155
+ dead.append(pid)
156
+ for pid in dead:
157
+ _gc_proc(pid)
158
+ if dead:
159
+ _save_procs()
160
+
161
+
162
+ _procs: dict[int, dict] = _load_procs()
163
+
164
+
165
+ # ── MCP server (stateless streamable HTTP) ─────────────────────────────────
166
+ #
167
+ # stateless_http=True means each request is self-contained: no in-memory
168
+ # session_id cache to go stale on restart. json_response=True means responses
169
+ # are single JSON payloads (not SSE event streams), so a client that POSTs and
170
+ # walks away cannot leave a zombie stream behind. This is the fix for the
171
+ # class of bugs where a server restart bricks the client.
172
+ #
173
+ # DNS-rebinding protection in the SDK rejects any Host header not in its
174
+ # allowlist, which breaks legitimate access via Tailscale IPs and LAN hostnames.
175
+ # This server is already protected by a 256-bit bearer token (constant-time
176
+ # compared); DNS rebinding is the wrong threat model on a tailnet/LAN. We
177
+ # default the protection OFF and let operators opt in by setting
178
+ # REMOTE_PC_MCP_ALLOWED_HOSTS to a comma-separated list when they want it.
179
+
180
+ _ALLOWED_HOSTS = [
181
+ h.strip() for h in os.getenv("REMOTE_PC_MCP_ALLOWED_HOSTS", "").split(",") if h.strip()
182
+ ]
183
+ _TRANSPORT_SECURITY = TransportSecuritySettings(
184
+ enable_dns_rebinding_protection=bool(_ALLOWED_HOSTS),
185
+ allowed_hosts=_ALLOWED_HOSTS,
186
+ allowed_origins=_ALLOWED_HOSTS,
187
+ )
188
+
189
+ mcp = FastMCP(
190
+ "remote-pc-mcp",
191
+ stateless_http=True,
192
+ json_response=True,
193
+ transport_security=_TRANSPORT_SECURITY,
194
+ )
195
+
196
+
197
+ # ── Tools ───────────────────────────────────────────────────────────────────
198
+
199
+
200
+ def _shell_exec_sync(command: str, capped_timeout: int, working_dir: Optional[str]) -> dict:
201
+ proc = subprocess.Popen(
202
+ command,
203
+ shell=True,
204
+ stdout=subprocess.PIPE,
205
+ stderr=subprocess.PIPE,
206
+ text=True,
207
+ cwd=working_dir,
208
+ )
209
+ try:
210
+ stdout, stderr = proc.communicate(timeout=capped_timeout)
211
+ return {"stdout": stdout, "stderr": stderr, "exit_code": proc.returncode, "timed_out": False}
212
+ except subprocess.TimeoutExpired:
213
+ _kill_process_tree(proc.pid)
214
+ try:
215
+ proc.wait(timeout=2)
216
+ except subprocess.TimeoutExpired:
217
+ pass
218
+ return {"stdout": "", "stderr": "Timed out", "exit_code": -1, "timed_out": True}
219
+ except Exception as e:
220
+ _kill_process_tree(proc.pid)
221
+ return {"stdout": "", "stderr": _safe_error(e), "exit_code": -1, "timed_out": False}
222
+
223
+
224
+ @mcp.tool()
225
+ async def shell_exec(
226
+ command: str,
227
+ timeout: int = 30,
228
+ working_dir: Optional[str] = None,
229
+ ) -> dict:
230
+ """Run a shell command. Returns stdout, stderr, exit_code.
231
+
232
+ timeout is capped at REMOTE_PC_MCP_MAX_SHELL_TIMEOUT (default 600s). The
233
+ blocking subprocess runs in a thread so /health and other tool calls keep
234
+ being served while a long command is in flight.
235
+ """
236
+ capped_timeout = min(max(1, timeout), _MAX_SHELL_TIMEOUT)
237
+ audit_cmd = command if len(command) <= 200 else command[:200] + "..."
238
+ logger.info("shell_exec timeout=%d cwd=%s cmd=%r", capped_timeout, working_dir, audit_cmd)
239
+ return await asyncio.to_thread(_shell_exec_sync, command, capped_timeout, working_dir)
240
+
241
+
242
+ def _kill_process_tree(pid: int) -> None:
243
+ """Kill a process and all of its children. shell=True on Windows spawns
244
+ cmd.exe which spawns the real command; killing only the parent leaves the
245
+ grandchild alive."""
246
+ try:
247
+ parent = psutil.Process(pid)
248
+ except psutil.NoSuchProcess:
249
+ return
250
+ for child in parent.children(recursive=True):
251
+ try:
252
+ child.kill()
253
+ except psutil.NoSuchProcess:
254
+ pass
255
+ try:
256
+ parent.kill()
257
+ except psutil.NoSuchProcess:
258
+ pass
259
+
260
+
261
+ @mcp.tool()
262
+ def read_file(path: str, encoding: str = "utf-8") -> dict:
263
+ """Read a file as text, with base64 fallback for binary files.
264
+
265
+ Files larger than REMOTE_PC_MCP_MAX_READ_BYTES (default 50 MB) are rejected.
266
+ """
267
+ try:
268
+ p = Path(path)
269
+ if not p.exists():
270
+ return {"error": _safe_msg(f"Not found: {path}")}
271
+ size = p.stat().st_size
272
+ if size > _MAX_READ_BYTES:
273
+ return {"error": f"File too large ({size} bytes, max {_MAX_READ_BYTES})"}
274
+ try:
275
+ return {"content": p.read_text(encoding=encoding), "encoding": encoding, "size": size}
276
+ except UnicodeDecodeError:
277
+ return {
278
+ "content": base64.b64encode(p.read_bytes()).decode(),
279
+ "encoding": "base64",
280
+ "size": size,
281
+ }
282
+ except Exception as e:
283
+ return {"error": _safe_error(e)}
284
+
285
+
286
+ @mcp.tool()
287
+ def write_file(
288
+ path: str, content: str, encoding: str = "utf-8", base64_encoded: bool = False
289
+ ) -> dict:
290
+ """Write content to a file. Set base64_encoded=True for binary data.
291
+
292
+ Content larger than REMOTE_PC_MCP_MAX_WRITE_BYTES (default 50 MB) is rejected.
293
+ """
294
+ try:
295
+ if base64_encoded:
296
+ data = base64.b64decode(content)
297
+ if len(data) > _MAX_WRITE_BYTES:
298
+ return {"error": f"Content too large ({len(data)} bytes, max {_MAX_WRITE_BYTES})"}
299
+ p = Path(path)
300
+ p.parent.mkdir(parents=True, exist_ok=True)
301
+ p.write_bytes(data)
302
+ else:
303
+ encoded = content.encode(encoding)
304
+ if len(encoded) > _MAX_WRITE_BYTES:
305
+ return {
306
+ "error": f"Content too large ({len(encoded)} bytes, max {_MAX_WRITE_BYTES})"
307
+ }
308
+ p = Path(path)
309
+ p.parent.mkdir(parents=True, exist_ok=True)
310
+ p.write_text(content, encoding=encoding)
311
+ return {"success": True, "path": str(p.resolve()), "size": p.stat().st_size}
312
+ except Exception as e:
313
+ return {"error": _safe_error(e)}
314
+
315
+
316
+ @mcp.tool()
317
+ def list_directory(path: str, recursive: bool = False) -> dict:
318
+ """List files and subdirectories at a path."""
319
+ try:
320
+ p = Path(path)
321
+ if not p.exists():
322
+ return {"error": _safe_msg(f"Not found: {path}")}
323
+ if not p.is_dir():
324
+ return {"error": _safe_msg(f"Not a directory: {path}")}
325
+ entries = []
326
+ items = p.rglob("*") if recursive else p.iterdir()
327
+ for item in sorted(items):
328
+ try:
329
+ st = item.stat()
330
+ entries.append(
331
+ {
332
+ "name": item.name,
333
+ "path": str(item),
334
+ "type": "dir" if item.is_dir() else "file",
335
+ "size": st.st_size if item.is_file() else None,
336
+ "modified": datetime.fromtimestamp(st.st_mtime).isoformat(),
337
+ }
338
+ )
339
+ except PermissionError:
340
+ pass
341
+ return {"path": str(p.resolve()), "count": len(entries), "entries": entries}
342
+ except Exception as e:
343
+ return {"error": _safe_error(e)}
344
+
345
+
346
+ @mcp.tool()
347
+ def system_info() -> dict:
348
+ """Return OS, CPU, RAM, and GPU (via nvidia-smi) information."""
349
+ vm = psutil.virtual_memory()
350
+ info = {
351
+ "hostname": platform.node(),
352
+ "os": platform.system(),
353
+ "os_version": platform.version(),
354
+ "architecture": platform.machine(),
355
+ "cpu_count_logical": psutil.cpu_count(),
356
+ "cpu_count_physical": psutil.cpu_count(logical=False),
357
+ "cpu_percent": psutil.cpu_percent(interval=1),
358
+ "ram_total_gb": round(vm.total / 1e9, 2),
359
+ "ram_used_gb": round(vm.used / 1e9, 2),
360
+ "ram_percent": vm.percent,
361
+ "gpu": [],
362
+ "server_version": __version__,
363
+ }
364
+ try:
365
+ r = subprocess.run(
366
+ [
367
+ "nvidia-smi",
368
+ "--query-gpu=name,memory.total,memory.used,utilization.gpu,temperature.gpu",
369
+ "--format=csv,noheader,nounits",
370
+ ],
371
+ capture_output=True,
372
+ text=True,
373
+ timeout=5,
374
+ )
375
+ if r.returncode == 0:
376
+ for line in r.stdout.strip().splitlines():
377
+ parts = [x.strip() for x in line.split(",")]
378
+ if len(parts) == 5:
379
+ info["gpu"].append(
380
+ {
381
+ "name": parts[0],
382
+ "vram_total_mb": int(parts[1]),
383
+ "vram_used_mb": int(parts[2]),
384
+ "utilization_pct": int(parts[3]),
385
+ "temp_c": int(parts[4]),
386
+ }
387
+ )
388
+ except Exception:
389
+ pass
390
+ return info
391
+
392
+
393
+ @mcp.tool()
394
+ def start_process(command: str, working_dir: Optional[str] = None) -> dict:
395
+ """Start a long-running command in the background. Returns PID to track it."""
396
+ try:
397
+ out = tempfile.NamedTemporaryFile(delete=False, suffix=".out.txt", mode="w")
398
+ err = tempfile.NamedTemporaryFile(delete=False, suffix=".err.txt", mode="w")
399
+ proc = subprocess.Popen(command, shell=True, stdout=out, stderr=err, cwd=working_dir)
400
+ out.close()
401
+ err.close()
402
+ with _procs_lock:
403
+ _procs[proc.pid] = {
404
+ "pid": proc.pid,
405
+ "command": command,
406
+ "stdout_path": out.name,
407
+ "stderr_path": err.name,
408
+ "started_at": datetime.now(timezone.utc).isoformat(),
409
+ }
410
+ _save_procs()
411
+ logger.info("start_process pid=%d cmd=%r", proc.pid, command[:200])
412
+ return {"pid": proc.pid, "command": command}
413
+ except Exception as e:
414
+ return {"error": _safe_error(e)}
415
+
416
+
417
+ @mcp.tool()
418
+ def get_process_output(pid: int, tail_lines: int = 100) -> dict:
419
+ """Get the latest stdout/stderr from a process started with start_process.
420
+
421
+ Reads output even after the process has exited (until the next call notices
422
+ it's dead and the temp files are reaped). After the reap, subsequent calls
423
+ return 'not tracked'.
424
+ """
425
+ if pid not in _procs:
426
+ return {"error": f"PID {pid} not tracked. Only processes started via start_process are tracked."}
427
+ info = _procs[pid]
428
+
429
+ def tail(fpath: str, n: int) -> str:
430
+ try:
431
+ lines = Path(fpath).read_text(errors="replace").splitlines()
432
+ return "\n".join(lines[-n:])
433
+ except Exception as ex:
434
+ return f"[error reading output: {_safe_error(ex)}]"
435
+
436
+ try:
437
+ proc = psutil.Process(pid)
438
+ running = proc.is_running() and proc.status() != psutil.STATUS_ZOMBIE
439
+ except psutil.NoSuchProcess:
440
+ running = False
441
+
442
+ result = {
443
+ "pid": pid,
444
+ "running": running,
445
+ "command": info["command"],
446
+ "started_at": info["started_at"],
447
+ "stdout": tail(info["stdout_path"], tail_lines),
448
+ "stderr": tail(info["stderr_path"], tail_lines),
449
+ }
450
+ # Reap on this call: once the caller has seen the final output of a dead
451
+ # process, drop the registry entry and the temp files so they don't leak
452
+ # for the lifetime of the server.
453
+ if not running:
454
+ with _procs_lock:
455
+ _gc_proc(pid)
456
+ _save_procs()
457
+ return result
458
+
459
+
460
+ @mcp.tool()
461
+ def kill_process(pid: int) -> dict:
462
+ """Terminate a running process by PID."""
463
+ try:
464
+ p = psutil.Process(pid)
465
+ p.terminate()
466
+ force = False
467
+ try:
468
+ p.wait(timeout=5)
469
+ except psutil.TimeoutExpired:
470
+ p.kill()
471
+ force = True
472
+ with _procs_lock:
473
+ _gc_proc(pid)
474
+ _save_procs()
475
+ logger.info("kill_process pid=%d force=%s", pid, force)
476
+ return {"pid": pid, "killed": True, "force_killed": force}
477
+ except psutil.NoSuchProcess:
478
+ with _procs_lock:
479
+ _gc_proc(pid)
480
+ _save_procs()
481
+ return {"error": f"No process with PID {pid}"}
482
+ except Exception as e:
483
+ return {"error": _safe_error(e)}
484
+
485
+
486
+ @mcp.tool()
487
+ async def download_file(url: str, destination: str) -> dict:
488
+ """Download a file from a URL to a local path on this machine.
489
+
490
+ Downloads larger than REMOTE_PC_MCP_MAX_DOWNLOAD_BYTES (default 2 GB) are aborted.
491
+ """
492
+ try:
493
+ dest = Path(destination)
494
+ dest.parent.mkdir(parents=True, exist_ok=True)
495
+ downloaded = 0
496
+ async with httpx.AsyncClient(follow_redirects=True, timeout=600) as client:
497
+ async with client.stream("GET", url) as resp:
498
+ resp.raise_for_status()
499
+ with open(dest, "wb") as f:
500
+ async for chunk in resp.aiter_bytes(8192):
501
+ downloaded += len(chunk)
502
+ if downloaded > _MAX_DOWNLOAD_BYTES:
503
+ f.close()
504
+ dest.unlink(missing_ok=True)
505
+ return {"error": f"Download exceeded {_MAX_DOWNLOAD_BYTES} bytes; aborted"}
506
+ f.write(chunk)
507
+ return {"success": True, "path": str(dest.resolve()), "size": dest.stat().st_size}
508
+ except Exception as e:
509
+ return {"error": _safe_error(e)}
510
+
511
+
512
+ @mcp.tool()
513
+ def take_screenshot(save_path: Optional[str] = None) -> dict:
514
+ """Capture the primary display. Returns base64-encoded PNG.
515
+
516
+ Requires an interactive desktop session on Windows; pyautogui-driven tools
517
+ cannot reach a Session 0 (service-context) desktop.
518
+ """
519
+ if save_path is None:
520
+ save_path = str(
521
+ Path(tempfile.gettempdir())
522
+ / f"screenshot_{datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S')}.png"
523
+ )
524
+
525
+ if IS_WINDOWS:
526
+ ps = f"""
527
+ Add-Type -AssemblyName System.Windows.Forms,System.Drawing
528
+ $s = [System.Windows.Forms.SystemInformation]::VirtualScreen
529
+ $b = New-Object System.Drawing.Bitmap($s.Width, $s.Height)
530
+ $g = [System.Drawing.Graphics]::FromImage($b)
531
+ $g.CopyFromScreen($s.Left, $s.Top, 0, 0, $b.Size)
532
+ $b.Save('{save_path}')
533
+ $g.Dispose(); $b.Dispose()
534
+ """
535
+ r = subprocess.run(
536
+ ["powershell", "-NoProfile", "-Command", ps],
537
+ capture_output=True,
538
+ text=True,
539
+ timeout=15,
540
+ )
541
+ if r.returncode != 0:
542
+ return {"error": _safe_error(RuntimeError(r.stderr.strip()))}
543
+ else:
544
+ taken = False
545
+ for cmd in [
546
+ f"scrot '{save_path}'",
547
+ f"gnome-screenshot -f '{save_path}'",
548
+ f"import -window root '{save_path}'",
549
+ ]:
550
+ r = subprocess.run(cmd, shell=True, capture_output=True, timeout=10)
551
+ if r.returncode == 0:
552
+ taken = True
553
+ break
554
+ if not taken:
555
+ return {"error": "No screenshot tool found. On Linux install scrot: sudo apt install scrot"}
556
+
557
+ data = base64.b64encode(Path(save_path).read_bytes()).decode()
558
+ return {"success": True, "path": save_path, "image_base64": data, "format": "png"}
559
+
560
+
561
+ # ── UI control (pyautogui) ──────────────────────────────────────────────────
562
+ #
563
+ # These require an interactive desktop session — they cannot drive a locked
564
+ # screen or a service-context (Session 0) Windows process.
565
+
566
+
567
+ @mcp.tool()
568
+ def click(x: int, y: int, button: str = "left", clicks: int = 1) -> dict:
569
+ """Click at screen coordinates (x, y). button = 'left' | 'right' | 'middle'."""
570
+ try:
571
+ pyautogui.click(x=x, y=y, clicks=clicks, button=button)
572
+ return {"success": True, "x": x, "y": y, "button": button, "clicks": clicks}
573
+ except Exception as e:
574
+ return {"error": _safe_error(e)}
575
+
576
+
577
+ @mcp.tool()
578
+ def move_mouse(x: int, y: int, duration: float = 0.0) -> dict:
579
+ """Move the cursor to (x, y). duration > 0 animates the movement."""
580
+ try:
581
+ pyautogui.moveTo(x=x, y=y, duration=duration)
582
+ return {"success": True, "x": x, "y": y}
583
+ except Exception as e:
584
+ return {"error": _safe_error(e)}
585
+
586
+
587
+ @mcp.tool()
588
+ def type_text(text: str, interval: float = 0.0) -> dict:
589
+ """Type a string into the focused window. interval = seconds between keys."""
590
+ try:
591
+ pyautogui.typewrite(text, interval=interval)
592
+ return {"success": True, "length": len(text)}
593
+ except Exception as e:
594
+ return {"error": _safe_error(e)}
595
+
596
+
597
+ @mcp.tool()
598
+ def press_key(key: str) -> dict:
599
+ """Press a single key or hotkey combo. Examples: 'enter', 'f11', 'ctrl+c', 'win+d'."""
600
+ try:
601
+ if "+" in key:
602
+ pyautogui.hotkey(*[k.strip() for k in key.split("+")])
603
+ else:
604
+ pyautogui.press(key)
605
+ return {"success": True, "key": key}
606
+ except Exception as e:
607
+ return {"error": _safe_error(e)}
608
+
609
+
610
+ @mcp.tool()
611
+ def scroll(amount: int, x: Optional[int] = None, y: Optional[int] = None) -> dict:
612
+ """Scroll the mouse wheel. Positive = up, negative = down. Optional (x, y) anchors at coords."""
613
+ try:
614
+ if x is not None and y is not None:
615
+ pyautogui.moveTo(x, y)
616
+ pyautogui.scroll(amount)
617
+ return {"success": True, "amount": amount}
618
+ except Exception as e:
619
+ return {"error": _safe_error(e)}
620
+
621
+
622
+ # ── Auth middleware ─────────────────────────────────────────────────────────
623
+
624
+
625
+ class _AuthMiddleware(BaseHTTPMiddleware):
626
+ async def dispatch(self, request: Request, call_next):
627
+ if request.url.path == "/health":
628
+ return await call_next(request)
629
+ auth = request.headers.get("authorization", "")
630
+ if not auth.startswith("Bearer "):
631
+ return JSONResponse({"error": "Unauthorized"}, status_code=401)
632
+ if not secrets.compare_digest(auth[7:].encode(), _TOKEN.encode()):
633
+ return JSONResponse({"error": "Unauthorized"}, status_code=401)
634
+ return await call_next(request)
635
+
636
+
637
+ # ── Starlette app (streamable HTTP transport) ──────────────────────────────
638
+
639
+
640
+ async def _health(_request: Request) -> JSONResponse:
641
+ return JSONResponse(
642
+ {"status": "ok", "server": "remote-pc-mcp", "version": __version__}
643
+ )
644
+
645
+
646
+ def _build_app() -> Starlette:
647
+ app: Starlette = mcp.streamable_http_app()
648
+ app.routes.insert(0, Route("/health", endpoint=_health))
649
+ app.add_middleware(_AuthMiddleware)
650
+ return app
651
+
652
+
653
+ # ── Entry point ─────────────────────────────────────────────────────────────
654
+
655
+
656
+ def main() -> None:
657
+ if not _TOKEN:
658
+ sys.exit("ERROR: REMOTE_PC_MCP_TOKEN not set. Copy .env.example → .env and fill it in.")
659
+
660
+ # Reap registry entries whose PIDs died while we were down. Without this,
661
+ # background processes that the user never explicitly killed accumulate in
662
+ # the registry across server restarts and leak their temp stdout/stderr
663
+ # files in %TEMP%.
664
+ _gc_dead_procs()
665
+
666
+ logger.info("remote-pc-mcp v%s starting on %s:%d", __version__, _HOST, _PORT)
667
+
668
+ # log_config=None preserves our dictConfig setup; uvicorn's default would
669
+ # overwrite it and route its loggers back to stderr (which is hollow under
670
+ # pythonw on Python 3.10+).
671
+ config = uvicorn.Config(
672
+ _build_app(), host=_HOST, port=_PORT, log_config=None
673
+ )
674
+ # Wrap the uvicorn server so a transient OSError on accept() (e.g. when the
675
+ # Tailscale interface briefly loses its bound IP during a network change)
676
+ # doesn't permanently kill the listener. Back off exponentially so a
677
+ # permanent OSError (interface gone for real) doesn't spin at 2s forever
678
+ # and flood the log; the schedule resets after a long-running success.
679
+ _REBIND_BACKOFF = (2, 5, 10, 30, 60)
680
+ _REBIND_LONG_RUN_SECONDS = 300
681
+ backoff_idx = 0
682
+ while True:
683
+ started = time.monotonic()
684
+ server = uvicorn.Server(config)
685
+ try:
686
+ server.run()
687
+ break
688
+ except OSError as e:
689
+ uptime = time.monotonic() - started
690
+ if uptime >= _REBIND_LONG_RUN_SECONDS:
691
+ backoff_idx = 0
692
+ delay = _REBIND_BACKOFF[min(backoff_idx, len(_REBIND_BACKOFF) - 1)]
693
+ logger.error("Listener died (%s); rebinding in %ds", _safe_error(e), delay)
694
+ time.sleep(delay)
695
+ backoff_idx += 1
696
+
697
+
698
+ if __name__ == "__main__":
699
+ main()
@@ -0,0 +1,331 @@
1
+ Metadata-Version: 2.4
2
+ Name: remote-pc-mcp
3
+ Version: 0.5.0
4
+ Summary: Expose any PC's capabilities - shell, filesystem, background processes, system stats, screenshots, UI control, and file transfer - to any MCP client over streamable HTTP.
5
+ Author: Raghib Murt
6
+ License: MIT License
7
+
8
+ Copyright (c) 2026 Raghib Murt
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Project-URL: Homepage, https://github.com/raghibrm/remote-pc-mcp
29
+ Project-URL: Repository, https://github.com/raghibrm/remote-pc-mcp
30
+ Project-URL: Changelog, https://github.com/raghibrm/remote-pc-mcp/blob/main/CHANGELOG.md
31
+ Keywords: mcp,model-context-protocol,remote-control,automation,tailscale
32
+ Classifier: Development Status :: 4 - Beta
33
+ Classifier: Intended Audience :: Developers
34
+ Classifier: License :: OSI Approved :: MIT License
35
+ Classifier: Operating System :: Microsoft :: Windows
36
+ Classifier: Operating System :: POSIX :: Linux
37
+ Classifier: Programming Language :: Python :: 3
38
+ Classifier: Topic :: System :: Systems Administration
39
+ Requires-Python: >=3.10
40
+ Description-Content-Type: text/markdown
41
+ License-File: LICENSE
42
+ Requires-Dist: mcp<2,>=1.10.0
43
+ Requires-Dist: uvicorn>=0.30.0
44
+ Requires-Dist: starlette>=0.40.0
45
+ Requires-Dist: python-dotenv>=1.0.0
46
+ Requires-Dist: httpx>=0.27.0
47
+ Requires-Dist: psutil>=5.9.0
48
+ Requires-Dist: pyautogui>=0.9.54
49
+ Requires-Dist: pillow>=10.0.0
50
+ Dynamic: license-file
51
+
52
+ # remote-pc-mcp
53
+
54
+ Expose any PC's capabilities — shell, filesystem, background processes, system stats, screenshots, UI control, and file transfer — to **any MCP client** (Claude Desktop, Claude Code, Cursor, Cline, Continue, Windsurf, custom agents — anything that speaks the [Model Context Protocol](https://modelcontextprotocol.io)) over streamable HTTP.
55
+
56
+ Drop it on any machine you want to drive remotely: a home server, a desktop, a build/CI box, a media server, a workstation, a Raspberry Pi. From a separate machine, your AI agent of choice can run commands on it, manage files, launch and monitor background jobs, take screenshots, and drive the desktop UI.
57
+
58
+ The transport is the `mcp` SDK's streamable HTTP (`stateless_http=True`), so a server restart does not break already-connected clients. Each request is self-contained — there is no in-memory session to go stale.
59
+
60
+ > ⚠️ **`shell_exec` runs arbitrary commands on the host as the user that started the server.** The bearer token is a root-equivalent credential. See [Security](#security) before exposing the server.
61
+
62
+ ## Tools
63
+
64
+ | Tool | Description |
65
+ |------|-------------|
66
+ | `shell_exec` | Run any shell command — returns stdout, stderr, exit code |
67
+ | `read_file` | Read a file as text or base64 (binary fallback) |
68
+ | `write_file` | Write text or binary content to a file |
69
+ | `list_directory` | List files and directories, optionally recursive |
70
+ | `system_info` | OS, CPU, RAM, and GPU stats (NVIDIA GPUs via `nvidia-smi`; absent on non-GPU hosts) |
71
+ | `start_process` | Start a long-running command in the background — returns a PID |
72
+ | `get_process_output` | Poll stdout/stderr of a background process by PID |
73
+ | `kill_process` | Terminate a process by PID |
74
+ | `download_file` | Download a URL directly to this machine |
75
+ | `take_screenshot` | Capture the primary display — returns base64-encoded PNG |
76
+ | `click` | Click at screen coordinates `(x, y)` — left / right / middle, single or multi-click |
77
+ | `move_mouse` | Move cursor to `(x, y)`, optionally animated |
78
+ | `type_text` | Type a string into the focused window |
79
+ | `press_key` | Press a single key or hotkey combo (e.g. `enter`, `f11`, `ctrl+c`, `win+d`) |
80
+ | `scroll` | Scroll the mouse wheel up or down, optionally at a specific point |
81
+
82
+ ## Requirements
83
+
84
+ - Python 3.10+
85
+ - Windows 10/11, or Linux with systemd (for autostart)
86
+
87
+ ## Install
88
+
89
+ On the machine you want to control:
90
+
91
+ ```bash
92
+ git clone https://github.com/raghibrm/remote-pc-mcp
93
+ cd remote-pc-mcp
94
+ cp .env.example .env
95
+ ```
96
+
97
+ Set a strong token in `.env`:
98
+
99
+ ```
100
+ REMOTE_PC_MCP_TOKEN=your-long-random-token-here
101
+ ```
102
+
103
+ Generate one:
104
+
105
+ ```bash
106
+ # Windows
107
+ python -c "import secrets; print(secrets.token_hex(32))"
108
+
109
+ # Linux / macOS
110
+ openssl rand -hex 32
111
+ ```
112
+
113
+ Then run the installer:
114
+
115
+ ```bash
116
+ # Windows
117
+ install.bat
118
+
119
+ # Linux
120
+ chmod +x install.sh
121
+ ./install.sh
122
+ ```
123
+
124
+ That's it — one command. The installer:
125
+
126
+ - installs Python dependencies
127
+ - registers the server to launch hidden on every login (Startup-folder shortcut on Windows, systemd user unit on Linux)
128
+ - starts it now
129
+ - supervises it with exponential backoff on crash (5→10→20→40→60 seconds, resets after 5 minutes of uptime)
130
+ - survives reboots — set once, runs forever
131
+
132
+ ### Verify it's up
133
+
134
+ ```bash
135
+ curl http://localhost:8765/health
136
+ # {"status":"ok","server":"remote-pc-mcp","version":"0.5.0"}
137
+ ```
138
+
139
+ ### When to rerun the installer
140
+
141
+ `install.bat` / `install.sh` are idempotent and self-healing. Rerun any time after:
142
+
143
+ - You **move the repo** to a different folder
144
+ - You **reinstall or upgrade Python** to a different path
145
+ - You **rebuild the machine** and want to restore autostart
146
+
147
+ For day-to-day operation you never need to think about it.
148
+
149
+ ### After a reboot
150
+
151
+ Autostart fires when you **sign in** to Windows. A reboot that sits at the lock screen will NOT start the daemon until somebody logs in. This is intentional — enabling Windows auto-logon to make reboots fully hands-off would let anyone with physical access to the machine get a logged-in desktop, which is the wrong trade-off for a remote-control tool.
152
+
153
+ If you need to bring the daemon back up after a reboot without walking to the PC, sign in remotely via Remote Desktop or Tailscale SSH. Once you're logged in, the Startup shortcut fires and the daemon starts.
154
+
155
+ Linux is different: `install.sh --linger` runs `sudo loginctl enable-linger $USER` so the systemd user unit runs across reboots without any logon. systemd's user services don't share the auto-logon security problem because they don't grant interactive desktop access — they just keep your user-scoped daemons alive.
156
+
157
+ ### Uninstall
158
+
159
+ ```bash
160
+ # Windows
161
+ install.bat --uninstall
162
+
163
+ # Linux
164
+ ./install.sh --uninstall
165
+ ```
166
+
167
+ Removes the autostart entry and stops the running server + supervisor.
168
+
169
+ ### Foreground run (development)
170
+
171
+ For a one-off run with visible console output and no autostart:
172
+
173
+ ```bash
174
+ python server.py
175
+ ```
176
+
177
+ That's it — no special script. Use `install.bat` / `install.sh` for the normal supervised setup.
178
+
179
+ ### Or install from PyPI
180
+
181
+ ```bash
182
+ pip install remote-pc-mcp
183
+ remote-pc-mcp # run the server in the foreground
184
+ remote-pc-mcp-daemon # supervised: restarts the server on crash
185
+ ```
186
+
187
+ A pip install gives you the server and supervisor commands but does not register autostart. For autostart on sign-in, use the clone and install-script path above. `.env`, logs, and `.state/` live in `REMOTE_PC_MCP_HOME` (default: the working directory).
188
+
189
+ ## Adding to your MCP client
190
+
191
+ Most MCP clients use the same JSON schema; the file just lives in different places. Example:
192
+
193
+ ```json
194
+ {
195
+ "mcpServers": {
196
+ "remote-pc": {
197
+ "type": "http",
198
+ "url": "http://YOUR_PC_IP_OR_HOSTNAME:8765/mcp",
199
+ "headers": {
200
+ "Authorization": "Bearer your-long-random-token-here"
201
+ }
202
+ }
203
+ }
204
+ }
205
+ ```
206
+
207
+ Where to put it:
208
+
209
+ | Client | Config file |
210
+ |--------|-------------|
211
+ | Claude Code | `.mcp.json` in the project root (or `~/.claude.json` for user-wide) |
212
+ | Claude Desktop | `claude_desktop_config.json` (Settings → Developer → Edit Config) |
213
+ | Cursor | `.cursor/mcp.json` |
214
+ | Cline / Continue / Windsurf | each has its own MCP servers panel — paste the JSON there |
215
+ | Custom agents | wherever your agent reads MCP server definitions |
216
+
217
+ For Tailscale users, the magic-DNS hostname works in the URL:
218
+
219
+ ```json
220
+ "url": "http://your-pc.tail12345.ts.net:8765/mcp"
221
+ ```
222
+
223
+ Restart (or reload) your client. The tools appear automatically. The `"remote-pc"` key is just a label — pick whatever name you want.
224
+
225
+ ## Security
226
+
227
+ `shell_exec` runs **any command** on the host as the user that started the server. That is intentional — it is what makes the server useful for remote-driving a PC. It also means:
228
+
229
+ - **The bearer token is a root-equivalent credential.** Generate a 32-byte hex token, store it only in `.env` (which is git-ignored), and treat it like a password.
230
+ - **Never expose the server to the public internet** without TLS and a reverse proxy (nginx, Caddy, Cloudflare Tunnel).
231
+ - **Use Tailscale** (strongly recommended): bind to your Tailscale IP (set `REMOTE_PC_MCP_HOST=100.x.x.x` in `.env`) so the listener is only reachable from devices in your tailnet.
232
+ - **LAN-only deployments** with `REMOTE_PC_MCP_HOST=0.0.0.0` are reasonable if you trust every device on the LAN and have a strong token. Don't do this on an untrusted network.
233
+
234
+ The token is compared with `secrets.compare_digest` (constant-time). All error messages pass through a sanitiser that strips absolute paths, the home directory, and the token before being returned to clients.
235
+
236
+ ## Configuration
237
+
238
+ All env vars are optional except `REMOTE_PC_MCP_TOKEN`.
239
+
240
+ | Var | Default | Description |
241
+ |-----|---------|-------------|
242
+ | `REMOTE_PC_MCP_TOKEN` | _(required)_ | Bearer token clients must present |
243
+ | `REMOTE_PC_MCP_HOST` | `0.0.0.0` | Bind address. Set to a Tailscale IP to restrict reach |
244
+ | `REMOTE_PC_MCP_PORT` | `8765` | Listen port |
245
+ | `REMOTE_PC_MCP_ALLOWED_HOSTS` | _(empty)_ | Comma-separated allowlist for DNS-rebinding protection. Empty disables it (default — wrong threat model on a tailnet) |
246
+ | `REMOTE_PC_MCP_MAX_SHELL_TIMEOUT` | `600` (s) | Cap on per-call `shell_exec` timeout |
247
+ | `REMOTE_PC_MCP_MAX_READ_BYTES` | 50 MB | `read_file` upper limit |
248
+ | `REMOTE_PC_MCP_MAX_WRITE_BYTES` | 50 MB | `write_file` upper limit |
249
+ | `REMOTE_PC_MCP_MAX_DOWNLOAD_BYTES` | 2 GB | `download_file` upper limit |
250
+
251
+ After changing `.env`, restart the server so the new value takes effect:
252
+
253
+ ```bash
254
+ # Windows: easiest path is just re-run the installer (idempotent)
255
+ install.bat --uninstall && install.bat
256
+
257
+ # Linux
258
+ systemctl --user restart remote-pc-mcp
259
+ ```
260
+
261
+ ## Logs and troubleshooting
262
+
263
+ Two log files in the repo root, both rotated automatically:
264
+
265
+ | File | What's in it | Rotation |
266
+ |------|--------------|----------|
267
+ | `server.log` | App events + uvicorn startup/access logs | 10 MB × 5 |
268
+ | `daemon.log` | Supervisor events (crashes, restarts, backoff) | 2 MB × 3 |
269
+
270
+ **Server isn't responding?**
271
+
272
+ ```bash
273
+ # Is the listener up locally?
274
+ curl http://localhost:8765/health
275
+
276
+ # What's the supervisor seeing?
277
+ tail -f daemon.log
278
+
279
+ # Linux: full journal
280
+ journalctl --user -u remote-pc-mcp -f
281
+
282
+ # Windows: is the autostart registered?
283
+ explorer shell:startup # look for remote-pc-mcp.lnk
284
+ ```
285
+
286
+ **MCP client says tools are missing after a server restart?**
287
+
288
+ The streamable HTTP transport is designed so a restart does not brick clients, but the client still has to issue a request to notice the new server. First fix: invoke any tool from this server (e.g. ask your agent to run `system_info`) — the client will retry the connection. If that fails, reconnect the MCP server in your client (Claude Code: `/mcp` ; Cursor: refresh in MCP panel) or restart the client.
289
+
290
+ **Stuck process / port already in use?**
291
+
292
+ ```bash
293
+ # Windows
294
+ install.bat --uninstall && install.bat
295
+
296
+ # Linux
297
+ ./install.sh --uninstall && ./install.sh
298
+ ```
299
+
300
+ ## UI-driving tools
301
+
302
+ `take_screenshot`, `click`, `move_mouse`, `type_text`, `press_key`, and `scroll` require an **interactive desktop session**:
303
+
304
+ - **Windows**: a user must be logged in and the screen unlocked. A service running under Session 0 cannot reach the desktop. The Startup-folder install gives you exactly this — the daemon runs in your user session.
305
+ - **Linux**: needs an X11 or Wayland session. For screenshots specifically, install `scrot`, `gnome-screenshot`, or ImageMagick's `import` — `sudo apt install scrot` is the easiest.
306
+
307
+ ## Development
308
+
309
+ Project layout:
310
+
311
+ | File | Purpose |
312
+ |------|---------|
313
+ | `server.py` | The MCP server — tools, auth, transport |
314
+ | `daemon.py` | Supervisor — spawns server, restarts on crash with backoff |
315
+ | `_logging.py` | Shared logging config — one handler for app + uvicorn loggers |
316
+ | `install.{bat,sh}` | Single entry point: default installs, `--uninstall` removes |
317
+
318
+ ### Tests
319
+
320
+ A self-contained test suite under `tests/` launches its own isolated server on a high port with an ephemeral token, exercises every tool, and verifies that a mid-run server restart does not lock the client out. It does **not** touch the production server you have running.
321
+
322
+ ```bash
323
+ pip install -r requirements-dev.txt
324
+ python -m pytest tests/ -v
325
+ ```
326
+
327
+ ## License
328
+
329
+ MIT
330
+
331
+ <!-- mcp-name: io.github.raghibrm/remote-pc-mcp -->
@@ -0,0 +1,10 @@
1
+ remote_pc_mcp/__init__.py,sha256=kjFeUKi0GgeoBLqkM_HJF28ciNmdCS2CE42VsZpclLw,559
2
+ remote_pc_mcp/_logging.py,sha256=bAaYPuEDv7RGBUHbuN9BcObsPYiXuATAj_4nBxLSpGw,1424
3
+ remote_pc_mcp/daemon.py,sha256=ktd6vS6n9frjhVCgninZYWX-WsC4MXvbIynO1mSTG98,3415
4
+ remote_pc_mcp/server.py,sha256=Rndry9utOYQfl1QTSCecjYSsrtsUThj11D-oHMZrTKQ,25758
5
+ remote_pc_mcp-0.5.0.dist-info/licenses/LICENSE,sha256=BvQ-76P3GAlZPL7B0UPVz_HtiyJJGvLaylVWvruegdk,1068
6
+ remote_pc_mcp-0.5.0.dist-info/METADATA,sha256=R1ed_Rc9hRoGp0Ydk2mCQ16h66mTNHYuf_Cqcwu2K3E,13721
7
+ remote_pc_mcp-0.5.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
8
+ remote_pc_mcp-0.5.0.dist-info/entry_points.txt,sha256=-GruXC6iqGnpzkIArg6FiFfXyDAlqokbhsiPXyqnUc0,109
9
+ remote_pc_mcp-0.5.0.dist-info/top_level.txt,sha256=Lgxuudm9ccsOtUmGCHFJ-KxkSkKdH9uZ_s27G0NI_lE,14
10
+ remote_pc_mcp-0.5.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ remote-pc-mcp = remote_pc_mcp.server:main
3
+ remote-pc-mcp-daemon = remote_pc_mcp.daemon:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Raghib Murt
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ remote_pc_mcp