gateway, gui: magpie's image recognition is an MCP server of its own, /mcp/magpie/vision, with one analyze_image tool (JonahFu on X)
What: beside /mcp/magpie/web-search, the gateway serves the model that describes images (Settings › Models › Image recognition, else magpie's automatic pick) as a Streamable HTTP MCP server. analyze_image takes an image (absolute file path, http(s) URL or data:image URL) and an optional prompt: without one it is described as a model's image is (same cache and system text), with one the prompt is asked beside it. The JSON-RPC serving, guard and Origin check are shared with the web search server (serveMCP). A file path is read only for a local, unproxied caller, up to 20 MB, and only when its bytes are an image; another computer sends a URL or data URL with a gateway key. Each call holds the key's limit (budget.Reserve) and reads in Routing as the agent's analyze_image call. Settings › Models shows the address under Image generation (#visionMcpRow), in every language. Run: - go test -tags nogui ./... (no failures); gofmt -l clean; GOOS=linux and GOOS=windows go vet ./internal/gateway. - New TestVisionMCPAnalyzesImage / WithNoSeer / Guarded / HeldToKeyLimit. Broke the local() guard by hand: TestVisionMCPGuarded went red on the other computer's file path being read. - GUI (chromium + webkit, en/zh/zh-TW/ja/de, 1100 and 520px): vision-mcp, search-mcp, public-url-default, images-missing, settings-sections, i18n-keys, routing-vision-why: 95 pass. The row was first put between the two pickers and images-missing went red (it finds them by position), so it sits last. - Real use: this build under a sandbox HOME holding only the owner's OpenRouter provider, Image recognition set to openai/gpt-6-luna. initialize, then tools/call with docs/screenshots/font-settings.png as a file path and a prompt: the model listed every settings row and its value correctly. Not tried: a real agent (Claude Code, Cursor) mounting it; its MCP exchange is the same as the web search server's.
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}`, `/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. Before any of that, `lanGuard` lets in one request without a key from anywhere: `POST /_magpie/claude-mcp/<token>` with the token of a Claude subscription run now live (`ownCallback`, see [the Claude subscription bridge](claude-subscription-bridge.md)), the run's MCP helper calling back to a `MAGPIE_ADDR` that isn't loopback (#1546). | [`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` and `/mcp/magpie/vision` (magpie's own web search and image recognition as MCP servers, 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. Before any of that, `lanGuard` lets in one request without a key from anywhere: `POST /_magpie/claude-mcp/<token>` with the token of a Claude subscription run now live (`ownCallback`, see [the Claude subscription bridge](claude-subscription-bridge.md)), the run's MCP helper calling back to a `MAGPIE_ADDR` that isn't loopback (#1546). | [`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). So does a member whose provider routes other than Smart (`ownRouting`): weighed as one by its first not resting (`firstAwake`), tried whole in its own order; `leastHeld` leaves such a group's order alone too. A provider on Smart, or routed as the group is, is pooled with the group's other keys and accounts. `group_own_routing_test.go`. 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) |
|
||||
@@ -229,6 +229,32 @@ Covered by `TestSearchMCPServesWebSearch`, `TestSearchMCPWithNoSearcher`,
|
||||
`TestSearchMCPGuarded`, `TestSearchMCPHeldToKeyLimit`,
|
||||
`TestSearchMCPRoutedAsTheAgentsCall` and `search-mcp.test.cjs`.
|
||||
|
||||
## Image recognition as an MCP server
|
||||
|
||||
`VisionMCPPath`, `/mcp/magpie/vision`, serves the model that describes
|
||||
images to a model that can't see them (`seer`: Settings › Models › Image
|
||||
recognition, else `AutoVision`'s) as an MCP server with one `analyze_image`
|
||||
tool (JonahFu on X). `serveMCP` is shared with the web search server, so it
|
||||
is answered, guarded and Origin-checked the same way, with a 32 MB body so
|
||||
an image fits as a data URL, and each call reserves the calling key's limit
|
||||
(`budget.Reserve`). The tool takes `image` and an optional `prompt`. With no
|
||||
prompt it is described as a model's image is (`describe`, the same cache and
|
||||
`visionSystem`); with one, `askVisionWith` asks the prompt beside it under
|
||||
`visionAskSystem`. `image` is an http(s) URL or a `data:image/…;base64,` URL,
|
||||
passed on as they are, or an absolute file path (`~/` and `file://` taken),
|
||||
read into a data URL up to 20 MB when `http.DetectContentType` says it is an
|
||||
image. A path is read only for a `local` caller: another machine's path
|
||||
names nothing here, a shared magpie's files aren't its callers', and a
|
||||
request through a proxy or tunnel isn't `local`. The description's route is
|
||||
marked `CallFor{Agent, MCP: true}`, so Routing says the agent called
|
||||
analyze_image. Image recognition off or no model that sees is a tool error
|
||||
that says where to pick one. Settings › Models shows the address
|
||||
(`#visionMcpRow`, below Image generation).
|
||||
|
||||
Covered by `TestVisionMCPAnalyzesImage`, `TestVisionMCPWithNoSeer`,
|
||||
`TestVisionMCPGuarded`, `TestVisionMCPHeldToKeyLimit` and
|
||||
`vision-mcp.test.cjs`.
|
||||
|
||||
## Verification
|
||||
|
||||
```sh
|
||||
@@ -236,7 +262,7 @@ go test -tags nogui ./internal/gateway -run 'TestLoop|TestLongReplyThatDoesNotLo
|
||||
go test -tags nogui ./internal/gateway -run 'TestVertex'
|
||||
go test -tags nogui ./internal/gateway ./internal/usage -run 'TestRetriedRequestCountsOnce|TestRequestsCountedOnceWithTheirRetries'
|
||||
go test -tags nogui ./internal/gateway -run 'TestRemoteMagpie|TestRedactedKinds|TestKeyLimitTellsOnlyTheCaller'
|
||||
go test -tags nogui ./internal/gateway -run 'TestSearchMCP'
|
||||
go test -tags nogui ./internal/gateway -run 'TestSearchMCP|TestVisionMCP'
|
||||
go test -tags nogui ./internal/gateway ./internal/gui . -run 'TestSearchAPIAtItsOwnBaseURL|TestSearchKeyStaysAtItsBaseURL|TestSearchAPIBaseURLFromSettings|TestSearchCLI'
|
||||
go test -tags nogui ./internal/redact ./internal/gui -run 'TestMoreKinds|TestCategoryDefaults|TestRedactKindsAreRedacts|TestRedactRuleEdit'
|
||||
go test -tags nogui ./internal/gateway -run 'TestCodexModelList|TestCodexModelsEtag'
|
||||
|
||||
@@ -569,6 +569,7 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.HandleFunc("POST "+claudeMCPPath+"{token}", s.subscription.mcpCall)
|
||||
mux.HandleFunc("/mcp/{name}", s.mcpProxy)
|
||||
mux.HandleFunc(SearchMCPPath, s.searchMCP)
|
||||
mux.HandleFunc(VisionMCPPath, s.visionMCP)
|
||||
mux.HandleFunc(CodexPath+"/", s.codexBackend)
|
||||
mux.HandleFunc("GET "+CodexCatalogPath, s.codexCatalog)
|
||||
mux.HandleFunc("GET /v1beta/models", s.geminiModels)
|
||||
@@ -596,7 +597,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", SearchMCPPath}})
|
||||
"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, VisionMCPPath}})
|
||||
}
|
||||
|
||||
// quotas is what is left of every subscription, plan and key magpie has,
|
||||
|
||||
@@ -66,8 +66,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, on a web search or an image's description, is that the agent
|
||||
// called magpie's MCP server (SearchMCPPath, VisionMCPPath) itself, for
|
||||
// no model of magpie's.
|
||||
MCP bool `json:"mcp,omitempty"`
|
||||
}
|
||||
|
||||
|
||||
@@ -44,15 +44,22 @@ type mcpMessage struct {
|
||||
}
|
||||
|
||||
func (s *Server) searchMCP(w http.ResponseWriter, r *http.Request) {
|
||||
serveMCP(w, r, "magpie's web search", 1<<20, s.searchMCPCall)
|
||||
}
|
||||
|
||||
// serveMCP answers the JSON-RPC messages POSTed to one of magpie's own MCP
|
||||
// servers (what names it in a refusal) with call, a body up to limit bytes
|
||||
// long: guarded as a gateway route, and a web page turned away.
|
||||
func serveMCP(w http.ResponseWriter, r *http.Request, what string, limit int64, call func(*http.Request, mcpMessage) (any, map[string]any)) {
|
||||
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)
|
||||
http.Error(w, what+" 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)
|
||||
http.Error(w, what+" MCP server answers agents, not web pages", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
if r.Method != http.MethodPost {
|
||||
@@ -61,7 +68,7 @@ func (s *Server) searchMCP(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "POST JSON-RPC messages here (MCP Streamable HTTP)", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
|
||||
body, err := io.ReadAll(io.LimitReader(r.Body, limit))
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
@@ -87,7 +94,7 @@ func (s *Server) searchMCP(w http.ResponseWriter, r *http.Request) {
|
||||
if len(m.ID) == 0 || bytes.Equal(m.ID, []byte("null")) || m.Method == "" {
|
||||
continue
|
||||
}
|
||||
result, rpcErr := s.searchMCPCall(r, m)
|
||||
result, rpcErr := call(r, m)
|
||||
reply := map[string]any{"jsonrpc": "2.0", "id": m.ID}
|
||||
if rpcErr != nil {
|
||||
reply["error"] = rpcErr
|
||||
@@ -111,16 +118,8 @@ func (s *Server) searchMCP(w http.ResponseWriter, r *http.Request) {
|
||||
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,
|
||||
"protocolVersion": mcpVersion(m),
|
||||
"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).",
|
||||
@@ -158,6 +157,19 @@ func (s *Server) searchMCPCall(r *http.Request, m mcpMessage) (any, map[string]a
|
||||
return nil, map[string]any{"code": -32601, "message": "method not found: " + m.Method}
|
||||
}
|
||||
|
||||
// mcpVersion is the MCP version an initialize is answered in: the one it
|
||||
// asks for when the server speaks it, else the newest.
|
||||
func mcpVersion(m mcpMessage) string {
|
||||
var p struct {
|
||||
ProtocolVersion string `json:"protocolVersion"`
|
||||
}
|
||||
json.Unmarshal(m.Params, &p)
|
||||
if slices.Contains(searchMCPVersions, p.ProtocolVersion) {
|
||||
return p.ProtocolVersion
|
||||
}
|
||||
return searchMCPVersions[0]
|
||||
}
|
||||
|
||||
func toolResult(text string, isError bool) map[string]any {
|
||||
return map[string]any{"content": []any{map[string]any{"type": "text", "text": text}}, "isError": isError}
|
||||
}
|
||||
|
||||
@@ -255,15 +255,21 @@ func (s *Server) describe(ctx context.Context, model, src string) (string, error
|
||||
// askVision asks model through the gateway itself, as a client would, what
|
||||
// the image at src shows.
|
||||
func (s *Server) askVision(ctx context.Context, model, src string) (string, error) {
|
||||
return s.askVisionWith(ctx, model, src, visionSystem, "Describe this image.")
|
||||
}
|
||||
|
||||
// askVisionWith asks model about the image at src: system, and the user's
|
||||
// text beside the image.
|
||||
func (s *Server) askVisionWith(ctx context.Context, model, src, system, text string) (string, error) {
|
||||
ctx, cancel := context.WithTimeout(context.WithValue(ctx, describingKey{}, true), visionTimeout)
|
||||
defer cancel()
|
||||
req := map[string]any{
|
||||
"model": model,
|
||||
"stream": false,
|
||||
"messages": []map[string]any{
|
||||
{"role": "system", "content": visionSystem},
|
||||
{"role": "system", "content": system},
|
||||
{"role": "user", "content": []map[string]any{
|
||||
{"type": "text", "text": "Describe this image."},
|
||||
{"type": "text", "text": text},
|
||||
{"type": "image_url", "image_url": map[string]string{"url": src}},
|
||||
}},
|
||||
},
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/budget"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// magpie's image recognition, the model that describes images to a model
|
||||
// that can't see them (seer: Settings › Models › Image recognition, else
|
||||
// AutoVision's), is also an MCP server of its own beside the web search's
|
||||
// (JonahFu on X), so an agent on a model that can't see, or any agent at
|
||||
// all, can mount it as an analyze_image tool: Streamable HTTP at
|
||||
// VisionMCPPath, served and guarded as SearchMCPPath is (serveMCP), a
|
||||
// gateway key's limit holding each look (budget.Reserve).
|
||||
|
||||
// VisionMCPPath is where the image recognition MCP server is served.
|
||||
const VisionMCPPath = "/mcp/magpie/vision"
|
||||
|
||||
const visionMCPTool = "analyze_image"
|
||||
|
||||
// visionMCPBody is how long a message to the server may be: an image is
|
||||
// sent in it as a data URL.
|
||||
const visionMCPBody = 32 << 20
|
||||
|
||||
// visionFileMax is the largest image file the tool reads from a path.
|
||||
const visionFileMax = 20 << 20
|
||||
|
||||
// visionAskSystem is what the model is told when the agent asks something
|
||||
// of the image, in place of visionSystem's full description.
|
||||
const visionAskSystem = `You look at an image for an AI agent that cannot see it, and answer what it asks about the image from what the image shows.
|
||||
- Transcribe text exactly as written wherever the answer needs it: code, terminal output, error messages, UI labels, numbers.
|
||||
- Say so when what is asked can't be read or isn't in the image; don't guess.
|
||||
No preamble.`
|
||||
|
||||
var visionMCPSchema = map[string]any{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"image": map[string]any{
|
||||
"type": "string",
|
||||
"description": "The image: an absolute path to an image file on this computer (PNG, JPEG, GIF or WebP), an http(s) URL, or a data URL (data:image/png;base64,...).",
|
||||
},
|
||||
"prompt": map[string]any{
|
||||
"type": "string",
|
||||
"description": "What to find out about the image. Without it the image is described in full: its text transcribed, its layout, charts and diagrams.",
|
||||
},
|
||||
},
|
||||
"required": []string{"image"},
|
||||
}
|
||||
|
||||
func (s *Server) visionMCP(w http.ResponseWriter, r *http.Request) {
|
||||
serveMCP(w, r, "magpie's image recognition", visionMCPBody, s.visionMCPCall)
|
||||
}
|
||||
|
||||
// visionMCPCall answers one request: its result, or its JSON-RPC error.
|
||||
func (s *Server) visionMCPCall(r *http.Request, m mcpMessage) (any, map[string]any) {
|
||||
switch m.Method {
|
||||
case "initialize":
|
||||
return map[string]any{
|
||||
"protocolVersion": mcpVersion(m),
|
||||
"capabilities": map[string]any{"tools": map[string]any{}},
|
||||
"serverInfo": map[string]any{"name": "magpie-vision", "title": "Magpie Image Recognition", "version": Version},
|
||||
"instructions": "analyze_image looks at an image with the model magpie describes images with (Settings → Models → Image recognition) and answers in text: for a model or agent that can't see images, or to read a screenshot, chart or diagram.",
|
||||
}, nil
|
||||
case "ping":
|
||||
return map[string]any{}, nil
|
||||
case "tools/list":
|
||||
return map[string]any{"tools": []any{map[string]any{
|
||||
"name": visionMCPTool,
|
||||
"title": "Analyze image",
|
||||
"description": "Looks at an image and answers in text: what the prompt asks of it, or, with no prompt, a full description with all its text transcribed. Use it to read screenshots, error dialogs, charts, diagrams and photos when you can't see images yourself.",
|
||||
"inputSchema": visionMCPSchema,
|
||||
"annotations": map[string]any{"readOnlyHint": true, "openWorldHint": false},
|
||||
}}}, nil
|
||||
case "tools/call":
|
||||
var p struct {
|
||||
Name string `json:"name"`
|
||||
Arguments struct {
|
||||
Image string `json:"image"`
|
||||
Prompt string `json:"prompt"`
|
||||
} `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 != visionMCPTool {
|
||||
return nil, map[string]any{"code": -32602, "message": "unknown tool " + p.Name + ": this server has " + visionMCPTool}
|
||||
}
|
||||
said, err := s.visionMCPRun(r, strings.TrimSpace(p.Arguments.Image), strings.TrimSpace(p.Arguments.Prompt))
|
||||
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}
|
||||
}
|
||||
|
||||
// visionMCPRun has the image looked at as an image of a model's request
|
||||
// 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) visionMCPRun(r *http.Request, image, prompt string) (string, error) {
|
||||
if image == "" {
|
||||
return "", searchMCPError("analyze_image needs an image: a file path, an http(s) URL or a data URL")
|
||||
}
|
||||
src, err := visionSrc(r, image)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
model, ok := seer()
|
||||
if !ok {
|
||||
if provider.HeldSettings().Vision == "off" {
|
||||
return "", searchMCPError("Image recognition is off in magpie: pick a model for it in Settings → Models → Image recognition")
|
||||
}
|
||||
return "", searchMCPError("magpie has no model that sees images: add a provider with one, or pick one in Settings → Models → Image recognition")
|
||||
}
|
||||
release, refused := budget.Reserve(access.Caller(r.Context()), int64(len(src)+len(prompt)), "", limitClock())
|
||||
if refused != nil {
|
||||
return "", refused
|
||||
}
|
||||
defer release()
|
||||
ctx := context.WithValue(r.Context(), describeForKey{}, describeFor{call: &CallFor{Agent: callerOf(r).agent, Missing: VisionMissing(), MCP: true}})
|
||||
var said string
|
||||
if prompt == "" {
|
||||
said, err = s.describe(ctx, model, src)
|
||||
} else {
|
||||
said, err = s.askVisionWith(ctx, model, src, visionAskSystem, prompt)
|
||||
}
|
||||
if err != nil {
|
||||
if r.Context().Err() == nil {
|
||||
log.Printf("vision MCP: %v", err)
|
||||
}
|
||||
return "", searchMCPError(fmt.Sprintf("magpie couldn't look at the image with %s: %v%s", model, err, missingSeerNote()))
|
||||
}
|
||||
return said, nil
|
||||
}
|
||||
|
||||
// visionSrc is the image as the describer is sent it: a URL or data URL as
|
||||
// it is, a file read into a data URL. A file is read only for an agent on
|
||||
// this computer: another machine's path names none of its own here, and a
|
||||
// shared magpie's files aren't its callers'.
|
||||
func visionSrc(r *http.Request, image string) (string, error) {
|
||||
low := strings.ToLower(image)
|
||||
switch {
|
||||
case strings.HasPrefix(low, "data:"):
|
||||
if !strings.HasPrefix(low, "data:image/") || !strings.Contains(low[:min(len(low), 64)], ";base64,") {
|
||||
return "", searchMCPError("analyze_image takes a data URL of an image in base64 (data:image/png;base64,...)")
|
||||
}
|
||||
return image, nil
|
||||
case strings.HasPrefix(low, "http://"), strings.HasPrefix(low, "https://"):
|
||||
return image, nil
|
||||
}
|
||||
path := image
|
||||
if strings.HasPrefix(low, "file://") {
|
||||
path = image[len("file://"):]
|
||||
}
|
||||
if strings.HasPrefix(path, "~/") {
|
||||
if home, err := os.UserHomeDir(); err == nil {
|
||||
path = filepath.Join(home, path[2:])
|
||||
}
|
||||
}
|
||||
if !filepath.IsAbs(path) {
|
||||
return "", searchMCPError("analyze_image takes an absolute file path (the gateway doesn't know your agent's working folder), an http(s) URL or a data URL: " + image + " is none of them")
|
||||
}
|
||||
if !local(r) {
|
||||
return "", searchMCPError("analyze_image reads a file only for an agent on the computer magpie runs on: from another computer, send the image as a data URL (data:image/png;base64,...) or an http(s) URL")
|
||||
}
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return "", searchMCPError("analyze_image couldn't read " + path + ": " + err.Error())
|
||||
}
|
||||
defer f.Close()
|
||||
if st, err := f.Stat(); err == nil && st.IsDir() {
|
||||
return "", searchMCPError(path + " is a folder, not an image")
|
||||
} else if err == nil && st.Size() > visionFileMax {
|
||||
return "", searchMCPError(fmt.Sprintf("%s is %d MB: analyze_image reads images up to %d MB", path, st.Size()>>20, visionFileMax>>20))
|
||||
}
|
||||
b, err := io.ReadAll(io.LimitReader(f, visionFileMax+1))
|
||||
if err != nil {
|
||||
return "", searchMCPError("analyze_image couldn't read " + path + ": " + err.Error())
|
||||
}
|
||||
if len(b) > visionFileMax {
|
||||
return "", searchMCPError(fmt.Sprintf("%s is over %d MB: analyze_image reads images up to %d MB", path, visionFileMax>>20, visionFileMax>>20))
|
||||
}
|
||||
mime := http.DetectContentType(b)
|
||||
if !strings.HasPrefix(mime, "image/") {
|
||||
return "", searchMCPError(path + " isn't an image analyze_image can read (PNG, JPEG, GIF or WebP): it reads as " + mime)
|
||||
}
|
||||
return "data:" + mime + ";base64," + base64.StdEncoding.EncodeToString(b), nil
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/budget"
|
||||
)
|
||||
|
||||
// visionPost sends one JSON-RPC body to the image recognition MCP server
|
||||
// through h, from addr, with hdr as name, value pairs.
|
||||
func visionPost(h http.Handler, addr, body string, hdr ...string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(http.MethodPost, VisionMCPPath, 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
|
||||
}
|
||||
|
||||
// analyzeCall is a tools/call of analyze_image with image and, when it
|
||||
// isn't "", prompt.
|
||||
func analyzeCall(image, prompt string) string {
|
||||
args := map[string]string{"image": image}
|
||||
if prompt != "" {
|
||||
args["prompt"] = prompt
|
||||
}
|
||||
b, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": map[string]any{"name": "analyze_image", "arguments": args}})
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// pngFile is a file whose bytes read as a PNG, in a test's folder.
|
||||
func pngFile(t *testing.T) (string, string) {
|
||||
t.Helper()
|
||||
b := append([]byte("\x89PNG\r\n\x1a\n"), "pixels"...)
|
||||
p := filepath.Join(t.TempDir(), "shot.png")
|
||||
if err := os.WriteFile(p, b, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return p, base64.StdEncoding.EncodeToString(b)
|
||||
}
|
||||
|
||||
// magpie's image recognition is an MCP server of its own beside the web
|
||||
// search's (JonahFu on X): an agent lists one analyze_image tool and calls
|
||||
// it with a file on this computer, and the model that describes images
|
||||
// answers — with a full description, or what the prompt asks.
|
||||
func TestVisionMCPAnalyzesImage(t *testing.T) {
|
||||
s, u := eyed(t)
|
||||
h := lanGuard(s.Handler())
|
||||
const here = "127.0.0.1:50000"
|
||||
|
||||
init := readMCP(t, visionPost(h, here, `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"claude-code","version":"2"}}}`))
|
||||
if init.Error != nil || init.Result.ProtocolVersion != "2025-06-18" || init.Result.ServerInfo.Name != "magpie-vision" {
|
||||
t.Fatalf("initialize: %+v", init)
|
||||
}
|
||||
list := readMCP(t, visionPost(h, here, `{"jsonrpc":"2.0","id":2,"method":"tools/list"}`))
|
||||
if len(list.Result.Tools) != 1 || list.Result.Tools[0].Name != "analyze_image" || !slices.Equal(list.Result.Tools[0].InputSchema.Required, []string{"image"}) {
|
||||
t.Fatalf("tools/list: %+v", list)
|
||||
}
|
||||
|
||||
file, b64 := pngFile(t)
|
||||
m := readMCP(t, visionPost(h, here, analyzeCall(file, ""), "User-Agent", "claude-code/2.1.0"))
|
||||
if m.Result.IsError || len(m.Result.Content) != 1 || m.Result.Content[0].Text != "A red square with the word HELLO in it." {
|
||||
t.Fatalf("a file: %+v", m)
|
||||
}
|
||||
sent := u.sent("eye")
|
||||
if len(sent) != 1 || !strings.Contains(sent[0], "data:image/png;base64,"+b64) || !strings.Contains(sent[0], "Describe this image.") {
|
||||
t.Fatalf("the describer was sent %q", sent)
|
||||
}
|
||||
// asked something of it: the prompt goes with the image
|
||||
if m := readMCP(t, visionPost(h, here, analyzeCall("data:image/png;base64,aGVsbG8=", "What does the dialog say?"))); m.Result.IsError {
|
||||
t.Fatalf("a data URL with a prompt: %+v", m)
|
||||
}
|
||||
sent = u.sent("eye")
|
||||
if len(sent) != 2 || !strings.Contains(sent[1], "What does the dialog say?") || !strings.Contains(sent[1], "aGVsbG8=") || !strings.Contains(sent[1], "answer what it asks") {
|
||||
t.Fatalf("asked %q", sent[1:])
|
||||
}
|
||||
var routed *Route
|
||||
for _, r := range s.Trace(context.Background(), 0, 0).Routes {
|
||||
if r.Kind == "vision" && r.For != nil && r.For.Agent == "claude-code" {
|
||||
routed = &r
|
||||
}
|
||||
}
|
||||
if routed == nil || !routed.For.MCP {
|
||||
t.Fatalf("route %+v", routed)
|
||||
}
|
||||
|
||||
// what isn't an image it can read is the tool's error, the describer
|
||||
// asked nothing
|
||||
notImage := filepath.Join(t.TempDir(), "notes.txt")
|
||||
os.WriteFile(notImage, []byte("hello"), 0o644)
|
||||
for _, bad := range []string{"", "shot.png", notImage, filepath.Dir(notImage), filepath.Join(t.TempDir(), "gone.png"), "data:text/plain;base64,aGk="} {
|
||||
if m := readMCP(t, visionPost(h, here, analyzeCall(bad, ""))); !m.Result.IsError {
|
||||
t.Fatalf("%q: %+v", bad, m)
|
||||
}
|
||||
}
|
||||
if n := len(u.sent("eye")); n != 2 {
|
||||
t.Fatalf("the describer was asked %d times", n)
|
||||
}
|
||||
if m := readMCP(t, visionPost(h, here, analyzeCall(filepath.Join(t.TempDir(), "x"), ""))); !strings.Contains(m.Result.Content[0].Text, "couldn't read") {
|
||||
t.Fatalf("a missing file: %+v", m)
|
||||
}
|
||||
}
|
||||
|
||||
// Image recognition off, or no model that sees: the tool's error says
|
||||
// where to pick one.
|
||||
func TestVisionMCPWithNoSeer(t *testing.T) {
|
||||
_, _ = eyed(t)
|
||||
noVision(t)
|
||||
m := readMCP(t, visionPost(lanGuard(New().Handler()), "127.0.0.1:50000", analyzeCall("data:image/png;base64,aGVsbG8=", "")))
|
||||
if !m.Result.IsError || !strings.Contains(m.Result.Content[0].Text, "Settings → Models → Image recognition") {
|
||||
t.Fatalf("%+v", m)
|
||||
}
|
||||
fresh(t)
|
||||
m = readMCP(t, visionPost(lanGuard(New().Handler()), "127.0.0.1:50000", analyzeCall("data:image/png;base64,aGVsbG8=", "")))
|
||||
if !m.Result.IsError || !strings.Contains(m.Result.Content[0].Text, "no model that sees images") {
|
||||
t.Fatalf("%+v", m)
|
||||
}
|
||||
}
|
||||
|
||||
// The server is a gateway route like the others: another computer reaches
|
||||
// it only while magpie is shared and with a gateway key, a web page is
|
||||
// turned away, and a file path is read only for an agent on this computer —
|
||||
// a shared magpie's files aren't its callers'.
|
||||
func TestVisionMCPGuarded(t *testing.T) {
|
||||
s, u := eyed(t)
|
||||
t.Setenv("MAGPIE_ADDR", "")
|
||||
t.Setenv("MAGPIE_PUBLIC_URL", "")
|
||||
h := lanGuard(s.Handler())
|
||||
file, _ := pngFile(t)
|
||||
const there = "192.0.2.7:4000"
|
||||
if w := visionPost(h, there, analyzeCall(file, "")); w.Code != http.StatusForbidden {
|
||||
t.Fatalf("not shared: %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
_, secrets := newCaller(t, "Laptop")
|
||||
if w := visionPost(h, there, analyzeCall(file, "")); w.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("shared, no key: %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
if w := visionPost(h, "127.0.0.1:50000", analyzeCall(file, ""), "Origin", "http://localhost:5173"); w.Code != http.StatusForbidden {
|
||||
t.Fatalf("a page on this computer: %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
m := readMCP(t, visionPost(h, there, analyzeCall(file, ""), "Authorization", "Bearer "+secrets[0]))
|
||||
if !m.Result.IsError || !strings.Contains(m.Result.Content[0].Text, "only for an agent on the computer magpie runs on") {
|
||||
t.Fatalf("another computer's file path: %+v", m)
|
||||
}
|
||||
// through a tunnel to this computer, too
|
||||
if m := readMCP(t, visionPost(h, "127.0.0.1:50000", analyzeCall(file, ""), "Authorization", "Bearer "+secrets[0], "X-Forwarded-For", "203.0.113.9")); !m.Result.IsError {
|
||||
t.Fatalf("a proxied file path: %+v", m)
|
||||
}
|
||||
if n := len(u.sent("eye")); n != 0 {
|
||||
t.Fatalf("the describer was asked %d times", n)
|
||||
}
|
||||
m = readMCP(t, visionPost(h, there, analyzeCall("data:image/png;base64,aGVsbG8=", ""), "Authorization", "Bearer "+secrets[0]))
|
||||
if m.Result.IsError || !strings.Contains(m.Result.Content[0].Text, "HELLO") {
|
||||
t.Fatalf("shared, a data URL with its key: %+v", m)
|
||||
}
|
||||
}
|
||||
|
||||
// A gateway key past its limit looks at no more images through the server.
|
||||
func TestVisionMCPHeldToKeyLimit(t *testing.T) {
|
||||
s, u := eyed(t)
|
||||
budget.Forget()
|
||||
pinLimitClock(t)
|
||||
calls := limitedUpstream(t, 0)
|
||||
keys, secrets := newCaller(t, "Capped")
|
||||
setLimit(t, keys[0].ID, &access.Limit{Period: "day", Tokens: 700})
|
||||
h := lanGuard(s.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())
|
||||
}
|
||||
m := readMCP(t, visionPost(h, "127.0.0.1:5000", analyzeCall("data:image/png;base64,aGVsbG8=", ""), "Authorization", "Bearer "+secrets[0]))
|
||||
if !m.Result.IsError || !strings.Contains(m.Result.Content[0].Text, `"Capped"`) {
|
||||
t.Fatalf("a spent key: %+v", m)
|
||||
}
|
||||
if n := len(u.sent("eye")); n != 0 {
|
||||
t.Fatalf("a spent key's image was looked at %d times", n)
|
||||
}
|
||||
// without a key, from this computer, it looks
|
||||
if m := readMCP(t, visionPost(h, "127.0.0.1:5000", analyzeCall("data:image/png;base64,aGVsbG8=", ""))); m.Result.IsError {
|
||||
t.Fatalf("keyless: %+v", m)
|
||||
}
|
||||
}
|
||||
@@ -21251,6 +21251,17 @@ function renderImages(s, keep) {
|
||||
r.append(who, val);
|
||||
box.append(r);
|
||||
renderImageGen(s, keep, box);
|
||||
// the same image recognition as an MCP server of the gateway's (JonahFu
|
||||
// on X), for an agent to mount as its analyze_image tool
|
||||
const mcpURL = mcpAddress(s, "/mcp/magpie/vision");
|
||||
const mcp = el("div", "row pref");
|
||||
const mwho = el("div", "who");
|
||||
mwho.append(el("div", "name", t("Image recognition MCP server")), el("div", "sub", t("Agents can add image recognition as an MCP server (Streamable HTTP) with one analyze_image tool, which reads an image with the Image recognition model from a file path, a URL or a data URL. From another computer, send a gateway key as Authorization: Bearer <key> and the image as a URL or data URL.")));
|
||||
const mval = el("div", "val");
|
||||
mval.append(el("code", "", mcpURL), copyBtn(mcpURL, t("Address")));
|
||||
mcp.append(mwho, mval);
|
||||
mcp.id = "visionMcpRow";
|
||||
box.append(mcp);
|
||||
}
|
||||
|
||||
// renderImageGen: the model magpie's generate_image tool draws with — the
|
||||
@@ -21296,6 +21307,12 @@ function renderImageGen(s, keep, box) {
|
||||
box.append(r);
|
||||
}
|
||||
|
||||
// mcpAddress: where one of the gateway's own MCP servers is, at path. A
|
||||
// page other machines open (magpie web) shows MAGPIE_PUBLIC_URL's (#1551).
|
||||
function mcpAddress(s, path) {
|
||||
return ((web && s.publicURL) || s.gateway || providers?.gateway?.url || `http://127.0.0.1:${s.port || 3425}`).replace(/\/+$/, "") + path;
|
||||
}
|
||||
|
||||
// renderSearch: the web search APIs a model's search goes to when no
|
||||
// provider can search (#419) — one row each, in the order they are tried,
|
||||
// and a row to add one: which API, its key, and the address of one the user
|
||||
@@ -21423,8 +21440,7 @@ function renderSearch(s, keep) {
|
||||
}
|
||||
// the same search as an MCP server of the gateway's (Kayphoon on
|
||||
// Discord), for an agent to mount as its web_search tool
|
||||
// a page other machines open (magpie web) shows MAGPIE_PUBLIC_URL's (#1551)
|
||||
const mcpURL = ((web && s.publicURL) || s.gateway || providers?.gateway?.url || `http://127.0.0.1:${s.port || 3425}`).replace(/\/+$/, "") + "/mcp/magpie/web-search";
|
||||
const mcpURL = mcpAddress(s, "/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";
|
||||
|
||||
@@ -976,6 +976,8 @@ const I18N = {
|
||||
"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> 发送网关密钥。",
|
||||
"Image recognition MCP server": "识图 MCP 服务器",
|
||||
"Agents can add image recognition as an MCP server (Streamable HTTP) with one analyze_image tool, which reads an image with the Image recognition model from a file path, a URL or a data URL. From another computer, send a gateway key as Authorization: Bearer <key> and the image as a URL or data URL.": "智能体可以把识图添加为 MCP 服务器(Streamable HTTP),提供一个 analyze_image 工具:用识图模型读取文件路径、URL 或 data URL 中的图片。从其他电脑访问时,请以 Authorization: Bearer <key> 发送网关密钥,图片以 URL 或 data URL 传入。",
|
||||
"The other is asked when it fails": "失败时再用另一种",
|
||||
"Model search": "模型代搜",
|
||||
"No provider can search, so these are asked": "没有能搜索的供应商,由这些 API 来搜",
|
||||
@@ -3430,6 +3432,7 @@ const I18N = {
|
||||
"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} 代为搜索。不属于对话轮次。",
|
||||
"{agent} called magpie's analyze_image MCP tool: {describer} looked at the image for it. Not a turn of the conversation.": "{agent} 调用了 magpie 的 analyze_image MCP 工具:由 {describer} 代为查看图片。不属于对话轮次。",
|
||||
"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} 能看图,所以把它当作只收文本,在图片位置给它这段描述。如果它其实能看图,请在它的服务商的模型里勾选“支持图片输入”。描述图片的模型在 设置 › 模型 › 识图模型 里选。不属于对话轮次。",
|
||||
@@ -5324,6 +5327,8 @@ const I18N = {
|
||||
"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> 傳送閘道金鑰。",
|
||||
"Image recognition MCP server": "識圖 MCP 伺服器",
|
||||
"Agents can add image recognition as an MCP server (Streamable HTTP) with one analyze_image tool, which reads an image with the Image recognition model from a file path, a URL or a data URL. From another computer, send a gateway key as Authorization: Bearer <key> and the image as a URL or data URL.": "智慧體可以把識圖新增為 MCP 伺服器(Streamable HTTP),提供一個 analyze_image 工具:用識圖模型讀取檔案路徑、URL 或 data URL 中的圖片。從其他電腦存取時,請以 Authorization: Bearer <key> 傳送閘道金鑰,圖片以 URL 或 data URL 傳入。",
|
||||
"The other is asked when it fails": "失敗時再用另一種",
|
||||
"Model search": "模型代搜",
|
||||
"No provider can search, so these are asked": "沒有能搜尋的供應商,由這些 API 來搜",
|
||||
@@ -7753,6 +7758,7 @@ const I18N = {
|
||||
"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} 代為搜尋。不屬於對話輪次。",
|
||||
"{agent} called magpie's analyze_image MCP tool: {describer} looked at the image for it. Not a turn of the conversation.": "{agent} 呼叫了 magpie 的 analyze_image MCP 工具:由 {describer} 代為查看圖片。不屬於對話輪次。",
|
||||
"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} 能看圖,所以把它當作只收文字,在圖片位置給它這段描述。如果它其實能看圖,請在它的服務商的模型裡勾選「支援圖片輸入」。描述圖片的模型在 設定 › 模型 › 識圖模型 裡選。不屬於對話輪次。",
|
||||
@@ -9642,6 +9648,8 @@ const I18N = {
|
||||
"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> として送ってください。",
|
||||
"Image recognition MCP server": "画像認識 MCP サーバー",
|
||||
"Agents can add image recognition as an MCP server (Streamable HTTP) with one analyze_image tool, which reads an image with the Image recognition model from a file path, a URL or a data URL. From another computer, send a gateway key as Authorization: Bearer <key> and the image as a URL or data URL.": "エージェントは、画像認識を analyze_image ツール 1 つを持つ MCP サーバー(Streamable HTTP)として追加できます。画像認識のモデルで、ファイルパス、URL、data URL の画像を読み取ります。別のコンピューターからは、ゲートウェイキーを Authorization: Bearer <key> として送り、画像は URL か data URL で渡してください。",
|
||||
"The other is asked when it fails": "失敗したときはもう一方を使います",
|
||||
"Model search": "モデルによる代理検索",
|
||||
"No provider can search, so these are asked": "検索できるプロバイダがないため、これらを使います",
|
||||
@@ -12093,6 +12101,7 @@ const I18N = {
|
||||
"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} が代わりに検索しました。会話のターンではありません。",
|
||||
"{agent} called magpie's analyze_image MCP tool: {describer} looked at the image for it. Not a turn of the conversation.": "{agent} が magpie の analyze_image MCP ツールを呼び出しました。{describer} が代わりに画像を見ました。会話のターンではありません。",
|
||||
"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 は持っていないため、テキストのみのモデルとして扱い、画像の代わりにその説明を渡しています。実際に画像を見られる場合は、プロバイダーのモデルで「画像入力に対応」をオンにしてください。説明するモデルは 設定 › モデル › 画像認識 で選べます。会話のターンではありません。",
|
||||
@@ -13979,6 +13988,8 @@ const I18N = {
|
||||
"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.",
|
||||
"Image recognition MCP server": "Bilderkennung als MCP-Server",
|
||||
"Agents can add image recognition as an MCP server (Streamable HTTP) with one analyze_image tool, which reads an image with the Image recognition model from a file path, a URL or a data URL. From another computer, send a gateway key as Authorization: Bearer <key> and the image as a URL or data URL.": "Agenten können die Bilderkennung als MCP-Server (Streamable HTTP) mit einem analyze_image-Tool hinzufügen, das ein Bild aus einem Dateipfad, einer URL oder einer Data-URL mit dem Modell der Bilderkennung liest. Von einem anderen Computer aus einen Gateway-Schlüssel als Authorization: Bearer <key> senden und das Bild als URL oder Data-URL übergeben.",
|
||||
"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",
|
||||
@@ -16430,6 +16441,7 @@ const I18N = {
|
||||
"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.",
|
||||
"{agent} called magpie's analyze_image MCP tool: {describer} looked at the image for it. Not a turn of the conversation.": "{agent} hat das analyze_image-MCP-Tool von magpie aufgerufen: {describer} hat sich das Bild dafür angesehen. 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.",
|
||||
|
||||
@@ -1825,6 +1825,8 @@
|
||||
// went to Codex's GPT, and nothing said why or where to change it)
|
||||
// the Image recognition model the user picked is missing: the one
|
||||
// magpie picks described in its place, and the row says so
|
||||
// the agent called magpie's image recognition MCP server itself
|
||||
if (r.kind === "vision" && r.for?.mcp) return t("{agent} called magpie's analyze_image MCP tool: {describer} looked at the image for it. Not a turn of the conversation.", { agent: agentName(r.for.agent), describer: r.model });
|
||||
if (r.kind === "vision" && r.for?.missing) return t("{picked}, the Image recognition model picked in Settings, isn't set up any more, so magpie had {describer}, its automatic choice, describe an image for {agent}'s {model} in its place. Pick another in Settings › Models › Image recognition. Not a turn of the conversation.", { picked: r.for.missing, agent: agentName(r.for.agent), model: r.for.model, describer: r.model });
|
||||
if (r.kind === "vision" && r.for?.unknown) return t("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.", { agent: agentName(r.for.agent), model: r.for.model, describer: r.model });
|
||||
if (r.kind === "vision") return r.for
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// magpie's image recognition as an MCP server (JonahFu on X): Settings ›
|
||||
// Models › Image recognition has an "MCP server" row with the gateway's
|
||||
// address of it, /mcp/magpie/vision, to copy into any agent, and says a
|
||||
// gateway key, and the image as a URL, go with it from another computer.
|
||||
// An image an agent asked it about reads in Routing as that agent's MCP
|
||||
// call, not as a description for one of magpie's 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/vision";
|
||||
const words = {
|
||||
en: { name: "Image recognition MCP server", sub: /analyze_image.*Authorization: Bearer <key>.*data URL/, story: /Claude Code called magpie's analyze_image MCP tool: codex\/gpt-6\.1-sol looked at the image for it/ },
|
||||
zh: { name: "识图 MCP 服务器", sub: /analyze_image.*Authorization: Bearer <key>.*data URL/, story: /Claude Code 调用了 magpie 的 analyze_image MCP 工具:由 codex\/gpt-6\.1-sol 代为查看图片/ },
|
||||
"zh-TW": { name: "識圖 MCP 伺服器", sub: /analyze_image.*Authorization: Bearer <key>.*data URL/, story: /Claude Code 呼叫了 magpie 的 analyze_image MCP 工具:由 codex\/gpt-6\.1-sol 代為查看圖片/ },
|
||||
ja: { name: "画像認識 MCP サーバー", sub: /analyze_image.*Authorization: Bearer <key>.*data URL/, story: /Claude Code が magpie の analyze_image MCP ツールを呼び出しました。codex\/gpt-6\.1-sol が代わりに画像を見ました/ },
|
||||
de: { name: "Bilderkennung als MCP-Server", sub: /analyze_image.*Authorization: Bearer <key>.*Data-URL/, story: /Claude Code hat das analyze_image-MCP-Tool von magpie aufgerufen: codex\/gpt-6\.1-sol hat sich das Bild dafür angesehen/ },
|
||||
};
|
||||
|
||||
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: "vision", 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", gateway: "http://127.0.0.1:3999", port: 3999, vision: "", visionAuto: "codex/gpt-6.1-sol",
|
||||
visionModels: [{ id: "codex/gpt-6.1-sol", name: "GPT-6.1 Sol", provider: "codex", providerName: "Codex", icon: "openai" }] };
|
||||
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}: Image recognition 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("#imagesList #visionMcpRow code")?.textContent === a, address);
|
||||
const row = await page.evaluate(() => {
|
||||
const r = document.querySelector("#imagesList #visionMcpRow");
|
||||
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 image 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