-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathOS_mcp_server.py
More file actions
2108 lines (1744 loc) · 86.6 KB
/
OS_mcp_server.py
File metadata and controls
2108 lines (1744 loc) · 86.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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import logging
import psutil
import platform
import shutil
import socket
import os
from pathlib import Path
from typing import List, Dict, Any, Optional
import datetime
from fastmcp import FastMCP
# Configure logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
logger = logging.getLogger(__name__)
mcp = FastMCP("Universal OS Information Helper")
# Global variable to store OS information
OS_INFO = {
"initialized": False,
"system": None,
"platform": None,
"version": None,
"architecture": None,
"hostname": None,
"python_version": None
}
def format_bytes(bytes_value: int) -> str:
"""Convert bytes to human readable format"""
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if bytes_value < 1024.0:
return f"{bytes_value:.2f} {unit}"
bytes_value /= 1024.0
return f"{bytes_value:.2f} PB"
def get_process_category(name: str) -> str:
"""Categorize processes for better understanding (works across all OS)"""
name_lower = name.lower()
# System processes (Windows, Linux, macOS)
if any(sys_name in name_lower for sys_name in [
'system', 'kernel', 'csrss', 'winlogon', 'services', 'lsass', 'svchost',
'systemd', 'init', 'launchd', 'kworker', 'ksoftirqd', 'migration'
]):
return "System Process"
# Web browsers
if any(browser in name_lower for browser in [
'chrome', 'firefox', 'safari', 'edge', 'opera', 'brave', 'chromium', 'vivaldi'
]):
return "Web Browser"
# Media/Entertainment
if any(media in name_lower for media in [
'spotify', 'vlc', 'media', 'music', 'video', 'netflix', 'youtube',
'itunes', 'rhythmbox', 'audacity'
]):
return "Media & Entertainment"
# Development tools
if any(dev in name_lower for dev in [
'code', 'visual', 'git', 'python', 'node', 'java', 'docker', 'terminal',
'vscode', 'pycharm', 'intellij', 'sublime', 'atom', 'vim', 'emacs'
]):
return "Development Tool"
# Office/Productivity
if any(office in name_lower for office in [
'word', 'excel', 'powerpoint', 'outlook', 'teams', 'slack', 'zoom',
'office', 'libreoffice', 'openoffice', 'notion', 'obsidian'
]):
return "Office & Productivity"
# Security
if any(sec in name_lower for sec in [
'antivirus', 'defender', 'security', 'firewall', 'malware', 'avast', 'norton'
]):
return "Security Software"
# Package managers and system tools
if any(pkg in name_lower for pkg in [
'apt', 'yum', 'dnf', 'pacman', 'brew', 'snap', 'flatpak'
]):
return "Package Manager"
return "Application"
def get_os_specific_commands() -> Dict[str, Any]:
"""Get OS-specific commands and paths"""
system = platform.system()
if system == "Windows":
return {
"clear_command": "cls",
"path_separator": "\\",
"temp_dir": os.environ.get('TEMP', 'C:\\Windows\\Temp'),
"home_dir": os.environ.get('USERPROFILE', 'C:\\Users\\'),
"package_manager": "winget or chocolatey",
"shell": "PowerShell or CMD"
}
elif system == "Darwin": # macOS
return {
"clear_command": "clear",
"path_separator": "/",
"temp_dir": "/tmp",
"home_dir": os.environ.get('HOME', '/Users/'),
"package_manager": "Homebrew",
"shell": "bash or zsh"
}
else: # Linux and other Unix-like
return {
"clear_command": "clear",
"path_separator": "/",
"temp_dir": "/tmp",
"home_dir": os.environ.get('HOME', '/home/'),
"package_manager": "apt/yum/dnf/pacman (distro-specific)",
"shell": "bash or zsh"
}
@mcp.tool
def initialize_os_connection() -> str:
"""
Initialize and detect the operating system.
This should be called first to establish OS-specific configurations.
Works on Windows, macOS, Linux, and other Unix-like systems.
"""
try:
global OS_INFO
# Get system information
uname = platform.uname()
OS_INFO = {
"initialized": True,
"system": uname.system,
"platform": platform.platform(),
"version": uname.version,
"release": uname.release,
"architecture": uname.machine,
"hostname": socket.gethostname(),
"python_version": platform.python_version(),
"processor": uname.processor or platform.processor(),
}
# Get OS-specific configurations
os_commands = get_os_specific_commands()
OS_INFO.update(os_commands)
result = "🔌 **OS CONNECTION INITIALIZED**\n\n"
result += "✅ Successfully connected to your operating system!\n\n"
result += "**DETECTED SYSTEM:**\n"
result += f"• Operating System: {OS_INFO['system']}\n"
result += f"• Platform: {OS_INFO['platform']}\n"
result += f"• Architecture: {OS_INFO['architecture']}\n"
result += f"• Computer Name: {OS_INFO['hostname']}\n"
result += f"• Processor: {OS_INFO['processor']}\n"
result += f"• Python Version: {OS_INFO['python_version']}\n\n"
result += "**OS-SPECIFIC CONFIGURATION:**\n"
result += f"• Shell: {OS_INFO['shell']}\n"
result += f"• Package Manager: {OS_INFO['package_manager']}\n"
result += f"• Home Directory: {OS_INFO['home_dir']}\n"
result += f"• Temp Directory: {OS_INFO['temp_dir']}\n\n"
# OS-specific notes
if OS_INFO['system'] == "Windows":
result += "**📝 WINDOWS NOTES:**\n"
result += "• Use Task Manager (Ctrl+Shift+Esc) for detailed process info\n"
result += "• Administrative privileges may be needed for some operations\n"
result += "• Windows Defender is your built-in security software\n"
elif OS_INFO['system'] == "Darwin":
result += "**📝 macOS NOTES:**\n"
result += "• Use Activity Monitor for detailed process info\n"
result += "• Some operations may require sudo privileges\n"
result += "• System Integrity Protection (SIP) may restrict certain actions\n"
else:
result += "**📝 LINUX/UNIX NOTES:**\n"
result += "• Use top/htop commands for detailed process info\n"
result += "• Some operations may require sudo privileges\n"
result += "• Package manager varies by distribution\n"
result += "\n✨ All tools are now ready to use!\n"
logger.info(f"OS initialized: {OS_INFO['system']} {OS_INFO['release']}")
return result
except Exception as e:
OS_INFO["initialized"] = False
return f"❌ Error initializing OS connection: {str(e)}"
def check_initialization() -> Optional[str]:
"""Check if OS has been initialized"""
if not OS_INFO.get("initialized", False):
return "⚠️ Please run 'initialize_os_connection' first to detect your operating system!"
return None
@mcp.tool
def get_running_processes(limit: int = 15) -> str:
"""
Get information about all running processes on the machine.
Works across Windows, macOS, Linux, and other Unix systems.
Args:
limit: Number of top processes to display (default: 15, max: 50)
"""
init_check = check_initialization()
if init_check:
return init_check
try:
limit = min(max(1, limit), 50) # Ensure limit is between 1 and 50
processes = []
for proc in psutil.process_iter(['pid', 'name', 'cpu_percent', 'memory_info', 'create_time', 'status', 'username']):
try:
pinfo = proc.info
category = get_process_category(pinfo['name'])
# Calculate memory usage
memory_mb = pinfo['memory_info'].rss / (1024 * 1024) if pinfo['memory_info'] else 0
# Calculate running time
create_time = datetime.datetime.fromtimestamp(pinfo['create_time'])
running_time = datetime.datetime.now() - create_time
# Get username (may fail on some systems)
username = pinfo.get('username', 'N/A')
if username and '\\' in username:
username = username.split('\\')[-1] # Remove domain on Windows
processes.append({
'name': pinfo['name'],
'pid': pinfo['pid'],
'category': category,
'memory_mb': memory_mb,
'cpu_percent': pinfo['cpu_percent'] or 0,
'status': pinfo['status'],
'running_time': str(running_time).split('.')[0],
'username': username
})
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
continue
# Sort by memory usage
processes.sort(key=lambda x: x['memory_mb'], reverse=True)
# Create summary
total_processes = len(processes)
categories = {}
for proc in processes:
cat = proc['category']
categories[cat] = categories.get(cat, 0) + 1
result = f"🖥️ **SYSTEM PROCESSES OVERVIEW** ({OS_INFO['system']})\n\n"
result += f"**Total Running Processes:** {total_processes}\n\n"
result += "**Process Categories:**\n"
for category, count in sorted(categories.items(), key=lambda x: x[1], reverse=True):
result += f"• {category}: {count} processes\n"
result += f"\n**TOP {limit} MEMORY CONSUMERS:**\n"
result += "*(These are using the most of your computer's memory)*\n\n"
for i, proc in enumerate(processes[:limit], 1):
memory_str = f"{proc['memory_mb']:.1f} MB"
cpu_str = f"{proc['cpu_percent']:.1f}%"
result += f"{i}. **{proc['name']}** ({proc['category']})\n"
result += f" - Memory: {memory_str} | CPU: {cpu_str} | Running: {proc['running_time']}\n"
result += f" - Status: {proc['status'].title()} | User: {proc['username']}\n\n"
result += "\n**WHAT THIS MEANS:**\n"
result += "• **Memory (MB)**: How much RAM each program is using\n"
result += "• **CPU (%)**: How much processing power each program is using\n"
result += "• **System Processes**: Core OS operations - usually safe to leave running\n"
result += "• **Applications**: Programs you've opened - you can usually close these if needed\n"
result += "• **High memory usage**: Normal for browsers, media apps, or if you have many tabs open\n"
return result
except Exception as e:
return f"❌ Error getting process information: {str(e)}"
@mcp.tool
def get_system_overview() -> str:
"""
Get a comprehensive overview of your computer's specifications and current status.
Works on Windows, macOS, Linux, and other Unix-like systems.
"""
init_check = check_initialization()
if init_check:
return init_check
try:
# CPU info
cpu_count = psutil.cpu_count(logical=False)
cpu_logical = psutil.cpu_count(logical=True)
cpu_freq = psutil.cpu_freq()
cpu_percent = psutil.cpu_percent(interval=1, percpu=False)
# Memory info
memory = psutil.virtual_memory()
swap = psutil.swap_memory()
# Disk info
disk = psutil.disk_usage('/')
# Boot time
boot_time = datetime.datetime.fromtimestamp(psutil.boot_time())
uptime = datetime.datetime.now() - boot_time
result = f"🖥️ **YOUR COMPUTER OVERVIEW**\n\n"
# Basic info
result += f"**Computer Name:** {OS_INFO['hostname']}\n"
result += f"**Operating System:** {OS_INFO['system']} {OS_INFO['release']}\n"
result += f"**Machine Type:** {OS_INFO['architecture']}\n"
result += f"**Processor:** {OS_INFO['processor']}\n\n"
# CPU details
result += f"**🔧 PROCESSOR (CPU) DETAILS:**\n"
result += f"• Physical CPU cores: {cpu_count}\n"
result += f"• Logical CPU cores (threads): {cpu_logical}\n"
if cpu_freq:
result += f"• Current CPU Speed: {cpu_freq.current:.0f} MHz\n"
if hasattr(cpu_freq, 'max') and cpu_freq.max > 0:
result += f"• Max CPU Speed: {cpu_freq.max:.0f} MHz\n"
result += f"• Current CPU Usage: {cpu_percent}%\n\n"
# Memory details
result += f"**💾 MEMORY (RAM) DETAILS:**\n"
result += f"• Total RAM: {format_bytes(memory.total)}\n"
result += f"• Available RAM: {format_bytes(memory.available)}\n"
result += f"• Used RAM: {format_bytes(memory.used)} ({memory.percent}%)\n"
if swap.total > 0:
result += f"• Swap/Page File: {format_bytes(swap.total)} ({swap.percent}% used)\n"
# Memory status
if memory.percent < 50:
result += f"• Status: ✅ Good - Plenty of memory available\n\n"
elif memory.percent < 80:
result += f"• Status: ⚠️ Moderate - Consider closing some programs\n\n"
else:
result += f"• Status: 🔴 High - Your computer might be slow\n\n"
# Disk details
result += f"**💿 STORAGE DETAILS:**\n"
result += f"• Total Storage: {format_bytes(disk.total)}\n"
result += f"• Used Storage: {format_bytes(disk.used)} ({disk.percent}%)\n"
result += f"• Free Storage: {format_bytes(disk.free)}\n"
# Storage status
if disk.percent < 70:
result += f"• Status: ✅ Good - Plenty of space available\n\n"
elif disk.percent < 90:
result += f"• Status: ⚠️ Moderate - Consider cleaning up files\n\n"
else:
result += f"• Status: 🔴 Low - Running out of space!\n\n"
# Uptime
result += f"**⏰ SYSTEM STATUS:**\n"
result += f"• Last Started: {boot_time.strftime('%Y-%m-%d %H:%M:%S')}\n"
result += f"• Running For: {str(uptime).split('.')[0]}\n\n"
# OS-specific tips
if OS_INFO['system'] == "Windows":
result += f"**💡 WINDOWS TIPS:**\n"
result += f"• Press Win+X for quick system access\n"
result += f"• Use Disk Cleanup to free up space\n"
elif OS_INFO['system'] == "Darwin":
result += f"**💡 macOS TIPS:**\n"
result += f"• Check 'About This Mac' for more details\n"
result += f"• Use Storage Management to optimize space\n"
else:
result += f"**💡 LINUX TIPS:**\n"
result += f"• Use 'df -h' for disk info\n"
result += f"• Use 'free -h' for memory info\n"
return result
except Exception as e:
return f"❌ Error getting system overview: {str(e)}"
@mcp.tool
def get_network_info() -> str:
"""
Get information about your network connections and internet status.
Works across all operating systems.
"""
init_check = check_initialization()
if init_check:
return init_check
try:
result = f"🌐 **NETWORK INFORMATION** ({OS_INFO['system']})\n\n"
# Hostname and IP
hostname = socket.gethostname()
try:
local_ip = socket.gethostbyname(hostname)
result += f"**Computer Name:** {hostname}\n"
result += f"**Local IP Address:** {local_ip}\n\n"
except:
result += f"**Computer Name:** {hostname}\n"
result += f"**Local IP Address:** Unable to determine\n\n"
# Network interfaces
interfaces = psutil.net_if_addrs()
stats = psutil.net_if_stats()
result += f"**🔌 NETWORK CONNECTIONS:**\n"
for interface_name, addresses in interfaces.items():
if interface_name in stats:
is_up = stats[interface_name].isup
status = "🟢 Connected" if is_up else "🔴 Disconnected"
speed = stats[interface_name].speed
speed_str = f" @ {speed}Mbps" if speed > 0 else ""
result += f"• **{interface_name}**: {status}{speed_str}\n"
for addr in addresses:
if addr.family == socket.AF_INET: # IPv4
result += f" - IPv4: {addr.address}\n"
elif addr.family == socket.AF_INET6: # IPv6
result += f" - IPv6: {addr.address}\n"
result += f"\n"
# Network usage
net_io = psutil.net_io_counters()
result += f"**📊 NETWORK USAGE (Since Boot):**\n"
result += f"• Data Sent: {format_bytes(net_io.bytes_sent)}\n"
result += f"• Data Received: {format_bytes(net_io.bytes_recv)}\n"
result += f"• Packets Sent: {net_io.packets_sent:,}\n"
result += f"• Packets Received: {net_io.packets_recv:,}\n"
if net_io.errin > 0 or net_io.errout > 0:
result += f"• Errors: {net_io.errin + net_io.errout}\n"
result += f"\n"
# Active connections (with error handling for different OS)
try:
connections = psutil.net_connections(kind='inet')
active_connections = [conn for conn in connections if conn.status == 'ESTABLISHED']
result += f"**🔗 ACTIVE CONNECTIONS:**\n"
result += f"• Total Active Connections: {len(active_connections)}\n"
# Group by remote address
remote_addresses = {}
for conn in active_connections[:10]:
if conn.raddr:
addr = conn.raddr.ip
remote_addresses[addr] = remote_addresses.get(addr, 0) + 1
if remote_addresses:
result += f"• Connected to these servers:\n"
for addr, count in list(remote_addresses.items())[:5]:
result += f" - {addr} ({count} connection{'s' if count > 1 else ''})\n"
except (psutil.AccessDenied, PermissionError):
result += f"**🔗 ACTIVE CONNECTIONS:**\n"
result += f"• Requires elevated privileges to view connection details\n"
result += f"\n**WHAT THIS MEANS:**\n"
result += f"• **Local IP**: Your computer's address on your home/office network\n"
result += f"• **Connections**: Programs communicating with internet servers\n"
result += f"• **Data Sent/Received**: How much internet data you've used\n"
return result
except Exception as e:
return f"❌ Error getting network information: {str(e)}"
@mcp.tool
def get_disk_usage() -> str:
"""
Show detailed information about disk space usage and storage devices.
Works on Windows (C:, D:, etc.), macOS (/), and Linux (/, /home, etc.).
"""
init_check = check_initialization()
if init_check:
return init_check
try:
result = f"💿 **STORAGE & DISK USAGE** ({OS_INFO['system']})\n\n"
# Get all disk partitions
partitions = psutil.disk_partitions(all=False)
for partition in partitions:
try:
usage = psutil.disk_usage(partition.mountpoint)
# Format device name
device = partition.device
mountpoint = partition.mountpoint
result += f"**Drive: {device}** (Mounted at: {mountpoint})\n"
result += f"• File System: {partition.fstype}\n"
result += f"• Total Size: {format_bytes(usage.total)}\n"
result += f"• Used: {format_bytes(usage.used)} ({usage.percent}%)\n"
result += f"• Free: {format_bytes(usage.free)}\n"
# Status indicator
if usage.percent < 70:
result += f"• Status: ✅ Healthy\n"
elif usage.percent < 90:
result += f"• Status: ⚠️ Getting Full\n"
else:
result += f"• Status: 🔴 Almost Full!\n"
result += f"\n"
except (PermissionError, OSError):
result += f"**Drive: {partition.device}** - No access or unavailable\n\n"
# Disk I/O statistics
try:
disk_io = psutil.disk_io_counters()
if disk_io:
result += f"**📊 DISK ACTIVITY (Since Boot):**\n"
result += f"• Data Read: {format_bytes(disk_io.read_bytes)}\n"
result += f"• Data Written: {format_bytes(disk_io.write_bytes)}\n"
result += f"• Read Operations: {disk_io.read_count:,}\n"
result += f"• Write Operations: {disk_io.write_count:,}\n\n"
except Exception:
pass # Some systems don't support disk I/O counters
result += f"**WHAT THIS MEANS:**\n"
result += f"• **Total Size**: Maximum storage capacity\n"
result += f"• **Used**: How much space is currently occupied\n"
result += f"• **Free**: How much space is available for new files\n"
result += f"• **Healthy**: Below 70% usage - good performance\n"
result += f"• **Getting Full**: 70-90% usage - consider cleanup\n"
result += f"• **Almost Full**: Above 90% - performance may suffer\n"
return result
except Exception as e:
return f"❌ Error getting disk usage: {str(e)}"
@mcp.tool
def get_performance_summary() -> str:
"""
Get a quick performance summary of your computer.
Universal health check for Windows, macOS, and Linux.
"""
init_check = check_initialization()
if init_check:
return init_check
try:
result = f"⚡ **COMPUTER PERFORMANCE SUMMARY** ({OS_INFO['system']})\n\n"
# CPU
cpu_percent = psutil.cpu_percent(interval=1)
cpu_count = psutil.cpu_count()
# Memory
memory = psutil.virtual_memory()
# Disk
disk = psutil.disk_usage('/')
# Load averages (Unix/Linux/Mac only)
load_1min = None
try:
load_avg = psutil.getloadavg()
load_1min = load_avg[0]
except (AttributeError, OSError):
pass # Not available on Windows
# Temperature (if available)
temps = {}
try:
temps = psutil.sensors_temperatures()
except (AttributeError, OSError):
pass # Not available on all systems
# Overall health score
health_score = 100
issues = []
warnings = []
# Check CPU
if cpu_percent > 80:
health_score -= 30
issues.append("🔴 High CPU usage - System may be slow")
elif cpu_percent > 60:
health_score -= 15
warnings.append("⚠️ Moderate CPU usage")
# Check Memory
if memory.percent > 85:
health_score -= 30
issues.append("🔴 Low memory available - Close some programs")
elif memory.percent > 70:
health_score -= 15
warnings.append("⚠️ Moderate memory usage")
# Check Disk
if disk.percent > 90:
health_score -= 25
issues.append("🔴 Very low disk space - Delete files urgently")
elif disk.percent > 80:
health_score -= 10
warnings.append("⚠️ Low disk space")
# Performance status
if health_score >= 85:
status = "🟢 EXCELLENT"
advice = "Your computer is running very well!"
elif health_score >= 70:
status = "🟡 GOOD"
advice = "Your computer is running well with minor issues."
elif health_score >= 50:
status = "🟠 FAIR"
advice = "Your computer has some performance issues that need attention."
else:
status = "🔴 POOR"
advice = "Your computer has significant performance issues!"
result += f"**OVERALL STATUS: {status}**\n"
result += f"**Health Score: {health_score}/100**\n\n"
result += f"**📊 CURRENT METRICS:**\n"
result += f"• CPU Usage: {cpu_percent}% ({cpu_count} cores available)\n"
result += f"• Memory Usage: {memory.percent}% ({format_bytes(memory.available)} available)\n"
result += f"• Disk Usage: {disk.percent}% ({format_bytes(disk.free)} free)\n"
if load_1min is not None:
load_per_core = load_1min / cpu_count
result += f"• System Load: {load_1min:.2f} ({load_per_core:.2f} per core)\n"
# Temperature info if available
if temps:
try:
for name, entries in temps.items():
for entry in entries:
if entry.current > 0:
result += f"• Temperature ({name}): {entry.current}°C\n"
if entry.current > 80:
warnings.append("⚠️ High system temperature detected")
break
break # Only show first sensor
except Exception:
pass
result += f"\n**🎯 ASSESSMENT:**\n{advice}\n\n"
if issues:
result += f"**🔴 CRITICAL ISSUES:**\n"
for issue in issues:
result += f"{issue}\n"
result += f"\n"
if warnings:
result += f"**⚠️ WARNINGS:**\n"
for warning in warnings:
result += f"{warning}\n"
result += f"\n"
# Quick fixes
result += f"**🔧 RECOMMENDED ACTIONS:**\n"
if cpu_percent > 70:
result += f"• Close unnecessary programs and browser tabs\n"
if memory.percent > 70:
result += f"• Restart memory-intensive applications\n"
result += f"• Consider restarting your computer\n"
if disk.percent > 80:
result += f"• Delete temporary files and downloads\n"
result += f"• Uninstall unused programs\n"
result += f"• Empty recycle bin/trash\n"
if not issues and not warnings:
result += f"• No immediate action needed - system is healthy!\n"
result += f"• Continue regular maintenance\n"
return result
except Exception as e:
return f"❌ Error getting performance summary: {str(e)}"
@mcp.tool
def get_temperature_info() -> str:
"""
Get temperature information from system sensors (when available).
Works on systems with temperature monitoring support (mainly Linux and some macOS).
"""
init_check = check_initialization()
if init_check:
return init_check
try:
result = f"🌡️ **SYSTEM TEMPERATURE MONITORING** ({OS_INFO['system']})\n\n"
try:
temps = psutil.sensors_temperatures()
if not temps:
result += "⚠️ No temperature sensors detected on this system.\n\n"
result += "**NOTE:**\n"
if OS_INFO['system'] == "Windows":
result += "• Windows requires specialized software for temperature monitoring\n"
result += "• Try tools like: HWMonitor, Core Temp, or Open Hardware Monitor\n"
elif OS_INFO['system'] == "Darwin":
result += "• macOS has limited temperature sensor access\n"
result += "• Try tools like: iStat Menus or Intel Power Gadget\n"
else:
result += "• Make sure lm-sensors is installed: sudo apt install lm-sensors\n"
result += "• Run: sudo sensors-detect\n"
return result
result += "**DETECTED SENSORS:**\n\n"
for name, entries in temps.items():
result += f"**{name.upper()}:**\n"
for entry in entries:
temp = entry.current
label = entry.label or "Sensor"
# Temperature status
if temp < 50:
status = "✅ Cool"
elif temp < 70:
status = "🟡 Warm"
elif temp < 85:
status = "🟠 Hot"
else:
status = "🔴 Very Hot!"
result += f"• {label}: {temp}°C ({temp * 9/5 + 32:.1f}°F) - {status}\n"
# Show high/critical temps if available
if entry.high:
result += f" - Warning threshold: {entry.high}°C\n"
if entry.critical:
result += f" - Critical threshold: {entry.critical}°C\n"
result += "\n"
result += "**TEMPERATURE GUIDE:**\n"
result += "• **< 50°C**: Optimal - System is cool\n"
result += "• **50-70°C**: Normal - System is warm under load\n"
result += "• **70-85°C**: High - Consider improving cooling\n"
result += "• **> 85°C**: Critical - Risk of thermal throttling or damage\n\n"
result += "**COOLING TIPS:**\n"
result += "• Ensure proper ventilation around your computer\n"
result += "• Clean dust from vents and fans\n"
result += "• Use laptop on hard, flat surfaces\n"
result += "• Consider a cooling pad for laptops\n"
except AttributeError:
result += "⚠️ Temperature monitoring not supported on this platform.\n"
result += f"Your OS ({OS_INFO['system']}) may not provide sensor access through this interface.\n"
return result
except Exception as e:
return f"❌ Error getting temperature information: {str(e)}"
@mcp.tool
def get_battery_info() -> str:
"""
Get battery status and information (for laptops and devices with batteries).
Works on Windows, macOS, and Linux laptops.
"""
init_check = check_initialization()
if init_check:
return init_check
try:
result = f"🔋 **BATTERY INFORMATION** ({OS_INFO['system']})\n\n"
if not hasattr(psutil, 'sensors_battery'):
result += "⚠️ Battery monitoring not available on this system.\n"
return result
battery = psutil.sensors_battery()
if battery is None:
result += "⚠️ No battery detected.\n"
result += "This is likely a desktop computer or battery information is unavailable.\n"
return result
# Battery percentage
percent = battery.percent
plugged = battery.power_plugged
# Status
if plugged:
if percent >= 100:
status = "🟢 Fully Charged"
else:
status = "🔌 Charging"
else:
if percent > 50:
status = "🟢 Discharging"
elif percent > 20:
status = "🟡 Discharging"
else:
status = "🔴 Low Battery"
result += f"**BATTERY STATUS: {status}**\n\n"
result += f"**CURRENT CHARGE:**\n"
result += f"• Battery Level: {percent}%\n"
result += f"• Power Plugged In: {'Yes' if plugged else 'No'}\n"
# Time remaining
if battery.secsleft != psutil.POWER_TIME_UNLIMITED and battery.secsleft != psutil.POWER_TIME_UNKNOWN:
hours, remainder = divmod(battery.secsleft, 3600)
minutes = remainder // 60
if plugged:
result += f"• Time until full charge: {int(hours)}h {int(minutes)}m\n"
else:
result += f"• Time remaining: {int(hours)}h {int(minutes)}m\n"
elif plugged and percent >= 100:
result += f"• Status: Fully charged\n"
elif battery.secsleft == psutil.POWER_TIME_UNLIMITED:
result += f"• Status: Calculating...\n"
result += "\n**BATTERY HEALTH:**\n"
if percent < 20 and not plugged:
result += "🔴 **Warning**: Battery is low! Plug in your charger soon.\n"
elif percent < 10 and not plugged:
result += "🔴 **Critical**: Battery is critically low! Plug in immediately.\n"
elif percent > 80 and plugged:
result += "✅ Battery is well charged.\n"
else:
result += "✅ Battery is in good condition.\n"
result += "\n**BATTERY CARE TIPS:**\n"
result += "• Avoid fully draining the battery regularly\n"
result += "• Keep charge between 20-80% for optimal battery life\n"
result += "• Avoid extreme temperatures\n"
result += "• Unplug once fully charged (if possible)\n"
return result
except Exception as e:
return f"❌ Error getting battery information: {str(e)}"
@mcp.tool
def check_startup_programs() -> str:
"""
Show programs that start automatically when your computer boots up.
Helps identify what might be slowing down startup time.
Works across Windows, macOS, and Linux.
"""
init_check = check_initialization()
if init_check:
return init_check
try:
result = f"🚀 **STARTUP PROGRAMS** ({OS_INFO['system']})\n\n"
# Get processes and check which ones started recently (likely startup programs)
boot_time = psutil.boot_time()
startup_window = 300 # 5 minutes after boot
startup_threshold = boot_time + startup_window
startup_processes = []
for proc in psutil.process_iter(['pid', 'name', 'create_time', 'memory_info']):
try:
pinfo = proc.info
if pinfo['create_time'] <= startup_threshold:
category = get_process_category(pinfo['name'])
memory_mb = pinfo['memory_info'].rss / (1024 * 1024) if pinfo['memory_info'] else 0
startup_processes.append({
'name': pinfo['name'],
'category': category,
'memory_mb': memory_mb,
'start_time': datetime.datetime.fromtimestamp(pinfo['create_time'])
})
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
continue
# Sort by memory usage
startup_processes.sort(key=lambda x: x['memory_mb'], reverse=True)
# Calculate stats
total_startup = len(startup_processes)
total_memory = sum(p['memory_mb'] for p in startup_processes)
result += f"**STARTUP SUMMARY:**\n"
result += f"• Total startup programs: {total_startup}\n"
result += f"• Memory used by startup programs: {total_memory:.1f} MB\n"
result += f"• System boot time: {datetime.datetime.fromtimestamp(boot_time).strftime('%Y-%m-%d %H:%M:%S')}\n\n"
# Group by category
categories = {}
for proc in startup_processes:
cat = proc['category']
if cat not in categories:
categories[cat] = []
categories[cat].append(proc)
result += f"**STARTUP PROGRAMS BY CATEGORY:**\n\n"
for category, procs in sorted(categories.items(), key=lambda x: len(x[1]), reverse=True):
result += f"**{category}** ({len(procs)} programs):\n"
# Sort processes in category by memory usage
procs.sort(key=lambda x: x['memory_mb'], reverse=True)
for proc in procs[:5]: # Show top 5 in each category
result += f"• {proc['name']} - {proc['memory_mb']:.1f} MB\n"
if len(procs) > 5:
result += f"• ... and {len(procs) - 5} more\n"
result += f"\n"
# Performance impact assessment
result += f"**🎯 STARTUP PERFORMANCE ASSESSMENT:**\n"
if total_startup < 20:
result += f"✅ **Good**: Reasonable number of startup programs\n"
elif total_startup < 40:
result += f"⚠️ **Moderate**: Quite a few startup programs\n"
else:
result += f"🔴 **High**: Many startup programs may slow boot time\n"
if total_memory < 500:
result += f"✅ **Good**: Startup programs use reasonable memory\n"
elif total_memory < 1000:
result += f"⚠️ **Moderate**: Startup programs use significant memory\n"
else:
result += f"🔴 **High**: Startup programs use a lot of memory\n"
result += f"\n**💡 HOW TO MANAGE STARTUP PROGRAMS:**\n"
if OS_INFO['system'] == "Windows":
result += f"• Press Ctrl+Shift+Esc → Startup tab\n"
result += f"• Or: Settings → Apps → Startup\n"
elif OS_INFO['system'] == "Darwin":
result += f"• System Preferences → Users & Groups → Login Items\n"
result += f"• Or: System Settings → General → Login Items\n"
else:
result += f"• Check ~/.config/autostart/ directory\n"
result += f"• Or use your desktop environment's startup settings\n"
result += f"\n**⚠️ RECOMMENDATIONS:**\n"
result += f"• **System Processes**: Essential - don't disable\n"
result += f"• **Security Software**: Important - keep enabled\n"
result += f"• **Applications**: Disable if not used daily\n"
result += f"• **Development Tools**: Disable unless actively coding\n"
return result
except Exception as e:
return f"❌ Error checking startup programs: {str(e)}"
@mcp.tool
def get_user_info() -> str:
"""
Get information about system users and current user session.
Works on Windows, macOS, and Linux.
"""
init_check = check_initialization()
if init_check:
return init_check
try:
result = f"👤 **USER INFORMATION** ({OS_INFO['system']})\n\n"
# Current user
current_user = os.getlogin() if hasattr(os, 'getlogin') else os.environ.get('USER', os.environ.get('USERNAME', 'Unknown'))
result += f"**CURRENT USER:**\n"
result += f"• Username: {current_user}\n"
result += f"• Home Directory: {Path.home()}\n"
# Try to get additional user info
try:
import pwd
user_info = pwd.getpwnam(current_user)
result += f"• User ID (UID): {user_info.pw_uid}\n"
result += f"• Group ID (GID): {user_info.pw_gid}\n"
result += f"• Real Name: {user_info.pw_gecos}\n"
result += f"• Shell: {user_info.pw_shell}\n"
except (ImportError, KeyError):
# Windows or user not found
result += f"• User ID: {os.getuid() if hasattr(os, 'getuid') else 'N/A'}\n"
result += f"\n**LOGGED IN USERS:**\n"
# Get all logged in users