@justanothermldude/mcp-exec 0.1.0 → 1.0.1

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.
@@ -1,223 +0,0 @@
1
- import { SandboxExecutor } from '../sandbox/index.js';
2
- import { MCPBridge } from '../bridge/index.js';
3
- import { DEFAULT_TIMEOUT_MS } from '../types/execution.js';
4
- /**
5
- * MCP Tool definition for execute_with_context
6
- */
7
- export const executeWithContextTool = {
8
- name: 'execute_with_context',
9
- description: 'Execute TypeScript/JavaScript code with pre-injected context variables. The context object is available as a global `context` variable in the executed code.',
10
- inputSchema: {
11
- type: 'object',
12
- properties: {
13
- code: {
14
- type: 'string',
15
- description: 'The TypeScript/JavaScript code to execute',
16
- },
17
- context: {
18
- type: 'object',
19
- description: 'Context object to inject into code execution (available as global `context` variable)',
20
- additionalProperties: true,
21
- },
22
- timeout_ms: {
23
- type: 'number',
24
- description: `Maximum execution time in milliseconds (default: ${DEFAULT_TIMEOUT_MS})`,
25
- },
26
- },
27
- required: ['code'],
28
- },
29
- };
30
- /**
31
- * Serialize context to JSON with error handling for circular references
32
- * @param context - The context object to serialize
33
- * @returns Serialized JSON string
34
- * @throws Error if context contains non-serializable values
35
- */
36
- function serializeContext(context) {
37
- try {
38
- return JSON.stringify(context);
39
- }
40
- catch (error) {
41
- if (error instanceof TypeError && error.message.includes('circular')) {
42
- throw new Error('Context contains circular references and cannot be serialized');
43
- }
44
- throw new Error(`Failed to serialize context: ${error instanceof Error ? error.message : String(error)}`);
45
- }
46
- }
47
- /**
48
- * Generate context injection code that creates a global `context` variable.
49
- * Uses Base64 encoding to prevent injection attacks via malicious context values.
50
- * @param context - The context object to inject
51
- * @returns Code string that declares the context variable
52
- */
53
- function generateContextInjection(context) {
54
- const serializedContext = serializeContext(context);
55
- const base64Context = Buffer.from(serializedContext, 'utf-8').toString('base64');
56
- return `// Context injection (Base64 encoded for security)
57
- declare global {
58
- var context: Record<string, unknown>;
59
- }
60
- globalThis.context = JSON.parse(Buffer.from('${base64Context}', 'base64').toString('utf-8'));
61
-
62
- `;
63
- }
64
- /**
65
- * Creates the execute_with_context handler function
66
- *
67
- * @param pool - Server pool for MCP connections
68
- * @param config - Optional handler configuration
69
- * @returns Handler function for execute_with_context tool
70
- */
71
- export function createExecuteWithContextHandler(pool, config = {}) {
72
- // Ensure bridge port matches sandbox network config
73
- const bridgePort = config.bridgeConfig?.port ?? 3000;
74
- const sandboxConfig = {
75
- ...config.sandboxConfig,
76
- mcpBridgePort: bridgePort,
77
- };
78
- const executor = new SandboxExecutor(sandboxConfig);
79
- const bridge = new MCPBridge(pool, {
80
- ...config.bridgeConfig,
81
- port: bridgePort,
82
- });
83
- /**
84
- * Execute with context handler - orchestrates context injection, bridge, executor, and cleanup
85
- */
86
- return async function executeWithContextHandler(args) {
87
- const { code, context = {}, timeout_ms = DEFAULT_TIMEOUT_MS } = args;
88
- // Validate input
89
- if (!code || typeof code !== 'string') {
90
- return {
91
- content: [{ type: 'text', text: 'Error: code parameter is required and must be a string' }],
92
- isError: true,
93
- };
94
- }
95
- if (context !== undefined && (typeof context !== 'object' || context === null || Array.isArray(context))) {
96
- return {
97
- content: [{ type: 'text', text: 'Error: context must be an object' }],
98
- isError: true,
99
- };
100
- }
101
- if (timeout_ms !== undefined && (typeof timeout_ms !== 'number' || timeout_ms <= 0)) {
102
- return {
103
- content: [{ type: 'text', text: 'Error: timeout_ms must be a positive number' }],
104
- isError: true,
105
- };
106
- }
107
- // Generate context injection code
108
- let contextInjection = '';
109
- try {
110
- if (Object.keys(context).length > 0) {
111
- contextInjection = generateContextInjection(context);
112
- }
113
- else {
114
- // Provide empty context object if no context provided
115
- contextInjection = `// Empty context
116
- declare global {
117
- var context: Record<string, unknown>;
118
- }
119
- globalThis.context = {};
120
-
121
- `;
122
- }
123
- }
124
- catch (error) {
125
- return {
126
- content: [{ type: 'text', text: `Error: ${error instanceof Error ? error.message : String(error)}` }],
127
- isError: true,
128
- };
129
- }
130
- // Compose final code: context injection prepended to user code
131
- // The executor will add MCP preamble after context injection
132
- const composedCode = contextInjection + code;
133
- let result = null;
134
- try {
135
- // Step 1: Start the MCP bridge server
136
- await bridge.start();
137
- // Step 2: Execute code in sandbox (executor adds MCP preamble)
138
- result = await executor.execute(composedCode, timeout_ms);
139
- // Step 3: Stop the bridge server
140
- await bridge.stop();
141
- // Step 4: Format and return result
142
- return formatResult(result);
143
- }
144
- catch (error) {
145
- // Ensure bridge is stopped on error
146
- try {
147
- if (bridge.isRunning()) {
148
- await bridge.stop();
149
- }
150
- }
151
- catch {
152
- // Ignore cleanup errors
153
- }
154
- // Return error with any partial output
155
- const errorMessage = error instanceof Error ? error.message : String(error);
156
- return formatErrorResult(errorMessage, result);
157
- }
158
- };
159
- }
160
- /**
161
- * Format a successful execution result
162
- */
163
- function formatResult(result) {
164
- const lines = [];
165
- // Add output
166
- if (result.output.length > 0) {
167
- lines.push(...result.output);
168
- }
169
- // Add error if present (non-fatal stderr)
170
- if (result.error) {
171
- lines.push(`[stderr]: ${result.error}`);
172
- }
173
- // Add execution time
174
- lines.push(`[Execution completed in ${result.durationMs}ms]`);
175
- const hasError = !!result.error;
176
- return {
177
- content: [{ type: 'text', text: lines.join('\n') }],
178
- isError: hasError,
179
- };
180
- }
181
- /**
182
- * Format an error result with optional partial output
183
- */
184
- function formatErrorResult(errorMessage, partialResult) {
185
- const lines = [];
186
- // Add partial output if available
187
- if (partialResult?.output.length) {
188
- lines.push('[Partial output]:');
189
- lines.push(...partialResult.output);
190
- lines.push('');
191
- }
192
- // Add error message
193
- lines.push(`Error: ${errorMessage}`);
194
- // Add duration if available
195
- if (partialResult?.durationMs) {
196
- lines.push(`[Execution failed after ${partialResult.durationMs}ms]`);
197
- }
198
- return {
199
- content: [{ type: 'text', text: lines.join('\n') }],
200
- isError: true,
201
- };
202
- }
203
- /**
204
- * Type guard for ExecuteWithContextInput
205
- */
206
- export function isExecuteWithContextInput(args) {
207
- if (typeof args !== 'object' || args === null) {
208
- return false;
209
- }
210
- const input = args;
211
- // code must be a string
212
- if (typeof input.code !== 'string') {
213
- return false;
214
- }
215
- // context, if provided, must be an object (not array, not null)
216
- if (input.context !== undefined) {
217
- if (typeof input.context !== 'object' || input.context === null || Array.isArray(input.context)) {
218
- return false;
219
- }
220
- }
221
- return true;
222
- }
223
- //# sourceMappingURL=execute-with-context.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"execute-with-context.js","sourceRoot":"","sources":["../../src/tools/execute-with-context.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,eAAe,EAA8B,MAAM,qBAAqB,CAAC;AAClF,OAAO,EAAE,SAAS,EAAwB,MAAM,oBAAoB,CAAC;AACrE,OAAO,EAAE,kBAAkB,EAAwB,MAAM,uBAAuB,CAAC;AAcjF;;GAEG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAG;IACpC,IAAI,EAAE,sBAAsB;IAC5B,WAAW,EACT,8JAA8J;IAChK,WAAW,EAAE;QACX,IAAI,EAAE,QAAiB;QACvB,UAAU,EAAE;YACV,IAAI,EAAE;gBACJ,IAAI,EAAE,QAAQ;gBACd,WAAW,EAAE,2CAA2C;aACzD;YACD,OAAO,EAAE;gBACP,IAAI,EAAE,QAAQ;gBACd,WAAW,EAAE,uFAAuF;gBACpG,oBAAoB,EAAE,IAAI;aAC3B;YACD,UAAU,EAAE;gBACV,IAAI,EAAE,QAAQ;gBACd,WAAW,EAAE,oDAAoD,kBAAkB,GAAG;aACvF;SACF;QACD,QAAQ,EAAE,CAAC,MAAM,CAAC;KACnB;CACF,CAAC;AA4BF;;;;;GAKG;AACH,SAAS,gBAAgB,CAAC,OAAgC;IACxD,IAAI,CAAC;QACH,OAAO,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;IACjC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,SAAS,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAC,EAAE,CAAC;YAC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