-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmcp-server.ts
More file actions
1402 lines (1221 loc) · 42.1 KB
/
mcp-server.ts
File metadata and controls
1402 lines (1221 loc) · 42.1 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
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
/**
* Code Mode Unified - MCP Server
*
* Exposes code execution capabilities via Model Context Protocol
* Can be used with Claude Code and other MCP clients
*/
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import {
CallToolRequestSchema,
ListToolsRequestSchema,
ListResourcesRequestSchema,
ReadResourceRequestSchema,
ListPromptsRequestSchema,
GetPromptRequestSchema,
type Tool
} from '@modelcontextprotocol/sdk/types.js';
import { RuntimeFactory, RuntimeType } from './runtime/base-runtime.js';
import type { BaseRuntime } from './runtime/base-runtime.js';
import type { ExecutionResult, ExecutionOptions } from './types/core.js';
import { MCPManager } from './mcp/index.js';
import type { MCPConfig } from './types/core.js';
import { readFileSync } from 'fs';
import { homedir } from 'os';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
// Server metadata
const SERVER_NAME = 'codemode-unified';
const SERVER_VERSION = '0.1.0';
// Configuration from environment
const TYPE_EXPOSURE_MODE = process.env.CODEMODE_TYPE_EXPOSURE || 'on-demand'; // 'on-demand' | 'auto-include'
// Runtime cache to avoid re-initialization
const runtimeCache = new Map<RuntimeType, BaseRuntime>();
// MCP Manager for accessing other MCP tools
let mcpManager: MCPManager | null = null;
/**
* Response helper methods exposed to agents for custom parsing
*/
interface MCPResponseHelpers {
parseAsStructured(): any;
parseAsArray(): any[];
parseAsKeyValue(): Record<string, any>;
getRawText(): string;
}
/**
* Enhanced MCP tool response with raw content + convenience fields + helpers
*/
interface EnhancedMCPResponse {
content: any[]; // Raw MCP content array (spec-compliant)
text: string; // Combined text from all text content
parsed: any | null; // Auto-parsed structure (or null if unparseable)
helpers: MCPResponseHelpers; // Utility methods for custom parsing
isError?: boolean;
}
/**
* Create helper methods bound to a specific text response
*/
function createResponseHelpers(text: string): MCPResponseHelpers {
return {
parseAsStructured(): any {
// Extract key-value pairs from formatted text
const result: any = {};
const lines = text.split('\n').map(l => l.trim()).filter(l => l);
for (const line of lines) {
const match = line.match(/^([A-Z][A-Za-z\s]+?):\s*(.+)$/);
if (match) {
const [, key, value] = match;
const normalizedKey = key.toLowerCase().replace(/\s+/g, '_');
result[normalizedKey] = value;
}
}
return Object.keys(result).length > 0 ? result : null;
},
parseAsArray(): any[] {
// Extract numbered list items with multi-line metadata
// Format: "1. Content...\n Key: Value\n Key2: Value2"
const lines = text.split('\n');
const items: any[] = [];
let currentItem: any = null;
for (const line of lines) {
// Check for numbered list item start
const match = line.match(/^(\d+)\.\s+(.+)$/);
if (match) {
// Save previous item if exists
if (currentItem) {
items.push(currentItem);
}
// Start new item
const [, index, content] = match;
currentItem = {
index: parseInt(index),
content: content.trim()
};
} else if (currentItem && line.trim()) {
// Check for metadata fields (indented key-value pairs)
const metaMatch = line.match(/^\s+([A-Za-z\s]+):\s*(.+)$/);
if (metaMatch) {
const [, key, value] = metaMatch;
const normalizedKey = key.toLowerCase().replace(/\s+/g, '_');
currentItem[normalizedKey] = value.trim();
}
}
}
// Add last item
if (currentItem) {
items.push(currentItem);
}
return items.length > 0 ? items : [];
},
parseAsKeyValue(): Record<string, any> {
// Simple key:value extraction
const result: Record<string, any> = {};
const lines = text.split('\n').map(l => l.trim()).filter(l => l);
for (const line of lines) {
const colonIndex = line.indexOf(':');
if (colonIndex > 0) {
const key = line.substring(0, colonIndex).trim();
const value = line.substring(colonIndex + 1).trim();
result[key] = value;
}
}
return result;
},
getRawText(): string {
return text;
}
};
}
/**
* Auto-parse text content intelligently
* Returns parsed structure if detected, null otherwise
*/
function autoParseContent(text: string): any | null {
// 1. Try JSON parsing first
try {
return JSON.parse(text);
} catch {
// Not JSON, continue
}
// 2. Check for key-value structure
const kvResult: any = {};
const lines = text.split('\n').map(l => l.trim()).filter(l => l);
let foundStructure = false;
for (const line of lines) {
const match = line.match(/^([A-Z][A-Za-z\s]+?):\s*(.+)$/);
if (match) {
const [, key, value] = match;
const normalizedKey = key.toLowerCase().replace(/\s+/g, '_');
kvResult[normalizedKey] = value;
foundStructure = true;
}
}
if (foundStructure) {
return kvResult;
}
// 3. Check for array structure (numbered lists with possible metadata)
const arrayMatch = text.match(/^\d+\.\s+/m);
if (arrayMatch) {
const textLines = text.split('\n');
const items: any[] = [];
let currentItem: any = null;
for (const line of textLines) {
const itemMatch = line.match(/^(\d+)\.\s+(.+)$/);
if (itemMatch) {
// Save previous item
if (currentItem) {
items.push(currentItem);
}
// Start new item
currentItem = {
index: parseInt(itemMatch[1]),
content: itemMatch[2].trim()
};
} else if (currentItem && line.trim()) {
// Check for indented metadata
const metaMatch = line.match(/^\s+([A-Za-z\s]+):\s*(.+)$/);
if (metaMatch) {
const normalizedKey = metaMatch[1].toLowerCase().replace(/\s+/g, '_');
currentItem[normalizedKey] = metaMatch[2].trim();
}
}
}
// Add last item
if (currentItem) {
items.push(currentItem);
}
if (items.length > 0) {
return items;
}
}
// No structure detected
return null;
}
/**
* Load MCP configuration from environment variable or service directory
* NOT greedy - only checks explicit path or own service directory
*/
function loadMCPConfig(): MCPConfig | null {
try {
// First priority: explicitly provided path
const configPath = process.env.MCP_CONFIG_PATH;
if (configPath) {
const content = readFileSync(configPath, 'utf-8');
const config = JSON.parse(content);
console.log(`✅ Loaded MCP config from: ${configPath}`);
return convertMCPJsonToConfig(config);
}
// Second priority: service's own directory (NOT parent/home directories)
// This allows codemode to have its own .mcp.json without loading the one that spawned it
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const serviceDir = join(__dirname, '..');
const serviceMcpPath = join(serviceDir, '.mcp.json');
try {
const content = readFileSync(serviceMcpPath, 'utf-8');
const config = JSON.parse(content);
console.log(`✅ Loaded MCP config from service directory: ${serviceMcpPath}`);
return convertMCPJsonToConfig(config);
} catch {
// Service directory config not found - run in standalone mode
}
// No config found - run in standalone mode (code execution only)
console.log('ℹ️ No MCP config found - running in standalone mode (code execution only)');
return null;
} catch (error) {
console.error('❌ Failed to load MCP config:', error);
return null;
}
}
/**
* Convert .mcp.json format to MCPConfig format
*/
function convertMCPJsonToConfig(json: any): MCPConfig {
const servers: Record<string, any> = {};
if (json.mcpServers) {
for (const [name, config] of Object.entries(json.mcpServers as Record<string, any>)) {
// Skip the codemode server (that's us!)
if (name === 'codemode' || name === 'codemode-unified') {
continue;
}
// Debug logging for config conversion
console.log(`🔍 [CONVERTER] Processing server: ${name}`);
console.log(`🔍 [CONVERTER] Raw config.env keys:`, Object.keys(config.env || {}));
console.log(`🔍 [CONVERTER] Raw config.env values (first 20 chars):`,
Object.entries(config.env || {}).reduce((acc, [k, v]) => {
acc[k] = typeof v === 'string' ? v.substring(0, 20) + '...' : v;
return acc;
}, {} as Record<string, any>)
);
servers[name] = {
name,
transport: config.transport || config.type || 'stdio', // Try transport first, then type, then default to stdio
command: config.command,
args: config.args || [],
env: config.env || {},
timeout: 30000,
retryPolicy: {
maxAttempts: 3,
backoffMs: 1000,
maxBackoffMs: 5000,
retryOn: ['ECONNREFUSED', 'TIMEOUT']
}
};
console.log(`🔍 [CONVERTER] Converted env keys:`, Object.keys(servers[name].env));
}
}
return {
servers,
discovery: {
enabled: false,
intervalMs: 60000,
directories: [],
filePatterns: []
},
pooling: {
maxConnections: 10,
idleTimeout: 300000,
reconnectAttempts: 3,
reconnectDelay: 5000
}
};
}
/**
* Load TypeScript declarations from generated file
*/
function loadTypeScriptDeclarations(): string {
try {
const { readFileSync, existsSync } = require('fs');
const { join } = require('path');
const declPath = join(__dirname, '../generated/mcp.d.ts');
if (existsSync(declPath)) {
return readFileSync(declPath, 'utf-8');
}
} catch (error) {
console.error('⚠️ Could not load TypeScript declarations:', error);
}
return '';
}
/**
* Generate a concise summary of available MCP tools for tool description
*/
function generateMCPToolSummary(): string {
if (!mcpManager) {
return '';
}
const tools = mcpManager.getAvailableTools();
if (tools.length === 0) {
return '';
}
// Group by namespace
const byNamespace = new Map<string, typeof tools>();
for (const tool of tools) {
const [namespace] = tool.namespace.split('.', 1);
if (!byNamespace.has(namespace)) {
byNamespace.set(namespace, []);
}
byNamespace.get(namespace)!.push(tool);
}
let summary = '\n\nAvailable MCP Tools:\n';
for (const [namespace, nsTools] of byNamespace.entries()) {
const safeNamespace = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(namespace)
? `mcp.${namespace}`
: `mcp["${namespace}"]`;
summary += `\n${safeNamespace}:\n`;
for (const tool of nsTools) {
const toolName = tool.name.replace(`${namespace}_`, '').replace(`${namespace}-`, '');
const safeToolName = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(toolName)
? toolName
: `"${toolName}"`;
// Get parameter names from schema
const params = tool.inputSchema?.properties
? Object.keys(tool.inputSchema.properties).slice(0, 3).join(', ')
: 'args';
summary += ` - ${safeToolName}(${params}${tool.inputSchema?.properties && Object.keys(tool.inputSchema.properties).length > 3 ? ', ...' : ''})`;
if (tool.description) {
// Truncate description to first sentence
const shortDesc = tool.description.split('.')[0] + '.';
summary += ` // ${shortDesc.substring(0, 80)}${shortDesc.length > 80 ? '...' : ''}`;
}
summary += '\n';
}
}
return summary;
}
/**
* Generate MCP proxy code to inject into sandbox
*/
function generateMCPProxy(includeTypes: boolean = false): string {
if (!mcpManager) {
return ''; // No MCP tools available
}
const tools = mcpManager.getAvailableTools();
if (tools.length === 0) {
return '';
}
// Debug: Log available tools
console.error('🔍 Available MCP tools:', tools.map(t => ({ name: t.name, namespace: t.namespace })));
let proxyCode = '';
// Prepend TypeScript declarations if requested
if (includeTypes) {
const typeDeclarations = loadTypeScriptDeclarations();
if (typeDeclarations) {
proxyCode += `// TypeScript declarations for MCP tools\n`;
proxyCode += `// @ts-ignore - declarations injected at runtime\n`;
proxyCode += typeDeclarations + '\n\n';
}
}
// Group tools by namespace
const byNamespace = new Map<string, typeof tools>();
for (const tool of tools) {
const [namespace] = tool.namespace.split('.', 1);
if (!byNamespace.has(namespace)) {
byNamespace.set(namespace, []);
}
byNamespace.get(namespace)!.push(tool);
}
// Generate proxy object
proxyCode += 'const mcp = {\n';
for (const [namespace, nsTools] of byNamespace.entries()) {
// Quote namespace if it contains special characters (like hyphens)
const safeNamespace = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(namespace)
? namespace
: `"${namespace}"`;
proxyCode += ` ${safeNamespace}: {\n`;
for (const tool of nsTools) {
const toolName = tool.name.replace(`${namespace}_`, '').replace(`${namespace}-`, '');
// Quote tool name if it contains special characters
const safeToolName = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(toolName)
? toolName
: `"${toolName}"`;
proxyCode += ` ${safeToolName}: async (args) => {\n`;
proxyCode += ` const response = await __mcpCall('${tool.namespace}', args);\n`;
proxyCode += ` return response;\n`;
proxyCode += ` },\n`;
}
proxyCode += ` },\n`;
}
proxyCode += '};\n\n';
return proxyCode;
}
/**
* Initialize MCP Manager to connect to other MCP servers
*/
async function initializeMCPManager(): Promise<void> {
const config = loadMCPConfig();
if (!config || Object.keys(config.servers).length === 0) {
console.error('📭 No MCP servers configured - running in standalone mode');
return;
}
try {
console.error('🔌 Initializing MCP Manager...');
console.error(` Connecting to ${Object.keys(config.servers).length} MCP server(s)`);
mcpManager = new MCPManager(config);
await mcpManager.initialize();
const tools = mcpManager.getAvailableTools();
console.error(`✅ MCP Manager initialized - ${tools.length} tools available`);
// Log available namespaces
const namespaces = new Set(tools.map(t => t.namespace.split('.')[0]));
console.error(` Namespaces: ${Array.from(namespaces).join(', ')}`);
} catch (error) {
console.error('⚠️ Failed to initialize MCP Manager:', error);
console.error(' Continuing without MCP tool access');
mcpManager = null;
}
}
async function getRuntime(type: RuntimeType): Promise<BaseRuntime> {
if (!runtimeCache.has(type)) {
const runtime = await RuntimeFactory.create({ type });
runtimeCache.set(type, runtime);
}
return runtimeCache.get(type)!;
}
/**
* Generate tool definitions dynamically based on configuration
*/
function generateToolDefinitions(): Tool[] {
// Base description for execute_code
let executeCodeDescription = 'Execute JavaScript/TypeScript code in a sandboxed runtime environment. Supports multiple runtimes with different capabilities.';
// Add MCP tool information based on mode
if (mcpManager && TYPE_EXPOSURE_MODE === 'auto-include') {
// Auto-include mode: Add tool summary directly in description
executeCodeDescription += ' When MCP integration is enabled, code has access to MCP tools via the global `mcp` object.';
const toolSummary = generateMCPToolSummary();
if (toolSummary) {
executeCodeDescription += toolSummary;
}
executeCodeDescription += '\n\nFor complete TypeScript type definitions, read the resource mcp://types/declarations.';
} else if (mcpManager) {
// On-demand mode: Just mention the resource
executeCodeDescription += ' When MCP integration is enabled, code has access to MCP tools via the global `mcp` object (e.g., mcp.automem.store_memory(), mcp["sequential-thinking"].sequentialthinking()). For TypeScript type definitions and API documentation of available MCP tools, read the resource mcp://types/declarations before writing code.';
}
return [
{
name: 'execute_code',
description: executeCodeDescription,
inputSchema: {
type: 'object',
properties: {
code: {
type: 'string',
description: 'The JavaScript or TypeScript code to execute'
},
runtime: {
type: 'string',
enum: ['quickjs', 'bun', 'deno', 'isolated-vm', 'e2b'],
description: 'Runtime to use. QuickJS: fast/lightweight but no async. Bun: full TypeScript/async support. Deno: secure with permissions. isolated-vm: V8 isolates. E2B: cloud VMs.',
default: 'quickjs'
},
timeout: {
type: 'number',
description: 'Execution timeout in milliseconds',
default: 30000
}
},
required: ['code']
}
},
{
name: 'list_runtimes',
description: 'List all available code execution runtimes with their capabilities and status',
inputSchema: {
type: 'object',
properties: {}
}
},
{
name: 'get_runtime_capabilities',
description: 'Get detailed capabilities and constraints for a specific runtime',
inputSchema: {
type: 'object',
properties: {
runtime: {
type: 'string',
enum: ['quickjs', 'bun', 'deno', 'isolated-vm', 'e2b'],
description: 'Runtime to query'
}
},
required: ['runtime']
}
},
{
name: 'runtime_health_check',
description: 'Check if a runtime is operational and ready to execute code',
inputSchema: {
type: 'object',
properties: {
runtime: {
type: 'string',
enum: ['quickjs', 'bun', 'deno', 'isolated-vm', 'e2b'],
description: 'Runtime to check'
}
},
required: ['runtime']
}
}
];
}
// Create MCP server
const server = new Server(
{
name: SERVER_NAME,
version: SERVER_VERSION,
capabilities: {
tools: {},
resources: {},
prompts: {}
}
}
);
// List available resources
server.setRequestHandler(ListResourcesRequestSchema, async (_request) => {
// Only expose type declarations if MCP integration is enabled
if (!mcpManager) {
return { resources: [] };
}
return {
resources: [
{
uri: 'mcp://types/declarations',
name: 'MCP Tool Type Declarations',
description: 'TypeScript declarations for all available MCP tools. Use these types when writing code that calls MCP tools via the mcp.* proxy.',
mimeType: 'text/x-typescript'
}
]
};
});
// Read resource content
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
const { uri } = request.params;
if (uri === 'mcp://types/declarations') {
const declarations = loadTypeScriptDeclarations();
if (!declarations) {
throw new Error('Type declarations not available. Ensure MCP integration is enabled and declarations have been generated.');
}
return {
contents: [
{
uri,
mimeType: 'text/x-typescript',
text: declarations
}
]
};
}
throw new Error(`Unknown resource: ${uri}`);
});
// List available prompts
server.setRequestHandler(ListPromptsRequestSchema, async (_request) => {
const prompts = [
{
name: 'mcp-tool-example',
description: 'Example code template for calling MCP tools with proper error handling',
arguments: [
{
name: 'tool_name',
description: 'The MCP tool to call (e.g., automem.store_memory)',
required: true
}
]
},
{
name: 'async-handler',
description: 'Template for async code with proper error handling and logging',
arguments: []
},
{
name: 'mcp-batch-operations',
description: 'Template for batching multiple MCP tool calls efficiently',
arguments: []
}
];
return { prompts };
});
// Get prompt content
server.setRequestHandler(GetPromptRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
switch (name) {
case 'mcp-tool-example': {
const toolName = args?.tool_name || 'automem.store_memory';
return {
messages: [
{
role: 'user',
content: {
type: 'text',
text: `Create example code for calling mcp.${toolName}(). Include proper error handling, type-safe arguments, and result processing.`
}
},
{
role: 'assistant',
content: {
type: 'text',
text: `Here's a type-safe example for mcp.${toolName}():
\`\`\`typescript
try {
// Read types first for reference
// Resource: mcp://types/declarations
const result = await mcp.${toolName}({
// Add type-safe arguments here based on the TypeScript definitions
// Check mcp.d.ts for exact parameter types
});
console.log('Success:', result);
return result;
} catch (error) {
console.error('MCP tool call failed:', error);
throw error;
}
\`\`\`
Remember to:
1. Read mcp://types/declarations resource for exact types
2. Use proper TypeScript types for all arguments
3. Handle errors appropriately
4. Use the correct namespace (quote if hyphenated: mcp["server-name"])
`
}
}
]
};
}
case 'async-handler': {
return {
messages: [
{
role: 'user',
content: {
type: 'text',
text: 'Create an async function template with error handling'
}
},
{
role: 'assistant',
content: {
type: 'text',
text: `\`\`\`typescript
async function handleOperation() {
const startTime = Date.now();
try {
console.log('Starting operation...');
// Your async operations here
const result = await someAsyncCall();
const duration = Date.now() - startTime;
console.log(\`Operation completed in \${duration}ms\`);
return {
success: true,
result,
duration
};
} catch (error) {
const duration = Date.now() - startTime;
console.error(\`Operation failed after \${duration}ms:\`, error);
return {
success: false,
error: error instanceof Error ? error.message : String(error),
duration
};
}
}
// Execute and return
return await handleOperation();
\`\`\`
`
}
}
]
};
}
case 'mcp-batch-operations': {
return {
messages: [
{
role: 'user',
content: {
type: 'text',
text: 'Create a template for batching multiple MCP tool calls'
}
},
{
role: 'assistant',
content: {
type: 'text',
text: `\`\`\`typescript
async function batchMCPOperations() {
console.log('Starting batch operations...');
try {
// Execute MCP calls in parallel for better performance
const results = await Promise.allSettled([
mcp.automem.store_memory({
content: 'First memory',
tags: ['batch'],
importance: 0.8
}),
mcp.automem.store_memory({
content: 'Second memory',
tags: ['batch'],
importance: 0.7
}),
mcp["sequential-thinking"].sequentialthinking({
thought: 'Analyzing batch results',
nextThoughtNeeded: false,
thoughtNumber: 1,
totalThoughts: 1
})
]);
// Process results
const successful = results.filter(r => r.status === 'fulfilled');
const failed = results.filter(r => r.status === 'rejected');
console.log(\`Batch complete: \${successful.length} succeeded, \${failed.length} failed\`);
return {
total: results.length,
successful: successful.length,
failed: failed.length,
results: results.map((r, i) => ({
index: i,
status: r.status,
value: r.status === 'fulfilled' ? r.value : undefined,
error: r.status === 'rejected' ? r.reason : undefined
}))
};
} catch (error) {
console.error('Batch operation failed:', error);
throw error;
}
}
return await batchMCPOperations();
\`\`\`
`
}
}
]
};
}
default:
throw new Error(`Unknown prompt: ${name}`);
}
});
// List available tools
server.setRequestHandler(ListToolsRequestSchema, async (_request) => {
const tools = generateToolDefinitions();
return { tools };
});
// Handle tool calls
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
try {
switch (name) {
case 'execute_code': {
const { code, runtime = 'quickjs', timeout = 30000 } = args as {
code: string;
runtime?: string;
timeout?: number;
};
// Validate runtime type
const runtimeType = runtime as RuntimeType;
if (!Object.values(RuntimeType).includes(runtimeType)) {
throw new Error(`Invalid runtime: ${runtime}. Valid options: ${Object.values(RuntimeType).join(', ')}`);
}
// Get or create runtime
const rt = await getRuntime(runtimeType);
// Check runtime capabilities
const capabilities = rt.getCapabilities();
const supportsAsync = capabilities.supportsAsync;
const supportsTypeScript = capabilities.supportsTypeScript;
// Inject MCP proxy if available
let enhancedCode = code;
const mcpCalls: Array<{ placeholder: string; namespace: string; args: any }> = [];
if (mcpManager) {
// MCP call handler - needed for both async and non-async runtimes
const mcpHandler = `
// MCP Tool Call Handler
const __mcpCallCounter = { count: 0 };
async function __mcpCall(namespace, args) {
const id = __mcpCallCounter.count++;
const placeholder = \`<<MCP_CALL_\${namespace}_\${id}>>\`;
console.log('__MCP_CALL__', JSON.stringify({ placeholder, namespace, args }));
return placeholder;
}
`;
// Generate and prepend MCP proxy (with types for TypeScript-aware runtimes)
const mcpProxy = generateMCPProxy(supportsTypeScript);
enhancedCode = mcpHandler + mcpProxy + code;
// Debug: Log generated code structure to file AND stderr
const debugInfo = `
=== MCP Proxy Debug Info ===
Timestamp: ${new Date().toISOString()}
MCP Proxy Length: ${mcpProxy.length} chars
Enhanced Code Preview (first 800 chars):
${enhancedCode.substring(0, 800)}
=== End Debug Info ===
`;
console.error(debugInfo);
// Also write to debug log file
try {
const { appendFileSync } = await import('fs');
const { tmpdir } = await import('os');
const { join } = await import('path');
const debugLogPath = join(tmpdir(), 'codemode-unified-debug.log');
appendFileSync(debugLogPath, debugInfo + '\n');
console.error(`📝 Debug log written to: ${debugLogPath}`);
} catch (e) {
// Ignore file write errors
}
}
// Execute code
const options: ExecutionOptions = { timeout };
const firstResult: ExecutionResult = await rt.execute(enhancedCode, options);
// Check if there were MCP calls - need two-pass for both runtimes
// since sandbox can't directly access parent process MCP manager
let finalResult = firstResult;
if (mcpManager && firstResult.logs) {
// Extract MCP calls from logs
for (const log of firstResult.logs) {
if (log.startsWith('__MCP_CALL__')) {
try {
const callData = JSON.parse(log.substring(12));
mcpCalls.push(callData);
} catch {
// Ignore parsing errors
}
}
}
// If MCP calls were made, resolve them and re-execute
if (mcpCalls.length > 0) {
console.error(`🔧 Resolving ${mcpCalls.length} MCP call(s)...`);
// Resolve all MCP calls
const resolutions = await Promise.all(
mcpCalls.map(async (call) => {
try {
const result = await mcpManager.callTool(call.namespace, call.args);
// MCP responses have format: { content: [{type, text}], isError?: boolean }
// Build enhanced response with raw content + convenience fields + helpers
let enhancedResponse: EnhancedMCPResponse;
if (result && result.content && Array.isArray(result.content)) {
// Extract combined text from all text content
const textParts = result.content
.filter((c: any) => c.type === 'text')
.map((c: any) => c.text);
const combinedText = textParts.join('\n');
// Create enhanced response
enhancedResponse = {
content: result.content, // Raw MCP content array
text: combinedText, // Combined text
parsed: autoParseContent(combinedText), // Auto-parsed structure
helpers: createResponseHelpers(combinedText), // Helper methods
isError: result.isError
};
} else {
// Fallback for non-standard responses
enhancedResponse = {
content: [],
text: String(result),
parsed: result,
helpers: createResponseHelpers(String(result)),
isError: false