-
-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathmcp-user-interrupt.js
More file actions
228 lines (192 loc) · 8.14 KB
/
mcp-user-interrupt.js
File metadata and controls
228 lines (192 loc) · 8.14 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
#!/usr/bin/env node
// ─── Internal MCP Server: user_interrupt ────────────────────────────────────
// Raw JSON-RPC 2.0 over stdio (newline-delimited). Zero external dependencies.
// Provides a "check_user_messages" tool that retrieves pending clarifications
// sent by the user while Claude is working on a task.
//
// Environment variables (set by server.js at injection time):
// INTERRUPT_SERVER_URL — e.g. http://127.0.0.1:3000
// INTERRUPT_SESSION_ID — local session ID for scoping messages
// INTERRUPT_SECRET — per-process auth secret
const http = require('http');
const { StringDecoder } = require('string_decoder');
const SERVER_URL = process.env.INTERRUPT_SERVER_URL || 'http://127.0.0.1:3000';
const SESSION_ID = process.env.INTERRUPT_SESSION_ID || '';
const SECRET = process.env.INTERRUPT_SECRET || '';
const MAX_STDIN_BUFFER = 10 * 1024 * 1024; // 10 MB
// ─── JSON-RPC helpers ────────────────────────────────────────────────────────
function sendResponse(id, result) {
const msg = JSON.stringify({ jsonrpc: '2.0', id, result });
process.stdout.write(msg + '\n');
}
function sendError(id, code, message) {
const msg = JSON.stringify({ jsonrpc: '2.0', id, error: { code, message } });
process.stdout.write(msg + '\n');
}
// ─── Tool definition ─────────────────────────────────────────────────────────
const CHECK_USER_MESSAGES_TOOL = {
name: 'check_user_messages',
description: 'Check if the user sent any clarifications or corrections while you are working. Returns pending messages or empty if none. Call this between major steps to stay aligned with user intent.',
inputSchema: {
type: 'object',
properties: {},
},
};
// ─── HTTP POST to Express server ─────────────────────────────────────────────
function postToServer(body) {
return new Promise((resolve, reject) => {
const data = JSON.stringify(body);
const parsed = new URL(SERVER_URL);
const options = {
hostname: parsed.hostname,
port: parsed.port || 80,
path: '/api/internal/user-interrupt',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(data),
'Authorization': `Bearer ${SECRET}`,
},
timeout: 5000,
};
const req = http.request(options, (res) => {
let responseBody = '';
res.on('data', (chunk) => { responseBody += chunk; });
res.on('end', () => {
try { resolve(JSON.parse(responseBody)); }
catch { resolve({ messages: [] }); }
});
});
req.on('error', (err) => reject(new Error(`HTTP request failed: ${err.message}`)));
req.on('timeout', () => { req.destroy(); resolve({ messages: [] }); });
req.write(data);
req.end();
});
}
// ─── Handle JSON-RPC messages ────────────────────────────────────────────────
let _initialized = false;
async function handleMessage(msg) {
const { id, method, params } = msg;
// Notifications (no id) — acknowledge silently
if (id === undefined || id === null) return;
switch (method) {
case 'initialize':
_initialized = true;
sendResponse(id, {
protocolVersion: '2024-11-05',
capabilities: { tools: {} },
serverInfo: { name: '_ccs_user_interrupt', version: '1.0.0' },
});
break;
case 'tools/list':
if (!_initialized) { sendError(id, -32002, 'Server not initialized'); return; }
sendResponse(id, { tools: [CHECK_USER_MESSAGES_TOOL] });
break;
case 'tools/call': {
if (!_initialized) { sendError(id, -32002, 'Server not initialized'); return; }
const toolName = params?.name;
if (toolName !== 'check_user_messages') {
sendError(id, -32602, `Unknown tool: ${toolName}`);
return;
}
try {
const result = await postToServer({ sessionId: SESSION_ID });
const messages = result.messages || [];
if (messages.length === 0) {
sendResponse(id, {
content: [{ type: 'text', text: 'No pending user messages.' }],
});
break;
}
// Build multimodal content blocks: text + images + file references
const contentBlocks = [];
// Text summary of all clarifications
const lines = messages.map((m, i) =>
messages.length === 1
? `User clarification: ${m.content}`
: `${i + 1}. ${m.content}`
);
let text = messages.length === 1
? lines[0]
: `User sent ${messages.length} clarification(s) while you were working:\n\n${lines.join('\n')}`;
// Collect attachment descriptions for the text summary
const attachDescriptions = [];
for (const m of messages) {
if (!Array.isArray(m.attachments) || m.attachments.length === 0) continue;
for (const att of m.attachments) {
if (att.type === 'ssh') {
let sshText = `[SSH Host: ${att.label || att.host || 'SSH'}]\nHost: ${att.host}:${att.port || 22}`;
if (att.sshKeyPath) sshText += `\nSSH Key: ${att.sshKeyPath}`;
else if (att.password) sshText += `\nPassword: ${att.password}`;
attachDescriptions.push(sshText);
} else if (att.base64 && att.mimeType && att.mimeType.startsWith('image/')) {
// Image with base64 — MCP ImageContent format (flat data + mimeType)
contentBlocks.push({
type: 'image',
data: att.base64,
mimeType: att.mimeType,
});
attachDescriptions.push(`[Attached image: ${att.name || 'screenshot'}]`);
} else if (att.path) {
// File saved to disk — tell Claude to read it
attachDescriptions.push(`[Attached file: ${att.name || 'file'}]\nSaved at: ${att.path}\nRead this file to see its contents.`);
}
}
}
if (attachDescriptions.length) {
text += '\n\nAttachments:\n' + attachDescriptions.join('\n\n');
}
text += '\n\nAcknowledge these and adjust your approach if needed.';
// Text block goes first (before images) so Claude sees the context
contentBlocks.unshift({ type: 'text', text });
sendResponse(id, { content: contentBlocks });
} catch (err) {
sendResponse(id, {
content: [{ type: 'text', text: 'No pending user messages.' }],
});
}
break;
}
default:
if (id !== undefined && id !== null) {
sendError(id, -32601, `Method not found: ${method}`);
}
}
}
// ─── Stdin line reader ───────────────────────────────────────────────────────
const decoder = new StringDecoder('utf8');
let buffer = '';
process.stdin.on('data', (chunk) => {
buffer += decoder.write(chunk);
if (buffer.length > MAX_STDIN_BUFFER) {
process.stderr.write('[mcp] stdin buffer overflow, resetting\n');
buffer = '';
return;
}
const lines = buffer.split(/\r?\n/);
buffer = lines.pop() || '';
for (const line of lines) {
if (!line.trim()) continue;
try {
const msg = JSON.parse(line);
handleMessage(msg).catch((err) => {
process.stderr.write(`user_interrupt MCP error: ${err.message}\n`);
});
} catch {
// Ignore unparseable lines
}
}
});
process.stdin.on('end', () => {
const remaining = buffer + decoder.end();
if (remaining.trim()) {
try {
const msg = JSON.parse(remaining);
handleMessage(msg).catch(() => {});
} catch {}
}
process.exit(0);
});
// Handle SIGTERM/SIGINT gracefully
process.on('SIGTERM', () => process.exit(0));
process.on('SIGINT', () => process.exit(0));