-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmcpresolve_test.go
More file actions
1911 lines (1761 loc) · 69.4 KB
/
Copy pathmcpresolve_test.go
File metadata and controls
1911 lines (1761 loc) · 69.4 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 agenthooks
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"testing"
"time"
)
const testHelperEnv = "AGENTHOOKS_TEST_HELPER"
func TestMain(m *testing.M) {
name := strings.TrimSuffix(filepath.Base(os.Args[0]), filepath.Ext(os.Args[0]))
// An explicit helper role wins over the binary's name: the stand-in for a
// running Claude session is the same on-PATH copy the CLI harness uses, so
// that CLAUDE_PID resolves to a claude executable the way a real session's
// does. Dispatching on the name alone would turn that launcher into a
// one-shot CLI run.
if os.Getenv(testHelperEnv) == "claude-launch" {
_, _ = io.Copy(io.Discard, os.Stdin)
os.Exit(0)
}
if strings.EqualFold(name, "claude") {
fakeClaudeMain()
os.Exit(0)
}
if strings.EqualFold(name, "codex") {
fakeCodexMain()
os.Exit(0)
}
switch os.Getenv(testHelperEnv) {
case "fake-claude":
fakeClaudeMain()
os.Exit(0)
case "agenthooks-main":
if path := os.Getenv("AGENTHOOKS_TEST_MAIN_READY"); path != "" {
_ = os.WriteFile(path, []byte("ready"), 0o600)
}
r := quietRunner(WithDedupDir(os.Getenv("AGENTHOOKS_TEST_STATE_DIR")))
if path := os.Getenv("AGENTHOOKS_TEST_MCP_RESULT"); path != "" {
r.OnToolPre(func(_ context.Context, ev *ToolPreEvent) (ToolPreDecision, error) {
if ev.Tool.MCP != nil {
_ = os.WriteFile(path, []byte(ev.Tool.MCP.URL), 0o600)
}
return NoDecision(), nil
})
}
Main(r)
}
os.Exit(m.Run())
}
func fakeCodexMain() {
if path := os.Getenv("AGENTHOOKS_FAKE_CODEX_COUNT"); path != "" {
f, _ := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)
if f != nil {
_, _ = f.WriteString("x\n")
_ = f.Close()
}
}
if path := os.Getenv("AGENTHOOKS_FAKE_CODEX_CALLS"); path != "" {
cwd, _ := os.Getwd()
data, _ := json.Marshal(fakeClaudeCall{Args: os.Args[1:], Dir: cwd})
f, _ := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)
if f != nil {
_, _ = f.Write(append(data, '\n'))
_ = f.Close()
}
}
if gate := os.Getenv("AGENTHOOKS_FAKE_CODEX_GATE"); gate != "" {
for {
if _, err := os.Stat(gate); err == nil {
break
}
time.Sleep(10 * time.Millisecond)
}
}
if data, err := os.ReadFile(os.Getenv("AGENTHOOKS_FAKE_CODEX_OUTPUT")); err == nil {
_, _ = os.Stdout.Write(data)
}
}
func fakeClaudeMain() {
if path := os.Getenv("AGENTHOOKS_FAKE_CLAUDE_COUNT"); path != "" {
f, _ := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)
if f != nil {
_, _ = f.WriteString("x\n")
_ = f.Close()
}
}
if path := os.Getenv("AGENTHOOKS_FAKE_CLAUDE_CALLS"); path != "" {
cwd, _ := os.Getwd()
data, _ := json.Marshal(fakeClaudeCall{Args: os.Args[1:], Dir: cwd})
f, _ := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)
if f != nil {
_, _ = f.Write(append(data, '\n'))
_ = f.Close()
}
}
if gate := os.Getenv("AGENTHOOKS_FAKE_CLAUDE_GATE"); gate != "" {
for {
if _, err := os.Stat(gate); err == nil {
break
}
time.Sleep(10 * time.Millisecond)
}
}
if data, err := os.ReadFile(os.Getenv("AGENTHOOKS_FAKE_CLAUDE_OUTPUT")); err == nil {
_, _ = os.Stdout.Write(data)
}
if data, err := os.ReadFile(os.Getenv("AGENTHOOKS_FAKE_CLAUDE_EXIT_FILE")); err == nil {
if code, _ := strconv.Atoi(strings.TrimSpace(string(data))); code != 0 {
os.Exit(code)
}
}
}
func writeConfig(t *testing.T, path, content string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
// isolateHome points HOME, the per-provider config-dir overrides, and PATH
// away from the developer's real config files and `claude` binary so
// resolution only sees what the test set up.
func isolateHome(t *testing.T) string {
t.Helper()
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home) // os.UserHomeDir reads this on windows
t.Setenv("CODEX_HOME", filepath.Join(home, ".codex"))
t.Setenv("KIMI_CODE_HOME", filepath.Join(home, ".kimi-code"))
t.Setenv("COPILOT_HOME", filepath.Join(home, ".copilot"))
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
t.Setenv("PATH", filepath.Join(home, "bin-empty"))
// Claude launch context is recovered from CLAUDE_PID, so a suite run from
// inside a live Claude Code session would otherwise inherit that session's
// pid and probe the developer's real CLI instead of the fake. Tests that
// want a launch context call startClaudeLaunch, which sets its own.
t.Setenv("CLAUDE_PID", "")
return home
}
// mcpTestRunner isolates the on-disk state dir so launch-context mcp-list
// caches can't leak across tests or into the real temp dir.
func mcpTestRunner(t *testing.T, opts ...Option) *Runner {
t.Helper()
return quietRunner(append([]Option{WithDedupDir(t.TempDir())}, opts...)...)
}
type fakeClaude struct {
countFile string
outputFile string
callsFile string
exitFile string
gateFile string
}
type fakeCodex struct {
countFile string
outputFile string
callsFile string
gateFile string
}
type fakeClaudeCall struct {
Args []string `json:"args"`
Dir string `json:"dir"`
}
// installFakeClaude copies the current test binary onto PATH as `claude`.
// TestMain turns that copy into a cross-platform deterministic CLI harness.
func installFakeClaude(t *testing.T, output string) fakeClaude {
t.Helper()
binDir := t.TempDir()
name := "claude"
if strings.EqualFold(filepath.Ext(os.Args[0]), ".exe") {
name += ".exe"
}
src, err := os.Executable()
if err != nil {
t.Fatal(err)
}
dst := filepath.Join(binDir, name)
data, err := os.ReadFile(src)
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(dst, data, 0o755); err != nil {
t.Fatal(err)
}
h := fakeClaude{
countFile: filepath.Join(binDir, "count"),
outputFile: filepath.Join(binDir, "output"),
callsFile: filepath.Join(binDir, "calls"),
exitFile: filepath.Join(binDir, "exit"),
gateFile: filepath.Join(binDir, "gate"),
}
writeConfig(t, h.outputFile, output)
t.Setenv("PATH", binDir)
t.Setenv(testHelperEnv, "fake-claude")
t.Setenv("AGENTHOOKS_FAKE_CLAUDE_COUNT", h.countFile)
t.Setenv("AGENTHOOKS_FAKE_CLAUDE_OUTPUT", h.outputFile)
t.Setenv("AGENTHOOKS_FAKE_CLAUDE_CALLS", h.callsFile)
t.Setenv("AGENTHOOKS_FAKE_CLAUDE_EXIT_FILE", h.exitFile)
return h
}
func installFakeCodex(t *testing.T, output string) fakeCodex {
t.Helper()
binDir := t.TempDir()
name := "codex"
if strings.EqualFold(filepath.Ext(os.Args[0]), ".exe") {
name += ".exe"
}
src, err := os.Executable()
if err != nil {
t.Fatal(err)
}
dst := filepath.Join(binDir, name)
data, err := os.ReadFile(src)
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(dst, data, 0o755); err != nil {
t.Fatal(err)
}
h := fakeCodex{
countFile: filepath.Join(binDir, "count"),
outputFile: filepath.Join(binDir, "output"),
callsFile: filepath.Join(binDir, "calls"),
gateFile: filepath.Join(binDir, "gate"),
}
writeConfig(t, h.outputFile, output)
t.Setenv("PATH", binDir)
t.Setenv("AGENTHOOKS_FAKE_CODEX_COUNT", h.countFile)
t.Setenv("AGENTHOOKS_FAKE_CODEX_OUTPUT", h.outputFile)
t.Setenv("AGENTHOOKS_FAKE_CODEX_CALLS", h.callsFile)
return h
}
func (h fakeCodex) calls(t *testing.T) []fakeClaudeCall {
t.Helper()
return readFakeCalls(t, h.callsFile)
}
func agenthooksMainCommand(t *testing.T, stateDir, resultFile, readyFile string, payload []byte) *exec.Cmd {
t.Helper()
return agenthooksMainCommandForProvider(t, ProviderClaudeCode, nil, stateDir, resultFile, readyFile, payload)
}
func agenthooksMainCommandForProvider(t *testing.T, provider Provider, extraArgs []string, stateDir, resultFile, readyFile string, payload []byte) *exec.Cmd {
t.Helper()
exe, err := os.Executable()
if err != nil {
t.Fatal(err)
}
args := []string{"agenthooks", "run", "--provider=" + string(provider)}
args = append(args, extraArgs...)
cmd := exec.Command(exe, args...)
cmd.Env = append(withoutEnv(os.Environ(), testHelperEnv),
testHelperEnv+"=agenthooks-main",
"AGENTHOOKS_TEST_STATE_DIR="+stateDir,
"AGENTHOOKS_TEST_MCP_RESULT="+resultFile,
"AGENTHOOKS_TEST_MAIN_READY="+readyFile,
)
cmd.Stdin = strings.NewReader(string(payload))
return cmd
}
func codexHookPayload(t *testing.T, launch codexLaunchContext, payload []byte) []byte {
t.Helper()
data, err := json.Marshal(launch)
if err != nil {
t.Fatal(err)
}
return append(append(data, '\n'), payload...)
}
func waitForTestFile(t *testing.T, path string) {
t.Helper()
deadline := time.Now().Add(10 * time.Second)
for time.Now().Before(deadline) {
if _, err := os.Stat(path); err == nil {
return
}
time.Sleep(10 * time.Millisecond)
}
t.Fatalf("timed out waiting for %s", path)
}
func fakeClaudeCLI(t *testing.T, output string) string {
t.Helper()
return installFakeClaude(t, output).countFile
}
func cliRuns(t *testing.T, countFile string) int {
t.Helper()
data, err := os.ReadFile(countFile)
if err != nil {
return 0
}
return strings.Count(string(data), "x")
}
func (h fakeClaude) calls(t *testing.T) []fakeClaudeCall {
t.Helper()
return readFakeCalls(t, h.callsFile)
}
func readFakeCalls(t *testing.T, path string) []fakeClaudeCall {
t.Helper()
f, err := os.Open(path)
if os.IsNotExist(err) {
return nil
}
if err != nil {
t.Fatal(err)
}
defer f.Close()
var calls []fakeClaudeCall
s := bufio.NewScanner(f)
for s.Scan() {
var call fakeClaudeCall
if err := json.Unmarshal(s.Bytes(), &call); err != nil {
t.Fatal(err)
}
calls = append(calls, call)
}
if err := s.Err(); err != nil {
t.Fatal(err)
}
return calls
}
func startClaudeLaunch(t *testing.T, projectDir string, args ...string) {
t.Helper()
// Launch the copy installed on PATH as `claude`, not the raw test binary:
// resolution recovers the CLI from CLAUDE_PID's executable, and a real
// session's CLAUDE_PID is always the claude binary itself. Both are copies
// of this test binary, so the helper behaves identically either way.
exe, err := exec.LookPath("claude")
if err != nil {
exe, err = os.Executable()
}
if err != nil {
t.Fatal(err)
}
cmd := exec.Command(exe, args...)
cmd.Env = append(withoutEnv(os.Environ(), testHelperEnv), testHelperEnv+"=claude-launch")
stdin, err := cmd.StdinPipe()
if err != nil {
t.Fatal(err)
}
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_ = stdin.Close()
_ = cmd.Wait()
})
t.Setenv("CLAUDE_PID", strconv.Itoa(cmd.Process.Pid))
t.Setenv("CLAUDE_PROJECT_DIR", projectDir)
}
func withoutEnv(env []string, name string) []string {
prefix := name + "="
out := make([]string, 0, len(env))
for _, kv := range env {
if !strings.HasPrefix(kv, prefix) {
out = append(out, kv)
}
}
return out
}
func mcpToolPre(p Provider, cwd, name string) *ToolPreEvent {
s := SessionInfo{ID: "sess-mcp", CWD: cwd}
return &ToolPreEvent{
Event: Event{Provider: p, Kind: KindToolPre, Session: s},
Tool: makeToolCall(s, name, "tid-1", nil, nil),
}
}
func TestResolveMCPClaudeProjectConfig(t *testing.T) {
isolateHome(t)
cwd := t.TempDir()
writeConfig(t, filepath.Join(cwd, ".mcp.json"), `{"mcpServers":{
"github": {"url": "https://api.example.com/mcp"},
"local (stdio)": {"command": "npx", "args": ["-y", "srv"]}
}}`)
r := mcpTestRunner(t)
ev := mcpToolPre(ProviderClaudeCode, cwd, "mcp__github__create_issue")
r.resolveMCP(ev)
if ev.Tool.MCP.URL != "https://api.example.com/mcp" || !ev.Tool.MCP.FromConfig {
t.Errorf("url not resolved: %+v", ev.Tool.MCP)
}
if ev.Tool.MCP.Server != "github" || ev.Tool.MCP.Tool != "create_issue" {
t.Errorf("identity clobbered: %+v", ev.Tool.MCP)
}
// "local (stdio)" sanitizes to prefix local_stdio (spaces -> _, parens dropped).
ev = mcpToolPre(ProviderClaudeCode, cwd, "mcp__local_stdio__run")
r.resolveMCP(ev)
if ev.Tool.MCP.Command != "npx -y srv" || ev.Tool.MCP.URL != "" {
t.Errorf("stdio command not resolved: %+v", ev.Tool.MCP)
}
}
func TestResolveMCPClaudeScopePrecedence(t *testing.T) {
home := isolateHome(t)
cwd := "/work/proj" // no .mcp.json on disk; only ~/.claude.json scopes apply
writeConfig(t, filepath.Join(home, ".claude.json"), `{
"mcpServers": {"linear": {"url": "https://user.example.com/mcp"}},
"projects": {"/work/proj": {"mcpServers": {"linear": {"url": "https://local.example.com/mcp"}}}}
}`)
ev := mcpToolPre(ProviderClaudeCode, cwd, "mcp__linear__list_issues")
mcpTestRunner(t).resolveMCP(ev)
if ev.Tool.MCP.URL != "https://local.example.com/mcp" {
t.Errorf("local scope must win over user scope: %+v", ev.Tool.MCP)
}
}
func TestResolveMCPClaudeAmbiguousPrefix(t *testing.T) {
isolateHome(t)
cwd := t.TempDir()
// Both names sanitize to the prefix "a_b": attribution is ambiguous.
writeConfig(t, filepath.Join(cwd, ".mcp.json"), `{"mcpServers":{
"a b": {"url": "https://one.example.com"},
"a_b": {"url": "https://two.example.com"}
}}`)
ev := mcpToolPre(ProviderClaudeCode, cwd, "mcp__a_b__tool")
mcpTestRunner(t).resolveMCP(ev)
if ev.Tool.MCP.URL != "" || ev.Tool.MCP.FromConfig {
t.Errorf("ambiguous match must stay empty: %+v", ev.Tool.MCP)
}
}
func TestResolveMCPCodex(t *testing.T) {
home := isolateHome(t)
writeConfig(t, filepath.Join(home, ".codex", "config.toml"), `
model = "gpt-5" # unrelated top-level key
[mcp_servers.int-linear] # sanitizes to int_linear
command = "npx"
args = [
"-y",
"linear-mcp",
]
[mcp_servers."foo--bar"]
url = "https://foo.example.com/mcp"
[mcp_servers.off]
url = "https://off.example.com"
enabled = false
[mcp_servers.int-linear.env]
url = "https://red-herring.example.com"
`)
r := mcpTestRunner(t)
ev := mcpToolPre(ProviderCodex, "", "mcp__int_linear__create_issue")
r.resolveMCP(ev)
if ev.Tool.MCP.Command != "npx -y linear-mcp" || ev.Tool.MCP.URL != "" || !ev.Tool.MCP.FromConfig {
t.Errorf("codex stdio not resolved: %+v", ev.Tool.MCP)
}
// "foo--bar" sanitizes to "foo__bar": the naive first-"__" split yields
// Server "foo" / Tool "bar__list"; longest-prefix matching repairs it.
ev = mcpToolPre(ProviderCodex, "", "mcp__foo__bar__list")
r.resolveMCP(ev)
if ev.Tool.MCP.Server != "foo__bar" || ev.Tool.MCP.Tool != "list" {
t.Errorf("codex split not repaired: %+v", ev.Tool.MCP)
}
if ev.Tool.MCP.URL != "https://foo.example.com/mcp" {
t.Errorf("codex url not resolved: %+v", ev.Tool.MCP)
}
ev = mcpToolPre(ProviderCodex, "", "mcp__off__anything")
r.resolveMCP(ev)
if ev.Tool.MCP.URL != "" {
t.Errorf("disabled server must not resolve: %+v", ev.Tool.MCP)
}
}
func TestParseCodexLaunchArgs(t *testing.T) {
ctx := parseCodexLaunchArgs([]string{
"codex", "-c", "one=1", "-ctwo=2", "--config=three=3", "-p", "old",
"exec", "--profile=new", "--enable", "plugin_mcp", "--disable=legacy", "--ignore-user-config", "--", "--config=ignored",
}, "/work")
want := []string{"--config", "one=1", "--config", "two=2", "--config", "three=3", "--enable", "plugin_mcp", "--disable", "legacy"}
if ctx.CWD != "/work" || ctx.Executable != "codex" || ctx.Profile != "new" || !ctx.Unreplayable || strings.Join(ctx.Overrides, "\x00") != strings.Join(want, "\x00") {
t.Fatalf("Codex launch context = %+v", ctx)
}
wantReplay := append([]string{"--profile", "new"}, want...)
if strings.Join(ctx.replayArgs(), "\x00") != strings.Join(wantReplay, "\x00") {
t.Fatalf("Codex replay args = %#v", ctx.replayArgs())
}
}
func TestParseCodexMCPList(t *testing.T) {
entries := parseCodexMCPList([]byte(`[
{"name":"local","enabled":true,"transport":{"type":"stdio","command":"npx","args":["-y","srv"],"env":{"TOKEN":"secret"}}},
{"name":"remote","enabled":true,"transport":{"type":"streamable_http","url":"https://example.com/mcp","http_headers":{"Authorization":"secret"}}},
{"name":"off","enabled":false,"transport":{"type":"streamable_http","url":"https://off.example.com"}},
{"name":"unknown","enabled":true,"transport":{"type":"tcp","url":"tcp://localhost"}}
]`))
if len(entries) != 2 || entries[0].Name != "local" || entries[0].Command != "npx -y srv" ||
entries[1].Name != "remote" || entries[1].URL != "https://example.com/mcp" {
t.Fatalf("Codex MCP list = %+v", entries)
}
if _, ok := decodeCodexMCPList([]byte(`not-json`)); ok {
t.Fatal("malformed Codex inventory reported success")
}
}
func TestResolveMCPCodexLaunchInventoryWins(t *testing.T) {
home := isolateHome(t)
project := t.TempDir()
writeConfig(t, filepath.Join(home, ".codex", "config.toml"), `[mcp_servers.shared]
url = "https://disk.example.com/mcp"
`)
fake := installFakeCodex(t, `[{"name":"shared","enabled":true,"transport":{"type":"streamable_http","url":"https://launch.example.com/mcp"}}]`)
launch := parseCodexLaunchArgs([]string{"codex", "-c", `mcp_servers.shared.url="https://launch.example.com/mcp"`}, project)
launch.Executable = "" // Missing argv recovery falls back to PATH's codex.
r := mcpTestRunner(t)
r.codexLaunchContext = &launch
ev := mcpToolPre(ProviderCodex, project, "mcp__shared__run")
r.resolveMCP(ev)
if ev.Tool.MCP.URL != "https://launch.example.com/mcp" || !ev.Tool.MCP.FromConfig {
t.Fatalf("Codex launch inventory = %+v", ev.Tool.MCP)
}
calls := fake.calls(t)
want := append(launch.replayArgs(), "mcp", "list", "--json")
if len(calls) != 1 || strings.Join(calls[0].Args, "\x00") != strings.Join(want, "\x00") || calls[0].Dir != project {
t.Fatalf("Codex inventory call = %+v, want args %#v dir %q", calls, want, project)
}
}
func TestResolveMCPCodexFailedProbeFallsBackToDirectConfig(t *testing.T) {
home := isolateHome(t)
project := t.TempDir()
writeConfig(t, filepath.Join(home, ".codex", "config.toml"), `[mcp_servers.direct]
url = "https://direct.example.com/mcp"
`)
launch := parseCodexLaunchArgs([]string{"codex"}, project)
launch.Executable = filepath.Join(project, "missing-codex")
r := mcpTestRunner(t)
r.codexLaunchContext = &launch
ev := mcpToolPre(ProviderCodex, project, "mcp__direct__run")
r.resolveMCP(ev)
if ev.Tool.MCP.URL != "https://direct.example.com/mcp" || !ev.Tool.MCP.FromConfig {
t.Fatalf("Codex direct fallback = %+v", ev.Tool.MCP)
}
}
func TestResolveMCPCodexSuccessfulEmptyInventoryStaysUnknown(t *testing.T) {
home := isolateHome(t)
project := t.TempDir()
writeConfig(t, filepath.Join(home, ".codex", "config.toml"), `[mcp_servers.direct]
url = "https://direct.example.com/mcp"
`)
installFakeCodex(t, `[]`)
launch := parseCodexLaunchArgs([]string{"codex"}, project)
launch.Executable = ""
r := mcpTestRunner(t)
r.codexLaunchContext = &launch
ev := mcpToolPre(ProviderCodex, project, "mcp__direct__run")
r.resolveMCP(ev)
if ev.Tool.MCP.URL != "" || ev.Tool.MCP.Command != "" || ev.Tool.MCP.FromConfig {
t.Fatalf("successful empty Codex inventory fell back to disk: %+v", ev.Tool.MCP)
}
}
func TestResolveMCPCodexUnreplayableLaunchStaysUnknown(t *testing.T) {
home := isolateHome(t)
project := t.TempDir()
writeConfig(t, filepath.Join(home, ".codex", "config.toml"), `[mcp_servers.shared]
url = "https://disk.example.com/mcp"
`)
launch := parseCodexLaunchArgs([]string{"codex", "--ignore-user-config"}, project)
r := mcpTestRunner(t)
r.codexLaunchContext = &launch
ev := mcpToolPre(ProviderCodex, project, "mcp__shared__run")
r.resolveMCP(ev)
if ev.Tool.MCP.URL != "" || ev.Tool.MCP.Command != "" || ev.Tool.MCP.FromConfig {
t.Fatalf("unreplayable Codex launch resolved from disk: %+v", ev.Tool.MCP)
}
}
func TestCodexSessionStartWarmsInventoryInBackground(t *testing.T) {
isolateHome(t)
project := t.TempDir()
stateDir := t.TempDir()
resultFile := filepath.Join(t.TempDir(), "result")
readyFile := filepath.Join(t.TempDir(), "ready")
fake := installFakeCodex(t, `[{"name":"background","enabled":true,"transport":{"type":"streamable_http","url":"https://background.example.com/mcp"}}]`)
t.Setenv("AGENTHOOKS_FAKE_CODEX_GATE", fake.gateFile)
t.Cleanup(func() { _ = os.WriteFile(fake.gateFile, []byte("release"), 0o600) })
launch := parseCodexLaunchArgs([]string{"codex", "-c", `mcp_servers.background.url="https://background.example.com/mcp"`}, project)
extra := []string{codexLaunchContextFlag}
sessionPayload := []byte(fmt.Sprintf(
`{"hook_event_name":"SessionStart","session_id":"s-background","cwd":%q,"source":"startup"}`,
project,
))
session := agenthooksMainCommandForProvider(t, ProviderCodex, extra, stateDir, resultFile, readyFile,
codexHookPayload(t, launch, sessionPayload))
if err := session.Start(); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = session.Process.Kill() })
sessionDone := make(chan error, 1)
go func() { sessionDone <- session.Wait() }()
select {
case err := <-sessionDone:
if err != nil {
t.Fatalf("Codex SessionStart failed: %v", err)
}
case <-time.After(10 * time.Second):
_ = session.Process.Kill()
t.Fatal("Codex SessionStart waited for blocked inventory discovery")
}
waitForTestFile(t, fake.countFile)
_ = os.Remove(readyFile)
prePayload := []byte(fmt.Sprintf(
`{"hook_event_name":"PreToolUse","session_id":"s-background","cwd":%q,"tool_name":"mcp__background__run","tool_input":{}}`,
project,
))
pre := agenthooksMainCommandForProvider(t, ProviderCodex, extra, stateDir, resultFile, readyFile,
codexHookPayload(t, launch, prePayload))
if err := pre.Start(); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = pre.Process.Kill() })
preDone := make(chan error, 1)
go func() { preDone <- pre.Wait() }()
waitForTestFile(t, readyFile)
select {
case err := <-preDone:
t.Fatalf("Codex MCP hook did not wait for in-flight inventory: %v", err)
case <-time.After(250 * time.Millisecond):
}
writeConfig(t, fake.gateFile, "release")
select {
case err := <-preDone:
if err != nil {
t.Fatalf("Codex MCP hook failed after inventory arrived: %v", err)
}
case <-time.After(10 * time.Second):
_ = pre.Process.Kill()
t.Fatal("Codex MCP hook did not consume background inventory")
}
data, err := os.ReadFile(resultFile)
if err != nil {
t.Fatal(err)
}
if string(data) != "https://background.example.com/mcp" || cliRuns(t, fake.countFile) != 1 {
t.Fatalf("Codex background inventory result=%q probes=%d", data, cliRuns(t, fake.countFile))
}
}
func TestCodexAsyncHookPreservesLaunchContext(t *testing.T) {
isolateHome(t)
project := t.TempDir()
resultFile := filepath.Join(t.TempDir(), "result")
readyFile := filepath.Join(t.TempDir(), "ready")
installFakeCodex(t, `[{"name":"async","enabled":true,"transport":{"type":"streamable_http","url":"https://async.example.com/mcp"}}]`)
launch := parseCodexLaunchArgs([]string{"codex", "-c", `mcp_servers.async.url="https://async.example.com/mcp"`}, project)
payload := []byte(fmt.Sprintf(
`{"hook_event_name":"PreToolUse","session_id":"s-async","cwd":%q,"tool_name":"mcp__async__run","tool_input":{}}`,
project,
))
cmd := agenthooksMainCommandForProvider(t, ProviderCodex,
[]string{codexLaunchContextFlag, "--async"}, t.TempDir(), resultFile, readyFile,
codexHookPayload(t, launch, payload))
if err := cmd.Run(); err != nil {
t.Fatal(err)
}
waitForTestFile(t, resultFile)
data, err := os.ReadFile(resultFile)
if err != nil || string(data) != "https://async.example.com/mcp" {
t.Fatalf("async Codex transport=%q err=%v", data, err)
}
}
func TestCodexInvalidLaunchContextPreservesHookPayload(t *testing.T) {
home := isolateHome(t)
project := t.TempDir()
writeConfig(t, filepath.Join(home, ".codex", "config.toml"), `[mcp_servers.direct]
url = "https://direct.example.com/mcp"
`)
resultFile := filepath.Join(t.TempDir(), "result")
payload := []byte(fmt.Sprintf(
`{"hook_event_name":"PreToolUse","session_id":"s-invalid","cwd":%q,"tool_name":"mcp__direct__run","tool_input":{}}`,
project,
))
input := append([]byte("not-json\n"), payload...)
cmd := agenthooksMainCommandForProvider(t, ProviderCodex,
[]string{codexLaunchContextFlag}, t.TempDir(), resultFile, "", input)
if err := cmd.Run(); err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(resultFile)
if err != nil || string(data) != "https://direct.example.com/mcp" {
t.Fatalf("transport after invalid context=%q err=%v", data, err)
}
}
func TestResolveMCPCursor(t *testing.T) {
home := isolateHome(t)
cwd := t.TempDir()
writeConfig(t, filepath.Join(cwd, ".cursor", "mcp.json"),
`{"mcpServers":{"shortcut":{"url":"https://mcp.shortcut.com/sse"}}}`)
r := mcpTestRunner(t)
// MCP:<tool> has no server identity; a single configured server is the
// only sound attribution.
ev := mcpToolPre(ProviderCursor, cwd, "MCP:create_story")
r.resolveMCP(ev)
if ev.Tool.MCP.URL != "https://mcp.shortcut.com/sse" || ev.Tool.MCP.Server != "shortcut" || !ev.Tool.MCP.FromConfig {
t.Errorf("single-server cursor attribution failed: %+v", ev.Tool.MCP)
}
// A second server (user scope) makes attribution ambiguous.
writeConfig(t, filepath.Join(home, ".cursor", "mcp.json"),
`{"mcpServers":{"other":{"command":"other-mcp"}}}`)
ev = mcpToolPre(ProviderCursor, cwd, "MCP:create_story")
ev.Tool.MCP.Server = "shortcut"
r.resolveMCP(ev)
if ev.Tool.MCP.URL != "https://mcp.shortcut.com/sse" || ev.Tool.MCP.Server != "shortcut" || !ev.Tool.MCP.FromConfig {
t.Errorf("payload server identity was not matched: %+v", ev.Tool.MCP)
}
ev = mcpToolPre(ProviderCursor, cwd, "MCP:create_story")
r.resolveMCP(ev)
if ev.Tool.MCP.URL != "" || ev.Tool.MCP.FromConfig {
t.Errorf("multi-server cursor attribution must stay empty: %+v", ev.Tool.MCP)
}
}
func TestResolveMCPPayloadTransportWins(t *testing.T) {
isolateHome(t)
cwd := t.TempDir()
writeConfig(t, filepath.Join(cwd, ".cursor", "mcp.json"),
`{"mcpServers":{"shortcut":{"url":"https://from-config.example.com"}}}`)
ev := mcpToolPre(ProviderCursor, cwd, "MCP:create_story")
ev.Tool.MCP.URL = "https://from-payload.example.com" // as beforeMCPExecution ships it
mcpTestRunner(t).resolveMCP(ev)
if ev.Tool.MCP.URL != "https://from-payload.example.com" || ev.Tool.MCP.FromConfig {
t.Errorf("payload-borne transport must never be overwritten: %+v", ev.Tool.MCP)
}
}
func TestResolveMCPGeminiSplitRepair(t *testing.T) {
isolateHome(t)
cwd := t.TempDir()
writeConfig(t, filepath.Join(cwd, ".gemini", "settings.json"),
`{"mcpServers":{"my_srv":{"httpUrl":"https://g.example.com/mcp"}}}`)
// Naive single-underscore split yields Server "my" / Tool "srv_do";
// matching against the configured name repairs it (quirk #15).
ev := mcpToolPre(ProviderGemini, cwd, "mcp_my_srv_do")
mcpTestRunner(t).resolveMCP(ev)
if ev.Tool.MCP.Server != "my_srv" || ev.Tool.MCP.Tool != "do" || ev.Tool.MCP.URL != "https://g.example.com/mcp" {
t.Errorf("gemini split not repaired: %+v", ev.Tool.MCP)
}
}
func TestResolveMCPGeminiPayloadContextWins(t *testing.T) {
isolateHome(t)
cwd := t.TempDir()
writeConfig(t, filepath.Join(cwd, ".gemini", "settings.json"),
`{"mcpServers":{"my_srv":{"httpUrl":"https://wrong.example.com/mcp"}}}`)
raw := []byte(fmt.Sprintf(`{
"session_id":"s","cwd":%q,"hook_event_name":"BeforeTool","tool_name":"mcp_my_srv_do","tool_input":{},
"mcp_context":{"server_name":"my_srv","tool_name":"do","tcp":"localhost:9000"}
}`, cwd))
typed, err := decodeGemini(VariantUnknown, DetectionConfig, time.Now(), raw)
if err != nil {
t.Fatal(err)
}
ev := typed.(*ToolPreEvent)
mcpTestRunner(t).resolveMCP(ev)
if ev.Tool.MCP == nil || ev.Tool.MCP.Server != "my_srv" || ev.Tool.MCP.Tool != "do" ||
ev.Tool.MCP.URL != "" || ev.Tool.MCP.Command != "" || ev.Tool.MCP.FromConfig {
t.Fatalf("payload MCP context was overwritten by config: %+v", ev.Tool.MCP)
}
}
func TestResolveMCPGeminiNullContextFallsBackToConfig(t *testing.T) {
isolateHome(t)
cwd := t.TempDir()
writeConfig(t, filepath.Join(cwd, ".gemini", "settings.json"),
`{"mcpServers":{"my_srv":{"httpUrl":"https://g.example.com/mcp"}}}`)
raw := []byte(fmt.Sprintf(`{
"session_id":"s","cwd":%q,"hook_event_name":"BeforeTool","tool_name":"mcp_my_srv_do","tool_input":{},
"mcp_context":null
}`, cwd))
typed, err := decodeGemini(VariantUnknown, DetectionConfig, time.Now(), raw)
if err != nil {
t.Fatal(err)
}
ev := typed.(*ToolPreEvent)
mcpTestRunner(t).resolveMCP(ev)
if ev.Tool.MCP.URL != "https://g.example.com/mcp" || !ev.Tool.MCP.FromConfig {
t.Fatalf("null Gemini MCP context did not fall back to config: %+v", ev.Tool.MCP)
}
}
func TestResolveMCPKimi(t *testing.T) {
home := isolateHome(t)
cwd := t.TempDir()
r := mcpTestRunner(t)
// Mirrors the live probe against kimi-code 0.22.2: project-scoped
// .kimi-code/mcp.json, hyphenated server name kept verbatim in
// mcp__test-echo__echo.
writeConfig(t, filepath.Join(cwd, ".kimi-code", "mcp.json"),
`{"mcpServers":{"test-echo":{"command":"npx","args":["-y","@modelcontextprotocol/server-everything"]}}}`)
ev := mcpToolPre(ProviderKimi, cwd, "mcp__test-echo__echo")
r.resolveMCP(ev)
if ev.Tool.MCP.Command != "npx -y @modelcontextprotocol/server-everything" || !ev.Tool.MCP.FromConfig {
t.Errorf("kimi project-scope transport not resolved: %+v", ev.Tool.MCP)
}
if ev.Tool.MCP.Server != "test-echo" || ev.Tool.MCP.Tool != "echo" {
t.Errorf("kimi hyphenated split wrong: %+v", ev.Tool.MCP)
}
// KIMI_CODE_HOME (isolateHome pins it under the temp home).
writeConfig(t, filepath.Join(home, ".kimi-code", "mcp.json"),
`{"mcpServers":{"github":{"url":"https://kimi.example.com/mcp"}}}`)
ev = mcpToolPre(ProviderKimi, "", "mcp__github__create_issue")
r.resolveMCP(ev)
if ev.Tool.MCP.URL != "https://kimi.example.com/mcp" {
t.Errorf("kimi user-scope transport not resolved: %+v", ev.Tool.MCP)
}
// Legacy kimi-cli fallback path.
writeConfig(t, filepath.Join(home, ".kimi", "mcp.json"),
`{"mcpServers":{"legacy":{"url":"https://legacy.example.com/mcp"}}}`)
ev = mcpToolPre(ProviderKimi, "", "mcp__legacy__x")
r.resolveMCP(ev)
if ev.Tool.MCP.URL != "https://legacy.example.com/mcp" {
t.Errorf("legacy ~/.kimi fallback not read: %+v", ev.Tool.MCP)
}
}
func TestResolveMCPOpenCodeDetection(t *testing.T) {
isolateHome(t)
cwd := t.TempDir()
// Mirrors the live probe against opencode 1.17.8: MCP tools are named
// <server>_<tool> verbatim with no reserved prefix, so the codec cannot
// classify them — the config match performs detection too (quirk #28).
writeConfig(t, filepath.Join(cwd, "opencode.json"), `{
"mcp": {
"test-echo": {"type": "local", "command": ["npx", "-y", "@modelcontextprotocol/server-everything"]},
"tracker": {"type": "remote", "url": "https://tracker.example.com/mcp"},
"off": {"type": "remote", "url": "https://off.example.com", "enabled": false}
}
}`)
r := mcpTestRunner(t)
ev := mcpToolPre(ProviderOpenCode, cwd, "test-echo_echo")
if ev.Tool.MCP != nil || ev.Tool.Canonical == ToolMCP {
t.Fatalf("precondition: codec must not classify opencode MCP names: %+v", ev.Tool)
}
r.resolveMCP(ev)
if ev.Tool.MCP == nil || ev.Tool.Canonical != ToolMCP {
t.Fatalf("opencode MCP call not detected: %+v", ev.Tool)
}
if ev.Tool.MCP.Server != "test-echo" || ev.Tool.MCP.Tool != "echo" ||
ev.Tool.MCP.Command != "npx -y @modelcontextprotocol/server-everything" || !ev.Tool.MCP.FromConfig {
t.Errorf("opencode identity/transport wrong: %+v", ev.Tool.MCP)
}
ev = mcpToolPre(ProviderOpenCode, cwd, "tracker_list_issues")
r.resolveMCP(ev)
if ev.Tool.MCP == nil || ev.Tool.MCP.URL != "https://tracker.example.com/mcp" || ev.Tool.MCP.Tool != "list_issues" {
t.Errorf("opencode remote server wrong: %+v", ev.Tool.MCP)
}
// Disabled server: no detection, stays a plain tool.
ev = mcpToolPre(ProviderOpenCode, cwd, "off_anything")
r.resolveMCP(ev)
if ev.Tool.MCP != nil {
t.Errorf("disabled opencode server must not detect: %+v", ev.Tool.MCP)
}
// Native tool: untouched.
ev = mcpToolPre(ProviderOpenCode, cwd, "bash")
r.resolveMCP(ev)
if ev.Tool.MCP != nil || ev.Tool.Canonical != ToolShell {
t.Errorf("native opencode tool must stay native: %+v", ev.Tool)
}
}
func TestResolveMCPCopilotDetection(t *testing.T) {
home := isolateHome(t)
// Copilot names MCP tools <server>-<tool> verbatim with no reserved
// prefix (GitHub Copilot CLI 1.0.80), so — as with OpenCode — the config
// match performs detection as well as transport attach.
writeConfig(t, filepath.Join(home, ".copilot", "mcp-config.json"), `{
"mcpServers": {
"github": {"command": "npx", "args": ["-y", "@modelcontextprotocol/server-github"]},
"tracker": {"url": "https://tracker.example.com/mcp"}
}
}`)
r := mcpTestRunner(t)
ev := mcpToolPre(ProviderCopilot, "", "github-create_issue")
if ev.Tool.MCP != nil || ev.Tool.Canonical == ToolMCP {
t.Fatalf("precondition: codec must not classify copilot MCP names: %+v", ev.Tool)
}
r.resolveMCP(ev)
if ev.Tool.MCP == nil || ev.Tool.Canonical != ToolMCP {
t.Fatalf("copilot MCP call not detected: %+v", ev.Tool)
}
if ev.Tool.MCP.Server != "github" || ev.Tool.MCP.Tool != "create_issue" ||
ev.Tool.MCP.Command != "npx -y @modelcontextprotocol/server-github" || !ev.Tool.MCP.FromConfig {
t.Errorf("copilot identity/transport wrong: %+v", ev.Tool.MCP)
}
ev = mcpToolPre(ProviderCopilot, "", "tracker-list_issues")
r.resolveMCP(ev)
if ev.Tool.MCP == nil || ev.Tool.MCP.URL != "https://tracker.example.com/mcp" || ev.Tool.MCP.Tool != "list_issues" {
t.Errorf("copilot remote server wrong: %+v", ev.Tool.MCP)
}
// Hyphenated native tool with no matching server: stays native. This is
// the boundary that keeps the "-" separator usable at all.
ev = mcpToolPre(ProviderCopilot, "", "read-file")
r.resolveMCP(ev)
if ev.Tool.MCP != nil {
t.Errorf("unconfigured hyphenated native tool must not detect: %+v", ev.Tool.MCP)
}
ev = mcpToolPre(ProviderCopilot, "", "shell")
r.resolveMCP(ev)
if ev.Tool.MCP != nil || ev.Tool.Canonical != ToolShell {
t.Errorf("native copilot tool must stay native: %+v", ev.Tool)
}
}
// TestResolveMCPCopilotHyphenCollision pins the known false positive: with a
// server named "read" configured, a native "read-file" is indistinguishable
// from an MCP call by name alone and resolves as MCP. Copilot supplies no
// marker to break the tie, so this is accepted rather than fixed — the test
// exists so the behaviour changes deliberately, not by accident.
func TestResolveMCPCopilotHyphenCollision(t *testing.T) {
home := isolateHome(t)
writeConfig(t, filepath.Join(home, ".copilot", "mcp-config.json"), `{
"mcpServers": {"read": {"url": "https://read.example.com/mcp"}}
}`)
ev := mcpToolPre(ProviderCopilot, "", "read-file")
mcpTestRunner(t).resolveMCP(ev)
if ev.Tool.MCP == nil || ev.Tool.MCP.Server != "read" || ev.Tool.MCP.Tool != "file" {
t.Errorf("expected the documented hyphen collision, got: %+v", ev.Tool.MCP)
}
}
func TestResolveMCPCopilotLongestPrefixWins(t *testing.T) {
home := isolateHome(t)
// Both the server name and the tool name may contain "-", so the split is
// ambiguous; configured names match longest-first.
writeConfig(t, filepath.Join(home, ".copilot", "mcp-config.json"), `{
"mcpServers": {
"a": {"url": "https://short.example.com"},
"a-b": {"url": "https://long.example.com"}
}
}`)
ev := mcpToolPre(ProviderCopilot, "", "a-b-do")
mcpTestRunner(t).resolveMCP(ev)
if ev.Tool.MCP == nil || ev.Tool.MCP.Server != "a-b" || ev.Tool.MCP.Tool != "do" ||
ev.Tool.MCP.URL != "https://long.example.com" {
t.Errorf("longest-prefix match wrong: %+v", ev.Tool.MCP)
}
}
// TestResolveMCPCopilotProjectScope pins that Copilot's workspace configs are
// read and outrank the user-scope file, the way Copilot itself resolves them.
func TestResolveMCPCopilotProjectScope(t *testing.T) {
home := isolateHome(t)