-
Notifications
You must be signed in to change notification settings - Fork 194
Expand file tree
/
Copy pathclaude_interactive.sh
More file actions
executable file
·357 lines (301 loc) · 9.81 KB
/
claude_interactive.sh
File metadata and controls
executable file
·357 lines (301 loc) · 9.81 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
#!/usr/bin/env bash
# claude_interactive.sh - Interactive script for working with Claude Code WebSocket API
# This script provides a menu-driven interface for common operations
# Source the libraries
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=./lib_claude.sh
source "$SCRIPT_DIR/lib_claude.sh"
# shellcheck source=./lib_ws_persistent.sh
source "$SCRIPT_DIR/lib_ws_persistent.sh"
# Configuration
export CLAUDE_LOG_DIR="mcp_interactive_logs"
mkdir -p "$CLAUDE_LOG_DIR"
CONN_ID="claude_interactive"
# Terminal colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Check if Claude Code is running
if ! claude_is_running; then
echo -e "${RED}Claude Code doesn't appear to be running.${NC}"
echo "Please start Claude Code and try again."
exit 1
fi
# Get WebSocket URL
WS_URL=$(get_claude_ws_url)
PORT=$(find_claude_lockfile)
# Initialize WebSocket connection
echo -e "${BLUE}Initializing WebSocket connection to ${WS_URL}...${NC}"
if ! ws_connect "$WS_URL" "$CONN_ID"; then
echo -e "${RED}Failed to establish connection.${NC}"
exit 1
fi
# Send initial connection handshake
echo -e "${BLUE}Sending initial handshake...${NC}"
# Format JSON to a single line for proper WebSocket transmission
HANDSHAKE_PARAMS=$(ws_format_json '{
"protocolVersion": "2024-11-05",
"capabilities": {
"tools": {}
},
"clientInfo": {
"name": "claude-nvim-client",
"version": "0.2.0"
}
}')
ws_notify "mcp.connect" "$HANDSHAKE_PARAMS" "$CONN_ID"
# Display header
clear
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE} Claude Code Interactive CLI ${NC}"
echo -e "${BLUE}========================================${NC}"
echo -e "${GREEN}Connected to WebSocket:${NC} $WS_URL"
echo -e "${GREEN}Using connection:${NC} $CONN_ID"
echo
# Function to display menu
show_menu() {
echo -e "${YELLOW}Available Commands:${NC}"
echo " 1) Get current selection"
echo " 2) List available tools"
echo " 3) Open a file"
echo " 4) Send custom JSON-RPC message"
echo " 5) Initialize session"
echo " 6) Show connection info"
echo " 7) Listen for messages"
echo " 8) Reconnect WebSocket"
echo " 9) Exit"
echo
echo -n "Enter your choice [1-9]: "
}
# Function to handle getting current selection
handle_get_selection() {
echo -e "${BLUE}Getting current selection...${NC}"
response=$(ws_rpc_request "tools/call" '{"name":"getCurrentSelection","arguments":{}}' "selection-$(date +%s)" "$CONN_ID")
if echo "$response" | grep -q '"error"'; then
echo -e "${RED}Error:${NC}"
echo "$response" | jq .error
else
echo -e "${GREEN}Selection information:${NC}"
echo "$response" | jq .
# Extract selection text if available - handle both direct response and nested content
selection_text=$(echo "$response" | jq -r '.result.text // .result.content[0].text // "No text selected"')
if [ "$selection_text" != "No text selected" ] && [ "$selection_text" != "null" ]; then
echo -e "${YELLOW}Selected text:${NC}"
echo "$selection_text"
fi
fi
}
# Function to handle listing tools
handle_list_tools() {
echo -e "${BLUE}Listing available tools...${NC}"
response=$(ws_rpc_request "tools/list" "{}" "tools-$(date +%s)" "$CONN_ID")
if echo "$response" | grep -q '"error"'; then
echo -e "${RED}Error:${NC}"
echo "$response" | jq .error
else
echo -e "${GREEN}Available tools:${NC}"
echo "$response" | jq -r '.result.tools[] | .name' 2>/dev/null | sort | while read -r tool; do
echo " - $tool"
done
echo
echo -e "${YELLOW}Total tools:${NC} $(echo "$response" | jq '.result.tools | length' 2>/dev/null || echo "unknown")"
fi
}
# Function to handle opening a file
handle_open_file() {
echo -n "Enter file path (absolute or relative): "
read -r file_path
if [ -z "$file_path" ]; then
echo -e "${RED}File path cannot be empty.${NC}"
return
fi
# Convert to absolute path if relative
if [[ $file_path != /* ]]; then
file_path="$(realpath "$file_path" 2>/dev/null)"
if ! realpath "$file_path" &>/dev/null; then
echo -e "${RED}Invalid file path: $file_path${NC}"
return
fi
fi
if [ ! -f "$file_path" ]; then
echo -e "${RED}File does not exist: $file_path${NC}"
return
fi
echo -e "${BLUE}Opening file:${NC} $file_path"
# Format the JSON parameters to a single line
PARAMS=$(ws_format_json "{\"name\":\"openFile\",\"arguments\":{\"filePath\":\"$file_path\",\"startText\":\"\",\"endText\":\"\"}}")
response=$(ws_rpc_request "tools/call" "$PARAMS" "open-file-$(date +%s)" "$CONN_ID")
if echo "$response" | grep -q '"error"'; then
echo -e "${RED}Error:${NC}"
echo "$response" | jq .error
else
echo -e "${GREEN}File opened successfully.${NC}"
fi
}
# Function to handle sending a custom message
handle_custom_message() {
echo "Enter method name (e.g., tools/list, getCurrentSelection):"
read -r method
if [ -z "$method" ]; then
echo -e "${RED}Method name cannot be empty.${NC}"
return
fi
echo "Enter parameters as JSON (default: {}):"
read -r params
# Use empty object if no params provided
if [ -z "$params" ]; then
params="{}"
fi
# Validate JSON
if ! echo "$params" | jq . >/dev/null 2>&1; then
echo -e "${RED}Invalid JSON parameters.${NC}"
return
fi
# Format params to single line JSON
params=$(ws_format_json "$params")
echo "Enter request ID (default: custom-$(date +%s)):"
read -r id
# Use default ID if none provided
if [ -z "$id" ]; then
id="custom-$(date +%s)"
fi
echo -e "${BLUE}Sending custom message:${NC}"
# Create message in proper single-line format
request=$(ws_create_message "$method" "$params" "$id")
echo "$request" | jq .
echo -e "${BLUE}Response:${NC}"
response=$(ws_request "$request" "$CONN_ID" 5)
echo "$response" | jq .
}
# Function to handle initializing a session
handle_initialize() {
echo -e "${BLUE}Initializing Claude session...${NC}"
# Format init params to single line
INIT_PARAMS=$(ws_format_json '{
"protocolVersion": "2025-03-26",
"capabilities": {
"roots": {
"listChanged": true
},
"sampling": {}
},
"clientInfo": {
"name": "ClaudeCodeNvim",
"version": "0.2.0"
}
}')
response=$(ws_rpc_request "initialize" "$INIT_PARAMS" "init-$(date +%s)" "$CONN_ID")
if echo "$response" | grep -q '"error"'; then
echo -e "${RED}Initialization error:${NC}"
echo "$response" | jq .error
else
echo -e "${GREEN}Session initialized successfully:${NC}"
echo "$response" | jq .
# Send initialized notification
ws_notify "initialized" "{}" "$CONN_ID"
echo -e "${GREEN}Sent initialized notification${NC}"
# Extract protocol version
protocol=$(echo "$response" | jq -r '.result.protocolVersion // "unknown"')
echo -e "${YELLOW}Protocol version:${NC} $protocol"
fi
}
# Function to display connection info
handle_connection_info() {
echo -e "${BLUE}Connection Information:${NC}"
echo -e "${YELLOW}WebSocket URL:${NC} $WS_URL"
echo -e "${YELLOW}Port:${NC} $PORT"
echo -e "${YELLOW}Lock file:${NC} $CLAUDE_LOCKFILE_DIR/$PORT.lock"
if [ -f "$CLAUDE_LOCKFILE_DIR/$PORT.lock" ]; then
echo -e "${YELLOW}Lock file contents:${NC}"
cat "$CLAUDE_LOCKFILE_DIR/$PORT.lock"
fi
# Display WebSocket connection info
if ws_is_connected "$CONN_ID"; then
echo -e "${YELLOW}WebSocket connection status:${NC} ${GREEN}Active${NC}"
else
echo -e "${YELLOW}WebSocket connection status:${NC} ${RED}Inactive${NC}"
fi
}
# Callback function for message listener
process_interactive_message() {
local message="$1"
local count="$2"
echo -e "${GREEN}Message #$count received:${NC}"
echo "$message" | jq .
echo
}
# Function to listen for messages
handle_listen() {
echo -e "${BLUE}Listening for WebSocket messages...${NC}"
echo "Press Ctrl+C to stop listening."
# Start the listener with our callback function
ws_start_listener "$CONN_ID" process_interactive_message
# We'll use a simple loop to keep this function running until Ctrl+C
while true; do
sleep 1
done
# The ws_stop_listener will be called by the trap in the main script
}
# Function to reconnect WebSocket
handle_reconnect() {
echo -e "${BLUE}Reconnecting WebSocket...${NC}"
# Disconnect and reconnect
ws_disconnect "$CONN_ID"
if ws_connect "$WS_URL" "$CONN_ID"; then
echo -e "${GREEN}Reconnection successful.${NC}"
# Send handshake again
HANDSHAKE_PARAMS=$(ws_format_json '{
"protocolVersion": "2024-11-05",
"capabilities": {
"tools": {}
},
"clientInfo": {
"name": "claude-nvim-client",
"version": "0.2.0"
}
}')
ws_notify "mcp.connect" "$HANDSHAKE_PARAMS" "$CONN_ID"
else
echo -e "${RED}Reconnection failed.${NC}"
fi
}
# Main loop
while true; do
show_menu
read -r choice
echo
case $choice in
1) handle_get_selection ;;
2) handle_list_tools ;;
3) handle_open_file ;;
4) handle_custom_message ;;
5) handle_initialize ;;
6) handle_connection_info ;;
7)
# Handle Ctrl+C gracefully for the listen function
trap 'echo -e "\n${YELLOW}Stopped listening.${NC}"; ws_stop_listener "$CONN_ID"; trap - INT; break' INT
handle_listen
trap - INT
;;
8) handle_reconnect ;;
9)
echo "Cleaning up connections and exiting..."
ws_stop_listener "$CONN_ID" 2>/dev/null # Stop any listener if active
ws_disconnect "$CONN_ID"
exit 0
;;
*) echo -e "${RED}Invalid choice. Please try again.${NC}" ;;
esac
echo
echo -n "Press Enter to continue..."
read -r
clear
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE} Claude Code Interactive CLI ${NC}"
echo -e "${BLUE}========================================${NC}"
echo -e "${GREEN}Connected to WebSocket:${NC} $WS_URL"
echo -e "${GREEN}Using connection:${NC} $CONN_ID"
echo
done