Files
skillshare/internal/mcp/render.go
T
Willie 0c31df5682 feat(mcp): manage many project folders from the global config
Project mode keeps MCP settings in each project's .skillshare/config.yaml and
is synced from inside that folder. Someone who works across many projects had
to repeat that per folder and could not see or sync them in one place.

mcp.projects in the global config lists project roots, each with its own
targets, servers and directTools. One sync plans the global files and every
root together, and removing a root cleans up what was written there. It is
refused in a project config, and disabled cannot target Claude Code there
because its off list shares ~/.claude.json with the global servers.

directTools is now a first-class setting for pi-mcp-adapter: per server
(--direct-tools on mcp add/edit), as a default under mcp, or per project.
Before this it could only be hand-edited into Pi's file.

Mutations accept a project root and a settings block so the dashboard can
edit all of this. Saving re-encodes only the nodes that changed, so other
projects keep their YAML as written, anchors, aliases and a leading ~ in the
key included. expandHome also accepts ~\ so Windows paths resolve.

Refs #286
2026-09-20 23:49:12 +08:00

196 lines
5.9 KiB
Go

package mcp
import (
"fmt"
"sort"
)
// renderDisabled writes only the switch. That works where the Agent merges its project
// file over its global one field by field, so the global command or url survives. Agents
// that replace the whole entry, or reject one without a transport, would break instead.
func renderDisabled(target string, s Server) (map[string]any, error) {
switch {
case openCodeFormat(target):
return map[string]any{"enabled": false}, nil
case target == "pi" && s.PiExtension == "pi-mcp-adapter":
return map[string]any{"disabled": true}, nil
case target == "claude":
// No entry to write: destination sends the name to Claude Code's per-project off list.
return map[string]any{}, nil
case target == "codex":
// Codex merges the project file by field, so the switch works where the global config
// defines the server. Where it does not, the merged entry has no command or url and
// 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")
}
return nil, fmt.Errorf("%s cannot turn off a global server from a project file; disabled supports claude, opencode, kilocode and pi with pi-mcp-adapter", target)
}
// Render converts a portable definition to a native entry without reading env.
func Render(target string, s Server) (map[string]any, error) {
if !validTarget(target) {
return nil, fmt.Errorf("unsupported MCP target %q", target)
}
if err := s.Validate("server"); err != nil {
return nil, err
}
if s.Disabled {
return renderDisabled(target, s)
}
if target == "pi" {
return renderPi(s)
}
if format, ok := clientFormats[target]; ok {
return renderAdditionalClient(target, format, s)
}
out := map[string]any{}
if target == "antigravity" {
if s.BearerToken != nil {
return nil, fmt.Errorf("Antigravity: bearerToken/fromEnv is not supported; complete OAuth authentication in Antigravity")
}
for _, values := range []map[string]Value{s.Env, s.Headers} {
for _, value := range values {
if value.FromEnv != "" {
return nil, fmt.Errorf("Antigravity: fromEnv is not supported because native environment interpolation is not documented")
}
}
}
}
resolve := func(v Value) string {
if v.FromEnv == "" {
return v.Literal
}
if openCodeFormat(target) {
return "{env:" + v.FromEnv + "}"
}
if target == "claude" || target == "grok" {
return "${" + v.FromEnv + "}"
}
return "${env:" + v.FromEnv + "}"
}
if s.Command != "" {
out["command"] = s.Command
if target != "codex" && target != "grok" && target != "antigravity" {
out["type"] = "stdio"
}
if len(s.Args) > 0 {
out["args"] = s.Args
}
env := map[string]string{}
var forwarded []string
for key, v := range s.Env {
if target == "codex" && v.FromEnv != "" {
if key != v.FromEnv {
return nil, fmt.Errorf("Codex requires environment reference %s to use the same variable name", key)
}
forwarded = append(forwarded, key)
} else {
env[key] = resolve(v)
}
}
if len(env) > 0 {
out["env"] = env
}
if len(forwarded) > 0 {
sort.Strings(forwarded)
out["env_vars"] = forwarded
}
if openCodeFormat(target) {
out["type"] = "local"
out["command"] = append([]string{s.Command}, s.Args...)
delete(out, "args")
if len(env) > 0 {
out["environment"] = env
delete(out, "env")
}
}
} else {
out["url"] = s.URL
if target == "antigravity" {
out["serverUrl"] = s.URL
delete(out, "url")
}
if openCodeFormat(target) {
out["type"] = "remote"
}
if target == "claude" || target == "vscode" {
out["type"] = "http"
}
headers := map[string]string{}
envHeaders := map[string]string{}
for key, v := range s.Headers {
if target == "codex" && v.FromEnv != "" {
envHeaders[key] = v.FromEnv
} else {
headers[key] = resolve(v)
}
}
if s.BearerToken != nil {
if target == "codex" {
out["bearer_token_env_var"] = s.BearerToken.FromEnv
} else {
headers["Authorization"] = "Bearer " + resolve(*s.BearerToken)
}
}
if len(headers) > 0 {
if target == "codex" {
out["http_headers"] = headers
} else {
out["headers"] = headers
}
}
if len(envHeaders) > 0 {
out["env_http_headers"] = envHeaders
}
}
return out, nil
}
// Rendered is one server as one Agent's config file would hold it.
type Rendered struct {
Target string `json:"target"`
Path string `json:"path"`
Content string `json:"content,omitempty"`
Error string `json:"error,omitempty"`
}
// RenderNative writes the server into an empty file per target, so the wrapper key and the
// format (JSON, TOML, YAML) come from the code that writes the real file, not from a guess
// made in the dashboard. Nothing is read from the environment or written to disk.
func (s *Service) RenderNative(name string, server Server) []Rendered {
// The saved mcp.directTools default is what sync would write; an unreadable config has none.
if source, err := LoadSource(s.ConfigPath); err == nil {
server = server.withDirectToolsDefault(source.DirectTools)
}
out := make([]Rendered, 0, len(server.Targets))
for _, target := range server.Targets {
r := Rendered{Target: target}
path, native, _ := s.destination(target, server)
r.Path = path
err := s.checkScope(name, target, server)
var entry map[string]any
if err == nil {
entry, err = Render(target, server)
}
var n *Native
if err == nil {
if target == "goose" {
entry["name"] = name
}
n, err = ParseNative(native, nil)
}
var data []byte
if err == nil {
data, err = n.Edit(map[string]map[string]any{name: entry})
}
if err != nil {
r.Error = err.Error()
} else {
r.Content = string(data)
}
out = append(out, r)
}
return out
}