From c24915f04eb73cf8e49efde431ecc8a7e391f487 Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 6 Nov 2026 00:19:39 +0800 Subject: [PATCH] library: LiveAgent in the MCP and Skills pickers (zero2sin) LiveAgent was missing from the Library's MCP and Skill agent pickers (zero2sin on Discord #feedback). It is now a target, written in its own engine's formats, read from K-brain 507f560 (the one LiveAgent af89ea7 pins), not guessed: - MCP: /config.json.live-mcp.json (cmd/kn/backend.go, internal/mcp/live.go LiveSettings): {"servers":[{"id","enabled", "transport":"stdio"|"http","command","args","env" | "url","headers", ...}],"selected":[...]}. Streamable HTTP only, so SSE is refused. ${NAME} in env and headers resolves as K-brain's secret refs (internal/config/secret.go). The user's servers and their description/enabled/cwd/timeoutMs/policy/auth/... are kept; untouched servers are written back byte for byte (json.RawMessage). A non-empty selected gets magpie's server added (or it would have no tools) and taken out on remove, never the last one. With no file yet, K-brain reads config.json's "mcp" object (settingsFromConfigs), so the first write carries those servers over the way K-brain's own first save does. A new file is 0600 like K-brain's. A file K-brain itself could not parse is not written over. - Skills: /skills, as copies (Target.Copy): K-brain refuses a link in a skill's path (safePath) and ScanDetailed walks past one. A skill there loads only when picked in skills-settings.json global.selected (Manager.Effective), so syncLiveAgentPicks picks each copy magpie makes once (Applied.Picked), never again after the user unpicks it, and unpicks it when the copy goes. Names K-brain refuses (validManagedName) are never put in selected, since its next save would fail on them. Its built-in skills-creator/skills-installer are not offered for import. - Not added: instructions (K-brain's brain.md is its own memory file). A server written while LiveAgent runs is seen at its next start (the app holds the list in memory and saves it whole). Run (mote-run, at base 326e72f4c): - go test -run LiveAgent ./internal/library/: 7 tests ok - go test ./internal/library/... ./internal/agent/ ./internal/gui/: library ok, agent ok, gui FAIL only TestMainWindowCorners/macOS_26_SDK (#3949, macOS 27 on mote, no library code) - GOOS=linux and GOOS=windows go vet ./internal/library/: clean; gofmt -l: clean - node --test of 100 GUI files (library-*, *skill*, *mcp*, i18n-keys) in chromium and webkit: 1941 of 1946 pass. Red: i18n-keys "a plugin's words are its own" (two Go test files elsewhere say a plugin's word) and found-skill-pick-remove "en at 420px" in both engines; this change touches no GUI file. - Rebased on origin/main 125fd93ec and run again there: go test ./internal/library/ ok; found-skill-pick-remove and i18n-keys red the same (en at 420px both engines; "a plugin's words are its own"), and red the same on a clean origin/main 125fd93ec worktree: filed as #5013 and #5327/#5332. Broken by hand, each red: Copy=false (TestLiveAgentTarget, TestLiveAgentSkills: a link); no syncLiveAgentPicks call (nothing picked); re-picking every sync (TestLiveAgentSkills: xlsx picked again after the user unpicked it); no built-in skip (found lists skills-creator); no selected append (TestLiveAgentMCP); no config.json seeding (TestLiveAgentMCPFromConfig); no chmod (0644); no name check (TestLiveAgentSkillsNewSettings: My_Skill picked). Not tried: a real LiveAgent app reading the written files (no LiveAgent on mote or here); Windows and Linux test runs (vet only). --- docs/subsystems/library.md | 1 + internal/library/envref.go | 7 + internal/library/library.go | 6 +- internal/library/liveagent.go | 401 +++++++++++++++++++++++++++++ internal/library/liveagent_test.go | 386 +++++++++++++++++++++++++++ internal/library/mcp.go | 42 ++- internal/library/skills.go | 6 + internal/library/targets.go | 11 + 8 files changed, 858 insertions(+), 2 deletions(-) create mode 100644 internal/library/liveagent.go create mode 100644 internal/library/liveagent_test.go diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index 64057e73d..cf18f1e90 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -48,6 +48,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it. - An update from GitHub or a git repository never silently replaces a skill changed here. It is refused, or skipped in an update of several, until the user says to replace it, and the version replaced goes to the backups. - A copy's mark establishes that it is unchanged only after its whole folder was scanned. If a subtree or its metadata can't be read, the copy stays in place and the sync reports a `Problem`; it isn't replaced, relinked or removed. A later sync tries again once it can be read. The same scan failure stops replacing a project's or Claude Desktop's copy. - A failure for one agent is a `Problem` in the result. It doesn't stop the others. +- LiveAgent (zero2sin on Discord) keeps its MCP servers in K-brain's `config.json.live-mcp.json` beside its `config.json`, in the folder `agent.liveAgentDir` finds: a list of servers by `id`, each `enabled` and `stdio` or `http` (streamable HTTP only, so SSE is refused). Until that file is there K-brain reads `config.json`'s `mcp` object, so magpie's first write carries those servers over. A non-empty `selected` is the only servers LiveAgent uses, so magpie adds its server there and takes it out again, never the last one. The app holds the list in memory once started, so a change is seen at its next start. Its skills folder takes copies, as K-brain refuses a link, and a skill there is used only once picked in `skills-settings.json`: `syncLiveAgentPicks` picks each copy magpie makes once (`Applied.Picked`), so one the user unpicks stays unpicked, and unpicks it when the copy goes. A name K-brain refuses (lowercase letters, digits and single hyphens, up to 64) is copied but never picked. Its built-in `skills-creator` and `skills-installer` are not offered to bring in (`liveagent.go`, `TestLiveAgentMCP`, `TestLiveAgentSkills`). - An MCP OAuth sign-in canceled or timed out before its callback commits never saves a late token or changes an existing sign-in. The callback's write and the flow's ending share a lock (`flow.keep` in [`mcpauth.go`](../../internal/mcpauth/mcpauth.go)); if the write wins first, it completes and tells the agents before saying done. A cancellation is not a sign-out of credentials already committed. - A server an agent can't reach is not written there, and `mcpFile.supports` says why. For example, Claude Desktop takes no remote server, and Codex, Goose, dsh, Grok, Command Code and Zed take no SSE. - A server's headers (remote) or environment (command) can name a variable as `${NAME}` (#1250). `library.json` keeps the placeholder, and `refsOf` gives each MCP format the agent's own syntax, with the agent's source cited beside it: `${NAME}` for most, `{env:NAME}` for OpenCode and MiMo, `${env:NAME}` for Cursor, and Codex's own keys (`bearer_token_env_var`, `env_http_headers`, `env_vars`). Goose gets `${NAME}` plus `env_keys`. dsh (DeepSeek Harness) gets a `!!js` expression it evaluates as it loads the server (#1435): a whole `${NAME}` is `!!js process.env.NAME`, and a value mixing text and variables is the text as JSON string literals joined with `(process.env.NAME ?? "")`, so the user's text is never run as code and an unset variable inside it is empty. A whole variable that isn't set makes dsh leave the server out as invalid. magpie reads only those forms back as `${NAME}`; any other `!!js` keeps the entry the user's. An agent with no syntax (Claude Desktop, Antigravity, Kimi, Cline, ZCode, Zed, Devin, Alma, Pi with pi-mcp-extension) is never written the value: `refsProblem` makes `supports` refuse the server, a magpie entry already there is taken out, and `AgentView.NoEnvRefs` greys its chip with the reason. Codex and Goose's extra keys are magpie's only while the server names a variable there (`refKeys`), so the user's own `env_vars` or `env_keys` are kept. `CheckServers`, the router (`dialHub`) and Codex's run through the gateway (`specOf`) expand the variable in memory (`expandAll`): from magpie's own environment, else from what a terminal opened now has (`proc.LoginVars`: what the login shell, or fish or nushell, exports, kept a minute; the registry's user then machine variables on Windows), since a magpie opened from the Finder has none of the profile's variables and a server whose token was exported in .zshrc showed no tools (Cyrus on Discord, `TestEnvRefsFromLoginShell`, `TestLoginVars`). The value is never set in magpie's environment, written to library.json or an agent's file, or logged. One set nowhere is `novar`, naming it. The page paints that as not checked (a ring, `lib-health unknown`), not red: it says nothing of the server, which the agent may start with the variable set, as Codex does its host-only `codex_app` (#2308). It starts a command server in home, with `PWD` set to it (not on Windows), as an agent started from home would, never in magpie's own working folder: a magpie started from the Windows Start menu has `C:\Windows\system32`, where a server that writes into `.` exits before it answers (#1727, `TestCheckStdio`). diff --git a/internal/library/envref.go b/internal/library/envref.go index e9fcb6425..c0e9e2659 100644 --- a/internal/library/envref.go +++ b/internal/library/envref.go @@ -178,6 +178,13 @@ func (f *mcpFile) refsOf() envSyntax { // (kiro.dev/docs/mcp/configuration), the ones its Mcp Approved Env // Vars setting approves return envSyntax{refDollar, refDollar} + case fmtLiveAgent: + // K-brain, LiveAgent's engine, reads ${NAME} (and $NAME, + // ${NAME:-default}) in a server's env and headers as it starts it, + // and leaves out one whose variable is unset (internal/config/ + // secret.go ResolveEnvMapContext, ResolveHeaderContext; internal/ + // mcp/manager.go defaultTransport, K-brain 507f560) + return envSyntax{refDollar, refDollar} } // None: Claude Desktop gives a command its env as written and only // HOME, LOGNAME, PATH, SHELL, TERM and USER of its own (2.7032's app.asar diff --git a/internal/library/library.go b/internal/library/library.go index 892651dcd..63e3f81fa 100644 --- a/internal/library/library.go +++ b/internal/library/library.go @@ -128,6 +128,10 @@ type Applied struct { // entry (Codex's startup_timeout_sec): one there other than this is // the user's Startup map[string]float64 `json:"startup,omitempty"` + // Picked are the skills magpie picked in the agent's own list of + // those it uses (LiveAgent's skills-settings.json, liveagent.go): one + // the user unpicked since stays unpicked + Picked []string `json:"picked,omitempty"` } // empty is whether a holds nothing magpie wrote: a sync that only looked @@ -137,7 +141,7 @@ type Applied struct { func (a *Applied) empty() bool { return !a.Instructions && a.InstrHash == "" && len(a.MCP) == 0 && len(a.Skills) == 0 && len(a.ToolsOff) == 0 && len(a.ToolRules) == 0 && len(a.Hooks) == 0 && - len(a.Subagents) == 0 && len(a.Startup) == 0 + len(a.Subagents) == 0 && len(a.Startup) == 0 && len(a.Picked) == 0 } var mu lock // one change at a time, from the page or the CLI's process diff --git a/internal/library/liveagent.go b/internal/library/liveagent.go new file mode 100644 index 000000000..c979c4226 --- /dev/null +++ b/internal/library/liveagent.go @@ -0,0 +1,401 @@ +package library + +// LiveAgent's MCP servers and skills, as its engine K-brain keeps them in +// its data folder (agent.liveAgentDir: $LIVEAGENT_HOME, $K_BRAIN_HOME, the +// folder ~/.liveagent/data-dir.json names, else ~/.liveagent). Read in +// K-brain 507f560 and LiveAgent af89ea7, which pins it. +// +// MCP: config.json.live-mcp.json, beside config.json (cmd/kn/backend.go +// OpenLiveManager(configFilename+".live-mcp.json", …)): +// +// {"servers": [{"id": "fs", "enabled": true, "transport": "stdio", +// "command": "npx", "args": […], "env": {…}}, …], "selected": […]} +// +// a list of servers by id, each stdio or streamable HTTP ("http"; there is +// no SSE, internal/mcp/manager.go defaultTransport), plus the user's own +// description, docsUrl, cwd, timeoutMs, workspaceRoots, policy and auth, +// kept as they are. A non-empty selected is the only servers whose tools +// are used (LiveManager.ToolsFor). Until that file is there K-brain reads +// config.json's "mcp" object instead (settingsFromConfigs), so magpie's +// first write carries those servers over, as K-brain's own first save +// does. The app holds the list in memory once started and saves it whole +// (src/lib/settings/storage.ts persistSettings), so a server written while +// it runs is seen at its next start. +// +// Skills: K-brain's own folder is skills there (internal/skills/ +// managed.go NewManager), and a skill in it is used only when its name is +// picked in skills-settings.json's global.selected (Manager.Effective). +// K-brain refuses a link anywhere in a skill's path (safePath) and walks +// past one (ScanDetailed's e.IsDir), so LiveAgent gets copies (Copy), and +// each copy magpie makes is picked for it once (syncLiveAgentPicks). + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "regexp" + "slices" + "sort" + "strings" + + "github.com/tidwall/jsonc" + + "github.com/yetone/magpie/internal/edit" +) + +// liveAgentMCP is the file K-brain keeps its MCP servers in, in its folder. +const liveAgentMCP = "config.json.live-mcp.json" + +// liveAgentPicked is K-brain's file of the skills picked in its folder. +const liveAgentPicked = "skills-settings.json" + +// liveAgentBuiltins are the skills K-brain makes in its folder itself and +// picks always (ensureBuiltins, builtinsSelected): never one the user +// brings into the library. +var liveAgentBuiltins = []string{"skills-creator", "skills-installer"} + +// liveAgentSkillName is a name K-brain takes for a skill in its folder: +// lowercase letters, digits and single hyphens inside, at most 64 +// (validManagedName); SaveSettings refuses a selection with another. +var liveAgentSkillName = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*$`) + +func liveAgentNameOK(name string) bool { + return len(name) <= 64 && liveAgentSkillName.MatchString(name) +} + +// liveAgentDoc is live-mcp.json: its servers in their order, each as +// written, and the rest of the file. +type liveAgentDoc struct { + servers []json.RawMessage + rest map[string]json.RawMessage + // there: the file is there; a doc made from config.json's servers + // isn't + there bool +} + +func (d *liveAgentDoc) ids() []string { + out := make([]string, len(d.servers)) + for i, raw := range d.servers { + var v struct { + ID string `json:"id"` + } + json.Unmarshal(raw, &v) + out[i] = strings.TrimSpace(v.ID) + } + return out +} + +func (d *liveAgentDoc) selected() []string { + var out []string + json.Unmarshal(d.rest["selected"], &out) + return out +} + +// liveAgentRead is the file at path, or, while there is none, what K-brain +// reads in its place: config.json's servers. +func liveAgentRead(path string) (*liveAgentDoc, error) { + raw, err := os.ReadFile(path) + if errors.Is(err, fs.ErrNotExist) { + return liveAgentSeed(filepath.Join(filepath.Dir(path), "config.json")) + } + if err != nil { + return nil, err + } + d := &liveAgentDoc{rest: map[string]json.RawMessage{}, there: true} + raw = edit.TrimBOM(raw) + if len(bytes.TrimSpace(raw)) == 0 { + return d, nil + } + // K-brain reads it as plain JSON (loadLiveSettings): a file it can't + // read isn't one magpie writes over + if err := json.Unmarshal(raw, &d.rest); err != nil { + return nil, fmt.Errorf("%s: %w", path, err) + } + if s := d.rest["servers"]; len(s) > 0 && string(s) != "null" { + if err := json.Unmarshal(s, &d.servers); err != nil { + return nil, fmt.Errorf("%s: servers: %w", path, err) + } + } + delete(d.rest, "servers") + return d, nil +} + +// liveAgentSeed is config.json's "mcp" servers as K-brain takes them when +// it has no live-mcp.json (mcp.settingsFromConfigs): a url is http, else +// the command's first word and its args; enabled unless it says false; +// startupTimeout's seconds as timeoutMs. +func liveAgentSeed(config string) (*liveAgentDoc, error) { + d := &liveAgentDoc{rest: map[string]json.RawMessage{}} + raw, err := os.ReadFile(config) + if errors.Is(err, fs.ErrNotExist) { + return d, nil + } + if err != nil { + return nil, err + } + var c struct { + MCP map[string]struct { + Command []string `json:"command"` + Env map[string]string `json:"env"` + Cwd string `json:"cwd"` + URL string `json:"url"` + Headers map[string]string `json:"headers"` + Enabled *bool `json:"enabled"` + StartupTimeout int `json:"startupTimeout"` + } `json:"mcp"` + } + if err := json.Unmarshal(jsonc.ToJSON(edit.TrimBOM(raw)), &c); err != nil { + return nil, fmt.Errorf("%s: %w", config, err) + } + for _, id := range slices.Sorted(func(yield func(string) bool) { + for k := range c.MCP { + if !yield(k) { + return + } + } + }) { + m := c.MCP[id] + if strings.TrimSpace(id) == "" { + continue + } + o := ordered{{"id", strings.TrimSpace(id)}, {"enabled", m.Enabled == nil || *m.Enabled}} + if m.URL != "" { + o = append(o, kv{"transport", "http"}, kv{"url", m.URL}) + } else { + o = append(o, kv{"transport", "stdio"}) + if len(m.Command) > 0 { + o = append(o, kv{"command", m.Command[0]}) + if len(m.Command) > 1 { + o = append(o, kv{"args", m.Command[1:]}) + } + } + } + if len(m.Env) > 0 { + o = append(o, kv{"env", m.Env}) + } + if m.Cwd != "" { + o = append(o, kv{"cwd", m.Cwd}) + } + if len(m.Headers) > 0 { + o = append(o, kv{"headers", m.Headers}) + } + if m.StartupTimeout > 0 { + o = append(o, kv{"timeoutMs", m.StartupTimeout * 1000}) + } + b, err := json.Marshal(o) + if err != nil { + return nil, err + } + d.servers = append(d.servers, b) + } + return d, nil +} + +// write saves d at path as K-brain saves it: indented JSON, the servers +// first, the file only its owner's to read (it holds their tokens). +func (d *liveAgentDoc) write(path string) error { + o := ordered{{"servers", d.servers}} + if d.servers == nil { + o[0].v = []json.RawMessage{} + } + keys := make([]string, 0, len(d.rest)) + for k := range d.rest { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + o = append(o, kv{k, d.rest[k]}) + } + b, err := json.MarshalIndent(o, "", " ") + if err != nil { + return err + } + _, statErr := os.Stat(path) + if err := edit.WriteAtomic(path, append(b, '\n')); err != nil { + return err + } + if errors.Is(statErr, fs.ErrNotExist) { + return os.Chmod(path, 0o600) + } + return nil +} + +// liveAgentEntries is each server of the file by its id, as K-brain reads +// them: the first by an id, none without one (normalizeLiveSettings). +func liveAgentEntries(path string) (map[string]map[string]any, error) { + d, err := liveAgentRead(path) + if err != nil { + return nil, err + } + out := map[string]map[string]any{} + for i, id := range d.ids() { + if id == "" || out[id] != nil { + continue + } + var m map[string]any + if json.Unmarshal(d.servers[i], &m) == nil && m != nil { + out[id] = m + } + } + return out, nil +} + +// liveAgentPut writes the server o as name's, in place of the one by that +// id or after the others, and picks it where the user picks servers. +func liveAgentPut(path, name string, o ordered) error { + d, err := liveAgentRead(path) + if err != nil { + return err + } + entry := append(ordered{{"id", name}}, slices.DeleteFunc(slices.Clone(o), func(e kv) bool { return e.k == "id" })...) + b, err := json.Marshal(entry) + if err != nil { + return err + } + if i := slices.Index(d.ids(), name); i >= 0 { + d.servers[i] = b + } else { + d.servers = append(d.servers, b) + } + // an empty selected is every server; one the user narrowed gets + // magpie's too, or it would be there with no tools + if sel := d.selected(); len(sel) > 0 && !slices.Contains(sel, name) { + raw, _ := json.Marshal(append(sel, name)) + d.rest["selected"] = raw + } + return d.write(path) +} + +// liveAgentDel takes the server by that id out, and out of selected but +// for the last one there: an empty selected would be every server. +func liveAgentDel(path, name string) error { + d, err := liveAgentRead(path) + if err != nil { + return err + } + ids := d.ids() + if !slices.Contains(ids, name) { + return nil + } + var kept []json.RawMessage + for i, id := range ids { + if id != name { + kept = append(kept, d.servers[i]) + } + } + d.servers = kept + if sel := d.selected(); len(sel) > 1 && slices.Contains(sel, name) { + raw, _ := json.Marshal(slices.DeleteFunc(sel, func(s string) bool { return s == name })) + d.rest["selected"] = raw + } + return d.write(path) +} + +// syncLiveAgentPicks picks, in K-brain's skills-settings.json, each copy +// of the library's magpie made in LiveAgent's folder, the first time it +// is there, and takes out of the picks one magpie picked when its copy is +// gone. One the user unpicked in LiveAgent stays unpicked: magpie picks a +// skill once (Applied.Picked), not at every sync. +func (l *Library) syncLiveAgentPicks(t *Target, res *Result) { + if t.Agent.ID != "liveagent" || t.Skills == "" || res.unreached(t) { + return + } + id := t.Agent.ID + a := l.applied(id) + var have []string + es, _ := os.ReadDir(t.Skills) + for _, e := range es { + if n := e.Name(); liveAgentNameOK(n) && ours(filepath.Join(t.Skills, n), n) { + have = append(have, n) + } + } + var add, drop []string + for _, n := range have { + if !slices.Contains(a.Picked, n) { + add = append(add, n) + } + } + for _, n := range a.Picked { + if !slices.Contains(have, n) { + drop = append(drop, n) + } + } + if len(add) == 0 && len(drop) == 0 { + return + } + path := filepath.Join(filepath.Dir(t.Skills), liveAgentPicked) + if err := liveAgentPick(path, add, drop); err != nil { + res.fail(id, "skills", err) + return + } + picked := slices.DeleteFunc(slices.Clone(a.Picked), func(n string) bool { return slices.Contains(drop, n) }) + a.Picked = append(picked, add...) + if len(a.Picked) == 0 { + a.Picked = nil + } + res.changed(id) +} + +// liveAgentPick adds the names to the file's global.selected and takes +// drop out of it, the rest of the file as it was, its revision one on as +// K-brain's own save makes it (Manager.SaveSettings). With no file, +// K-brain's defaults are written first: skills on, nothing picked. +func liveAgentPick(path string, add, drop []string) error { + raw, err := os.ReadFile(path) + if errors.Is(err, fs.ErrNotExist) { + if len(add) == 0 { + return nil + } + raw, err = []byte(`{"revision": 0, "global": {"enabled": true, "selected": []}, "projects": {}}`), nil + } + if err != nil { + return err + } + var doc map[string]json.RawMessage + if err := json.Unmarshal(edit.TrimBOM(raw), &doc); err != nil { + return fmt.Errorf("%s: %w", path, err) + } + var global map[string]json.RawMessage + if g := doc["global"]; len(g) > 0 && string(g) != "null" { + if err := json.Unmarshal(g, &global); err != nil { + return fmt.Errorf("%s: global: %w", path, err) + } + } + if global == nil { + // K-brain's default for a file without one: skills on + global = map[string]json.RawMessage{"enabled": json.RawMessage("true")} + } + var sel []string + if s := global["selected"]; len(s) > 0 && string(s) != "null" { + if err := json.Unmarshal(s, &sel); err != nil { + return fmt.Errorf("%s: global.selected: %w", path, err) + } + } + was := slices.Clone(sel) + sel = slices.DeleteFunc(sel, func(n string) bool { return slices.Contains(drop, n) }) + for _, n := range add { + if !slices.Contains(sel, n) { + sel = append(sel, n) + } + } + if _, there := os.Stat(path); there == nil && slices.Equal(sel, was) { + return nil + } + if sel == nil { + sel = []string{} + } + global["selected"], _ = json.Marshal(sel) + doc["global"], _ = json.Marshal(global) + var rev uint64 + json.Unmarshal(doc["revision"], &rev) + doc["revision"], _ = json.Marshal(rev + 1) + out, err := json.MarshalIndent(doc, "", " ") + if err != nil { + return err + } + return edit.WriteAtomic(path, out) +} diff --git a/internal/library/liveagent_test.go b/internal/library/liveagent_test.go new file mode 100644 index 000000000..dac347ff9 --- /dev/null +++ b/internal/library/liveagent_test.go @@ -0,0 +1,386 @@ +package library + +import ( + "encoding/json" + "errors" + "os" + "path/filepath" + "slices" + "strings" + "testing" +) + +// liveAgentHome is LiveAgent's folder in the sandbox, there as LiveAgent +// leaves it, so that it is found (agent.liveagent's detect). +func liveAgentHome(t *testing.T, h string) string { + t.Helper() + d := filepath.Join(h, ".liveagent") + write(t, filepath.Join(d, "config.json"), "{}") + return d +} + +type liveMCP struct { + Servers []map[string]any `json:"servers"` + Selected []string `json:"selected"` +} + +func readLiveMCP(t *testing.T, p string) liveMCP { + t.Helper() + var f liveMCP + // K-brain reads it with plain encoding/json (loadLiveSettings) + if err := json.Unmarshal([]byte(read(t, p)), &f); err != nil { + t.Fatalf("%v:\n%s", err, read(t, p)) + } + return f +} + +func liveServer(f liveMCP, id string) map[string]any { + for _, s := range f.Servers { + if s["id"] == id { + return s + } + } + return nil +} + +// LiveAgent had neither the MCP picker nor the Skills one (zero2sin on +// Discord): its engine K-brain keeps its servers in +// config.json.live-mcp.json and its skills in skills, both in the folder +// LiveAgent hands it (K-brain 507f560 cmd/kn/backend.go, +// internal/skills/managed.go). +func TestLiveAgentTarget(t *testing.T) { + h := sandbox(t) + d := liveAgentHome(t, h) + tg := targetByID("liveagent") + if tg == nil { + t.Fatalf("liveagent is not a target: %v", ids(Targets())) + } + if tg.MCP == nil || tg.MCP.Path != filepath.Join(d, "config.json.live-mcp.json") || tg.MCP.Format != fmtLiveAgent { + t.Errorf("mcp: %+v", tg.MCP) + } + if tg.Skills != filepath.Join(d, "skills") || !tg.Copy { + t.Errorf("skills: %q copy %v", tg.Skills, tg.Copy) + } + for _, kind := range []string{"mcp", "skills"} { + if id, err := Takes("liveagent", kind); id != "liveagent" || err != nil { + t.Errorf("Takes(liveagent, %s): %q %v", kind, id, err) + } + } + + // $LIVEAGENT_HOME, as LiveAgent starts K-brain with it + other := filepath.Join(h, "elsewhere") + write(t, filepath.Join(other, "config.json"), "{}") + t.Setenv("LIVEAGENT_HOME", other) + if tg := targetByID("liveagent"); tg == nil || tg.MCP.Path != filepath.Join(other, "config.json.live-mcp.json") || tg.Skills != filepath.Join(other, "skills") { + t.Errorf("$LIVEAGENT_HOME: %+v", tg) + } +} + +// The file magpie writes is K-brain's LiveSettings: servers by id, each +// enabled, stdio or http, as its own GUI saves them; the user's servers, +// their fields, the file's other keys and their pick of servers kept. +func TestLiveAgentMCP(t *testing.T) { + h := sandbox(t) + d := liveAgentHome(t, h) + p := filepath.Join(d, "config.json.live-mcp.json") + write(t, p, `{ + "servers": [ + { + "id": "mine", + "description": "my own", + "enabled": false, + "transport": "stdio", + "command": "uvx", + "args": ["mine-mcp"], + "cwd": "/work", + "timeoutMs": 9000, + "policy": {"allow": ["read"]} + } + ], + "selected": ["mine"] +} +`) + agents := []string{"liveagent"} + stdio := Server{Name: "fs", Transport: "stdio", Command: "npx", Args: []string{"-y", "@mcp/fs"}, Env: map[string]string{"K": "V", "T": "${TOKEN}"}, Agents: agents} + web := Server{Name: "web", Transport: "http", URL: "https://example.com/mcp", Headers: map[string]string{"Authorization": "Bearer ${TOKEN}"}, Agents: agents} + for _, s := range []Server{stdio, web} { + ok(t)(SaveServer("", s)) + } + + f := readLiveMCP(t, p) + if len(f.Servers) != 3 || f.Servers[0]["id"] != "mine" { + t.Fatalf("servers, the user's first:\n%s", read(t, p)) + } + fs := liveServer(f, "fs") + if fs["transport"] != "stdio" || fs["command"] != "npx" || fs["enabled"] != true { + t.Errorf("fs: %v", fs) + } else if a, _ := fs["args"].([]any); len(a) != 2 || a[1] != "@mcp/fs" { + t.Errorf("fs args: %v", fs) + } else if e, _ := fs["env"].(map[string]any); e["K"] != "V" || e["T"] != "${TOKEN}" { + t.Errorf("fs env, ${NAME} as K-brain resolves it: %v", fs) + } + w := liveServer(f, "web") + if w["transport"] != "http" || w["url"] != "https://example.com/mcp" || w["enabled"] != true { + t.Errorf("web: %v", w) + } else if hd, _ := w["headers"].(map[string]any); hd["Authorization"] != "Bearer ${TOKEN}" { + t.Errorf("web headers: %v", w) + } + for _, s := range f.Servers { + if _, ok := s["type"]; ok { + t.Errorf("%v has a type, which K-brain's servers never name", s) + } + } + mine := liveServer(f, "mine") + if mine["enabled"] != false || mine["description"] != "my own" || mine["cwd"] != "/work" || mine["timeoutMs"] != float64(9000) || mine["policy"] == nil { + t.Errorf("the user's server changed: %v", mine) + } + // the user picked their servers: magpie's are picked too, or they + // would be there with no tools (LiveManager.ToolsFor) + if !slices.Equal(f.Selected, []string{"mine", "fs", "web"}) { + t.Errorf("selected: %v", f.Selected) + } + // the user turns magpie's off in LiveAgent: it stays off + var raw map[string]any + json.Unmarshal([]byte(read(t, p)), &raw) + for _, s := range raw["servers"].([]any) { + if m := s.(map[string]any); m["id"] == "fs" { + m["enabled"] = false + m["timeoutMs"] = 5000 + } + } + b, _ := json.MarshalIndent(raw, "", " ") + write(t, p, string(b)) + ok(t)(Sync()) + if fs := liveServer(readLiveMCP(t, p), "fs"); fs["enabled"] != false || fs["timeoutMs"] != float64(5000) { + t.Errorf("a sync undid the user's enabled/timeoutMs: %v", fs) + } + + // read back, and left as they are by a sync that changes nothing + tg := targetByID("liveagent") + got, err := tg.MCP.read() + if err != nil { + t.Fatal(err) + } + for _, want := range []Server{stdio, web} { + if s := got[want.Name]; s == nil || !s.same(&want) { + t.Errorf("%s read back as %+v", want.Name, s) + } + } + if got["mine"] == nil || got["mine"].Command != "uvx" { + t.Errorf("mine read back as %+v", got["mine"]) + } + before := read(t, p) + ok(t)(Sync()) + if read(t, p) != before { + t.Errorf("a sync rewrote servers that are as the library has them:\n%s", read(t, p)) + } + + // no SSE: K-brain's http is streamable HTTP alone + if err := tg.MCP.supports(&Server{Transport: "sse"}); !errors.Is(err, errNoSSE) { + t.Errorf("sse: %v", err) + } + + for _, s := range []string{"fs", "web"} { + ok(t)(RemoveServer(s)) + } + f = readLiveMCP(t, p) + if len(f.Servers) != 1 || f.Servers[0]["id"] != "mine" || f.Servers[0]["description"] != "my own" { + t.Errorf("after:\n%s", read(t, p)) + } + if !slices.Equal(f.Selected, []string{"mine"}) { + t.Errorf("selected after: %v", f.Selected) + } +} + +// With no live-mcp.json K-brain reads config.json's mcp servers +// (settingsFromConfigs): magpie's first write carries them over, as +// K-brain's own first save would, rather than leave them behind. +func TestLiveAgentMCPFromConfig(t *testing.T) { + h := sandbox(t) + d := liveAgentHome(t, h) + write(t, filepath.Join(d, "config.json"), `{ + // K-brain's config.json takes comments + "mcp": { + "old": {"command": ["node", "server.js", "--x"], "env": {"A": "1"}, "enabled": false, "startupTimeout": 20}, + "remote": {"url": "https://example.com/r", "headers": {"H": "v"}} + } +}`) + tg := targetByID("liveagent") + got, err := tg.MCP.read() + if err != nil { + t.Fatal(err) + } + if o := got["old"]; o == nil || o.Command != "node" || !slices.Equal(o.Args, []string{"server.js", "--x"}) { + t.Errorf("old read as %+v", o) + } + if r := got["remote"]; r == nil || r.URL != "https://example.com/r" || r.Transport != "http" { + t.Errorf("remote read as %+v", r) + } + + ok(t)(SaveServer("", Server{Name: "fs", Transport: "stdio", Command: "npx", Agents: []string{"liveagent"}})) + p := filepath.Join(d, "config.json.live-mcp.json") + f := readLiveMCP(t, p) + if len(f.Servers) != 3 { + t.Fatalf("servers:\n%s", read(t, p)) + } + old := liveServer(f, "old") + if old["enabled"] != false || old["command"] != "node" || old["timeoutMs"] != float64(20000) { + t.Errorf("old carried over as %v", old) + } + if r := liveServer(f, "remote"); r["transport"] != "http" || r["enabled"] != true { + t.Errorf("remote carried over as %v", r) + } + if st, err := os.Stat(p); err != nil || os.PathSeparator == '/' && st.Mode().Perm() != 0o600 { + t.Errorf("a new file is the user's alone, as K-brain writes it: %v %v", st.Mode(), err) + } + if f.Selected != nil { + t.Errorf("nothing picked, every server is used: %v", f.Selected) + } +} + +// A file K-brain itself couldn't read is not written over. +func TestLiveAgentMCPUnreadable(t *testing.T) { + h := sandbox(t) + d := liveAgentHome(t, h) + p := filepath.Join(d, "config.json.live-mcp.json") + write(t, p, `{"servers": [ {"id": "mine", `) + SaveServer("", Server{Name: "fs", Transport: "stdio", Command: "npx", Agents: []string{"liveagent"}}) + if got := read(t, p); got != `{"servers": [ {"id": "mine", ` { + t.Errorf("wrote over a file it couldn't read:\n%s", got) + } +} + +type liveSkillSettings struct { + Revision uint64 `json:"revision"` + Global struct { + Enabled bool `json:"enabled"` + Selected []string `json:"selected"` + Mode string `json:"mode"` + } `json:"global"` + Projects map[string]any `json:"projects"` +} + +func readLiveSkills(t *testing.T, p string) liveSkillSettings { + t.Helper() + var s liveSkillSettings + if err := json.Unmarshal([]byte(read(t, p)), &s); err != nil { + t.Fatalf("%v:\n%s", err, read(t, p)) + } + return s +} + +// K-brain walks past a link in its skills folder and uses a skill there +// only once picked in skills-settings.json (internal/skills/managed.go +// ScanDetailed, Manager.Effective): LiveAgent gets a copy, picked once. +// One the user unpicks stays unpicked; one taken from LiveAgent is +// unpicked; the user's own picks and fields are kept. +func TestLiveAgentSkills(t *testing.T) { + h := sandbox(t) + d := liveAgentHome(t, h) + sp := filepath.Join(d, "skills-settings.json") + write(t, sp, `{ + "revision": 4, + "global": {"enabled": true, "selected": ["mine"], "mode": "custom", "skillNames": ["mine"]}, + "projects": {"/work": {"enabled": false, "selected": []}} +}`) + skill(t, filepath.Join(d, "skills", "mine"), "mine", "My own") + src := filepath.Join(h, "src/skills") + skill(t, filepath.Join(src, "pdf"), "pdf", "Read PDFs") + skill(t, filepath.Join(src, "xlsx"), "xlsx", "Sheets") + if _, err := ProbeSkills(src); err != nil { + t.Fatal(err) + } + ok(t)(InstallSkills(src, []string{"pdf", "xlsx"}, []string{"liveagent"})) + + for _, n := range []string{"pdf", "xlsx"} { + p := filepath.Join(d, "skills", n) + st, err := os.Lstat(p) + if err != nil || !st.IsDir() { + t.Fatalf("%s is no folder of its own (K-brain refuses a link): %v %v", n, st, err) + } + if _, err := os.Stat(filepath.Join(p, "SKILL.md")); err != nil { + t.Errorf("%s has no SKILL.md", n) + } + } + s := readLiveSkills(t, sp) + if !slices.Equal(s.Global.Selected, []string{"mine", "pdf", "xlsx"}) || !s.Global.Enabled || s.Global.Mode != "custom" || s.Revision != 5 || s.Projects["/work"] == nil { + t.Errorf("settings:\n%s", read(t, sp)) + } + if !strings.Contains(read(t, sp), `"skillNames"`) { + t.Errorf("lost the user's skillNames:\n%s", read(t, sp)) + } + + // a sync with nothing new writes nothing + before := read(t, sp) + ok(t)(Sync()) + if read(t, sp) != before { + t.Errorf("a sync rewrote the settings:\n%s", read(t, sp)) + } + + // the user unpicks xlsx in LiveAgent: a sync leaves it unpicked + write(t, sp, strings.Replace(read(t, sp), `"xlsx"`, `"other"`, 1)) + ok(t)(Sync()) + if s := readLiveSkills(t, sp); slices.Contains(s.Global.Selected, "xlsx") { + t.Errorf("a sync picked xlsx again: %v", s.Global.Selected) + } + + // pdf taken from LiveAgent: its copy and its pick go, the rest stays + ok(t)(SkillAgents("pdf", []string{})) + if _, err := os.Stat(filepath.Join(d, "skills", "pdf")); !os.IsNotExist(err) { + t.Errorf("pdf's copy is still there: %v", err) + } + s = readLiveSkills(t, sp) + if slices.Contains(s.Global.Selected, "pdf") || !slices.Contains(s.Global.Selected, "mine") || !slices.Contains(s.Global.Selected, "other") { + t.Errorf("selected after pdf went: %v", s.Global.Selected) + } + if _, err := os.Stat(filepath.Join(d, "skills", "mine", "SKILL.md")); err != nil { + t.Error("the user's own skill went") + } + + // given again, picked again: a new copy + ok(t)(SkillAgents("pdf", []string{"liveagent"})) + if s := readLiveSkills(t, sp); !slices.Contains(s.Global.Selected, "pdf") { + t.Errorf("pdf given again isn't picked: %v", s.Global.Selected) + } +} + +// With no skills-settings.json, magpie writes K-brain's defaults with its +// picks; a name K-brain refuses (validManagedName) is never put there, +// for its next save would fail on it. +func TestLiveAgentSkillsNewSettings(t *testing.T) { + h := sandbox(t) + d := liveAgentHome(t, h) + src := filepath.Join(h, "src/skills") + skill(t, filepath.Join(src, "pdf"), "pdf", "Read PDFs") + skill(t, filepath.Join(src, "My_Skill"), "My_Skill", "Odd name") + if _, err := ProbeSkills(src); err != nil { + t.Fatal(err) + } + ok(t)(InstallSkills(src, []string{"pdf", "My_Skill"}, []string{"liveagent"})) + sp := filepath.Join(d, "skills-settings.json") + s := readLiveSkills(t, sp) + if !s.Global.Enabled || !slices.Equal(s.Global.Selected, []string{"pdf"}) || s.Revision != 1 { + t.Errorf("settings:\n%s", read(t, sp)) + } +} + +// LiveAgent's own skills, made in its folder at every start, are not +// offered to bring into the library; a skill of the user's there is. +func TestLiveAgentBuiltinSkillsNotFound(t *testing.T) { + h := sandbox(t) + d := liveAgentHome(t, h) + skill(t, filepath.Join(d, "skills", "skills-creator"), "skills-creator", "built in") + skill(t, filepath.Join(d, "skills", "skills-installer"), "skills-installer", "built in") + skill(t, filepath.Join(d, "skills", "mine"), "mine", "My own") + l, err := load() + if err != nil { + t.Fatal(err) + } + var names []string + for _, f := range foundSkills(l) { + names = append(names, f.Name) + } + if slices.Contains(names, "skills-creator") || slices.Contains(names, "skills-installer") || !slices.Contains(names, "mine") { + t.Errorf("found: %v", names) + } +} diff --git a/internal/library/mcp.go b/internal/library/mcp.go index 0bf074cf7..f2385ac47 100644 --- a/internal/library/mcp.go +++ b/internal/library/mcp.go @@ -236,6 +236,10 @@ const ( // command/args/env or url/headers — no type on an entry, its shape // saying which, and no way to name SSE (kiro.dev/docs/mcp/configuration) fmtKiro + // fmtLiveAgent is LiveAgent's MCP settings, K-brain's + // config.json.live-mcp.json: a list of servers, each by its id, stdio + // or streamable HTTP (liveagent.go) + fmtLiveAgent ) // mcpFile is the file an agent keeps its user-wide MCP servers in. @@ -286,7 +290,7 @@ func (f *mcpFile) supports(s *Server) error { if f.Format == fmtDesktop && s.Remote() { return errNoRemote } - if s.Transport == "sse" && (f.Format == fmtCodex || f.Format == fmtGoose || f.Format == fmtDsh || f.Format == fmtPiNative || f.Format == fmtGrok || f.Format == fmtCommandCode || f.Format == fmtZed || f.Format == fmtKiro) { + if s.Transport == "sse" && (f.Format == fmtCodex || f.Format == fmtGoose || f.Format == fmtDsh || f.Format == fmtPiNative || f.Format == fmtGrok || f.Format == fmtCommandCode || f.Format == fmtZed || f.Format == fmtKiro || f.Format == fmtLiveAgent) { return errNoSSE } if f.Format == fmtDsh && s.Name != "" && !dshServerName.MatchString(s.Name) { @@ -684,6 +688,23 @@ func (f *mcpFile) encode(s *Server) ordered { add("args", list(s.Args)) optional("env", s.Env) } + case fmtLiveAgent: + // as LiveAgent's own MCP settings save one (K-brain's LiveServer, + // internal/mcp/live.go): on, stdio or http, args, env and headers + // left out when there are none + add("enabled", true) + if s.Remote() { + add("transport", "http") + add("url", s.URL) + optional("headers", s.Headers) + } else { + add("transport", "stdio") + add("command", s.Command) + if len(s.Args) > 0 { + add("args", list(s.Args)) + } + optional("env", s.Env) + } case fmtCline: // as `cline mcp add` writes it; a url with no type would be SSE if s.Remote() { @@ -979,6 +1000,15 @@ func (f *mcpFile) decode(name string, m map[string]any) (*Server, bool) { } else { local(str(m, "command"), m["args"], m["env"]) } + case fmtLiveAgent: + // K-brain's transport, or a url's or a command's when there is + // none (normalizeLiveSettings); its http is streamable HTTP alone + switch t := strings.ToLower(strings.TrimSpace(str(m, "transport"))); { + case t == "http" || t == "" && str(m, "url") != "": + remote("http", str(m, "url"), m["headers"]) + case t == "stdio" || t == "": + local(str(m, "command"), m["args"], m["env"]) + } default: // Claude Code, Cursor, Copilot, Crush, ZCode, omp, Grok, Zed t := str(m, "type") if u := str(m, "url"); u != "" { @@ -1011,6 +1041,9 @@ func (f *mcpFile) entries() (map[string]map[string]any, error) { if f.Format == fmtDsh { return dshEntries(f.Path) } + if f.Format == fmtLiveAgent { + return liveAgentEntries(f.Path) + } kind := fmt.Sprintf("mcp entries %d %s", f.Format, f.key()) es, err := filememo.Read(kind, f.Path, f.parseEntries) if errors.Is(err, fs.ErrNotExist) { @@ -1266,6 +1299,9 @@ var owned = map[mcpFormat][]string{ // disabled, autoApprove, disabledTools and oauth are the user's; a // transport names nothing Kiro reads fmtKiro: {"transport", "url", "headers", "command", "args", "env"}, + // enabled, and the id's description, docsUrl, cwd, timeoutMs, + // workspaceRoots, policy and auth, are the user's + fmtLiveAgent: {"transport", "url", "headers", "command", "args", "env"}, // a url agy read in place of serverUrl goes when magpie writes one fmtAntigravity: {"type", "serverUrl", "url", "headers", "command", "args", "env"}, @@ -1387,6 +1423,8 @@ func (f *mcpFile) putEntry(s *Server, o ordered) error { } } return nil + case fmtLiveAgent: + return liveAgentPut(f.Path, s.Name, o) } // Claude Code saves the file under its own lock: read and written // back under it, or a save of its own between the two is lost (#4747) @@ -1434,6 +1472,8 @@ func (f *mcpFile) del(name string) error { return nil case fmtCodex, fmtGrok: return delCodex(f.Path, name, true) + case fmtLiveAgent: + return liveAgentDel(f.Path, name) case fmtGoose: return edit.DelYAML(f.Path, "extensions."+name) case fmtHermes: diff --git a/internal/library/skills.go b/internal/library/skills.go index 974d3bcd1..ded191b68 100644 --- a/internal/library/skills.go +++ b/internal/library/skills.go @@ -595,6 +595,8 @@ func (l *Library) syncSkills(t *Target, res *Result, all []*Target) { return } id := t.Agent.ID + // LiveAgent uses a skill in its folder only once it is picked there + defer l.syncLiveAgentPicks(t, res) a := l.applied(id) // another agent may read the very same folder (one linked to the other): // what that agent is to have stays @@ -2169,6 +2171,10 @@ func foundSkills(l *Library) []FoundSkill { es, _ := os.ReadDir(pl.dir) for _, e := range es { name := e.Name() + // LiveAgent's own, which it makes again in its folder + if pl.agent == "liveagent" && slices.Contains(liveAgentBuiltins, name) { + continue + } p := filepath.Join(pl.dir, name) f := byName[name] // magpie's link to the library's folder is an agent having the diff --git a/internal/library/targets.go b/internal/library/targets.go index 85a674280..0bf53bfea 100644 --- a/internal/library/targets.go +++ b/internal/library/targets.go @@ -515,6 +515,17 @@ func targetOf(a *agent.Agent) *Target { t.Instructions = filepath.Join(d, "steering", "AGENTS.md") t.MCP = &mcpFile{Path: filepath.Join(d, "settings", "mcp.json"), Format: fmtKiro} t.Skills = filepath.Join(d, "skills") + case "liveagent": + // LiveAgent's engine, K-brain, keeps its MCP servers in + // config.json.live-mcp.json beside its config.json, in the folder + // LiveAgent hands it as $LIVEAGENT_HOME (agent.liveAgentDir), and + // its own skills in skills there, as copies: it refuses a link in + // a skill's path. A skill there is used once it is picked in + // skills-settings.json (liveagent.go; K-brain 507f560 cmd/kn/ + // backend.go, internal/skills/managed.go; zero2sin on Discord) + t.MCP = &mcpFile{Path: filepath.Join(a.Dir, liveAgentMCP), Format: fmtLiveAgent} + t.Skills = filepath.Join(a.Dir, "skills") + t.Copy = true case "claude-desktop": // Claude Desktop reads only commands from its file: a remote server // is added in its own Connectors settings. In its 3p mode (magpie's