gateway: a key can be held to some MCP servers and tools
wakaka on Discord (#help, 11-06) asked for gateway keys limited to some MCP servers and tools, as keys already are to models (#882). A key's MCP list (caller-keys.json "mcp") holds entries "server" (every tool of it) or "server/tool"; "-" alone is no MCP server; an empty list is every server, as before. A key issued under another is held to its issuer's list too. Every MCP route checks it: - magpie's own servers (web search, vision, image, Magpie Browser, plugin tools) through serveMCP: initialize/tools/list/tools/call are refused or filtered per server and tool, and /v1/magpie/key-limits names "mcp"; - the Library hub ("magpie"): only the backing servers and tools the key may use are listed, and a call by name or by fallback is refused; - /mcp/<name> and /mcp/run/<name>: the server is refused, tools/list is filtered in JSON and SSE replies, tools/call refused; a reply the filter can't read (an encoded body) is a 502, never passed through. GUI: "MCP servers" in the key row's menu opens the app's own picker (no native select) with All, No MCP server, each server and its tools (GET /api/caller-keys/mcp lists magpie's own servers and the Library's). A key held to some shows a badge saying which, that opens the same list; a free key shows nothing more in its row, on hover either. A hover badge was tried first: it pushed the row past 560px (gateway-caller-keys) and squeezed the masked key under a drag at 420px (gateway-key-arrange). CLI: magpie gateway-key mcp <id> github fs/read_file | none | all. zh, zh-TW, ja, de strings; docs/reference.md and the gateway-routing and library subsystem pages. Not covered: a model's own built-in web search (a vendor tool, not MCP). GET /api/caller-keys/mcp is named in the CLI parity test's notYet (its list is what `magpie gateway-key mcp` takes; TestEveryRouteHasACommandOrIsNamed caught it at the rebased head). Run on mote (mote-run), at the pushed head: - go test ./internal/access ./internal/cli ./internal/gui ./internal/library ./internal/gateway at a9c40186d (this change on2ce44dc28): ok except internal/gui's TestMainWindowCorners/macOS_26_SDK (#3949, the same message on macOS 27). After the rebase ontoa9667daad(no file in common): TestCoreScriptBudget, TestCallerKey*, TestEveryRoute*, TestGatewayKey*, TestKeyMCP*, internal/access and go vet ./internal/... at d36f89224's tree: ok. - gateway-caller-keys chromium en reads wider than 560px 4 of 6 runs alone on this branch and 4 of 6 on origin/maina9667daad: #3797, recorded there. - go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: clean; darwin, linux (nogui) and windows builds ok; gofmt -l clean. - GUI: gateway-key-mcp.test.cjs in chromium and webkit, widths 1100 and 420, en/zh/zh-TW/ja/de: 20/20. Every gateway-key*, gateway-keys* and i18n* file in both engines: ok except gateway-key-models en (red on origin/mainecc26a339too, #4081/#5233) and i18n-keys "a plugin's words are its own" (red on main, #5332). - The whole GUI suite (both engines, every language) with the hover badge: 91 reds in 25 files. Rerun alone on this branch and on origin/main54dc257f1: only gateway-caller-keys (560px sideways), gateway-key-readonly, models-fold and models-select-all-api were red on the branch alone; the badge moved into the row menu for the first two. After it, every gateway-key*, gateway-caller-keys, gateway-card, gateway-connect-keys, api-key-theme and i18n* file passes in both engines, except i18n-keys "a plugin's words are its own" (red on main, #5332, none of the three strings are this change's) and 1 of 20 models-select-all-api "the click scrolled" (#4389; models-fold is #4071). The rest are red on origin/main too and each has an issue: account-weight #4644, codex-auto-reset #2360, header-centre #3479, images-codex-one #4618, key-replace #4126, menu-input-scroll #3402, mobile-web #3952, model-chip-steady #4388, model-copy-id #4621, models-works-only #4391, nav-timeout #4787, omarchy #4624, page-width-steady #5013, phone-connect-menu #4706/#4707, plugin-move-unserved #4392. Broken by hand, each went red: the serveMCP server gate, call check and list filter, the own-server list filter and key-limits "mcp" (TestKeyMCPOwnServer); hubTools, hubServersOf, the hubToolNamed fallback and hubMCPRun (TestKeyMCPHub); /mcp/run (TestKeyMCPRun); the /mcp/<name> guard and filter (TestKeyMCPProxy); the GUI's "No MCP server" being exclusive (gateway-key-mcp). gateway-key-readonly chromium 420 ja was red with the hover badge (the sibling run, the whole suite and its rerun; green on origin/main) and passes with the badge in the row menu. Not tried: a real Library server through a live gateway, the hub with a real agent, and running on Windows or Linux (vet and build only). Reported-by: wakaka
This commit is contained in:
@@ -664,6 +664,8 @@ magpie gateway-key models <id> openai/gpt-5 anthropic/* # only these models
|
||||
magpie gateway-key models <id> all # every model
|
||||
magpie gateway-key accounts <id> codex/me@example.com # only these accounts
|
||||
magpie gateway-key accounts <id> all # every account
|
||||
magpie gateway-key mcp <id> github fs/read_file # only these MCP servers and tools
|
||||
magpie gateway-key mcp <id> none # no MCP server (all: every one)
|
||||
magpie gateway-key quotas <id> on # told the quotas of what it may use
|
||||
```
|
||||
|
||||
@@ -776,6 +778,25 @@ magpie's list of decision models, only when it names it (or its
|
||||
`<provider>/*`). The menu lists the decision models after their provider's
|
||||
chat models, each marked as one (Kautism on Discord).
|
||||
|
||||
A gateway key can also be held to some **MCP servers and tools** (wakaka
|
||||
on Discord): pick them under **MCP servers** in the key row's ⋯ menu (a
|
||||
key held to some then shows a badge that opens the same list), or run
|
||||
`magpie gateway-key mcp <id> github fs/read_file` (`all` takes the
|
||||
restriction off, `none` gives the key no MCP server). An entry is a
|
||||
server's name, every tool of it, or `<server>/<tool>`, that tool alone; the
|
||||
servers are the Library's (by their names there) and magpie's own:
|
||||
`magpie-web-search`, `magpie-vision`, `magpie-image`, `magpie-browser` and
|
||||
`magpie-tools`. Every route that reaches a server holds the key to it: the
|
||||
MCP hub lists only the servers and tools the key may use and refuses a
|
||||
call of any other; `/mcp/<name>` and `/mcp/run/<name>` answer 403 for a
|
||||
server the key may not use, leave the tools it may not use out of
|
||||
`tools/list` and refuse a `tools/call` of one; magpie's own servers do the
|
||||
same, and `/v1/magpie/mcp` lists only those the key may use. A key issued
|
||||
under a held key is held to its issuer's list too. `GET /v1/magpie/limit`
|
||||
tells a held key its list as `mcp`. A model's own web search, which magpie
|
||||
serves through its search when the provider has none, is not an MCP call
|
||||
and is not held by this list.
|
||||
|
||||
A gateway key can also be held to some **accounts** (#905): the accounts
|
||||
and keys its requests may use, picked in the same menu right after their
|
||||
provider's models — an account by who is signed in, a key by its
|
||||
|
||||
@@ -152,6 +152,7 @@ recorded as a prediction failure (`noPrediction`).
|
||||
- Each request that had anything masked is recorded as it goes to the vendor (`noteMasked` in [`masked.go`](../../internal/gateway/masked.go), from chat, the Codex backend, search, images, video, System One, embeddings and audio; count_tokens is masked and not recorded). The masker says what it swapped through `gwmw.Teller` (`JSONHits`, `TextHits`: each placeholder's kind, its finder, `redact.ByRule`, `ByYours`, `ByWord`, `ByModel` or `ByKnown`, and a hint of its first characters and its length), and [`internal/maskrec`](../../internal/maskrec/maskrec.go) keeps one line per request in a file per day under `~/.config/magpie/masking`, 30 days and 100 MB in all: the agent (the one usage records, `callerOf`, so a request another magpie passed on is named by the agent it came from, not as `magpie`; linkaww on Discord), session, provider, model, and each placeholder with its kind, finder, action and hint, never the value. A chat, an embedding or a video whose group can pass it to another member is held in memory until the request is over (`noteMaskedUntil`, `maskrec.Hold`), and its line names the provider and model the last try went to, not the first planned, which a failover may never have reached; the list sorts each day's lines by key, since a long request's line is written after later ones. The text around each placeholder as the vendor saw it is kept in memory only, for the last 400 records, and what a placeholder stood for only in the masker's own memory (`Teller.Value`); after a restart neither is there. A recent call (`Call.Masked`) and the route trace (`Route.Masked`) carry the counts and the record's key, which the Gateway and Routing pages' badge opens in Settings → Privacy (`/api/masking/*`, [`internal/gui/masking.go`](../../internal/gui/masking.go)). A masker without `Teller`, a plugin's, masks as before and records nothing. Under a test binary testenv isolated nothing is written (`maskrec.inTest`). The page's Clear records… (after a confirm) posts `/api/masking/clear`, and `maskrec.Clear` removes every day's file whole under the store's lock, with the in-memory text around placeholders; a day it can't remove stays listed and is named in the error. What the masker holds for each placeholder stays, so a placeholder still in an agent's context is put back in its answers.
|
||||
- `DecidesModel` gives a 400 (`decisionModelRefused`; a decision group, `decisionGroupRefused`), and count_tokens gives the same 400 before the vendor is asked. For OpenRouter, a variant of a model its decisions list names (`inception/mercury-decide:free`, picked by hand) is a decision model too (`openRouterVariant`): OpenRouter lists the model once, and answered such a variant 400 "is a decisions model" on chat/completions (coeo91 on Discord).
|
||||
- A gateway key held to some models (`keyHolds`, #882) gets a 403 for any other model. A routing group passes only through `groupAllowed`, which every route asks (the model lists' `entryAllowed`, `serve`, `countHeld`, embeddings, images, videos, decision groups, a subagent's and masking's route): a group of the user's own only when the key names it, whatever its members (kautism on Discord), a found group (`foundGroup`), or any group for a key that names accounts and no model (`Identity.AccountModels`), when the key may use every member; a bare name that is both a group of the user's the key may not use and a model it may use is that model for the key (`keyGroupFor`; `TestGatewayKeyGivenAModelIsNotGivenItsGroup`). A decision model is one: `serveSystemOne` and the decision list another magpie asks for (`DecidersHeader`) hold the key to it, while a group the key names asks its own decider in `askJev` with no key check (`TestGatewayKeyHeldToAGroupKeepsItsDecider`); the key editor offers the decision models (`GET /api/caller-keys/models`, `decides`, `TestCallerKeyModelsOfferDeciders`, `gateway-key-deciders.test.cjs`).
|
||||
- A gateway key held to some MCP servers and tools (`Key.MCP`, [`access/mcp.go`](../../internal/access/mcp.go), wakaka on Discord) is held on every MCP route, in [`mcp_key.go`](../../internal/gateway/mcp_key.go): `serveMCP` refuses a server it may not use with a 403 (`mcpKeyServe`), leaves its tools out of `tools/list` (`mcpKeyList`) and refuses their `tools/call` with -32602 (`mcpKeyCall`); the hub is held per Library server behind it (`hubServersOf`, `hubTools`, the `hubToolNamed` fallback and `hubMCPRun`, which every hub call goes through); `/mcp/<name>` and `/mcp/run/<name>` go through `mcpKeyGuard`, which reads the request for a refused `tools/call` (a batch with one gets a 403) and filters a `tools/list` answer, JSON whole or SSE event by event (`mcpToolsFilter`), refusing with a 502 an answer it can't read (a Content-Encoding); `/v1/magpie/mcp` lists only the key's servers (`ownMCPList`). An issued key is held to its issuer's list too (`Identity.MCPServer`, `MCPAllows`). Tests: `TestKeyMCPOwnServer`, `TestKeyMCPHub`, `TestKeyMCPProxy`, `TestKeyMCPRun`, `TestKeyMCPFilterRefusesUnreadable`; the picker is `GET /api/caller-keys/mcp` (`TestCallerKeyMCPRoutes`, `gateway-key-mcp.test.cjs`). A model's own web search, served through magpie's search, is not an MCP call and is not held by it.
|
||||
- A model the user disabled (#1867) gets a 403 for every caller (`idOff`), before anything is sent; see [Disabled models](#disabled-models).
|
||||
- Sealed tasks (#619) are checked here. A Codex subagent's task its lead's `spawn_agent` sealed goes only to a ChatGPT account, or back to the Responses provider that answered the lead (`leadProvider`, a relay of the ChatGPT backend such as Sub2API, #1109), relayed as it came even when web search is offered. A lead's turn carrying its subagent's sealed reply (`send_message`) goes back to the Responses provider that answered the lead's own conversation (`leadProvider` of the request's `conversationID`, #1237); otherwise it is refused before anyone is asked (`sealedReader`, `sealedTaskError`). A sealed message (`Message Type: MESSAGE`, not a task) that nobody asked can open is left out instead, an `input_text` note naming its sender in its place (`withoutSealedMessages`, #1613): a lead on a chat provider whose subagent is on one of Codex's own models goes on, as the subagent's final result still reaches it as text. Only a sealed task (`NEW_TASK`, or an item with neither header) is refused. Who answered is first what affinity remembers; when affinity has let it go (a day since, a restart past the 512 conversations `affinity.json` keeps, or the lead's last reply broken off, `unanswered`), the usage log's answers to the lead's thread and the request's own conversation in the last 30 days count too (`loggedAnswers`, #1367), and `leadFirst` reads the lead's key or account from them. A refused or failed call and a title answer nothing, and Codex's own sign-in is told of as the ChatGPT backend. The refusal names who sealed the task when it is known, and says how to go on with it. It also says what is sealed (`sealedTaskItself`, #1855): the task itself, `spawn_agent`'s `message`, which the backend returns sealed (`encrypted_function_args`) and Codex hands the subagent as it came, so `fork_turns="none"`, which only leaves the lead's turns out, doesn't help; nothing in it can be left out for the subagent to go on.
|
||||
- A model set for Codex's subagents (`settings.CodexSubagentModel`, the Agents page's Codex "subagent model", willz on Discord) is put on a Codex subagent's request (`x-openai-subagent` read as `kind:collab_spawn`) before this check, whatever model its lead's `spawn_agent` asked for (`codexSubagentPick` in [`codex_subagent.go`](../../internal/gateway/codex_subagent.go)): in `codexBackend` for one of Codex's own bare models, which then goes through `serveAgent`, and in `serve` for any other. Any model magpie serves can be set (`provider.SetCodexSubagentModel`, #1633): a task handed as text (a lead magpie served on a chat provider, or multi-agent V1) is read by any model. A request carrying a task the ChatGPT backend sealed (`sealedTaskIn`: a sealed agent message that isn't a `MESSAGE`, which `withoutSealedMessages` leaves out) is put only on a ChatGPT account's model; set to another, the subagent stays on the model asked for, which the sealed gate below handles as with nothing set. When magpie doesn't serve the model set now, or a gateway key held to some models may not use it, the subagent goes on the model asked for too. The route trace keeps both models and the reason it stayed (`Route.Subagent`), and the Routing page's `kindWhy` says it. Set to `lead` (`provider.CodexSubagentLead`, "Same as the lead"), the model is the one the lead's own turns last went on (`codexLeads.lookup`: the parent thread's, else the session's, else the gateway key's last turn), with `SubagentPick.Lead`; `codexBackend` then picks for any model asked, a magpie model too, and a lead on one of Codex's own models takes the subagent to the ChatGPT sign-in on it (in `serve` such a lead leaves the request as asked). With no lead turn seen, the request goes as asked. The lead's turns, titles and every other kind are never moved.
|
||||
|
||||
@@ -64,6 +64,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it.
|
||||
- Every other agent (Cursor, Copilot and Goose, whose lists are allow-lists only, Zed, Kimi, Pi, Grok, Devin, Antigravity, Alma, dsh, omp, ZCode, Command Code, Cline, WorkBuddy, CodeBuddy, Droid, Claude Desktop, MiMo Code, DevEco Code, a plugin's agent) gets the server whole. `AgentView.ToolsOff` is false for it, and the open list of tools names those given the server as unable to turn off single tools. A project's file and Copy config… carry no tools turned off either.
|
||||
magpie records what it added (`Applied.ToolsOff` per server for a list in an entry, `Applied.ToolRules` for Claude Code's rules and OpenCode's keys) and takes back only that (`offList`): a name, rule or key the user had already is theirs and stays when the tool is turned on again, and an OpenCode key the user set to `true` is never written over. A list or `permissions.deny` that isn't a list of names is a problem, never taken as empty, and the file is left as it is. The key, and Claude Code's `permissions` or OpenCode's `tools`, goes when magpie's were the last in it. The editor's save sends no tools, so `SaveServer` keeps those turned off.
|
||||
- With the MCP router on (`MCPHub`), an agent that takes a Streamable HTTP server is given magpie's one `magpie` entry in place of the Library servers ticked for it, and each server's own entry again when it is turned off. One that can't, or has an entry called magpie of its own, or whose library has a server called magpie, keeps each server's own entry, and the page says why ([MCP router](mcp-router.md)).
|
||||
- A gateway key held to some MCP servers and tools (wakaka on Discord) reaches through the router only those: the gateway holds each hub tool to the Library server behind it (see [gateway routing](gateway-routing.md)). The key editor lists every Library server, the hub's or not, with the tools it last listed (`KeyMCPServers`, from the router's cards); a server that never listed shows no tools and can still be given whole.
|
||||
- magpie's own MCP servers (`magpie-image`, `magpie-browser`, `magpie-web-search`, `magpie-vision`, and any `mcp …` run by a program named magpie) run this computer's magpie (#1439). `InstallServer` gives it magpie by full path (`update.Program`: the AppImage, not its mount; Homebrew's opt link, not the Cellar), and that path is right only on this computer. When the library is read, and after every change, `heal` points such a server whose program isn't on this computer (another system's path, a magpie moved out of Downloads, a bare `magpie`) at this magpie, so the agents and `CheckServers` get it; a magpie program that is here (another build) and a server run by any other program stay as they are. A carried library (`Collect`, for a backup or a WebDAV or S3 sync) names it as plain `magpie`, so two computers carry the same bundle and a sync doesn't write one's path over the other's; `Put` then reads it as that computer's magpie. [`self_here.go`](../../internal/library/self_here.go)
|
||||
- Magpie Web Search (`magpie-web-search`, `searchServer` in [`market.go`](../../internal/library/market.go)) is the featured, opt-in server for magpie's web search: `magpie mcp search` (`RunSearch` in [`browsermcp.go`](../../internal/browsermcp/browsermcp.go)) passes each stdio message to the gateway's `/mcp/magpie/web-search`, as `magpie mcp browser` does to its own path, with no browser session. Its sheet says each search goes where Settings › Models › Web search sends it. That page's MCP server row (`#searchMcpRow`) keeps the address to copy, and under its words Give agents Magpie Web Search… opens the sheet in the Library (`magpie.call("library", "server", "magpie-web-search")`), Turn on the Library when the Library is off, and nothing in gateway mode, as Settings › Images does for Magpie Image (lutra_fs on Discord: the search was in Settings and not in the Library; `search-mcp-library.test.cjs`). Each agent is given a 120-second tool timeout for it (`selfTimeout`). An agent in WSL is not given it directly, as with Magpie Browser; the MCP router serves it there.
|
||||
- Magpie Browser (`magpie-browser`) is opt-in, added with no agents, so the router offers it to none until one is ticked (an agent asked to use the browser reached for AppleScript instead). While its extension is connected (`GET /api/library/browser`, read again every 3 seconds while the row is shown) and no agent has it, its row in the MCP list asks which agents may use it, on a line of its own under the row's name, command and chips (from the name's left edge to the row's right one, the row's `lib-asking`), a button per agent whose chip can be clicked; a button clicks that chip, so the choice goes through `servers/agents` as a chip's does, and the row asks nothing more (`browserAsk` in [`client.js`](../../internal/gui/assets/plugins/library/client.js); `library-browser-ask.test.cjs`).
|
||||
|
||||
@@ -149,6 +149,10 @@ type Key struct {
|
||||
// "<provider>/<account>": a signed-in account by its stable id, a
|
||||
// key by its fingerprint; none for every account, as keys always did.
|
||||
Accounts []string `json:"accounts,omitempty"`
|
||||
// MCP are the MCP servers and tools the key may use (mcp.go):
|
||||
// "<server>", "<server>/<tool>", or NoMCP alone for none; none
|
||||
// listed for every server and tool.
|
||||
MCP []string `json:"mcp,omitempty"`
|
||||
// Quotas lets a key held to a budget, models or accounts be told the
|
||||
// quotas of what it may use (#2216): the cards of the providers whose
|
||||
// every model it may use, of the accounts and keys it may use, names
|
||||
@@ -195,8 +199,11 @@ type Identity struct {
|
||||
// on Discord).
|
||||
AccountModels bool
|
||||
Accounts []string
|
||||
Quotas bool
|
||||
ReadOnly bool
|
||||
// MCP are the MCP servers and tools the key may use (Key.MCP); an
|
||||
// issued key is held to its issuer's too (Issuer.MCP)
|
||||
MCP []string
|
||||
Quotas bool
|
||||
ReadOnly bool
|
||||
// Browser: the key may connect the Magpie Browser extension and do
|
||||
// nothing else (Key.Browser).
|
||||
Browser bool
|
||||
@@ -401,6 +408,9 @@ type Change struct {
|
||||
// Accounts is what "accounts-key" sets (#905); none lets the key use
|
||||
// every account and key.
|
||||
Accounts []string `json:"accounts,omitempty"`
|
||||
// MCP is what "mcp-key" sets: none lets the key use every MCP server
|
||||
// and tool, NoMCP alone none of them.
|
||||
MCP []string `json:"mcp,omitempty"`
|
||||
// Quotas is what "quotas-key" sets (#2216).
|
||||
Quotas bool `json:"quotas,omitempty"`
|
||||
// ReadOnly is what "access-key" sets, and "add-key" gives the new key:
|
||||
@@ -563,6 +573,12 @@ func Update(action string, in Change) (string, error) {
|
||||
return "", err
|
||||
}
|
||||
keys[i].Accounts = as
|
||||
case "mcp-key":
|
||||
mcp, err := CleanMCP(in.MCP)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
keys[i].MCP = mcp
|
||||
case "quotas-key":
|
||||
keys[i].Quotas = in.Quotas
|
||||
case "issuer-key":
|
||||
@@ -610,7 +626,7 @@ func Update(action string, in Change) (string, error) {
|
||||
default:
|
||||
return "", fmt.Errorf("unknown key action %q", action)
|
||||
}
|
||||
if defaultKey && action != "remove-key" && action != "rename-key" && action != "limit-key" && action != "reset-limit-key" && action != "models-key" && action != "accounts-key" && action != "quotas-key" && action != "access-key" && action != "issuer-key" && action != "move-key" {
|
||||
if defaultKey && action != "remove-key" && action != "rename-key" && action != "limit-key" && action != "reset-limit-key" && action != "models-key" && action != "accounts-key" && action != "mcp-key" && action != "quotas-key" && action != "access-key" && action != "issuer-key" && action != "move-key" {
|
||||
mirror = &keys[i]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -320,7 +320,7 @@ func ScopeBrowser(id string) error {
|
||||
|
||||
// identityOf is who k is, folded into its issuer when it has one.
|
||||
func identityOf(k Key, keys []Key, now time.Time) (Identity, error) {
|
||||
who := Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More, Models: HeldModels(k.Models, k.Accounts), AccountModels: len(k.Models) == 0 && len(k.Accounts) > 0, Accounts: k.Accounts, Quotas: k.Quotas, ReadOnly: k.ReadOnly, Browser: k.Browser, Expires: k.Expires, Issues: k.Issues && k.Issuer == "" && !k.Browser}
|
||||
who := Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More, Models: HeldModels(k.Models, k.Accounts), AccountModels: len(k.Models) == 0 && len(k.Accounts) > 0, Accounts: k.Accounts, MCP: k.MCP, Quotas: k.Quotas, ReadOnly: k.ReadOnly, Browser: k.Browser, Expires: k.Expires, Issues: k.Issues && k.Issuer == "" && !k.Browser}
|
||||
// the default key as Default tells it: marked LAN, or the id the
|
||||
// settings name (settings read only for an unmarked key)
|
||||
who.Default = k.LAN || (k.ID != "" && settings.Load().LANKeyID == k.ID)
|
||||
@@ -346,7 +346,7 @@ func identityOf(k Key, keys []Key, now time.Time) (Identity, error) {
|
||||
if !p.Expires.IsZero() && (who.Expires.IsZero() || p.Expires.Before(who.Expires)) {
|
||||
who.Expires = p.Expires
|
||||
}
|
||||
who.Issuer = &Identity{KeyID: p.ID, KeyName: p.Name, Limit: p.Limit, More: p.More}
|
||||
who.Issuer = &Identity{KeyID: p.ID, KeyName: p.Name, Limit: p.Limit, More: p.More, MCP: p.MCP}
|
||||
return who, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
package access
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// A key's MCP list (Key.MCP, wakaka on Discord) holds it to some of the
|
||||
// MCP servers the gateway serves, and some of their tools: the Library's
|
||||
// servers (by the hub, /mcp/<name>, /mcp/run/<name>) and magpie's own
|
||||
// (web search, image recognition, image generation, Magpie Browser, the
|
||||
// plugin tools). An entry is a server's name, every tool of it, or
|
||||
// "<server>/<tool>", that one tool; NoMCP alone holds the key to none.
|
||||
// An empty list is every server, as keys always were.
|
||||
|
||||
// NoMCP is the list of a key held to no MCP server at all.
|
||||
const NoMCP = "-"
|
||||
|
||||
// mcpServerRe is a server's name as the Library takes one (library's
|
||||
// nameRe), and as magpie names its own servers.
|
||||
var mcpServerRe = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$`)
|
||||
|
||||
// CleanMCP is a key's MCP list as it is kept: each entry trimmed and
|
||||
// checked, told apart in no other way than as written, a tool dropped
|
||||
// whose server is listed whole, and NoMCP dropped beside any server.
|
||||
func CleanMCP(in []string) ([]string, error) {
|
||||
var out []string
|
||||
none := false
|
||||
for _, e := range in {
|
||||
e = strings.TrimSpace(e)
|
||||
if e == "" {
|
||||
continue
|
||||
}
|
||||
if e == NoMCP {
|
||||
none = true
|
||||
continue
|
||||
}
|
||||
server, tool, hasTool := strings.Cut(e, "/")
|
||||
if !mcpServerRe.MatchString(server) || hasTool && (tool == "" || len(tool) > 128 || strings.TrimSpace(tool) != tool) {
|
||||
return nil, errors.New("A key's MCP entry is <server> or <server>/<tool>, like github or github/search_code: " + e)
|
||||
}
|
||||
if !slices.Contains(out, e) {
|
||||
out = append(out, e)
|
||||
}
|
||||
}
|
||||
// a server listed whole has every tool already
|
||||
out = slices.DeleteFunc(out, func(e string) bool {
|
||||
server, _, hasTool := strings.Cut(e, "/")
|
||||
return hasTool && slices.Contains(out, server)
|
||||
})
|
||||
if len(out) > 500 {
|
||||
return nil, errors.New("A key can list at most 500 MCP servers and tools")
|
||||
}
|
||||
if len(out) == 0 && none {
|
||||
return []string{NoMCP}, nil
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// mcpServer is whether the list l lets in server, and whether it lets in
|
||||
// every tool of it; an empty list lets in everything.
|
||||
func mcpServer(l []string, server string) (ok, every bool) {
|
||||
if len(l) == 0 {
|
||||
return true, true
|
||||
}
|
||||
for _, e := range l {
|
||||
s, _, hasTool := strings.Cut(e, "/")
|
||||
if s != server {
|
||||
continue
|
||||
}
|
||||
if !hasTool {
|
||||
return true, true
|
||||
}
|
||||
ok = true
|
||||
}
|
||||
return ok, false
|
||||
}
|
||||
|
||||
// MCPHeld is whether the key, or the key it was issued under, is held to
|
||||
// some MCP servers or tools.
|
||||
func (who Identity) MCPHeld() bool {
|
||||
return len(who.MCP) > 0 || who.Issuer != nil && len(who.Issuer.MCP) > 0
|
||||
}
|
||||
|
||||
// MCPServer is whether the key may reach the MCP server called server,
|
||||
// and whether it may use every tool of it (else MCPAllows says which).
|
||||
func (who Identity) MCPServer(server string) (ok, every bool) {
|
||||
ok, every = mcpServer(who.MCP, server)
|
||||
if who.Issuer != nil {
|
||||
pOK, pEvery := mcpServer(who.Issuer.MCP, server)
|
||||
ok, every = ok && pOK, every && pEvery
|
||||
}
|
||||
return ok, ok && every
|
||||
}
|
||||
|
||||
// MCPAllows is whether the key may use the tool of the MCP server called
|
||||
// server.
|
||||
func (who Identity) MCPAllows(server, tool string) bool {
|
||||
allows := func(l []string) bool {
|
||||
ok, every := mcpServer(l, server)
|
||||
return every || ok && slices.Contains(l, server+"/"+tool)
|
||||
}
|
||||
return allows(who.MCP) && (who.Issuer == nil || allows(who.Issuer.MCP))
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package access
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A key's MCP list is servers whole and <server>/<tool> entries, kept as
|
||||
// written; "-" alone holds it to none, and a bad entry is refused.
|
||||
func TestCleanMCP(t *testing.T) {
|
||||
got, err := CleanMCP([]string{" github ", "", "fs/read", "github/search_code", "fs/read", "magpie-web-search/web_fetch"})
|
||||
if err != nil || !slices.Equal(got, []string{"github", "fs/read", "magpie-web-search/web_fetch"}) {
|
||||
t.Fatal(got, err)
|
||||
}
|
||||
if got, err := CleanMCP([]string{NoMCP}); err != nil || !slices.Equal(got, []string{NoMCP}) {
|
||||
t.Fatal("none:", got, err)
|
||||
}
|
||||
if got, err := CleanMCP([]string{NoMCP, "fs"}); err != nil || !slices.Equal(got, []string{"fs"}) {
|
||||
t.Fatal("none beside a server:", got, err)
|
||||
}
|
||||
if got, err := CleanMCP(nil); err != nil || len(got) != 0 {
|
||||
t.Fatal("all:", got, err)
|
||||
}
|
||||
for _, bad := range []string{"fs/", "/read", "-fs", "a b", "fs/ read", "fs/" + strings.Repeat("x", 129), strings.Repeat("s", 65)} {
|
||||
if _, err := CleanMCP([]string{bad}); err == nil {
|
||||
t.Error("accepted", bad)
|
||||
}
|
||||
}
|
||||
many := make([]string, 501)
|
||||
for i := range many {
|
||||
many[i] = "fs/t" + strings.Repeat("x", i%7) + string(rune('a'+i%26)) + strings.Repeat("y", i/26)
|
||||
}
|
||||
if _, err := CleanMCP(many); err == nil {
|
||||
t.Error("took 501 entries")
|
||||
}
|
||||
}
|
||||
|
||||
// What a key may use: everything with no list, a server listed whole
|
||||
// with every tool, a listed tool alone of its server, nothing with "-";
|
||||
// an issued key is held to its issuer's list too.
|
||||
func TestKeyMCPAllows(t *testing.T) {
|
||||
all := Identity{}
|
||||
if all.MCPHeld() || !all.MCPAllows("fs", "read") {
|
||||
t.Fatal("a key with no list is held")
|
||||
}
|
||||
if ok, every := all.MCPServer("fs"); !ok || !every {
|
||||
t.Fatal("a key with no list: fs", ok, every)
|
||||
}
|
||||
who := Identity{MCP: []string{"github", "fs/read"}}
|
||||
for _, c := range []struct {
|
||||
server, tool string
|
||||
want bool
|
||||
}{
|
||||
{"github", "create_issue", true},
|
||||
{"fs", "read", true},
|
||||
{"fs", "write", false},
|
||||
{"magpie-web-search", "web_search", false},
|
||||
{"fs/read", "", false},
|
||||
} {
|
||||
if got := who.MCPAllows(c.server, c.tool); got != c.want {
|
||||
t.Errorf("%s %s: %v", c.server, c.tool, got)
|
||||
}
|
||||
}
|
||||
if ok, every := who.MCPServer("fs"); !ok || every {
|
||||
t.Error("fs is some tools:", ok, every)
|
||||
}
|
||||
if ok, every := who.MCPServer("github"); !ok || !every {
|
||||
t.Error("github is whole:", ok, every)
|
||||
}
|
||||
if ok, _ := who.MCPServer("linear"); ok {
|
||||
t.Error("linear isn't listed")
|
||||
}
|
||||
none := Identity{MCP: []string{NoMCP}}
|
||||
if ok, _ := none.MCPServer("fs"); ok || none.MCPAllows("fs", "read") || !none.MCPHeld() {
|
||||
t.Error("a key held to none")
|
||||
}
|
||||
// issued under a key held to github: its own wider list doesn't widen it
|
||||
child := Identity{MCP: []string{"github", "fs"}, Issuer: &Identity{MCP: []string{"github/search_code"}}}
|
||||
if !child.MCPHeld() || child.MCPAllows("fs", "read") || child.MCPAllows("github", "create_issue") || !child.MCPAllows("github", "search_code") {
|
||||
t.Error("an issued key past its issuer")
|
||||
}
|
||||
if ok, every := child.MCPServer("github"); !ok || every {
|
||||
t.Error("github under the issuer:", ok, every)
|
||||
}
|
||||
free := Identity{Issuer: &Identity{MCP: []string{"fs"}}}
|
||||
if !free.MCPHeld() || free.MCPAllows("github", "x") || !free.MCPAllows("fs", "x") {
|
||||
t.Error("an issued key with no list of its own")
|
||||
}
|
||||
}
|
||||
|
||||
// A key's MCP list is kept in caller-keys.json, reaches the gateway with
|
||||
// the key and with every key issued under it, and is cleared by an empty
|
||||
// list; a bad one is refused and leaves the list as it was.
|
||||
func TestKeyMCPKept(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
clockAt(t, time.Date(2026, 11, 6, 9, 0, 0, 0, time.UTC))
|
||||
id, secret := addKey(t, "Phone")
|
||||
if who, ok := Authenticate(secret); !ok || who.MCPHeld() {
|
||||
t.Fatal("a new key is held", who)
|
||||
}
|
||||
if _, err := Update("mcp-key", Change{Key: id, MCP: []string{"github", "fs/read"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := Update("mcp-key", Change{Key: id, MCP: []string{"fs/"}}); err == nil {
|
||||
t.Fatal("took a bad entry")
|
||||
}
|
||||
who, ok := Authenticate(secret)
|
||||
if !ok || !slices.Equal(who.MCP, []string{"github", "fs/read"}) || who.MCPAllows("fs", "write") {
|
||||
t.Fatal(who, ok)
|
||||
}
|
||||
if keys, _ := List(); !slices.Equal(keys[0].MCP, []string{"github", "fs/read"}) {
|
||||
t.Fatal("listed", keys[0].MCP)
|
||||
}
|
||||
if _, err := Update("issuer-key", Change{Key: id, Issues: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
child, err := IssueKey(Issue{TTL: time.Hour, Issuer: id})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cw, ok := Authenticate(child.Key); !ok || !cw.MCPHeld() || cw.MCPAllows("fs", "write") || !cw.MCPAllows("github", "x") {
|
||||
t.Fatal("issued:", cw, ok)
|
||||
}
|
||||
if _, err := Update("mcp-key", Change{Key: id}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if who, _ := Authenticate(secret); who.MCPHeld() {
|
||||
t.Fatal("an empty list still holds", who.MCP)
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,10 @@ func gatewayKeysTo(out io.Writer, args []string) error {
|
||||
access.MigrateLegacyLANKeyBestEffort()
|
||||
return gatewayKeyQuotas(out, args[1:])
|
||||
}
|
||||
if action == "mcp" {
|
||||
access.MigrateLegacyLANKeyBestEffort()
|
||||
return gatewayKeyMCP(out, args[1:])
|
||||
}
|
||||
if action == "access" {
|
||||
access.MigrateLegacyLANKeyBestEffort()
|
||||
return gatewayKeyAccess(out, args[1:])
|
||||
@@ -92,7 +96,7 @@ func gatewayKeysTo(out io.Writer, args []string) error {
|
||||
args = args[:2]
|
||||
}
|
||||
if (action == "list" && len(args) != 1) || (action != "list" && len(args) != 2) {
|
||||
return fmt.Errorf("usage: magpie gateway-key list | add <name> [--key <value> | --key -] [--read-only] | rotate <id> [--key <value> | --key -] | remove <id> | limit <id> [list | off | reset [<n>] | remove <n> | [add] day|week|month|<N>d|<N>h [--tokens N] [--cost USD] [--cache-reads] [--model <provider>/<model>|<provider>/* ...]] | models <id> [all | <provider>/<model>|<provider>/* ...] | accounts <id> [all | <provider>/<account>|<provider>/<key id> ...] | quotas <id> [on | off] | access <id> [read-only | full] | move <id> <place> | issue --ttl <duration> [--name <name>] [--models a,b] [--accounts a,b] [--tokens N] [--cost USD] [--read-only] [--from <id>] | issuer <id> [on | off] | oidc [list | add --key <id> --repo owner/name … | remove <rule id>]")
|
||||
return fmt.Errorf("usage: magpie gateway-key list | add <name> [--key <value> | --key -] [--read-only] | rotate <id> [--key <value> | --key -] | remove <id> | limit <id> [list | off | reset [<n>] | remove <n> | [add] day|week|month|<N>d|<N>h [--tokens N] [--cost USD] [--cache-reads] [--model <provider>/<model>|<provider>/* ...]] | models <id> [all | <provider>/<model>|<provider>/* ...] | accounts <id> [all | <provider>/<account>|<provider>/<key id> ...] | quotas <id> [on | off] | mcp <id> [all | none | <server>|<server>/<tool> ...] | access <id> [read-only | full] | move <id> <place> | issue --ttl <duration> [--name <name>] [--models a,b] [--accounts a,b] [--tokens N] [--cost USD] [--read-only] [--from <id>] | issuer <id> [on | off] | oidc [list | add --key <id> --repo owner/name … | remove <rule id>]")
|
||||
}
|
||||
switch action {
|
||||
case "list", "add", "rotate", "remove":
|
||||
@@ -475,6 +479,52 @@ func gatewayKeyModels(out io.Writer, args []string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// gatewayKeyMCP shows or sets the MCP servers and tools a key may use
|
||||
// (wakaka on Discord):
|
||||
//
|
||||
// magpie gateway-key mcp <id> what it may use
|
||||
// magpie gateway-key mcp <id> all every server
|
||||
// magpie gateway-key mcp <id> none no server
|
||||
// magpie gateway-key mcp <id> github fs/read_file only these
|
||||
func gatewayKeyMCP(out io.Writer, args []string) error {
|
||||
if len(args) == 0 {
|
||||
return fmt.Errorf("usage: magpie gateway-key mcp <id> [all | none | <server>|<server>/<tool> ...]")
|
||||
}
|
||||
id := args[0]
|
||||
if len(args) > 1 {
|
||||
l := args[1:]
|
||||
switch {
|
||||
case len(l) == 1 && l[0] == "all":
|
||||
l = nil
|
||||
case len(l) == 1 && l[0] == "none":
|
||||
l = []string{access.NoMCP}
|
||||
case slices.ContainsFunc(l, func(e string) bool { return strings.HasPrefix(e, "-") }):
|
||||
return fmt.Errorf("usage: magpie gateway-key mcp <id> [all | none | <server>|<server>/<tool> ...]")
|
||||
}
|
||||
if _, err := access.Update("mcp-key", access.Change{Key: id, MCP: l}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
keys, err := access.List()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
i := slices.IndexFunc(keys, func(k access.Key) bool { return k.ID == id })
|
||||
if i < 0 {
|
||||
return fmt.Errorf("Key not found")
|
||||
}
|
||||
k := keys[i]
|
||||
switch {
|
||||
case len(k.MCP) == 0:
|
||||
_, err = fmt.Fprintf(out, "%s: every MCP server\n", k.Name)
|
||||
case slices.Equal(k.MCP, []string{access.NoMCP}):
|
||||
_, err = fmt.Fprintf(out, "%s: no MCP server\n", k.Name)
|
||||
default:
|
||||
_, err = fmt.Fprintf(out, "%s: only %s\n", k.Name, strings.Join(k.MCP, ", "))
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// limitWords is a key's limits in the list: "-" for none, else what it
|
||||
// has used of each, "1200/1000000 tokens per day; $1.00/$20.00 per week".
|
||||
func limitWords(k access.Key, now time.Time) string {
|
||||
|
||||
@@ -548,3 +548,51 @@ func TestGatewayKeyScopedLimitCLI(t *testing.T) {
|
||||
t.Fatalf("a refused command left %d limits", len(ls))
|
||||
}
|
||||
}
|
||||
|
||||
// magpie gateway-key mcp sets, shows and takes off the MCP servers and
|
||||
// tools a key may use (wakaka on Discord), and refuses a flag or a bad
|
||||
// entry as one.
|
||||
func TestGatewayKeyMCPCLI(t *testing.T) {
|
||||
t.Setenv("HOME", t.TempDir())
|
||||
t.Setenv("USERPROFILE", os.Getenv("HOME"))
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
if err := settings.Save(settings.Settings{LAN: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
call := func(args ...string) (string, error) {
|
||||
var out bytes.Buffer
|
||||
err := gatewayKeysTo(&out, append([]string{"gateway-key"}, args...))
|
||||
return out.String(), err
|
||||
}
|
||||
if _, err := call("add", "Phone"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
keys, _ := access.List()
|
||||
id := keys[0].ID
|
||||
if got, err := call("mcp", id); err != nil || got != "Phone: every MCP server\n" {
|
||||
t.Fatal(got, err)
|
||||
}
|
||||
if got, err := call("mcp", id, "github", "fs/read_file"); err != nil || got != "Phone: only github, fs/read_file\n" {
|
||||
t.Fatal(got, err)
|
||||
}
|
||||
if keys, _ = access.List(); !slices.Equal(keys[0].MCP, []string{"github", "fs/read_file"}) {
|
||||
t.Fatal("kept", keys[0].MCP)
|
||||
}
|
||||
for _, args := range [][]string{{"mcp"}, {"mcp", id, "fs/"}, {"mcp", id, "--help"}, {"mcp", id, "-"}, {"mcp", "missing", "fs"}, {"mcp", "missing"}} {
|
||||
if _, err := call(args...); err == nil {
|
||||
t.Error("accepted", args)
|
||||
}
|
||||
}
|
||||
if keys, _ = access.List(); !slices.Equal(keys[0].MCP, []string{"github", "fs/read_file"}) {
|
||||
t.Fatal("a refused change was kept", keys[0].MCP)
|
||||
}
|
||||
if got, err := call("mcp", id, "none"); err != nil || got != "Phone: no MCP server\n" {
|
||||
t.Fatal(got, err)
|
||||
}
|
||||
if got, err := call("mcp", id, "all"); err != nil || got != "Phone: every MCP server\n" {
|
||||
t.Fatal(got, err)
|
||||
}
|
||||
if keys, _ = access.List(); keys[0].MCP != nil {
|
||||
t.Fatal("all kept", keys[0].MCP)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -135,6 +135,7 @@ const usage = `magpie — one place to pick every agent's model
|
||||
magpie gateway-key limit <id> [list|off|reset [n]|remove <n>|[add] day|week|month|<N>d|<N>h --tokens N --cost USD --cache-reads --model openai/*] a key's own limits, and what it used; --model counts only those models
|
||||
magpie gateway-key models <id> [all|<provider>/<model>|<provider>/* ...] the models a key may use, every one unless it names some
|
||||
magpie gateway-key quotas <id> [on|off] whether a key held to a budget, models or accounts is told the quotas of what it may use
|
||||
magpie gateway-key mcp <id> [all|none|<server>|<server>/<tool> ...] the MCP servers and tools a key may use
|
||||
magpie gateway-key access <id> [read-only|full] read-only: the key reads quotas and usage (GET /, /v1/magpie/quotas, /v1/magpie/usage) and uses no model, MCP server or write
|
||||
magpie gateway-key move <id> <place> put a key at a place in the list (from 1), the order list and the app show them in
|
||||
magpie gateway-key issue --ttl 1h [--name n] [--models a,b] [--accounts a,b] [--tokens N] [--cost USD] [--read-only] [--from <id>] [--json]
|
||||
|
||||
@@ -252,6 +252,7 @@ var notYet = map[string]string{
|
||||
"POST /api/library/browser/drag": L, // browser.go
|
||||
"POST /api/library/browser/extension": L, // browser.go
|
||||
"GET /api/caller-keys/models": P, // caller_keys.go
|
||||
"GET /api/caller-keys/mcp": L, // caller_keys.go: the servers `magpie gateway-key mcp` takes
|
||||
"POST /api/config/repair": A, // config_repair.go
|
||||
"GET /api/context": U, // context.go
|
||||
"GET /api/context/text": W, // context.go
|
||||
|
||||
@@ -227,8 +227,18 @@ func hubServersOf(ctx context.Context, agent string) []HubServer {
|
||||
if FromRouter(ctx) {
|
||||
ss = slices.DeleteFunc(ss, func(s HubServer) bool { return s.Bridge })
|
||||
}
|
||||
v := HubVisitorOf(ctx)
|
||||
return slices.DeleteFunc(ss, func(s HubServer) bool { return !v.Gives(s) })
|
||||
v, who := HubVisitorOf(ctx), access.Caller(ctx)
|
||||
ss = slices.DeleteFunc(ss, func(s HubServer) bool {
|
||||
ok, _ := who.MCPServer(s.Name)
|
||||
return !v.Gives(s) || !ok
|
||||
})
|
||||
// a key held to some tools of a server is told of those only
|
||||
for i, sv := range ss {
|
||||
if _, every := who.MCPServer(sv.Name); !every {
|
||||
ss[i].Tools = slices.DeleteFunc(slices.Clone(sv.Tools), func(n HubToolNote) bool { return !who.MCPAllows(sv.Name, n.Name) })
|
||||
}
|
||||
}
|
||||
return ss
|
||||
}
|
||||
|
||||
// hubServes is whether the hub gives another magpie's router a server.
|
||||
@@ -309,7 +319,9 @@ func hubTools(ctx context.Context, agent string) []hubTool {
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, hubListWait)
|
||||
defer cancel()
|
||||
ts := slices.DeleteFunc(slices.Clone(MCPHub.Tools(ctx, agent)), func(t HubTool) bool { return kept[t.Server] })
|
||||
// nor is one the calling gateway key may not use (access.Key.MCP)
|
||||
who := access.Caller(ctx)
|
||||
ts := slices.DeleteFunc(slices.Clone(MCPHub.Tools(ctx, agent)), func(t HubTool) bool { return kept[t.Server] || !who.MCPAllows(t.Server, t.Tool) })
|
||||
return hubNamed(ts)
|
||||
}
|
||||
|
||||
@@ -662,6 +674,9 @@ func hubToolNamed(ctx context.Context, ts []hubTool, agent, name string) (hubToo
|
||||
if !ok || tool == "" {
|
||||
continue
|
||||
}
|
||||
if !access.Caller(ctx).MCPAllows(sv.Name, tool) {
|
||||
continue
|
||||
}
|
||||
t := hubTool{HubTool: HubTool{Server: sv.Name, Tool: tool}, name: name}
|
||||
for _, l := range ts {
|
||||
if l.Server == sv.Name {
|
||||
@@ -702,6 +717,11 @@ func (s *Server) hubMCPRun(r *http.Request, agent string, t hubTool, args json.R
|
||||
use.on(t.Server)
|
||||
use.as(agent)
|
||||
use.named(t.name)
|
||||
// every hub call comes here: a tool the gateway key may not use is
|
||||
// refused whichever way it was found
|
||||
if who := access.Caller(r.Context()); !who.MCPAllows(t.Server, t.Tool) {
|
||||
return toolResult(keyMCPToolRefused(who, t.Server, t.Tool), true)
|
||||
}
|
||||
release, err := reserveFor(access.Caller(r.Context()), int64(len(args)), "", limitClock())
|
||||
if err != nil {
|
||||
return toolResult(err.Error(), true)
|
||||
|
||||
@@ -170,6 +170,8 @@ func protoOfPath(path string) provider.Protocol {
|
||||
// quota, with "quotaProviders" the providers it is told those of
|
||||
// (scopeQuotas). An account is not named: a key its owner tells no quota
|
||||
// is told no account either. A key held to nothing has none of these.
|
||||
// "mcp" is the MCP servers and tools a key may use, when its owner chose
|
||||
// some.
|
||||
func (s *Server) keyLimit(w http.ResponseWriter, r *http.Request) {
|
||||
who := access.Caller(r.Context())
|
||||
out := map[string]any{"limited": false, "key": who.KeyName}
|
||||
@@ -204,6 +206,10 @@ func (s *Server) keyLimit(w http.ResponseWriter, r *http.Request) {
|
||||
if who.KeyID != "" && who.Issuer != nil && len(who.Issuer.Limits()) > 0 {
|
||||
out["issuerLimits"] = budget.All(access.Key{ID: who.Issuer.KeyID, Name: who.Issuer.KeyName, Limit: who.Issuer.Limit, More: who.Issuer.More}, limitClock())
|
||||
}
|
||||
// "mcp", the MCP servers and tools a key is held to (access.Key.MCP)
|
||||
if who.KeyID != "" && len(who.MCP) > 0 {
|
||||
out["mcp"] = who.MCP
|
||||
}
|
||||
if !who.Expires.IsZero() {
|
||||
out["expires"] = who.Expires
|
||||
}
|
||||
|
||||
@@ -51,6 +51,12 @@ func runMCP(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "magpie runs no MCP server here", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
// a gateway key held to some MCP servers or tools (access.Key.MCP)
|
||||
w, r, done, ok := mcpKeyGuard(w, r, r.PathValue("name"))
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
defer done()
|
||||
RunMCP(w, r, r.PathValue("name"))
|
||||
}
|
||||
|
||||
@@ -74,6 +80,12 @@ func (s *Server) mcpProxy(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "magpie lends its MCP sign-ins to agents, not to web pages", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
// a gateway key held to some MCP servers or tools (access.Key.MCP)
|
||||
w, r, done, held := mcpKeyGuard(w, r, name)
|
||||
if !held {
|
||||
return
|
||||
}
|
||||
defer done()
|
||||
rec, ok := mcpauth.Get(name)
|
||||
if !ok {
|
||||
http.Error(w, "magpie isn't signed in to an MCP server called "+name+": sign in to it in magpie's Library", http.StatusNotFound)
|
||||
|
||||
@@ -0,0 +1,382 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
)
|
||||
|
||||
// A gateway key held to some MCP servers and tools (access.Key.MCP,
|
||||
// wakaka on Discord) is held to them on every route that reaches one:
|
||||
//
|
||||
// - magpie's own servers (web search, image recognition, image
|
||||
// generation, Magpie Browser, the plugin tools) and the hub all answer
|
||||
// through serveMCP, which refuses a server the key may not use, leaves
|
||||
// the tools it may not use out of tools/list and refuses a tools/call
|
||||
// of one (mcpKeyServe);
|
||||
// - the hub's tools are of the Library's servers, so it holds each to
|
||||
// the key by the server behind it: hubServersOf and hubTools leave out
|
||||
// what the key may not use, and hubMCPRun, which every hub call goes
|
||||
// through, refuses it;
|
||||
// - the relays, /mcp/<name> (a remote server magpie signed in to) and
|
||||
// /mcp/run/<name> (a command magpie runs), pass the server's own
|
||||
// messages on, so mcpKeyGuard reads the request for a tools/call and
|
||||
// the answer for a tools/list (mcpToolsFilter);
|
||||
// - OwnMCPPath lists only the servers the key may use.
|
||||
|
||||
// hubServerName is what serveMCP names the hub by; its tools are the
|
||||
// Library's servers', which the hub holds to the key itself.
|
||||
const hubServerName = "magpie"
|
||||
|
||||
// keyMCPServerRefused is what a key is told of a server it may not use.
|
||||
func keyMCPServerRefused(who access.Identity, server string) string {
|
||||
return "the gateway key " + quoteName(who.KeyName) + " may not use the MCP server " + server + ": its owner picks the MCP servers it may use in Gateway → Gateway keys"
|
||||
}
|
||||
|
||||
// keyMCPToolRefused is what a key is told of a tool it may not use.
|
||||
func keyMCPToolRefused(who access.Identity, server, tool string) string {
|
||||
return "the gateway key " + quoteName(who.KeyName) + " may not use the tool " + tool + " of the MCP server " + server + ": its owner picks the MCP tools it may use in Gateway → Gateway keys"
|
||||
}
|
||||
|
||||
func quoteName(s string) string { return "\"" + s + "\"" }
|
||||
|
||||
// mcpCallName is the tool a tools/call names.
|
||||
func mcpCallName(params json.RawMessage) string {
|
||||
var p struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
json.Unmarshal(params, &p)
|
||||
return p.Name
|
||||
}
|
||||
|
||||
// mcpKeyServe is whether serveMCP may answer r for server at all: a key
|
||||
// held to MCP servers that may not use it is refused, and told so.
|
||||
func mcpKeyServe(w http.ResponseWriter, r *http.Request, server string) bool {
|
||||
if server == hubServerName {
|
||||
return true
|
||||
}
|
||||
who := access.Caller(r.Context())
|
||||
if ok, _ := who.MCPServer(server); ok {
|
||||
return true
|
||||
}
|
||||
log.Printf("refused %s %s: gateway key %q may not use the MCP server %s", r.Method, r.URL.Path, who.KeyName, server)
|
||||
http.Error(w, keyMCPServerRefused(who, server), http.StatusForbidden)
|
||||
return false
|
||||
}
|
||||
|
||||
// mcpKeyCall is the JSON-RPC error a tools/call of server is refused
|
||||
// with for r's key; nil when it may run. The hub's calls are held by the
|
||||
// server behind each (hubMCPRun).
|
||||
func mcpKeyCall(r *http.Request, server string, m mcpMessage) map[string]any {
|
||||
if server == hubServerName {
|
||||
return nil
|
||||
}
|
||||
who := access.Caller(r.Context())
|
||||
if tool := mcpCallName(m.Params); !who.MCPAllows(server, tool) {
|
||||
return map[string]any{"code": -32602, "message": keyMCPToolRefused(who, server, tool)}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// mcpKeyList is result, a tools/list's of server, without the tools r's
|
||||
// key may not use.
|
||||
func mcpKeyList(r *http.Request, server string, result any) any {
|
||||
if server == hubServerName {
|
||||
return result
|
||||
}
|
||||
who := access.Caller(r.Context())
|
||||
if _, every := who.MCPServer(server); every {
|
||||
return result
|
||||
}
|
||||
b, err := json.Marshal(map[string]any{"result": result})
|
||||
if err != nil {
|
||||
return map[string]any{"tools": []any{}}
|
||||
}
|
||||
out, changed := keepTools(b, func(tool string) bool { return who.MCPAllows(server, tool) })
|
||||
if !changed {
|
||||
return result
|
||||
}
|
||||
var m struct {
|
||||
Result json.RawMessage `json:"result"`
|
||||
}
|
||||
if json.Unmarshal(out, &m) != nil {
|
||||
return map[string]any{"tools": []any{}}
|
||||
}
|
||||
return m.Result
|
||||
}
|
||||
|
||||
// keepTools is b, a JSON-RPC message or a batch of them, with each
|
||||
// result's tools (a tools/list's answer) cut to those keep names, and
|
||||
// whether anything was cut. A tools list that can't be read is none.
|
||||
func keepTools(b []byte, keep func(string) bool) ([]byte, bool) {
|
||||
t := bytes.TrimSpace(b)
|
||||
if len(t) > 0 && t[0] == '[' {
|
||||
var msgs []json.RawMessage
|
||||
if json.Unmarshal(t, &msgs) != nil {
|
||||
return b, false
|
||||
}
|
||||
changed := false
|
||||
for i, m := range msgs {
|
||||
if out, ok := keepTools(m, keep); ok {
|
||||
msgs[i], changed = out, true
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
return b, false
|
||||
}
|
||||
out, err := json.Marshal(msgs)
|
||||
if err != nil {
|
||||
return []byte("[]"), true
|
||||
}
|
||||
return out, true
|
||||
}
|
||||
var m map[string]json.RawMessage
|
||||
if json.Unmarshal(t, &m) != nil || len(m["result"]) == 0 {
|
||||
return b, false
|
||||
}
|
||||
var res map[string]json.RawMessage
|
||||
if json.Unmarshal(m["result"], &res) != nil {
|
||||
return b, false
|
||||
}
|
||||
raw, ok := res["tools"]
|
||||
if !ok {
|
||||
return b, false
|
||||
}
|
||||
var tools []json.RawMessage
|
||||
json.Unmarshal(raw, &tools)
|
||||
kept := make([]json.RawMessage, 0, len(tools))
|
||||
for _, tool := range tools {
|
||||
var named struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
if json.Unmarshal(tool, &named) == nil && named.Name != "" && keep(named.Name) {
|
||||
kept = append(kept, tool)
|
||||
}
|
||||
}
|
||||
if len(kept) == len(tools) && len(tools) > 0 || string(bytes.TrimSpace(raw)) == "[]" {
|
||||
return b, false
|
||||
}
|
||||
res["tools"], _ = json.Marshal(kept)
|
||||
m["result"], _ = json.Marshal(res)
|
||||
out, err := json.Marshal(m)
|
||||
if err != nil {
|
||||
return b, false
|
||||
}
|
||||
return out, true
|
||||
}
|
||||
|
||||
// mcpKeyGuard holds a request to a relayed server (/mcp/<name>,
|
||||
// /mcp/run/<name>) to its key's MCP list: refused when the key may not
|
||||
// use the server; when it may use only some of its tools, a tools/call of
|
||||
// another is answered with a JSON-RPC error and never sent, and the
|
||||
// answers are passed through mcpToolsFilter. It is the writer to answer
|
||||
// through, the request (its body read again), and done, to call once the
|
||||
// answer is written; ok false when it answered r itself.
|
||||
func mcpKeyGuard(w http.ResponseWriter, r *http.Request, server string) (_ http.ResponseWriter, _ *http.Request, done func(), ok bool) {
|
||||
who := access.Caller(r.Context())
|
||||
if !who.MCPHeld() {
|
||||
return w, r, func() {}, true
|
||||
}
|
||||
allowed, every := who.MCPServer(server)
|
||||
if !allowed {
|
||||
log.Printf("refused %s %s: gateway key %q may not use the MCP server %s", r.Method, r.URL.Path, who.KeyName, server)
|
||||
http.Error(w, keyMCPServerRefused(who, server), http.StatusForbidden)
|
||||
return nil, nil, nil, false
|
||||
}
|
||||
if every {
|
||||
return w, r, func() {}, true
|
||||
}
|
||||
if r.Method == http.MethodPost {
|
||||
body, ok := readMCPBody(w, r, 32<<20)
|
||||
if !ok {
|
||||
return nil, nil, nil, false
|
||||
}
|
||||
t := bytes.TrimSpace(body)
|
||||
var msgs []mcpMessage
|
||||
var err error
|
||||
if len(t) > 0 && t[0] == '[' {
|
||||
err = json.Unmarshal(t, &msgs)
|
||||
} else {
|
||||
var m mcpMessage
|
||||
err = json.Unmarshal(t, &m)
|
||||
msgs = []mcpMessage{m}
|
||||
}
|
||||
// a message that can't be read can't be told a tool it may use
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]any{"jsonrpc": "2.0", "id": nil, "error": map[string]any{"code": -32700, "message": "parse error: the body isn't a JSON-RPC message"}})
|
||||
return nil, nil, nil, false
|
||||
}
|
||||
for _, m := range msgs {
|
||||
if m.Method != "tools/call" {
|
||||
continue
|
||||
}
|
||||
if tool := mcpCallName(m.Params); !who.MCPAllows(server, tool) {
|
||||
log.Printf("refused %s %s: gateway key %q may not use the tool %s of the MCP server %s", r.Method, r.URL.Path, who.KeyName, tool, server)
|
||||
if len(msgs) > 1 {
|
||||
http.Error(w, keyMCPToolRefused(who, server, tool), http.StatusForbidden)
|
||||
return nil, nil, nil, false
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"jsonrpc": "2.0", "id": m.ID, "error": map[string]any{"code": -32602, "message": keyMCPToolRefused(who, server, tool)}})
|
||||
return nil, nil, nil, false
|
||||
}
|
||||
}
|
||||
r.Body, r.ContentLength = io.NopCloser(bytes.NewReader(body)), int64(len(body))
|
||||
}
|
||||
f := &mcpToolsFilter{w: w, keep: func(tool string) bool { return who.MCPAllows(server, tool) }}
|
||||
return f, r, f.finish, true
|
||||
}
|
||||
|
||||
// mcpToolsFilter writes a relayed server's answers with the tools its
|
||||
// caller's key may not use left out of each tools/list's: a JSON answer
|
||||
// whole once written (done), an event stream event by event.
|
||||
type mcpToolsFilter struct {
|
||||
w http.ResponseWriter
|
||||
keep func(string) bool
|
||||
// mode is how the body is written, decided by its Content-Type
|
||||
mode int
|
||||
status int
|
||||
buf bytes.Buffer
|
||||
event [][]byte // the event stream's lines read of the event not yet ended
|
||||
}
|
||||
|
||||
const (
|
||||
mcpFilterUndecided = iota
|
||||
mcpFilterJSON
|
||||
mcpFilterEvents
|
||||
mcpFilterPass
|
||||
mcpFilterRefused
|
||||
)
|
||||
|
||||
func (f *mcpToolsFilter) Header() http.Header { return f.w.Header() }
|
||||
|
||||
func (f *mcpToolsFilter) WriteHeader(code int) {
|
||||
if f.mode != mcpFilterUndecided {
|
||||
return
|
||||
}
|
||||
ct := strings.ToLower(f.w.Header().Get("Content-Type"))
|
||||
enc := strings.ToLower(strings.TrimSpace(f.w.Header().Get("Content-Encoding")))
|
||||
readable := enc == "" || enc == "identity"
|
||||
switch {
|
||||
case !readable && (strings.HasPrefix(ct, "application/json") || strings.HasPrefix(ct, "text/event-stream")):
|
||||
// an answer that can't be read can't be told to list only the
|
||||
// tools the key may use
|
||||
f.mode = mcpFilterRefused
|
||||
f.w.Header().Del("Content-Encoding")
|
||||
f.w.Header().Del("Content-Length")
|
||||
f.w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||
f.w.WriteHeader(http.StatusBadGateway)
|
||||
io.WriteString(f.w, "the MCP server answered in an encoding ("+enc+") magpie can't read, so it can't hold the answer to the tools this gateway key may use\n")
|
||||
return
|
||||
case strings.HasPrefix(ct, "application/json"):
|
||||
f.mode, f.status = mcpFilterJSON, code
|
||||
f.w.Header().Del("Content-Length")
|
||||
return
|
||||
case strings.HasPrefix(ct, "text/event-stream"):
|
||||
f.mode = mcpFilterEvents
|
||||
f.w.Header().Del("Content-Length")
|
||||
default:
|
||||
f.mode = mcpFilterPass
|
||||
}
|
||||
f.w.WriteHeader(code)
|
||||
}
|
||||
|
||||
func (f *mcpToolsFilter) Write(b []byte) (int, error) {
|
||||
if f.mode == mcpFilterUndecided {
|
||||
f.WriteHeader(http.StatusOK)
|
||||
}
|
||||
switch f.mode {
|
||||
case mcpFilterJSON:
|
||||
return f.buf.Write(b)
|
||||
case mcpFilterEvents:
|
||||
f.buf.Write(b)
|
||||
if err := f.lines(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return len(b), nil
|
||||
case mcpFilterRefused:
|
||||
return len(b), nil
|
||||
}
|
||||
return f.w.Write(b)
|
||||
}
|
||||
|
||||
// lines writes each event of the stream that has ended.
|
||||
func (f *mcpToolsFilter) lines() error {
|
||||
for {
|
||||
i := bytes.IndexByte(f.buf.Bytes(), '\n')
|
||||
if i < 0 {
|
||||
return nil
|
||||
}
|
||||
line := bytes.Clone(f.buf.Next(i + 1))
|
||||
if len(bytes.TrimRight(line, "\r\n")) > 0 {
|
||||
f.event = append(f.event, line)
|
||||
continue
|
||||
}
|
||||
if err := f.endEvent(line); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// endEvent writes the event read, its data's tools cut, then end.
|
||||
func (f *mcpToolsFilter) endEvent(end []byte) error {
|
||||
var data [][]byte
|
||||
for _, l := range f.event {
|
||||
if v, ok := bytes.CutPrefix(bytes.TrimRight(l, "\r\n"), []byte("data:")); ok {
|
||||
data = append(data, bytes.TrimPrefix(v, []byte(" ")))
|
||||
}
|
||||
}
|
||||
var out bytes.Buffer
|
||||
cut := false
|
||||
if len(data) > 0 {
|
||||
if kept, changed := keepTools(bytes.Join(data, []byte("\n")), f.keep); changed {
|
||||
cut = true
|
||||
for _, l := range f.event {
|
||||
if !bytes.HasPrefix(l, []byte("data:")) {
|
||||
out.Write(l)
|
||||
}
|
||||
}
|
||||
out.WriteString("data: ")
|
||||
out.Write(kept)
|
||||
out.WriteString("\n")
|
||||
}
|
||||
}
|
||||
if !cut {
|
||||
for _, l := range f.event {
|
||||
out.Write(l)
|
||||
}
|
||||
}
|
||||
out.Write(end)
|
||||
f.event = nil
|
||||
_, err := f.w.Write(out.Bytes())
|
||||
return err
|
||||
}
|
||||
|
||||
func (f *mcpToolsFilter) Flush() {
|
||||
if f.mode == mcpFilterJSON || f.mode == mcpFilterRefused {
|
||||
return
|
||||
}
|
||||
if fl, ok := f.w.(http.Flusher); ok {
|
||||
fl.Flush()
|
||||
}
|
||||
}
|
||||
|
||||
// finish writes what is held: a JSON answer, cut, or the end of a stream
|
||||
// that stopped mid-event.
|
||||
func (f *mcpToolsFilter) finish() {
|
||||
switch f.mode {
|
||||
case mcpFilterJSON:
|
||||
out, _ := keepTools(f.buf.Bytes(), f.keep)
|
||||
f.w.WriteHeader(f.status)
|
||||
f.w.Write(out)
|
||||
case mcpFilterEvents:
|
||||
for _, l := range f.event {
|
||||
f.w.Write(l)
|
||||
}
|
||||
f.w.Write(f.buf.Bytes())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/mcpauth/mcpauthtest"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// keyHeldToMCP is a gateway key (and its secret) held to the MCP servers
|
||||
// and tools in mcp.
|
||||
func keyHeldToMCP(t *testing.T, name string, mcp ...string) string {
|
||||
t.Helper()
|
||||
keys, secrets := newCaller(t, name)
|
||||
if _, err := access.Update("mcp-key", access.Change{Key: keys[0].ID, MCP: mcp}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return secrets[0]
|
||||
}
|
||||
|
||||
// A key held to some MCP servers and tools (wakaka on Discord) is held on
|
||||
// magpie's own servers: a server it isn't given answers 403, a server it
|
||||
// is given some tools of lists those alone and refuses a call of another
|
||||
// before it runs, and OwnMCPPath leaves the others out. A key held to
|
||||
// nothing, and a request with no key, see every tool as before.
|
||||
func TestKeyMCPOwnServer(t *testing.T) {
|
||||
fresh(t)
|
||||
t.Setenv("MAGPIE_ADDR", "")
|
||||
t.Setenv("MAGPIE_PUBLIC_URL", "")
|
||||
apis := newSearchAPIs(t)
|
||||
if err := provider.SetSearchAPI(apis.api("tavily", "tvly-k")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := New()
|
||||
h := lanGuard(s.Handler())
|
||||
fetchOnly := keyHeldToMCP(t, "Fetch", "magpie-web-search/web_fetch")
|
||||
other := keyHeldToMCP(t, "Other", "github")
|
||||
free := keyHeldToMCP(t, "Free")
|
||||
auth := func(secret string) []string { return []string{"Authorization", "Bearer " + secret} }
|
||||
|
||||
if got := listedNames(t, readMCP(t, mcpPost(h, here, toolsList, auth(fetchOnly)...))); !slices.Equal(got, []string{fetchMCPTool}) {
|
||||
t.Fatalf("a key given web_fetch alone lists %v", got)
|
||||
}
|
||||
m := readMCP(t, mcpPost(h, here, mcpSearchCall, auth(fetchOnly)...))
|
||||
if m.Error == nil || m.Error.Code != -32602 || !strings.Contains(m.Error.Message, `"Fetch" may not use the tool web_search`) {
|
||||
t.Fatalf("a call of web_search: %+v", m)
|
||||
}
|
||||
// in a batch, the refused call is refused alone
|
||||
w := mcpPost(h, here, `[`+toolsList+`,`+mcpSearchCall+`]`, auth(fetchOnly)...)
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `"web_fetch"`) || strings.Contains(w.Body.String(), `"name":"web_search"`) || !strings.Contains(w.Body.String(), "may not use the tool web_search") {
|
||||
t.Fatalf("a batch: %d %s", w.Code, w.Body)
|
||||
}
|
||||
if w := mcpPost(h, here, mcpSearchCall, auth(other)...); w.Code != http.StatusForbidden || !strings.Contains(w.Body.String(), "may not use the MCP server magpie-web-search") {
|
||||
t.Fatalf("a key not given the server: %d %s", w.Code, w.Body)
|
||||
}
|
||||
if len(apis.asked) != 0 {
|
||||
t.Fatalf("searched for a refused call: %q", apis.asked)
|
||||
}
|
||||
for _, hdr := range [][]string{auth(free), nil} {
|
||||
if got := listedNames(t, readMCP(t, mcpPost(h, here, toolsList, hdr...))); !slices.Equal(got, []string{searchMCPTool, fetchMCPTool}) {
|
||||
t.Fatalf("%v lists %v", hdr, got)
|
||||
}
|
||||
}
|
||||
if m := readMCP(t, mcpPost(h, here, mcpSearchCall, auth(free)...)); m.Error != nil || m.Result.IsError {
|
||||
t.Fatalf("a key held to nothing: %+v", m)
|
||||
}
|
||||
|
||||
own := func(hdr ...string) []string {
|
||||
r := httptest.NewRequest("GET", OwnMCPPath, nil)
|
||||
r.RemoteAddr = here
|
||||
for i := 0; i+1 < len(hdr); i += 2 {
|
||||
r.Header.Set(hdr[i], hdr[i+1])
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
var got struct{ Servers []OwnMCP }
|
||||
json.Unmarshal(w.Body.Bytes(), &got)
|
||||
var names []string
|
||||
for _, o := range got.Servers {
|
||||
names = append(names, o.Name)
|
||||
}
|
||||
return names
|
||||
}
|
||||
if got := own(auth(other)...); slices.Contains(got, "magpie-web-search") {
|
||||
t.Errorf("a key not given web search is told of it: %v", got)
|
||||
}
|
||||
if got := own(auth(fetchOnly)...); !slices.Contains(got, "magpie-web-search") {
|
||||
t.Errorf("a key given web_fetch isn't told of its server: %v", got)
|
||||
}
|
||||
if got := own(); !slices.Contains(got, "magpie-web-search") {
|
||||
t.Errorf("no key: %v", got)
|
||||
}
|
||||
|
||||
r := httptest.NewRequest("GET", "/v1/magpie/limit", nil)
|
||||
r.RemoteAddr = here
|
||||
r.Header.Set("Authorization", "Bearer "+fetchOnly)
|
||||
lw := httptest.NewRecorder()
|
||||
h.ServeHTTP(lw, r)
|
||||
if !strings.Contains(lw.Body.String(), `"mcp":["magpie-web-search/web_fetch"]`) {
|
||||
t.Errorf("the key isn't told its MCP list: %s", lw.Body)
|
||||
}
|
||||
}
|
||||
|
||||
// Through the hub, a key is given the tools of the Library's servers it
|
||||
// may use alone: listed, named in the instructions, found and run on
|
||||
// demand, and by a name the hub asks the server for (hubToolNamed's
|
||||
// fallback); any other is unknown and never runs.
|
||||
func TestKeyMCPHub(t *testing.T) {
|
||||
fresh(t)
|
||||
tools := []HubTool{
|
||||
{Server: "github", Tool: "create_issue", Spec: hubSpec("create_issue")},
|
||||
{Server: "github", Tool: "delete_repo", Spec: hubSpec("delete_repo")},
|
||||
{Server: "fs", Tool: "read", Spec: hubSpec("read")},
|
||||
{Server: "linear", Tool: "list_issues", Spec: hubSpec("list_issues")},
|
||||
}
|
||||
servers := []HubServer{
|
||||
{Name: "github", Known: true, Tools: []HubToolNote{{Name: "create_issue", About: "Opens an issue"}, {Name: "delete_repo", About: "Deletes a repository"}}},
|
||||
{Name: "fs", Known: true, Tools: []HubToolNote{{Name: "read", About: "Reads a file"}}},
|
||||
{Name: "linear", Known: true, About: "Linear's issues", Tools: []HubToolNote{{Name: "list_issues", About: "Lists issues"}}},
|
||||
}
|
||||
f := &fakeHub{on: true, tools: map[string][]HubTool{"claude": tools}, servers: map[string][]HubServer{"claude": servers}}
|
||||
withHub(t, f)
|
||||
h := lanGuard(New().Handler())
|
||||
held := keyHeldToMCP(t, "Held", "github/create_issue", "fs")
|
||||
key := []string{"Authorization", "Bearer " + held}
|
||||
|
||||
if got := listedNames(t, readMCP(t, hubPost(h, "claude", here, toolsList, key...))); !slices.Equal(got, []string{"github__create_issue", "fs__read"}) {
|
||||
t.Fatalf("listed %v", got)
|
||||
}
|
||||
say := initInstructions(t, hubPost(h, "claude", here, hubInit, key...).Body.String())
|
||||
if !strings.Contains(say, "create_issue") || strings.Contains(say, "delete_repo") || strings.Contains(say, "linear") {
|
||||
t.Fatalf("instructions: %s", say)
|
||||
}
|
||||
for _, name := range []string{"github__delete_repo", "linear__list_issues", "linear__other", "github__other"} {
|
||||
m := readMCP(t, hubPost(h, "claude", here, toolsCall(name, `{}`), key...))
|
||||
if m.Error == nil || !strings.Contains(m.Error.Message, "unknown tool "+name) {
|
||||
t.Errorf("%s: %+v", name, m)
|
||||
}
|
||||
}
|
||||
// a server given whole: a tool it no longer lists is still asked for
|
||||
if m := readMCP(t, hubPost(h, "claude", here, toolsCall("fs__write", `{}`), key...)); m.Error != nil || m.Result.Content[0].Text != "ran fs write" {
|
||||
t.Fatalf("fs__write: %+v", m)
|
||||
}
|
||||
if m := readMCP(t, hubPost(h, "claude", here, toolsCall("github__create_issue", `{}`), key...)); m.Error != nil || m.Result.IsError {
|
||||
t.Fatalf("github__create_issue: %+v", m)
|
||||
}
|
||||
|
||||
// on demand: find_tools and call_tool are held the same way
|
||||
srv := New()
|
||||
r := httptest.NewRequest("POST", HubMCPPath+"claude", nil)
|
||||
who, _ := access.Authenticate(held)
|
||||
r = r.WithContext(access.WithIdentity(t.Context(), who))
|
||||
ts := hubTools(r.Context(), "claude")
|
||||
if res, _ := json.Marshal(srv.hubCallByName(r, "claude", ts, json.RawMessage(`{"name":"delete_repo"}`), hubCallMeta{})); !strings.Contains(string(res), `"isError":true`) {
|
||||
t.Fatalf("call_tool delete_repo: %s", res)
|
||||
}
|
||||
if found := hubMatches(ts, "issue"); slices.ContainsFunc(found, func(t hubTool) bool { return t.Server == "linear" || t.Tool == "delete_repo" }) {
|
||||
t.Fatalf("find_tools found %v", found)
|
||||
}
|
||||
// every hub call is held where it runs, however it was found
|
||||
res, _ := json.Marshal(srv.hubMCPRun(r, "claude", hubTool{HubTool: HubTool{Server: "github", Tool: "delete_repo"}, name: "github__delete_repo"}, nil))
|
||||
if !strings.Contains(string(res), "may not use the tool delete_repo") {
|
||||
t.Fatalf("hubMCPRun: %s", res)
|
||||
}
|
||||
want := []string{"claude fs write {}", "claude github create_issue {}"}
|
||||
if got := f.ran(); !slices.Equal(got, want) {
|
||||
t.Fatalf("ran %q, want %q", got, want)
|
||||
}
|
||||
// a request with no key sees every tool
|
||||
if got := listedNames(t, readMCP(t, hubPost(h, "claude", here, toolsList))); len(got) != 4 {
|
||||
t.Fatalf("no key: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// /mcp/<server>, a server magpie signed in to: a key not given it is
|
||||
// refused before the server is asked, a key given some of its tools has
|
||||
// a call of another answered with an error and never sent, and a batch
|
||||
// holding one refused whole.
|
||||
func TestKeyMCPProxy(t *testing.T) {
|
||||
fresh(t)
|
||||
f := mcpauthtest.New(t)
|
||||
f.SignIn(t, "neon")
|
||||
h := lanGuard(New().Handler())
|
||||
call := func(secret, body string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest("POST", "/mcp/neon", strings.NewReader(body))
|
||||
r.RemoteAddr, r.Host = here, "127.0.0.1:3425"
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
r.Header.Set("Accept", "application/json, text/event-stream")
|
||||
r.Header.Set("Authorization", "Bearer "+secret)
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
other := keyHeldToMCP(t, "Other", "github")
|
||||
some := keyHeldToMCP(t, "Some", "neon/run_sql")
|
||||
if w := call(other, toolsList); w.Code != http.StatusForbidden || len(f.Calls) != 0 {
|
||||
t.Fatalf("a key not given neon: %d %s, calls %v", w.Code, w.Body, f.Calls)
|
||||
}
|
||||
m := readMCP(t, call(some, toolsCall("delete_branch", `{}`)))
|
||||
if m.Error == nil || m.Error.Code != -32602 || !strings.Contains(m.Error.Message, "may not use the tool delete_branch") || len(f.Calls) != 0 {
|
||||
t.Fatalf("a call of another tool: %+v, calls %v", m, f.Calls)
|
||||
}
|
||||
if w := call(some, `[`+toolsCall("run_sql", `{}`)+`,`+toolsCall("delete_branch", `{}`)+`]`); w.Code != http.StatusForbidden || len(f.Calls) != 0 {
|
||||
t.Fatalf("a batch: %d %s, calls %v", w.Code, w.Body, f.Calls)
|
||||
}
|
||||
if w := call(some, `{"jsonrpc":`); w.Code != http.StatusBadRequest || len(f.Calls) != 0 {
|
||||
t.Fatalf("a body that isn't one: %d %s, calls %v", w.Code, w.Body, f.Calls)
|
||||
}
|
||||
// its own tool goes through, its event stream with it
|
||||
w := call(some, toolsCall("run_sql", `{}`))
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), "notifications/progress") || !strings.Contains(w.Body.String(), `"id":3,"result"`) {
|
||||
t.Fatalf("run_sql: %d %s", w.Code, w.Body)
|
||||
}
|
||||
if !slices.Equal(f.Calls, []string{"POST tools/call "}) {
|
||||
t.Fatalf("calls %q", f.Calls)
|
||||
}
|
||||
}
|
||||
|
||||
// /mcp/run/<server>, a command magpie runs: a key given some of its tools
|
||||
// is listed those alone, in a JSON answer or an event stream however it
|
||||
// is cut into writes, and a call of another never reaches the server. A
|
||||
// key given the server whole, and one held to nothing, get its answers as
|
||||
// they are.
|
||||
func TestKeyMCPRun(t *testing.T) {
|
||||
fresh(t)
|
||||
const list = `{"jsonrpc":"2.0","id":2,"result":{"tools":[{"name":"read","inputSchema":{"type":"object"}},{"name":"write","inputSchema":{"type":"object"}}]}}`
|
||||
var got []string
|
||||
was := RunMCP
|
||||
RunMCP = func(w http.ResponseWriter, r *http.Request, name string) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
got = append(got, name+" "+string(b))
|
||||
if r.Header.Get("X-Stream") == "" {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Content-Length", "999")
|
||||
io.WriteString(w, list[:20])
|
||||
io.WriteString(w, list[20:])
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.WriteHeader(200)
|
||||
ev := "event: message\nid: 7\ndata: " + list + "\n\n"
|
||||
note := "data: {\"jsonrpc\":\"2.0\",\"method\":\"notifications/progress\"}\n\n"
|
||||
for _, part := range []string{note[:9], note[9:] + ev[:30], ev[30:70], ev[70:]} {
|
||||
io.WriteString(w, part)
|
||||
w.(http.Flusher).Flush()
|
||||
}
|
||||
}
|
||||
t.Cleanup(func() { RunMCP = was })
|
||||
h := lanGuard(New().Handler())
|
||||
call := func(secret, body string, stream bool) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest("POST", "/mcp/run/fs", strings.NewReader(body))
|
||||
r.RemoteAddr, r.Host = here, "127.0.0.1:3425"
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
if secret != "" {
|
||||
r.Header.Set("Authorization", "Bearer "+secret)
|
||||
}
|
||||
if stream {
|
||||
r.Header.Set("X-Stream", "1")
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
some := keyHeldToMCP(t, "Some", "fs/read")
|
||||
if names := listedNames(t, readMCP(t, call(some, toolsList, false))); !slices.Equal(names, []string{"read"}) {
|
||||
t.Fatalf("JSON lists %v", names)
|
||||
}
|
||||
w := call(some, toolsList, true)
|
||||
body := w.Body.String()
|
||||
if !strings.Contains(body, `"name":"read"`) || strings.Contains(body, `"name":"write"`) || !strings.Contains(body, "notifications/progress") || !strings.Contains(body, "id: 7\n") || !strings.HasSuffix(body, "\n\n") {
|
||||
t.Fatalf("the stream: %q", body)
|
||||
}
|
||||
m := readMCP(t, call(some, toolsCall("write", `{"path":"/etc/hosts"}`), false))
|
||||
if m.Error == nil || !strings.Contains(m.Error.Message, "may not use the tool write") {
|
||||
t.Fatalf("a call of write: %+v", m)
|
||||
}
|
||||
if len(got) != 2 || got[0] != "fs "+toolsList {
|
||||
t.Fatalf("the server got %q", got)
|
||||
}
|
||||
if w := call(keyHeldToMCP(t, "Other", "github"), toolsList, false); w.Code != http.StatusForbidden || len(got) != 2 {
|
||||
t.Fatalf("a key not given fs: %d %s", w.Code, w.Body)
|
||||
}
|
||||
for _, secret := range []string{keyHeldToMCP(t, "Whole", "fs"), keyHeldToMCP(t, "Free"), ""} {
|
||||
if names := listedNames(t, readMCP(t, call(secret, toolsList, false))); len(names) != 2 {
|
||||
t.Fatalf("%q lists %v", secret, names)
|
||||
}
|
||||
if w := call(secret, toolsList, true); !strings.Contains(w.Body.String(), `"name":"write"`) {
|
||||
t.Fatalf("%q's stream: %s", secret, w.Body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// An answer magpie can't read (an encoding it didn't ask for) isn't passed
|
||||
// to a key held to some tools: the tools it lists couldn't be cut.
|
||||
func TestKeyMCPFilterRefusesUnreadable(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
f := &mcpToolsFilter{w: rec, keep: func(string) bool { return false }}
|
||||
f.Header().Set("Content-Type", "application/json")
|
||||
f.Header().Set("Content-Encoding", "zstd")
|
||||
f.WriteHeader(200)
|
||||
f.Write([]byte(`{"result":{"tools":[{"name":"x"}]}}`))
|
||||
f.finish()
|
||||
if rec.Code != http.StatusBadGateway || strings.Contains(rec.Body.String(), `"x"`) {
|
||||
t.Fatalf("%d %s", rec.Code, rec.Body)
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,11 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"slices"
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/gwtool"
|
||||
"github.com/yetone/magpie/internal/plugin"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
@@ -57,7 +60,44 @@ func ownMCP() []OwnMCP {
|
||||
}
|
||||
|
||||
func (s *Server) ownMCPList(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, 200, map[string]any{"servers": ownMCP()})
|
||||
// a gateway key held to some MCP servers is told of those alone
|
||||
who := access.Caller(r.Context())
|
||||
ss := slices.DeleteFunc(ownMCP(), func(o OwnMCP) bool { ok, _ := who.MCPServer(o.Name); return !ok })
|
||||
writeJSON(w, 200, map[string]any{"servers": ss})
|
||||
}
|
||||
|
||||
// OwnMCPTools are magpie's own MCP servers that are on now, Magpie
|
||||
// Browser beside them, each with the names of its tools, for the picker
|
||||
// of the servers and tools a gateway key may use (wakaka on Discord). The
|
||||
// plugin tools' server is listed with no tools when they can't be read:
|
||||
// it can still be given whole.
|
||||
func OwnMCPTools(ctx context.Context) []OwnMCPServer {
|
||||
out := []OwnMCPServer{}
|
||||
for _, o := range ownMCP() {
|
||||
s := OwnMCPServer{Name: o.Name, Title: o.Title}
|
||||
switch o.Name {
|
||||
case "magpie-web-search":
|
||||
s.Tools = []string{searchMCPTool, fetchMCPTool}
|
||||
case "magpie-vision":
|
||||
s.Tools = []string{visionMCPTool}
|
||||
case imageServerName:
|
||||
s.Tools = []string{GenerateImageTool, GenerateVideoTool, GenerationResultTool}
|
||||
case "magpie-tools":
|
||||
ts, _ := servedTools(ctx)
|
||||
for _, t := range ts {
|
||||
s.Tools = append(s.Tools, t.name)
|
||||
}
|
||||
}
|
||||
out = append(out, s)
|
||||
}
|
||||
return append(out, OwnMCPServer{Name: "magpie-browser", Title: "Magpie Browser", Tools: []string{"browser"}})
|
||||
}
|
||||
|
||||
// OwnMCPServer is one of magpie's own MCP servers with its tools' names.
|
||||
type OwnMCPServer struct {
|
||||
Name string `json:"name"`
|
||||
Title string `json:"title"`
|
||||
Tools []string `json:"tools"`
|
||||
}
|
||||
|
||||
// OwnUnready is why magpie's own server name (Magpie Web Search, Magpie
|
||||
|
||||
@@ -110,6 +110,10 @@ func serveMCP(w http.ResponseWriter, r *http.Request, what, server string, limit
|
||||
http.Error(w, what+" MCP server answers agents, not web pages", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
// a gateway key held to some MCP servers (access.Key.MCP)
|
||||
if !mcpKeyServe(w, r, server) {
|
||||
return
|
||||
}
|
||||
if r.Method != http.MethodPost {
|
||||
// no stream of the server's own (GET) and no session to end (DELETE)
|
||||
w.Header().Set("Allow", "POST")
|
||||
@@ -159,9 +163,16 @@ func serveMCP(w http.ResponseWriter, r *http.Request, what, server string, limit
|
||||
}
|
||||
var result any
|
||||
var rpcErr map[string]any
|
||||
if m.Method == "tools/call" {
|
||||
result, rpcErr = callMCPTool(r, server, m, call)
|
||||
} else {
|
||||
switch {
|
||||
case m.Method == "tools/call":
|
||||
if rpcErr = mcpKeyCall(r, server, m); rpcErr == nil {
|
||||
result, rpcErr = callMCPTool(r, server, m, call)
|
||||
}
|
||||
case m.Method == "tools/list":
|
||||
if result, rpcErr = call(r, m); rpcErr == nil {
|
||||
result = mcpKeyList(r, server, result)
|
||||
}
|
||||
default:
|
||||
result, rpcErr = call(r, m)
|
||||
}
|
||||
reply := map[string]any{"jsonrpc": "2.0", "id": m.ID}
|
||||
|
||||
@@ -3004,6 +3004,8 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; }
|
||||
and gives way before the row runs past a narrow window */
|
||||
#gatewayKeys .amodels.key-quotas { display: inline-block; flex: 0 1 auto; min-width: 0; line-height: 20px; overflow: hidden; text-overflow: ellipsis; }
|
||||
#gatewayKeys .acc:not(:hover) > .key-quotas:not(.set):not(:focus) { max-width: 0; padding: 0; margin-left: -9px; box-shadow: none; }
|
||||
/* the MCP servers a key held to some may use: cut, and gives way first */
|
||||
#gatewayKeys .amodels.key-mcp { display: inline-block; flex: 0 1 auto; min-width: 24px; max-width: 180px; line-height: 20px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
/* a read-only key's tag, always shown, never a button */
|
||||
#gatewayKeys .amodels.key-readonly { display: inline-block; flex: 0 1 auto; min-width: 0; line-height: 20px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; cursor: default; }
|
||||
#gatewayKeys .amodels.key-readonly:hover { color: var(--accent); background: var(--accent-soft); }
|
||||
|
||||
@@ -460,6 +460,14 @@ const I18N = {
|
||||
"Not served now": "当前未提供",
|
||||
"{name} may use only the models picked": "{name} 仅可使用所选模型",
|
||||
"{name} may use every model": "{name} 可使用全部模型",
|
||||
"All MCP servers": "全部 MCP 服务器",
|
||||
"No MCP server": "无 MCP 服务器",
|
||||
"{n} MCP servers": "{n} 个 MCP 服务器",
|
||||
"Only these MCP servers and tools: {list}": "仅限这些 MCP 服务器和工具:{list}",
|
||||
"MCP servers this key may use": "这个密钥可用的 MCP 服务器",
|
||||
"{name} may use every MCP server": "{name} 可使用全部 MCP 服务器",
|
||||
"{name} may use no MCP server": "{name} 不可使用 MCP 服务器",
|
||||
"{name} may use only the MCP servers and tools picked": "{name} 只可使用所选的 MCP 服务器和工具",
|
||||
"No model is picked, so this key may use only the picked accounts' providers' models": "没有勾选模型,此密钥只能使用所勾选账号所属供应商的模型",
|
||||
"Not used: no {provider} model or account is picked": "不会被使用:{provider} 没有勾选任何模型或账号",
|
||||
"{name} may use only the picked accounts' models": "{name} 仅可使用所选账号的模型",
|
||||
@@ -5115,6 +5123,14 @@ const I18N = {
|
||||
"Not served now": "目前未提供",
|
||||
"{name} may use only the models picked": "{name} 僅可使用所選模型",
|
||||
"{name} may use every model": "{name} 可使用全部模型",
|
||||
"All MCP servers": "全部 MCP 伺服器",
|
||||
"No MCP server": "無 MCP 伺服器",
|
||||
"{n} MCP servers": "{n} 個 MCP 伺服器",
|
||||
"Only these MCP servers and tools: {list}": "僅限這些 MCP 伺服器和工具:{list}",
|
||||
"MCP servers this key may use": "這個金鑰可用的 MCP 伺服器",
|
||||
"{name} may use every MCP server": "{name} 可使用全部 MCP 伺服器",
|
||||
"{name} may use no MCP server": "{name} 不可使用 MCP 伺服器",
|
||||
"{name} may use only the MCP servers and tools picked": "{name} 只可使用所選的 MCP 伺服器和工具",
|
||||
"No model is picked, so this key may use only the picked accounts' providers' models": "沒有勾選模型,此金鑰只能使用所勾選帳號所屬供應商的模型",
|
||||
"Not used: no {provider} model or account is picked": "不會被使用:{provider} 沒有勾選任何模型或帳號",
|
||||
"{name} may use only the picked accounts' models": "{name} 僅可使用所選帳號的模型",
|
||||
@@ -9731,6 +9747,14 @@ const I18N = {
|
||||
"Not served now": "現在は提供されていません",
|
||||
"{name} may use only the models picked": "{name} は選んだモデルのみ使えます",
|
||||
"{name} may use every model": "{name} はすべてのモデルを使えます",
|
||||
"All MCP servers": "すべての MCP サーバー",
|
||||
"No MCP server": "MCP サーバーなし",
|
||||
"{n} MCP servers": "{n} 個の MCP サーバー",
|
||||
"Only these MCP servers and tools: {list}": "この MCP サーバーとツールのみ:{list}",
|
||||
"MCP servers this key may use": "このキーが使える MCP サーバー",
|
||||
"{name} may use every MCP server": "{name} はすべての MCP サーバーを使えます",
|
||||
"{name} may use no MCP server": "{name} は MCP サーバーを使えません",
|
||||
"{name} may use only the MCP servers and tools picked": "{name} は選んだ MCP サーバーとツールだけを使えます",
|
||||
"No model is picked, so this key may use only the picked accounts' providers' models": "モデルが選ばれていないため、このキーは選んだアカウントのプロバイダーのモデルだけを使えます",
|
||||
"Not used: no {provider} model or account is picked": "使われません:{provider} のモデルもアカウントも選ばれていません",
|
||||
"{name} may use only the picked accounts' models": "{name} は選んだアカウントのモデルのみ使えます",
|
||||
@@ -14365,6 +14389,14 @@ const I18N = {
|
||||
"Not served now": "Derzeit nicht angeboten",
|
||||
"{name} may use only the models picked": "{name} darf nur die gewählten Modelle nutzen",
|
||||
"{name} may use every model": "{name} darf alle Modelle nutzen",
|
||||
"All MCP servers": "Alle MCP-Server",
|
||||
"No MCP server": "Kein MCP-Server",
|
||||
"{n} MCP servers": "{n} MCP-Server",
|
||||
"Only these MCP servers and tools: {list}": "Nur diese MCP-Server und Werkzeuge: {list}",
|
||||
"MCP servers this key may use": "MCP-Server, die dieser Schlüssel nutzen darf",
|
||||
"{name} may use every MCP server": "{name} darf alle MCP-Server nutzen",
|
||||
"{name} may use no MCP server": "{name} darf keinen MCP-Server nutzen",
|
||||
"{name} may use only the MCP servers and tools picked": "{name} darf nur die gewählten MCP-Server und Werkzeuge nutzen",
|
||||
"No model is picked, so this key may use only the picked accounts' providers' models": "Kein Modell ist ausgewählt, daher darf dieser Schlüssel nur Modelle der Anbieter der ausgewählten Konten nutzen",
|
||||
"Not used: no {provider} model or account is picked": "Wird nicht genutzt: kein {provider}-Modell und kein Konto ist ausgewählt",
|
||||
"{name} may use only the picked accounts' models": "{name} darf nur die Modelle der gewählten Konten nutzen",
|
||||
|
||||
@@ -226,7 +226,7 @@ function renderGatewayKeys() {
|
||||
tick.onclick = () => gatewayKeyAction(k.off ? "on-key" : "off-key", { key: k.id });
|
||||
// the copy sits by the key it copies (the owner: stranded among the
|
||||
// badges it read as nobody's); Rotate and Remove wait in the row's menu
|
||||
row.append(tick, gatewayRename(k), el("span", "plan mono", k.masked), copyCallerKeyBtn(k), el("span", "grow"), ...(k.browser ? [gatewayBrowserTag()] : k.readOnly ? [gatewayReadOnlyTag()] : []), gatewayModelsBadge(k), gatewayQuotasBadge(k), gatewayLimitBadge(k), gatewayKeyMore(k));
|
||||
row.append(tick, gatewayRename(k), el("span", "plan mono", k.masked), copyCallerKeyBtn(k), el("span", "grow"), ...(k.browser ? [gatewayBrowserTag()] : k.readOnly ? [gatewayReadOnlyTag()] : []), gatewayModelsBadge(k), ...gatewayMCPBadge(k), gatewayQuotasBadge(k), gatewayLimitBadge(k), gatewayKeyMore(k));
|
||||
const under = gatewayLimit?.id === k.id ? [gatewayLimitEditor(k)] : keyUsed(k).map((u) => gatewayLimitLine(k, u));
|
||||
if (under.length) row.classList.add("with-limit"), row.append(...under);
|
||||
list.append(row);
|
||||
@@ -308,6 +308,7 @@ function gatewayKeyPage() {
|
||||
|
||||
const ROTATE_GLYPH = "M13.5 8a5.5 5.5 0 1 1-1.6-3.9M13.5 2.5v3.25h-3.25";
|
||||
const REMOVE_GLYPH = "M3 4.5h10M6.5 4.5V3h3v1.5M4.5 4.5l.6 8.5h5.8l.6-8.5M7 7v4M9 7v4";
|
||||
const MCP_GLYPH = "M6 2.5v3M10 2.5v3M4.5 5.5h7V8a3.5 3.5 0 0 1-7 0zM8 11.5v2";
|
||||
const POWER_GLYPH = "M8 2.5v5M4.8 4.6a4.75 4.75 0 1 0 6.4 0";
|
||||
function gatewayKeyMore(k) {
|
||||
const more = el("button", "copy gw-key-more");
|
||||
@@ -331,6 +332,9 @@ function gatewayKeyMore(k) {
|
||||
...(k.browser ? [] : [k.readOnly
|
||||
? { name: "Give full access", icon: EYE_GLYPH, run: () => gatewayKeyAccess(k, false) }
|
||||
: { name: "Make read-only", icon: EYE_GLYPH, run: () => gatewayKeyAccess(k, true), off: k.lan, why: k.lan ? t("The sharing key is given to agents, so it can't be read-only") : "" }]),
|
||||
// the MCP servers and tools it may use (wakaka on Discord); the
|
||||
// Browser key connects the extension alone
|
||||
...(k.browser ? [] : [{ name: "MCP servers", icon: MCP_GLYPH, run: () => gatewayMCPPick(k, more) }]),
|
||||
{ name: "Rotate key", icon: ROTATE_GLYPH, run: () => askGatewayKey(k, true) },
|
||||
{ name: "Remove", icon: REMOVE_GLYPH, sep: true, run: () => askGatewayKey(k, false) },
|
||||
]);
|
||||
@@ -540,6 +544,56 @@ function gatewayModelsBadge(k) {
|
||||
return b;
|
||||
}
|
||||
|
||||
// gatewayMCPPick picks the MCP servers and tools a key may use (wakaka
|
||||
// on Discord), as gatewayModelsBadge picks its models: a server whole, or
|
||||
// some of its tools, or none. It opens from the row's menu, and from the
|
||||
// key's MCP badge once it holds some.
|
||||
async function gatewayMCPPick(k, anchor) {
|
||||
const ms = k.mcp || [];
|
||||
let list = [];
|
||||
try { ({ servers: list } = await api("caller-keys/mcp")); } catch (err) { status(t(err.message), "err"); return; }
|
||||
if (!anchor.isConnected) return;
|
||||
const opts = [{ v: "", name: "All MCP servers", note: "" }, { v: "-", name: "No MCP server", note: "" }];
|
||||
for (const sv of list || []) {
|
||||
opts.push({ v: sv.name, name: sv.title || sv.name, note: sv.title && sv.title !== sv.name ? sv.name : "", literalName: true });
|
||||
for (const tool of sv.tools || []) opts.push({ v: sv.name + "/" + tool, name: tool, note: sv.name + "/" + tool, literalName: true });
|
||||
}
|
||||
// what the CLI kept that the list hasn't: a server gone, or a tool it
|
||||
// no longer lists
|
||||
for (const v of ms) if (!opts.some((o) => o.v === v)) opts.push({ v, name: v, note: "Not served now", literalName: true });
|
||||
openProtoMenu(anchor, opts, [...ms], (picked) => {
|
||||
// "No MCP server" just ticked is none; left ticked beside a server
|
||||
// ticked since, the server
|
||||
const mcp = picked.includes("-") && !ms.includes("-") ? ["-"] : picked.length > 1 ? picked.filter((v) => v !== "-") : picked;
|
||||
(async () => {
|
||||
const out = await gatewayKeyAction("mcp-key", { key: k.id, mcp });
|
||||
if (out) status(t(!mcp.length ? "{name} may use every MCP server" : mcp[0] === "-" ? "{name} may use no MCP server" : "{name} may use only the MCP servers and tools picked", { name: k.name }), "ok");
|
||||
})();
|
||||
}, "MCP servers this key may use", "sess-menu", "right");
|
||||
}
|
||||
|
||||
// gatewayMCPBadge says which MCP servers a key held to some may use; a
|
||||
// key that may use any has none (the row's menu sets it)
|
||||
function gatewayMCPBadge(k) {
|
||||
const ms = k.mcp || [];
|
||||
if (!ms.length) return [];
|
||||
const b = el("button", "amodels key-mcp set");
|
||||
b.type = "button";
|
||||
const servers = new Set(ms.map((v) => v.split("/")[0]));
|
||||
b.textContent = ms[0] === "-" ? t("No MCP server") : ms.length === 1 ? ms[0] : t("{n} MCP servers", { n: servers.size });
|
||||
b.title = ms[0] === "-" ? t("No MCP server") : t("Only these MCP servers and tools: {list}", { list: ms.join(", ") });
|
||||
b.setAttribute("aria-label", t("MCP servers this key may use"));
|
||||
b.setAttribute("aria-haspopup", "menu");
|
||||
b.setAttribute("aria-expanded", "false");
|
||||
b.onclick = (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (b.classList.contains("open")) return closeProtoMenu();
|
||||
gatewayMCPPick(k, b);
|
||||
};
|
||||
return [b];
|
||||
}
|
||||
|
||||
// ---- the quotas a gateway key is told (#2216) ----
|
||||
|
||||
// gatewayQuotasBadge turns on or off a key's being told the quotas of what
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/library"
|
||||
)
|
||||
|
||||
// The Gateway page lists the MCP servers a key can be held to, magpie's
|
||||
// own and then the Library's, each with its tools, and keeps what was
|
||||
// picked for it (wakaka on Discord).
|
||||
func TestCallerKeyMCPRoutes(t *testing.T) {
|
||||
sandboxHome(t)
|
||||
if _, err := library.SaveServer("", library.Server{Name: "github", Transport: "http", URL: "http://127.0.0.1:1/mcp"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
callerKeyRoutes(mux)
|
||||
request := func(method, path, body string) *httptest.ResponseRecorder {
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body)))
|
||||
return w
|
||||
}
|
||||
var l struct{ Servers []keyMCPJSON }
|
||||
if w := request("GET", "/api/caller-keys/mcp", ""); w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &l) != nil {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
var names []string
|
||||
for _, s := range l.Servers {
|
||||
names = append(names, s.Name)
|
||||
if s.Tools == nil {
|
||||
t.Fatalf("%s: tools null", s.Name)
|
||||
}
|
||||
if s.Name == "magpie-browser" && (!s.Own || !slices.Equal(s.Tools, []string{"browser"})) {
|
||||
t.Fatalf("browser %+v", s)
|
||||
}
|
||||
if s.Name == "github" && s.Own {
|
||||
t.Fatalf("github %+v", s)
|
||||
}
|
||||
}
|
||||
if len(names) < 2 || names[len(names)-1] != "github" || !slices.Contains(names, "magpie-browser") {
|
||||
t.Fatal("servers", names)
|
||||
}
|
||||
var s struct{ Keys []access.Key }
|
||||
if w := request("POST", "/api/caller-keys/add-key", `{"name":"Phone"}`); w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &s) != nil {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
id := s.Keys[0].ID
|
||||
if w := request("POST", "/api/caller-keys/mcp-key", `{"key":"`+id+`","mcp":["github/search_code","magpie-browser"]}`); w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &s) != nil {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
if !slices.Equal(s.Keys[0].MCP, []string{"github/search_code", "magpie-browser"}) {
|
||||
t.Fatal("kept", s.Keys[0].MCP)
|
||||
}
|
||||
if w := request("POST", "/api/caller-keys/mcp-key", `{"key":"`+id+`","mcp":["github/"]}`); w.Code == 200 {
|
||||
t.Fatal("took a bad entry", w.Body)
|
||||
}
|
||||
// a fresh value: an omitted mcp would keep the last decode's
|
||||
s = struct{ Keys []access.Key }{}
|
||||
if w := request("POST", "/api/caller-keys/mcp-key", `{"key":"`+id+`","mcp":[]}`); w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &s) != nil || len(s.Keys[0].MCP) != 0 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,8 @@ import (
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/budget"
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
"github.com/yetone/magpie/internal/library"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
@@ -39,6 +41,15 @@ type keyModelJSON struct {
|
||||
Decides bool `json:"decides,omitempty"`
|
||||
}
|
||||
|
||||
// keyMCPJSON is an MCP server a gateway key may be held to, with its
|
||||
// tools, as its picker lists it.
|
||||
type keyMCPJSON struct {
|
||||
Name string `json:"name"`
|
||||
Title string `json:"title,omitempty"`
|
||||
Tools []string `json:"tools"`
|
||||
Own bool `json:"own,omitempty"` // one of magpie's own
|
||||
}
|
||||
|
||||
func withLimits(keys []access.Key) []keyRow {
|
||||
now := time.Now()
|
||||
out := make([]keyRow, 0, len(keys))
|
||||
@@ -136,6 +147,27 @@ func callerKeyRoutes(mux *http.ServeMux) {
|
||||
}
|
||||
writeJSON(w, map[string]any{"models": out, "accounts": accounts})
|
||||
})
|
||||
// the MCP servers and tools a key may be held to (wakaka on Discord):
|
||||
// magpie's own, then the Library's, each with its tools by name
|
||||
mux.HandleFunc("GET /api/caller-keys/mcp", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
out := []keyMCPJSON{}
|
||||
for _, o := range gateway.OwnMCPTools(r.Context()) {
|
||||
m := keyMCPJSON{Name: o.Name, Title: o.Title, Tools: o.Tools, Own: true}
|
||||
if m.Tools == nil {
|
||||
m.Tools = []string{}
|
||||
}
|
||||
out = append(out, m)
|
||||
}
|
||||
for _, s := range library.KeyMCPServers() {
|
||||
m := keyMCPJSON{Name: s.Name, Title: s.Title, Tools: []string{}}
|
||||
for _, t := range s.Tools {
|
||||
m.Tools = append(m.Tools, t.Name)
|
||||
}
|
||||
out = append(out, m)
|
||||
}
|
||||
writeJSON(w, map[string]any{"servers": out})
|
||||
})
|
||||
mux.HandleFunc("POST /api/caller-keys/{action}", func(w http.ResponseWriter, r *http.Request) {
|
||||
var in access.Change
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
|
||||
+8
@@ -124,6 +124,13 @@ function fixture(lang, theme, events, options = {}) {
|
||||
{ id: "relay/spare@example.com", name: "spare@example.com", provider: "relay", providerName: "Relay", account: true },
|
||||
{ id: "openai/k-1a2b3c", name: "k-1a2b3c", provider: "openai", providerName: "OpenAI", key: true },
|
||||
] });
|
||||
// the MCP servers and tools a key may be held to: magpie's own, then
|
||||
// the Library's (wakaka on Discord)
|
||||
if (url.pathname === "/api/caller-keys/mcp") return json({ servers: [
|
||||
{ name: "magpie-web-search", title: "Magpie Web Search", tools: ["web_search", "web_fetch"], own: true },
|
||||
{ name: "magpie-browser", title: "Magpie Browser", tools: ["browser"], own: true },
|
||||
{ name: "github", tools: ["create_issue", "search_code"] },
|
||||
] });
|
||||
if (url.pathname.startsWith("/api/caller-keys/")) {
|
||||
const action = url.pathname.split("/").at(-1), body = req.postDataJSON();
|
||||
events.push({ action, body });
|
||||
@@ -182,6 +189,7 @@ function fixture(lang, theme, events, options = {}) {
|
||||
}
|
||||
if (action === "models-key") k.models = body.models?.length ? body.models : undefined;
|
||||
if (action === "accounts-key") k.accounts = body.accounts?.length ? body.accounts : undefined;
|
||||
if (action === "mcp-key") k.mcp = body.mcp?.length ? body.mcp : undefined;
|
||||
if (action === "quotas-key") k.quotas = body.quotas || undefined;
|
||||
if (action === "access-key") k.readOnly = body.readOnly || undefined;
|
||||
// a key put at a place in the list, as access.Update keeps it;
|
||||
|
||||
@@ -105,9 +105,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
const menu = page.locator(".row-menu");
|
||||
await menu.waitFor();
|
||||
const items = (await menu.getByRole("menuitem").allTextContents()).map((s) => s.trim());
|
||||
assert.equal(items.length, 4);
|
||||
if (w.rotate) assert.deepEqual(items, [w.off, w.readOnly, w.rotate, w.remove]);
|
||||
assert.deepEqual(items, await page.evaluate(() => [t("Disable key"), t("Make read-only"), t("Rotate key"), t("Remove")]));
|
||||
assert.equal(items.length, 5);
|
||||
if (w.rotate) assert.deepEqual(items.filter((s) => !/MCP/.test(s)), [w.off, w.readOnly, w.rotate, w.remove]);
|
||||
assert.deepEqual(items, await page.evaluate(() => [t("Disable key"), t("Make read-only"), t("MCP servers"), t("Rotate key"), t("Remove")]));
|
||||
// off from the menu, then on again: the key stays, only its switch moves
|
||||
await menu.getByRole("menuitem").first().click();
|
||||
await menu.waitFor({ state: "detached" });
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
// The MCP servers and tools a gateway key may use (wakaka on Discord):
|
||||
// picked in the app's own menu, opened from the key row's menu and from
|
||||
// the key's badge once it holds some, a server whole or some of its
|
||||
// tools, sent as "mcp-key" when the menu closes; "All MCP servers" takes
|
||||
// the restriction off, "No MCP server" holds it to none.
|
||||
const assert = require("node:assert/strict");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
const { fixture } = require("./fixtures/caller-keys.cjs");
|
||||
|
||||
const words = {
|
||||
en: { item: "MCP servers", label: "MCP servers this key may use", all: "All MCP servers", two: "2 MCP servers", none: "No MCP server", only: /Only these MCP servers and tools: github, magpie-web-search\/web_fetch/ },
|
||||
zh: { item: "MCP 服务器", label: "这个密钥可用的 MCP 服务器", all: "全部 MCP 服务器", two: "2 个 MCP 服务器", none: "无 MCP 服务器", only: /仅限这些 MCP 服务器和工具/ },
|
||||
"zh-TW": { item: "MCP 伺服器", label: "這個金鑰可用的 MCP 伺服器", all: "全部 MCP 伺服器", two: "2 個 MCP 伺服器", none: "無 MCP 伺服器", only: /僅限這些 MCP 伺服器和工具/ },
|
||||
ja: { item: "MCP サーバー", label: "このキーが使える MCP サーバー", all: "すべての MCP サーバー", two: "2 個の MCP サーバー", none: "MCP サーバーなし", only: /この MCP サーバーとツールのみ/ },
|
||||
de: { item: "MCP-Server", label: "MCP-Server, die dieser Schlüssel nutzen darf", all: "Alle MCP-Server", two: "2 MCP-Server", none: "Kein MCP-Server", only: /Nur diese MCP-Server und Werkzeuge/ },
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const width of [1100, 420]) {
|
||||
for (const [lang, w] of Object.entries(words)) {
|
||||
test(`${engine} ${width} ${lang}: a gateway key is held to the MCP servers and tools picked for it`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const page = await (await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce" })).newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
const events = [], errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", fixture(lang, "light", events, { lan: true, keyHolds: { server: { mcp: ["github", "magpie-web-search/web_fetch"] } } }));
|
||||
await page.goto("http://magpie.test/?view=gateway");
|
||||
await page.locator("#gatewayKeys .acc[data-key]").last().waitFor();
|
||||
const row = (id) => page.locator(`#gatewayKeys .acc[data-key="${id}"]`);
|
||||
const badge = (id) => row(id).getByRole("button", { name: w.label, exact: true });
|
||||
// a held key says how many servers; a free one has no badge, not
|
||||
// even on hover, and is picked from its row's menu
|
||||
await page.mouse.move(0, 0);
|
||||
assert.equal((await badge("server").textContent()).trim(), w.two);
|
||||
assert.match(await badge("server").getAttribute("title"), w.only);
|
||||
await row("work").hover();
|
||||
assert.equal(await row("work").locator(".key-mcp").count(), 0);
|
||||
const view = page.locator("#view-gateway");
|
||||
const scrolled = async () => [await view.evaluate((v) => v.scrollTop), await page.evaluate(() => window.scrollY)];
|
||||
const at = await scrolled();
|
||||
await row("work").locator(".gw-key-more").click();
|
||||
await page.locator(".row-menu").getByRole("menuitem", { name: w.item, exact: true }).click();
|
||||
const menu = page.locator(".proto-menu");
|
||||
await menu.waitFor();
|
||||
assert.equal(await page.locator("select").count(), 0, "no native select");
|
||||
assert.equal((await menu.locator(".pm-head").textContent()).trim(), w.label);
|
||||
assert.equal(await menu.locator(".pm-item.on").count(), 1, "All MCP servers is ticked for a free key");
|
||||
// a server whole, and one tool of another; sent when the menu closes
|
||||
await menu.locator('.pm-item:has(.pm-name:text-is("Magpie Browser"))').click();
|
||||
await menu.locator('.pm-item:has(.pm-note:text-is("github/create_issue"))').click();
|
||||
assert.equal(events.filter((e) => e.action === "mcp-key").length, 0, "a pick was sent before the menu closed");
|
||||
await page.keyboard.press("Escape");
|
||||
await menu.waitFor({ state: "detached" });
|
||||
assert.deepEqual(events.filter((e) => e.action === "mcp-key").map((e) => e.body), [{ key: "work", mcp: ["magpie-browser", "github/create_issue"] }]);
|
||||
await page.waitForFunction(() => document.querySelector('#gatewayKeys .acc[data-key="work"] .key-mcp.set'));
|
||||
assert.equal((await badge("work").textContent()).trim(), w.two);
|
||||
// "No MCP server" ticked beside the key's servers holds it to none
|
||||
await row("server").hover();
|
||||
await badge("server").click();
|
||||
await menu.waitFor();
|
||||
assert.equal(await menu.locator(".pm-item.on").count(), 2);
|
||||
await menu.locator(".pm-item", { hasText: w.none }).click();
|
||||
await page.keyboard.press("Escape");
|
||||
await menu.waitFor({ state: "detached" });
|
||||
assert.deepEqual(events.filter((e) => e.action === "mcp-key").at(-1).body, { key: "server", mcp: ["-"] });
|
||||
await page.waitForFunction((none) => document.querySelector('#gatewayKeys .acc[data-key="server"] .key-mcp')?.textContent.trim() === none, w.none);
|
||||
assert.equal((await badge("server").textContent()).trim(), w.none);
|
||||
// All MCP servers takes it off
|
||||
await badge("server").click();
|
||||
await menu.waitFor();
|
||||
await menu.locator(".pm-item", { hasText: w.all }).first().click();
|
||||
await menu.waitFor({ state: "detached" });
|
||||
assert.deepEqual(events.filter((e) => e.action === "mcp-key").at(-1).body, { key: "server", mcp: [] });
|
||||
await page.waitForFunction(() => !document.querySelector('#gatewayKeys .acc[data-key="server"] .key-mcp'));
|
||||
assert.deepEqual(await scrolled(), at, "a click moved the page");
|
||||
// the row still fits
|
||||
const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
|
||||
assert.ok(over <= 0, `the page scrolls sideways by ${over}px`);
|
||||
const lefts = await page.locator("#gatewayKeys .key-mcp").evaluateAll((els) => els.map((e) => getComputedStyle(e).borderLeftStyle));
|
||||
assert(lefts.every((s) => s === "none"), "a coloured left border");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -193,3 +193,20 @@ func hubServerOf(s *Server) gateway.HubServer {
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// KeyMCPServers are every MCP server in the library, by name, with its
|
||||
// tools but those turned off as it last listed them (none when it never
|
||||
// has), for the picker of the servers and tools a gateway key may use
|
||||
// (wakaka on Discord): the hub, /mcp/<name> and /mcp/run/<name> reach
|
||||
// each, whether or not the hub gives it.
|
||||
func KeyMCPServers() []gateway.HubServer {
|
||||
mu.Lock()
|
||||
l, err := load()
|
||||
var ss []*Server
|
||||
if err == nil {
|
||||
ss = slices.Clone(l.MCP)
|
||||
}
|
||||
mu.Unlock()
|
||||
slices.SortStableFunc(ss, func(a, b *Server) int { return strings.Compare(a.Name, b.Name) })
|
||||
return hubAbouts(ss)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user