-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathcode_exec_test.go
More file actions
382 lines (333 loc) · 14.1 KB
/
Copy pathcode_exec_test.go
File metadata and controls
382 lines (333 loc) · 14.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
package httpapi_test
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/config"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/contracts"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/httpapi"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/zap"
)
// mockController is a minimal mock for testing the code exec handler
type mockController struct {
callToolFunc func(ctx context.Context, toolName string, args map[string]interface{}) (interface{}, error)
}
func (m *mockController) CallTool(ctx context.Context, toolName string, args map[string]interface{}) (interface{}, error) {
if m.callToolFunc != nil {
return m.callToolFunc(ctx, toolName, args)
}
return nil, nil
}
// Stub implementations for other ServerController methods
func (m *mockController) IsRunning() bool { return true }
func (m *mockController) IsReady() bool { return true }
func (m *mockController) GetListenAddress() string { return "" }
func (m *mockController) GetUpstreamStats() map[string]interface{} { return nil }
func (m *mockController) StartServer(ctx context.Context) error { return nil }
func (m *mockController) StopServer() error { return nil }
func (m *mockController) GetStatus() interface{} { return nil }
func (m *mockController) StatusChannel() <-chan interface{} { return nil }
func (m *mockController) EventsChannel() <-chan interface{} { return nil }
func (m *mockController) GetAllServers() ([]map[string]interface{}, error) {
return nil, nil
}
func (m *mockController) EnableServer(serverName string, enabled bool) error { return nil }
func (m *mockController) RestartServer(serverName string) error { return nil }
func (m *mockController) ForceReconnectAllServers(reason string) error { return nil }
func (m *mockController) GetDockerRecoveryStatus() interface{} { return nil }
func (m *mockController) QuarantineServer(serverName string, quarantined bool) error {
return nil
}
func (m *mockController) GetQuarantinedServers() ([]map[string]interface{}, error) {
return nil, nil
}
func (m *mockController) UnquarantineServer(serverName string) error { return nil }
func (m *mockController) GetServerTools(serverName string) ([]map[string]interface{}, error) {
return nil, nil
}
func (m *mockController) SearchTools(query string, limit int) ([]map[string]interface{}, error) {
return nil, nil
}
func (m *mockController) GetServerLogs(serverName string, tail int) ([]contracts.LogEntry, error) {
return nil, nil
}
func (m *mockController) ReloadConfiguration() error { return nil }
func (m *mockController) GetConfigPath() string { return "" }
func (m *mockController) GetLogDir() string { return "" }
func (m *mockController) TriggerOAuthLogin(serverName string) error { return nil }
func (m *mockController) GetSecretResolver() interface{} { return nil }
func (m *mockController) GetCurrentConfig() interface{} { return nil }
func (m *mockController) NotifySecretsChanged(ctx context.Context, operation, secretName string) error {
return nil
}
func (m *mockController) GetToolCalls(limit, offset int) (interface{}, int, error) {
return nil, 0, nil
}
func (m *mockController) GetToolCallByID(id string) (interface{}, error) { return nil, nil }
func (m *mockController) GetServerToolCalls(serverName string, limit int) (interface{}, error) {
return nil, nil
}
func (m *mockController) ReplayToolCall(id string, arguments map[string]interface{}) (interface{}, error) {
return nil, nil
}
func (m *mockController) ValidateConfig(cfg interface{}) (interface{}, error) { return nil, nil }
func (m *mockController) ApplyConfig(cfg interface{}, cfgPath string) (interface{}, error) {
return nil, nil
}
func (m *mockController) GetConfig() (interface{}, error) { return nil, nil }
func (m *mockController) GetTokenSavings() (interface{}, error) {
return nil, nil
}
func (m *mockController) ListRegistries() ([]interface{}, error) { return nil, nil }
func (m *mockController) SearchRegistryServers(registryID, tag, query string, limit int) ([]interface{}, *contracts.RegistryCacheInfo, error) {
return nil, nil, nil
}
func (m *mockController) RefreshRegistryCache(registryID string) (int, error) { return 0, nil }
func (m *mockController) AddServerFromRegistryRef(_ context.Context, _, _, _ string, _ map[string]string, _ *bool) (*config.ServerConfig, *contracts.RegistryAddError, error) {
return nil, nil, nil
}
func (m *mockController) AddRegistrySourceRef(_, _, _, _ string) (*config.RegistryEntry, *contracts.RegistryAddError, error) {
return nil, nil, nil
}
func (m *mockController) RemoveRegistrySourceRef(_ string) (*config.RegistryEntry, *contracts.RegistryAddError, error) {
return nil, nil, nil
}
func (m *mockController) GetManagementService() interface{} { return nil }
func (m *mockController) GetRuntime() interface{} { return nil }
func (m *mockController) GetSessions(limit, offset int) (interface{}, int, error) { return nil, 0, nil }
func (m *mockController) GetSessionByID(id string) (interface{}, error) { return nil, nil }
func (m *mockController) GetRecentSessions(limit int) (interface{}, int, error) { return nil, 0, nil }
func (m *mockController) GetToolCallsBySession(sessionID string, limit, offset int) (interface{}, int, error) {
return nil, 0, nil
}
func (m *mockController) GetVersionInfo() interface{} { return nil }
func (m *mockController) RefreshVersionInfo() interface{} { return nil }
func (m *mockController) DiscoverServerTools(_ context.Context, _ string) error { return nil }
func (m *mockController) AddServer(_ context.Context, _ interface{}) error { return nil }
func (m *mockController) RemoveServer(_ context.Context, _ string) error { return nil }
func (m *mockController) ListActivities(_ interface{}) (interface{}, int, error) { return nil, 0, nil }
func (m *mockController) GetActivity(_ string) (interface{}, error) { return nil, nil }
func (m *mockController) StreamActivities(_ interface{}) <-chan interface{} {
ch := make(chan interface{})
close(ch)
return ch
}
func TestCodeExecHandler_Success(t *testing.T) {
// Given: Valid code execution request
reqBody := map[string]interface{}{
"code": "({ result: input.value * 2 })",
"input": map[string]interface{}{"value": 21},
"options": map[string]interface{}{
"timeout_ms": 60000,
"max_tool_calls": 10,
},
}
bodyBytes, _ := json.Marshal(reqBody)
req := httptest.NewRequest(http.MethodPost, "/api/v1/code/exec", bytes.NewReader(bodyBytes))
req.Header.Set("Content-Type", "application/json")
// Mock controller that returns success result in MCP Content format
mockCtrl := &mockController{
callToolFunc: func(ctx context.Context, toolName string, args map[string]interface{}) (interface{}, error) {
assert.Equal(t, "code_execution", toolName)
// Return MCP Content array format (matches actual CallTool behavior)
execResult := map[string]interface{}{
"ok": true,
"value": 42,
}
resultJSON, _ := json.Marshal(execResult)
return []interface{}{
map[string]interface{}{
"type": "text",
"text": string(resultJSON),
},
}, nil
},
}
logger := zap.NewNop().Sugar()
handler := httpapi.NewCodeExecHandler(mockCtrl, logger)
// When: Calling endpoint
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, req)
// Then: Returns success with result
assert.Equal(t, http.StatusOK, recorder.Code)
var response map[string]interface{}
err := json.Unmarshal(recorder.Body.Bytes(), &response)
require.NoError(t, err)
assert.True(t, response["ok"].(bool))
assert.Contains(t, response, "result")
}
func TestCodeExecHandler_MissingCode(t *testing.T) {
// Given: Request without code
reqBody := map[string]interface{}{
"input": map[string]interface{}{},
}
bodyBytes, _ := json.Marshal(reqBody)
req := httptest.NewRequest(http.MethodPost, "/api/v1/code/exec", bytes.NewReader(bodyBytes))
req.Header.Set("Content-Type", "application/json")
mockCtrl := &mockController{}
logger := zap.NewNop().Sugar()
handler := httpapi.NewCodeExecHandler(mockCtrl, logger)
// When: Calling endpoint
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, req)
// Then: Returns 400 Bad Request
assert.Equal(t, http.StatusBadRequest, recorder.Code)
var response map[string]interface{}
err := json.Unmarshal(recorder.Body.Bytes(), &response)
require.NoError(t, err)
assert.False(t, response["ok"].(bool))
assert.Contains(t, response, "error")
}
func TestCodeExecHandler_TypeScriptSuccess(t *testing.T) {
// Given: TypeScript code execution request
reqBody := map[string]interface{}{
"code": "const x: number = 42; ({ result: x })",
"language": "typescript",
"input": map[string]interface{}{},
"options": map[string]interface{}{
"timeout_ms": 60000,
"max_tool_calls": 10,
},
}
bodyBytes, _ := json.Marshal(reqBody)
req := httptest.NewRequest(http.MethodPost, "/api/v1/code/exec", bytes.NewReader(bodyBytes))
req.Header.Set("Content-Type", "application/json")
// Mock controller that verifies language is passed through
mockCtrl := &mockController{
callToolFunc: func(ctx context.Context, toolName string, args map[string]interface{}) (interface{}, error) {
assert.Equal(t, "code_execution", toolName)
// Verify language parameter is passed
assert.Equal(t, "typescript", args["language"])
// Return success
execResult := map[string]interface{}{
"ok": true,
"value": 42,
}
resultJSON, _ := json.Marshal(execResult)
return []interface{}{
map[string]interface{}{
"type": "text",
"text": string(resultJSON),
},
}, nil
},
}
logger := zap.NewNop().Sugar()
handler := httpapi.NewCodeExecHandler(mockCtrl, logger)
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, req)
assert.Equal(t, http.StatusOK, recorder.Code)
var response map[string]interface{}
err := json.Unmarshal(recorder.Body.Bytes(), &response)
require.NoError(t, err)
assert.True(t, response["ok"].(bool))
}
func TestCodeExecHandler_NoLanguageDefaultsToJavaScript(t *testing.T) {
// Given: Request without language field
reqBody := map[string]interface{}{
"code": "({ result: 42 })",
"input": map[string]interface{}{},
}
bodyBytes, _ := json.Marshal(reqBody)
req := httptest.NewRequest(http.MethodPost, "/api/v1/code/exec", bytes.NewReader(bodyBytes))
req.Header.Set("Content-Type", "application/json")
mockCtrl := &mockController{
callToolFunc: func(ctx context.Context, toolName string, args map[string]interface{}) (interface{}, error) {
// Verify no language parameter is passed (backward compat)
_, hasLanguage := args["language"]
assert.False(t, hasLanguage, "language should not be in args when not specified")
execResult := map[string]interface{}{
"ok": true,
"value": 42,
}
resultJSON, _ := json.Marshal(execResult)
return []interface{}{
map[string]interface{}{
"type": "text",
"text": string(resultJSON),
},
}, nil
},
}
logger := zap.NewNop().Sugar()
handler := httpapi.NewCodeExecHandler(mockCtrl, logger)
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, req)
assert.Equal(t, http.StatusOK, recorder.Code)
var response map[string]interface{}
err := json.Unmarshal(recorder.Body.Bytes(), &response)
require.NoError(t, err)
assert.True(t, response["ok"].(bool))
}
func TestCodeExecHandler_InvalidLanguage(t *testing.T) {
// Given: Request with invalid language
reqBody := map[string]interface{}{
"code": "({ result: 42 })",
"language": "python",
"input": map[string]interface{}{},
}
bodyBytes, _ := json.Marshal(reqBody)
req := httptest.NewRequest(http.MethodPost, "/api/v1/code/exec", bytes.NewReader(bodyBytes))
req.Header.Set("Content-Type", "application/json")
mockCtrl := &mockController{}
logger := zap.NewNop().Sugar()
handler := httpapi.NewCodeExecHandler(mockCtrl, logger)
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, req)
assert.Equal(t, http.StatusBadRequest, recorder.Code)
var response map[string]interface{}
err := json.Unmarshal(recorder.Body.Bytes(), &response)
require.NoError(t, err)
assert.False(t, response["ok"].(bool))
errorMap := response["error"].(map[string]interface{})
assert.Equal(t, "INVALID_LANGUAGE", errorMap["code"])
assert.Contains(t, errorMap["message"], "python")
}
func TestCodeExecHandler_ExecutionError(t *testing.T) {
// Given: Code with syntax error (returned from code_execution tool)
reqBody := map[string]interface{}{
"code": "invalid javascript {{{",
"input": map[string]interface{}{},
}
bodyBytes, _ := json.Marshal(reqBody)
req := httptest.NewRequest(http.MethodPost, "/api/v1/code/exec", bytes.NewReader(bodyBytes))
req.Header.Set("Content-Type", "application/json")
// Mock controller returns error result from code_execution tool in MCP Content format
mockCtrl := &mockController{
callToolFunc: func(ctx context.Context, toolName string, args map[string]interface{}) (interface{}, error) {
// Return MCP Content array format with error
execResult := map[string]interface{}{
"ok": false,
"error": map[string]interface{}{
"code": "SYNTAX_ERROR",
"message": "Invalid syntax",
},
}
resultJSON, _ := json.Marshal(execResult)
return []interface{}{
map[string]interface{}{
"type": "text",
"text": string(resultJSON),
},
}, nil
},
}
logger := zap.NewNop().Sugar()
handler := httpapi.NewCodeExecHandler(mockCtrl, logger)
// When: Calling endpoint
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, req)
// Then: Returns 200 with ok=false (execution error, not HTTP error)
assert.Equal(t, http.StatusOK, recorder.Code)
var response map[string]interface{}
err := json.Unmarshal(recorder.Body.Bytes(), &response)
require.NoError(t, err)
assert.False(t, response["ok"].(bool))
errorMap := response["error"].(map[string]interface{})
assert.Equal(t, "SYNTAX_ERROR", errorMap["code"])
}