Repository navigation
Expand file tree
/
Copy pathapp_mcp.go
More file actions
1395 lines (1330 loc) · 51.8 KB
/
Copy pathapp_mcp.go
File metadata and controls
1395 lines (1330 loc) · 51.8 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 main
// MCP: agents (Claude Code, Codex, Cursor, …) read bowel's state and, as
// the user's policy says (settings' mcpPolicy: ask, allow or deny), change
// it. The app serves the tools on a unix socket in its data folder, for
// this user only; `bowel mcp` (main.go) bridges an agent's stdio to it.
//
// Reading is always allowed. A change is shown to the user first, as the
// settings it would change, when the policy is ask; the dialog can let the
// rest of that connection through. Every change an agent asks for is kept
// in a short list the 设置 > MCP page shows.
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"os"
"path/filepath"
"reflect"
"slices"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/egoist/mygo"
"github.com/oboo/moho/internal/core"
"github.com/oboo/moho/internal/devnet"
"github.com/oboo/moho/internal/i18n"
"github.com/oboo/moho/internal/mcp"
"github.com/oboo/moho/internal/nowindow"
"github.com/oboo/moho/internal/routes"
"github.com/oboo/moho/internal/settings"
)
// mcpSocket is where the app serves MCP: in its data folder (on Windows,
// see app_socket.go), or, when that path is too long for a unix socket,
// in the temporary folder.
func mcpSocket(dataDir string) string { return mcpSocketIn(socketDir(dataDir)) }
// olderMCPSocket is where bowel 0.4.9 and before served it, "" when that
// is mcpSocket.
func olderMCPSocket(dataDir string) string {
return olderSocket(mcpSocket(dataDir), mcpSocketIn(dataDir))
}
func mcpSocketIn(dir string) string {
p := filepath.Join(dir, "mcp.sock")
if len(p) < 100 {
return p
}
return filepath.Join(os.TempDir(), fmt.Sprintf("bowel-%d-mcp.sock", os.Getuid()))
}
// mcpErr is why the server is not serving, "" while it is.
var mcpErr atomic.Pointer[string]
// serveMCP serves the tools until ctx is done.
func (a *App) serveMCP(ctx context.Context) {
dropOlderSocket(olderMCPSocket(a.dataDir))
l, err := mcp.Listen(mcpSocket(a.dataDir))
if err != nil {
log.Println("mcp:", err)
e := err.Error()
mcpErr.Store(&e)
return
}
mcpErr.Store(new(string))
a.mcpServer().Accept(ctx, l)
}
// mcpCommand is how an agent starts bowel's MCP server: this executable,
// with the argument "mcp". Screenshots replace it with the installed path.
var mcpCommand = func() string {
exe, err := os.Executable()
if err != nil {
return "bowel"
}
if p, err := filepath.EvalSymlinks(exe); err == nil {
exe = p
}
return exe
}
// runMCPBridge is `bowel mcp`: it carries the agent's stdio to the running
// app, opening the app first when it is not running. An app older than
// this command, which an update has not restarted yet, is reached where
// it serves.
func runMCPBridge() error {
data, err := mygo.App.Path(mygo.PathUserData)
if err != nil {
return err
}
paths := []string{mcpSocket(data)}
if p := olderMCPSocket(data); p != "" {
paths = append(paths, p)
}
return mcp.Bridge(paths, os.Stdin, os.Stdout, startOwnApp)
}
// startOwnApp opens the .app this executable belongs to, in the
// background. Outside a bundle (go run, mygo dev) there is nothing to open.
func startOwnApp() error {
exe, err := os.Executable()
if err != nil {
return err
}
exe, _ = filepath.EvalSymlinks(exe)
bundle := filepath.Dir(filepath.Dir(filepath.Dir(exe))) // X.app/Contents/MacOS/x
if !strings.HasSuffix(bundle, ".app") {
return errors.New("not inside an .app; start bowel first")
}
return nowindow.Command("open", "-g", bundle).Run()
}
// ---- Approval ----
// agentChange is one change an agent asked for, as the MCP page lists it.
type agentChange struct {
At time.Time
Client string
What words
// Outcome: "applied", "denied", "failed".
Outcome string
Error string
}
var agentLog struct {
mu sync.Mutex
list []agentChange // newest first
}
func (a *App) noteAgentChange(ch agentChange) {
agentLog.mu.Lock()
agentLog.list = append([]agentChange{ch}, agentLog.list...)
if len(agentLog.list) > 30 {
agentLog.list = agentLog.list[:30]
}
agentLog.mu.Unlock()
if u := a.uiRef(); u != nil {
u.settingsRedraw()
}
}
func agentChanges() []agentChange {
agentLog.mu.Lock()
defer agentLog.mu.Unlock()
return slices.Clone(agentLog.list)
}
// words are a few words in both languages, put in the interface's at the
// time they are shown.
type words struct{ zh, en string }
func (w words) String() string { return i18n.T(w.zh, w.en) }
// askAgent asks the user whether client may make the change what (detail
// says more). remember lets the rest of the connection through. Tests
// replace it.
var askAgent = func(ctx context.Context, client, what, detail string) (ok, remember bool, err error) {
askMu.Lock() // one dialog at a time
defer askMu.Unlock()
if err := ctx.Err(); err != nil {
return false, false, err
}
type answer struct {
r mygo.MessageResult
err error
}
ch := make(chan answer, 1)
go func() {
mygo.App.Focus() // from the menu bar, the dialog must come to the front
r, err := mygo.Dialog.Message(mygo.MessageOptions{
Type: mygo.MessageQuestion,
Message: fmt.Sprintf(i18n.T("%s 想修改 bowel:%s", "%s wants to change bowel: %s"), client, what),
Detail: detail,
Buttons: []string{i18n.T("允许", "Allow"), i18n.T("拒绝", "Deny")},
DefaultButton: 0, CancelButton: 1,
CheckboxLabel: i18n.T("这次连接里不再询问", "Don't ask again for this connection"),
})
ch <- answer{r, err}
}()
select {
case ans := <-ch:
if ans.err != nil {
return false, false, ans.err
}
return ans.r.Button == 0, ans.r.Button == 0 && ans.r.CheckboxChecked, nil
case <-ctx.Done(): // the agent gave up, or left
return false, false, ctx.Err()
}
}
var askMu sync.Mutex
var errDenied = errors.New("denied")
// approve lets a change through as the policy says, asking when it is ask.
func (a *App) approve(ctx context.Context, s *mcp.Session, what words, detail string) error {
if isLocal(s) { // the user's own command (app_cli.go): nothing to ask
return nil
}
switch a.settings.Get().Policy() {
case "allow":
return nil
case "deny":
a.noteAgentChange(agentChange{At: time.Now(), Client: s.Name(), What: what, Outcome: "denied"})
return errors.New(i18n.T("bowel 设置为不允许 agent 做变更(设置 > MCP)。请让用户自己修改,或请用户改这项设置。",
"bowel is set not to let agents make changes (Settings > MCP). Ask the user to make the change, or to change that setting."))
}
if s.Get("allowed") == true {
return nil
}
ok, remember, err := askAgent(ctx, s.Name(), what.String(), detail)
if err == nil && !ok {
err = errDenied
}
if err != nil {
a.noteAgentChange(agentChange{At: time.Now(), Client: s.Name(), What: what, Outcome: "denied"})
if errors.Is(err, errDenied) {
return errors.New(i18n.T("用户拒绝了这次变更。", "The user denied this change."))
}
return err
}
if remember {
s.Set("allowed", true)
}
return nil
}
// change is an approved action: it asks, runs do, and notes the outcome.
func (a *App) change(ctx context.Context, s *mcp.Session, what words, detail string, do func() error) error {
if err := a.approve(ctx, s, what, detail); err != nil {
return err
}
err := do()
if isLocal(s) { // the list is of what agents asked for
return err
}
ch := agentChange{At: time.Now(), Client: s.Name(), What: what, Outcome: "applied"}
if err != nil {
ch.Outcome, ch.Error = "failed", err.Error()
}
a.noteAgentChange(ch)
return err
}
// changeSettings is a change of the saved settings by edit: it is checked,
// shown as what it changes, approved, then saved and applied. edit runs
// again on the settings as they are then. It returns what changed.
func (a *App) changeSettings(ctx context.Context, s *mcp.Session, what words, edit func(*settings.Settings) error) ([]string, error) {
old := a.settings.Get()
next := old.Clone()
if err := edit(&next); err != nil {
return nil, err
}
if err := next.Validate(); err != nil {
return nil, err
}
diff := a.settingsDiff(old, next)
if len(diff) == 0 {
return nil, nil
}
err := a.change(ctx, s, what, strings.Join(diff, "\n"), func() error {
var editErr error
err := a.updateSettings(func(st *settings.Settings) { editErr = edit(st) })
return errors.Join(editErr, err)
})
return diff, err
}
// secretKeys are the settings an agent reads only as set or not.
var secretKeys = []string{"extSecret", "authentication"}
// settingsMap is s as its JSON keys, with the secrets hidden.
func settingsMap(s settings.Settings) map[string]any {
b, _ := json.Marshal(s)
m := map[string]any{}
_ = json.Unmarshal(b, &m)
for _, k := range secretKeys {
switch v := m[k].(type) {
case string:
if v != "" {
m[k] = "••••"
}
case []any:
for i, e := range v {
if str, ok := e.(string); ok {
user, _, _ := strings.Cut(str, ":")
v[i] = user + ":••••"
}
}
}
}
if m["mcpPolicy"] == "" {
m["mcpPolicy"] = "ask"
}
return m
}
// settingsDiff is what changes from old to next, a line each, for people.
func (a *App) settingsDiff(old, next settings.Settings) []string {
om, nm := settingsMap(old), settingsMap(next)
keys := make([]string, 0, len(nm))
for k := range nm {
keys = append(keys, k)
}
sort.Strings(keys)
var out []string
for _, k := range keys {
if reflect.DeepEqual(om[k], nm[k]) {
continue
}
if k == "rules" {
out = append(out, a.rulesDiff(old.Rules, next.Rules)...)
continue
}
ol, ok1 := om[k].([]any)
nl, ok2 := nm[k].([]any)
if ok1 || ok2 {
before := len(out)
for _, e := range nl {
if !slices.ContainsFunc(ol, func(o any) bool { return reflect.DeepEqual(o, e) }) {
out = append(out, fmt.Sprintf("%s: + %v", k, e))
}
}
for _, e := range ol {
if !slices.ContainsFunc(nl, func(n any) bool { return reflect.DeepEqual(n, e) }) {
out = append(out, fmt.Sprintf("%s: − %v", k, e))
}
}
if len(out) == before {
out = append(out, k+": "+i18n.T("顺序调整", "reordered"))
}
continue
}
out = append(out, fmt.Sprintf("%s: %v → %v", k, show(om[k]), show(nm[k])))
}
return out
}
// show is a setting's value in a diff: a string as it is, "" as "".
func show(v any) string {
if s, ok := v.(string); ok && s != "" {
return s
}
b, _ := json.Marshal(v)
return string(b)
}
func (a *App) rulesDiff(old, next []routes.UserRule) []string {
var out []string
for _, r := range next {
i := slices.IndexFunc(old, r.Same)
switch {
case i < 0:
out = append(out, fmt.Sprintf("rules: + %s → %s", r.Mihomo(), routes.Title(a.route(r.Route))))
case old[i].Route != r.Route:
out = append(out, fmt.Sprintf("rules: %s %s → %s", r.Mihomo(), routes.Title(a.route(old[i].Route)), routes.Title(a.route(r.Route))))
}
}
for _, r := range old {
if !slices.ContainsFunc(next, r.Same) {
out = append(out, fmt.Sprintf("rules: − %s → %s", r.Mihomo(), routes.Title(a.route(r.Route))))
}
}
return out
}
// ---- Lookups ----
// findRoute is the route s names: its id, its Chinese name or its title.
func (a *App) findRoute(s string) (routes.Route, error) {
s = strings.TrimSpace(s)
for _, r := range a.routes() {
if strings.EqualFold(s, r.ID) || s == r.Name || strings.EqualFold(s, routes.Title(r)) {
return r, nil
}
}
ids := make([]string, len(a.routes()))
for i, r := range a.routes() {
ids[i] = r.ID
}
return routes.Route{}, fmt.Errorf("%s: %q (%s)", i18n.T("没有这条路由", "No such route"), s, strings.Join(ids, ", "))
}
// findNode is the node s names: its name in the core, or its label when
// one node has it.
func (a *App) findNode(s string) (string, error) {
nodes := a.snapshot().Nodes
for _, n := range nodes {
if n.Name == s {
return n.Name, nil
}
}
var hits []string
for _, n := range nodes {
if strings.EqualFold(n.Display, s) || strings.EqualFold(display(n.Name), s) {
hits = append(hits, n.Name)
}
}
switch len(hits) {
case 1:
return hits[0], nil
case 0:
return "", fmt.Errorf(i18n.T("没有这个节点: %s", "No such node: %s"), s)
}
return "", fmt.Errorf(i18n.T("有多个节点叫 %s,请用节点的 name", "Several nodes are called %s; use the node's name"), s)
}
// ---- Views for agents ----
// mcpConn is a connection with its route and rule as the window's list
// words them: route alone is an id, which under an imported config's
// routing is g1, g2 and so on.
type mcpConn struct {
Conn
RouteName string `json:"routeName,omitempty"`
RuleName string `json:"ruleName,omitempty"`
}
type mcpRoute struct {
ID string `json:"id"`
Name string `json:"name"`
Summary string `json:"summary"`
Direct bool `json:"direct"`
// Reject: what this route gets is refused, not sent anywhere.
Reject bool `json:"reject,omitempty"`
// Auto: the route picks its fastest node by itself.
Auto bool `json:"auto,omitempty"`
// Node is the node it uses now (a node's name), "" for direct.
Node string `json:"node,omitempty"`
NodeLabel string `json:"nodeLabel,omitempty"`
UserRules int `json:"userRules"`
// Locked is the exit lock (lock_route); Refused, that its traffic is
// refused now, takeover being off; Unheld, that the lock does not hold
// now, nothing bringing the group's traffic to bowel.
Locked bool `json:"locked,omitempty"`
Refused bool `json:"refused,omitempty"`
Unheld bool `json:"unheld,omitempty"`
// Sites are its test sites, the main one first (what an automatic
// route chooses its node by), as the node it uses did on each.
Sites []mcpSite `json:"sites,omitempty"`
}
type mcpNode struct {
Name string `json:"name"`
Label string `json:"label"`
Provider string `json:"provider"`
Type string `json:"type"`
// DelayMs is the last test's; 0 failed. Absent when untested.
DelayMs *int `json:"delayMs,omitempty"`
// RefusedBySite: that test failed because the site answered and turned
// the node away, not because nothing answered.
RefusedBySite bool `json:"refusedBySite,omitempty"`
Where string `json:"where,omitempty"`
}
// mcpSite is one of a route's test sites, as the node the route uses did
// on it.
type mcpSite struct {
Name string `json:"name"`
URL string `json:"url"`
DelayMs *int `json:"delayMs,omitempty"`
RefusedBySite bool `json:"refusedBySite,omitempty"`
}
func (a *App) mcpRoutes(snap Snapshot) []mcpRoute {
out := make([]mcpRoute, 0, len(snap.Routes))
for _, r := range snap.Routes {
v := mcpRoute{ID: r.ID, Name: r.Name, Summary: r.Summary, Direct: r.Direct, Reject: r.Reject, Auto: r.Auto, Node: r.Node, UserRules: r.Mine, Locked: r.Locked, Refused: r.Refused, Unheld: r.Unheld}
if r.Node != "" {
v.NodeLabel = a.display(r.Node)
v.Sites = mcpSites(snap, r)
}
out = append(out, v)
}
return out
}
// mcpSites lists route r's test sites, its main one first, with what the
// node it uses did on each.
func mcpSites(snap Snapshot, r RouteView) []mcpSite {
if r.Main.URL == "" {
return nil
}
site := func(name, url string, ms int, tested, refused bool) mcpSite {
s := mcpSite{Name: name, URL: url}
if tested {
s.DelayMs, s.RefusedBySite = &ms, refused
}
return s
}
main := site(r.Main.Name, r.Main.URL, 0, false, false)
for _, n := range snap.Nodes {
if n.Name == r.Node {
n = n.On(r.ID)
main = site(r.Main.Name, r.Main.URL, n.Delay, n.Tested, n.Refused)
break
}
}
out := []mcpSite{main}
for _, s := range r.Sites {
out = append(out, site(s.Name, s.URL, s.Delay, s.Tested, s.Refused))
}
return out
}
// mcpNodes lists the nodes, with their delays on a route's main target.
func mcpNodes(snap Snapshot, route string) []mcpNode {
out := make([]mcpNode, 0, len(snap.Nodes))
for _, n := range snap.Nodes {
n = n.On(route)
v := mcpNode{Name: n.Name, Label: n.Display, Provider: n.Provider, Type: n.Type}
if n.Tested {
d := n.Delay
v.DelayMs, v.RefusedBySite = &d, n.Refused
}
if p := n.Where.Place; p != nil {
v.Where = strings.TrimSpace(p.Country + " " + p.City + " (" + n.Where.Source + ")")
}
out = append(out, v)
}
return out
}
type mcpRule struct {
Kind string `json:"kind"`
Value string `json:"value"`
Route string `json:"route"`
Mihomo string `json:"mihomo"`
Matches string `json:"matches"`
}
func mcpRules(rs []routes.UserRule) []mcpRule {
out := make([]mcpRule, 0, len(rs))
for _, r := range rs {
out = append(out, mcpRule{Kind: r.Kind, Value: r.Value, Route: r.Route, Mihomo: r.Mihomo(), Matches: r.Describe()})
}
return out
}
// editable are the keys update_settings takes: all but what has a tool of
// its own, and the policy, which only the user sets.
func editable(s settings.Settings) []string {
var keys []string
for k := range settingsMap(s) {
if !slices.Contains(notEditable, k) {
keys = append(keys, k)
}
}
sort.Strings(keys)
return keys
}
var notEditable = []string{"mcpPolicy", "rules", "mode", "systemProxy", "tun", "paused", "importedRouting"}
// parseTarget reads a host, URL, domain pattern or IP into a rule of kind
// ("" guesses) for route.
func parseTarget(kind, target, route string) (routes.UserRule, error) {
return routes.ParseRule(kind, target, route)
}
// whitelists are the lists the whitelist tools edit.
var whitelists = []string{"direct", "bypass", "lan"}
func (a *App) whitelistView(s settings.Settings) map[string]any {
var direct []mcpRule
for _, r := range mcpRules(s.Rules) {
if r.Route == "direct" {
direct = append(direct, r)
}
}
if direct == nil {
direct = []mcpRule{}
}
return map[string]any{
"direct": direct,
"bypass": s.Bypass,
"lan": s.LanAllowedIPs,
"about": map[string]string{
"direct": "Your rules sending traffic to the direct route: it goes out without a proxy, through the core.",
"bypass": "The system proxy's exceptions: apps that follow the system proxy don't send these to bowel at all.",
"lan": "Addresses on the LAN allowed to use bowel's proxy port when allowLan is on.",
},
}
}
// devNetView is get_dev_network's answer.
func (a *App) devNetView(s settings.Settings) map[string]any {
env := a.devEnv()
dev := overlayOf(s, env)
scenarios := []map[string]any{}
for _, sc := range devnet.Scenarios() {
scenarios = append(scenarios, map[string]any{"id": sc.ID, "name": sc.Name(), "on": !s.DevOff && !slices.Contains(s.DevOffScenarios, sc.ID)})
}
return map[string]any{
"on": !s.DevOff, "scenarios": scenarios, "extra": s.DevExtra, "found": env, "warnings": a.devReport(s, false).Warnings,
"bypass": dev.Bypass, "noProxy": dev.NoProxy, "rules": dev.Rules, "outbounds": dev.Outbounds, "tunExclude": dev.TunExclude, "dnsPolicy": dev.Policy,
}
}
// ---- The server ----
func obj(props map[string]any, required ...string) map[string]any {
m := map[string]any{"type": "object", "properties": props, "additionalProperties": false}
if len(required) > 0 {
m["required"] = required
}
return m
}
func str(desc string, enum ...string) map[string]any {
m := map[string]any{"type": "string", "description": desc}
if len(enum) > 0 {
m["enum"] = enum
}
return m
}
func (a *App) mcpServer() *mcp.Server {
routeIDs := make([]string, len(a.routes()))
for i, r := range a.routes() {
routeIDs[i] = r.ID
}
routeArg := str("A route's id: "+strings.Join(routeIDs, ", ")+".", routeIDs...)
return &mcp.Server{
Name: "bowel", Title: "bowel", Version: mygo.App.Version(),
Instructions: mcpInstructions,
Tools: []mcp.Tool{
{
Name: "get_status", Title: "Status", ReadOnly: true,
Description: "bowel's state now: the one light (ok, degraded, error, off) and its issue, the core, the mode, the takeover (system proxy, TUN, port, LAN), each route's node, and today's traffic.",
Run: func(ctx context.Context, s *mcp.Session, _ json.RawMessage) (any, error) {
snap, t := a.snapshot(), a.tick()
return map[string]any{
"state": snap.State, "issue": snap.Issue, "core": snap.Core, "mode": snap.Mode,
"takeover": snap.Takeover, "routes": a.mcpRoutes(snap), "nodes": len(snap.Nodes),
"providers": len(snap.Providers), "activeConnections": t.Active,
"traffic": map[string]int64{"downBps": t.Down, "upBps": t.Up, "todayDown": t.TodayDown, "todayUp": t.TodayUp, "monthDown": t.MonthDown},
"agentPolicy": a.settings.Get().Policy(), "version": snap.Version,
"ipv6": a.ipv6Report(), "headless": a.headless, "mcpHttp": mcpHTTPView(),
}, nil
},
},
{
Name: "get_settings", Title: "Settings", ReadOnly: true,
Description: "All saved settings as settings.json has them (secrets hidden), the keys update_settings can change, and the choices of the keys that take one of a few values.",
Run: func(ctx context.Context, s *mcp.Session, _ json.RawMessage) (any, error) {
st := a.settings.Get()
return map[string]any{"settings": settingsMap(st), "editable": editable(st), "choices": settingChoices()}, nil
},
},
{
Name: "list_routes", Title: "Routes and nodes", ReadOnly: true,
Description: "The routes (kinds of traffic: default, ai, media, dev, direct) with the node each uses, and every node with its last delay and location. Every node can serve every proxied route. A route's sites are its test sites, the main one first, as the node it uses did on each: delayMs 0 is a failed test, and refusedBySite says the site answered and turned that exit away rather than nothing answering (api.openai.com and api.anthropic.com do so for exits they don't serve), so another node may do where this one doesn't; an automatic route does not choose a node its main site refuses. When a provider's own config routes the traffic, `imported` has its groups, the routes are those groups that rules point at, and only select groups can change. Its unusedSettings are the parts of that config that act on traffic and are not used (dns, hosts, tun, listeners, ports and the like): bowel's own settings do those.",
Run: func(ctx context.Context, s *mcp.Session, _ json.RawMessage) (any, error) {
snap := a.snapshot()
out := map[string]any{"routes": a.mcpRoutes(snap), "nodes": mcpNodes(snap, routes.Default)}
if snap.Imported != nil {
out["imported"] = mcpImported(snap.Imported)
}
return out, nil
},
},
{
Name: "list_rules", Title: "Your rules", ReadOnly: true,
Description: "The user's own rules: what each matches and its route. Also the imported rule sets. Every rule, the built-in ones too, applies in the order of the route group list (list_routes), from the top down: the first group with a rule that matches takes the connection, however specific a rule in a group below is. The developer networks come before every group, and a rule of the user's inside them before those.",
Run: func(ctx context.Context, s *mcp.Session, _ json.RawMessage) (any, error) {
return map[string]any{"rules": mcpRules(a.settings.Get().Rules), "ruleSets": a.mcpRuleSets()}, nil
},
},
{
Name: "explain", Title: "Where would it go", ReadOnly: true,
Description: "Where a connection to a host, URL or IP would go, and which rule decides. When GeoSite/GeoIP data or the default route decides, sure is false.",
Input: obj(map[string]any{"target": str("A host, URL or IP, as api.openai.com.")}, "target"),
Run: func(ctx context.Context, s *mcp.Session, raw json.RawMessage) (any, error) {
var p struct {
Target string `json:"target"`
}
if err := mcp.Args(raw, &p); err != nil {
return nil, err
}
if a.importedNow() != nil {
return map[string]any{"target": p.Target, "sure": false, "note": "An imported config's own rules are in use; bowel can't evaluate them. Use list_connections to see which rule each connection matched."}, nil
}
host := p.Target
if r, err := routes.ParseRule(routes.KindDomain, host, ""); err == nil {
host = r.Value
} else if r, err := routes.ParseRule(routes.KindIP, host, ""); err == nil {
host, _, _ = strings.Cut(r.Value, "/")
} else {
return nil, err
}
id, rule, _, mine, sure := routes.ExplainSets(host, routes.Active(a.routes(), a.settings.Get().Rules), a.routes(), a.matchRuleSet)
if st := a.settings.Get(); !mine {
if r, ok := overlayOf(st, a.devEnv()).Match(host); ok {
return map[string]any{"host": host, "site": routes.Site(host), "sure": true, "userRule": false,
"route": "direct", "rule": r.Text, "leavesBy": r.Target,
"note": "A developer network: it never reaches a proxy. See get_dev_network."}, nil
}
}
out := map[string]any{"host": host, "site": routes.Site(host), "sure": sure, "userRule": mine}
if sure {
out["route"], out["rule"] = id, rule
} else {
out["note"] = "No user rule or built-in domain rule matches; GeoSite/GeoIP data decides, else the default route."
}
return out, nil
},
},
{
Name: "get_dev_network", Title: "Developer networks", ReadOnly: true,
Description: "What stays off the proxy and why: Tailscale's state, VPNs and split DNS found on this Mac, each scenario's switch, and what is added to the bypass list, rules and TUN.",
Input: obj(map[string]any{}),
Run: func(ctx context.Context, _ *mcp.Session, raw json.RawMessage) (any, error) {
return a.devNetView(a.settings.Get()), nil
},
},
{
Name: "list_connections", Title: "Connections", ReadOnly: true,
Description: "Recent connections, newest first: app, host, route (its id and routeName), node, rule (ruleName as the window words it) and traffic. Filter by a part of the host or app.",
Input: obj(map[string]any{
"filter": str("Only connections whose host or app contains this."),
"status": str("Only these: active, closed, failed or blocked (refused by a rule).", "active", "closed", "failed", "blocked"),
"limit": map[string]any{"type": "integer", "description": "At most this many (default 50, at most 500).", "minimum": 1, "maximum": 500},
}),
Run: func(ctx context.Context, s *mcp.Session, raw json.RawMessage) (any, error) {
var p struct {
Filter, Status string
Limit int
}
if err := mcp.Args(raw, &p); err != nil {
return nil, err
}
if p.Limit <= 0 || p.Limit > 500 {
p.Limit = 50
}
all := a.connections()
sort.SliceStable(all, func(i, j int) bool { return all[i].Start.After(all[j].Start) })
f := strings.ToLower(p.Filter)
services := a.settings.Get().Routing.Services
out := []mcpConn{}
for _, c := range all {
if p.Status != "" && c.Status != p.Status {
continue
}
if f != "" && !strings.Contains(strings.ToLower(c.Host), f) && !strings.Contains(strings.ToLower(c.App), f) && !strings.Contains(c.IP, f) {
continue
}
mc := mcpConn{Conn: c, RuleName: ruleWord(c, services)}
if c.Route != "" {
mc.RouteName = routes.Title(a.route(c.Route))
}
out = append(out, mc)
if len(out) == p.Limit {
break
}
}
return map[string]any{"connections": out, "total": len(all)}, nil
},
},
{
Name: "list_providers", Title: "Providers", ReadOnly: true,
Description: "The providers that supply nodes (subscriptions, links, files): their nodes, data used and expiry. Subscription URLs are masked.",
Run: func(ctx context.Context, s *mcp.Session, _ json.RawMessage) (any, error) {
return map[string]any{"providers": a.snapshot().Providers}, nil
},
},
{
Name: "get_logs", Title: "Core logs", ReadOnly: true,
Description: "The core's recent log lines, newest last.",
Input: obj(map[string]any{
"level": str("Only this level and worse.", "debug", "info", "warning", "error"),
"limit": map[string]any{"type": "integer", "description": "At most this many (default 100, at most 1000).", "minimum": 1, "maximum": 1000},
}),
Run: func(ctx context.Context, s *mcp.Session, raw json.RawMessage) (any, error) {
var p struct {
Level string
Limit int
}
if err := mcp.Args(raw, &p); err != nil {
return nil, err
}
if p.Limit <= 0 || p.Limit > 1000 {
p.Limit = 100
}
rank := map[string]int{"debug": 0, "info": 1, "warning": 2, "error": 3}
var out []LogLine
for _, l := range a.logs(0) {
if p.Level == "" || rank[l.Level] >= rank[p.Level] {
out = append(out, l)
}
}
if len(out) > p.Limit {
out = out[len(out)-p.Limit:]
}
if out == nil {
out = []LogLine{}
}
return map[string]any{"logs": out}, nil
},
},
{
Name: "get_whitelists", Title: "Whitelists", ReadOnly: true,
Description: "The three whitelists: direct (sites sent straight out, without a proxy), bypass (the system proxy's exceptions) and lan (LAN addresses allowed to use the proxy).",
Run: func(ctx context.Context, s *mcp.Session, _ json.RawMessage) (any, error) {
return a.whitelistView(a.settings.Get()), nil
},
},
{
Name: "test_route", Title: "Test a route's nodes",
Description: "Measures the delay of a route's nodes on its main test site now, and returns them. delayMs 0 is a failed test; refusedBySite says the site answered and turned the node away, as api.openai.com and api.anthropic.com do for exits they don't serve. Changes nothing.",
Input: obj(map[string]any{"route": routeArg}, "route"),
Run: func(ctx context.Context, s *mcp.Session, raw json.RawMessage) (any, error) {
var p struct{ Route string }
if err := mcp.Args(raw, &p); err != nil {
return nil, err
}
r, err := a.findRoute(p.Route)
if err != nil {
return nil, err
}
if r.Direct {
return nil, errors.New("this route uses no node")
}
err = a.testRoute(ctx, r.ID)
snap := a.snapshot()
out := map[string]any{"nodes": mcpNodes(snap, r.ID)}
if err != nil {
out["error"] = err.Error()
}
return out, nil
},
},
// ---- Changes: as the policy says ----
{
Name: "set_mode", Title: "Set the mode",
Description: "Changes the proxy mode: rule (routes by rules), global (everything through the default route's node) or direct (no proxy). Open connections are closed so they reconnect the new way.",
Input: obj(map[string]any{"mode": str("The mode.", "rule", "global", "direct")}, "mode"),
Run: func(ctx context.Context, s *mcp.Session, raw json.RawMessage) (any, error) {
var p struct{ Mode string }
if err := mcp.Args(raw, &p); err != nil {
return nil, err
}
old := a.settings.Get().Mode
if p.Mode == old {
return "The mode is " + old + " already.", nil
}
err := a.change(ctx, s, words{"切换代理模式", "Switch the proxy mode"}, "mode: "+old+" → "+p.Mode, func() error { return a.setMode(p.Mode) })
if err != nil {
return nil, err
}
return "The mode is now " + p.Mode + ".", nil
},
},
{
Name: "set_takeover", Title: "Set the takeover", Destructive: true,
Description: "Turns bowel's takeover of this Mac's traffic on or off, and chooses its entries: the system proxy and TUN (all traffic; the first time macOS asks the user for an administrator's password). Give only what should change. Asking for TUN on while its status is error tries its core again.",
Input: obj(map[string]any{
"enabled": map[string]any{"type": "boolean", "description": "Take over traffic at all (false pauses it, keeping the entries)."},
"systemProxy": map[string]any{"type": "boolean", "description": "Use the system proxy."},
"tun": map[string]any{"type": "boolean", "description": "Use TUN."},
}),
Run: func(ctx context.Context, s *mcp.Session, raw json.RawMessage) (any, error) {
var p struct {
Enabled, SystemProxy, Tun *bool
}
if err := mcp.Args(raw, &p); err != nil {
return nil, err
}
st := a.settings.Get()
systemProxy, tun := st.SystemProxy, st.Tun
// Pause keeps the saved entries, but asking to turn one on
// must reach the setter that resumes it. An explicit off
// still clears the saved entry for the next full resume.
if st.Paused {
if p.SystemProxy != nil && *p.SystemProxy {
systemProxy = false
}
if p.Tun != nil && *p.Tun {
tun = false
}
}
var lines []string
note := func(k string, from, to bool) {
if from != to {
lines = append(lines, fmt.Sprintf("%s: %v → %v", k, from, to))
}
}
if p.SystemProxy != nil {
note("systemProxy", systemProxy, *p.SystemProxy)
}
// TUN wanted and not had (its core did not start), or on
// without the rule that points the system's DNS at it:
// asking for it again is asking to try again.
retry := p.Tun != nil && *p.Tun && st.Tun && a.tunFailed()
if p.Tun != nil {
note("tun", tun, *p.Tun)
}
if retry {
lines = append(lines, "tun: retry")
}
if p.Enabled != nil {
note("enabled", a.takeoverOn(st), *p.Enabled)
}
if len(lines) == 0 {
return "Nothing to change.", nil
}
err := a.change(ctx, s, words{"更改接管", "Change the takeover"}, strings.Join(lines, "\n"), func() error {
if p.SystemProxy != nil && *p.SystemProxy != systemProxy {
if err := a.setSystemProxy(*p.SystemProxy); err != nil {
return err
}
}
if p.Tun != nil && (*p.Tun != tun || retry) {
if err := a.setTun(*p.Tun); err != nil {
return err
}
}
if p.Enabled != nil && *p.Enabled != a.takeoverOn(a.settings.Get()) {
return a.setTakeover(*p.Enabled)
}
return nil
})
if err != nil {
return nil, err
}
return map[string]any{"changed": lines, "takeover": a.snapshot().Takeover}, nil
},
},
{
Name: "retake_system_proxy", Title: "Take the system proxy over again", Destructive: true,
Description: "Points the system proxy back at bowel when takeover wants it and it points elsewhere (status hijacked or error). set_takeover does nothing here, as the setting has not changed. What the system had before bowel stays saved, to be put back when bowel quits.",
Input: obj(map[string]any{}),
Run: func(ctx context.Context, s *mcp.Session, _ json.RawMessage) (any, error) {
st := a.settings.Get()
if !a.takeoverOn(st) || !st.SystemProxy {
return nil, errors.New("bowel is not set to use the system proxy: turn it on with set_takeover")
}
cur, err := osProxy.check(st.MixedPort)
if err != nil {
return nil, err
}
if cur.Ours {
return "Nothing to change: the system proxy points at bowel.", nil
}
detail := fmt.Sprintf("system proxy → 127.0.0.1:%d", st.MixedPort)
if err := a.change(ctx, s, words{"重新接管系统代理", "Take the system proxy over again"}, detail, a.retake); err != nil {
return nil, err
}
return map[string]any{"takeover": a.snapshot().Takeover}, nil
},
},
{
Name: "select_node", Title: "Choose a route's node",
Description: "Makes a proxied route use a node, or pick the fastest by itself (node \"auto\"). Nodes are named as list_routes gives them. Under an imported config, route is any select group by name and node one of its members.",
Input: obj(map[string]any{"route": routeArg, "node": str("A node's name or label, or \"auto\".")}, "route", "node"),
Run: func(ctx context.Context, s *mcp.Session, raw json.RawMessage) (any, error) {
var p struct{ Route, Node string }
if err := mcp.Args(raw, &p); err != nil {
return nil, err
}
if a.importedNow() != nil {
return a.mcpSelectMember(ctx, s, p.Route, p.Node)
}
r, err := a.findRoute(p.Route)
if err != nil {
return nil, err
}
if r.Direct {
return nil, errors.New("this route uses no node")
}
node, label := "", i18n.T("自动", "Auto")
if !strings.EqualFold(p.Node, "auto") && p.Node != "" {
if node, err = a.findNode(p.Node); err != nil {
return nil, err
}
label = a.display(node)
}
cur := i18n.T("自动", "Auto")
for _, rv := range a.snapshot().Routes {
if rv.ID == r.ID && !rv.Auto && rv.Node != "" {
cur = a.display(rv.Node)
}
}
err = a.change(ctx, s, words{"为路由选择节点", "Choose a route's node"},
fmt.Sprintf("%s: %s → %s", routes.Title(r), cur, label), func() error { return a.selectNode(r.ID, node) })
if err != nil {
return nil, err
}
return fmt.Sprintf("%s now uses %s.", r.ID, label), nil
},
},
{