feat(mcp): turn off a global server for Pi from the project switch

A Pi project entry replaces the global one and is skipped without a
command or url, so a switch-only entry left the server on in Pi and the
project page could not turn it off there. Reporters want a server off in
one project while every other project keeps loading it.

For a project under mcp.projects, the switch now writes the global
server's command, or its url without the query, with enabled: false to
the project's .pi/mcp.json. A disabled server never starts, so args, env
and headers stay out of a file that may be committed, and every sync
rewrites the entry from the global server. A project's own config cannot
see the global server, so pi there is still refused. The migration that
dropped pi from switch-only entries is gone.

Refs #305
This commit is contained in:
Willie
2026-10-01 16:08:23 +08:00
parent 886e3672a2
commit f837f0e94d
27 changed files with 175 additions and 124 deletions
+60 -47
View File
@@ -5,6 +5,7 @@ import (
"maps"
"os"
"path/filepath"
"reflect"
"slices"
"strings"
"testing"
@@ -81,7 +82,8 @@ func TestDisabledRejected(t *testing.T) {
}
}
// Loading drops pi from an old switch, but saving a new one for pi still fails.
// A project's own config cannot see the global server, so it has no command or url to give
// Pi's switch, and saving one for pi fails.
func TestPiSwitchRejectedOnSave(t *testing.T) {
s := testService(t)
s.ProjectRoot = filepath.Join(s.Home, "project")
@@ -312,7 +314,7 @@ func TestSwitchWithoutTargetsFollowsTheProject(t *testing.T) {
}{
"only what the project uses": {"claude, opencode, kilocode, pi", "opencode, kilocode", []string{"kilocode", "opencode"}},
"only what the server reaches": {"claude, codex, pi", "claude, opencode", []string{"claude"}},
"skips an Agent with no switch": {"cursor, opencode, pi", "cursor, opencode, pi", []string{"opencode"}},
"skips an Agent with no switch": {"cursor, opencode, pi", "cursor, opencode, pi", []string{"opencode", "pi"}},
} {
t.Run(name, func(t *testing.T) {
s, tmp := projectsService(t, "mcp:\n servers:\n docs:\n command: tool\n targets: ["+tc.global+"]\n projects:\n $TMP/p1:\n targets: ["+tc.project+"]\n servers:\n docs:\n disabled: true\n")
@@ -334,60 +336,71 @@ func TestSwitchWithoutTargetsFollowsTheProject(t *testing.T) {
}
}
// Pi's built-in MCP has no per-project switch, so a switch that names no targets leaves Pi
// alone even where the project and the global server both reach it.
func TestSwitchLeavesPiAlone(t *testing.T) {
s, tmp := projectsService(t, "mcp:\n servers:\n docs:\n command: tool\n targets: [opencode, pi]\n projects:\n $TMP/p1:\n targets: [opencode, pi]\n servers:\n mine:\n command: tool\n targets: [pi]\n docs:\n disabled: true\n")
plan, err := s.Preview()
// Pi replaces a global entry with the project entry of the same name, so its switch carries
// the global server's command or url, and nothing else: args, env, headers and the url's
// query stay out of the project file.
func TestPiSwitchCarriesTheGlobalEndpoint(t *testing.T) {
s, tmp := projectsService(t, "mcp:\n servers:\n docs:\n command: tool\n args: [--port, \"3000\"]\n env: {TOKEN: {fromEnv: TOKEN}}\n targets: [opencode, pi]\n web:\n url: https://example.com/mcp?key=secret\n headers: {Authorization: {fromEnv: AUTH}}\n targets: [pi]\n projects:\n $TMP/p1:\n targets: [opencode, pi]\n servers:\n docs:\n disabled: true\n web:\n disabled: true\n")
plan := applyProjects(t, s)
for _, c := range plan.Changes {
if c.Root == filepath.Join(tmp, "p1") && !c.Switch {
t.Fatalf("not a switch: %+v", c)
}
}
data, err := os.ReadFile(filepath.Join(tmp, "p1", ".pi", "mcp.json"))
if err != nil {
t.Fatal(err)
}
var got []string
for _, c := range plan.Changes {
if c.Root == filepath.Join(tmp, "p1") && c.Name == "docs" {
got = append(got, c.Target)
}
var file struct{ McpServers map[string]map[string]any }
if err := json.Unmarshal(data, &file); err != nil {
t.Fatal(err)
}
if !slices.Equal(got, []string{"opencode"}) {
t.Fatalf("got %v", got)
want := map[string]map[string]any{"docs": {"command": "tool", "enabled": false}, "web": {"url": "https://example.com/mcp", "enabled": false}}
if !reflect.DeepEqual(file.McpServers, want) {
t.Fatalf("project .pi/mcp.json: %s", data)
}
if global, _ := os.ReadFile(filepath.Join(tmp, ".pi", "agent", "mcp.json")); !strings.Contains(string(global), "3000") {
t.Fatalf("global .pi/agent/mcp.json lost the server: %s", global)
}
}
// Before 0.23.0 an adapter user could turn a global server off for one project in Pi. Pi's
// built-in MCP has no such switch, so loading drops pi from the entry instead of failing sync.
func TestPiSwitchLeavesPiOnLoad(t *testing.T) {
s, tmp := projectsService(t, `mcp:
targets: [opencode]
projects:
$TMP/both:
servers:
docs:
disabled: true
targets: [pi, opencode]
$TMP/only:
servers:
docs:
disabled: true
targets: [pi]
`)
plan, err := s.Preview()
if err != nil || plan.Blocked {
t.Fatalf("%+v %v", plan, err)
}
if len(plan.Changes) != 1 || plan.Changes[0].Target != "opencode" || plan.Changes[0].Root != filepath.Join(tmp, "both") {
t.Fatalf("changes: %+v", plan.Changes)
}
if want := "Pi cannot turn off a server per project; the next sync removes pi from these entries: docs (both, only)"; len(plan.Notices) != 1 || plan.Notices[0] != want {
t.Fatalf("notices: %q", plan.Notices)
}
if _, err := s.Mutate(Mutation{Name: "other", Server: &Server{Command: "other"}}, "", false); err != nil {
// The switch follows the global server, and removing it takes the Pi entry away.
func TestPiSwitchFollowsTheGlobalServer(t *testing.T) {
s, tmp := projectsService(t, "mcp:\n servers:\n docs:\n command: tool\n targets: [pi]\n projects:\n $TMP/p1:\n targets: [pi]\n servers:\n docs:\n disabled: true\n")
applyProjects(t, s)
project := filepath.Join(tmp, "p1", ".pi", "mcp.json")
config, _ := os.ReadFile(s.ConfigPath)
if err := os.WriteFile(s.ConfigPath, []byte(strings.Replace(string(config), "command: tool", "command: tool2", 1)), 0600); err != nil {
t.Fatal(err)
}
data, _ := os.ReadFile(s.ConfigPath)
if strings.Contains(string(data), "- pi") || strings.Count(string(data), "- opencode") != 2 || !strings.Contains(string(data), "targets: []") {
t.Fatalf("saved config: %s", data)
applyProjects(t, s)
if data, _ := os.ReadFile(project); !strings.Contains(string(data), `"tool2"`) {
t.Fatalf("switch did not follow the global command: %s", data)
}
if source, err := LoadSource(s.ConfigPath); err != nil || len(source.Notices) != 0 {
t.Fatalf("%v %v", source, err)
config, _ = os.ReadFile(s.ConfigPath)
if err := os.WriteFile(s.ConfigPath, []byte(strings.Replace(string(config), " docs:\n disabled: true\n", " {}\n", 1)), 0600); err != nil {
t.Fatal(err)
}
applyProjects(t, s)
if data, _ := os.ReadFile(project); strings.Contains(string(data), "docs") {
t.Fatalf("switch still in Pi: %s", data)
}
}
// A switch that names pi keeps it; there is nothing left to migrate.
func TestPiSwitchNamedInTargetsStays(t *testing.T) {
s, tmp := projectsService(t, "mcp:\n servers:\n docs:\n command: tool\n targets: [opencode, pi]\n projects:\n $TMP/p1:\n servers:\n docs:\n disabled: true\n targets: [pi]\n")
plan, err := s.Preview()
if err != nil || plan.Blocked || len(plan.Notices) != 0 {
t.Fatalf("%+v %v", plan, err)
}
var got []string
for _, c := range plan.Changes {
if c.Root == filepath.Join(tmp, "p1") {
got = append(got, c.Target)
}
}
if !slices.Equal(got, []string{"pi"}) {
t.Fatalf("got %v", got)
}
}
+3 -3
View File
@@ -36,7 +36,7 @@ mcp:
targets: [pi, opencode]
`
var retiredFields = []string{"piExtension", "piOptionsPrune", "idleTimeout", "includeTools", "directTools", "[pi, opencode]"}
var retiredFields = []string{"piExtension", "piOptionsPrune", "idleTimeout", "includeTools", "directTools"}
// legacyService is a service over legacyConfig that records the files it backs up.
func legacyService(t *testing.T) (*Service, *[]string) {
@@ -78,9 +78,9 @@ func TestSyncSavesTheConfigWithoutRetiredSettings(t *testing.T) {
if err != nil || plan.Blocked {
t.Fatalf("%+v %v", plan, err)
}
// Five retired kinds, the tool policy lists converted from includeTools, and what Pi's
// Four retired kinds, the tool policy lists converted from includeTools, and what Pi's
// built-in MCP needs, which the sync keeps saying after the config is saved.
if len(plan.Notices) != 7 || plan.Notices[6] != PiBuiltinNotice || !plan.Migrates {
if len(plan.Notices) != 6 || plan.Notices[5] != PiBuiltinNotice || !plan.Migrates {
t.Fatalf("notices: %q", plan.Notices)
}
result, err := s.Apply(plan.Revision)
+4 -18
View File
@@ -88,6 +88,9 @@ type Server struct {
// Agent's global config defines. Unselecting an Agent already covers a server
// Skillshare defines, so a disabled server carries no command or url.
Disabled bool `yaml:"disabled,omitempty" json:"disabled,omitempty"`
// global is the global server a project's switch-only entry turns off, when the plan
// knows it. Pi needs its command or url to take the switch.
global *Server
}
// legacyServerFields chose Pi's MCP extension and opted in to pruning Pi fields, before
@@ -161,9 +164,7 @@ func (m migration) reachesPi(server *yaml.Node) bool {
// pi-mcp-extension is also keyed "piExtension.<extension>";
// - pi-mcp-adapter piOptions are dropped, keyed "piOptions.<field>";
// - directTools and piOptions includeTools/excludeTools become Pi exposure settings or
// tools (adoptAdapterTools), keyed "piTools", or are dropped, keyed "piTools.<field>";
// - pi and piAccounts leave the targets of a switch-only entry, keyed "piSwitch": Pi has
// no per-project switch, and an entry left with no targets stays, turning nothing off.
// tools (adoptAdapterTools), keyed "piTools", or are dropped, keyed "piTools.<field>".
func migrateServers(servers *yaml.Node, m migration) map[string][]string {
found := map[string][]string{}
servers = deref(servers)
@@ -201,21 +202,6 @@ func migrateServers(servers *yaml.Node, m migration) map[string][]string {
if options := deref(field(server, "piOptions")); options != nil && options.Kind == yaml.MappingNode && len(options.Content) == 0 {
drop(server, "piOptions")
}
disabled := deref(field(server, "disabled"))
targets := deref(field(server, "targets"))
if disabled == nil || disabled.Tag != "!!bool" || disabled.Value != "true" || targets == nil || targets.Kind != yaml.SequenceNode {
continue
}
kept := []*yaml.Node{}
for _, target := range targets.Content {
if value := deref(target).Value; value != "pi" && !slices.Contains(m.piAccounts, value) {
kept = append(kept, target)
}
}
if len(kept) < len(targets.Content) {
targets.Content = kept
found["piSwitch"] = append(found["piSwitch"], name)
}
}
return found
}
+13 -3
View File
@@ -35,6 +35,10 @@ func switchOnly(target string, entry map[string]any) bool {
if strings.HasPrefix(target, claudeOffPrefix) {
return true
}
if target == "pi" {
// Pi's switch carries the global server's command or url; see renderDisabled.
return len(entry) == 2 && entry["enabled"] == false && (entry["command"] != nil || entry["url"] != nil)
}
return len(entry) == 1 && (entry["enabled"] == false || entry["disabled"] == true)
}
@@ -261,23 +265,29 @@ func SwitchTargets(server Server, defaults, reached []string) TargetList {
func followingSwitches(servers map[string]Server, defaults []string, global *Source) map[string]Server {
out := maps.Clone(servers)
for name, server := range servers {
if !server.Disabled || server.Targets != nil {
if !server.Disabled {
continue
}
var reached []string
if global != nil {
if shared, ok := global.Servers[name]; ok {
server.global = &shared
if reached = shared.Targets; reached == nil {
reached = global.Targets
}
}
}
if server.Targets != nil {
out[name] = server
continue
}
server.Targets = SwitchTargets(server, defaults, reached)
// The off list is per account, so an account that has the server gets the switch too.
// Claude Code's off list is per account, so an account that has the server gets the
// switch too. Pi accounts all read the project's one .pi/mcp.json, which pi writes.
if global != nil {
for _, account := range sortedKeys(global.Accounts) {
agent := global.Accounts[account].Agent
if _, err := renderDisabled(agent, server); err == nil && slices.Contains(defaults, agent) && (reached == nil || slices.Contains(reached, account)) {
if _, err := renderDisabled(agent, server); err == nil && agent == "claude" && slices.Contains(defaults, agent) && (reached == nil || slices.Contains(reached, account)) {
server.Targets = append(server.Targets, account)
}
}
+17 -1
View File
@@ -2,6 +2,7 @@ package mcp
import (
"fmt"
"net/url"
"sort"
)
@@ -21,10 +22,25 @@ func renderDisabled(target string, s Server) (map[string]any, error) {
// Codex fails its whole config load with "invalid transport". The project file is
// usually committed, so one person's switch would break Codex for a teammate.
return nil, fmt.Errorf("codex cannot turn off a global server from a project file: on a machine whose global config lacks the server, Codex stops loading its whole config; set enabled = false in ~/.codex/config.toml instead")
case target == "pi" && s.global != nil:
// Pi replaces a global entry with the project entry of the same name and skips one
// without a command or url. A disabled server is never started, so its command or
// url alone is enough; args, env, headers and the url's query, which may hold a key,
// stay out of the project file, which may be committed. Validate already refuses a
// url with credentials or a fragment.
if s.global.Command != "" {
return map[string]any{"command": s.global.Command, "enabled": false}, nil
}
u, err := url.Parse(s.global.URL)
if err != nil {
return nil, fmt.Errorf("pi: invalid url of the global server: %w", err)
}
u.RawQuery = ""
return map[string]any{"url": u.String(), "enabled": false}, nil
case target == "pi":
// Pi replaces a global entry with the project entry of the same name, and skips one
// without a command or url, so a switch-only entry leaves the global server on.
return nil, fmt.Errorf("pi cannot turn off a global server with a switch-only entry: a Pi project entry replaces the global one, so it needs the server's command or url; add the complete server with piOptions: {\"enabled\": false} instead")
return nil, fmt.Errorf("pi cannot turn off a server the global config does not define for it: a Pi project entry replaces the global one, so it needs the server's command or url; add the complete server with piOptions: {\"enabled\": false} instead")
}
return nil, fmt.Errorf("%s cannot turn off a global server from a project file; disabled supports claude, opencode and kilocode", target)
}
-1
View File
@@ -343,7 +343,6 @@ func legacyNotices(legacy map[string][]legacyName) []string {
if len(adapter) > 0 {
add("Pi's built-in MCP does not read "+strings.Join(adapter, ", ")+"; the next sync removes them", keys...)
}
add("Pi cannot turn off a server per project; the next sync removes pi from these entries", "piSwitch")
add("directTools, includeTools and excludeTools become tool settings; the next sync converts them", "piTools")
add("directTools, includeTools or excludeTools the server already covers, or that are not tool lists, are dropped; the next sync removes them", "piTools.directTools", "piTools.excludeTools", "piTools.includeTools")
return notices