forked from doobidoo/mcp-memory-service
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall.py
More file actions
3228 lines (2737 loc) · 137 KB
/
install.py
File metadata and controls
3228 lines (2737 loc) · 137 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
#!/usr/bin/env python3
# Copyright 2024 Heinrich Krupp
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Installation script for MCP Memory Service with cross-platform compatibility.
This script guides users through the installation process with the appropriate
dependencies for their platform.
"""
import os
import sys
import platform
import subprocess
import argparse
import shutil
from pathlib import Path
# Import shared GPU detection utilities
try:
from src.mcp_memory_service.utils.gpu_detection import detect_gpu as shared_detect_gpu
except ImportError:
# Fallback for development/testing scenarios
sys.path.insert(0, str(Path(__file__).parent))
from src.mcp_memory_service.utils.gpu_detection import detect_gpu as shared_detect_gpu
# Fix Windows console encoding issues
if platform.system() == "Windows":
# Ensure stdout uses UTF-8 on Windows to prevent character encoding issues in logs
if hasattr(sys.stdout, 'reconfigure'):
try:
sys.stdout.reconfigure(encoding='utf-8')
sys.stderr.reconfigure(encoding='utf-8')
except AttributeError:
pass
# Enhanced logging system for installer
import logging
from datetime import datetime
class DualOutput:
"""Class to handle both console and file output simultaneously."""
def __init__(self, log_file_path):
self.console = sys.stdout
self.log_file = None
self.log_file_path = log_file_path
self._setup_log_file()
def _setup_log_file(self):
"""Set up the log file with proper encoding."""
try:
# Create log file with UTF-8 encoding
self.log_file = open(self.log_file_path, 'w', encoding='utf-8')
# Write header
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# Fix Windows version display in log header
platform_info = f"{platform.system()} {platform.release()}"
if platform.system() == "Windows":
try:
import winreg
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows NT\CurrentVersion")
build_number = winreg.QueryValueEx(key, "CurrentBuildNumber")[0]
winreg.CloseKey(key)
# Windows 11 has build number >= 22000
if int(build_number) >= 22000:
platform_info = f"Windows 11"
else:
platform_info = f"Windows {platform.release()}"
except (ImportError, OSError, ValueError):
pass # Use default
header = f"""
================================================================================
MCP Memory Service Installation Log
Started: {timestamp}
Platform: {platform_info} ({platform.machine()})
Python: {sys.version}
================================================================================
"""
self.log_file.write(header)
self.log_file.flush()
except Exception as e:
print(f"Warning: Could not create log file {self.log_file_path}: {e}")
self.log_file = None
def write(self, text):
"""Write to both console and log file."""
# Write to console
self.console.write(text)
self.console.flush()
# Write to log file if available
if self.log_file:
try:
self.log_file.write(text)
self.log_file.flush()
except Exception:
pass # Silently ignore log file write errors
def flush(self):
"""Flush both outputs."""
self.console.flush()
if self.log_file:
try:
self.log_file.flush()
except Exception:
pass
def close(self):
"""Close the log file."""
if self.log_file:
try:
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
footer = f"""
================================================================================
Installation completed: {timestamp}
================================================================================
"""
self.log_file.write(footer)
self.log_file.close()
except Exception:
pass
# Global dual output instance
_dual_output = None
def setup_installer_logging():
"""Set up the installer logging system."""
global _dual_output
# Create log file path
log_file = Path.cwd() / "installation.log"
# Remove old log file if it exists
if log_file.exists():
try:
log_file.unlink()
except Exception:
pass
# Set up dual output
_dual_output = DualOutput(str(log_file))
# Redirect stdout to dual output
sys.stdout = _dual_output
print(f"Installation log will be saved to: {log_file}")
return str(log_file)
def cleanup_installer_logging():
"""Clean up the installer logging system."""
global _dual_output
if _dual_output:
# Restore original stdout
sys.stdout = _dual_output.console
_dual_output.close()
_dual_output = None
# Import Claude commands utilities
try:
from scripts.claude_commands_utils import install_claude_commands, check_claude_code_cli
except ImportError:
# Handle case where script is run from different directory
script_dir = Path(__file__).parent
sys.path.insert(0, str(script_dir))
try:
from scripts.claude_commands_utils import install_claude_commands, check_claude_code_cli
except ImportError:
install_claude_commands = None
check_claude_code_cli = None
# Global variable to store the uv executable path
UV_EXECUTABLE_PATH = None
def print_header(text):
"""Print a formatted header."""
print("\n" + "=" * 80)
print(f" {text}")
print("=" * 80)
def print_step(step, text):
"""Print a formatted step."""
print(f"\n[{step}] {text}")
def print_info(text):
"""Print formatted info text."""
print(f" -> {text}")
def print_error(text):
"""Print formatted error text."""
print(f" [ERROR] {text}")
def print_success(text):
"""Print formatted success text."""
print(f" [OK] {text}")
def print_warning(text):
"""Print formatted warning text."""
print(f" [WARNING] {text}")
def prompt_user_input(prompt_text, default_value=""):
"""
Prompt user for input with formatted banner.
Args:
prompt_text: The input prompt to display
default_value: Optional default value if user presses Enter
Returns:
User's input (or default if empty)
"""
print("\n" + "=" * 60)
print("⚠️ USER INPUT REQUIRED")
print("=" * 60)
response = input(prompt_text).strip()
print("=" * 60 + "\n")
return response if response else default_value
def build_mcp_server_config(storage_backend="sqlite_vec", repo_path=None):
"""
Build MCP server configuration dict for multi-client access.
Args:
storage_backend: Storage backend to use (sqlite_vec or chromadb)
repo_path: Repository path (defaults to current directory)
Returns:
Dict containing MCP server configuration with command, args, and env
"""
if repo_path is None:
repo_path = str(Path.cwd())
# Build environment configuration based on storage backend
env_config = {
"MCP_MEMORY_STORAGE_BACKEND": storage_backend,
"LOG_LEVEL": "INFO"
}
# Add backend-specific configuration
if storage_backend == "sqlite_vec":
env_config["MCP_MEMORY_SQLITE_PRAGMAS"] = "busy_timeout=15000,cache_size=20000"
return {
"command": UV_EXECUTABLE_PATH or "uv",
"args": ["--directory", repo_path, "run", "memory"],
"env": env_config
}
# Cache for system detection to avoid duplicate calls
_system_info_cache = None
def detect_system():
"""Detect the system architecture and platform."""
global _system_info_cache
if _system_info_cache is not None:
return _system_info_cache
system = platform.system().lower()
machine = platform.machine().lower()
python_version = f"{sys.version_info.major}.{sys.version_info.minor}"
is_windows = system == "windows"
is_macos = system == "darwin"
is_linux = system == "linux"
is_arm = machine in ("arm64", "aarch64")
is_x86 = machine in ("x86_64", "amd64", "x64")
# Fix Windows version detection - Windows 11 reports as Windows 10
if is_windows:
try:
import winreg
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows NT\CurrentVersion")
build_number = winreg.QueryValueEx(key, "CurrentBuildNumber")[0]
winreg.CloseKey(key)
# Windows 11 has build number >= 22000
if int(build_number) >= 22000:
windows_version = "11"
else:
windows_version = platform.release()
except (ImportError, OSError, ValueError):
windows_version = platform.release()
print_info(f"System: {platform.system()} {windows_version}")
else:
print_info(f"System: {platform.system()} {platform.release()}")
print_info(f"Architecture: {machine}")
print_info(f"Python: {python_version}")
# Check for virtual environment
in_venv = sys.prefix != sys.base_prefix
if not in_venv:
print_warning("Not running in a virtual environment. It's recommended to install in a virtual environment.")
else:
print_info(f"Virtual environment: {sys.prefix}")
# Check for Homebrew PyTorch installation
has_homebrew_pytorch = False
homebrew_pytorch_version = None
if is_macos:
try:
# Check if pytorch is installed via brew
print_info("Checking for Homebrew PyTorch installation...")
result = subprocess.run(
['brew', 'list', 'pytorch', '--version'],
capture_output=True,
text=True,
timeout=30 # Increased timeout to prevent hanging
)
if result.returncode == 0:
has_homebrew_pytorch = True
# Extract version from output
version_line = result.stdout.strip()
homebrew_pytorch_version = version_line.split()[1] if len(version_line.split()) > 1 else "Unknown"
print_info(f"Detected Homebrew PyTorch installation: {homebrew_pytorch_version}")
except subprocess.TimeoutExpired:
print_info("Homebrew PyTorch detection timed out - skipping")
has_homebrew_pytorch = False
except (subprocess.SubprocessError, FileNotFoundError):
pass
_system_info_cache = {
"system": system,
"machine": machine,
"python_version": python_version,
"is_windows": is_windows,
"is_macos": is_macos,
"is_linux": is_linux,
"is_arm": is_arm,
"is_x86": is_x86,
"in_venv": in_venv,
"has_homebrew_pytorch": has_homebrew_pytorch,
"homebrew_pytorch_version": homebrew_pytorch_version
}
return _system_info_cache
def check_sqlite_extension_support():
"""Check if Python's sqlite3 supports loading extensions."""
import sqlite3
test_conn = None
try:
test_conn = sqlite3.connect(":memory:")
if not hasattr(test_conn, 'enable_load_extension'):
return False, "Python sqlite3 module not compiled with extension support"
# Test if we can actually enable extension loading
test_conn.enable_load_extension(True)
test_conn.enable_load_extension(False)
return True, "Extension loading supported"
except AttributeError as e:
return False, f"enable_load_extension not available: {e}"
except Exception as e:
return False, f"Extension support check failed: {e}"
finally:
if test_conn:
test_conn.close()
def detect_gpu():
"""Detect GPU and acceleration capabilities.
Wrapper function that uses the shared GPU detection module.
"""
system_info = detect_system()
# Use shared GPU detection module
gpu_info = shared_detect_gpu(system_info)
# Print GPU information (maintain installer output format)
if gpu_info.get("has_cuda"):
cuda_version = gpu_info.get("cuda_version")
print_info(f"CUDA detected: {cuda_version or 'Unknown version'}")
if gpu_info.get("has_rocm"):
rocm_version = gpu_info.get("rocm_version")
print_info(f"ROCm detected: {rocm_version or 'Unknown version'}")
if gpu_info.get("has_mps"):
print_info("Apple Metal Performance Shaders (MPS) detected")
if gpu_info.get("has_directml"):
directml_version = gpu_info.get("directml_version")
if directml_version:
print_info(f"DirectML detected: {directml_version}")
else:
print_info("DirectML detected")
if not (gpu_info.get("has_cuda") or gpu_info.get("has_rocm") or
gpu_info.get("has_mps") or gpu_info.get("has_directml")):
print_info("No GPU acceleration detected, will use CPU-only mode")
return gpu_info
def check_dependencies():
"""Check for required dependencies.
Note on package managers:
- Traditional virtual environments (venv, virtualenv) include pip by default
- Alternative package managers like uv may not include pip or may manage packages differently
- We attempt multiple detection methods for pip and only fail if:
a) We're not in a virtual environment, or
b) We can't detect pip AND can't install dependencies
We proceed with installation even if pip isn't detected when in a virtual environment,
assuming an alternative package manager (like uv) is handling dependencies.
Returns:
bool: True if all dependencies are met, False otherwise.
"""
print_step("2", "Checking dependencies")
# Check for pip
pip_installed = False
# Try subprocess check first
try:
subprocess.check_call([sys.executable, '-m', 'pip', '--version'],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
pip_installed = True
print_info("pip is installed")
except subprocess.SubprocessError:
# Fallback to import check
try:
import pip
pip_installed = True
print_info(f"pip is installed: {pip.__version__}")
except ImportError:
# Check if we're in a virtual environment
in_venv = sys.prefix != sys.base_prefix
if in_venv:
print_warning("pip could not be detected, but you're in a virtual environment. "
"If you're using uv or another alternative package manager, this is normal. "
"Continuing installation...")
pip_installed = True # Proceed anyway
else:
print_error("pip is not installed. Please install pip first.")
return False
# Check for setuptools
try:
import setuptools
print_info(f"setuptools is installed: {setuptools.__version__}")
except ImportError:
print_warning("setuptools is not installed. Will attempt to install it.")
# If pip is available, use it to install setuptools
if pip_installed:
try:
subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'setuptools'],
stdout=subprocess.DEVNULL)
print_success("setuptools installed successfully")
except subprocess.SubprocessError:
# Check if in virtual environment
in_venv = sys.prefix != sys.base_prefix
if in_venv:
print_warning("Failed to install setuptools with pip. If you're using an alternative package manager "
"like uv, please install setuptools manually using that tool (e.g., 'uv pip install setuptools').")
else:
print_error("Failed to install setuptools. Please install it manually.")
return False
else:
# Should be unreachable since pip_installed would only be False if we returned earlier
print_error("Cannot install setuptools without pip. Please install setuptools manually.")
return False
# Check for wheel
try:
import wheel
print_info(f"wheel is installed: {wheel.__version__}")
except ImportError:
print_warning("wheel is not installed. Will attempt to install it.")
# If pip is available, use it to install wheel
if pip_installed:
try:
subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'wheel'],
stdout=subprocess.DEVNULL)
print_success("wheel installed successfully")
except subprocess.SubprocessError:
# Check if in virtual environment
in_venv = sys.prefix != sys.base_prefix
if in_venv:
print_warning("Failed to install wheel with pip. If you're using an alternative package manager "
"like uv, please install wheel manually using that tool (e.g., 'uv pip install wheel').")
else:
print_error("Failed to install wheel. Please install it manually.")
return False
else:
# Should be unreachable since pip_installed would only be False if we returned earlier
print_error("Cannot install wheel without pip. Please install wheel manually.")
return False
return True
def install_pytorch_platform_specific(system_info, gpu_info, args=None):
"""Install PyTorch with platform-specific configurations."""
# Check if PyTorch installation should be skipped
if args and args.skip_pytorch:
print_info("Skipping PyTorch installation as requested")
return True
if system_info["is_windows"]:
return install_pytorch_windows(gpu_info)
elif system_info["is_macos"] and system_info["is_x86"]:
return install_pytorch_macos_intel()
elif system_info["is_macos"] and system_info["is_arm"]:
return install_pytorch_macos_arm64()
else:
# For other platforms, let the regular installer handle it
return True
def install_pytorch_macos_intel():
"""Install PyTorch specifically for macOS with Intel CPUs."""
print_step("3a", "Installing PyTorch for macOS Intel CPU")
# Use the versions known to work well on macOS Intel and with Python 3.13+
try:
# For Python 3.13+, we need newer PyTorch versions
python_version = sys.version_info
if python_version >= (3, 13):
# For Python 3.13+, try to install latest compatible version
print_info(f"Installing PyTorch for macOS Intel (Python {python_version.major}.{python_version.minor})...")
print_info("Attempting to install latest PyTorch compatible with Python 3.13...")
try:
# Try to install without version specifiers to get latest compatible version
cmd = [
sys.executable, '-m', 'pip', 'install',
"torch", "torchvision", "torchaudio"
]
print_info(f"Running: {' '.join(cmd)}")
subprocess.check_call(cmd)
st_version = "3.0.0" # Newer sentence-transformers for newer PyTorch
except subprocess.SubprocessError as e:
print_warning(f"Failed to install latest PyTorch: {e}")
# Fallback to a specific version
torch_version = "2.1.0"
torch_vision_version = "0.16.0"
torch_audio_version = "2.1.0"
st_version = "3.0.0"
print_info(f"Trying fallback to PyTorch {torch_version}...")
cmd = [
sys.executable, '-m', 'pip', 'install',
f"torch=={torch_version}",
f"torchvision=={torch_vision_version}",
f"torchaudio=={torch_audio_version}"
]
print_info(f"Running: {' '.join(cmd)}")
subprocess.check_call(cmd)
else:
# Use traditional versions for older Python
torch_version = "1.13.1"
torch_vision_version = "0.14.1"
torch_audio_version = "0.13.1"
st_version = "2.2.2"
print_info(f"Installing PyTorch {torch_version} for macOS Intel (Python {python_version.major}.{python_version.minor})...")
# Install PyTorch first with compatible version
cmd = [
sys.executable, '-m', 'pip', 'install',
f"torch=={torch_version}",
f"torchvision=={torch_vision_version}",
f"torchaudio=={torch_audio_version}"
]
print_info(f"Running: {' '.join(cmd)}")
subprocess.check_call(cmd)
# Install a compatible version of sentence-transformers
print_info(f"Installing sentence-transformers {st_version}...")
cmd = [
sys.executable, '-m', 'pip', 'install',
f"sentence-transformers=={st_version}"
]
print_info(f"Running: {' '.join(cmd)}")
subprocess.check_call(cmd)
print_success(f"PyTorch {torch_version} and sentence-transformers {st_version} installed successfully for macOS Intel")
return True
except subprocess.SubprocessError as e:
print_error(f"Failed to install PyTorch for macOS Intel: {e}")
# Provide fallback instructions
if python_version >= (3, 13):
print_warning("You may need to manually install compatible versions for Python 3.13+ on Intel macOS:")
print_info("pip install torch==2.3.0 torchvision==0.18.0 torchaudio==2.3.0")
print_info("pip install sentence-transformers==3.0.0")
else:
print_warning("You may need to manually install compatible versions for Intel macOS:")
print_info("pip install torch==1.13.1 torchvision==0.14.1 torchaudio==0.13.1")
print_info("pip install sentence-transformers==2.2.2")
return False
def install_pytorch_macos_arm64():
"""Install PyTorch specifically for macOS with ARM64 (Apple Silicon)."""
print_step("3a", "Installing PyTorch for macOS ARM64 (Apple Silicon)")
try:
# For Apple Silicon, we can use the latest PyTorch with MPS support
print_info("Installing PyTorch with Metal Performance Shaders (MPS) support...")
# Install PyTorch with MPS support - let pip choose the best compatible version
cmd = [
sys.executable, '-m', 'pip', 'install',
'torch>=2.0.0',
'torchvision',
'torchaudio'
]
print_info(f"Running: {' '.join(cmd)}")
subprocess.check_call(cmd)
# Install sentence-transformers
print_info("Installing sentence-transformers (for embedding generation)...")
print_info("Note: Models will be downloaded on first use (~25MB)")
cmd = [
sys.executable, '-m', 'pip', 'install',
'sentence-transformers>=2.2.2'
]
print_info(f"Running: {' '.join(cmd)}")
subprocess.check_call(cmd)
print_success("PyTorch and sentence-transformers installed successfully for macOS ARM64")
print_info("MPS (Metal Performance Shaders) acceleration is available for GPU compute")
return True
except subprocess.SubprocessError as e:
print_error(f"Failed to install PyTorch for macOS ARM64: {e}")
# Provide fallback instructions
print_warning("You may need to manually install PyTorch for Apple Silicon:")
print_info("pip install torch torchvision torchaudio")
print_info("pip install sentence-transformers")
print_info("")
print_info("If you encounter issues, try:")
print_info("pip install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/cpu")
return False
def install_pytorch_windows(gpu_info):
"""Install PyTorch on Windows using the appropriate index URL."""
print_step("3a", "Installing PyTorch for Windows")
# Check if PyTorch is already installed and compatible
pytorch_installed = False
torch_version_installed = None
directml_compatible = False
try:
import torch
torch_version_installed = torch.__version__
pytorch_installed = True
print_info(f"PyTorch {torch_version_installed} is already installed")
# Check if version is compatible with DirectML (2.4.x works, 2.5.x doesn't)
version_parts = torch_version_installed.split('.')
major, minor = int(version_parts[0]), int(version_parts[1])
if gpu_info["has_directml"]:
if major == 2 and minor == 4:
directml_compatible = True
print_success(f"PyTorch {torch_version_installed} is compatible with DirectML")
# Check if torch-directml is also installed
try:
import torch_directml
directml_version = getattr(torch_directml, '__version__', 'Unknown version')
print_success(f"torch-directml {directml_version} is already installed")
return True # Everything is compatible, no need to reinstall
except ImportError:
print_info("torch-directml not found, will install it")
# Install torch-directml only
try:
subprocess.check_call([
sys.executable, '-m', 'pip', 'install', 'torch-directml==0.2.5.dev240914'
])
print_success("torch-directml installed successfully")
return True
except subprocess.SubprocessError:
print_warning("Failed to install torch-directml - DirectML support will be limited")
return True # Still return True since PyTorch works
elif major == 2 and minor >= 5:
print_warning(f"PyTorch {torch_version_installed} is not compatible with torch-directml")
print_info("torch-directml requires PyTorch 2.4.x, but 2.5.x is installed")
print_info("Keeping existing PyTorch installation - DirectML support will be limited")
return True # Don't break existing installation
else:
print_info(f"PyTorch {torch_version_installed} compatibility with DirectML is unknown")
else:
# No DirectML needed, check if current version is reasonable
if major == 2 and minor >= 4:
print_success(f"PyTorch {torch_version_installed} is acceptable for CPU usage")
return True # Keep existing installation
except ImportError:
print_info("PyTorch not found, will install compatible version")
# If we get here, we need to install PyTorch
# Determine the appropriate PyTorch index URL based on GPU
if gpu_info["has_cuda"]:
# Get CUDA version and determine appropriate index URL
cuda_version = gpu_info.get("cuda_version", "")
# Extract major version from CUDA version string
cuda_major = None
if cuda_version:
# Try to extract the major version (e.g., "11.8" -> "11")
try:
cuda_major = cuda_version.split('.')[0]
except (IndexError, AttributeError):
pass
# Default to cu118 if we couldn't determine the version or it's not a common one
if cuda_major == "12":
cuda_suffix = "cu121" # CUDA 12.x
print_info(f"Detected CUDA {cuda_version}, using cu121 channel")
elif cuda_major == "11":
cuda_suffix = "cu118" # CUDA 11.x
print_info(f"Detected CUDA {cuda_version}, using cu118 channel")
elif cuda_major == "10":
cuda_suffix = "cu102" # CUDA 10.x
print_info(f"Detected CUDA {cuda_version}, using cu102 channel")
else:
# Default to cu118 as a safe choice for newer NVIDIA GPUs
cuda_suffix = "cu118"
print_info(f"Using default cu118 channel for CUDA {cuda_version}")
index_url = f"https://download.pytorch.org/whl/{cuda_suffix}"
else:
# CPU-only version
index_url = "https://download.pytorch.org/whl/cpu"
print_info("Using CPU-only PyTorch for Windows")
# Install PyTorch with the appropriate index URL
try:
# Use versions compatible with DirectML if needed
if gpu_info["has_directml"]:
# Use PyTorch 2.4.x which is compatible with torch-directml
torch_version = "2.4.1"
torchvision_version = "0.19.1" # Compatible with torch 2.4.1
torchaudio_version = "2.4.1"
print_info("Using PyTorch 2.4.1 for DirectML compatibility")
else:
# Use latest version for non-DirectML systems
torch_version = "2.5.1"
torchvision_version = "0.20.1" # Compatible with torch 2.5.1
torchaudio_version = "2.5.1"
print_info("Using PyTorch 2.5.1 for optimal performance")
cmd = [
sys.executable, '-m', 'pip', 'install',
f"torch=={torch_version}",
f"torchvision=={torchvision_version}",
f"torchaudio=={torchaudio_version}",
f"--index-url={index_url}"
]
print_info(f"Running: {' '.join(cmd)}")
subprocess.check_call(cmd)
# Check if DirectML is needed
if gpu_info["has_directml"]:
print_info("Installing torch-directml for DirectML support")
try:
# Try the latest dev version since stable versions aren't available
subprocess.check_call([
sys.executable, '-m', 'pip', 'install', 'torch-directml==0.2.5.dev240914'
])
except subprocess.SubprocessError:
print_warning("Failed to install torch-directml - DirectML support will be limited")
print_info("You can install manually later with: pip install torch-directml==0.2.5.dev240914")
print_success("PyTorch installed successfully for Windows")
return True
except subprocess.SubprocessError as e:
print_error(f"Failed to install PyTorch for Windows: {e}")
print_warning("You may need to manually install PyTorch using instructions from https://pytorch.org/get-started/locally/")
return False
def detect_storage_backend_compatibility(system_info, gpu_info):
"""Detect which storage backends are compatible with the current environment."""
print_step("3a", "Analyzing storage backend compatibility")
compatibility = {
"chromadb": {"supported": True, "issues": [], "recommendation": "legacy"},
"sqlite_vec": {"supported": True, "issues": [], "recommendation": "default"}
}
# Check ChromaDB compatibility issues
chromadb_issues = []
# macOS Intel compatibility issues
if system_info["is_macos"] and system_info["is_x86"]:
chromadb_issues.append("ChromaDB has known installation issues on older macOS Intel systems")
chromadb_issues.append("May require specific dependency versions")
compatibility["chromadb"]["recommendation"] = "problematic"
compatibility["sqlite_vec"]["recommendation"] = "recommended"
# Memory constraints
total_memory_gb = 0
try:
import psutil
total_memory_gb = psutil.virtual_memory().total / (1024**3)
except ImportError:
# Fallback memory detection
try:
with open('/proc/meminfo', 'r') as f:
for line in f:
if line.startswith('MemTotal:'):
total_memory_gb = int(line.split()[1]) / (1024**2)
break
except (FileNotFoundError, IOError):
pass
if total_memory_gb > 0 and total_memory_gb < 4:
chromadb_issues.append(f"System has {total_memory_gb:.1f}GB RAM - ChromaDB may consume significant memory")
compatibility["sqlite_vec"]["recommendation"] = "recommended"
# Older Python versions
python_version = f"{sys.version_info.major}.{sys.version_info.minor}"
if sys.version_info < (3, 9):
chromadb_issues.append(f"Python {python_version} may have ChromaDB compatibility issues")
# ARM architecture considerations
if system_info["is_arm"]:
print_info("ARM architecture detected - both backends should work well")
compatibility["chromadb"]["issues"] = chromadb_issues
# Print compatibility analysis
print_info("Storage Backend Compatibility Analysis:")
for backend, info in compatibility.items():
status = "[OK]" if info["supported"] else "[X]"
rec_text = {
"recommended": "[*] RECOMMENDED",
"default": "[+] Standard",
"problematic": "[!] May have issues",
"lightweight": "[-] Lightweight"
}.get(info["recommendation"], "")
print_info(f" {status} {backend.upper()}: {rec_text}")
if info["issues"]:
for issue in info["issues"]:
print_info(f" • {issue}")
return compatibility
def choose_storage_backend(system_info, gpu_info, args):
"""Choose storage backend based on environment and user preferences."""
compatibility = detect_storage_backend_compatibility(system_info, gpu_info)
# Check if user specified a backend via environment
env_backend = os.environ.get('MCP_MEMORY_STORAGE_BACKEND')
if env_backend:
print_info(f"Using storage backend from environment: {env_backend}")
return env_backend
# Check for command line argument (we'll add this)
if hasattr(args, 'storage_backend') and args.storage_backend:
print_info(f"Using storage backend from command line: {args.storage_backend}")
return args.storage_backend
# Auto-select based on compatibility
recommended_backend = None
for backend, info in compatibility.items():
if info["recommendation"] == "recommended":
recommended_backend = backend
break
if not recommended_backend:
recommended_backend = "sqlite_vec" # Default fallback
# Interactive selection if no auto-recommendation is clear
if compatibility["chromadb"]["recommendation"] == "problematic":
print_step("3b", "Storage Backend Selection")
print_info("Based on your system, ChromaDB may have installation issues.")
print_info("SQLite-vec is recommended as a lightweight, compatible alternative.")
print_info("")
print_info("Available options:")
print_info(" 1. SQLite-vec (Recommended) - Lightweight, fast, minimal dependencies")
print_info(" 2. ChromaDB (Standard) - Full-featured but may have issues on your system")
print_info(" 3. Auto-detect - Try ChromaDB first, fallback to SQLite-vec if it fails")
print_info("")
while True:
try:
if args.non_interactive:
print_info("Non-interactive mode: using default storage backend (SQLite-vec)")
choice = "1"
else:
choice = prompt_user_input("Choose storage backend [1-3] (default: 1, press Enter for default): ", "1")
if choice == "1":
return "sqlite_vec"
elif choice == "2":
return "chromadb"
elif choice == "3":
return "auto_detect"
else:
print_error("Please enter 1, 2, or 3")
except (EOFError, KeyboardInterrupt):
print_info("\nUsing recommended backend: sqlite_vec")
return "sqlite_vec"
return recommended_backend
def install_storage_backend(backend, system_info):
"""Install the chosen storage backend."""
print_step("3c", f"Installing {backend} storage backend")
if backend == "sqlite_vec":
# Check extension support before attempting installation
extension_supported, extension_message = check_sqlite_extension_support()
if not extension_supported:
print_warning(f"SQLite extension support not available: {extension_message}")
# Provide platform-specific guidance
if platform.system().lower() == "darwin": # macOS
print_info("This is common on macOS with system Python.")
print_info("SOLUTIONS:")
print_info(" • Install Python via Homebrew: brew install python")
print_info(" • Use pyenv with extensions: PYTHON_CONFIGURE_OPTS='--enable-loadable-sqlite-extensions' pyenv install 3.12.0")
print_info(" • Switch to ChromaDB backend: --storage-backend chromadb")
# Ask user what they want to do
if not system_info.get('non_interactive'):
print("\n" + "=" * 60)
print("⚠️ USER INPUT REQUIRED")
print("=" * 60)
print("sqlite-vec requires SQLite extension support, which is not available.")
response = input("Switch to ChromaDB backend instead? (y/N): ").strip().lower()
print("=" * 60 + "\n")
if response in ['y', 'yes']:
print_info("Switching to ChromaDB backend...")
return install_storage_backend("chromadb", system_info)
else:
print_info("Continuing with sqlite-vec installation (may fail at runtime)...")
else:
print_info("Non-interactive mode: attempting sqlite-vec installation anyway")
else:
print_info("Consider switching to ChromaDB backend for better compatibility")
# Special handling for Python 3.13
if sys.version_info >= (3, 13):
print_info("Detected Python 3.13+ - using special installation method for sqlite-vec")
return install_sqlite_vec_python313(system_info)
# Standard installation for older Python versions
try:
print_info("Installing SQLite-vec...")
subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'sqlite-vec'])
print_success("SQLite-vec installed successfully")
return True
except subprocess.SubprocessError as e:
print_error(f"Failed to install SQLite-vec: {e}")
return False
elif backend == "chromadb":
print_error("ChromaDB backend has been removed in v8.0.0")
print_info("Please use one of the supported backends:")
print_info(" - 'hybrid': Local speed + cloud persistence (recommended)")
print_info(" - 'sqlite_vec': Fast local storage")
print_info(" - 'cloudflare': Cloud storage only")
print_info("\nTo migrate from ChromaDB, run: python scripts/migration/migrate_to_sqlite_vec.py")
return False
elif backend == "auto_detect":
print_info("Attempting auto-detection...")
# Try ChromaDB first
print_info("Trying ChromaDB installation...")
if install_storage_backend("chromadb", system_info):
print_success("ChromaDB installed successfully")
return "chromadb"