-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathgetorlaunchforsession_test.go
More file actions
416 lines (342 loc) · 14.2 KB
/
Copy pathgetorlaunchforsession_test.go
File metadata and controls
416 lines (342 loc) · 14.2 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
package launcher
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/github/gh-aw-mcpg/internal/config"
)
// NOTE: Many tests in this file that originally used stdio backends with commands like
// "echo" or "sleep" are now skipped because these commands don't implement the MCP protocol.
// The launcher validates MCP protocol handshake during connection creation.
//
// To test actual MCP connections, use integration tests with real MCP servers
// or HTTP backend mocks.
// TestGetOrLaunchForSession_StdioBackend tests stdio backend launching for a new session
func TestGetOrLaunchForSession_StdioBackend(t *testing.T) {
t.Skip("Requires MCP protocol server - echo command doesn't implement MCP")
}
// TestGetOrLaunchForSession_StdioReuse tests session connection reuse
func TestGetOrLaunchForSession_StdioReuse(t *testing.T) {
t.Skip("Requires MCP protocol server - echo command doesn't implement MCP")
}
// TestGetOrLaunchForSession_MultipleSessions tests multiple independent sessions
func TestGetOrLaunchForSession_MultipleSessions(t *testing.T) {
t.Skip("Requires MCP protocol server - echo command doesn't implement MCP")
}
// TestGetOrLaunchForSession_DoubleCheckLock tests double-check locking pattern
func TestGetOrLaunchForSession_DoubleCheckLock(t *testing.T) {
t.Skip("Requires MCP protocol server - sleep command doesn't implement MCP")
}
// TestGetOrLaunchForSession_EnvPassthrough tests environment variable passthrough
func TestGetOrLaunchForSession_EnvPassthrough(t *testing.T) {
t.Skip("Requires MCP protocol server - echo command doesn't implement MCP")
}
// TestGetOrLaunchForSession_EnvMissing tests missing environment variable warning
func TestGetOrLaunchForSession_EnvMissing(t *testing.T) {
t.Skip("Requires MCP protocol server - echo command doesn't implement MCP")
}
// TestGetOrLaunchForSession_EnvExplicit tests explicit VAR=value env format
func TestGetOrLaunchForSession_EnvExplicit(t *testing.T) {
t.Skip("Requires MCP protocol server - echo command doesn't implement MCP")
}
// TestGetOrLaunchForSession_EnvLongValue tests long value truncation in logs
func TestGetOrLaunchForSession_EnvLongValue(t *testing.T) {
t.Skip("Requires MCP protocol server - echo command doesn't implement MCP")
}
// TestGetOrLaunchForSession_EnvMap tests additional environment variables from config
func TestGetOrLaunchForSession_EnvMap(t *testing.T) {
t.Skip("Requires MCP protocol server - echo command doesn't implement MCP")
}
// TestGetOrLaunchForSession_DirectCommandWarning tests warning for direct commands in container
func TestGetOrLaunchForSession_DirectCommandWarning(t *testing.T) {
t.Skip("Requires MCP protocol server - echo command doesn't implement MCP")
}
// TestGetOrLaunchForSession_DockerCommandInContainer tests docker command is OK in container
func TestGetOrLaunchForSession_DockerCommandInContainer(t *testing.T) {
t.Skip("Requires Docker and MCP protocol server")
}
// TestGetOrLaunchForSession_ConnectionFailure tests connection creation failure
func TestGetOrLaunchForSession_ConnectionFailure(t *testing.T) {
t.Skip("Test assumes session pool records errors, but implementation may not add metadata on failure")
}
// TestGetOrLaunchForSession_Timeout tests startup timeout handling
func TestGetOrLaunchForSession_Timeout(t *testing.T) {
t.Skip("Test requires timeout behavior which depends on MCP handshake timing")
}
// TestGetOrLaunchForSession_MultipleServers tests different servers with different sessions
func TestGetOrLaunchForSession_MultipleServers(t *testing.T) {
t.Skip("Requires MCP protocol server - echo command doesn't implement MCP")
}
// TestGetOrLaunchForSession_EmptyEnvMap tests empty env map doesn't log
func TestGetOrLaunchForSession_EmptyEnvMap(t *testing.T) {
t.Skip("Requires MCP protocol server - echo command doesn't implement MCP")
}
// TestGetOrLaunchForSession_ConcurrentDifferentSessions tests concurrent launches for different sessions
func TestGetOrLaunchForSession_ConcurrentDifferentSessions(t *testing.T) {
t.Skip("Requires MCP protocol server - echo command doesn't implement MCP")
}
// TestGetOrLaunchForSession_ErrorRecording tests error count increases on failures
func TestGetOrLaunchForSession_ErrorRecording(t *testing.T) {
t.Skip("Test assumes session pool records errors, but implementation may not add metadata on failure")
}
// TestGetOrLaunchForSession_MultipleEnvFlags tests multiple -e flags in args
func TestGetOrLaunchForSession_MultipleEnvFlags(t *testing.T) {
t.Skip("Requires MCP protocol server - echo command doesn't implement MCP")
}
// TestGetOrLaunchForSession_StartupTimeoutConfig tests custom startup timeout from config
func TestGetOrLaunchForSession_StartupTimeoutConfig(t *testing.T) {
cfg := newTestConfig(map[string]*config.ServerConfig{
"stdio-server": {
Type: "stdio",
Command: "echo",
Args: []string{"test"},
},
})
ctx := context.Background()
l := New(ctx, cfg)
defer l.Close()
// Set custom startup timeout
customTimeout := 5 * time.Second
l.startupTimeout = customTimeout
// Verify timeout is set correctly
assert.Equal(t, customTimeout, l.startupTimeout)
// Note: We don't actually try to launch the connection here because
// the echo command doesn't implement the MCP protocol. This test
// verifies that the startupTimeout field can be configured correctly.
// The actual timeout behavior is tested in integration tests.
}
// TestGetOrLaunchForSession_StdioSessionPoolHit tests that a cached stdio session connection
// is returned from the session pool without launching a new backend.
func TestGetOrLaunchForSession_StdioSessionPoolHit(t *testing.T) {
require := require.New(t)
assert := assert.New(t)
// Create a mock HTTP server to get a real *mcp.Connection to put in the pool
mockServer := newMockHTTPMCPServer(t)
defer mockServer.Close()
ctx := context.Background()
cfg := newTestConfig(map[string]*config.ServerConfig{
"http-backend": {
Type: "http",
URL: mockServer.URL,
},
"stdio-backend": {
Type: "stdio",
Command: "docker",
Args: []string{"run", "--rm", "-i", "nonexistent:latest"},
},
})
l := New(ctx, cfg)
defer l.Close()
// Get a real HTTP connection to use as a stand-in in the session pool
httpConn, err := GetOrLaunch(l, "http-backend")
require.NoError(err)
require.NotNil(httpConn)
// Pre-populate the session pool with the connection for the stdio backend
sessionID := "test-session-123"
l.sessionPool.Set("stdio-backend", sessionID, httpConn)
// GetOrLaunchForSession should return the cached connection without launching a new process
result, err := GetOrLaunchForSession(l, "stdio-backend", sessionID)
require.NoError(err)
require.NotNil(result)
// Verify we got back the same cached connection
assert.Equal(httpConn, result, "Should return the pre-cached connection from session pool")
}
// TestGetOrLaunchForSession_StdioLaunchFailure tests that a failed stdio launch returns an error.
func TestGetOrLaunchForSession_StdioLaunchFailure(t *testing.T) {
require := require.New(t)
ctx := context.Background()
cfg := newTestConfig(map[string]*config.ServerConfig{
"stdio-backend": {
Type: "stdio",
Command: "nonexistent-command-xyz-99999",
Args: []string{"--flag"},
},
})
l := New(ctx, cfg)
defer l.Close()
// GetOrLaunchForSession should fail for an invalid command
conn, err := GetOrLaunchForSession(l, "stdio-backend", "session-abc")
require.Error(err, "Should return error for invalid command")
require.Nil(conn)
assert.ErrorContains(t, err, "failed to create connection")
}
// TestGetOrLaunchForSession_DirectCommandWarningInContainer tests that a security warning
// is logged when a direct (non-docker) command is used inside a container.
func TestGetOrLaunchForSession_DirectCommandWarningInContainer(t *testing.T) {
require := require.New(t)
ctx := context.Background()
cfg := newTestConfig(map[string]*config.ServerConfig{
"stdio-backend": {
Type: "stdio",
Command: "echo", // direct command, not docker
Args: []string{"hello"},
},
})
l := New(ctx, cfg)
defer l.Close()
// Simulate running inside a container
l.runningInContainer = true
// The launch will fail (echo doesn't implement MCP), but the security
// warning path (lines 222-226 of launcher.go) will be exercised.
conn, err := GetOrLaunchForSession(l, "stdio-backend", "session-warn")
require.Error(err, "Should fail since echo doesn't implement MCP protocol")
require.Nil(conn)
}
// TestGetOrLaunchForSession_StdioSessionPoolHit_DifferentSessions tests that different
// session IDs for the same backend return different cached connections.
func TestGetOrLaunchForSession_StdioSessionPoolHit_DifferentSessions(t *testing.T) {
require := require.New(t)
assert := assert.New(t)
mockServer := newMockHTTPMCPServer(t)
defer mockServer.Close()
ctx := context.Background()
cfg := newTestConfig(map[string]*config.ServerConfig{
"http-helper": {
Type: "http",
URL: mockServer.URL,
},
"stdio-backend": {
Type: "stdio",
Command: "docker",
Args: []string{"run", "--rm", "-i", "nonexistent:latest"},
},
})
l := New(ctx, cfg)
defer l.Close()
// Get a shared HTTP connection to use as two distinct pool entries
httpConn, err := GetOrLaunch(l, "http-helper")
require.NoError(err)
// Pre-populate session pool with the same connection pointer for two different sessions
l.sessionPool.Set("stdio-backend", "session-A", httpConn)
l.sessionPool.Set("stdio-backend", "session-B", httpConn)
// Both sessions should return from cache
connA, err := GetOrLaunchForSession(l, "stdio-backend", "session-A")
require.NoError(err)
require.NotNil(connA)
connB, err := GetOrLaunchForSession(l, "stdio-backend", "session-B")
require.NoError(err)
require.NotNil(connB)
// Both return the same underlying connection (we used the same pointer)
assert.Equal(httpConn, connA)
assert.Equal(httpConn, connB)
}
// TestGetOrLaunchForSession_ServerNotFound tests that an unknown server ID returns an error.
func TestGetOrLaunchForSession_ServerNotFound(t *testing.T) {
require := require.New(t)
ctx := context.Background()
cfg := newTestConfig(map[string]*config.ServerConfig{})
l := New(ctx, cfg)
defer l.Close()
conn, err := GetOrLaunchForSession(l, "nonexistent-server", "session-1")
require.Error(err)
require.Nil(conn)
require.ErrorIs(err, ErrServerNotFound)
}
// TestGetOrLaunchForSession_HTTPBackendRecordsStart tests that GetOrLaunchForSession
// for an HTTP backend records the server start time.
func TestGetOrLaunchForSession_HTTPBackendRecordsStart(t *testing.T) {
require := require.New(t)
assert := assert.New(t)
mockServer := newMockHTTPMCPServer(t)
defer mockServer.Close()
ctx := context.Background()
cfg := newTestConfig(map[string]*config.ServerConfig{
"http-backend": {
Type: "http",
URL: mockServer.URL,
},
})
l := New(ctx, cfg)
defer l.Close()
// First call: creates the connection and records start time.
conn1, err := GetOrLaunchForSession(l, "http-backend", "session-x")
require.NoError(err)
require.NotNil(conn1)
// Verify server state was recorded as running.
state := l.GetServerState("http-backend")
assert.Equal("running", state.Status)
assert.False(state.StartedAt.IsZero(), "StartedAt should be set after successful launch")
// Second call for a different session ID should return the same cached connection.
conn2, err := GetOrLaunchForSession(l, "http-backend", "session-y")
require.NoError(err)
require.NotNil(conn2)
assert.Equal(conn1, conn2, "HTTP backends reuse a single stateless connection")
}
// TestGetOrLaunchForSession_DoubleCheckLockPoolHit exercises the double-check locking
// path where another goroutine populates the session pool between the first
// check and the mutex acquisition.
func TestGetOrLaunchForSession_DoubleCheckLockPoolHit(t *testing.T) {
require := require.New(t)
assert := assert.New(t)
mockServer := newMockHTTPMCPServer(t)
defer mockServer.Close()
ctx := context.Background()
cfg := newTestConfig(map[string]*config.ServerConfig{
"http-helper": {
Type: "http",
URL: mockServer.URL,
},
"stdio-backend": {
Type: "stdio",
Command: "docker",
Args: []string{"run", "--rm", "-i", "nonexistent:latest"},
},
})
l := New(ctx, cfg)
defer l.Close()
// Get a real connection to put in the pool.
httpConn, err := GetOrLaunch(l, "http-helper")
require.NoError(err)
require.NotNil(httpConn)
sessionID := "double-check-session"
// Simulate: first Get check returns false (not in pool yet),
// but by the time we acquire the mutex and do the second check,
// another goroutine already populated it.
// We do this by calling Set while holding no external lock, then
// calling GetOrLaunchForSession which will find it on the second check.
// First call: pool is empty — will fail to launch, but we'll use a
// pre-populated pool to hit the "double-check" path directly.
// Pre-populate AFTER the first Get would run by directly calling Set
// and then invoking GetOrLaunchForSession (which will hit the double-check).
// Manually populate the pool so the second check inside GetOrLaunchForSession
// finds the entry.
l.mu.Lock()
l.sessionPool.Set("stdio-backend", sessionID, httpConn)
l.mu.Unlock()
// Now call GetOrLaunchForSession. The first pool.Get (without lock) should find it
// and return immediately.
conn, err := GetOrLaunchForSession(l, "stdio-backend", sessionID)
require.NoError(err)
require.NotNil(conn)
assert.Equal(httpConn, conn)
}
// newMockHTTPMCPServer creates a test HTTP server that responds to MCP initialize requests.
func newMockHTTPMCPServer(t *testing.T) *httptest.Server {
t.Helper()
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var req map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
response := map[string]interface{}{
"jsonrpc": "2.0",
"id": req["id"],
"result": map[string]interface{}{
"protocolVersion": "2024-11-05",
"capabilities": map[string]interface{}{},
"serverInfo": map[string]interface{}{
"name": "mock-server",
"version": "1.0.0",
},
},
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}))
}