-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathimp-mcp.mts
More file actions
482 lines (428 loc) · 12 KB
/
imp-mcp.mts
File metadata and controls
482 lines (428 loc) · 12 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
#!/usr/bin/env node
/**
* MCP Server for Implish
* Allows Claude Code to evaluate implish code directly via MCP protocol
*
* Setup (dev-only):
* 1. npm install && npm run build
* 2. Add to Claude Code MCP settings:
* {
* "mcpServers": {
* "implish": {
* "command": "node",
* "args": ["C:\\ver\\implish\\dist\\imp-mcp.mjs"]
* }
* }
* }
* To do this from the command line, run:
*
* claude mcp add implish -- node `realpath ./dist/imp-mcp.mjs`
*
* 3. Restart Claude Code
*/
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { spawn, type ChildProcess } from 'child_process';
import { watch } from 'fs';
// Get the directory of the current module
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
interface WorkerRequest {
operation: 'eval' | 'load' | 'list_words' | 'inspect_word' | 'reload';
code?: string;
word?: string;
}
interface WorkerResponse {
success: boolean;
result?: string;
error?: string;
}
// Global worker process
let workerProcess: ChildProcess | null = null;
let workerReady = false;
let pendingRequests = new Map<number, { resolve: (value: WorkerResponse) => void, reject: (reason: any) => void }>();
let requestIdCounter = 0;
// Start a long-running worker process
function startWorker(): void {
if (workerProcess) {
workerProcess.kill();
}
const workerPath = join(__dirname, 'imp-mcp-worker.mjs');
workerProcess = spawn('node', [workerPath], {
stdio: ['pipe', 'pipe', 'pipe'],
});
workerReady = false;
let outputBuffer = '';
workerProcess.stdout?.on('data', (data) => {
outputBuffer += data.toString();
// Process complete JSON responses
const lines = outputBuffer.split('\n');
outputBuffer = lines.pop() || ''; // Keep incomplete line in buffer
for (const line of lines) {
if (!line.trim()) continue;
try {
const response = JSON.parse(line);
// Check if this is a ready signal
if (response.ready) {
workerReady = true;
console.error('Worker ready');
continue;
}
// Handle request responses
const requestId = response.id;
if (requestId !== undefined && pendingRequests.has(requestId)) {
const { resolve } = pendingRequests.get(requestId)!;
pendingRequests.delete(requestId);
resolve(response);
}
} catch (error) {
console.error('Failed to parse worker output:', line, error);
}
}
});
workerProcess.stderr?.on('data', (data) => {
console.error('Worker stderr:', data.toString());
});
workerProcess.on('error', (error) => {
console.error('Worker error:', error);
workerReady = false;
});
workerProcess.on('exit', (code) => {
console.error(`Worker exited with code ${code}`);
workerReady = false;
workerProcess = null;
// Reject all pending requests
for (const [id, { reject }] of pendingRequests.entries()) {
reject(new Error('Worker process exited'));
}
pendingRequests.clear();
});
}
// Send request to worker and wait for response
async function sendToWorker(request: WorkerRequest, timeoutMs: number = 5000): Promise<WorkerResponse> {
if (!workerProcess || !workerReady) {
startWorker();
// Wait for worker to be ready
const maxWait = 10000;
const start = Date.now();
while (!workerReady && (Date.now() - start) < maxWait) {
await new Promise(resolve => setTimeout(resolve, 100));
}
if (!workerReady) {
throw new Error('Worker failed to start');
}
}
return new Promise((resolve, reject) => {
const requestId = requestIdCounter++;
const requestWithId = { ...request, id: requestId };
// Set timeout
const timeout = setTimeout(() => {
if (pendingRequests.has(requestId)) {
pendingRequests.delete(requestId);
reject(new Error(`Request timed out after ${timeoutMs}ms (possible infinite loop)`));
}
}, timeoutMs);
// Store resolver
pendingRequests.set(requestId, {
resolve: (response) => {
clearTimeout(timeout);
resolve(response);
},
reject: (error) => {
clearTimeout(timeout);
reject(error);
}
});
// Send request
try {
workerProcess!.stdin!.write(JSON.stringify(requestWithId) + '\n');
} catch (error) {
pendingRequests.delete(requestId);
clearTimeout(timeout);
reject(error);
}
});
}
// Watch for file changes and reload worker
function watchFiles(): void {
const filesToWatch = [
'imp-core.mjs',
'imp-load.mjs',
'imp-eval.mjs',
'imp-show.mjs',
'imp-mcp-worker.mjs',
].map(f => join(__dirname, f));
for (const file of filesToWatch) {
watch(file, (eventType) => {
if (eventType === 'change') {
console.error(`File changed: ${file}, reloading worker...`);
if (workerReady) {
sendToWorker({ operation: 'reload' }).catch(() => {
// If reload fails, restart the worker
startWorker();
});
}
}
});
}
}
// Create server instance
const server = new Server(
{
name: "implish-mcp-server",
version: "0.1.0",
},
{
capabilities: {
tools: {},
},
}
);
// List available tools
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: "eval_implish",
description: "Evaluate implish code and return the result. Handles multi-line code, expressions, and assignments. Returns the value of the last expression or NIL if there's no result to display.",
inputSchema: {
type: "object",
properties: {
code: {
type: "string",
description: "The implish code to evaluate",
},
},
required: ["code"],
},
},
{
name: "load_implish",
description: "Parse implish code into its token tree representation without evaluating it. Useful for debugging parser behavior.",
inputSchema: {
type: "object",
properties: {
code: {
type: "string",
description: "The implish code to parse",
},
},
required: ["code"],
},
},
{
name: "list_words",
description: "List all currently defined words (functions and variables) in the implish environment",
inputSchema: {
type: "object",
properties: {},
},
},
{
name: "inspect_word",
description: "Show the definition/value of a specific word in the implish environment",
inputSchema: {
type: "object",
properties: {
word: {
type: "string",
description: "The word name to inspect",
},
},
required: ["word"],
},
},
{
name: "reset_implish",
description: "Reset the implish environment by restarting the worker process. This clears all user-defined variables and functions, restoring the environment to its initial state.",
inputSchema: {
type: "object",
properties: {},
},
},
],
};
});
// Handle tool calls
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
try {
switch (name) {
case "eval_implish": {
if (!args) {
throw new Error("arguments are required");
}
const code = args.code as string;
if (!code) {
throw new Error("code parameter is required");
}
// Send to long-running worker
const response = await sendToWorker({ operation: 'eval', code });
if (!response.success) {
return {
content: [
{
type: "text",
text: `Error: ${response.error}`,
},
],
isError: true,
};
}
return {
content: [
{
type: "text",
text: response.result || "",
},
],
};
}
case "load_implish": {
if (!args) {
throw new Error("arguments are required");
}
const code = args.code as string;
if (!code) {
throw new Error("code parameter is required");
}
// Send to long-running worker
const response = await sendToWorker({ operation: 'load', code });
if (!response.success) {
return {
content: [
{
type: "text",
text: `Error: ${response.error}`,
},
],
isError: true,
};
}
return {
content: [
{
type: "text",
text: response.result || "",
},
],
};
}
case "list_words": {
// Send to long-running worker
const response = await sendToWorker({ operation: 'list_words' });
if (!response.success) {
return {
content: [
{
type: "text",
text: `Error: ${response.error}`,
},
],
isError: true,
};
}
return {
content: [
{
type: "text",
text: response.result || "",
},
],
};
}
case "inspect_word": {
if (!args) {
throw new Error("arguments are required");
}
const word = args.word as string;
if (!word) {
throw new Error("word parameter is required");
}
// Send to long-running worker
const response = await sendToWorker({ operation: 'inspect_word', word });
if (!response.success) {
return {
content: [
{
type: "text",
text: `Error: ${response.error}`,
},
],
isError: true,
};
}
return {
content: [
{
type: "text",
text: response.result || "",
},
],
};
}
case "reset_implish": {
// Restart the worker process to clear all state
startWorker();
// Wait for worker to be ready
const maxWait = 10000;
const start = Date.now();
while (!workerReady && (Date.now() - start) < maxWait) {
await new Promise(resolve => setTimeout(resolve, 100));
}
if (!workerReady) {
return {
content: [
{
type: "text",
text: "Error: Worker failed to restart",
},
],
isError: true,
};
}
return {
content: [
{
type: "text",
text: "Implish environment reset successfully",
},
],
};
}
default:
throw new Error(`Unknown tool: ${name}`);
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
return {
content: [
{
type: "text",
text: `Error: ${errorMessage}`,
},
],
isError: true,
};
}
});
// Start the server
async function main() {
// Start worker process
startWorker();
// Watch for file changes
watchFiles();
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("Implish MCP server running on stdio");
}
main().catch((error) => {
console.error("Fatal error in main():", error);
process.exit(1);
});