forked from BeehiveInnovations/pal-mcp-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun-server.ps1
More file actions
2235 lines (1913 loc) · 71.7 KB
/
run-server.ps1
File metadata and controls
2235 lines (1913 loc) · 71.7 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
<#
.SYNOPSIS
Installation, configuration, and launch script for Zen MCP server on Windows.
.DESCRIPTION
This PowerShell script prepares the environment for the Zen MCP server:
- Installs and checks Python 3.10+ (with venv or uv if available)
- Installs required Python dependencies
- Configures environment files (.env)
- Validates presence of required API keys
- Cleans Python caches and obsolete Docker artifacts
- Offers automatic integration with Claude Desktop, Gemini CLI, VSCode, Cursor, Windsurf, and Trae
- Manages configuration file backups (max 3 retained)
- Allows real-time log following or server launch
.PARAMETER Help
Shows script help.
.PARAMETER Version
Shows Zen MCP server version.
.PARAMETER Follow
Follows server logs in real time.
.PARAMETER Config
Shows configuration instructions for Claude and other compatible clients.
.PARAMETER ClearCache
Removes Python cache files (__pycache__, .pyc).
.PARAMETER SkipVenv
Skips Python virtual environment creation.
.PARAMETER SkipDocker
Skips Docker checks and cleanup.
.PARAMETER Force
Forces recreation of the Python virtual environment.
.PARAMETER VerboseOutput
Enables more detailed output (currently unused).
.PARAMETER Dev
Installs development dependencies from requirements-dev.txt if available.
.PARAMETER Docker
Uses Docker to build and run the MCP server instead of Python virtual environment.
.EXAMPLE
.\run-server.ps1
Prepares the environment and starts the Zen MCP server.
.\run-server.ps1 -Follow
Follows server logs in real time.
.\run-server.ps1 -Config
Shows configuration instructions for clients.
.\run-server.ps1 -Dev
Prepares the environment with development dependencies and starts the server.
.\run-server.ps1 -Docker
Builds and runs the server using Docker containers.
.\run-server.ps1 -Docker -Follow
Builds and runs the server using Docker containers and follows the logs.
.\run-server.ps1 -Docker -Force
Forces rebuilding of the Docker image and runs the server.
.NOTES
Project Author : BeehiveInnovations
Script Author : GiGiDKR (https://github.com/GiGiDKR)
Date : 07-05-2025
Version : See config.py (__version__)
References : https://github.com/BeehiveInnovations/zen-mcp-server
#>
#Requires -Version 5.1
[CmdletBinding()]
param(
[switch]$Help,
[switch]$Version,
[switch]$Follow,
[switch]$Config,
[switch]$ClearCache,
[switch]$SkipVenv,
[switch]$SkipDocker,
[switch]$Force,
[switch]$VerboseOutput,
[switch]$Dev,
[switch]$Docker
)
# ============================================================================
# Zen MCP Server Setup Script for Windows
#
# A Windows-compatible setup script that handles environment setup,
# dependency installation, and configuration.
# ============================================================================
# Set error action preference
$ErrorActionPreference = "Stop"
# ----------------------------------------------------------------------------
# Constants and Configuration
# ----------------------------------------------------------------------------
$script:VENV_PATH = ".zen_venv"
$script:DOCKER_CLEANED_FLAG = ".docker_cleaned"
$script:DESKTOP_CONFIG_FLAG = ".desktop_configured"
$script:LOG_DIR = "logs"
$script:LOG_FILE = "mcp_server.log"
# ----------------------------------------------------------------------------
# Utility Functions
# ----------------------------------------------------------------------------
function Write-Success {
param([string]$Message)
Write-Host "✓ " -ForegroundColor Green -NoNewline
Write-Host $Message
}
function Write-Error {
param([string]$Message)
Write-Host "✗ " -ForegroundColor Red -NoNewline
Write-Host $Message
}
function Write-Warning {
param([string]$Message)
Write-Host "⚠ " -ForegroundColor Yellow -NoNewline
Write-Host $Message
}
function Write-Info {
param([string]$Message)
Write-Host "ℹ " -ForegroundColor Cyan -NoNewline
Write-Host $Message
}
function Write-Step {
param([string]$Message)
Write-Host ""
Write-Host "=== $Message ===" -ForegroundColor Cyan
}
# Check if command exists
function Test-Command {
param([string]$Command)
try {
$null = Get-Command $Command -ErrorAction Stop
return $true
}
catch {
return $false
}
}
# Alternative method to force remove locked directories
function Remove-LockedDirectory {
param([string]$Path)
if (!(Test-Path $Path)) {
return $true
}
try {
# Try standard removal first
Remove-Item -Recurse -Force $Path -ErrorAction Stop
return $true
}
catch {
Write-Warning "Standard removal failed, trying alternative methods..."
# Method 1: Use takeown and icacls to force ownership
try {
Write-Info "Attempting to take ownership of locked files..."
takeown /F "$Path" /R /D Y 2>$null | Out-Null
icacls "$Path" /grant administrators:F /T 2>$null | Out-Null
Remove-Item -Recurse -Force $Path -ErrorAction Stop
return $true
}
catch {
Write-Warning "Ownership method failed"
}
# Method 2: Rename and schedule for deletion on reboot
try {
$tempName = "$Path.delete_$(Get-Random)"
Write-Info "Renaming to: $tempName (will be deleted on next reboot)"
Rename-Item $Path $tempName -ErrorAction Stop
# Schedule for deletion on reboot using movefile
if (Get-Command "schtasks" -ErrorAction SilentlyContinue) {
Write-Info "Scheduling for deletion on next reboot..."
}
Write-Warning "Environment renamed to $tempName and will be deleted on next reboot"
return $true
}
catch {
Write-Warning "Rename method failed"
}
# If all methods fail, return false
return $false
}
}
# Manage configuration file backups with maximum 3 files retention
function Manage-ConfigBackups {
param(
[string]$ConfigFilePath,
[int]$MaxBackups = 3
)
if (!(Test-Path $ConfigFilePath)) {
Write-Warning "Configuration file not found: $ConfigFilePath"
return $null
}
try {
# Create new backup with timestamp
$timestamp = Get-Date -Format 'yyyyMMdd_HHmmss'
$backupPath = "$ConfigFilePath.backup_$timestamp"
Copy-Item $ConfigFilePath $backupPath -ErrorAction Stop
# Find all existing backups for this config file
$configDir = Split-Path $ConfigFilePath -Parent
$configFileName = Split-Path $ConfigFilePath -Leaf
$backupPattern = "$configFileName.backup_*"
$existingBackups = Get-ChildItem -Path $configDir -Filter $backupPattern -ErrorAction SilentlyContinue |
Sort-Object LastWriteTime -Descending
# Keep only the most recent MaxBackups files
if ($existingBackups.Count -gt $MaxBackups) {
$backupsToRemove = $existingBackups | Select-Object -Skip $MaxBackups
foreach ($backup in $backupsToRemove) {
try {
Remove-Item $backup.FullName -Force -ErrorAction Stop
Write-Info "Removed old backup: $($backup.Name)"
}
catch {
Write-Warning "Could not remove old backup: $($backup.Name)"
}
}
Write-Success "Backup retention: kept $MaxBackups most recent backups"
}
Write-Success "Backup created: $(Split-Path $backupPath -Leaf)"
return $backupPath
}
catch {
Write-Warning "Failed to create backup: $_"
return $null
}
}
# Get version from config.py
function Get-Version {
try {
if (Test-Path "config.py") {
$content = Get-Content "config.py" -ErrorAction Stop
$versionLine = $content | Where-Object { $_ -match '^__version__ = ' }
if ($versionLine) {
return ($versionLine -replace '__version__ = "([^"]*)"', '$1')
}
}
return "unknown"
}
catch {
return "unknown"
}
}
# Clear Python cache files
function Clear-PythonCache {
Write-Info "Clearing Python cache files..."
try {
# Remove .pyc files
Get-ChildItem -Path . -Recurse -Filter "*.pyc" -ErrorAction SilentlyContinue | Remove-Item -Force
# Remove __pycache__ directories
Get-ChildItem -Path . -Recurse -Name "__pycache__" -Directory -ErrorAction SilentlyContinue |
ForEach-Object { Remove-Item -Path $_ -Recurse -Force }
Write-Success "Python cache cleared"
}
catch {
Write-Warning "Could not clear all cache files: $_"
}
}
# Get absolute path
function Get-AbsolutePath {
param([string]$Path)
if (Test-Path $Path) {
# Use Resolve-Path for full resolution
return Resolve-Path $Path
}
else {
# Use unresolved method
return $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path)
}
}
# Check Python version
function Test-PythonVersion {
param([string]$PythonCmd)
try {
$version = & $PythonCmd --version 2>&1
if ($version -match "Python (\d+)\.(\d+)") {
$major = [int]$matches[1]
$minor = [int]$matches[2]
return ($major -gt 3) -or ($major -eq 3 -and $minor -ge 10)
}
return $false
}
catch {
return $false
}
}
# Find Python installation
function Find-Python {
$pythonCandidates = @("python", "python3", "py")
foreach ($cmd in $pythonCandidates) {
if (Test-Command $cmd) {
if (Test-PythonVersion $cmd) {
$version = & $cmd --version 2>&1
Write-Success "Found Python: $version"
return $cmd
}
}
}
# Try Windows Python Launcher with specific versions
$pythonVersions = @("3.12", "3.11", "3.10", "3.9")
foreach ($version in $pythonVersions) {
$cmd = "py -$version"
try {
$null = Invoke-Expression "$cmd --version" 2>$null
Write-Success "Found Python via py launcher: $cmd"
return $cmd
}
catch {
continue
}
}
Write-Error "Python 3.10+ not found. Please install Python from https://python.org"
return $null
}
# Clean up old Docker artifacts
function Cleanup-Docker {
if (Test-Path $DOCKER_CLEANED_FLAG) {
return
}
if (!(Test-Command "docker")) {
return
}
try {
$null = docker info 2>$null
}
catch {
return
}
$foundArtifacts = $false
# Define containers to remove
$containers = @(
"gemini-mcp-server",
"gemini-mcp-redis",
"zen-mcp-server",
"zen-mcp-redis",
"zen-mcp-log-monitor"
)
# Remove containers
foreach ($container in $containers) {
try {
$exists = docker ps -a --format "{{.Names}}" | Where-Object { $_ -eq $container }
if ($exists) {
if (!$foundArtifacts) {
Write-Info "One-time Docker cleanup..."
$foundArtifacts = $true
}
Write-Info " Removing container: $container"
docker stop $container 2>$null | Out-Null
docker rm $container 2>$null | Out-Null
}
}
catch {
# Ignore errors
}
}
# Remove images
$images = @("gemini-mcp-server:latest", "zen-mcp-server:latest")
foreach ($image in $images) {
try {
$exists = docker images --format "{{.Repository}}:{{.Tag}}" | Where-Object { $_ -eq $image }
if ($exists) {
if (!$foundArtifacts) {
Write-Info "One-time Docker cleanup..."
$foundArtifacts = $true
}
Write-Info " Removing image: $image"
docker rmi $image 2>$null | Out-Null
}
}
catch {
# Ignore errors
}
}
# Remove volumes
$volumes = @("redis_data", "mcp_logs")
foreach ($volume in $volumes) {
try {
$exists = docker volume ls --format "{{.Name}}" | Where-Object { $_ -eq $volume }
if ($exists) {
if (!$foundArtifacts) {
Write-Info "One-time Docker cleanup..."
$foundArtifacts = $true
}
Write-Info " Removing volume: $volume"
docker volume rm $volume 2>$null | Out-Null
}
}
catch {
# Ignore errors
}
}
if ($foundArtifacts) {
Write-Success "Docker cleanup complete"
}
New-Item -Path $DOCKER_CLEANED_FLAG -ItemType File -Force | Out-Null
}
# Validate API keys
function Test-ApiKeys {
Write-Step "Validating API Keys"
if (!(Test-Path ".env")) {
Write-Warning "No .env file found. API keys should be configured."
return $false
}
$envContent = Get-Content ".env"
$hasValidKey = $false
$keyPatterns = @{
"GEMINI_API_KEY" = "AIza[0-9A-Za-z-_]{35}"
"OPENAI_API_KEY" = "sk-[a-zA-Z0-9]{20}T3BlbkFJ[a-zA-Z0-9]{20}"
"XAI_API_KEY" = "xai-[a-zA-Z0-9-_]+"
"OPENROUTER_API_KEY" = "sk-or-[a-zA-Z0-9-_]+"
}
foreach ($line in $envContent) {
if ($line -match '^([^#][^=]*?)=(.*)$') {
$key = $matches[1].Trim()
$value = $matches[2].Trim() -replace '^["'']|["'']$', ''
if ($keyPatterns.ContainsKey($key) -and $value -ne "your_${key.ToLower()}_here" -and $value.Length -gt 10) {
Write-Success "Found valid $key"
$hasValidKey = $true
}
}
}
if (!$hasValidKey) {
Write-Warning "No valid API keys found in .env file"
Write-Info "Please edit .env file with your actual API keys"
return $false
}
return $true
}
# Check if uv is available
function Test-Uv {
return Test-Command "uv"
}
# Setup environment using uv-first approach
function Initialize-Environment {
Write-Step "Setting up Python Environment"
# Try uv first for faster package management
if (Test-Uv) {
Write-Info "Using uv for faster package management..."
if (Test-Path $VENV_PATH) {
if ($Force) {
Write-Warning "Removing existing environment..."
Remove-Item -Recurse -Force $VENV_PATH
}
else {
Write-Success "Virtual environment already exists"
$pythonPath = "$VENV_PATH\Scripts\python.exe"
if (Test-Path $pythonPath) {
return Get-AbsolutePath $pythonPath
}
}
}
try {
Write-Info "Creating virtual environment with uv..."
uv venv $VENV_PATH --python 3.12
if ($LASTEXITCODE -eq 0) {
Write-Success "Environment created with uv"
return Get-AbsolutePath "$VENV_PATH\Scripts\python.exe"
}
}
catch {
Write-Warning "uv failed, falling back to venv"
}
}
# Fallback to standard venv
$pythonCmd = Find-Python
if (!$pythonCmd) {
throw "Python 3.10+ not found"
}
if (Test-Path $VENV_PATH) {
if ($Force) {
Write-Warning "Removing existing environment..."
try {
# Stop any Python processes that might be using the venv
Get-Process python* -ErrorAction SilentlyContinue | Where-Object { $_.Path -like "*$VENV_PATH*" } | Stop-Process -Force -ErrorAction SilentlyContinue
# Wait a moment for processes to terminate
Start-Sleep -Seconds 2
# Use the robust removal function
if (Remove-LockedDirectory $VENV_PATH) {
Write-Success "Existing environment removed"
}
else {
throw "Unable to remove existing environment. Please restart your computer and try again."
}
}
catch {
Write-Error "Failed to remove existing environment: $_"
Write-Host ""
Write-Host "Try these solutions:" -ForegroundColor Yellow
Write-Host "1. Close all terminals and VS Code instances" -ForegroundColor White
Write-Host "2. Run: Get-Process python* | Stop-Process -Force" -ForegroundColor White
Write-Host "3. Manually delete: $VENV_PATH" -ForegroundColor White
Write-Host "4. Then run the script again" -ForegroundColor White
exit 1
}
}
else {
Write-Success "Virtual environment already exists"
return Get-AbsolutePath "$VENV_PATH\Scripts\python.exe"
}
}
Write-Info "Creating virtual environment with $pythonCmd..."
if ($pythonCmd.StartsWith("py ")) {
Invoke-Expression "$pythonCmd -m venv $VENV_PATH"
}
else {
& $pythonCmd -m venv $VENV_PATH
}
if ($LASTEXITCODE -ne 0) {
throw "Failed to create virtual environment"
}
Write-Success "Virtual environment created"
return Get-AbsolutePath "$VENV_PATH\Scripts\python.exe"
}
# Setup virtual environment (legacy function for compatibility)
function Initialize-VirtualEnvironment {
Write-Step "Setting up Python Virtual Environment"
if (!$SkipVenv -and (Test-Path $VENV_PATH)) {
if ($Force) {
Write-Warning "Removing existing virtual environment..."
try {
# Stop any Python processes that might be using the venv
Get-Process python* -ErrorAction SilentlyContinue | Where-Object { $_.Path -like "*$VENV_PATH*" } | Stop-Process -Force -ErrorAction SilentlyContinue
# Wait a moment for processes to terminate
Start-Sleep -Seconds 2
# Use the robust removal function
if (Remove-LockedDirectory $VENV_PATH) {
Write-Success "Existing environment removed"
}
else {
throw "Unable to remove existing environment. Please restart your computer and try again."
}
}
catch {
Write-Error "Failed to remove existing environment: $_"
Write-Host ""
Write-Host "Try these solutions:" -ForegroundColor Yellow
Write-Host "1. Close all terminals and VS Code instances" -ForegroundColor White
Write-Host "2. Run: Get-Process python* | Stop-Process -Force" -ForegroundColor White
Write-Host "3. Manually delete: $VENV_PATH" -ForegroundColor White
Write-Host "4. Then run the script again" -ForegroundColor White
exit 1
}
}
else {
Write-Success "Virtual environment already exists"
return
}
}
if ($SkipVenv) {
Write-Warning "Skipping virtual environment setup"
return
}
$pythonCmd = Find-Python
if (!$pythonCmd) {
Write-Error "Python 3.10+ not found. Please install Python from https://python.org"
exit 1
}
Write-Info "Using Python: $pythonCmd"
Write-Info "Creating virtual environment..."
try {
if ($pythonCmd.StartsWith("py ")) {
Invoke-Expression "$pythonCmd -m venv $VENV_PATH"
}
else {
& $pythonCmd -m venv $VENV_PATH
}
if ($LASTEXITCODE -ne 0) {
throw "Failed to create virtual environment"
}
Write-Success "Virtual environment created"
}
catch {
Write-Error "Failed to create virtual environment: $_"
exit 1
}
}
# Install dependencies function - Simplified uv-first approach
function Install-Dependencies {
param(
[Parameter(Mandatory = $true)]
[string]$PythonPath,
[switch]$InstallDevDependencies = $false
)
Write-Step "Installing Dependencies"
# Build requirements files list
$requirementsFiles = @("requirements.txt")
if ($InstallDevDependencies) {
if (Test-Path "requirements-dev.txt") {
$requirementsFiles += "requirements-dev.txt"
Write-Info "Including development dependencies from requirements-dev.txt"
}
else {
Write-Warning "Development dependencies requested but requirements-dev.txt not found"
}
}
# Try uv first for faster package management
$useUv = Test-Uv
if ($useUv) {
Write-Info "Installing dependencies with uv (fast)..."
try {
foreach ($file in $requirementsFiles) {
Write-Info "Installing from $file with uv..."
$uv = (Get-Command uv -ErrorAction Stop).Source
$arguments = @('pip', 'install', '-r', $file, '--python', $PythonPath)
$proc = Start-Process -FilePath $uv -ArgumentList $arguments -NoNewWindow -Wait -PassThru
if ($proc.ExitCode -ne 0) {
throw "uv failed to install $file with exit code $($proc.ExitCode)"
}
}
Write-Success "Dependencies installed successfully with uv"
return
}
catch {
Write-Warning "uv installation failed: $_. Falling back to pip"
$useUv = $false
}
}
# Fallback to pip
Write-Info "Installing dependencies with pip..."
$pipCmd = Join-Path (Split-Path $PythonPath -Parent) "pip.exe"
try {
# Upgrade pip first
& $pipCmd install --upgrade pip | Out-Null
}
catch {
Write-Warning "Could not upgrade pip, continuing..."
}
try {
foreach ($file in $requirementsFiles) {
Write-Info "Installing from $file with pip..."
& $pipCmd install -r $file
if ($LASTEXITCODE -ne 0) {
throw "pip failed to install $file"
}
}
Write-Success "Dependencies installed successfully with pip"
}
catch {
Write-Error "Failed to install dependencies with pip: $_"
exit 1
}
}
# ----------------------------------------------------------------------------
# Docker Functions
# ============================================================================
# Test Docker availability and requirements
function Test-DockerRequirements {
Write-Step "Checking Docker Requirements"
if (!(Test-Command "docker")) {
Write-Error "Docker not found. Please install Docker Desktop from https://docker.com"
return $false
}
try {
$null = docker version 2>$null
Write-Success "Docker is installed and running"
}
catch {
Write-Error "Docker is installed but not running. Please start Docker Desktop."
return $false
}
if (!(Test-Command "docker-compose")) {
Write-Warning "docker-compose not found. Trying docker compose..."
try {
$null = docker compose version 2>$null
Write-Success "Docker Compose (v2) is available"
return $true
}
catch {
Write-Error "Docker Compose not found. Please install Docker Compose."
return $false
}
}
else {
Write-Success "Docker Compose is available"
return $true
}
}
# Build Docker image
function Build-DockerImage {
param([switch]$Force = $false)
Write-Step "Building Docker Image"
# Check if image exists
try {
$imageExists = docker images --format "{{.Repository}}:{{.Tag}}" | Where-Object { $_ -eq "zen-mcp-server:latest" }
if ($imageExists -and !$Force) {
Write-Success "Docker image already exists. Use -Force to rebuild."
return $true
}
}
catch {
# Continue if command fails
}
if ($Force -and $imageExists) {
Write-Info "Forcing rebuild of Docker image..."
try {
docker rmi zen-mcp-server:latest 2>$null
}
catch {
Write-Warning "Could not remove existing image, continuing..."
}
}
Write-Info "Building Docker image from Dockerfile..."
try {
$buildArgs = @()
if ($Dev) {
# For development builds, we could add specific build args
Write-Info "Building with development support..."
}
docker build -t zen-mcp-server:latest .
if ($LASTEXITCODE -ne 0) {
throw "Docker build failed"
}
Write-Success "Docker image built successfully"
return $true
}
catch {
Write-Error "Failed to build Docker image: $_"
return $false
}
}
# Prepare Docker environment file
function Initialize-DockerEnvironment {
Write-Step "Preparing Docker Environment"
# Ensure .env file exists
if (!(Test-Path ".env")) {
Write-Warning "No .env file found. Creating default .env file..."
$defaultEnv = @"
# API Keys - Replace with your actual keys
GEMINI_API_KEY=your_gemini_api_key_here
GOOGLE_API_KEY=your_google_api_key_here
OPENAI_API_KEY=your_openai_api_key_here
ANTHROPIC_API_KEY=your_anthropic_api_key_here
XAI_API_KEY=your_xai_api_key_here
DIAL_API_KEY=your_dial_api_key_here
DIAL_API_HOST=your_dial_api_host_here
DIAL_API_VERSION=your_dial_api_version_here
OPENROUTER_API_KEY=your_openrouter_api_key_here
CUSTOM_API_URL=your_custom_api_url_here
CUSTOM_API_KEY=your_custom_api_key_here
CUSTOM_MODEL_NAME=your_custom_model_name_here
# Server Configuration
DEFAULT_MODEL=auto
LOG_LEVEL=INFO
LOG_MAX_SIZE=10MB
LOG_BACKUP_COUNT=5
DEFAULT_THINKING_MODE_THINKDEEP=high
# Optional Advanced Settings
#DISABLED_TOOLS=
#MAX_MCP_OUTPUT_TOKENS=
#TZ=UTC
"@
$defaultEnv | Out-File -FilePath ".env" -Encoding UTF8
Write-Success "Default .env file created"
Write-Warning "Please edit .env file with your actual API keys"
}
else {
Write-Success ".env file exists"
}
# Create logs directory for volume mount
Initialize-Logging
return $true
}
# Start Docker services
function Start-DockerServices {
param([switch]$Follow = $false)
Write-Step "Starting Docker Services"
# Check if docker-compose.yml exists
if (!(Test-Path "docker-compose.yml")) {
Write-Error "docker-compose.yml not found in current directory"
return $false
}
try {
# Stop any existing services
Write-Info "Stopping any existing services..."
if (Test-Command "docker-compose") {
docker-compose down 2>$null
}
else {
docker compose down 2>$null
}
# Start services
Write-Info "Starting Zen MCP Server with Docker Compose..."
if (Test-Command "docker-compose") {
if ($Follow) {
docker-compose up --build
}
else {
docker-compose up -d --build
}
}
else {
if ($Follow) {
docker compose up --build
}
else {
docker compose up -d --build
}
}
if ($LASTEXITCODE -ne 0) {
throw "Failed to start Docker services"
}
if (!$Follow) {
Write-Success "Docker services started successfully"
Write-Info "Container name: zen-mcp-server"
Write-Host ""
Write-Host "To view logs: " -NoNewline
Write-Host "docker logs -f zen-mcp-server" -ForegroundColor Yellow
Write-Host "To stop: " -NoNewline
Write-Host "docker-compose down" -ForegroundColor Yellow
}
return $true
}
catch {
Write-Error "Failed to start Docker services: $_"
return $false
}
}
# Get Docker container status
function Get-DockerStatus {
try {
$containerStatus = docker ps --filter "name=zen-mcp-server" --format "{{.Status}}"
if ($containerStatus) {
Write-Success "Container status: $containerStatus"
return $true
}
else {
Write-Warning "Container not running"
return $false
}
}
catch {
Write-Warning "Could not get container status: $_"
return $false
}
}
# ============================================================================
# End Docker Functions
# ============================================================================
# Setup logging directory
function Initialize-Logging {
Write-Step "Setting up Logging"
if (!(Test-Path $LOG_DIR)) {
New-Item -ItemType Directory -Path $LOG_DIR -Force | Out-Null
Write-Success "Logs directory created"
}
else {
Write-Success "Logs directory already exists"
}
}
# Check Docker
function Test-Docker {
Write-Step "Checking Docker Setup"
if ($SkipDocker) {
Write-Warning "Skipping Docker checks"
return
}
if (Test-Command "docker") {
try {
$null = docker version 2>$null
Write-Success "Docker is installed and running"
if (Test-Command "docker-compose") {
Write-Success "Docker Compose is available"
}
else {
Write-Warning "Docker Compose not found. Install Docker Desktop for Windows."
}
}