telegram-claude-mcp 1.2.3 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,93 @@
1
+ #!/bin/bash
2
+ #
3
+ # Claude Code Interactive Stop Hook
4
+ #
5
+ # When Claude stops, this sends a message to Telegram and waits for your reply.
6
+ # If you reply with instructions, Claude continues working on them.
7
+ # If you reply "done" or don't reply, Claude stops.
8
+ #
9
+
10
+ SESSION_DIR="/tmp/telegram-claude-sessions"
11
+
12
+ # Function to find the most recent active session
13
+ find_active_session() {
14
+ local latest_file=""
15
+ local latest_time=0
16
+
17
+ [ -d "$SESSION_DIR" ] || return
18
+
19
+ for info_file in "$SESSION_DIR"/*.info; do
20
+ [ -e "$info_file" ] || continue
21
+
22
+ local pid
23
+ pid=$(jq -r '.pid // empty' "$info_file" 2>/dev/null)
24
+ if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
25
+ local file_time
26
+ file_time=$(stat -f %m "$info_file" 2>/dev/null || stat -c %Y "$info_file" 2>/dev/null)
27
+ if [ "$file_time" -gt "$latest_time" ]; then
28
+ latest_time=$file_time
29
+ latest_file=$info_file
30
+ fi
31
+ fi
32
+ done
33
+
34
+ echo "$latest_file"
35
+ }
36
+
37
+ # Read hook input
38
+ INPUT=$(cat)
39
+
40
+ # Check if stop_hook_active - if true, we already continued once, don't loop
41
+ STOP_HOOK_ACTIVE=$(echo "$INPUT" | jq -r '.stop_hook_active // false')
42
+ if [ "$STOP_HOOK_ACTIVE" = "true" ]; then
43
+ echo "[stop-hook] Already continued once, allowing stop" >&2
44
+ exit 0
45
+ fi
46
+
47
+ # Find active session
48
+ INFO_FILE=$(find_active_session)
49
+
50
+ if [ -z "$INFO_FILE" ] || [ ! -f "$INFO_FILE" ]; then
51
+ echo "[stop-hook] No active session found" >&2
52
+ exit 0
53
+ fi
54
+
55
+ # Read port from session info
56
+ HOOK_PORT=$(jq -r '.port' "$INFO_FILE")
57
+ HOOK_HOST=$(jq -r '.host // "localhost"' "$INFO_FILE")
58
+ HOOK_URL="http://${HOOK_HOST}:${HOOK_PORT}/stop"
59
+
60
+ echo "[stop-hook] Using session: $INFO_FILE (port $HOOK_PORT)" >&2
61
+
62
+ # Extract transcript path to get context
63
+ TRANSCRIPT_PATH=$(echo "$INPUT" | jq -r '.transcript_path // empty')
64
+
65
+ # Build request payload
66
+ PAYLOAD=$(jq -n \
67
+ --arg transcript_path "$TRANSCRIPT_PATH" \
68
+ '{transcript_path: $transcript_path}')
69
+
70
+ # Send to server and wait for response (blocking - waits for user reply)
71
+ RESPONSE=$(curl -s -X POST "$HOOK_URL" \
72
+ -H "Content-Type: application/json" \
73
+ -d "$PAYLOAD" \
74
+ --max-time 300)
75
+
76
+ if [ $? -ne 0 ]; then
77
+ echo "[stop-hook] Failed to connect to server" >&2
78
+ exit 0
79
+ fi
80
+
81
+ echo "[stop-hook] Response: $RESPONSE" >&2
82
+
83
+ # Check if user wants to continue
84
+ DECISION=$(echo "$RESPONSE" | jq -r '.decision // empty')
85
+ REASON=$(echo "$RESPONSE" | jq -r '.reason // empty')
86
+
87
+ if [ "$DECISION" = "block" ] && [ -n "$REASON" ]; then
88
+ # User provided instructions - continue with them
89
+ echo "$RESPONSE"
90
+ else
91
+ # User said done or no response - allow stop
92
+ exit 0
93
+ fi
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "telegram-claude-mcp",
3
- "version": "1.2.3",
3
+ "version": "1.3.0",
4
4
  "description": "MCP server that lets Claude message you on Telegram with hooks support",
5
5
  "author": "Geravant",
6
6
  "license": "MIT",
package/src/index.ts CHANGED
@@ -153,14 +153,18 @@ async function main() {
153
153
  tool_input || {}
154
154
  );
155
155
 
156
+ const responseDecision: Record<string, unknown> = {
157
+ behavior: decision.behavior,
158
+ };
159
+ if (decision.message) {
160
+ responseDecision.message = decision.message;
161
+ }
162
+
156
163
  res.writeHead(200, { 'Content-Type': 'application/json' });
157
164
  res.end(JSON.stringify({
158
165
  hookSpecificOutput: {
159
166
  hookEventName: 'PermissionRequest',
160
- decision: {
161
- behavior: decision.behavior,
162
- message: decision.message,
163
- },
167
+ decision: responseDecision,
164
168
  },
165
169
  }));
166
170
  return;
@@ -186,6 +190,19 @@ async function main() {
186
190
  return;
187
191
  }
188
192
 
193
+ // Handle interactive stop (waits for user reply)
194
+ if (url === '/stop' || url === '/hooks/stop') {
195
+ const { transcript_path } = data;
196
+
197
+ console.error(`[HTTP] Interactive stop request`);
198
+
199
+ const result = await telegram.handleInteractiveStop(transcript_path);
200
+
201
+ res.writeHead(200, { 'Content-Type': 'application/json' });
202
+ res.end(JSON.stringify(result));
203
+ return;
204
+ }
205
+
189
206
  // Unknown endpoint
190
207
  res.writeHead(404, { 'Content-Type': 'application/json' });
191
208
  res.end(JSON.stringify({ error: 'Not found' }));
package/src/telegram.ts CHANGED
@@ -241,6 +241,74 @@ export class TelegramManager {
241
241
  await this.bot.sendMessage(this.config.chatId, message);
242
242
  }
243
243
 
244
+ /**
245
+ * Handle interactive stop - send message and wait for user to reply with instructions
246
+ * Returns { decision: "block", reason: "..." } if user wants to continue
247
+ * Returns {} if user is done
248
+ */
249
+ async handleInteractiveStop(transcriptPath?: string): Promise<Record<string, unknown>> {
250
+ // Try to get last assistant message from transcript
251
+ let lastMessage = 'Claude has finished working.';
252
+ if (transcriptPath) {
253
+ try {
254
+ const fs = await import('fs');
255
+ if (fs.existsSync(transcriptPath)) {
256
+ const content = fs.readFileSync(transcriptPath, 'utf-8');
257
+ const lines = content.trim().split('\n');
258
+ // Find last assistant message
259
+ for (let i = lines.length - 1; i >= 0; i--) {
260
+ try {
261
+ const entry = JSON.parse(lines[i]);
262
+ if (entry.type === 'assistant' && entry.message?.content) {
263
+ const textContent = entry.message.content.find((c: any) => c.type === 'text');
264
+ if (textContent?.text) {
265
+ lastMessage = textContent.text.slice(0, 500);
266
+ if (textContent.text.length > 500) lastMessage += '...';
267
+ break;
268
+ }
269
+ }
270
+ } catch {
271
+ // Skip invalid JSON lines
272
+ }
273
+ }
274
+ }
275
+ } catch (err) {
276
+ console.error('[Telegram] Error reading transcript:', err);
277
+ }
278
+ }
279
+
280
+ const message = `šŸ [${this.config.sessionName}] Claude stopped\n\n${lastMessage}\n\nšŸ’¬ Reply with instructions to continue, or "done" to finish.`;
281
+
282
+ const sent = await this.bot.sendMessage(this.config.chatId, message);
283
+
284
+ // Update session state
285
+ this.updateSessionState({
286
+ waitingForResponse: true,
287
+ messageIds: [...this.getSessionState().messageIds, sent.message_id],
288
+ });
289
+
290
+ // Wait for response with longer timeout for interactive stop
291
+ try {
292
+ const response = await this.waitForResponse(sent.message_id);
293
+
294
+ // Check if user wants to stop
295
+ const lowerResponse = response.toLowerCase().trim();
296
+ if (lowerResponse === 'done' || lowerResponse === 'stop' || lowerResponse === 'finish' || lowerResponse === 'ok') {
297
+ return {};
298
+ }
299
+
300
+ // User provided instructions - continue
301
+ return {
302
+ decision: 'block',
303
+ reason: response,
304
+ };
305
+ } catch (err) {
306
+ // Timeout or error - allow stop
307
+ console.error('[Telegram] Interactive stop timeout or error:', err);
308
+ return {};
309
+ }
310
+ }
311
+
244
312
  /**
245
313
  * Format tool input for display
246
314
  */