gateway, gui: magpie's web search is an MCP server too (Kayphoon on Discord)
What: /mcp/magpie/web-search serves the gateway's existing web search
(webSearch: the searcher's model, a Kimi Code plan's service, the search
APIs, in the order Settings sets) as an MCP server with one web_search
tool, so Cursor, Claude Desktop (through mcp-remote) or any agent can
mount it. Streamable HTTP only: POSTed JSON-RPC messages and batches are
answered with JSON (initialize with version negotiation, ping, tools/list,
tools/call), notifications get 202, GET/DELETE 405. Legacy SSE isn't
served. Two segments under /mcp/, so it can't hide a signed-in server's
/mcp/{name}.
Guards: lanGuard as on every route (a gateway key from another machine,
only while shared; rebound browser hosts refused), plus a local/shared
backstop in the handler. Any web page Origin (localhost too) is refused
unless listed in Settings, as the MCP spec asks of a server. keyLimited
passes /mcp/ by, so each tools/call reserves the calling key's limit
(budget.Reserve) and a spent key gets a tool error with no search. The
search is marked CallFor{MCP: true}, and Routing says the agent called
magpie's web_search MCP tool. With nothing that can search, the tool error
says where to add a search API.
GUI: Settings > Models > Web search has an "MCP server" row with the
address (from the Settings page's gateway URL) and Copy, in en, zh, zh-TW,
ja, de. docs/subsystems/gateway-routing.md has a section on it.
Run:
- go test -tags nogui -timeout 40m ./... (all ok, at the first rebase),
then gateway/gui package tests again after rebasing onto b1396d23.
- TestSearchMCP* (protocol, guards, key limit, Routing mark, no
searcher). Break checks: dropping Reserve, the Origin check or MCP:true
each turns its test red; dropping the handler's local/shared check does
not, because lanGuard already refuses (it is a backstop).
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui ./...
- GUI, Chromium + WebKit: search-mcp (new, 5 languages, 520px), i18n-keys,
gui-ja, gui-de, gui-zh-tw, search-first, search-api, searcher-pick,
routing-side-calls. search-mcp caught the address falling back to 3425.
search-mcp first held its row across Settings' redraws ("not attached
to the DOM" 3 times in ~60 WebKit runs under load ~150); it now reads
the row in one evaluate, and 3 full runs in both engines passed 60/60.
- Sandbox magpie (temp HOME, MAGPIE_ADDR 127.0.0.1:3512) with a fake
SearXNG on 3513: the official MCP TypeScript SDK client 1.32.1 did
initialize (2025-06-18), tools/list, tools/call and got the hit, as did
mcp-remote 0.14.3 over stdio; curl: GET 405, localhost/foreign Origin
403, rebound host 403, notification 202.
This commit is contained in:
@@ -16,7 +16,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md).
|
||||
| Part | Responsibility | Source |
|
||||
| --- | --- | --- |
|
||||
| Address and caller | `DefaultAddr`. The local token `magpie` and the per-agent `magpie-<agent>` (`TokenFor`). `agentOf` tells which agent asked, first by token, then by User-Agent. | [`gateway.go`](../../internal/gateway/gateway.go) |
|
||||
| HTTP surface | `Handler` routes `/v1/chat/completions`, `/v1/responses`, `/v1/messages` (each also without `/v1`), `/v1/models`, Gemini's `/v1beta/models/…`, the Codex backend path, `/v1/codex/models` (Codex's catalog shape for a Codex elsewhere with a gateway key, `codexCatalog`, kept to the key's models by `keyAllowed`; #1281), `/mcp/{name}` and the `/v1/magpie/*` status endpoints. A GET on `/v1/responses` (a client opening Responses over a WebSocket) is answered 426, a plain one 405: Responses is relayed over HTTP only. Every route is wrapped in `counted`, `corsGuard`, `callerGuard`, `withCaller` and `keyLimited`; `/v1/messages`, `/messages` and `/v1/messages/count_tokens` in `keepsSignIn` too. `corsGuard` (#1051) serves CORS only to the origins listed in Settings › Network › Web pages (`settings.CORSOrigins`, cleaned to `scheme://host[:port]` by `settings.CleanOrigins`, which refuses a wildcard). For a listed origin it answers the preflight (204) and adds `Access-Control-Allow-Origin`, and every other request from it needs an enabled gateway key (`access.Authenticate`), even on loopback, or gets a 401. It takes the key from the caller `lanGuard` recorded too, since on the running server `lanGuard` has already put magpie's own token in the key's place. Any other web page is refused 403 on every route (`foreignPage`): on loopback a call needs no key and the body's Content-Type isn't checked, so a page the user visits could otherwise send a "simple" `text/plain` POST and spend their subscriptions blind. Only an `http`/`https` Origin is judged, and one on this computer (`localhost`, `*.localhost`, `127.0.0.0/8`, `[::1]`, any port) or the request's own origin (its host and port equal to `Host`, such as a page on the gateway's LAN address) passes, as does usemagpie.ai on `/v1/magpie/omarchy`. `null` and other schemes (`app://`, `file://`, `tauri://`, `vscode-webview://`, `chrome-extension://`) come from desktop apps, webviews and extensions that don't enforce CORS, and pass. A request with no Origin (every agent's) passes through with no CORS headers, as before. A page whose own name resolves to 127.0.0.1 (DNS rebinding) would count as same-origin here, so `lanGuard` refuses it first (`rebound`, 403): a loopback request carrying a browser's marks (`Origin`, `Sec-Fetch-Site`/`Sec-Fetch-Mode`, a `Mozilla/` user agent) whose `Host` isn't this computer's (an IP, `localhost`, `*.localhost`, a container runtime's name for the host such as `host.docker.internal`, `MAGPIE_PUBLIC_URL`'s or `MAGPIE_ADDR`'s host, the machine's own name) needs an enabled gateway key. Agents send none of those marks and pass under any name. | [`gateway.go`](../../internal/gateway/gateway.go), [`cors.go`](../../internal/gateway/cors.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`internal/settings/origins.go`](../../internal/settings/origins.go) |
|
||||
| HTTP surface | `Handler` routes `/v1/chat/completions`, `/v1/responses`, `/v1/messages` (each also without `/v1`), `/v1/models`, Gemini's `/v1beta/models/…`, the Codex backend path, `/v1/codex/models` (Codex's catalog shape for a Codex elsewhere with a gateway key, `codexCatalog`, kept to the key's models by `keyAllowed`; #1281), `/mcp/{name}`, `/mcp/magpie/web-search` (magpie's own web search as an MCP server, below) and the `/v1/magpie/*` status endpoints. A GET on `/v1/responses` (a client opening Responses over a WebSocket) is answered 426, a plain one 405: Responses is relayed over HTTP only. Every route is wrapped in `counted`, `corsGuard`, `callerGuard`, `withCaller` and `keyLimited`; `/v1/messages`, `/messages` and `/v1/messages/count_tokens` in `keepsSignIn` too. `corsGuard` (#1051) serves CORS only to the origins listed in Settings › Network › Web pages (`settings.CORSOrigins`, cleaned to `scheme://host[:port]` by `settings.CleanOrigins`, which refuses a wildcard). For a listed origin it answers the preflight (204) and adds `Access-Control-Allow-Origin`, and every other request from it needs an enabled gateway key (`access.Authenticate`), even on loopback, or gets a 401. It takes the key from the caller `lanGuard` recorded too, since on the running server `lanGuard` has already put magpie's own token in the key's place. Any other web page is refused 403 on every route (`foreignPage`): on loopback a call needs no key and the body's Content-Type isn't checked, so a page the user visits could otherwise send a "simple" `text/plain` POST and spend their subscriptions blind. Only an `http`/`https` Origin is judged, and one on this computer (`localhost`, `*.localhost`, `127.0.0.0/8`, `[::1]`, any port) or the request's own origin (its host and port equal to `Host`, such as a page on the gateway's LAN address) passes, as does usemagpie.ai on `/v1/magpie/omarchy`. `null` and other schemes (`app://`, `file://`, `tauri://`, `vscode-webview://`, `chrome-extension://`) come from desktop apps, webviews and extensions that don't enforce CORS, and pass. A request with no Origin (every agent's) passes through with no CORS headers, as before. A page whose own name resolves to 127.0.0.1 (DNS rebinding) would count as same-origin here, so `lanGuard` refuses it first (`rebound`, 403): a loopback request carrying a browser's marks (`Origin`, `Sec-Fetch-Site`/`Sec-Fetch-Mode`, a `Mozilla/` user agent) whose `Host` isn't this computer's (an IP, `localhost`, `*.localhost`, a container runtime's name for the host such as `host.docker.internal`, `MAGPIE_PUBLIC_URL`'s or `MAGPIE_ADDR`'s host, the machine's own name) needs an enabled gateway key. Agents send none of those marks and pass under any name. | [`gateway.go`](../../internal/gateway/gateway.go), [`cors.go`](../../internal/gateway/cors.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`internal/settings/origins.go`](../../internal/settings/origins.go) |
|
||||
| Model resolution | `serve` resolves the model the agent asked for: Claude tier stand-ins, a routing group (`provider.GroupFor`: its id, the model's id however a vendor spells it, else the one group whose name it is, unless a provider serves a model by that id), auto stand-ins, the agent's own stand-in (`StandIn`: Codex's config.toml `model` when magpie is its provider, for a name it sends that magpie doesn't serve, such as its auto-review's `codex-auto-review`), itself taken through `GroupFor` and auto stand-ins so a config naming a group bare reaches it, then `provider.Resolve`. A Codex memory call or auto-review (`x-openai-subagent: guardian`, or `codex-auto-review`) that still names no served model goes to the model Codex's last turn was answered on (`codexMemoryStandIn`, per agent and gateway key), so a Codex on magpie through another provider table, a profile or another computer isn't answered 404 (Adam on Discord, `TestCodexAutoReviewReachesItsTurnsModel`). A bare model id several providers serve (MOMO on Discord: `glm-5.3` under opencode-go and a6api) is never refused: with found groups on (the default) `GroupFor` takes it to the group magpie found for it (`auto-<slug>`), its members in the Providers order, routed and failed over as any group, a conversation staying with the member that answered it while its cache is worth it (affinity); with them off, `Resolve` takes the first provider in the Providers order that exposes it, with no fallback. magpie writes only `provider/model` ids into agents' configs (`magpieModels`), so a bare id is one the user wrote. Every reply says who answered in `X-Magpie-Provider` and `X-Magpie-Model` (`noteMember`), and the usage log and the Routing page keep it. A model id with `~` and no slash that resolves as nothing else is the one served id (a provider's model or a group) whose slashes it spells as `~` (`unflat`, `provider.Unflat`; MiniMax Code's spelling, #1387), taken back in `validateModel` before key limits, middleware and usage see it; two ids spelled alike are neither. A Claude model id whose version is dashed (`relay/claude-opus-4-6-us`, with or without `:level` and `[1m]`) that is not served as spelled is the one served id it dashes (`provider.ClaudeUndashed`; the spelling magpie gives Claude Code, which reads a dotted version as Claude Opus 4), taken back in `validateModel` and `unprefixed` the same way. An unknown model gets a 404 naming why: a switched-off provider, a disabled group or an empty group. Otherwise it names up to three ids nearest to what was asked (`provider.Closest`: words of a model's display name count before words of its id, and a provider's id or name only alongside them, so "Zen-Space-Bunny" is told `opencode-zen-free/space-bunny-free`, MOMO on Discord), then the ways a model can be named, then every id (`unknownModel`; chat and embeddings). | [`gateway.go`](../../internal/gateway/gateway.go), [`internal/provider/group.go`](../../internal/provider/group.go), [`internal/provider/flat.go`](../../internal/provider/flat.go), [`internal/provider/claudedash.go`](../../internal/provider/claudedash.go) |
|
||||
| Candidates | `plan` lists one provider's candidates: one per key or account on, then each `Fallback` model, with resting ones last (`restLast`). `planGroup` and `planLevel` weigh a group's members together. A nested group plans by its own routing (#576). A member's own fallbacks are not the group's. | [`fallback.go`](../../internal/gateway/fallback.go) |
|
||||
| Order of keys and accounts | `Routing`: smart (""), `order`, `rotate`, `usage` (least used, with an `usageHalfLife` of 1h), `pace` or `weight` (`weightedFirst`). Smart, `usage` and `pace` weigh a subscription by its allowance (`allowances`), and a key by its own usage windows when magpie reads them (`keyAllowance`: a sub2api key given a 5-hour, day or 7-day limit, or a key bought as a plan, such as Kimi Code's or a GLM Coding Plan's); any other key has none. A lone key or account is weighed against nobody, but what it has left is still read into the trace (`weighRouted`), so the Routing page shows it as it does for several (#1016); all but used up, it keeps its conversation rather than being said to move (`affine`). A failure rests a candidate (`failure`, `failureOf`). | [`routing.go`](../../internal/gateway/routing.go), [`weighted.go`](../../internal/gateway/weighted.go), [`internal/provider/routing.go`](../../internal/provider/routing.go) |
|
||||
@@ -146,12 +146,47 @@ named provider still falls back to that selection.
|
||||
Covered by `TestSearchProviderOff`, `TestSearchProviderOffForwarding`, `TestSearchProviderOffTellsRemoteMagpie`,
|
||||
`TestSearcherChosen`, `TestSettingsSearchProviderOff`, and `searcher-pick.test.cjs`.
|
||||
|
||||
## Web search as an MCP server
|
||||
|
||||
`SearchMCPPath`, `/mcp/magpie/web-search`, serves the same `webSearch` a
|
||||
model that can't search is given (the searcher's model, a Kimi Code plan's
|
||||
service, the search APIs, as Settings › Models › Web search orders them)
|
||||
as an MCP server of its own, so Cursor, Claude Desktop or any agent can
|
||||
mount it as a `web_search` tool (Kayphoon on Discord). It speaks Streamable
|
||||
HTTP only: each POST of a JSON-RPC message or batch is answered with JSON
|
||||
(`initialize`, `ping`, `tools/list`, `tools/call`), notifications get 202,
|
||||
and GET and DELETE get 405, since the server has no stream or session of
|
||||
its own. Legacy SSE isn't served; a client that only speaks stdio mounts it
|
||||
through `mcp-remote`. The path has two segments under `/mcp/`, so it can't
|
||||
hide a signed-in server's `/mcp/{name}`.
|
||||
|
||||
It is a gateway route like the others. `lanGuard` takes a gateway key from
|
||||
another machine (only while magpie is shared) and refuses a rebound browser
|
||||
host, and the handler checks `local`/`sharedWith` again as a backstop when
|
||||
`Handler` is served without `lanGuard`. Unlike other routes, a web page on
|
||||
this computer (a `localhost` Origin, which `corsGuard` lets through) is
|
||||
refused too: only an origin listed in Settings, which `corsGuard` already
|
||||
held to a gateway key, may call it, as the MCP spec has a server check
|
||||
`Origin`. `keyLimited` passes `/mcp/` by, so each `tools/call` reserves the
|
||||
calling key's limit itself (`budget.Reserve`), and a spent key's call is a
|
||||
tool error with no search made. The search is marked `CallFor{Agent, MCP:
|
||||
true}`, so Routing says the agent called magpie's web_search MCP tool rather
|
||||
than that magpie searched for one of its models. With nothing that can
|
||||
search, the tool error says where to add a search API. Settings › Models ›
|
||||
Web search shows the address (`#searchMcpRow`, from the Settings page's own
|
||||
`gateway` address).
|
||||
|
||||
Covered by `TestSearchMCPServesWebSearch`, `TestSearchMCPWithNoSearcher`,
|
||||
`TestSearchMCPGuarded`, `TestSearchMCPHeldToKeyLimit`,
|
||||
`TestSearchMCPRoutedAsTheAgentsCall` and `search-mcp.test.cjs`.
|
||||
|
||||
## Verification
|
||||
|
||||
```sh
|
||||
go test -tags nogui ./internal/gateway -run 'TestLoop|TestLongReplyThatDoesNotLoop|TestQuiet|TestSilentHeld|TestRotateSpreadsSessions|TestRouting|TestSmartRouting|TestFallback|TestNoFallbackForOtherErrors|TestLastFallbackErrorReachesTheAgent|TestRateLimitedSinksToTheBack|TestGroupRateLimitedSinks|TestAffinity|TestSeveralKeysOnTakeOverFromEachOther|TestModelNotInPlanRestsTheModelNotTheKey|TestSubscriptionAccountsTakeOver|TestGroup|TestTrace|TestImageTool|TestCodexNoCredits|TestWindowCapsHoldTheAccount|TestAccountCap|TestClaudeGoesOnMessagesWhereTheRelayHasThem|TestAutoRelaysOnTheClientsOwnAPI|TestSearchOfferedStaysOnTheClientsAPI|TestCodexSearchAnsweredOnResponses|TestAgentEffortOnCursorLocal|TestAzureCompactionWithoutMagpiesReasoning|TestCodexCompact|TestProtection|TestSearchedConversation|TestUnsearchedConversationUnchanged|TestNotAnAPIReply|TestAPIReplyUntouched|TestCodexBackendWebPage|TestSub2APIKeyLimitIsQuota|TestKeysWeighedByTheirWindows|TestGroupWeighsKeyWindows|TestKeyOutOfItsWindowRestsUntilReset|TestKeyPoolErrorDoesNotRestForWindow|TestKeyBackOnceItsWindowIsNotFull|TestRestingKeyReadAgainInAnOrderedGroup|TestClaudeAccountBackOnceItsWindowRenews|TestThinkingStreams|TestHeldThinkingKeepsTheAgentAlive|TestCodexHeardWithinItsIdleTimeout|TestRefusalAfterThinkingFailsOver|TestGeminiEmptyRepliesAskedAgain|TestLocalUnredacted|TestCORS|TestForeignPagesRefused|TestAIStudioThinking|TestGeminiThoughtsThroughLocalProxy|TestGeminiRefusedLevel|TestGeminiThinkingOffAtItsLowest|TestThinkingOff|TestClaudeFiveFiveThinkingOffOnTheWire|TestSamplingAsTheModelTakesIt|TestHaikuFiveFiveSamplingOnTheWire|TestGeminiThoughtsMarkedInExtraContent|TestGeminiThinkingLevelRefused|TestGeminiMinimalRefusedTwiceAtOnce|TestPassthroughGeminiMinimalRefused|TestPassthroughEffortNoneRefused|TestPassthroughMinimalRefusedNoneTaken|TestOtherOffNamed|TestClaudeSignInNotToldItsSignInFailed|TestSignInWriterReleasesA403|TestSignInBetaStaysWithMagpie|TestStructuredOutput|TestResponsesTextKeepsVerbosityBesideFormat|TestRefusedFormatToldInWords|RPM|TestQueued|TestCustomGeminiUpstream|TestWholeNums|TestGrokCalls|TestOnlyGrokCalls|TestGrokModel|TestGrokPluginCalls'
|
||||
go test -tags nogui ./internal/gateway -run 'TestVertex'
|
||||
go test -tags nogui ./internal/gateway -run 'TestRemoteMagpie|TestRedactedKinds'
|
||||
go test -tags nogui ./internal/gateway -run 'TestSearchMCP'
|
||||
go test -tags nogui ./internal/redact ./internal/gui -run 'TestMoreKinds|TestCategoryDefaults|TestRedactKindsAreRedacts'
|
||||
go test -tags nogui ./internal/gateway -run 'TestCodexModelList|TestCodexModelsEtag'
|
||||
go test -tags nogui ./internal/provider -run 'TestGroup|TestCodexCreditsSwitch|TestRenewedAccountForgetsItsAllowance|TestDeclareSearch|TestNative|TestKeyAllowance|TestPlanKeyAllowance|TestClaudeAccountToldRenewed|TestPluginAccountToldRenewed|TestSkipsRedaction|TestSetRPM'
|
||||
|
||||
@@ -532,6 +532,7 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.HandleFunc("GET /videos/{id}/content", s.videosContent)
|
||||
mux.HandleFunc("POST /_magpie/claude-mcp/{token}", s.subscription.mcpCall)
|
||||
mux.HandleFunc("/mcp/{name}", s.mcpProxy)
|
||||
mux.HandleFunc(SearchMCPPath, s.searchMCP)
|
||||
mux.HandleFunc(CodexPath+"/", s.codexBackend)
|
||||
mux.HandleFunc("GET "+CodexCatalogPath, s.codexCatalog)
|
||||
mux.HandleFunc("GET /v1beta/models", s.geminiModels)
|
||||
@@ -559,7 +560,7 @@ func responsesOverHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func (s *Server) info(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, 200, map[string]any{"name": "magpie", "version": Version, "models": len(provider.Catalog()), "window": Window,
|
||||
"apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1/systemone", "/v1beta/models/{model}:generateContent", "/v1/images/generations", "/v1/images/edits", "/v1/videos", "/v1/embeddings", "/v1/rerank", "/v1/magpie/quotas", "/v1/magpie/quotas/history", "/v1/magpie/usage", "/v1/magpie/usage/requests", "/v1/magpie/route"}})
|
||||
"apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1/systemone", "/v1beta/models/{model}:generateContent", "/v1/images/generations", "/v1/images/edits", "/v1/videos", "/v1/embeddings", "/v1/rerank", "/v1/magpie/quotas", "/v1/magpie/quotas/history", "/v1/magpie/usage", "/v1/magpie/usage/requests", "/v1/magpie/route", SearchMCPPath}})
|
||||
}
|
||||
|
||||
// quotas is what is left of every subscription, plan and key magpie has,
|
||||
|
||||
@@ -65,6 +65,9 @@ type CallFor struct {
|
||||
// model that described is the one magpie picks in its place
|
||||
// (VisionMissing), and the Routing view names both.
|
||||
Missing string `json:"missing,omitempty"`
|
||||
// MCP, on a web search, is that the agent called magpie's web search
|
||||
// MCP server (SearchMCPPath) itself, for no model of magpie's.
|
||||
MCP bool `json:"mcp,omitempty"`
|
||||
}
|
||||
|
||||
func searchFor(ctx context.Context) *CallFor {
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/budget"
|
||||
)
|
||||
|
||||
// magpie's web search, the one a model that can't search is given
|
||||
// (webSearch: the searcher's model, a Kimi Code plan's service, the
|
||||
// search APIs), is also an MCP server of its own (Kayphoon on Discord),
|
||||
// so Cursor, Claude Desktop and any other agent can mount it as a
|
||||
// web_search tool: Streamable HTTP at SearchMCPPath, JSON answered to each
|
||||
// POST. It is a gateway route like the others: this computer calls it with
|
||||
// any key, another one only while magpie is shared and with an enabled
|
||||
// gateway key (lanGuard), a gateway key's limit holds each search
|
||||
// (budget.Reserve), and a web page is turned away, as the MCP spec has a
|
||||
// server check Origin.
|
||||
|
||||
// SearchMCPPath is where the web search MCP server is served. It has two
|
||||
// segments under /mcp/, so it can't hide a signed-in server's /mcp/{name}.
|
||||
const SearchMCPPath = "/mcp/magpie/web-search"
|
||||
|
||||
// searchMCPVersions are the MCP versions the server speaks, newest first:
|
||||
// a client asking for one of them is answered in it, any other in the first.
|
||||
var searchMCPVersions = []string{"2025-06-18", "2025-03-26", "2024-11-05"}
|
||||
|
||||
const searchMCPTool = "web_search"
|
||||
|
||||
type mcpMessage struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
ID json.RawMessage `json:"id,omitempty"`
|
||||
Method string `json:"method,omitempty"`
|
||||
Params json.RawMessage `json:"params,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Server) searchMCP(w http.ResponseWriter, r *http.Request) {
|
||||
if !local(r) && !sharedWith(r) {
|
||||
http.Error(w, "magpie's web search is served to another machine only when magpie is shared on the local network and the request carries a gateway key (Authorization: Bearer <key>)", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
// a page on this computer (localhost) gets past corsGuard; only one the
|
||||
// user listed in Settings, which corsGuard held to a gateway key, may
|
||||
// call this
|
||||
if o := r.Header.Get("Origin"); o != "" && !corsAllowed(o) {
|
||||
http.Error(w, "magpie's web search MCP server answers agents, not web pages", http.StatusForbidden)
|
||||
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")
|
||||
http.Error(w, "POST JSON-RPC messages here (MCP Streamable HTTP)", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
body = bytes.TrimSpace(body)
|
||||
batch := len(body) > 0 && body[0] == '['
|
||||
var msgs []mcpMessage
|
||||
if batch {
|
||||
err = json.Unmarshal(body, &msgs)
|
||||
} else {
|
||||
var m mcpMessage
|
||||
err = json.Unmarshal(body, &m)
|
||||
msgs = []mcpMessage{m}
|
||||
}
|
||||
if err != nil || len(msgs) == 0 {
|
||||
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
|
||||
}
|
||||
var out []any
|
||||
for _, m := range msgs {
|
||||
// a notification (no id) or a response to the server is answered
|
||||
// with nothing
|
||||
if len(m.ID) == 0 || bytes.Equal(m.ID, []byte("null")) || m.Method == "" {
|
||||
continue
|
||||
}
|
||||
result, rpcErr := s.searchMCPCall(r, m)
|
||||
reply := map[string]any{"jsonrpc": "2.0", "id": m.ID}
|
||||
if rpcErr != nil {
|
||||
reply["error"] = rpcErr
|
||||
} else {
|
||||
reply["result"] = result
|
||||
}
|
||||
out = append(out, reply)
|
||||
}
|
||||
if len(out) == 0 {
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
return
|
||||
}
|
||||
if batch {
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out[0])
|
||||
}
|
||||
|
||||
// searchMCPCall answers one request: its result, or its JSON-RPC error.
|
||||
func (s *Server) searchMCPCall(r *http.Request, m mcpMessage) (any, map[string]any) {
|
||||
switch m.Method {
|
||||
case "initialize":
|
||||
var p struct {
|
||||
ProtocolVersion string `json:"protocolVersion"`
|
||||
}
|
||||
json.Unmarshal(m.Params, &p)
|
||||
v := searchMCPVersions[0]
|
||||
if slices.Contains(searchMCPVersions, p.ProtocolVersion) {
|
||||
v = p.ProtocolVersion
|
||||
}
|
||||
return map[string]any{
|
||||
"protocolVersion": v,
|
||||
"capabilities": map[string]any{"tools": map[string]any{}},
|
||||
"serverInfo": map[string]any{"name": "magpie-web-search", "title": "Magpie Web Search", "version": Version},
|
||||
"instructions": "web_search searches the web with the search magpie gives its models: a provider that can search, or the search APIs set up in magpie (Settings → Models → Web search).",
|
||||
}, nil
|
||||
case "ping":
|
||||
return map[string]any{}, nil
|
||||
case "tools/list":
|
||||
t := searchTool(nil)
|
||||
return map[string]any{"tools": []any{map[string]any{
|
||||
"name": searchMCPTool,
|
||||
"title": "Web search",
|
||||
"description": t.Description,
|
||||
"inputSchema": t.Schema,
|
||||
"annotations": map[string]any{"readOnlyHint": true, "openWorldHint": true},
|
||||
}}}, nil
|
||||
case "tools/call":
|
||||
var p struct {
|
||||
Name string `json:"name"`
|
||||
Arguments struct {
|
||||
Query string `json:"query"`
|
||||
} `json:"arguments"`
|
||||
}
|
||||
if err := json.Unmarshal(m.Params, &p); err != nil {
|
||||
return nil, map[string]any{"code": -32602, "message": "invalid params: " + err.Error()}
|
||||
}
|
||||
if p.Name != searchMCPTool {
|
||||
return nil, map[string]any{"code": -32602, "message": "unknown tool " + p.Name + ": this server has " + searchMCPTool}
|
||||
}
|
||||
said, err := s.searchMCPRun(r, strings.TrimSpace(p.Arguments.Query))
|
||||
if err != nil {
|
||||
return toolResult(err.Error(), true), nil
|
||||
}
|
||||
return toolResult(said, false), nil
|
||||
}
|
||||
return nil, map[string]any{"code": -32601, "message": "method not found: " + m.Method}
|
||||
}
|
||||
|
||||
func toolResult(text string, isError bool) map[string]any {
|
||||
return map[string]any{"content": []any{map[string]any{"type": "text", "text": text}}, "isError": isError}
|
||||
}
|
||||
|
||||
type searchMCPError string
|
||||
|
||||
func (e searchMCPError) Error() string { return string(e) }
|
||||
|
||||
// searchMCPRun searches for the query as a model's web_search would be:
|
||||
// held to the calling gateway key's limit, and named in the Routing view
|
||||
// as the agent's MCP call.
|
||||
func (s *Server) searchMCPRun(r *http.Request, query string) (string, error) {
|
||||
if query == "" {
|
||||
return "", searchMCPError("web_search needs a query")
|
||||
}
|
||||
release, refused := budget.Reserve(access.Caller(r.Context()), int64(len(query)), "", limitClock())
|
||||
if refused != nil {
|
||||
return "", refused
|
||||
}
|
||||
defer release()
|
||||
ctx := context.WithValue(r.Context(), searchForKey{}, &CallFor{Agent: callerOf(r).agent, MCP: true})
|
||||
said, _, err := s.webSearch(ctx, query)
|
||||
if err != nil {
|
||||
if r.Context().Err() == nil {
|
||||
log.Printf("web search MCP: %v", err)
|
||||
}
|
||||
msg := "magpie couldn't search the web: " + err.Error()
|
||||
if errors.Is(err, errNoSearcher) {
|
||||
msg += ": add a search API in magpie's Settings → Models → Web search (or magpie search add <api> <key>), or a provider that can search"
|
||||
}
|
||||
return "", searchMCPError(msg)
|
||||
}
|
||||
return said, nil
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/budget"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// mcpPost sends one JSON-RPC body to the web search MCP server through h,
|
||||
// from addr, with hdr as name, value pairs.
|
||||
func mcpPost(h http.Handler, addr, body string, hdr ...string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(http.MethodPost, SearchMCPPath, strings.NewReader(body))
|
||||
r.RemoteAddr = addr
|
||||
r.Host = "127.0.0.1:3425"
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
r.Header.Set("Accept", "application/json, text/event-stream")
|
||||
for i := 0; i+1 < len(hdr); i += 2 {
|
||||
r.Header.Set(hdr[i], hdr[i+1])
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
|
||||
type mcpReply struct {
|
||||
ID json.RawMessage `json:"id"`
|
||||
Result struct {
|
||||
ProtocolVersion string `json:"protocolVersion"`
|
||||
ServerInfo struct{ Name string }
|
||||
Tools []struct {
|
||||
Name string
|
||||
InputSchema struct {
|
||||
Required []string
|
||||
}
|
||||
}
|
||||
Content []struct{ Type, Text string }
|
||||
IsError bool
|
||||
}
|
||||
Error *struct {
|
||||
Code int
|
||||
Message string
|
||||
}
|
||||
}
|
||||
|
||||
func readMCP(t *testing.T, w *httptest.ResponseRecorder) mcpReply {
|
||||
t.Helper()
|
||||
if w.Code != 200 || !strings.HasPrefix(w.Header().Get("Content-Type"), "application/json") {
|
||||
t.Fatalf("%d %s: %s", w.Code, w.Header().Get("Content-Type"), w.Body.String())
|
||||
}
|
||||
var m mcpReply
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &m); err != nil {
|
||||
t.Fatalf("%v: %s", err, w.Body.String())
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
const mcpSearchCall = `{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"web_search","arguments":{"query":"latest go"}}}`
|
||||
|
||||
// magpie's web search is an MCP server of its own on the gateway (Kayphoon
|
||||
// on Discord): an MCP client initializes, lists one web_search tool and
|
||||
// calls it, and the search goes where a model's web_search would go — here
|
||||
// the search API the user set up — the pages it found in the tool's text.
|
||||
func TestSearchMCPServesWebSearch(t *testing.T) {
|
||||
fresh(t)
|
||||
apis := newSearchAPIs(t)
|
||||
if err := provider.SetSearchAPI(apis.api("tavily", "tvly-k")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := lanGuard(New().Handler()) // as the real server has it
|
||||
const here = "127.0.0.1:50000"
|
||||
|
||||
init := readMCP(t, mcpPost(h, here, `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"cursor","version":"1"}}}`))
|
||||
if init.Error != nil || init.Result.ProtocolVersion != "2025-03-26" || init.Result.ServerInfo.Name != "magpie-web-search" || string(init.ID) != "1" {
|
||||
t.Fatalf("initialize: %+v", init)
|
||||
}
|
||||
// a version it doesn't speak is answered in its newest
|
||||
if v := readMCP(t, mcpPost(h, here, `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2099-01-01"}}`)).Result.ProtocolVersion; v != searchMCPVersions[0] {
|
||||
t.Fatalf("unknown version answered in %q", v)
|
||||
}
|
||||
if w := mcpPost(h, here, `{"jsonrpc":"2.0","method":"notifications/initialized"}`); w.Code != http.StatusAccepted || w.Body.Len() != 0 {
|
||||
t.Fatalf("a notification: %d %q", w.Code, w.Body.String())
|
||||
}
|
||||
list := readMCP(t, mcpPost(h, here, `{"jsonrpc":"2.0","id":2,"method":"tools/list"}`))
|
||||
if len(list.Result.Tools) != 1 || list.Result.Tools[0].Name != "web_search" || !slices.Equal(list.Result.Tools[0].InputSchema.Required, []string{"query"}) {
|
||||
t.Fatalf("tools/list: %+v", list)
|
||||
}
|
||||
call := readMCP(t, mcpPost(h, here, mcpSearchCall, "User-Agent", "Cursor/1.7"))
|
||||
if call.Result.IsError || len(call.Result.Content) != 1 || call.Result.Content[0].Type != "text" ||
|
||||
!strings.Contains(call.Result.Content[0].Text, "Go downloads — https://go.dev/dl/") || !strings.Contains(call.Result.Content[0].Text, "go1.27.1 is the latest release.") {
|
||||
t.Fatalf("tools/call: %+v", call)
|
||||
}
|
||||
if strings.Join(apis.asked, "|") != "tavily: latest go" {
|
||||
t.Fatalf("asked %q", apis.asked)
|
||||
}
|
||||
|
||||
// a batch is answered as one, its notification left out
|
||||
w := mcpPost(h, here, `[{"jsonrpc":"2.0","id":"a","method":"ping"},{"jsonrpc":"2.0","method":"notifications/initialized"},{"jsonrpc":"2.0","id":"b","method":"resources/list"}]`)
|
||||
var batch []mcpReply
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &batch); err != nil || len(batch) != 2 || batch[0].Error != nil || batch[1].Error == nil || batch[1].Error.Code != -32601 {
|
||||
t.Fatalf("batch: %s", w.Body.String())
|
||||
}
|
||||
// another tool, no query, a body that isn't JSON
|
||||
if m := readMCP(t, mcpPost(h, here, `{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"fetch","arguments":{}}}`)); m.Error == nil || m.Error.Code != -32602 {
|
||||
t.Fatalf("unknown tool: %+v", m)
|
||||
}
|
||||
if m := readMCP(t, mcpPost(h, here, `{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"web_search","arguments":{"query":" "}}}`)); !m.Result.IsError {
|
||||
t.Fatalf("no query: %+v", m)
|
||||
}
|
||||
if w := mcpPost(h, here, `nope`); w.Code != 400 || !strings.Contains(w.Body.String(), "-32700") {
|
||||
t.Fatalf("not JSON: %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
// no stream of its own to GET
|
||||
r := httptest.NewRequest(http.MethodGet, SearchMCPPath, nil)
|
||||
r.RemoteAddr = here
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, r)
|
||||
if rec.Code != http.StatusMethodNotAllowed || rec.Header().Get("Allow") != "POST" {
|
||||
t.Fatalf("GET: %d %v", rec.Code, rec.Header())
|
||||
}
|
||||
}
|
||||
|
||||
// Nothing to search with: the call says so as the tool's error, with where
|
||||
// to set a search up, rather than failing the request.
|
||||
func TestSearchMCPWithNoSearcher(t *testing.T) {
|
||||
fresh(t)
|
||||
m := readMCP(t, mcpPost(lanGuard(New().Handler()), "127.0.0.1:50000", mcpSearchCall))
|
||||
if !m.Result.IsError || len(m.Result.Content) != 1 || !strings.Contains(m.Result.Content[0].Text, "Settings → Models → Web search") {
|
||||
t.Fatalf("%+v", m)
|
||||
}
|
||||
}
|
||||
|
||||
// The server is a gateway route like the others: another computer reaches
|
||||
// it only while magpie is shared and with an enabled gateway key, a web
|
||||
// page — one rebound to 127.0.0.1, or one on this computer — is turned
|
||||
// away, and the search API is asked for none of them.
|
||||
func TestSearchMCPGuarded(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)
|
||||
}
|
||||
h := lanGuard(New().Handler())
|
||||
const there = "192.0.2.7:4000"
|
||||
if w := mcpPost(h, there, mcpSearchCall); w.Code != http.StatusForbidden {
|
||||
t.Fatalf("not shared: %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
_, secrets := newCaller(t, "Laptop") // shares magpie
|
||||
if w := mcpPost(h, there, mcpSearchCall); w.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("shared, no key: %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
if w := mcpPost(h, there, mcpSearchCall, "Authorization", "Bearer sk-magpie-wrong"); w.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("shared, a wrong key: %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
chrome := []string{"User-Agent", "Mozilla/5.0 (Macintosh) Chrome/140", "Sec-Fetch-Site", "same-origin", "Sec-Fetch-Mode", "cors"}
|
||||
r := httptest.NewRequest(http.MethodPost, SearchMCPPath, strings.NewReader(mcpSearchCall))
|
||||
r.RemoteAddr = "127.0.0.1:50000"
|
||||
r.Host = "rebind.attacker.example:3425"
|
||||
for i := 0; i+1 < len(chrome); i += 2 {
|
||||
r.Header.Set(chrome[i], chrome[i+1])
|
||||
}
|
||||
r.Header.Set("Origin", "http://rebind.attacker.example:3425")
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, r)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("a rebound page: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if w := mcpPost(h, "127.0.0.1:50000", mcpSearchCall, "Origin", "http://localhost:5173"); w.Code != http.StatusForbidden {
|
||||
t.Fatalf("a page on this computer: %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
if w := mcpPost(h, "127.0.0.1:50000", mcpSearchCall, "Origin", "https://evil.example"); w.Code != http.StatusForbidden {
|
||||
t.Fatalf("another site's page: %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
if len(apis.asked) != 0 {
|
||||
t.Fatalf("searched for a refused call: %q", apis.asked)
|
||||
}
|
||||
m := readMCP(t, mcpPost(h, there, mcpSearchCall, "Authorization", "Bearer "+secrets[0]))
|
||||
if m.Result.IsError || !strings.Contains(m.Result.Content[0].Text, "https://go.dev/dl/") {
|
||||
t.Fatalf("shared, with its key: %+v", m)
|
||||
}
|
||||
}
|
||||
|
||||
// A gateway key past its limit searches no more through the server: the
|
||||
// call says the limit, and no search is made.
|
||||
func TestSearchMCPHeldToKeyLimit(t *testing.T) {
|
||||
fresh(t)
|
||||
budget.Forget()
|
||||
pinLimitClock(t)
|
||||
calls := limitedUpstream(t, 0)
|
||||
apis := newSearchAPIs(t)
|
||||
if err := provider.SetSearchAPI(apis.api("tavily", "tvly-k")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
keys, secrets := newCaller(t, "Capped")
|
||||
setLimit(t, keys[0].ID, &access.Limit{Period: "day", Tokens: 700})
|
||||
h := lanGuard(New().Handler())
|
||||
for range 2 {
|
||||
r := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(chatReq))
|
||||
r.RemoteAddr = "127.0.0.1:5000"
|
||||
r.Header.Set("Authorization", "Bearer "+secrets[0])
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != 200 {
|
||||
t.Fatal(w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
if calls.Load() != 2 {
|
||||
t.Fatal(calls.Load())
|
||||
}
|
||||
apis.asked = nil
|
||||
m := readMCP(t, mcpPost(h, "127.0.0.1:5000", mcpSearchCall, "Authorization", "Bearer "+secrets[0]))
|
||||
if !m.Result.IsError || !strings.Contains(m.Result.Content[0].Text, `"Capped"`) {
|
||||
t.Fatalf("a spent key: %+v", m)
|
||||
}
|
||||
if len(apis.asked) != 0 {
|
||||
t.Fatalf("a spent key searched: %q", apis.asked)
|
||||
}
|
||||
// without a key, from this computer, it searches
|
||||
if m := readMCP(t, mcpPost(h, "127.0.0.1:5000", mcpSearchCall)); m.Result.IsError {
|
||||
t.Fatalf("keyless: %+v", m)
|
||||
}
|
||||
}
|
||||
|
||||
// A search a provider's model runs for the server is named in the Routing
|
||||
// view as the agent's MCP call, not as a search for a model of its.
|
||||
func TestSearchMCPRoutedAsTheAgentsCall(t *testing.T) {
|
||||
searchSandbox(t)
|
||||
ds := newFakeDeepSeek(t)
|
||||
searchesOn(t, provider.Responses, ds.URL)
|
||||
save(t, provider.Provider{ID: "ds", Name: "DeepSeek", Key: "k", Chat: ds.URL + "/v1", Responses: ds.URL + "/v1", Models: []string{"deepseek-flash"}})
|
||||
st := settings.Load()
|
||||
st.Searcher = ""
|
||||
settings.Save(st)
|
||||
s := New()
|
||||
m := readMCP(t, mcpPost(lanGuard(s.Handler()), "127.0.0.1:5000", mcpSearchCall, "User-Agent", "claude-code/2.1.0"))
|
||||
if m.Result.IsError || !strings.Contains(m.Result.Content[0].Text, "22/17℃") || !strings.Contains(m.Result.Content[0].Text, "https://www.weather.com.cn/") {
|
||||
t.Fatalf("%+v", m)
|
||||
}
|
||||
var searched *Route
|
||||
for _, r := range s.Trace(context.Background(), 0, 0).Routes {
|
||||
if r.Kind == "web_search" {
|
||||
searched = &r
|
||||
}
|
||||
}
|
||||
if searched == nil || searched.For == nil || !searched.For.MCP || searched.For.Agent != "claude-code" {
|
||||
t.Fatalf("route %+v", searched)
|
||||
}
|
||||
}
|
||||
@@ -20406,6 +20406,12 @@ function renderSearch(s, keep) {
|
||||
(v) => savePrefs({ ...keep, searchFirst: v === "api" ? "api" : "" })));
|
||||
r.id = "searchFirstRow";
|
||||
}
|
||||
// the same search as an MCP server of the gateway's (Kayphoon on
|
||||
// Discord), for an agent to mount as its web_search tool
|
||||
const mcpURL = (s.gateway || providers?.gateway?.url || `http://127.0.0.1:${s.port || 3425}`).replace(/\/+$/, "") + "/mcp/magpie/web-search";
|
||||
const mcp = row(t("MCP server"), t("Cursor, Claude Desktop and other agents can add this search as an MCP server (Streamable HTTP) with one web_search tool. From another computer, send a gateway key as Authorization: Bearer <key>."),
|
||||
el("code", "", mcpURL), copyBtn(mcpURL, t("Address")));
|
||||
mcp.id = "searchMcpRow";
|
||||
}
|
||||
|
||||
// renderSearcher: the provider that searches the web for a model that
|
||||
|
||||
@@ -950,6 +950,8 @@ const I18N = {
|
||||
"Now done by {who}; these come after it": "目前由 {who} 代搜,这些排在它之后",
|
||||
"Asked before {who}, which searches when these fail": "先用这些搜索,都失败时再由 {who} 代搜",
|
||||
"Search first with": "优先使用",
|
||||
"MCP server": "MCP 服务器",
|
||||
"Cursor, Claude Desktop and other agents can add this search as an MCP server (Streamable HTTP) with one web_search tool. From another computer, send a gateway key as Authorization: Bearer <key>.": "Cursor、Claude Desktop 等智能体可以把这个搜索添加为 MCP 服务器(Streamable HTTP),提供一个 web_search 工具。从其他电脑访问时,请以 Authorization: Bearer <key> 发送网关密钥。",
|
||||
"The other is asked when it fails": "失败时再用另一种",
|
||||
"Model search": "模型代搜",
|
||||
"No provider can search, so these are asked": "没有能搜索的供应商,由这些 API 来搜",
|
||||
@@ -3293,6 +3295,7 @@ const I18N = {
|
||||
"Suggestions": "提示词建议",
|
||||
"Background prompt suggestions": "后台提示词建议",
|
||||
"magpie ran this web search for {agent}'s {model}, which can't search the web by itself: {searcher} searched, and {model} goes on answering once it has what was found. Not a turn of the conversation.": "magpie 代 {agent} 的 {model} 发起的联网搜索:{model} 无法自行搜索,由 {searcher} 搜索,{model} 拿到结果后继续回答。不属于对话轮次。",
|
||||
"{agent} called magpie's web_search MCP tool: {searcher} searched for it. Not a turn of the conversation.": "{agent} 调用了 magpie 的 web_search MCP 工具:由 {searcher} 代为搜索。不属于对话轮次。",
|
||||
"magpie ran this web search for a model that can't search the web by itself: {searcher} searched, and that model goes on answering once it has what was found. Not a turn of the conversation.": "magpie 代一个无法自行搜索的模型发起的联网搜索:由 {searcher} 搜索,该模型拿到结果后继续回答。不属于对话轮次。",
|
||||
"Image description": "图片描述",
|
||||
"magpie had {describer} describe an image for {agent}'s {model}: nothing magpie knows says {model} can see images, so it is counted as text-only and given the description in the image's place. If it does see them, tick “Accepts images” for it in its provider's models. Settings › Models › Image recognition picks the model that describes. Not a turn of the conversation.": "magpie 让 {describer} 为 {agent} 的 {model} 描述图片:magpie 所知的信息都没有说 {model} 能看图,所以把它当作只收文本,在图片位置给它这段描述。如果它其实能看图,请在它的服务商的模型里勾选“支持图片输入”。描述图片的模型在 设置 › 模型 › 识图模型 里选。不属于对话轮次。",
|
||||
@@ -5063,6 +5066,8 @@ const I18N = {
|
||||
"Now done by {who}; these come after it": "目前由 {who} 代搜,這些排在它之後",
|
||||
"Asked before {who}, which searches when these fail": "先用這些搜尋,都失敗時再由 {who} 代搜",
|
||||
"Search first with": "優先使用",
|
||||
"MCP server": "MCP 伺服器",
|
||||
"Cursor, Claude Desktop and other agents can add this search as an MCP server (Streamable HTTP) with one web_search tool. From another computer, send a gateway key as Authorization: Bearer <key>.": "Cursor、Claude Desktop 等智慧體可以把這個搜尋新增為 MCP 伺服器(Streamable HTTP),提供一個 web_search 工具。從其他電腦存取時,請以 Authorization: Bearer <key> 傳送閘道金鑰。",
|
||||
"The other is asked when it fails": "失敗時再用另一種",
|
||||
"Model search": "模型代搜",
|
||||
"No provider can search, so these are asked": "沒有能搜尋的供應商,由這些 API 來搜",
|
||||
@@ -7381,6 +7386,7 @@ const I18N = {
|
||||
"Suggestions": "提示詞建議",
|
||||
"Background prompt suggestions": "後臺提示詞建議",
|
||||
"magpie ran this web search for {agent}'s {model}, which can't search the web by itself: {searcher} searched, and {model} goes on answering once it has what was found. Not a turn of the conversation.": "magpie 代 {agent} 的 {model} 發起的聯網搜尋:{model} 無法自行搜尋,由 {searcher} 搜尋,{model} 拿到結果後繼續回答。不屬於對話輪次。",
|
||||
"{agent} called magpie's web_search MCP tool: {searcher} searched for it. Not a turn of the conversation.": "{agent} 呼叫了 magpie 的 web_search MCP 工具:由 {searcher} 代為搜尋。不屬於對話輪次。",
|
||||
"magpie ran this web search for a model that can't search the web by itself: {searcher} searched, and that model goes on answering once it has what was found. Not a turn of the conversation.": "magpie 代一個無法自行搜尋的模型發起的聯網搜尋:由 {searcher} 搜尋,該模型拿到結果後繼續回答。不屬於對話輪次。",
|
||||
"Image description": "圖片描述",
|
||||
"magpie had {describer} describe an image for {agent}'s {model}: nothing magpie knows says {model} can see images, so it is counted as text-only and given the description in the image's place. If it does see them, tick “Accepts images” for it in its provider's models. Settings › Models › Image recognition picks the model that describes. Not a turn of the conversation.": "magpie 讓 {describer} 為 {agent} 的 {model} 描述圖片:magpie 所知的資訊都沒有說 {model} 能看圖,所以把它當作只收文字,在圖片位置給它這段描述。如果它其實能看圖,請在它的服務商的模型裡勾選「支援圖片輸入」。描述圖片的模型在 設定 › 模型 › 識圖模型 裡選。不屬於對話輪次。",
|
||||
@@ -9146,6 +9152,8 @@ const I18N = {
|
||||
"Now done by {who}; these come after it": "現在は {who} が検索しています。これらはその後に使われます",
|
||||
"Asked before {who}, which searches when these fail": "まずこれらで検索し、すべて失敗したときに {who} が検索します",
|
||||
"Search first with": "優先して使う検索",
|
||||
"MCP server": "MCP サーバー",
|
||||
"Cursor, Claude Desktop and other agents can add this search as an MCP server (Streamable HTTP) with one web_search tool. From another computer, send a gateway key as Authorization: Bearer <key>.": "Cursor、Claude Desktop などのエージェントは、この検索を web_search ツール 1 つを持つ MCP サーバー(Streamable HTTP)として追加できます。別のコンピューターからは、ゲートウェイキーを Authorization: Bearer <key> として送ってください。",
|
||||
"The other is asked when it fails": "失敗したときはもう一方を使います",
|
||||
"Model search": "モデルによる代理検索",
|
||||
"No provider can search, so these are asked": "検索できるプロバイダがないため、これらを使います",
|
||||
@@ -11486,6 +11494,7 @@ const I18N = {
|
||||
"Suggestions": "提案",
|
||||
"Background prompt suggestions": "バックグラウンドのプロンプト候補",
|
||||
"magpie ran this web search for {agent}'s {model}, which can't search the web by itself: {searcher} searched, and {model} goes on answering once it has what was found. Not a turn of the conversation.": "magpie が、自分でウェブ検索できない {agent} の {model} のためにこのウェブ検索を実行しました。{searcher} が検索し、{model} は結果を受け取ってから応答を続けます。会話のターンではありません。",
|
||||
"{agent} called magpie's web_search MCP tool: {searcher} searched for it. Not a turn of the conversation.": "{agent} が magpie の web_search MCP ツールを呼び出しました。{searcher} が代わりに検索しました。会話のターンではありません。",
|
||||
"magpie ran this web search for a model that can't search the web by itself: {searcher} searched, and that model goes on answering once it has what was found. Not a turn of the conversation.": "magpie が自分でウェブ検索できないモデルのためにこのウェブ検索を実行しました。{searcher} が検索し、そのモデルは結果を受け取ってから応答を続けます。会話のターンではありません。",
|
||||
"Image description": "画像の説明",
|
||||
"magpie had {describer} describe an image for {agent}'s {model}: nothing magpie knows says {model} can see images, so it is counted as text-only and given the description in the image's place. If it does see them, tick “Accepts images” for it in its provider's models. Settings › Models › Image recognition picks the model that describes. Not a turn of the conversation.": "magpie は {agent} の {model} のために {describer} に画像を説明させました。{model} が画像を見られると示す情報を magpie は持っていないため、テキストのみのモデルとして扱い、画像の代わりにその説明を渡しています。実際に画像を見られる場合は、プロバイダーのモデルで「画像入力に対応」をオンにしてください。説明するモデルは 設定 › モデル › 画像認識 で選べます。会話のターンではありません。",
|
||||
@@ -13248,6 +13257,8 @@ const I18N = {
|
||||
"Now done by {who}; these come after it": "Derzeit übernimmt das {who}; diese folgen danach",
|
||||
"Asked before {who}, which searches when these fail": "Werden vor {who} gefragt, das sucht, wenn alle scheitern",
|
||||
"Search first with": "Zuerst suchen mit",
|
||||
"MCP server": "MCP-Server",
|
||||
"Cursor, Claude Desktop and other agents can add this search as an MCP server (Streamable HTTP) with one web_search tool. From another computer, send a gateway key as Authorization: Bearer <key>.": "Cursor, Claude Desktop und andere Agenten können diese Suche als MCP-Server (Streamable HTTP) mit einem web_search-Tool hinzufügen. Von einem anderen Computer aus einen Gateway-Schlüssel als Authorization: Bearer <key> senden.",
|
||||
"The other is asked when it fails": "Scheitert es, wird das andere gefragt",
|
||||
"Model search": "Modellsuche",
|
||||
"No provider can search, so these are asked": "Kein Anbieter kann suchen, daher werden diese gefragt",
|
||||
@@ -15588,6 +15599,7 @@ const I18N = {
|
||||
"Suggestions": "Vorschläge",
|
||||
"Background prompt suggestions": "Prompt-Vorschläge im Hintergrund",
|
||||
"magpie ran this web search for {agent}'s {model}, which can't search the web by itself: {searcher} searched, and {model} goes on answering once it has what was found. Not a turn of the conversation.": "magpie hat diese Websuche für {model} von {agent} ausgeführt, das selbst nicht im Web suchen kann: {searcher} hat gesucht, und {model} antwortet weiter, sobald es die Ergebnisse hat. Keine Runde der Unterhaltung.",
|
||||
"{agent} called magpie's web_search MCP tool: {searcher} searched for it. Not a turn of the conversation.": "{agent} hat das web_search-MCP-Tool von magpie aufgerufen: {searcher} hat dafür gesucht. Keine Runde der Unterhaltung.",
|
||||
"magpie ran this web search for a model that can't search the web by itself: {searcher} searched, and that model goes on answering once it has what was found. Not a turn of the conversation.": "magpie hat diese Websuche für ein Modell ausgeführt, das selbst nicht im Web suchen kann: {searcher} hat gesucht, und dieses Modell antwortet weiter, sobald es die Ergebnisse hat. Keine Runde der Unterhaltung.",
|
||||
"Image description": "Bildbeschreibung",
|
||||
"magpie had {describer} describe an image for {agent}'s {model}: nothing magpie knows says {model} can see images, so it is counted as text-only and given the description in the image's place. If it does see them, tick “Accepts images” for it in its provider's models. Settings › Models › Image recognition picks the model that describes. Not a turn of the conversation.": "magpie ließ {describer} ein Bild für {model} von {agent} beschreiben: Nichts, was magpie weiß, sagt, dass {model} Bilder sehen kann, daher gilt es als reines Textmodell und erhält die Beschreibung anstelle des Bildes. Wenn es doch Bilder sieht, aktiviere „Akzeptiert Bilder“ dafür bei den Modellen seines Anbieters. Unter Einstellungen › Modelle › Bilderkennung wählst du das Modell, das beschreibt. Keine Runde der Unterhaltung.",
|
||||
|
||||
@@ -1809,6 +1809,8 @@
|
||||
: t("{agent} requested a subagent on {model}.", { agent, model: r.model });
|
||||
if (purposeOf(r.kind) === "kind:ambient_suggestions") return t("{agent} drafted the suggested prompts on its home page by itself, in the background, searching the project's files and connected apps, and checked them for safety. Not a turn of the conversation; Codex's Settings › Configuration › Suggested prompts turns it off.", { agent });
|
||||
if (r.kind === "luna_reserve") return t("{agent} sent this turn on Luna Reserve, which it turns to once the plan's own allowance is used up; it picks the model itself.", { agent });
|
||||
// the agent called magpie's web search MCP server itself, for no model
|
||||
if (r.kind === "web_search" && r.for?.mcp) return t("{agent} called magpie's web_search MCP tool: {searcher} searched for it. Not a turn of the conversation.", { agent: agentName(r.for.agent), searcher: r.model });
|
||||
if (r.kind === "web_search") return r.for
|
||||
? t("magpie ran this web search for {agent}'s {model}, which can't search the web by itself: {searcher} searched, and {model} goes on answering once it has what was found. Not a turn of the conversation.", { agent: agentName(r.for.agent), model: r.for.model, searcher: r.model })
|
||||
: t("magpie ran this web search for a model that can't search the web by itself: {searcher} searched, and that model goes on answering once it has what was found. Not a turn of the conversation.", { searcher: r.model });
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// magpie's web search as an MCP server (Kayphoon on Discord): Settings ›
|
||||
// Models › Web search has an "MCP server" row with the gateway's address of
|
||||
// it, /mcp/magpie/web-search, to copy into Cursor, Claude Desktop or any
|
||||
// other agent, and says a gateway key goes with it from another computer.
|
||||
// A search an agent asked of it reads in Routing as that agent's MCP call,
|
||||
// not as a search magpie ran for one of its models. In every language.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const address = "http://127.0.0.1:3999/mcp/magpie/web-search";
|
||||
const words = {
|
||||
en: { name: "MCP server", sub: /Cursor, Claude Desktop .*web_search.*Authorization: Bearer <key>/, story: /Claude Code called magpie's web_search MCP tool: codex\/gpt-6\.1-sol searched for it/ },
|
||||
zh: { name: "MCP 服务器", sub: /Cursor、Claude Desktop .*web_search.*Authorization: Bearer <key>/, story: /Claude Code 调用了 magpie 的 web_search MCP 工具:由 codex\/gpt-6\.1-sol 代为搜索/ },
|
||||
"zh-TW": { name: "MCP 伺服器", sub: /web_search.*Authorization: Bearer <key>/, story: /Claude Code 呼叫了 magpie 的 web_search MCP 工具:由 codex\/gpt-6\.1-sol 代為搜尋/ },
|
||||
ja: { name: "MCP サーバー", sub: /web_search.*Authorization: Bearer <key>/, story: /Claude Code が magpie の web_search MCP ツールを呼び出しました。codex\/gpt-6\.1-sol が代わりに検索しました/ },
|
||||
de: { name: "MCP-Server", sub: /web_search.*Authorization: Bearer <key>/, story: /Claude Code hat das web_search-MCP-Tool von magpie aufgerufen: codex\/gpt-6\.1-sol hat dafür gesucht/ },
|
||||
};
|
||||
|
||||
const now = new Date();
|
||||
const day = [now.getFullYear(), now.getMonth() + 1, now.getDate()].map((n) => String(n).padStart(2, "0")).join("-");
|
||||
const routes = [{
|
||||
id: 7, seq: 7, time: new Date(now.getTime() - 60e3).toISOString(), agent: "magpie", model: "codex/gpt-6.1-sol", provider: "codex",
|
||||
kind: "web_search", for: { agent: "claude-code", mcp: true },
|
||||
order: [{ id: "codex", provider: "codex", name: "Codex", who: "a@b.c", kind: "account", model: "gpt-6.1-sol" }],
|
||||
tries: [{ id: "codex", model: "gpt-6.1-sol", start: new Date(now.getTime() - 60e3).toISOString(), done: true, status: 200, ms: 900 }],
|
||||
done: true, status: 200, ms: 900, tokens: 1200,
|
||||
}];
|
||||
|
||||
function serve(lang) {
|
||||
const settings = { lang, theme: "light", searcher: "", gateway: "http://127.0.0.1:3999", port: 3999,
|
||||
searchVendors: [{ id: "tavily", name: "Tavily", keysURL: "https://app.tavily.com/home" }],
|
||||
searchAPIs: [{ vendor: "tavily", name: "Tavily", key: "tvly…abcd", ready: true }], searchChoices: [] };
|
||||
const state = {
|
||||
agents: [], profiles: [], settings,
|
||||
clients: [{ id: "claude-code", name: "Claude Code", icon: "claude-color" }, { id: "magpie", name: "magpie", icon: "magpie" }],
|
||||
};
|
||||
return async (r) => {
|
||||
const url = new URL(r.request().url());
|
||||
const json = (data) => r.fulfill({ json: data });
|
||||
if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
|
||||
if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json(state);
|
||||
if (url.pathname === "/api/settings") return json(settings);
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname === "/api/gateway/trace") {
|
||||
if (url.searchParams.get("wait")) await new Promise((res) => setTimeout(res, 20e3));
|
||||
return json({ mine: true, now: now.toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] });
|
||||
}
|
||||
if (url.pathname === "/api/gateway/history") {
|
||||
return json({ cut: false, days: [{ day, requests: routes.length }], routes: url.searchParams.get("day") ? routes : [] });
|
||||
}
|
||||
if (url.pathname === "/api/groups") return json({ models: [], groups: [], pools: [] });
|
||||
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } });
|
||||
if (url.pathname.startsWith("/api/")) return json({});
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
|
||||
try { await r.fulfill({ body: await fs.readFile(file), contentType }); } catch { await r.fulfill({ status: 404, body: "" }); }
|
||||
};
|
||||
}
|
||||
|
||||
async function open(t, engine, lang, view, width = 1100) {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const page = await (await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" })).newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", serve(lang));
|
||||
await page.goto("http://magpie.test/?view=" + view);
|
||||
return { page, errors };
|
||||
}
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of Object.keys(words)) {
|
||||
const w = words[lang];
|
||||
test(`${engine} ${lang}: Web search gives its MCP server's address`, async (t) => {
|
||||
for (const width of [1100, 520]) {
|
||||
const { page, errors } = await open(t, engine, lang, "settings&tab=models", width);
|
||||
// Settings is drawn again as its answers come in, each time with a
|
||||
// new row: it is read in one go, never held across a redraw
|
||||
await page.waitForFunction((a) => document.querySelector("#searchList #searchMcpRow code")?.textContent === a, address);
|
||||
const row = await page.evaluate(() => {
|
||||
const r = document.querySelector("#searchList #searchMcpRow");
|
||||
r.scrollIntoView({ block: "nearest" });
|
||||
return { name: r.querySelector(".name").textContent, sub: r.querySelector(".sub").textContent,
|
||||
code: r.querySelector("code").textContent, buttons: r.querySelectorAll("button").length };
|
||||
});
|
||||
assert.equal(row.name, w.name);
|
||||
assert.match(row.sub, w.sub);
|
||||
assert.equal(row.code, address);
|
||||
assert.equal(row.buttons, 1, "a copy button");
|
||||
// nothing spills out of the window at a narrow width
|
||||
assert(await page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth + 1), `no sideways scroll at ${width}px`);
|
||||
assert.deepEqual(errors, []);
|
||||
}
|
||||
});
|
||||
|
||||
test(`${engine} ${lang}: an agent's search through the MCP server reads as its own call`, async (t) => {
|
||||
const { page, errors } = await open(t, engine, lang, "routing");
|
||||
await page.locator(".rt-days .rt-day").nth(1).click();
|
||||
const req = page.locator(".rt-req").first();
|
||||
await req.waitFor();
|
||||
await req.click();
|
||||
const story = page.locator(".rt-steps li.kind");
|
||||
await story.waitFor();
|
||||
assert.match(await story.textContent(), w.story);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user