Repository navigation
Expand file tree
/
Copy pathinstall-hooks.ps1
More file actions
541 lines (463 loc) · 20.8 KB
/
Copy pathinstall-hooks.ps1
File metadata and controls
541 lines (463 loc) · 20.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
# Token Optimizer MCP - Automated Hooks Installer
# Installs global Claude Code hooks for automatic token optimization
param(
[switch]$Force, # Force reinstall even if already installed
[switch]$SkipMCPCheck, # Skip MCP server installation check
[switch]$DryRun # Preview changes without applying
)
$ErrorActionPreference = "Stop"
# ============================================================
# Configuration
# ============================================================
$HOOKS_DIR = "$env:USERPROFILE\.claude-global\hooks"
$CLAUDE_SETTINGS = "$env:USERPROFILE\.claude\settings.json"
$CLAUDE_STATE = "$env:USERPROFILE\.claude.json"
$MCP_CONFIG = "$env:APPDATA\Claude\claude_desktop_config.json"
$REPO_URL = "https://raw.githubusercontent.com/ooples/token-optimizer-mcp/master/hooks"
# ============================================================
# Helper Functions
# ============================================================
function Write-Status {
param([string]$Message, [string]$Type = "INFO")
$color = switch ($Type) {
"SUCCESS" { "Green" }
"ERROR" { "Red" }
"WARN" { "Yellow" }
default { "Cyan" }
}
Write-Host "[$Type] $Message" -ForegroundColor $color
}
function Test-Prerequisites {
Write-Status "Checking prerequisites..." "INFO"
# Check PowerShell version
if ($PSVersionTable.PSVersion.Major -lt 5) {
throw "PowerShell 5.1 or later is required. Current version: $($PSVersionTable.PSVersion)"
}
Write-Status " PowerShell version: $($PSVersionTable.PSVersion)" "SUCCESS"
# Check Claude Code is installed
try {
$claudeVersion = & claude --version 2>&1
Write-Status " Claude Code installed: $claudeVersion" "SUCCESS"
} catch {
throw "Claude Code CLI not found. Install from: https://docs.claude.com/en/docs/claude-code"
}
# Check execution policy
$policy = Get-ExecutionPolicy
if ($policy -eq "Restricted") {
Write-Status "PowerShell execution policy is Restricted" "WARN"
Write-Status "Setting execution policy to RemoteSigned..." "INFO"
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser -Force
Write-Status " Execution policy updated" "SUCCESS"
} else {
Write-Status " Execution policy: $policy" "SUCCESS"
}
# Check token-optimizer-mcp is installed (optional)
if (-not $SkipMCPCheck) {
$mcpPath = "$env:APPDATA\npm\node_modules\@ooples\token-optimizer-mcp"
if (-not (Test-Path $mcpPath)) {
Write-Status "token-optimizer-mcp not found" "WARN"
Write-Status "Install with: npm install -g @ooples/token-optimizer-mcp" "INFO"
$response = Read-Host "Install token-optimizer-mcp now? (y/n)"
if ($response -eq "y") {
npm install -g @ooples/token-optimizer-mcp
Write-Status " token-optimizer-mcp installed" "SUCCESS"
} else {
throw "token-optimizer-mcp is required for hooks to work"
}
} else {
Write-Status " token-optimizer-mcp found" "SUCCESS"
}
}
}
function Install-HooksFiles {
Write-Status "Installing hooks files..." "INFO"
# Install the CURRENT hook files from the package.
#
# This used to download a dispatcher.ps1 from the default branch and wire
# four events at it -- none of them SessionStart, which is where the policy
# and the project briefing are delivered. The plugin's real hooks are three
# ES modules under plugin/hooks, and they are what the doctor probes.
$sourceHooks = Join-Path $PSScriptRoot "plugin\hooks"
if (-not (Test-Path $sourceHooks)) {
$sourceHooks = Join-Path $MCP_GLOBAL_PATH "plugin\hooks"
}
if (-not (Test-Path $sourceHooks)) {
Write-Status "Could not find the plugin hooks to install (looked in $sourceHooks)" "ERROR"
Write-Status "Reinstall the package: npm install -g @ooples/token-optimizer-mcp" "INFO"
throw "Plugin hooks not found"
}
if ($DryRun) {
Write-Status "[DRY RUN] Would install the plugin hooks into $HOOKS_DIR oken-optimizer" "INFO"
return
}
# Under a token-optimizer\ subdirectory on purpose: it puts our marker into
# every command string we write, which is what makes the entries findable
# for verification and removable on uninstall.
$dest = Join-Path $HOOKS_DIR "token-optimizer"
if (-not (Test-Path $dest)) { New-Item -ItemType Directory -Path $dest -Force | Out-Null }
Copy-Item -Path (Join-Path $sourceHooks "*") -Destination $dest -Recurse -Force
Write-Status "Installed hooks to $dest" "SUCCESS"
}
function Configure-ClaudeSettings {
Write-Status "Configuring Claude Code settings..." "INFO"
# Wire the hooks by MERGING, never by overwriting.
#
# The previous version assigned $settings.hooks wholesale, which destroyed
# every hook the user had configured -- silently, and from a tool whose
# uninstaller promises it never touches anything it did not write. The merge
# now lives in scripts/wire-hooks.mjs, shared with the bash installer and
# covered by tests.
$wireScript = Join-Path $PSScriptRoot "scripts\wire-hooks.mjs"
if (-not (Test-Path $wireScript)) {
$wireScript = Join-Path $MCP_GLOBAL_PATH "scripts\wire-hooks.mjs"
}
if (-not (Test-Path $wireScript)) {
Write-Status "Could not find wire-hooks.mjs; settings were NOT modified" "ERROR"
return
}
$hooksTarget = Join-Path $HOOKS_DIR "token-optimizer"
if ($DryRun) {
& node $wireScript $CLAUDE_SETTINGS $hooksTarget --dry-run
return
}
& node $wireScript $CLAUDE_SETTINGS $hooksTarget
if ($LASTEXITCODE -ne 0) {
Write-Status "Could not wire hooks into $CLAUDE_SETTINGS" "ERROR"
return
}
Write-Status "Updated Claude Code settings" "SUCCESS"
}
function Configure-WorkspaceTrust {
Write-Status "Configuring workspace trust..." "INFO"
$currentDir = (Get-Location).Path
if (-not (Test-Path $CLAUDE_STATE)) {
Write-Status "No .claude.json found - trust will be prompted on first run" "WARN"
return
}
# Backup existing state
$backup = "$CLAUDE_STATE.backup.$(Get-Date -Format 'yyyyMMdd-HHmmss')"
Copy-Item $CLAUDE_STATE $backup
# Read and update state
$state = Get-Content $CLAUDE_STATE -Raw | ConvertFrom-Json
# Ensure projects object exists
if (-not $state.projects) {
$state | Add-Member -NotePropertyName "projects" -NotePropertyValue @{} -Force
}
# Add/update current directory trust
if (-not $state.projects.$currentDir) {
$state.projects | Add-Member -NotePropertyName $currentDir -NotePropertyValue @{} -Force
}
$state.projects.$currentDir | Add-Member -NotePropertyName "hasTrustDialogAccepted" -NotePropertyValue $true -Force
if ($DryRun) {
Write-Status "[DRY RUN] Would accept workspace trust for: $currentDir" "INFO"
return
}
# Save state
$json = $state | ConvertTo-Json -Depth 100
[System.IO.File]::WriteAllText($CLAUDE_STATE, $json, (New-Object System.Text.UTF8Encoding $false))
Write-Status " Accepted workspace trust for: $currentDir" "SUCCESS"
}
function Configure-MCPServer {
Write-Status "Detecting installed AI tools and configuring MCP server..." "INFO"
$mcpPath = "$env:APPDATA\npm\node_modules\@ooples\token-optimizer-mcp\dist\index.js"
$mcpServerConfig = @{
type = "stdio"
command = "node"
args = @($mcpPath)
env = @{}
}
$toolsConfigured = 0
# 1. Claude Desktop
$claudeDesktopConfig = "$env:APPDATA\Claude\claude_desktop_config.json"
if (Test-Path $claudeDesktopConfig) {
try {
$settings = Get-Content $claudeDesktopConfig -Raw | ConvertFrom-Json
if (-not $settings.mcpServers) {
$settings | Add-Member -NotePropertyName "mcpServers" -NotePropertyValue @{} -Force
}
$settings.mcpServers."token-optimizer" = $mcpServerConfig
if (-not $DryRun) {
$json = $settings | ConvertTo-Json -Depth 10
[System.IO.File]::WriteAllText($claudeDesktopConfig, $json, (New-Object System.Text.UTF8Encoding $false))
Write-Status " Configured token-optimizer for Claude Desktop" "SUCCESS"
$toolsConfigured++
} else {
Write-Status "[DRY RUN] Would configure Claude Desktop" "INFO"
}
} catch {
Write-Status " Failed to configure Claude Desktop: $($_.Exception.Message)" "WARN"
}
}
# 2. Cursor IDE
$cursorConfig = "$env:USERPROFILE\.cursor\mcp.json"
if (Test-Path $cursorConfig) {
try {
$settings = Get-Content $cursorConfig -Raw | ConvertFrom-Json
if (-not $settings.mcpServers) {
$settings | Add-Member -NotePropertyName "mcpServers" -NotePropertyValue @{} -Force
}
$settings.mcpServers."token-optimizer" = $mcpServerConfig
if (-not $DryRun) {
$json = $settings | ConvertTo-Json -Depth 10
[System.IO.File]::WriteAllText($cursorConfig, $json, (New-Object System.Text.UTF8Encoding $false))
Write-Status " Configured token-optimizer for Cursor IDE" "SUCCESS"
$toolsConfigured++
} else {
Write-Status "[DRY RUN] Would configure Cursor IDE" "INFO"
}
} catch {
Write-Status " Failed to configure Cursor IDE: $($_.Exception.Message)" "WARN"
}
}
# 3. VS Code with Cline extension
$vscodeConfigDir = "$env:APPDATA\Code\User\globalStorage\saoudrizwan.claude-dev"
if (Test-Path $vscodeConfigDir) {
$clineConfig = "$vscodeConfigDir\cline_mcp_settings.json"
try {
if (Test-Path $clineConfig) {
$settings = Get-Content $clineConfig -Raw | ConvertFrom-Json
} else {
$settings = @{ mcpServers = @{} }
}
if (-not $settings.mcpServers) {
$settings | Add-Member -NotePropertyName "mcpServers" -NotePropertyValue @{} -Force
}
$settings.mcpServers."token-optimizer" = $mcpServerConfig
if (-not $DryRun) {
$json = $settings | ConvertTo-Json -Depth 10
[System.IO.File]::WriteAllText($clineConfig, $json, (New-Object System.Text.UTF8Encoding $false))
Write-Status " Configured token-optimizer for Cline (VS Code)" "SUCCESS"
$toolsConfigured++
} else {
Write-Status "[DRY RUN] Would configure Cline (VS Code)" "INFO"
}
} catch {
Write-Status " Failed to configure Cline: $($_.Exception.Message)" "WARN"
}
}
# 4. VS Code with GitHub Copilot
$vscodeWorkspaceConfig = ".vscode\mcp.json"
if (Test-Path $vscodeWorkspaceConfig) {
try {
$settings = Get-Content $vscodeWorkspaceConfig -Raw | ConvertFrom-Json
if (-not $settings.mcpServers) {
$settings | Add-Member -NotePropertyName "mcpServers" -NotePropertyValue @{} -Force
}
$settings.mcpServers."token-optimizer" = $mcpServerConfig
if (-not $DryRun) {
$json = $settings | ConvertTo-Json -Depth 10
[System.IO.File]::WriteAllText($vscodeWorkspaceConfig, $json, (New-Object System.Text.UTF8Encoding $false))
Write-Status " Configured token-optimizer for VS Code Copilot (workspace)" "SUCCESS"
$toolsConfigured++
} else {
Write-Status "[DRY RUN] Would configure VS Code Copilot" "INFO"
}
} catch {
Write-Status " Failed to configure VS Code Copilot: $($_.Exception.Message)" "WARN"
}
}
# 5. Windsurf IDE
$windsurfConfig = "$env:APPDATA\Windsurf\mcp.json"
if (Test-Path $windsurfConfig) {
try {
$settings = Get-Content $windsurfConfig -Raw | ConvertFrom-Json
if (-not $settings.mcpServers) {
$settings | Add-Member -NotePropertyName "mcpServers" -NotePropertyValue @{} -Force
}
$settings.mcpServers."token-optimizer" = $mcpServerConfig
if (-not $DryRun) {
$json = $settings | ConvertTo-Json -Depth 10
[System.IO.File]::WriteAllText($windsurfConfig, $json, (New-Object System.Text.UTF8Encoding $false))
Write-Status " Configured token-optimizer for Windsurf IDE" "SUCCESS"
$toolsConfigured++
} else {
Write-Status "[DRY RUN] Would configure Windsurf IDE" "INFO"
}
} catch {
Write-Status " Failed to configure Windsurf IDE: $($_.Exception.Message)" "WARN"
}
}
if ($toolsConfigured -eq 0) {
Write-Status "No AI tools detected. MCP server not configured." "WARN"
Write-Status "Supported tools: Claude Desktop / Cursor IDE / Cline (VS Code) / GitHub Copilot (VS Code) / Windsurf" "INFO"
} else {
Write-Status " Configured token-optimizer MCP server for $toolsConfigured AI tool(s)" "SUCCESS"
}
}
function Test-Installation {
Write-Status "Verifying installation..." "INFO"
$issues = @()
# Verify the files this installer ACTUALLY SHIPS.
#
# This list used to require a dispatcher.ps1 plus handlers/ and helpers/
# shell libraries -- the design Install-HooksFiles replaced with three ES
# modules, as the comment above it says. None of those files has been
# produced by an install for some time, so verification could not pass, and
# a failed verification skipped record-install.mjs. That is why the doctor
# reports "no record of what was installed": the installer was prevented
# from writing the manifest by a check on files it no longer creates.
#
# Note the subdirectory: Install-HooksFiles copies into
# $HOOKS_DIR\token-optimizer, not $HOOKS_DIR. The old list omitted it, so
# every path was wrong twice over.
$requiredFiles = @(
"$HOOKS_DIR\token-optimizer\session-start.mjs",
"$HOOKS_DIR\token-optimizer\pretooluse-router.mjs",
"$HOOKS_DIR\token-optimizer\precompact-optimize.mjs",
"$HOOKS_DIR\token-optimizer\hooks.json",
# The shared library every hook imports. Present but empty would break
# all three entrypoints, so it is checked explicitly.
"$HOOKS_DIR\token-optimizer\lib\policy.mjs"
)
foreach ($file in $requiredFiles) {
if (-not (Test-Path $file)) {
$issues += "Missing file: $file"
}
}
# Check settings.json has hooks
if (Test-Path $CLAUDE_SETTINGS) {
$settings = Get-Content $CLAUDE_SETTINGS -Raw | ConvertFrom-Json
if (-not $settings.hooks) {
$issues += "Hooks not configured in settings.json"
}
} else {
$issues += "Settings.json not found"
}
# Check MCP server configured in at least one AI tool
$mcpConfigured = $false
$checkedConfigs = @()
# Claude Desktop
$claudeDesktopConfig = "$env:APPDATA\Claude\claude_desktop_config.json"
if (Test-Path $claudeDesktopConfig) {
$settings = Get-Content $claudeDesktopConfig -Raw | ConvertFrom-Json
if ($settings.mcpServers."token-optimizer") {
$mcpConfigured = $true
$checkedConfigs += "Claude Desktop"
}
}
# Cursor IDE
$cursorConfig = "$env:USERPROFILE\.cursor\mcp.json"
if (Test-Path $cursorConfig) {
$settings = Get-Content $cursorConfig -Raw | ConvertFrom-Json
if ($settings.mcpServers."token-optimizer") {
$mcpConfigured = $true
$checkedConfigs += "Cursor IDE"
}
}
# Cline (VS Code)
$clineConfig = "$env:APPDATA\Code\User\globalStorage\saoudrizwan.claude-dev\cline_mcp_settings.json"
if (Test-Path $clineConfig) {
$settings = Get-Content $clineConfig -Raw | ConvertFrom-Json
if ($settings.mcpServers."token-optimizer") {
$mcpConfigured = $true
$checkedConfigs += "Cline (VS Code)"
}
}
# VS Code Copilot
$vscodeConfig = ".vscode\mcp.json"
if (Test-Path $vscodeConfig) {
$settings = Get-Content $vscodeConfig -Raw | ConvertFrom-Json
if ($settings.mcpServers."token-optimizer") {
$mcpConfigured = $true
$checkedConfigs += "VS Code Copilot"
}
}
# Windsurf IDE
$windsurfConfig = "$env:APPDATA\Windsurf\mcp.json"
if (Test-Path $windsurfConfig) {
$settings = Get-Content $windsurfConfig -Raw | ConvertFrom-Json
if ($settings.mcpServers."token-optimizer") {
$mcpConfigured = $true
$checkedConfigs += "Windsurf IDE"
}
}
# ADVISORY, NOT FATAL. This check looks for the server in
# claude_desktop_config.json, Cursor, Cline, Copilot and Windsurf. A Claude
# Code CLI user has it in none of them -- that path gets the MCP server from
# the plugin's own .mcp.json -- so treating absence as an installation
# failure fails the install for the primary supported client.
if (-not $mcpConfigured) {
Write-Status "MCP server not found in Claude Desktop / Cursor / Cline / Copilot / Windsurf" "WARN"
Write-Status "That is expected on Claude Code, which gets the server from the plugin instead" "INFO"
} else {
Write-Status " MCP server configured in: $($checkedConfigs -join ', ')" "SUCCESS"
}
if ($issues.Count -gt 0) {
Write-Status "Installation issues found:" "ERROR"
$issues | ForEach-Object { Write-Status " - $_" "ERROR" }
return $false
}
Write-Status " All verification checks passed!" "SUCCESS"
return $true
}
# ============================================================
# Main Installation Flow
# ============================================================
try {
Write-Host ""
Write-Host "=============================================================" -ForegroundColor Cyan
Write-Host " Token Optimizer MCP - Hooks Installer " -ForegroundColor Cyan
Write-Host " Automated installation of global Claude Code hooks " -ForegroundColor Cyan
Write-Host "=============================================================" -ForegroundColor Cyan
Write-Host ""
if ($DryRun) {
Write-Status "DRY RUN MODE - No changes will be made" "WARN"
Write-Host ""
}
# Step 1: Prerequisites
Test-Prerequisites
Write-Host ""
# Step 2: Install hooks files
Install-HooksFiles
Write-Host ""
# Step 3: Configure Claude Code settings
Configure-ClaudeSettings
Write-Host ""
# Step 4: Configure workspace trust
Configure-WorkspaceTrust
Write-Host ""
# Step 5: Configure MCP server
Configure-MCPServer
Write-Host ""
# Step 6: Verify installation
if ($DryRun) {
Write-Status "DRY RUN COMPLETE - No changes were made" "SUCCESS"
} else {
$verified = Test-Installation
# RECORD THE MANIFEST REGARDLESS OF THE VERDICT.
#
# This used to sit inside `if ($verified)`, which inverted the
# relationship it needed: the manifest records what was written to this
# machine, and files were written before verification ran. Skipping it on
# failure leaves those files with no record of where they came from --
# exactly the case where an exact uninstall matters most. It is also why
# the doctor reported a missing manifest on a machine whose hooks were
# installed and working.
try {
& node (Join-Path $PSScriptRoot 'scripts/record-install.mjs') $HOOKS_DIR $CLAUDE_SETTINGS
} catch {
Write-Status "Could not record the install manifest (uninstall will be manual)" "WARN"
}
if ($verified) {
Write-Host ""
Write-Host "=============================================================" -ForegroundColor Green
Write-Host " Installation Complete! " -ForegroundColor Green
Write-Host "=============================================================" -ForegroundColor Green
Write-Host ""
Write-Status "Next steps" "INFO"
Write-Status "1. Restart Claude Code CLI" "INFO"
Write-Status "2. Run any command (e.g. claude help)" "INFO"
Write-Status "3. Check logs at $env:USERPROFILE\.claude-global\hooks\logs\dispatcher.log" "INFO"
Write-Host ""
Write-Status "Documentation: https://github.com/ooples/token-optimizer-mcp/blob/main/HOOKS-INSTALLATION.md" "INFO"
} else {
throw "Installation verification failed"
}
}
} catch {
Write-Host ""
Write-Status "Installation failed: $($_.Exception.Message)" "ERROR"
Write-Status "Check the error above and try again" "ERROR"
Write-Status "For help see: https://github.com/ooples/token-optimizer-mcp/issues" "INFO"
exit 1
}