File size: 16,296 Bytes
16a4dbd
c3ae75f
16a4dbd
 
 
 
 
 
 
 
 
66097e1
e9d7b34
16a4dbd
 
 
 
 
e9d7b34
c3ae75f
 
822cbdd
16a4dbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c3ae75f
 
707bbb4
 
 
c3ae75f
a5cf716
c3ae75f
a5cf716
c3ae75f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16a4dbd
c3ae75f
16a4dbd
c3ae75f
 
 
 
 
 
 
 
 
 
 
 
 
16a4dbd
 
c3ae75f
16a4dbd
c3ae75f
16a4dbd
c3ae75f
 
 
 
 
16a4dbd
 
c3ae75f
16a4dbd
 
 
e9d7b34
c3ae75f
16a4dbd
 
 
c3ae75f
16a4dbd
c3ae75f
 
 
 
 
16a4dbd
e9d7b34
16a4dbd
c3ae75f
e9d7b34
c3ae75f
 
e9d7b34
 
c3ae75f
e9d7b34
 
 
c3ae75f
aea1786
c3ae75f
aea1786
 
 
c3ae75f
e9d7b34
d686137
e9d7b34
 
aea1786
 
 
 
e9d7b34
 
75d362b
 
c3ae75f
75d362b
 
d686137
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16a4dbd
 
 
 
 
 
 
 
c3ae75f
 
 
 
 
 
e9d7b34
 
d686137
 
16a4dbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d686137
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94c2cc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d686137
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c3ae75f
e9d7b34
c3ae75f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9faf78d
 
 
 
 
 
 
c3ae75f
e9d7b34
 
 
 
9faf78d
e9d7b34
 
 
c3ae75f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9d7b34
16a4dbd
c3ae75f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9d7b34
 
 
 
c3ae75f
e9d7b34
 
 
c3ae75f
 
 
 
e9d7b34
c3ae75f
 
 
 
 
 
16a4dbd
c3ae75f
 
 
e9d7b34
c3ae75f
 
 
 
 
e9d7b34
c3ae75f
 
 
 
 
33d698c
c3ae75f
 
 
 
 
 
 
 
 
 
 
33d698c
c3ae75f
33d698c
c3ae75f
 
 
 
 
 
 
 
e9d7b34
 
33d698c
c3ae75f
33d698c
 
 
 
e9d7b34
 
c3ae75f
 
 
e9d7b34
c3ae75f
 
 
 
 
 
 
e9d7b34
 
33d698c
e9d7b34
c3ae75f
e9d7b34
c3ae75f
e9d7b34
33d698c
75d362b
e9d7b34
 
 
 
c3ae75f
e9d7b34
 
 
c3ae75f
e9d7b34
 
75d362b
e9d7b34
75d362b
e9d7b34
c3ae75f
9faf78d
75d362b
e9d7b34
 
 
 
9faf78d
e9d7b34
 
 
 
 
c3ae75f
e9d7b34
 
 
75d362b
c3ae75f
75d362b
 
 
 
16a4dbd
 
 
c3ae75f
16a4dbd
 
 
 
 
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
#!/usr/bin/env node
// mcp-server.js - MCP Server for Reuben OS with Passkey System

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 fetch from 'node-fetch';

const BASE_URL = process.env.REUBENOS_URL || 'https://mcp-1st-birthday-reuben-os.hf.space';
const API_ENDPOINT = `${BASE_URL}/api/mcp-handler`;

class ReubenOSMCPServer {
  constructor() {
    this.server = new Server(
      {
        name: 'reubenos-mcp-server',
        version: '3.0.0',
        description: 'MCP Server for Reuben OS with secure passkey-based file storage',
        icon: 'πŸ–₯️',
      },
      {
        capabilities: {
          tools: {},
        },
      }
    );

    this.setupToolHandlers();

    // Error handling
    this.server.onerror = (error) => console.error('[MCP Error]', error);
    process.on('SIGINT', async () => {
      await this.server.close();
      process.exit(0);
    });
  }

  setupToolHandlers() {
    this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
      tools: [
        {
          name: 'save_file',
          description: 'Save a file to Reuben OS. Use your passkey for secure storage or save to public folder.',
          inputSchema: {
            type: 'object',
            properties: {
              fileName: {
                type: 'string',
                description: 'File name (e.g., main.dart, document.tex, report.pdf, quiz.json)',
              },
              content: {
                type: 'string',
                description: 'File content to save',
              },
              passkey: {
                type: 'string',
                description: 'Your passkey for secure storage (min 4 characters). Leave empty to save to public folder.',
              },
              isPublic: {
                type: 'boolean',
                description: 'Set to true to save to public folder (accessible to everyone). Default: false',
              },
            },
            required: ['fileName', 'content'],
          },
        },
        {
          name: 'list_files',
          description: 'List all files in your secure storage or public folder',
          inputSchema: {
            type: 'object',
            properties: {
              passkey: {
                type: 'string',
                description: 'Your passkey to list secure files. Leave empty to list public files.',
              },
              isPublic: {
                type: 'boolean',
                description: 'Set to true to list public files. Default: false',
              },
            },
          },
        },
        {
          name: 'delete_file',
          description: 'Delete a specific file from your storage',
          inputSchema: {
            type: 'object',
            properties: {
              fileName: {
                type: 'string',
                description: 'Name of the file to delete',
              },
              passkey: {
                type: 'string',
                description: 'Your passkey (required for secure files)',
              },
              isPublic: {
                type: 'boolean',
                description: 'Set to true if deleting from public folder. Default: false',
              },
            },
            required: ['fileName'],
          },
        },
        {
          name: 'deploy_quiz',
          description: 'Deploy an interactive quiz to Reuben OS Quiz App',
          inputSchema: {
            type: 'object',
            properties: {
              passkey: {
                type: 'string',
                description: 'Your passkey for secure quiz storage',
              },
              isPublic: {
                type: 'boolean',
                description: 'Make quiz public (default: false)',
              },
              quizData: {
                type: 'object',
                description: 'Quiz configuration',
                properties: {
                  title: { type: 'string', description: 'Quiz title' },
                  description: { type: 'string', description: 'Quiz description' },
                  questions: {
                    type: 'array',
                    description: 'Array of questions',
                    items: {
                      type: 'object',
                      properties: {
                        id: { type: 'string' },
                        type: { type: 'string', enum: ['multiple_choice'] },
                        question: { type: 'string' },
                        options: { type: 'array', items: { type: 'string' } },
                        correctAnswer: { type: 'string' },
                        explanation: { type: 'string' },
                        points: { type: 'number' },
                      },
                      required: ['id', 'question', 'type'],
                    },
                  },
                  timeLimit: {
                    type: 'number',
                    description: 'Time limit in minutes for the quiz (optional)',
                  },
                },
                required: ['title', 'questions'],
              },
            },
            required: ['quizData'],
          },
        },
        {
          name: 'read_file',
          description: 'Read the content of a file from secure storage or public folder. Useful for evaluating quiz answers.',
          inputSchema: {
            type: 'object',
            properties: {
              fileName: {
                type: 'string',
                description: 'Name of the file to read (e.g., quiz_answers.json)',
              },
              passkey: {
                type: 'string',
                description: 'Your passkey (required for secure files)',
              },
              isPublic: {
                type: 'boolean',
                description: 'Set to true if reading from public folder. Default: false',
              },
            },
            required: ['fileName'],
          },
        },
      ],
    }));

    this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
      const { name, arguments: args } = request.params;

      try {
        switch (name) {
          case 'save_file':
            return await this.saveFile(args);
          case 'list_files':
            return await this.listFiles(args);
          case 'delete_file':
            return await this.deleteFile(args);
          case 'deploy_quiz':
            return await this.deployQuiz(args);
          case 'read_file':
            return await this.readFile(args);
          default:
            throw new Error(`Unknown tool: ${name}`);
        }
      } catch (error) {
        return {
          content: [
            {
              type: 'text',
              text: `Error: ${error.message}`,
            },
          ],
        };
      }
    });
  }

  async readFile(args) {
    try {
      const { fileName, passkey, isPublic = false } = args;

      if (!fileName) {
        return {
          content: [{ type: 'text', text: '❌ fileName is required' }],
        };
      }

      if (!isPublic && !passkey) {
        return {
          content: [{ type: 'text', text: '❌ Passkey is required (or set isPublic=true)' }],
        };
      }

      const ext = fileName.split('.').pop().toLowerCase();
      const isDocument = ['pdf', 'docx', 'xlsx', 'xls', 'pptx'].includes(ext);

      if (isDocument) {
        // Use document processing endpoint
        const processUrl = `${BASE_URL}/api/documents/process`;
        const response = await fetch(processUrl, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            fileName,
            key: passkey,
            isPublic,
            operation: 'read'
          })
        });

        const data = await response.json();

        if (response.ok && data.success) {
          let textContent = '';
          if (data.content.text) {
            textContent = data.content.text;
          } else if (data.content.sheets) {
            textContent = JSON.stringify(data.content.sheets, null, 2);
          } else {
            textContent = JSON.stringify(data.content, null, 2);
          }

          return {
            content: [
              {
                type: 'text',
                text: `πŸ“„ Content of ${fileName} (${data.content.type}):\n\n${textContent}`,
              },
            ],
          };
        } else {
          return {
            content: [{ type: 'text', text: `❌ Failed to process document: ${data.error || 'Unknown error'}` }],
          };
        }
      }

      const url = new URL(API_ENDPOINT);
      if (passkey) url.searchParams.set('passkey', passkey);
      if (isPublic) url.searchParams.set('isPublic', 'true');

      const response = await fetch(url, {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' },
      });

      const data = await response.json();

      if (response.ok && data.success) {
        const file = data.files.find(f => f.name === fileName);

        if (!file) {
          return {
            content: [{ type: 'text', text: `❌ File '${fileName}' not found in ${data.location}` }],
          };
        }

        return {
          content: [
            {
              type: 'text',
              text: `πŸ“„ Content of ${fileName}:\n\n${file.content || '(Empty file)'}`,
            },
          ],
        };
      } else {
        return {
          content: [{ type: 'text', text: `❌ Failed: ${data.error || 'Unknown error'}` }],
        };
      }
    } catch (error) {
      return {
        content: [{ type: 'text', text: `❌ Error: ${error.message}` }],
      };
    }
  }

  async saveFile(args) {
    try {
      const { fileName, content, passkey, isPublic = false } = args;

      if (!fileName || content === undefined) {
        return {
          content: [{ type: 'text', text: '❌ fileName and content are required' }],
        };
      }

      if (!isPublic && !passkey) {
        return {
          content: [{ type: 'text', text: '❌ Passkey is required for secure storage (or set isPublic=true)' }],
        };
      }

      const response = await fetch(API_ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          passkey,
          action: 'save_file',
          fileName,
          content,
          isPublic,
        }),
      });

      const data = await response.json();

      if (response.ok && data.success) {
        const location = isPublic ? 'Public Folder' : `Secure Data (passkey: ${passkey})`;
        
        // Check if PDF was generated for .tex files
        let pdfNote = '';
        if (fileName.endsWith('.tex') && data.pdfGenerated) {
          pdfNote = `\nπŸ“„ PDF generated: ${data.pdfFileName}`;
        }

        return {
          content: [
            {
              type: 'text',
              text: `βœ… File saved: ${fileName}\nπŸ“ Saved to: ${location}${pdfNote}`,
            },
          ],
        };
      } else {
        return {
          content: [{ type: 'text', text: `❌ Failed to save: ${data.error || 'Unknown error'}` }],
        };
      }
    } catch (error) {
      return {
        content: [{ type: 'text', text: `❌ Error: ${error.message}` }],
      };
    }
  }

  async listFiles(args) {
    try {
      const { passkey, isPublic = false } = args;

      if (!isPublic && !passkey) {
        return {
          content: [{ type: 'text', text: '❌ Passkey is required (or set isPublic=true)' }],
        };
      }

      const url = new URL(API_ENDPOINT);
      if (passkey) url.searchParams.set('passkey', passkey);
      if (isPublic) url.searchParams.set('isPublic', 'true');

      const response = await fetch(url, {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' },
      });

      const data = await response.json();

      if (response.ok && data.success) {
        if (data.files.length === 0) {
          return {
            content: [{ type: 'text', text: `πŸ“ No files found in ${data.location}` }],
          };
        }

        const fileList = data.files
          .map(f => `πŸ“„ ${f.name} (${(f.size / 1024).toFixed(2)} KB)${f.isQuiz ? ' [QUIZ]' : ''}`)
          .join('\n');

        return {
          content: [
            {
              type: 'text',
              text: `πŸ“ Files in ${data.location}:\n\n${fileList}\n\nTotal: ${data.count} file(s)`,
            },
          ],
        };
      } else {
        return {
          content: [{ type: 'text', text: `❌ Failed: ${data.error || 'Unknown error'}` }],
        };
      }
    } catch (error) {
      return {
        content: [{ type: 'text', text: `❌ Error: ${error.message}` }],
      };
    }
  }

  async deleteFile(args) {
    try {
      const { fileName, passkey, isPublic = false } = args;

      if (!fileName) {
        return {
          content: [{ type: 'text', text: '❌ fileName is required' }],
        };
      }

      if (!isPublic && !passkey) {
        return {
          content: [{ type: 'text', text: '❌ Passkey is required (or set isPublic=true)' }],
        };
      }

      const response = await fetch(API_ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          passkey,
          action: 'delete_file',
          fileName,
          isPublic,
          content: '', // Required by API but not used
        }),
      });

      const data = await response.json();

      if (response.ok && data.success) {
        return {
          content: [{ type: 'text', text: `βœ… File '${fileName}' deleted successfully` }],
        };
      } else {
        return {
          content: [{ type: 'text', text: `❌ Failed: ${data.error || 'File not found'}` }],
        };
      }
    } catch (error) {
      return {
        content: [{ type: 'text', text: `❌ Error: ${error.message}` }],
      };
    }
  }

  async deployQuiz(args) {
    try {
      const { quizData, passkey, isPublic = false } = args;

      if (!quizData || !quizData.questions || quizData.questions.length === 0) {
        return {
          content: [{ type: 'text', text: '❌ Quiz must have at least one question' }],
        };
      }

      if (!isPublic && !passkey) {
        return {
          content: [{ type: 'text', text: '❌ Passkey is required (or set isPublic=true)' }],
        };
      }

      const fullQuizData = {
        ...quizData,
        createdAt: new Date().toISOString(),
        passkey: passkey || 'public',
        version: '1.0',
      };

      const response = await fetch(API_ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          passkey,
          action: 'deploy_quiz',
          fileName: 'quiz.json',
          content: JSON.stringify(fullQuizData, null, 2),
          isPublic,
        }),
      });

      const data = await response.json();

      if (response.ok && data.success) {
        const totalPoints = quizData.questions.reduce((sum, q) => sum + (q.points || 1), 0);
        const location = isPublic ? 'Public Folder' : `Secure Data (passkey: ${passkey})`;

        return {
          content: [
            {
              type: 'text',
              text: `βœ… Quiz deployed: ${quizData.title}\nπŸ“Š ${quizData.questions.length} questions, ${totalPoints} points\nπŸ“ Saved to: ${location}`,
            },
          ],
        };
      } else {
        return {
          content: [{ type: 'text', text: `❌ Failed: ${data.error || 'Unknown error'}` }],
        };
      }
    } catch (error) {
      return {
        content: [{ type: 'text', text: `❌ Error: ${error.message}` }],
      };
    }
  }

  async run() {
    const transport = new StdioServerTransport();
    await this.server.connect(transport);
    console.error('ReubenOS MCP Server running with passkey authentication...');
  }
}

const server = new ReubenOSMCPServer();
server.run();