forked from BeehiveInnovations/pal-mcp-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun-server.sh
More file actions
executable file
·2727 lines (2361 loc) · 89.8 KB
/
run-server.sh
File metadata and controls
executable file
·2727 lines (2361 loc) · 89.8 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
#!/bin/bash
set -euo pipefail
# ============================================================================
# PAL MCP Server Setup Script
#
# A platform-agnostic setup script that works on macOS, Linux, and WSL.
# Handles environment setup, dependency installation, and configuration.
# ============================================================================
# Initialize pyenv if available (do this early)
if [[ -d "$HOME/.pyenv" ]]; then
export PYENV_ROOT="$HOME/.pyenv"
export PATH="$PYENV_ROOT/bin:$PATH"
if command -v pyenv &> /dev/null; then
eval "$(pyenv init --path)" 2>/dev/null || true
eval "$(pyenv init -)" 2>/dev/null || true
fi
fi
# ----------------------------------------------------------------------------
# Constants and Configuration
# ----------------------------------------------------------------------------
# Colors for output (ANSI codes work on all platforms)
readonly GREEN='\033[0;32m'
readonly YELLOW='\033[1;33m'
readonly RED='\033[0;31m'
readonly NC='\033[0m' # No Color
# Configuration
readonly VENV_PATH=".pal_venv"
readonly DOCKER_CLEANED_FLAG=".docker_cleaned"
readonly DESKTOP_CONFIG_FLAG=".desktop_configured"
readonly LOG_DIR="logs"
readonly LOG_FILE="mcp_server.log"
readonly LEGACY_MCP_NAMES=("zen" "zen-mcp" "zen-mcp-server" "zen_mcp" "zen_mcp_server")
# Determine portable arguments for sed -i (GNU vs BSD)
declare -a SED_INPLACE_ARGS
if sed --version >/dev/null 2>&1; then
SED_INPLACE_ARGS=(-i)
else
SED_INPLACE_ARGS=(-i "")
fi
# ----------------------------------------------------------------------------
# Utility Functions
# ----------------------------------------------------------------------------
# Print colored output
print_success() {
echo -e "${GREEN}✓${NC} $1" >&2
}
print_error() {
echo -e "${RED}✗${NC} $1" >&2
}
print_warning() {
echo -e "${YELLOW}!${NC} $1" >&2
}
print_info() {
echo -e "${YELLOW}$1${NC}" >&2
}
# Get the script's directory (works on all platforms)
get_script_dir() {
cd "$(dirname "$0")" && pwd
}
# Extract version from config.py
get_version() {
grep -E '^__version__ = ' config.py 2>/dev/null | sed 's/__version__ = "\(.*\)"/\1/' || echo "unknown"
}
# Clear Python cache files to prevent import issues
clear_python_cache() {
print_info "Clearing Python cache files..."
find . -name "*.pyc" -delete 2>/dev/null || true
find . -name "__pycache__" -type d -exec rm -rf {} + 2>/dev/null || true
print_success "Python cache cleared"
}
# ----------------------------------------------------------------------------
# Platform Detection Functions
# ----------------------------------------------------------------------------
# Get cross-platform Python executable path from venv
get_venv_python_path() {
local venv_path="$1"
# Convert to absolute path for consistent behavior across shell environments
local abs_venv_path
abs_venv_path=$(cd "$(dirname "$venv_path")" && pwd)/$(basename "$venv_path")
# Check for both Unix and Windows Python executable paths
if [[ -f "$abs_venv_path/bin/python" ]]; then
echo "$abs_venv_path/bin/python"
elif [[ -f "$abs_venv_path/Scripts/python.exe" ]]; then
echo "$abs_venv_path/Scripts/python.exe"
else
return 1 # No Python executable found
fi
}
# Detect the operating system
detect_os() {
case "$OSTYPE" in
darwin*) echo "macos" ;;
linux*)
if grep -qi microsoft /proc/version 2>/dev/null; then
echo "wsl"
else
echo "linux"
fi
;;
msys*|cygwin*|win32) echo "windows" ;;
*) echo "unknown" ;;
esac
}
# Get Claude config path based on platform
get_claude_config_path() {
local os_type=$(detect_os)
case "$os_type" in
macos)
echo "$HOME/Library/Application Support/Claude/claude_desktop_config.json"
;;
linux)
echo "$HOME/.config/Claude/claude_desktop_config.json"
;;
wsl)
local win_appdata
if command -v wslvar &> /dev/null; then
win_appdata=$(wslvar APPDATA 2>/dev/null)
fi
if [[ -n "${win_appdata:-}" ]]; then
echo "$(wslpath "$win_appdata")/Claude/claude_desktop_config.json"
else
print_warning "Could not determine Windows user path automatically. Please ensure APPDATA is set correctly or provide the full path manually."
echo "/mnt/c/Users/$USER/AppData/Roaming/Claude/claude_desktop_config.json"
fi
;;
windows)
echo "$APPDATA/Claude/claude_desktop_config.json"
;;
*)
echo ""
;;
esac
}
# ----------------------------------------------------------------------------
# Docker Cleanup Functions
# ----------------------------------------------------------------------------
# Clean up old Docker artifacts
cleanup_docker() {
# Skip if already cleaned or Docker not available
[[ -f "$DOCKER_CLEANED_FLAG" ]] && return 0
if ! command -v docker &> /dev/null || ! docker info &> /dev/null 2>&1; then
return 0
fi
local found_artifacts=false
# Define containers to remove
local containers=(
"gemini-mcp-server"
"gemini-mcp-redis"
"zen-mcp-server"
"zen-mcp-redis"
"zen-mcp-log-monitor"
)
# Remove containers
for container in "${containers[@]}"; do
if docker ps -a --format "{{.Names}}" | grep -q "^${container}$" 2>/dev/null; then
if [[ "$found_artifacts" == false ]]; then
echo "One-time Docker cleanup..."
found_artifacts=true
fi
echo " Removing container: $container"
docker stop "$container" >/dev/null 2>&1 || true
docker rm "$container" >/dev/null 2>&1 || true
fi
done
# Remove images
local images=("gemini-mcp-server:latest" "zen-mcp-server:latest")
for image in "${images[@]}"; do
if docker images --format "{{.Repository}}:{{.Tag}}" | grep -q "^${image}$" 2>/dev/null; then
if [[ "$found_artifacts" == false ]]; then
echo "One-time Docker cleanup..."
found_artifacts=true
fi
echo " Removing image: $image"
docker rmi "$image" >/dev/null 2>&1 || true
fi
done
# Remove volumes
local volumes=("redis_data" "mcp_logs")
for volume in "${volumes[@]}"; do
if docker volume ls --format "{{.Name}}" | grep -q "^${volume}$" 2>/dev/null; then
if [[ "$found_artifacts" == false ]]; then
echo "One-time Docker cleanup..."
found_artifacts=true
fi
echo " Removing volume: $volume"
docker volume rm "$volume" >/dev/null 2>&1 || true
fi
done
if [[ "$found_artifacts" == true ]]; then
print_success "Docker cleanup complete"
fi
touch "$DOCKER_CLEANED_FLAG"
}
# ----------------------------------------------------------------------------
# Python Environment Functions
# ----------------------------------------------------------------------------
# Find suitable Python command
find_python() {
# Pyenv should already be initialized at script start, but check if .python-version exists
if [[ -f ".python-version" ]] && command -v pyenv &> /dev/null; then
# Ensure pyenv respects the local .python-version
pyenv local &>/dev/null || true
fi
# Prefer Python 3.12 for best compatibility
local python_cmds=("python3.12" "python3.13" "python3.11" "python3.10" "python3" "python" "py")
for cmd in "${python_cmds[@]}"; do
if command -v "$cmd" &> /dev/null; then
local version=$($cmd --version 2>&1)
if [[ $version =~ Python\ 3\.([0-9]+)\.([0-9]+) ]]; then
local major_version=${BASH_REMATCH[1]}
local minor_version=${BASH_REMATCH[2]}
# Check minimum version (3.10) for better library compatibility
if [[ $major_version -ge 10 ]]; then
# Verify the command actually exists (important for pyenv)
if command -v "$cmd" &> /dev/null; then
echo "$cmd"
print_success "Found Python: $version"
# Recommend Python 3.12
if [[ $major_version -ne 12 ]]; then
print_info "Note: Python 3.12 is recommended for best compatibility."
fi
return 0
fi
fi
fi
fi
done
# No suitable Python found - check if we can use pyenv
local os_type=$(detect_os)
# Check for pyenv on Unix-like systems (macOS/Linux)
if [[ "$os_type" == "macos" || "$os_type" == "linux" || "$os_type" == "wsl" ]]; then
if command -v pyenv &> /dev/null; then
# pyenv exists, check if Python 3.12 is installed
if ! pyenv versions 2>/dev/null | grep -E "3\.(1[2-9]|[2-9][0-9])" >/dev/null; then
echo ""
echo "Python 3.10+ is required. Pyenv can install Python 3.12 locally for this project."
read -p "Install Python 3.12 using pyenv? (Y/n): " -n 1 -r
echo ""
if [[ ! $REPLY =~ ^[Nn]$ ]]; then
if install_python_with_pyenv; then
# Try finding Python again
if python_cmd=$(find_python); then
echo "$python_cmd"
return 0
fi
fi
fi
else
# Python 3.12+ is installed in pyenv but may not be active
# Check if .python-version exists
if [[ ! -f ".python-version" ]] || ! grep -qE "3\.(1[2-9]|[2-9][0-9])" .python-version 2>/dev/null; then
echo ""
print_info "Python 3.12 is installed via pyenv but not set for this project."
read -p "Set Python 3.12.0 for this project? (Y/n): " -n 1 -r
echo ""
if [[ ! $REPLY =~ ^[Nn]$ ]]; then
# Find the first suitable Python version
local py_version=$(pyenv versions --bare | grep -E "^3\.(1[2-9]|[2-9][0-9])" | head -1)
if [[ -n "$py_version" ]]; then
pyenv local "$py_version"
print_success "Set Python $py_version for this project"
# Re-initialize pyenv to pick up the change
eval "$(pyenv init --path)" 2>/dev/null || true
eval "$(pyenv init -)" 2>/dev/null || true
# Try finding Python again
if python_cmd=$(find_python); then
echo "$python_cmd"
return 0
fi
fi
fi
fi
fi
else
# No pyenv installed - show instructions
echo "" >&2
print_error "Python 3.10+ not found. The 'mcp' package requires Python 3.10+."
echo "" >&2
if [[ "$os_type" == "macos" ]]; then
echo "To install Python locally for this project:" >&2
echo "" >&2
echo "1. Install pyenv (manages Python versions per project):" >&2
echo " brew install pyenv" >&2
echo "" >&2
echo "2. Add to ~/.zshrc:" >&2
echo ' export PYENV_ROOT="$HOME/.pyenv"' >&2
echo ' export PATH="$PYENV_ROOT/bin:$PATH"' >&2
echo ' eval "$(pyenv init -)"' >&2
echo "" >&2
echo "3. Restart terminal, then run:" >&2
echo " pyenv install 3.12.0" >&2
echo " cd $(pwd)" >&2
echo " pyenv local 3.12.0" >&2
echo " ./run-server.sh" >&2
else
# Linux/WSL
echo "To install Python locally for this project:" >&2
echo "" >&2
echo "1. Install pyenv:" >&2
echo " curl https://pyenv.run | bash" >&2
echo "" >&2
echo "2. Add to ~/.bashrc:" >&2
echo ' export PYENV_ROOT="$HOME/.pyenv"' >&2
echo ' export PATH="$PYENV_ROOT/bin:$PATH"' >&2
echo ' eval "$(pyenv init -)"' >&2
echo "" >&2
echo "3. Restart terminal, then run:" >&2
echo " pyenv install 3.12.0" >&2
echo " cd $(pwd)" >&2
echo " pyenv local 3.12.0" >&2
echo " ./run-server.sh" >&2
fi
fi
else
# Other systems (shouldn't happen with bash script)
print_error "Python 3.10+ not found. Please install Python 3.10 or newer."
fi
return 1
}
# Install Python with pyenv (when pyenv is already installed)
install_python_with_pyenv() {
# Ensure pyenv is initialized
export PYENV_ROOT="${PYENV_ROOT:-$HOME/.pyenv}"
export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init -)" 2>/dev/null || true
print_info "Installing Python 3.12 (this may take a few minutes)..."
if pyenv install -s 3.12.0; then
print_success "Python 3.12 installed"
# Set local Python version for this project
pyenv local 3.12.0
print_success "Python 3.12 set for this project"
# Show shell configuration instructions
echo ""
print_info "To make pyenv work in new terminals, add to your shell config:"
local shell_config="~/.zshrc"
if [[ "$SHELL" == *"bash"* ]]; then
shell_config="~/.bashrc"
fi
echo ' export PYENV_ROOT="$HOME/.pyenv"'
echo ' command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"'
echo ' eval "$(pyenv init -)"'
echo ""
# Re-initialize pyenv to use the newly installed Python
eval "$(pyenv init --path)" 2>/dev/null || true
eval "$(pyenv init -)" 2>/dev/null || true
return 0
else
print_error "Failed to install Python 3.12"
return 1
fi
}
# Detect Linux distribution
detect_linux_distro() {
if [[ -f /etc/os-release ]]; then
. /etc/os-release
echo "${ID:-unknown}"
elif [[ -f /etc/debian_version ]]; then
echo "debian"
elif [[ -f /etc/redhat-release ]]; then
echo "rhel"
elif [[ -f /etc/arch-release ]]; then
echo "arch"
else
echo "unknown"
fi
}
# Get package manager and install command for the distro
get_install_command() {
local distro="$1"
local python_version="${2:-}"
# Extract major.minor version if provided
local version_suffix=""
if [[ -n "$python_version" ]] && [[ "$python_version" =~ ([0-9]+\.[0-9]+) ]]; then
version_suffix="${BASH_REMATCH[1]}"
fi
case "$distro" in
ubuntu|debian|raspbian|pop|linuxmint|elementary)
if [[ -n "$version_suffix" ]]; then
# Try version-specific packages first, then fall back to generic
echo "sudo apt update && (sudo apt install -y python${version_suffix}-venv python${version_suffix}-dev || sudo apt install -y python3-venv python3-pip)"
else
echo "sudo apt update && sudo apt install -y python3-venv python3-pip"
fi
;;
fedora)
echo "sudo dnf install -y python3-venv python3-pip"
;;
rhel|centos|rocky|almalinux|oracle)
echo "sudo dnf install -y python3-venv python3-pip || sudo yum install -y python3-venv python3-pip"
;;
arch|manjaro|endeavouros)
echo "sudo pacman -Syu --noconfirm python-pip python-virtualenv"
;;
opensuse|suse)
echo "sudo zypper install -y python3-venv python3-pip"
;;
alpine)
echo "sudo apk add --no-cache python3-dev py3-pip py3-virtualenv"
;;
*)
echo ""
;;
esac
}
# Check if we can use sudo
can_use_sudo() {
# Check if sudo exists and user can use it
if command -v sudo &> /dev/null; then
# Test sudo with a harmless command
if sudo -n true 2>/dev/null; then
return 0
elif [[ -t 0 ]]; then
# Terminal is interactive, test if sudo works with password
if sudo true 2>/dev/null; then
return 0
fi
fi
fi
return 1
}
# Try to install system packages automatically
try_install_system_packages() {
local python_cmd="${1:-python3}"
local os_type=$(detect_os)
# Skip on macOS as it works fine
if [[ "$os_type" == "macos" ]]; then
return 1
fi
# Only try on Linux systems
if [[ "$os_type" != "linux" && "$os_type" != "wsl" ]]; then
return 1
fi
# Get Python version
local python_version=""
if command -v "$python_cmd" &> /dev/null; then
python_version=$($python_cmd --version 2>&1 | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' || echo "")
fi
local distro=$(detect_linux_distro)
local install_cmd=$(get_install_command "$distro" "$python_version")
if [[ -z "$install_cmd" ]]; then
return 1
fi
print_info "Attempting to install required Python packages..."
# Check if we can use sudo
if can_use_sudo; then
print_info "Installing system packages (this may ask for your password)..."
if bash -c "$install_cmd" >/dev/null 2>&1; then # Replaced eval to prevent command injection
print_success "System packages installed successfully"
return 0
else
print_warning "Failed to install system packages automatically"
fi
fi
return 1
}
# Bootstrap pip in virtual environment
bootstrap_pip() {
local venv_python="$1"
local python_cmd="$2"
print_info "Bootstrapping pip in virtual environment..."
# Try ensurepip first
if $venv_python -m ensurepip --default-pip >/dev/null 2>&1; then
print_success "Successfully bootstrapped pip using ensurepip"
return 0
fi
# Try to download get-pip.py
print_info "Downloading pip installer..."
local get_pip_url="https://bootstrap.pypa.io/get-pip.py"
local temp_pip=$(mktemp)
local download_success=false
# Try curl first
if command -v curl &> /dev/null; then
if curl -sSL "$get_pip_url" -o "$temp_pip" 2>/dev/null; then
download_success=true
fi
fi
# Try wget if curl failed
if [[ "$download_success" == false ]] && command -v wget &> /dev/null; then
if wget -qO "$temp_pip" "$get_pip_url" 2>/dev/null; then
download_success=true
fi
fi
# Try python urllib as last resort
if [[ "$download_success" == false ]]; then
print_info "Using Python to download pip installer..."
if $python_cmd -c "import urllib.request; urllib.request.urlretrieve('$get_pip_url', '$temp_pip')" 2>/dev/null; then
download_success=true
fi
fi
if [[ "$download_success" == true ]] && [[ -f "$temp_pip" ]] && [[ -s "$temp_pip" ]]; then
print_info "Installing pip..."
if $venv_python "$temp_pip" --no-warn-script-location >/dev/null 2>&1; then
rm -f "$temp_pip"
print_success "Successfully installed pip"
return 0
fi
fi
rm -f "$temp_pip" 2>/dev/null
return 1
}
# Setup environment using uv-first approach
setup_environment() {
local venv_python=""
# Try uv-first approach
if command -v uv &> /dev/null; then
print_info "Setting up environment with uv..."
# Only remove existing venv if it wasn't created by uv (to ensure clean uv setup)
if [[ -d "$VENV_PATH" ]] && [[ ! -f "$VENV_PATH/uv_created" ]]; then
print_info "Removing existing environment for clean uv setup..."
rm -rf "$VENV_PATH"
fi
# Try Python 3.12 first (preferred)
local uv_output
if uv_output=$(uv venv --python 3.12 "$VENV_PATH" 2>&1); then
# Use helper function for cross-platform path detection
if venv_python=$(get_venv_python_path "$VENV_PATH"); then
touch "$VENV_PATH/uv_created" # Mark as uv-created
print_success "Created environment with uv using Python 3.12"
# Ensure pip is installed in uv environment
if ! $venv_python -m pip --version &>/dev/null 2>&1; then
print_info "Installing pip in uv environment..."
# uv doesn't install pip by default, use bootstrap method
if bootstrap_pip "$venv_python" "python3"; then
print_success "pip installed in uv environment"
else
print_warning "Failed to install pip in uv environment"
fi
fi
else
print_warning "uv succeeded but Python executable not found in venv"
fi
# Fall back to any available Python through uv
elif uv_output=$(uv venv "$VENV_PATH" 2>&1); then
# Use helper function for cross-platform path detection
if venv_python=$(get_venv_python_path "$VENV_PATH"); then
touch "$VENV_PATH/uv_created" # Mark as uv-created
local python_version=$($venv_python --version 2>&1)
print_success "Created environment with uv using $python_version"
# Ensure pip is installed in uv environment
if ! $venv_python -m pip --version &>/dev/null 2>&1; then
print_info "Installing pip in uv environment..."
# uv doesn't install pip by default, use bootstrap method
if bootstrap_pip "$venv_python" "python3"; then
print_success "pip installed in uv environment"
else
print_warning "Failed to install pip in uv environment"
fi
fi
else
print_warning "uv succeeded but Python executable not found in venv"
fi
else
print_warning "uv environment creation failed, falling back to system Python detection"
print_warning "uv output: $uv_output"
fi
else
print_info "uv not found, using system Python detection"
fi
# If uv failed or not available, fallback to system Python detection
if [[ -z "$venv_python" ]]; then
print_info "Setting up environment with system Python..."
local python_cmd
python_cmd=$(find_python) || return 1
# Use existing venv creation logic
venv_python=$(setup_venv "$python_cmd")
if [[ $? -ne 0 ]]; then
return 1
fi
else
# venv_python was already set by uv creation above, just convert to absolute path
if [[ -n "$venv_python" ]]; then
# Convert to absolute path for MCP registration
local abs_venv_python
if cd "$(dirname "$venv_python")" 2>/dev/null; then
abs_venv_python=$(pwd)/$(basename "$venv_python")
venv_python="$abs_venv_python"
else
print_error "Failed to resolve absolute path for venv_python"
return 1
fi
fi
fi
echo "$venv_python"
return 0
}
# Setup virtual environment
setup_venv() {
local python_cmd="$1"
local venv_python=""
local venv_pip=""
# Create venv if it doesn't exist
if [[ ! -d "$VENV_PATH" ]]; then
print_info "Creating isolated environment..."
# Capture error output for better diagnostics
local venv_error
if venv_error=$($python_cmd -m venv "$VENV_PATH" 2>&1); then
print_success "Created isolated environment"
else
# Check for common Linux issues and try fallbacks
local os_type=$(detect_os)
if [[ "$os_type" == "linux" || "$os_type" == "wsl" ]]; then
if echo "$venv_error" | grep -E -q "No module named venv|venv.*not found|ensurepip is not|python3.*-venv"; then
# Try to install system packages automatically first
if try_install_system_packages "$python_cmd"; then
print_info "Retrying virtual environment creation..."
if venv_error=$($python_cmd -m venv "$VENV_PATH" 2>&1); then
print_success "Created isolated environment"
else
# Continue to fallback methods below
print_warning "Still unable to create venv, trying fallback methods..."
fi
fi
# If venv still doesn't exist, try fallback methods
if [[ ! -d "$VENV_PATH" ]]; then
# Try virtualenv as fallback
if command -v virtualenv &> /dev/null; then
print_info "Attempting to create environment with virtualenv..."
if virtualenv -p "$python_cmd" "$VENV_PATH" &>/dev/null 2>&1; then
print_success "Created environment using virtualenv fallback"
fi
fi
# Try python -m virtualenv if directory wasn't created
if [[ ! -d "$VENV_PATH" ]]; then
if $python_cmd -m virtualenv "$VENV_PATH" &>/dev/null 2>&1; then
print_success "Created environment using python -m virtualenv fallback"
fi
fi
# Last resort: try to install virtualenv via pip and use it
if [[ ! -d "$VENV_PATH" ]] && command -v pip3 &> /dev/null; then
print_info "Installing virtualenv via pip..."
if pip3 install --user virtualenv &>/dev/null 2>&1; then
local user_bin="$HOME/.local/bin"
if [[ -f "$user_bin/virtualenv" ]]; then
if "$user_bin/virtualenv" -p "$python_cmd" "$VENV_PATH" &>/dev/null 2>&1; then
print_success "Created environment using pip-installed virtualenv"
fi
fi
fi
fi
fi
# Check if any method succeeded
if [[ ! -d "$VENV_PATH" ]]; then
print_error "Unable to create virtual environment"
echo ""
echo "Your system is missing Python development packages."
echo ""
local distro=$(detect_linux_distro)
local python_version=$($python_cmd --version 2>&1 | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' || echo "")
local install_cmd=$(get_install_command "$distro" "$python_version")
if [[ -n "$install_cmd" ]]; then
echo "Please run this command to install them:"
echo " $install_cmd"
else
echo "Please install Python venv support for your system:"
echo " Ubuntu/Debian: sudo apt install python3-venv python3-pip"
echo " RHEL/CentOS: sudo dnf install python3-venv python3-pip"
echo " Arch: sudo pacman -S python-pip python-virtualenv"
fi
echo ""
echo "Then run this script again."
exit 1
fi
elif echo "$venv_error" | grep -q "Permission denied"; then
print_error "Permission denied creating virtual environment"
echo ""
echo "Try running in a different directory:"
echo " cd ~ && git clone <repository-url> && cd pal-mcp-server && ./run-server.sh"
echo ""
exit 1
else
print_error "Failed to create virtual environment"
echo "Error: $venv_error"
exit 1
fi
else
# For non-Linux systems, show the error and exit
print_error "Failed to create virtual environment"
echo "Error: $venv_error"
exit 1
fi
fi
fi
# Get venv Python path based on platform
local os_type=$(detect_os)
case "$os_type" in
windows)
venv_python="$VENV_PATH/Scripts/python.exe"
venv_pip="$VENV_PATH/Scripts/pip.exe"
;;
*)
venv_python="$VENV_PATH/bin/python"
venv_pip="$VENV_PATH/bin/pip"
;;
esac
# Check if venv Python exists
if [[ ! -f "$venv_python" ]]; then
print_error "Virtual environment Python not found"
exit 1
fi
# Always check if pip exists in the virtual environment (regardless of how it was created)
if [[ ! -f "$venv_pip" ]] && ! $venv_python -m pip --version &>/dev/null 2>&1; then
print_warning "pip not found in virtual environment, installing..."
# On Linux, try to install system packages if pip is missing
local os_type=$(detect_os)
if [[ "$os_type" == "linux" || "$os_type" == "wsl" ]]; then
if try_install_system_packages "$python_cmd"; then
# Check if pip is now available after system package install
if $venv_python -m pip --version &>/dev/null 2>&1; then
print_success "pip is now available"
else
# Still need to bootstrap pip
bootstrap_pip "$venv_python" "$python_cmd" || true
fi
else
# Try to bootstrap pip without system packages
bootstrap_pip "$venv_python" "$python_cmd" || true
fi
else
# For non-Linux systems, just try to bootstrap pip
bootstrap_pip "$venv_python" "$python_cmd" || true
fi
# Final check after all attempts
if ! $venv_python -m pip --version &>/dev/null 2>&1; then
print_error "Failed to install pip in virtual environment"
echo ""
echo "Your Python installation appears to be incomplete."
echo ""
local distro=$(detect_linux_distro)
local python_version=$($python_cmd --version 2>&1 | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' || echo "")
local install_cmd=$(get_install_command "$distro" "$python_version")
if [[ -n "$install_cmd" ]]; then
echo "Please run this command to install Python packages:"
echo " $install_cmd"
else
echo "Please install Python pip support for your system."
fi
echo ""
echo "Then delete the virtual environment and run this script again:"
echo " rm -rf $VENV_PATH"
echo " ./run-server.sh"
echo ""
exit 1
fi
fi
# Verify pip is working
if ! $venv_python -m pip --version &>/dev/null 2>&1; then
print_error "pip is not working correctly in the virtual environment"
echo ""
echo "Try deleting the virtual environment and running again:"
echo " rm -rf $VENV_PATH"
echo " ./run-server.sh"
echo ""
exit 1
fi
if [[ -n "${VIRTUAL_ENV:-}" ]]; then
print_success "Using activated virtual environment with pip"
else
print_success "Virtual environment ready with pip"
fi
# Convert to absolute path for MCP registration
local abs_venv_python=$(cd "$(dirname "$venv_python")" && pwd)/$(basename "$venv_python")
echo "$abs_venv_python"
return 0
}
# Check if package is installed
check_package() {
local python_cmd="$1"
local module_name="$2"
"$python_cmd" -c "import importlib, sys; importlib.import_module(sys.argv[1])" "$module_name" &>/dev/null
}
# Install dependencies
install_dependencies() {
local python_cmd="$1"
local deps_needed=false
# First verify pip is available with retry logic and bootstrap fallback
local pip_available=false
local max_attempts=3
for ((attempt=1; attempt<=max_attempts; attempt++)); do
if "$python_cmd" -m pip --version &>/dev/null; then
pip_available=true
break
else
if (( attempt < max_attempts )); then
print_warning "Attempt $attempt/$max_attempts: pip not available, retrying in 1 second..."
sleep 1
fi
fi
done
# If pip is still not available after retries, try to bootstrap it
if [[ "$pip_available" == false ]]; then
print_warning "pip is not available in the Python environment after $max_attempts attempts"
# Enhanced diagnostic information for debugging
print_info "Diagnostic information:"
print_info " Python executable: $python_cmd"
print_info " Python executable exists: $(if [[ -f "$python_cmd" ]]; then echo "Yes"; else echo "No"; fi)"
print_info " Python executable permissions: $(ls -la "$python_cmd" 2>/dev/null || echo "Cannot check")"
print_info " Virtual environment path: $VENV_PATH"
print_info " Virtual environment exists: $(if [[ -d "$VENV_PATH" ]]; then echo "Yes"; else echo "No"; fi)"
print_info "Attempting to bootstrap pip..."
# Extract the base python command for bootstrap (fallback to python3)
local base_python_cmd="python3"
if command -v python &> /dev/null; then
base_python_cmd="python"
fi
# Try to bootstrap pip
if bootstrap_pip "$python_cmd" "$base_python_cmd"; then
print_success "Successfully bootstrapped pip"
# Verify pip is now available
if $python_cmd -m pip --version &>/dev/null 2>&1; then
pip_available=true
else
print_error "pip still not available after bootstrap attempt"
fi
else
print_error "Failed to bootstrap pip"
fi
fi
# Final check - if pip is still not available, exit with error
if [[ "$pip_available" == false ]]; then
print_error "pip is not available in the Python environment"
echo ""
echo "This indicates an incomplete Python installation or a problem with the virtual environment."
echo ""
echo "Final diagnostic information:"
echo " Python executable: $python_cmd"
echo " Python version: $($python_cmd --version 2>&1 || echo "Cannot determine")"
echo " pip module check: $($python_cmd -c "import pip; print('Available')" 2>&1 || echo "Not available")"
echo ""
echo "Troubleshooting steps:"
echo "1. Delete the virtual environment: rm -rf $VENV_PATH"
echo "2. Run this script again: ./run-server.sh"
echo "3. If the problem persists, check your Python installation"
echo "4. For Git Bash on Windows, try running from a regular Command Prompt or PowerShell"
echo ""
return 1
fi
# Check required packages
local packages=("mcp" "google.genai" "openai" "pydantic" "dotenv")
for package in "${packages[@]}"; do
if ! check_package "$python_cmd" "$package"; then
deps_needed=true
break
fi
done
if [[ "$deps_needed" == false ]]; then
print_success "Dependencies already installed"
return 0
fi
echo ""
print_info "Setting up PAL MCP Server..."
echo "Installing required components:"
echo " • MCP protocol library"
echo " • AI model connectors"
echo " • Data validation tools"
echo " • Environment configuration"
echo ""
# Determine installation method and execute directly to handle paths with spaces
local install_output
local exit_code=0
echo -n "Downloading packages..."
if command -v uv &> /dev/null && [[ -f "$VENV_PATH/uv_created" ]]; then
print_info "Using uv for faster package installation..."
install_output=$(uv pip install -q -r requirements.txt --python "$python_cmd" 2>&1) || exit_code=$?
elif [[ -n "${VIRTUAL_ENV:-}" ]] || [[ "$python_cmd" == *"$VENV_PATH"* ]]; then
install_output=$("$python_cmd" -m pip install -q -r requirements.txt 2>&1) || exit_code=$?
else
install_output=$("$python_cmd" -m pip install -q --user -r requirements.txt 2>&1) || exit_code=$?
fi
if [[ $exit_code -ne 0 ]]; then
echo -e "\r${RED}✗ Setup failed${NC} "
echo ""
echo "Installation error:"
echo "$install_output" | head -20
echo ""
# Check for common issues
if echo "$install_output" | grep -q "No module named pip"; then
print_error "pip module not found"
echo ""
echo "Your Python installation is incomplete. Please install pip:"
local distro=$(detect_linux_distro)