-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathgateway_mcp_test.go
More file actions
1448 lines (1314 loc) · 44.6 KB
/
Copy pathgateway_mcp_test.go
File metadata and controls
1448 lines (1314 loc) · 44.6 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
package aigateway
import (
"context"
"encoding/json"
"errors"
"fmt"
"math"
"net/http"
"net/http/httptest"
"os"
"slices"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/ferro-labs/ai-gateway/config"
"github.com/ferro-labs/ai-gateway/internal/authctx"
"github.com/ferro-labs/ai-gateway/mcp"
"github.com/ferro-labs/ai-gateway/models"
"github.com/ferro-labs/ai-gateway/pkg/logger"
"github.com/ferro-labs/ai-gateway/plugin"
providers "github.com/ferro-labs/ai-gateway/providers"
"github.com/ferro-labs/ai-gateway/providers/core"
)
// mcpUndefinedVar names the environment variable the malformed-server fixtures
// below reference. Their whole premise is that it does NOT resolve, so the
// fixtures must not depend on it merely happening to be absent from the ambient
// environment: an exported value would make the "broken" server register and
// invert what every one of these tests asserts.
const mcpUndefinedVar = "GATEWAY_MCP_TEST_UNDEFINED_VAR"
// requireUnsetEnv guarantees key is unset for the duration of the test and
// restores any prior value afterwards.
func requireUnsetEnv(t *testing.T, key string) {
t.Helper()
prev, had := os.LookupEnv(key)
if !had {
return
}
if err := os.Unsetenv(key); err != nil {
t.Fatalf("unset %s: %v", key, err)
}
t.Cleanup(func() {
if err := os.Setenv(key, prev); err != nil {
t.Errorf("restore %s: %v", key, err)
}
})
}
// TestWireMCPLocked_MalformedServerDoesNotBlockOthers verifies that one MCP
// server with an unresolvable ${VAR} in its headers does not prevent
// subsequent, well-formed servers in the same config from being registered.
func TestWireMCPLocked_MalformedServerDoesNotBlockOthers(t *testing.T) {
requireUnsetEnv(t, mcpUndefinedVar)
gw := &Gateway{log: logger.Default()}
ctx, cancel := context.WithCancel(context.Background())
gw.shutdownCtx = ctx
gw.shutdownCancel = cancel
t.Cleanup(cancel)
cfg := config.Config{
MCPServers: []mcp.ServerConfig{
{
Name: "broken",
URL: "http://127.0.0.1:1/mcp",
Headers: map[string]string{
"Authorization": "Bearer ${" + mcpUndefinedVar + "}",
},
},
{
Name: "good",
URL: "http://127.0.0.1:1/mcp",
},
},
}
gw.wireMCPLocked(cfg, "test: mcp init failed")
if gw.mcpRegistry == nil {
t.Fatal("mcpRegistry is nil, want a registry containing the well-formed server")
}
names := gw.mcpRegistry.ServerNames()
if !slices.Contains(names, "good") {
t.Errorf("ServerNames() = %v, want it to contain %q", names, "good")
}
// The broken server is recorded rather than dropped: readiness reads the
// registry, so a server missing from it cannot be reported at all. It is
// present and unready, with its reason retained.
if !slices.Contains(names, "broken") {
t.Fatalf("ServerNames() = %v, want it to contain %q so its failure stays visible", names, "broken")
}
if gw.mcpRegistry.IsReady("broken") {
t.Error("a server whose headers never resolved is reported ready")
}
for _, st := range gw.mcpRegistry.Status() {
if st.Name == "broken" && st.LastError == "" {
t.Error("Status() lost the reason the server could not be built")
}
}
}
// TestReloadConfig_MalformedMCPServerDoesNotLeaveStaleRegistry verifies that a
// reload whose new config contains one malformed MCP server still rebuilds the
// registry from the new config, rather than leaving the pre-reload registry in
// place.
func TestReloadConfig_MalformedMCPServerDoesNotLeaveStaleRegistry(t *testing.T) {
requireUnsetEnv(t, mcpUndefinedVar)
gw := &Gateway{log: logger.Default()}
ctx, cancel := context.WithCancel(context.Background())
gw.shutdownCtx = ctx
gw.shutdownCancel = cancel
t.Cleanup(cancel)
base := config.Config{
Strategy: config.StrategyConfig{Mode: config.ModeSingle},
Targets: []config.Target{{VirtualKey: "test-provider"}},
}
initial := base
initial.MCPServers = []mcp.ServerConfig{{Name: "old-only", URL: "http://127.0.0.1:1/mcp"}}
gw.wireMCPLocked(initial, "test: initial mcp init failed")
reloaded := base
reloaded.MCPServers = []mcp.ServerConfig{
{
Name: "broken",
URL: "http://127.0.0.1:1/mcp",
Headers: map[string]string{
"Authorization": "Bearer ${" + mcpUndefinedVar + "}",
},
},
{Name: "good2", URL: "http://127.0.0.1:1/mcp"},
}
if err := gw.ReloadConfig(context.Background(), reloaded); err != nil {
t.Fatalf("ReloadConfig() error = %v", err)
}
gw.mu.RLock()
reg := gw.mcpRegistry
gw.mu.RUnlock()
if reg == nil {
t.Fatal("mcpRegistry is nil after reload, want the rebuilt registry")
}
names := reg.ServerNames()
if slices.Contains(names, "old-only") {
t.Errorf("ServerNames() = %v, still contains the pre-reload server; registry was not rebuilt from the new config", names)
}
if !slices.Contains(names, "good2") {
t.Errorf("ServerNames() = %v, want it to contain %q from the reloaded config", names, "good2")
}
}
// TestWireMCPLocked_MaxCallDepthIgnoresSkippedServers verifies that a server
// skipped due to unresolvable headers does not contribute its MaxCallDepth to
// the shared executor's depth limit.
func TestWireMCPLocked_MaxCallDepthIgnoresSkippedServers(t *testing.T) {
requireUnsetEnv(t, mcpUndefinedVar)
gw := &Gateway{log: logger.Default()}
ctx, cancel := context.WithCancel(context.Background())
gw.shutdownCtx = ctx
gw.shutdownCancel = cancel
t.Cleanup(cancel)
// The good server must actually serve tools: ShouldContinueLoop only arms
// for tool calls MCP owns, so a registry that discovered nothing can no
// longer stand in for a healthy one.
goodSrv := newMCPTestServer(t)
defer goodSrv.Close()
cfg := config.Config{
MCPServers: []mcp.ServerConfig{
{
Name: "broken",
URL: "http://127.0.0.1:1/mcp",
MaxCallDepth: 1,
Headers: map[string]string{
"Authorization": "Bearer ${" + mcpUndefinedVar + "}",
},
},
{
Name: "good",
URL: goodSrv.URL,
MaxCallDepth: 5,
},
},
}
gw.wireMCPLocked(cfg, "test: mcp init failed")
if gw.mcpExecutor == nil {
t.Fatal("mcpExecutor is nil, want an executor built from the well-formed server")
}
select {
case <-gw.MCPInitDone():
case <-time.After(10 * time.Second):
t.Fatal("MCP init timeout")
}
resp := &core.Response{
Choices: []core.Choice{
{Message: core.Message{ToolCalls: []core.ToolCall{{ID: "1", Function: core.FunctionCall{Name: "get_answer"}}}}},
},
}
// The broken server's max_call_depth: 1 must not clamp the shared
// executor's depth limit down from the good server's max_call_depth: 5.
if !gw.mcpExecutor.ShouldContinueLoop(resp, 4) {
t.Error("ShouldContinueLoop(resp, 4) = false, want true: depth limit should be 5 (the good server's), not 1 (the skipped server's)")
}
}
// R8: closeOnce has already fired by the time a late reload lands, so a registry
// built after shutdown would spawn its subprocesses and leave nothing able to
// close them — leaked for the life of the host process.
func TestReloadConfigAfterCloseIsRejected(t *testing.T) {
gw, err := New(config.Config{
Strategy: config.StrategyConfig{Mode: config.ModeSingle},
Targets: []config.Target{{VirtualKey: "openai"}},
})
if err != nil {
t.Fatalf("New: %v", err)
}
if err := gw.Close(); err != nil {
t.Fatalf("Close: %v", err)
}
err = gw.ReloadConfig(context.Background(), config.Config{
Strategy: config.StrategyConfig{Mode: config.ModeSingle},
Targets: []config.Target{{VirtualKey: "openai"}},
MCPServers: []mcp.ServerConfig{{
Name: "late", URL: "http://127.0.0.1:1/mcp",
}},
})
if err == nil {
t.Fatal("ReloadConfig after Close succeeded; it would spawn MCP subprocesses nothing can ever close")
}
}
// R5: ReloadConfig writes g.mcpRegistry under g.mu while Close used to read it
// after unlocking. Race-detector reproducible, and the losing interleaving left
// a live registry unclosed. Run this with -race.
func TestCloseAndReloadConfigDoNotRace(t *testing.T) {
mcpSrv := newMCPTestServer(t)
defer mcpSrv.Close()
base := config.Config{
Strategy: config.StrategyConfig{Mode: config.ModeSingle},
Targets: []config.Target{{VirtualKey: "openai"}},
MCPServers: []mcp.ServerConfig{{
Name: "s1", URL: mcpSrv.URL, TimeoutSeconds: 5,
}},
}
gw, err := New(base)
if err != nil {
t.Fatalf("New: %v", err)
}
select {
case <-gw.MCPInitDone():
case <-time.After(10 * time.Second):
t.Fatal("MCP init timeout")
}
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
// A late reload may legitimately be rejected once Close has won the
// race; both outcomes are correct, neither may race or leak.
_ = gw.ReloadConfig(context.Background(), base)
}()
go func() {
defer wg.Done()
_ = gw.Close()
}()
wg.Wait()
}
// callerTool is a tool the client declares and intends to execute itself.
func callerTool() providers.Tool {
return providers.Tool{
Type: "function",
Function: providers.Function{
Name: "client_side_lookup",
Description: "Executed by the caller, not the gateway.",
},
}
}
// The gateway must not advertise MCP tools on a request whose caller supplied
// its own tools array.
//
// Injecting both manufactures a turn neither party can resolve: the gateway
// cannot answer the caller's calls, and the caller cannot answer a tool it never
// declared and has no implementation for. Before this guard the gateway
// advertised mcp tools unconditionally, the model could call one alongside a
// caller tool, and the executor's ownership gate then declined the whole turn —
// returning a 200 carrying a tool_call_id the client could not act on, with no
// error surfaced anywhere.
func TestRoute_CallerSuppliedToolsSuppressMCPInjection(t *testing.T) {
mcpSrv := newMCPTestServer(t)
defer mcpSrv.Close()
var (
mu sync.Mutex
seen []providers.Tool
)
mp := &mockProvider{
name: "mock-tools",
models: []string{"gpt-4o"},
completeFn: func(_ context.Context, req providers.Request) (*providers.Response, error) {
mu.Lock()
seen = append([]providers.Tool{}, req.Tools...)
mu.Unlock()
return &providers.Response{
ID: "r1",
Model: "gpt-4o",
Choices: []providers.Choice{{
Message: providers.Message{Role: "assistant", Content: "done"},
FinishReason: "stop",
}},
}, nil
},
}
gw, err := newTestGateway(t, config.Config{
Strategy: config.StrategyConfig{Mode: config.ModeSingle},
Targets: []config.Target{{VirtualKey: "mock-tools"}},
MCPServers: []mcp.ServerConfig{{Name: "s1", URL: mcpSrv.URL, TimeoutSeconds: 5}},
})
if err != nil {
t.Fatalf("New: %v", err)
}
gw.RegisterProvider(mp)
select {
case <-gw.MCPInitDone():
case <-time.After(10 * time.Second):
t.Fatal("MCP init timeout")
}
if _, err := gw.Route(context.Background(), providers.Request{
Model: "gpt-4o",
Tools: []providers.Tool{callerTool()},
Messages: []providers.Message{{Role: "user", Content: "hi"}},
}); err != nil {
t.Fatalf("Route: %v", err)
}
mu.Lock()
got := seen
mu.Unlock()
if len(got) != 1 {
t.Fatalf("provider saw %d tools, want only the caller's 1: %+v", len(got), got)
}
if got[0].Function.Name != "client_side_lookup" {
t.Errorf("provider saw tool %q, want the caller's client_side_lookup", got[0].Function.Name)
}
for _, tool := range got {
if tool.Function.Name == "get_answer" {
t.Error("gateway injected an MCP tool alongside the caller's own tools; " +
"the model can then emit a turn neither party can resolve")
}
}
}
// With no caller tools, MCP still participates exactly as before.
func TestRoute_NoCallerToolsStillInjectsMCP(t *testing.T) {
mcpSrv := newMCPTestServer(t)
defer mcpSrv.Close()
var (
mu sync.Mutex
seen []providers.Tool
)
mp := &mockProvider{
name: "mock-tools2",
models: []string{"gpt-4o"},
completeFn: func(_ context.Context, req providers.Request) (*providers.Response, error) {
mu.Lock()
seen = append([]providers.Tool{}, req.Tools...)
mu.Unlock()
return &providers.Response{
ID: "r1",
Model: "gpt-4o",
Choices: []providers.Choice{{
Message: providers.Message{Role: "assistant", Content: "done"},
FinishReason: "stop",
}},
}, nil
},
}
gw, err := newTestGateway(t, config.Config{
Strategy: config.StrategyConfig{Mode: config.ModeSingle},
Targets: []config.Target{{VirtualKey: "mock-tools2"}},
MCPServers: []mcp.ServerConfig{{Name: "s1", URL: mcpSrv.URL, TimeoutSeconds: 5}},
})
if err != nil {
t.Fatalf("New: %v", err)
}
gw.RegisterProvider(mp)
select {
case <-gw.MCPInitDone():
case <-time.After(10 * time.Second):
t.Fatal("MCP init timeout")
}
if _, err := gw.Route(context.Background(), providers.Request{
Model: "gpt-4o",
Messages: []providers.Message{{Role: "user", Content: "hi"}},
}); err != nil {
t.Fatalf("Route: %v", err)
}
mu.Lock()
got := seen
mu.Unlock()
var found bool
for _, tool := range got {
if tool.Function.Name == "get_answer" {
found = true
}
}
if !found {
t.Errorf("MCP tool was not injected for a caller that supplied none: %+v", got)
}
}
// Suppressing injection must also restore streaming: MCP is not participating,
// so there is nothing to buffer the stream for.
func TestRouteStream_CallerSuppliedToolsKeepStreaming(t *testing.T) {
mcpSrv := newMCPTestServer(t)
defer mcpSrv.Close()
const wantChunks = 3
sp := &chunkStreamProvider{
mockProvider: mockProvider{name: "mock-stream-tools", models: []string{"gpt-4o"}},
chunks: wantChunks,
}
gw, err := newTestGateway(t, config.Config{
Strategy: config.StrategyConfig{Mode: config.ModeSingle},
Targets: []config.Target{{VirtualKey: "mock-stream-tools"}},
MCPServers: []mcp.ServerConfig{{Name: "s1", URL: mcpSrv.URL, TimeoutSeconds: 5}},
})
if err != nil {
t.Fatalf("New: %v", err)
}
gw.RegisterProvider(sp)
select {
case <-gw.MCPInitDone():
case <-time.After(10 * time.Second):
t.Fatal("MCP init timeout")
}
ch, err := gw.RouteStream(context.Background(), providers.Request{
Model: "gpt-4o",
Stream: true,
Tools: []providers.Tool{callerTool()},
Messages: []providers.Message{{Role: "user", Content: "hi"}},
})
if err != nil {
t.Fatalf("RouteStream: %v", err)
}
var got int
for chunk := range ch {
if chunk.Error != nil {
t.Fatalf("stream chunk error: %v", chunk.Error)
}
got++
}
if got != wantChunks {
t.Fatalf("got %d chunks, want %d — MCP collapsed the stream for a caller "+
"whose own tools mean MCP is not participating", got, wantChunks)
}
}
// A before_request plugin that adds tools must not retroactively disable MCP.
//
// RouteStream decides whether to divert a streaming request into the agentic
// loop before plugins run; Route used to decide whether MCP participates after
// they run. A transform plugin adding tools in between produced the worst of
// both: the stream was already diverted and buffered, and then MCP was switched
// off, so the caller lost streaming and got no agentic loop for it. Both
// decisions now read the caller's original request.
//
// Chunk count cannot distinguish the two cases — an active MCP loop collapses
// the stream legitimately — so the assertion is on whether MCP actually
// participated, i.e. whether its tools reached the provider.
func TestRouteStream_PluginAddedToolsDoNotDisableMCP(t *testing.T) {
mcpSrv := newMCPTestServer(t)
defer mcpSrv.Close()
var (
mu sync.Mutex
seen []providers.Tool
)
mp := &mockProvider{
name: "mock-plugin-tools",
models: []string{"gpt-4o"},
completeFn: func(_ context.Context, req providers.Request) (*providers.Response, error) {
mu.Lock()
seen = append([]providers.Tool{}, req.Tools...)
mu.Unlock()
return &providers.Response{
ID: "r1",
Model: "gpt-4o",
Choices: []providers.Choice{{
Message: providers.Message{Role: "assistant", Content: "done"},
FinishReason: "stop",
}},
}, nil
},
}
// The MCP server must actually be registered: without it g.mcpRegistry is
// nil, RouteStream's diversion gate can never fire, and the assertion below
// would hold whether or not the fix is present.
gw, err := newTestGateway(t, config.Config{
Strategy: config.StrategyConfig{Mode: config.ModeSingle},
Targets: []config.Target{{VirtualKey: "mock-plugin-tools"}},
MCPServers: []mcp.ServerConfig{{Name: "s1", URL: mcpSrv.URL, TimeoutSeconds: 5}},
})
if err != nil {
t.Fatalf("New: %v", err)
}
gw.RegisterProvider(mp)
select {
case <-gw.MCPInitDone():
case <-time.After(10 * time.Second):
t.Fatal("MCP init timeout")
}
// Adds a tool the caller never sent, mid-flight.
if err := gw.RegisterPlugin(plugin.StageBeforeRequest, &testPlugin{
name: "tool-adder",
typ: plugin.TypeTransform,
execFn: func(_ context.Context, pctx *plugin.Context) error {
if pctx.Request != nil {
pctx.Request.Tools = append(pctx.Request.Tools, callerTool())
}
return nil
},
}); err != nil {
t.Fatalf("RegisterPlugin: %v", err)
}
ch, err := gw.RouteStream(context.Background(), providers.Request{
Model: "gpt-4o",
Stream: true,
Messages: []providers.Message{{Role: "user", Content: "hi"}},
})
if err != nil {
t.Fatalf("RouteStream: %v", err)
}
for chunk := range ch {
if chunk.Error != nil {
t.Fatalf("stream chunk error: %v", chunk.Error)
}
}
mu.Lock()
got := seen
mu.Unlock()
var sawMCPTool, sawPluginTool bool
for _, tool := range got {
switch tool.Function.Name {
case "get_answer":
sawMCPTool = true
case "client_side_lookup":
sawPluginTool = true
}
}
if !sawPluginTool {
t.Fatalf("the plugin's tool never reached the provider (%+v); the probe is broken, "+
"so the assertion below would pass vacuously", got)
}
if !sawMCPTool {
t.Errorf("MCP was disabled by a plugin-added tool after the stream had already been "+
"diverted — the caller lost streaming and got no agentic loop for it: %+v", got)
}
}
// mcpServerReturning is an MCP server whose single tool answers with text the
// test chooses, so a guardrail can be pointed at content the CALLER never sent.
func mcpServerReturning(t *testing.T, toolText string) *httptest.Server {
t.Helper()
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close() //nolint:errcheck // test handler
var rpc struct {
ID any `json:"id"`
Method string `json:"method"`
}
if err := json.NewDecoder(r.Body).Decode(&rpc); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
write := func(result any) {
b, _ := json.Marshal(result)
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"jsonrpc": "2.0", "id": rpc.ID, "result": json.RawMessage(b),
})
}
switch rpc.Method {
case "initialize":
w.Header().Set("Mcp-Session-Id", "guardrail-session")
write(map[string]any{
"name": "guard-mcp", "version": "1.0",
"capabilities": map[string]any{"tools": map[string]any{}},
})
case "notifications/initialized":
w.WriteHeader(http.StatusAccepted)
case "tools/list":
write(map[string]any{"tools": []map[string]any{{
"name": "lookup", "description": "Looks something up.",
"inputSchema": json.RawMessage(`{"type":"object"}`),
}}})
case "tools/call":
write(map[string]any{
"content": []map[string]any{{"type": "text", "text": toolText}},
"isError": false,
})
default:
w.WriteHeader(http.StatusNotFound)
}
}))
}
// A configured content guardrail must inspect every provider call, including
// the turns an agentic loop makes on the caller's behalf.
//
// Those turns carry tool RESULTS produced by an external MCP server — content
// the caller never wrote and the operator has the least reason to trust. The
// loop called the router directly, so the before stage had run once, against
// the prompt alone, and the guardrail never saw them. It is the same governance
// escape as an unguarded surface, one level in.
func TestRoute_MCPLoopRunsGuardrailsOnToolResults(t *testing.T) {
const blocked = "hunter2"
mcpSrv := mcpServerReturning(t, "the password is "+blocked)
defer mcpSrv.Close()
// Turn 1 asks for the tool; turn 2 would answer. Turn 2 must never be made:
// the guardrail rejects the request carrying the tool result.
provider := &multiCallProvider{
name: "guard-provider",
models: []string{"guard-model"},
responses: []*providers.Response{
{
ID: "r1", Model: "guard-model", Provider: "guard-provider",
Choices: []providers.Choice{{
Message: providers.Message{Role: "assistant", ToolCalls: []providers.ToolCall{{
ID: "call-1", Type: "function",
Function: providers.FunctionCall{Name: "lookup", Arguments: "{}"},
}}},
FinishReason: "tool_calls",
}},
},
{
ID: "r2", Model: "guard-model", Provider: "guard-provider",
Choices: []providers.Choice{{
Message: providers.Message{Role: "assistant", Content: "done"},
FinishReason: "stop",
}},
},
},
}
gw, err := newTestGateway(t, config.Config{
Strategy: config.StrategyConfig{Mode: config.ModeSingle},
Targets: []config.Target{{VirtualKey: "guard-provider"}},
MCPServers: []mcp.ServerConfig{{Name: "s1", URL: mcpSrv.URL, TimeoutSeconds: 5}},
Plugins: []config.PluginConfig{{
Name: "word-filter", Type: "guardrail", Stage: "before_request", Enabled: true,
Config: map[string]any{"blocked_words": []any{blocked}},
}},
})
if err != nil {
t.Fatalf("new gateway: %v", err)
}
gw.RegisterProvider(provider)
if err := gw.LoadPlugins(); err != nil {
t.Fatalf("load plugins: %v", err)
}
select {
case <-gw.MCPInitDone():
case <-time.After(10 * time.Second):
t.Fatal("MCP init timeout")
}
if gw.mcpRegistry == nil || len(gw.mcpRegistry.AllTools()) == 0 {
t.Fatal("no MCP tools registered; the loop would never run and this would pass vacuously")
}
_, routeErr := gw.Route(context.Background(), providers.Request{
Model: "guard-model",
Messages: []providers.Message{{Role: "user", Content: "look it up"}},
})
if routeErr == nil {
t.Fatal("Route succeeded; the guardrail never saw the tool result")
}
var rejection *plugin.RejectionError
if !errors.As(routeErr, &rejection) {
t.Fatalf("error = %T (%v), want a plugin rejection", routeErr, routeErr)
}
if !strings.Contains(strings.ToLower(rejection.Error()), "word") {
t.Errorf("rejection = %q, want the word filter's", rejection.Error())
}
// The second turn must not have been made: the guardrail runs BEFORE the
// call, so blocked content never reaches the provider.
provider.mu.Lock()
calls := len(provider.requests)
provider.mu.Unlock()
if calls != 1 {
t.Errorf("provider was called %d times, want 1 — the blocked turn must not be sent", calls)
}
}
// multiCallProvider is a test provider that returns pre-configured responses
// in sequence, recording every request it receives for later inspection.
type multiCallProvider struct {
name string
models []string
responses []*providers.Response
mu sync.Mutex
requests []providers.Request
}
func (m *multiCallProvider) Name() string { return m.name }
func (m *multiCallProvider) ConfiguredModels() []string { return m.models }
func (m *multiCallProvider) Models() []providers.ModelInfo { return nil }
func (m *multiCallProvider) SupportsModel(model string) bool {
for _, mm := range m.models {
if mm == model {
return true
}
}
return false
}
func (m *multiCallProvider) Complete(_ context.Context, req providers.Request) (*providers.Response, error) {
m.mu.Lock()
idx := len(m.requests)
m.requests = append(m.requests, req)
m.mu.Unlock()
if idx >= len(m.responses) {
return nil, fmt.Errorf("multiCallProvider: no response configured for call %d", idx+1)
}
return m.responses[idx], nil
}
func (m *multiCallProvider) callCount() int {
m.mu.Lock()
defer m.mu.Unlock()
return len(m.requests)
}
// newMCPTestServer returns a minimal httptest MCP server that exposes a
// single "get_answer" tool returning {"type":"text","text":"42"}.
func newMCPTestServer(t *testing.T) *httptest.Server {
t.Helper()
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
defer r.Body.Close() //nolint:errcheck // test HTTP server handler; request body close error is irrelevant
var rpcReq struct {
JSONRPC string `json:"jsonrpc"`
ID any `json:"id"`
Method string `json:"method"`
Params json.RawMessage `json:"params,omitempty"`
}
if err := json.NewDecoder(r.Body).Decode(&rpcReq); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
type rpcResp struct {
JSONRPC string `json:"jsonrpc"`
ID any `json:"id"`
Result json.RawMessage `json:"result"`
}
write := func(result any) {
b, _ := json.Marshal(result)
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(rpcResp{JSONRPC: "2.0", ID: rpcReq.ID, Result: b})
}
switch rpcReq.Method {
case "initialize":
w.Header().Set("Mcp-Session-Id", "test-session-001")
write(map[string]any{
"name": "test-mcp",
"version": "1.0",
"capabilities": map[string]any{"tools": map[string]any{}},
})
case "tools/list":
write(map[string]any{
"tools": []map[string]any{{
"name": "get_answer",
"description": "Returns the ultimate answer.",
"inputSchema": json.RawMessage(`{"type":"object","properties":{"q":{"type":"string"}}}`),
}},
})
case "tools/call":
write(map[string]any{
"content": []map[string]any{{"type": "text", "text": "42"}},
"isError": false,
})
default:
w.WriteHeader(http.StatusNotFound)
}
}))
}
// TestGateway_Route_MCPToolInjectionAndLoop verifies the full MCP agentic loop:
// 1. MCP tools are injected into the first LLM request.
// 2. When the LLM returns tool_calls the gateway calls the MCP server and
// appends a tool-result message before re-routing.
// 3. The loop terminates when the LLM returns a normal response.
func TestGateway_Route_MCPToolInjectionAndLoop(t *testing.T) {
// Start a mock MCP server.
mcpSrv := newMCPTestServer(t)
defer mcpSrv.Close()
// Provider call 1 — returns a tool_call for "get_answer".
// Provider call 2 — returns the final answer after seeing the tool result.
mp := &multiCallProvider{
name: "test-provider",
models: []string{"test-model"},
responses: []*providers.Response{
{
ID: "resp-1",
Model: "test-model",
Choices: []providers.Choice{{
Message: providers.Message{
Role: "assistant",
ToolCalls: []providers.ToolCall{{
ID: "tc-1",
Type: "function",
Function: providers.FunctionCall{
Name: "get_answer",
Arguments: `{"q":"what is the answer?"}`,
},
}},
},
FinishReason: "tool_calls",
}},
},
{
ID: "resp-2",
Model: "test-model",
Choices: []providers.Choice{{
Message: providers.Message{
Role: "assistant",
Content: "The answer is 42.",
},
FinishReason: "stop",
}},
},
},
}
gw, err := newTestGateway(t, config.Config{
Strategy: config.StrategyConfig{Mode: config.ModeSingle},
Targets: []config.Target{{VirtualKey: "test-provider"}},
MCPServers: []mcp.ServerConfig{{
Name: "test-mcp",
URL: mcpSrv.URL + "/mcp",
TimeoutSeconds: 5,
}},
})
if err != nil {
t.Fatalf("New() error: %v", err)
}
gw.RegisterProvider(mp)
// Wait for MCP init (tools/list handshake) to finish.
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
select {
case <-gw.MCPInitDone():
case <-ctx.Done():
t.Fatal("timed out waiting for MCP initialization")
}
// Route the request through the agentic loop.
resp, err := gw.Route(ctx, providers.Request{
Model: "test-model",
Messages: []providers.Message{{Role: "user", Content: "What is the answer?"}},
})
if err != nil {
t.Fatalf("Route() error: %v", err)
}
// The final response must be from the second provider call.
if resp.ID != "resp-2" {
t.Errorf("final response ID = %q, want resp-2", resp.ID)
}
// Provider must have been called exactly twice.
if got := mp.callCount(); got != 2 {
t.Fatalf("provider called %d times, want 2", got)
}
mp.mu.Lock()
requests := mp.requests
mp.mu.Unlock()
// First request must contain the "get_answer" tool injected by the gateway.
var toolFound bool
for _, tool := range requests[0].Tools {
if tool.Function.Name == "get_answer" {
toolFound = true
break
}
}
if !toolFound {
t.Error("first request: get_answer tool not injected")
}
// Second request must contain a tool-result message for tc-1 with content "42".
var toolMsg *providers.Message
for i := range requests[1].Messages {
if requests[1].Messages[i].Role == "tool" && requests[1].Messages[i].ToolCallID == "tc-1" {
toolMsg = &requests[1].Messages[i]
break
}
}
if toolMsg == nil {
t.Fatal("second request: missing tool-result message with ToolCallID=tc-1")
}
if toolMsg.Content != "42" {
t.Errorf("tool-result content = %q, want \"42\"", toolMsg.Content)
}
}
// TestGateway_RouteStream_MCPRedirect verifies that when MCP servers are
// configured, RouteStream routes through Route (running the full agentic loop)
// and wraps the final non-streaming response into a single-chunk channel.
func TestGateway_RouteStream_MCPRedirect(t *testing.T) {
mcpSrv := newMCPTestServer(t)
defer mcpSrv.Close()
// Provider call 1 — returns a tool_call for "get_answer".
// Provider call 2 — returns the final text after seeing the tool result.
mp := &multiCallProvider{
name: "mock-mcp-stream",
models: []string{"gpt-4o"},
responses: []*providers.Response{
{
ID: "s1",
Model: "gpt-4o",
Choices: []providers.Choice{{
Message: providers.Message{
Role: "assistant",
ToolCalls: []providers.ToolCall{{
ID: "tc-stream-1",
Type: "function",
Function: providers.FunctionCall{
Name: "get_answer",
Arguments: `{"q":"test"}`,
},
}},
},
}},
},
{
ID: "s2",
Model: "gpt-4o",
Choices: []providers.Choice{{
Message: providers.Message{
Role: "assistant",
Content: "The answer is 42.",
},
FinishReason: "stop",
}},
},
},