minimax 0.2.0: MiniMax web search and Matrix media tools (#671)

Adds MiniMax Code's account tools to the minimax plugin, as a Magpie-only `exports["./server"]` entry (magpie.mjs):
- `web_search`, MiniMax's own search, at /mavis/api/v1/mcp/web_search;
- the Matrix connector tools: image, video, speech, music, media understanding, image search and enhancement, and asset URLs, plus `list_tools`, `tool_schema` and `call_tool` limited to connector__matrix__*. The schemas are bundled in matrix-tools.json, and each call is routed through the account's live catalog.
- Tool requests reuse the chat sign-in's refresh logic per stored account key, and go through siteFetch: a cross-host redirect (Akamai's 307 to the other site) is an OtherSite hint and spends no refresh (#666).
- With no `account` named, a tool uses the site's first stored account. An explicitly named account never falls back to another one.
- No `web_fetch`: magpie's search MCP already serves one that refuses private addresses.
- Tool descriptions don't name magpie (tested).
- Version 0.2.0. The OpenCode entries still export only the two chat plugins.

Run at the reviewed head e776afc, on mote (macOS, sandbox HOME):
- `bun test` in packages/minimax: 123 pass, 0 fail, 12 files.
- `bun scripts/check.mjs`: ok (minimax ✓).
- Broken by hand: with `send` back on plain fetch, "tool redirects to another host stop before a 401 or token rotation" goes red (1 fail), and green again when restored.
- The first review's probe (307 to another host, 401 there) spent 3 refreshes over 3 calls at 2467992. The new test covers the same case: 0 refreshes and 0 requests reaching the other host.
- Checked against magpie's plugin host (internal/plugin/host.js): ./server is tried first, `directory` is magpie's config dir, and auth.set with a `minimax-code#…` id writes that key.

Not tried: a real MiniMax account (search, generation, billing), and a real mainland-China network against the Global site.
This commit is contained in:
Klarkxy
2026-11-03 19:43:11 +08:00
committed by GitHub
parent add66fc954
commit 95f37f46fa
11 changed files with 1295 additions and 43 deletions
+69
View File
@@ -62,6 +62,75 @@ Refreshing:
with `invalid_grant` (HTTP 400). Any other failure keeps the sign-in, and
the current token is used while it lasts.
## Generation and media tools in Magpie
The same plugin also exports `MiniMaxCodeToolsPlugin`. Magpie serves its tools
through the Library's MiniMax MCP server and `/mcp/magpie/tools`. Connect
that server to your agent to use the tools with any of its chat models.
| Tools | What they do |
|---|---|
| `web_search` | Native web/news/video/place/shopping search |
| `generate_image` | Text-to-image and image editing from reference URLs |
| `submit_video_generation`, `query_video_generation` | Submit H3, H3 Max or Hailuo video tasks, then check their progress |
| `synthesize_speech`, `batch_text_to_audio`, `get_voice_list` | Speech synthesis and voice selection |
| `batch_text_to_music` | Music and song generation |
| `describe_images`, `videos_understand`, `audios_understand`, `listen_audio` | Image, video and audio understanding, and transcription |
| `search_images`, `reverse_image_search` | Find image references |
| `enhance_image`, `remove_image_background` | Upscale images and remove backgrounds |
| `get_asset_url` | Get a fresh download URL for a generated asset's `node_id` |
| `list_tools`, `tool_schema`, `call_tool` | Discover and call the account's current Matrix tools and read their live schemas |
On the combined MCP server these are named `minimax_generate_image`,
`minimax_submit_video_generation`, and so on. In the Library's routed server,
the separator is `minimax__generate_image`.
Webpage reading is available through Magpie's search MCP server, whose
`web_fetch` protects loopback and private network addresses.
Account-backed tools accept `site`: `minimax-code` (China, the default) or
`minimax-code-global`. These tools read the chosen site's first stored account
from Magpie's `plugin-auth.json` on each call. To choose a particular account,
set `account` to its full stored key, such as `minimax-code#xxxxxx`. The
selected account's tokens are renewed by the same refresh logic as chat.
A missing account asks you to sign in; the selected account stays fixed
during a call and its authentication retry.
Tool requests use the same redirect handling as chat: redirects within
the same host are followed, while a redirect to another host returns a
site/proxy hint and preserves the account's refresh token.
The gateway status (`base_resp.status_code`) and the tool payload status
(`code`) are checked independently. A successful gateway response can
still carry a plan-limit error from the tool, even when the account has
credits available; that error is returned to the caller.
Inputs use HTTPS media URLs. Upload local reference files to a reachable
URL before passing them. Generated results include `node_id` and
`file_name`; pass the node id to `get_asset_url` and download the returned
URL. A URL can expire while its asset is still available: ask for a fresh
URL with the same node id.
Video generation is asynchronous: keep the returned task id and model,
then pass both to `query_video_generation`. Generation uses the selected
account's plan or credits according to MiniMax's billing. Choose the model
and parameters before submitting. Transport failures are reported so the
caller can check the outcome before deciding whether to submit again.
The tool definitions ship with the package; each execution also resolves
the tool against the selected account's live catalog. Availability and
provider failures come from that catalog. Use `tool_schema` and
`call_tool` when a newly added Matrix capability needs its current
parameters. Connector calls honor the host's cancellation signal. Magpie
currently limits an MCP tool call to 55 seconds, so a long synchronous
image or audio request may outlast that limit; video uses separate
submission and query calls.
Magpie loads `magpie.mjs` through `exports["./server"]` to expose these
tools with its account store. OpenCode 1.x loads `opencode.mjs`, and
OpenCode 2.x loads the shared adapter. Both OpenCode entry points expose
the two chat providers.
## Requests
Chats are Anthropic messages (`@ai-sdk/anthropic`) sent to
+343
View File
@@ -0,0 +1,343 @@
// The account's MiniMax Matrix connector tools, as magpie tools every
// agent on this provider can call: image/video/audio/music generation and
// understanding, through MiniMax Code's connector gateway
// (/minimax-cloud/api/v1/connectors/*). request is the parent transport's
// authenticated OAuth POST (site, path, body, {signal, timeoutMs, account}); it
// answers the response's JSON body with base_resp already checked.
//
// The bundled matrix-tools.json is a copy of the catalog's real schemas,
// taken from mcode-tools (connector tool <name>) on 2026-11-03, so loading
// this plugin never asks the network. The live catalog still routes every
// call (provider/provider_tool_name/runtime_tool_name), and is re-read on
// each operation: another signed-in account may connect different tools.
import { readFileSync } from "node:fs"
const LIST_PATH = "/minimax-cloud/api/v1/connectors/connected-tools/list"
const CALL_PATH = "/minimax-cloud/api/v1/connectors/tools/call"
const MATRIX = "connector__matrix__"
const LIST_MS = 30 * 1000
const CALL_MS = 55 * 1000 // magpie's MCP host lets a tool run about this long
const GEN_MS = 10 * 60 * 1000 // a generation may outlast it; ctx.abort still cuts it
const SITES = ["minimax-code", "minimax-code-global"]
// a bundled copy of the gateway's schemas; loading never waits on a fetch
const MATRIX_TOOLS = Object.freeze(
JSON.parse(readFileSync(new URL("./matrix-tools.json", import.meta.url), "utf8")).tools)
// generation and understanding calls get the long budget; the rest the
// host's. A video is submit + later query, never a poll inside one call.
const LONG = new Set([
"generate_image", "submit_video_generation", "synthesize_speech",
"batch_text_to_audio", "batch_text_to_music", "enhance_image",
"remove_image_background", "describe_images", "videos_understand",
"audios_understand", "listen_audio", "search_images",
"reverse_image_search",
])
const obj = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : undefined)
const str = (v) => (typeof v === "string" && v.trim() ? v.trim() : undefined)
// ---- a small JSON-Schema check -------------------------------------------------
// Enough of the draft for the bundled schemas: types, required, enum,
// properties + additionalProperties, items, string/array/number limits,
// const, allOf/anyOf/oneOf, not, and if/then/else (the video schema's
// per-model rules). Anything it doesn't know it leaves for the gateway.
function check(schema, value, path, errs) {
if (!obj(schema)) return
if (schema.const !== undefined && value !== schema.const)
errs.push(path + " must be " + JSON.stringify(schema.const))
if (Array.isArray(schema.enum) && !schema.enum.some((e) => same(e, value)))
errs.push(path + " must be one of " + schema.enum.map((e) => JSON.stringify(e)).join(", "))
const t = schema.type
if (t === "string" && typeof value !== "string") errs.push(path + " must be a string")
else if (t === "integer" && !Number.isInteger(value)) errs.push(path + " must be an integer")
else if (t === "number" && (typeof value !== "number" || !Number.isFinite(value))) errs.push(path + " must be a number")
else if (t === "boolean" && typeof value !== "boolean") errs.push(path + " must be a boolean")
else if (t === "array" && !Array.isArray(value)) errs.push(path + " must be an array")
else if (t === "object" && !obj(value)) errs.push(path + " must be an object")
if (errs.length) return
if (typeof value === "string") {
if (schema.minLength !== undefined && value.length < schema.minLength) errs.push(path + " is shorter than " + schema.minLength)
if (schema.maxLength !== undefined && value.length > schema.maxLength) errs.push(path + " is longer than " + schema.maxLength)
}
if (typeof value === "number") {
if (schema.minimum !== undefined && value < schema.minimum) errs.push(path + " must be >= " + schema.minimum)
if (schema.maximum !== undefined && value > schema.maximum) errs.push(path + " must be <= " + schema.maximum)
}
if (Array.isArray(value)) {
if (schema.minItems !== undefined && value.length < schema.minItems) errs.push(path + " needs at least " + schema.minItems + " item(s)")
if (schema.maxItems !== undefined && value.length > schema.maxItems) errs.push(path + " takes at most " + schema.maxItems + " item(s)")
if (obj(schema.items)) value.forEach((v, i) => check(schema.items, v, path + "[" + i + "]", errs))
}
if (obj(value)) {
const props = obj(schema.properties) ?? {}
for (const key of schema.required ?? [])
if (value[key] === undefined || value[key] === null) errs.push(path + "." + key + " is required")
for (const [key, v] of Object.entries(value)) {
if (Object.hasOwn(props, key)) check(props[key], v, path + "." + key, errs)
else if (schema.additionalProperties === false) errs.push(path + "." + key + " is not an accepted argument")
else if (obj(schema.additionalProperties)) check(schema.additionalProperties, v, path + "." + key, errs)
}
}
for (const sub of schema.allOf ?? []) check(sub, value, path, errs)
const iff = schema.if
if (obj(iff) && (obj(schema.then) || obj(schema.else))) {
const errsIf = []
check(iff, value, path, errsIf)
const branch = errsIf.length === 0 ? schema.then : schema.else
if (obj(branch)) check(branch, value, path, errs)
}
if (Array.isArray(schema.anyOf) && schema.anyOf.length) {
const ok = schema.anyOf.some((sub) => { const e = []; check(sub, value, path, e); return e.length === 0 })
if (!ok) errs.push(path + " matches none of the accepted shapes")
}
if (Array.isArray(schema.oneOf) && schema.oneOf.length) {
const ok = schema.oneOf.filter((sub) => { const e = []; check(sub, value, path, e); return e.length === 0 }).length
if (ok !== 1) errs.push(path + " must match exactly one of the accepted shapes")
}
if (obj(schema.not)) {
const e = []
check(schema.not, value, path, e)
if (e.length === 0) errs.push(path + " uses a combination the tool refuses")
}
}
const same = (a, b) => a === b || (obj(a) && obj(b) && JSON.stringify(a) === JSON.stringify(b))
// checked(schema, args) validates a tool call's own arguments (site and
// account already stripped) against its input_schema; a failure means the
// call never left, which for a priced generation is the point.
function checked(schema, args) {
if (!obj(args)) throw new Error("tool arguments must be an object")
const errs = []
check(schema, args, "arguments", errs)
if (errs.length) throw new Error("bad arguments: " + errs.join("; "))
return args
}
// ---- the connector gateway -------------------------------------------------------
// validateTool is the catalog entry the gateway needs to route a call.
function routeOf(t) {
const r = obj(t)
if (!r || !str(r.provider) || !str(r.provider_tool_name) || !str(r.runtime_tool_name)) return undefined
return { provider: r.provider, provider_tool_name: r.provider_tool_name, runtime_tool_name: r.runtime_tool_name }
}
// catalog reads the account's connected tools. It is deliberately not
// cached: a different account (or a changed connection) answers a
// different list, and a stale route would call the wrong provider.
async function catalog(request, site, signal, account) {
const body = await request(site, LIST_PATH, {}, { signal, timeoutMs: LIST_MS, account })
const b = obj(body)
if (!b || !Array.isArray(b.tools)) throw new Error("MiniMax connector list: malformed response (no tools array)")
if (!Array.isArray(b.provider_failures)) throw new Error("MiniMax connector list: malformed response (no provider_failures)")
if (typeof b.partial !== "boolean") throw new Error("MiniMax connector list: malformed partial flag")
if (b.provider_failures.some(f => !obj(f) || !str(f.provider) || !str(f.code) || !str(f.message)))
throw new Error("MiniMax connector list: malformed provider failure")
const seen = new Set()
const tools = []
for (const t of b.tools) {
const r = routeOf(t)
if (!r || typeof t.input_schema_json !== "string") throw new Error("MiniMax connector list: malformed tool entry")
if (seen.has(r.runtime_tool_name)) throw new Error("MiniMax connector list: duplicate tool " + r.runtime_tool_name)
seen.add(r.runtime_tool_name)
tools.push({ ...r, description: typeof t.description === "string" ? t.description : "", input_schema_json: t.input_schema_json, output_schema_json: t.output_schema_json })
}
return { tools, partial: b.partial === true, failures: b.provider_failures.filter(obj) }
}
// find resolves a runtime_tool_name in the fresh catalog, telling the
// truth about a provider failure instead of pretending success.
function find(cat, name) {
const match = cat.tools.find((t) => t.runtime_tool_name === name)
if (match) return match
const provider = /^connector__(.+?)__/.exec(name)?.[1]
const f = provider && cat.failures.find((x) => x.provider === provider)
if (f) throw new Error("connector provider " + f.provider + " is unavailable: " + (f.code ?? "?") + " — " + (f.message ?? ""))
throw new Error("connector tool " + JSON.stringify(name) + " is not connected on this account" + (cat.partial ? " (catalog is partial; it may still exist)" : ""))
}
// invoke sends one call through the gateway and answers the parsed result.
// is_error is the tool's own failure, thrown with its code and message —
// never shaped like a result.
async function invoke(request, site, entry, args, signal, timeoutMs, account) {
const body = await request(site, CALL_PATH, {
provider: entry.provider,
provider_tool_name: entry.provider_tool_name,
runtime_tool_name: entry.runtime_tool_name,
arguments_json: JSON.stringify(args ?? {}),
}, { signal, timeoutMs, account })
const b = obj(body)
if (!b) throw new Error("MiniMax connector call " + entry.runtime_tool_name + ": malformed response")
if (b.is_error === true) {
const code = str(b.error_code) ?? "connector_tool_error"
const msg = str(b.error_message) ?? "the connector tool failed"
throw new Error(code + ": " + msg)
}
if (b.is_error !== undefined && typeof b.is_error !== "boolean") throw new Error("MiniMax connector call: malformed is_error flag")
const raw = b.result_json
if (typeof raw !== "string" || !raw.trim()) throw new Error("MiniMax connector call: missing result_json")
let result
try { result = JSON.parse(raw) } catch {
throw new Error("MiniMax connector call " + entry.runtime_tool_name + ": result_json is not valid JSON")
}
if (obj(result) && result.code !== undefined && Number.isFinite(Number(result.code)) && Number(result.code) !== 0)
throw new Error("MiniMax Matrix tool: " + (str(result.message) ?? "request failed") + " (code=" + result.code + ")")
return result
}
// ---- the tools -------------------------------------------------------------------
// Each tool's visible args are its own input_schema's properties plus two
// routing fields, site and account, which are stripped before the call
// leaves: the gateway never sees them.
const siteArg = {
type: "string",
enum: SITES,
default: "minimax-code",
description: "Which MiniMax Code site's account asks: minimax-code (China, default) or minimax-code-global (international).",
}
const accountArg = {
type: "string",
description: "The full stored account key, e.g. minimax-code or minimax-code#xxxxxx. Defaults to the selected site's first stored account. The selected account stays fixed during the call and any authentication retry.",
}
function routing(args, callCtx) {
const a = obj(args) ?? {}
const site = a.site === undefined ? "minimax-code" : a.site
if (!SITES.includes(site)) throw new Error("site must be one of " + SITES.join(", "))
if (a.account !== undefined && typeof a.account !== "string") throw new Error("account must be a string")
const rest = { ...a }
delete rest.site
delete rest.account
return { site, account: a.account, args: rest, signal: callCtx?.abort }
}
function directTool(request, name, def) {
const inner = def.input_schema ?? { type: "object", properties: {} }
return {
description: def.description,
args: {
...inner,
type: "object",
properties: { site: siteArg, account: accountArg, ...(inner.properties ?? {}) },
required: inner.required ?? [],
additionalProperties: inner.additionalProperties ?? false,
},
async execute(args, callCtx) {
const r = routing(args, callCtx)
const cat = await catalog(request, r.site, r.signal, r.account)
const entry = find(cat, MATRIX + name)
const checkedArgs = checked(entry.input_schema_json ? parseSchema(entry.input_schema_json) : inner, r.args)
return invoke(request, r.site, entry, checkedArgs, r.signal, LONG.has(name) ? GEN_MS : CALL_MS, r.account)
},
}
}
function parseSchema(json) {
try {
const value = JSON.parse(json)
if (!obj(value)) throw new Error()
return value
} catch { throw new Error("MiniMax connector list: malformed input_schema_json") }
}
export function createConnectorTools(request) {
if (typeof request !== "function") throw new Error("createConnectorTools needs the request transport")
const tool = {}
// the named matrix tools, each its own first-class magpie tool
for (const [name, def] of Object.entries(MATRIX_TOOLS)) tool[name] = directTool(request, name, def)
tool.list_tools = {
description:
"List this account's connected MiniMax Matrix tools with their descriptions (the catalog is read fresh, so a newly connected tool shows up). " +
"Pass keyword to filter names and descriptions. The answer notes when the catalog is partial or a provider failed.",
args: {
type: "object",
properties: {
site: siteArg,
account: accountArg,
keyword: { type: "string", description: "optional filter on tool names and descriptions" },
},
additionalProperties: false,
},
async execute(args, callCtx) {
const r = routing(args, callCtx)
const cat = await catalog(request, r.site, r.signal, r.account)
const kw = str(r.args.keyword)?.toLocaleLowerCase()
const tools = cat.tools
.filter((t) => t.runtime_tool_name.startsWith(MATRIX))
.filter((t) => !kw || t.runtime_tool_name.toLocaleLowerCase().includes(kw) || t.description.toLocaleLowerCase().includes(kw))
.map((t) => ({ tool_name: t.runtime_tool_name, description: t.description }))
return { tools, partial: cat.partial, provider_failures: cat.failures }
},
}
tool.tool_schema = {
description:
"Show a connected tool's real input and output JSON schema as the account's catalog declares them, before calling it with call_tool.",
args: {
type: "object",
properties: {
site: siteArg,
account: accountArg,
tool_name: { type: "string", description: "the connector tool's full runtime name, e.g. connector__matrix__generate_image" },
},
required: ["tool_name"],
additionalProperties: false,
},
async execute(args, callCtx) {
const r = routing(args, callCtx)
const name = str(r.args.tool_name)
if (!name) throw new Error("tool_name is required")
if (!name.startsWith(MATRIX)) throw new Error("tool_schema only describes connector__matrix__* tools")
const cat = await catalog(request, r.site, r.signal, r.account)
const entry = find(cat, name)
let input_schema = null
let output_schema = null
input_schema = parseSchema(entry.input_schema_json)
try { output_schema = entry.output_schema_json ? JSON.parse(entry.output_schema_json) : null } catch { output_schema = { malformed: entry.output_schema_json } }
return { tool_name: name, provider: entry.provider, description: entry.description, input_schema, output_schema, partial: cat.partial }
},
}
tool.call_tool = {
description:
"Call a connected MiniMax Matrix connector tool by its runtime_tool_name with a JSON arguments object. " +
"Only connector__matrix__* tools are callable through here — this account's other integrations stay unreachable, so nothing else can be spent or read by accident. " +
"Use list_tools and tool_schema first; arguments are checked against the catalog's own schema before the call goes out.",
args: {
type: "object",
properties: {
site: siteArg,
account: accountArg,
tool_name: { type: "string", description: "a connector__matrix__* runtime name from list_tools" },
arguments: { type: "object", description: "the tool's arguments, conforming to its input_schema" },
},
required: ["tool_name", "arguments"],
additionalProperties: false,
},
async execute(args, callCtx) {
const r = routing(args, callCtx)
const name = str(r.args.tool_name)
if (!name) throw new Error("tool_name is required")
if (!name.startsWith(MATRIX)) throw new Error("call_tool only calls connector__matrix__* tools; got " + JSON.stringify(name))
const cat = await catalog(request, r.site, r.signal, r.account)
const entry = find(cat, name)
const checkedArgs = checked(entry.input_schema_json ? parseSchema(entry.input_schema_json) : { type: "object" }, r.args.arguments)
return invoke(request, r.site, entry, checkedArgs, r.signal, GEN_MS, r.account)
},
}
for (const t of Object.values(tool)) {
const execute = t.execute
t.execute = async (args, ctx) => {
checked(t.args, args)
ctx?.abort?.throwIfAborted()
return execute(args, ctx)
}
}
return { tool }
}
export const _internal = { check, checked, catalog, find, invoke, routing, MATRIX_TOOLS, SITES }
+276
View File
@@ -0,0 +1,276 @@
// The connector tools over a fake request transport: no server, each
// test answering the two gateway calls itself and checking what went out.
// Covers site/account stripping, the catalog's partial and provider
// failures, is_error and broken result_json, bad arguments stopped before
// they could be sent, abort propagation, and the matrix-only call guard.
import "./nonet.mjs"
import { expect, test } from "bun:test"
import { createConnectorTools } from "./connector-tools.mjs"
const LIST = "/minimax-cloud/api/v1/connectors/connected-tools/list"
const CALL = "/minimax-cloud/api/v1/connectors/tools/call"
const entry = (name, over = {}) => ({
provider: "matrix",
provider_tool_name: "mcp_" + name,
runtime_tool_name: "connector__matrix__" + name,
description: name + " tool",
input_schema_json: JSON.stringify({ type: "object" }),
...over,
})
// transport(script) is a request() fake: script[path] answers or throws;
// sent records every call as {site, path, body, signal, timeoutMs, account}.
function transport(script) {
const sent = []
const request = async (site, path, body, opts = {}) => {
sent.push({ site, path, body, signal: opts.signal, timeoutMs: opts.timeoutMs, account: opts.account })
const h = script[path]
if (!h) throw new Error("no fake for " + path)
if (h instanceof Error) throw h
return typeof h === "function" ? h({ site, body }) : h
}
return { request, sent }
}
const catalog = (tools, over = {}) => ({ tools, partial: false, provider_failures: [], ...over })
test("a direct tool calls the gateway with the catalog's own routing, site and account stripped", async () => {
const t = transport({
[LIST]: catalog([entry("generate_image")]),
[CALL]: { result_json: JSON.stringify({ success_items: [{ node_id: "n1", file_name: "a.png" }] }) },
})
const { tool } = createConnectorTools(t.request)
const out = await tool.generate_image.execute(
{ site: "minimax-code-global", account: "minimax-code-global#u42", requests: [{ prompt: "a cat" }] },
{ abort: new AbortController().signal },
)
expect(out).toEqual({ success_items: [{ node_id: "n1", file_name: "a.png" }] })
const [list, call] = t.sent
expect(list.site).toBe("minimax-code-global")
expect(list.account).toBe("minimax-code-global#u42")
expect(list.body).toEqual({})
expect(call.path).toBe(CALL)
expect(call.body).toEqual({
provider: "matrix",
provider_tool_name: "mcp_generate_image",
runtime_tool_name: "connector__matrix__generate_image",
arguments_json: JSON.stringify({ requests: [{ prompt: "a cat" }] }),
})
// site/account never reach the gateway arguments
expect(JSON.parse(call.body.arguments_json).site).toBeUndefined()
expect(JSON.parse(call.body.arguments_json).account).toBeUndefined()
})
test("the default site is minimax-code and no account is sent when none is given", async () => {
const t = transport({
[LIST]: catalog([entry("get_voice_list", { input_schema_json: JSON.stringify({ type: "object", properties: {}, additionalProperties: false }) })]),
[CALL]: { result_json: JSON.stringify({ code: 0, message: "ok", available_voices: [], total: 0 }) },
})
const { tool } = createConnectorTools(t.request)
await tool.get_voice_list.execute({}, { abort: new AbortController().signal })
expect(t.sent.every((r) => r.site === "minimax-code")).toBe(true)
expect(t.sent.every((r) => r.account === undefined)).toBe(true)
})
test("ctx.abort is the signal the transport gets", async () => {
const t = transport({
[LIST]: catalog([entry("describe_images")]),
[CALL]: { result_json: "{}" },
})
const { tool } = createConnectorTools(t.request)
const ac = new AbortController()
await tool.describe_images.execute({ image_info: [{ url: "https://x/a.png" }] }, { abort: ac.signal })
expect(t.sent.every((r) => r.signal === ac.signal)).toBe(true)
})
test("list_tools answers the catalog and reports partial and provider failures", async () => {
const t = transport({
[LIST]: catalog([entry("generate_image"), entry("search_images")], {
partial: true,
provider_failures: [{ provider: "email", code: "auth", message: "expired" }],
}),
})
const { tool } = createConnectorTools(t.request)
const out = await tool.list_tools.execute({ keyword: "image" }, {})
expect(out.tools.map((x) => x.tool_name)).toEqual(["connector__matrix__generate_image", "connector__matrix__search_images"])
expect(out.partial).toBe(true)
expect(out.provider_failures).toEqual([{ provider: "email", code: "auth", message: "expired" }])
})
test("tool_schema shows the catalog's own schemas", async () => {
const input = { type: "object", properties: { node_id: { type: "string" } }, required: ["node_id"] }
const t = transport({
[LIST]: catalog([
entry("get_asset_url", {
input_schema_json: JSON.stringify(input),
output_schema_json: JSON.stringify({ type: "object", properties: { code: { type: "integer" } } }),
}),
]),
})
const { tool } = createConnectorTools(t.request)
const out = await tool.tool_schema.execute({ tool_name: "connector__matrix__get_asset_url" }, {})
expect(out.input_schema).toEqual(input)
expect(out.output_schema).toEqual({ type: "object", properties: { code: { type: "integer" } } })
expect(out.provider).toBe("matrix")
})
test("call_tool routes a matrix call and parses result_json", async () => {
const t = transport({
[LIST]: catalog([entry("generate_image")]),
[CALL]: { result_json: JSON.stringify({ node_id: "n9" }) },
})
const { tool } = createConnectorTools(t.request)
const out = await tool.call_tool.execute(
{ tool_name: "connector__matrix__generate_image", arguments: { prompt: "x" } },
{},
)
expect(out).toEqual({ node_id: "n9" })
})
test("call_tool refuses a non-matrix tool so other integrations stay unreachable", async () => {
const t = transport({})
const { tool } = createConnectorTools(t.request)
await expect(
tool.call_tool.execute({ tool_name: "connector__email_workbench_credentials__session", arguments: {} }, {}),
).rejects.toThrow(/only calls connector__matrix__/)
expect(t.sent).toHaveLength(0)
})
test("is_error from the gateway is thrown with its code and message, not shaped like a result", async () => {
const t = transport({
[LIST]: catalog([entry("generate_image")]),
[CALL]: { is_error: true, error_code: "quota_exceeded", error_message: "weekly limit reached" },
})
const { tool } = createConnectorTools(t.request)
await expect(
tool.generate_image.execute({ requests: [{ prompt: "x" }] }, {}),
).rejects.toThrow("quota_exceeded: weekly limit reached")
})
test("a broken result_json is an error, not a silent null", async () => {
const t = transport({
[LIST]: catalog([entry("generate_image")]),
[CALL]: { result_json: "{not json" },
})
const { tool } = createConnectorTools(t.request)
await expect(
tool.generate_image.execute({ requests: [{ prompt: "x" }] }, {}),
).rejects.toThrow(/result_json is not valid JSON/)
})
test("bad arguments are refused before any request leaves", async () => {
const t = transport({
[LIST]: catalog([entry("generate_image", {
input_schema_json: JSON.stringify({ type: "object", properties: { requests: { type: "array" } }, required: ["requests"], additionalProperties: false }),
})]),
})
const { tool } = createConnectorTools(t.request)
// 'requests' is required by the catalog schema
await expect(tool.generate_image.execute({ prompt: "x" }, {})).rejects.toThrow(/bad arguments/)
expect(t.sent).toHaveLength(0) // bundled schema catches it before reading the catalog
})
test("video validation follows the per-model allOf rules", async () => {
const video = {
type: "object",
properties: {
model: { type: "string", enum: ["MiniMax-H3", "MiniMax-H3-Max", "MiniMax-Hailuo-2.3"] },
prompt: { type: "string" },
duration: { type: "integer" },
reference_images: { type: "array", items: { type: "object" } },
last_frame_image: { type: "object" },
},
required: ["prompt", "model"],
additionalProperties: false,
allOf: [
{ if: { properties: { model: { const: "MiniMax-Hailuo-2.3" } }, required: ["model"] },
then: { not: { anyOf: [{ required: ["reference_images"] }, { required: ["last_frame_image"] }] } } },
{ if: { properties: { model: { const: "MiniMax-H3" } }, required: ["model"] },
then: { properties: { duration: { minimum: 4, maximum: 15, type: "integer" } }, required: ["duration"] } },
],
}
const t = transport({
[LIST]: catalog([entry("submit_video_generation", { input_schema_json: JSON.stringify(video) })]),
[CALL]: { result_json: JSON.stringify({ task_id: "t1" }) },
})
const { tool } = createConnectorTools(t.request)
// Hailuo + reference_images: the allOf not/anyOf refuses it
await expect(
tool.submit_video_generation.execute(
{ model: "MiniMax-Hailuo-2.3", prompt: "p", reference_images: [{ url: "u" }] },
{},
),
).rejects.toThrow(/bad arguments/)
// H3 without duration: required by its branch
await expect(
tool.submit_video_generation.execute({ model: "MiniMax-H3", prompt: "p" }, {}),
).rejects.toThrow(/bad arguments/)
// H3 duration out of range
await expect(
tool.submit_video_generation.execute({ model: "MiniMax-H3", prompt: "p", duration: 20 }, {}),
).rejects.toThrow(/bad arguments/)
// a legal H3 call goes out
const out = await tool.submit_video_generation.execute({ model: "MiniMax-H3", prompt: "p", duration: 6 }, {})
expect(out).toEqual({ task_id: "t1" })
const calls = t.sent.filter((r) => r.path === CALL)
expect(calls).toHaveLength(1)
})
test("a malformed catalog entry or a duplicate name is an error", async () => {
const t = transport({
[LIST]: catalog([entry("generate_image"), entry("generate_image")]),
})
const { tool } = createConnectorTools(t.request)
await expect(tool.list_tools.execute({}, {})).rejects.toThrow(/duplicate tool/)
const t2 = transport({
[LIST]: catalog([{ provider: "matrix" }]), // missing names
})
const { tool: tool2 } = createConnectorTools(t2.request)
await expect(tool2.list_tools.execute({}, {})).rejects.toThrow(/malformed tool entry/)
})
test("a provider failure for the tool's provider is reported as such", async () => {
const t = transport({
[LIST]: catalog([], {
provider_failures: [{ provider: "matrix", code: "disconnected", message: "token revoked" }],
}),
})
const { tool } = createConnectorTools(t.request)
await expect(
tool.call_tool.execute({ tool_name: "connector__matrix__generate_image", arguments: { prompt: "x" } }, {}),
).rejects.toThrow(/provider matrix is unavailable: disconnected/)
})
test("an abort mid-call propagates as the transport's own rejection", async () => {
const ac = new AbortController()
const t = transport({
[LIST]: () => { ac.abort(); return catalog([entry("get_voice_list")]) },
[CALL]: new DOMException("The operation was aborted", "AbortError"),
})
const { tool } = createConnectorTools(t.request)
await expect(tool.get_voice_list.execute({}, { abort: ac.signal })).rejects.toThrow(/abort/i)
})
test("missing results and Matrix business failures never look like a successful generation", async () => {
for (const response of [{}, { is_error: "false", result_json: "{}" }, { result_json: JSON.stringify({ code: 402, message: "insufficient credits" }) }]) {
const t = transport({ [LIST]: catalog([entry("generate_image")]), [CALL]: response })
const { tool } = createConnectorTools(t.request)
await expect(tool.generate_image.execute({ requests: [{ prompt: "fixture" }] })).rejects.toThrow()
expect(t.sent.filter(r => r.path === CALL)).toHaveLength(1)
}
})
test("discovery stays scoped to Matrix and generic arguments are checked before catalog lookup", async () => {
const email = { ...entry("hidden"), runtime_tool_name: "connector__email__hidden", provider: "email" }
const t = transport({ [LIST]: catalog([entry("generate_image"), email]) })
const { tool } = createConnectorTools(t.request)
const result = await tool.list_tools.execute({})
expect(result.tools.map(t => t.tool_name)).toEqual(["connector__matrix__generate_image"])
await expect(tool.tool_schema.execute({ tool_name: "connector__email__hidden" })).rejects.toThrow("only describes")
const before = t.sent.length
await expect(tool.list_tools.execute({ keyword: 42 })).rejects.toThrow("must be a string")
await expect(tool.get_voice_list.execute(null)).rejects.toThrow("object")
expect(t.sent.length).toBe(before)
})
+154 -39
View File
@@ -11,6 +11,10 @@
// claimed with the same token, on the minimax-cloud endpoints.
import { createHash, randomBytes, randomUUID } from "node:crypto"
import { readFile } from "node:fs/promises"
import { join } from "node:path"
import { createConnectorTools } from "./connector-tools.mjs"
import { createWebTools } from "./web-tools.mjs"
const CLIENT_ID = "mcode-public"
const SCOPE = "agent.default"
@@ -828,49 +832,54 @@ function renew(site, a, save) {
return r
}
function makePlugin(site) {
return async ({ client }) => {
const save = async (a) => {
if (typeof client?.auth?.set !== "function") return false
try {
await client.auth.set({ path: { id: site.id }, body: a })
return true
} catch {
return false
}
function accountSession(site, client, accountID = site.id) {
const save = async (a) => {
if (typeof client?.auth?.set !== "function") return false
try {
await client.auth.set({ path: { id: accountID }, body: a })
return true
} catch {
return false
}
}
// fresh is the account with an access token that isn't about to end,
// refreshed (and saved) when it is, or when MiniMax turned away the
// access token rejected and no newer one is had. renewed says the
// token isn't the one getAuth read: this call or another refreshed it.
const fresh = async (getAuth, rejected, again = false) => {
const stored = await getAuth()
if (stored?.type !== "oauth" || !stored.access) throw new Error(`${site.name} isn't signed in`)
const a = latest(site, stored)
const newer = a.access !== stored.access
if (rejected !== undefined && a.access !== rejected) return { a, renewed: true }
const force = rejected !== undefined
if (!force && !(a.expires && Date.now() >= a.expires - EARLY_MS)) return { a, renewed: newer }
if (!a.refresh) {
if (Date.now() < a.expires) return { a, renewed: newer }
// fresh is the account with an access token that isn't about to end,
// refreshed (and saved) when it is, or when MiniMax turned away the
// access token rejected and no newer one is had. renewed says the
// token isn't the one getAuth read: this call or another refreshed it.
const fresh = async (getAuth, rejected, again = false) => {
const stored = await getAuth()
if (stored?.type !== "oauth" || !stored.access) throw new Error(`${site.name} isn't signed in`)
const a = latest(site, stored)
const newer = a.access !== stored.access
if (rejected !== undefined && a.access !== rejected) return { a, renewed: true }
const force = rejected !== undefined
if (!force && !(a.expires && Date.now() >= a.expires - EARLY_MS)) return { a, renewed: newer }
if (!a.refresh) {
if (Date.now() < a.expires) return { a, renewed: newer }
throw new SignInExpired(site)
}
try {
return { a: { ...a, ...(await renew(site, a, save)) }, renewed: true }
} catch (e) {
if (signedOut(e)) {
// spent by someone else (magpie's renewal, another process of
// magpie's), who saved the new one: that one is used
const now = again ? undefined : await getAuth().catch(() => undefined)
if (now?.type === "oauth" && now.refresh && now.refresh !== a.refresh && now.refresh !== stored.refresh) return fresh(getAuth, rejected, true)
throw new SignInExpired(site)
}
try {
return { a: { ...a, ...(await renew(site, a, save)) }, renewed: true }
} catch (e) {
if (signedOut(e)) {
// spent by someone else (magpie's renewal, another process of
// magpie's), who saved the new one: that one is used
const now = again ? undefined : await getAuth().catch(() => undefined)
if (now?.type === "oauth" && now.refresh && now.refresh !== a.refresh && now.refresh !== stored.refresh) return fresh(getAuth, rejected, true)
throw new SignInExpired(site)
}
// passing: the token in hand may still do
if (!force && Date.now() < a.expires) return { a, renewed: newer }
throw Object.assign(new Error(`${site.name} token refresh: ${e?.message ?? e}`), { signIn: "kept" })
}
// passing: the token in hand may still do
if (!force && Date.now() < a.expires) return { a, renewed: newer }
throw Object.assign(new Error(`${site.name} token refresh: ${e?.message ?? e}`), { signIn: "kept" })
}
}
return fresh
}
function makePlugin(site) {
return async ({ client }) => {
const fresh = accountSession(site, client)
// one conversation id for requests that come with none of their own
const session = randomUUID()
@@ -1086,8 +1095,114 @@ function makePlugin(site) {
}
}
// Tools run outside a chat account's scope. Read the explicitly selected
// account afresh for each call; the site's first stored account is the default.
function createToolRequest({ client, directory }) {
const sessions = new Map()
return async (siteID, path, body, { signal, timeoutMs = 30000, account } = {}) => {
const site = SITES[siteID]
if (!site) throw new Error("unknown MiniMax Code site")
let id = account
const belongs = (key) => typeof key === "string" && (key === site.id || key.startsWith(site.id + "#") && key.length > site.id.length + 1)
if (id !== undefined && !belongs(id))
throw new Error("account must belong to the selected MiniMax Code site")
if (!directory) throw new Error("MiniMax tools require Magpie's config directory")
const abort = AbortSignal.any([AbortSignal.timeout(timeoutMs), ...(signal ? [signal] : [])])
abort.throwIfAborted()
// Stop this tool promptly while a shared token rotation finishes and saves.
const wait = async (pending) => {
let onAbort
const cancelled = new Promise((_, reject) => {
onAbort = () => reject(abort.reason)
abort.addEventListener("abort", onAbort, { once: true })
})
try {
abort.throwIfAborted()
return await Promise.race([pending, cancelled])
} finally { abort.removeEventListener("abort", onAbort) }
}
const getAuth = async () => {
let store
try {
store = obj(JSON.parse(await readFile(join(directory, "plugin-auth.json"), "utf8")))
} catch (e) {
if (e.code === "ENOENT") throw new Error("Sign in to " + site.name + " in Magpie before using its tools")
throw new Error("MiniMax tools: Magpie's plugin-auth.json could not be read")
}
if (!store) throw new Error("MiniMax tools: invalid Magpie account store")
// Resolve once per call so a retry stays on the same account.
id ??= Object.keys(store).find(belongs) ?? site.id
return Object.hasOwn(store, id) ? store[id] : undefined
}
await wait(getAuth())
if (!sessions.has(id)) sessions.set(id, accountSession(site, client, id))
const fresh = sessions.get(id)
let { a } = await wait(fresh(getAuth))
const secrets = new Set([a.access, a.refresh].filter(Boolean))
const redact = (message) => {
let out = String(message)
for (const secret of secrets) out = out.replaceAll(secret, "<redacted>")
return out
}
const send = (auth) => {
abort.throwIfAborted()
const req = {
url: new URL(path, site.llm).href,
init: { method: "POST", headers: { "Content-Type": "application/json", "User-Agent": "MiniMaxAgent", Authorization: "Bearer " + auth.access }, body: JSON.stringify(body) },
}
return siteFetch(site, req.url, { ...req.init, signal: abort }, site.name + " tool API")
}
try {
let res = await send(a)
// A 401 means the request was refused before execution. Transport
// failures and business errors are surfaced, never replayed.
if (res.status === 401) {
await res.body?.cancel()
;({ a } = await wait(fresh(getAuth, a.access)))
secrets.add(a.access)
if (a.refresh) secrets.add(a.refresh)
res = await send(a)
}
if (!res.ok) throw new Error(site.name + " tool API: HTTP " + res.status)
let env
try { env = obj(JSON.parse(await res.text())) } catch (e) {
abort.throwIfAborted()
throw new Error("MiniMax tool API: invalid JSON response")
}
if (!env) throw new Error("MiniMax tool API: expected a JSON object")
// The gateway may succeed while the tool payload reports a billing
// or execution error. Both status layers must pass independently.
if (env.code !== undefined) {
const { code: rawCode, message, ...payload } = env
const code = num(rawCode)
if (code === undefined) throw new Error("MiniMax tool API: invalid response code")
if (code !== 0) throw new Error("MiniMax tool API: " + (str(env, "message") ?? "status " + code))
if (env.base_resp === undefined) env = { ...payload, base_resp: { status_code: code, status_msg: message } }
}
if (env.base_resp !== undefined) {
const br = obj(env.base_resp)
const code = br && num(br.status_code)
if (code === undefined) throw new Error("MiniMax tool API: invalid base_resp")
if (code !== 0) throw new Error("MiniMax tool API: " + (str(br, "status_msg") ?? "status " + code))
}
checked(env, "MiniMax tool API")
abort.throwIfAborted()
return env
} catch (e) {
abort.throwIfAborted()
e.message = redact(e.message)
throw e
}
}
}
export const MiniMaxCodeToolsPlugin = async (input) => {
const request = createToolRequest(input)
return { tool: { ...createConnectorTools(request).tool, ...createWebTools(request) } }
}
export const MiniMaxCodeAuthPlugin = makePlugin(SITES["minimax-code"])
export const MiniMaxCodeGlobalAuthPlugin = makePlugin(SITES["minimax-code-global"])
// for tests
export const _internal = { SITES, MODELS, signed, md5, parseModels, planWindows, membershipOf, usageOf, credits, creditsWindow, ledgerBatches, variants, renewing, renewed, startDevice, pollDevice, checkinOf }
export const _internal = { SITES, MODELS, createToolRequest, signed, md5, parseModels, planWindows, membershipOf, usageOf, credits, creditsWindow, ledgerBatches, variants, renewing, renewed, startDevice, pollDevice, checkinOf }
+3
View File
@@ -0,0 +1,3 @@
// Magpie selects exports["./server"]. Its MCP tools use Magpie's account
// store; the OpenCode entry points expose the two chat providers.
export { MiniMaxCodeAuthPlugin, MiniMaxCodeGlobalAuthPlugin, MiniMaxCodeToolsPlugin } from "./index.mjs"
File diff suppressed because one or more lines are too long
+3 -3
View File
@@ -1,11 +1,11 @@
{
"name": "@magpie-community/opencode-minimax-auth",
"version": "0.1.9",
"version": "0.2.0",
"description": "OpenCode provider plugins for MiniMax Code accounts: their credits and M Plan, China (minimax-code) and international (minimax-code-global), with MiniMax Code's own device sign-in",
"type": "module",
"main": "./opencode.mjs",
"exports": { ".": "./opencode2.mjs" },
"files": ["index.mjs", "opencode.mjs", "opencode2.mjs", "README.md"],
"exports": { "./server": "./magpie.mjs", ".": "./opencode2.mjs" },
"files": ["index.mjs", "opencode.mjs", "opencode2.mjs", "magpie.mjs", "connector-tools.mjs", "matrix-tools.json", "web-tools.mjs", "README.md"],
"keywords": ["opencode", "opencode-plugin", "minimax", "mcode", "minimax-code"],
"license": "MIT",
"repository": { "type": "git", "url": "git+https://github.com/magpie-community/plugins.git", "directory": "packages/minimax" }
+290
View File
@@ -0,0 +1,290 @@
import "./nonet.mjs"
import { afterEach, expect, test } from "bun:test"
import { mkdir, rm, writeFile } from "node:fs/promises"
import { join, resolve } from "node:path"
import { randomUUID } from "node:crypto"
import { MiniMaxCodeAuthPlugin, _internal } from "./index.mjs"
import { MiniMaxCodeToolsPlugin } from "./magpie.mjs"
import * as openCode from "./opencode.mjs"
import { fakeMiniMax, json } from "./fake.mjs"
const dirs = []
let f
afterEach(async () => {
f?.close()
f = undefined
for (const directory of dirs.splice(0)) await rm(directory, { recursive: true, force: true })
})
const auth = (access = "tool-token") => ({ type: "oauth", access, refresh: "tool-refresh", expires: Date.now() + 3600_000 })
async function fixture(store = { "minimax-code": auth() }) {
const directory = resolve(".sandbox", "minimax-tools-" + randomUUID())
dirs.push(directory)
await mkdir(directory, { recursive: true })
const saveStore = () => writeFile(join(directory, "plugin-auth.json"), JSON.stringify(store), "utf8")
await saveStore()
const saves = []
const client = { auth: { set: async ({ path, body }) => {
saves.push({ id: path.id, body })
store[path.id] = body
await saveStore()
} } }
return { request: _internal.createToolRequest({ directory, client }), store, saves, client, saveStore }
}
const path = "/minimax-cloud/api/v1/connectors/tools/call"
test("default selection follows the first stored account and refresh saves its exact key", async () => {
f = fakeMiniMax()
f.route("POST /oauth2/token", () => json({ access_token: "default-new", refresh_token: "default-refresh-new", expires_in: 3600 }))
f.route("POST " + path, () => json({}))
for (const site of ["minimax-code", "minimax-code-global"]) {
const key = site + "#first"
const t = await fixture({
[site + "-other#unrelated"]: auth("unrelated"),
[key]: { ...auth("default-old"), refresh: "default-refresh-" + site, expires: Date.now() - 1 },
[site]: auth("bare"),
})
await t.request(site, path, {})
expect(f.seen.at(-1).headers.get("authorization")).toBe("Bearer default-new")
expect(t.saves.map(s => s.id)).toEqual([key])
delete t.store[site]
await t.saveStore()
await t.request(site, path, {})
expect(f.seen.at(-1).headers.get("authorization")).toBe("Bearer default-new")
delete t.store[key]
t.store[site + "#next"] = auth("next-default")
await t.saveStore()
await t.request(site, path, {})
expect(f.seen.at(-1).headers.get("authorization")).toBe("Bearer next-default")
}
})
test("an account removed during a 401 retry does not switch to another account", async () => {
f = fakeMiniMax()
const key = "minimax-code#first"
const t = await fixture({ [key]: auth(), "minimax-code#second": auth("second") })
f.route("POST " + path, async () => {
delete t.store[key]
await t.saveStore()
return json({}, 401)
})
await expect(t.request("minimax-code", path, {})).rejects.toThrow("isn't signed in")
expect(f.seen).toHaveLength(1)
expect(t.saves).toHaveLength(0)
})
test("tool redirects to another host stop before a 401 or token rotation", async () => {
f = fakeMiniMax()
let targetCalls = 0
const target = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch() { targetCalls++; return json({ error: "invalid access token" }, 401) } })
try {
const endpoints = ["/mavis/api/v1/mcp/web_search", "/minimax-cloud/api/v1/connectors/connected-tools/list", path]
const t = await fixture({ "minimax-code": auth(), "minimax-code-global": auth("global") })
for (const status of [307, 308]) {
for (const endpoint of endpoints) {
f.route("POST " + endpoint, () => new Response(null, { status, headers: { location: target.url.href + "refused" } }))
for (const site of ["minimax-code", "minimax-code-global"]) {
for (let call = 0; call < 3; call++) {
const e = await t.request(site, endpoint, {}).catch(e => e)
expect(e.status).toBe(status)
expect(e.message).toContain("sent the request on to")
expect(e.message).toContain("proxy")
if (site === "minimax-code-global") expect(e.message).toContain("outside mainland China")
}
}
}
}
expect(targetCalls).toBe(0)
expect(t.saves).toHaveLength(0)
expect(f.seen.filter(r => r.path === "/oauth2/token")).toHaveLength(0)
expect(f.seen).toHaveLength(36)
} finally { target.stop(true) }
})
test("same-host tool redirects preserve POST body and authorization", async () => {
f = fakeMiniMax()
const t = await fixture()
f.route("POST /tool-destination", () => json({ result_json: "{}" }))
for (const status of [307, 308]) {
f.route("POST " + path, () => new Response(null, { status, headers: { location: "/tool-destination" } }))
expect(await t.request("minimax-code", path, { arguments_json: "{}" })).toEqual({ result_json: "{}" })
expect(f.seen.at(-1).path).toBe("/tool-destination")
expect(f.seen.at(-1).method).toBe("POST")
expect(f.seen.at(-1).json).toEqual({ arguments_json: "{}" })
expect(f.seen.at(-1).headers.get("authorization")).toBe("Bearer tool-token")
}
expect(t.saves).toHaveLength(0)
})
test("tools use their Magpie account and the verified Connector host", async () => {
f = fakeMiniMax()
f.route("POST " + path, () => json({ result_json: "{}" }))
const t = await fixture()
expect(await t.request("minimax-code", path, { arguments_json: "{}" })).toEqual({ result_json: "{}" })
const r = f.seen[0]
expect(r.headers.get("authorization")).toBe("Bearer tool-token")
expect(r.json).toEqual({ arguments_json: "{}" })
expect(r.query.size).toBe(0)
})
test("tools can select a second account and refresh saves that exact key", async () => {
f = fakeMiniMax()
f.route("POST /oauth2/token", () => json({ access_token: "second-new", refresh_token: "second-refresh-new", expires_in: 3600 }))
f.route("POST " + path, () => json({}))
const key = "minimax-code#second"
const primary = auth()
const t = await fixture({ "minimax-code": primary, [key]: { ...auth("second-old"), expires: Date.now() - 1 } })
await t.request("minimax-code", path, {}, { account: key })
expect(f.seen.at(-1).headers.get("authorization")).toBe("Bearer second-new")
expect(t.saves.map(s => s.id)).toEqual([key])
expect(t.store["minimax-code"]).toEqual(primary)
})
test("an explicitly missing account stays missing and accounts stay within their site", async () => {
const t = await fixture({ "minimax-code#second": auth(), "minimax-code-global": auth("global") })
await expect(t.request("minimax-code", path, {}, { account: "minimax-code" })).rejects.toThrow("isn't signed in")
await expect(t.request("minimax-code", path, {}, { account: "minimax-code#missing" })).rejects.toThrow("isn't signed in")
const otherSite = await fixture({ "minimax-code-global": auth("global") })
await expect(otherSite.request("minimax-code", path, {})).rejects.toThrow("isn't signed in")
await expect(t.request("minimax-code", path, {}, { account: "minimax-code-global" })).rejects.toThrow("selected MiniMax Code site")
await expect(t.request("not-a-site", path, {})).rejects.toThrow("unknown")
})
test("tools read login changes each time and support the global site", async () => {
f = fakeMiniMax()
f.route("POST " + path, () => json({}))
const t = await fixture({ "minimax-code-global": auth("global-old") })
await t.request("minimax-code-global", path, {})
t.store["minimax-code-global"] = auth("global-new")
await t.saveStore()
await t.request("minimax-code-global", path, {})
expect(f.seen.map(r => r.headers.get("authorization"))).toEqual(["Bearer global-old", "Bearer global-new"])
})
test("a 401 refreshes once; other statuses never replay a generation", async () => {
f = fakeMiniMax()
let calls = 0
f.route("POST " + path, () => { calls++; return calls === 1 ? json({}, 401) : json({ result_json: "{}" }) })
f.route("POST /oauth2/token", () => json({ access_token: "fresh-token", refresh_token: "fresh-refresh", expires_in: 3600 }))
const t = await fixture()
await t.request("minimax-code", path, {})
expect(calls).toBe(2)
expect(t.saves.length).toBe(1)
f.route("POST " + path, () => { calls++; return json({}, 500) })
await expect(t.request("minimax-code", path, {})).rejects.toThrow("HTTP 500")
expect(calls).toBe(3)
})
test("chat and tools share the same in-flight OAuth refresh", async () => {
f = fakeMiniMax()
let refreshes = 0
f.route("POST /oauth2/token", async () => {
refreshes++
await Bun.sleep(30)
return json({ access_token: "shared-new", refresh_token: "shared-r2", expires_in: 3600 })
})
f.route("POST " + path, () => json({}))
f.route("POST /mavis/api/v1/llm/v1/messages", () => json({}))
const t = await fixture({ "minimax-code": { ...auth(), expires: Date.now() - 1 } })
const hooks = await MiniMaxCodeAuthPlugin({ client: t.client })
const loader = await hooks.auth.loader(async () => t.store["minimax-code"])
await Promise.all([
t.request("minimax-code", path, {}),
loader.fetch(loader.baseURL + "/messages", { method: "POST", body: "{}" }),
])
expect(refreshes).toBe(1)
for (const r of f.seen.filter(r => r.path !== "/oauth2/token")) expect(r.headers.get("authorization")).toBe("Bearer shared-new")
})
test("business errors and malformed JSON are errors with credentials redacted", async () => {
f = fakeMiniMax()
const t = await fixture()
f.route("POST " + path, () => json({ base_resp: { status_code: "1000", status_msg: "tool-token tool-refresh" } }))
const e = await t.request("minimax-code", path, {}).catch(e => e)
expect(e.message).toContain("<redacted>")
expect(e.message).not.toContain("tool-token")
expect(e.message).not.toContain("tool-refresh")
f.route("POST " + path, () => new Response("broken-json tool-token"))
await expect(t.request("minimax-code", path, {})).rejects.toThrow("invalid JSON")
f.route("POST " + path, () => json([]))
await expect(t.request("minimax-code", path, {})).rejects.toThrow("JSON object")
})
test("cancelled calls never start, and a slow response can be cancelled", async () => {
f = fakeMiniMax()
f.route("POST " + path, async () => { await Bun.sleep(100); return json({}) })
const t = await fixture()
const controller = new AbortController()
controller.abort()
await expect(t.request("minimax-code", path, {}, { signal: controller.signal })).rejects.toThrow()
expect(f.seen.length).toBe(0)
await expect(t.request("minimax-code", path, {}, { timeoutMs: 20 })).rejects.toThrow()
})
test("the OpenCode entry retains only its two supported chat plugins", () => {
expect(Object.keys(openCode).sort()).toEqual(["MiniMaxCodeAuthPlugin", "MiniMaxCodeGlobalAuthPlugin"])
})
test("the actual plugin exports all 20 tools flat and performs a complete generation call", async () => {
f = fakeMiniMax()
f.route("POST /minimax-cloud/api/v1/connectors/connected-tools/list", () => json({
tools: [{ provider: "matrix", provider_tool_name: "matrix_generate_image", runtime_tool_name: "connector__matrix__generate_image", input_schema_json: JSON.stringify({ type: "object" }) }], partial: false, provider_failures: [],
}))
f.route("POST " + path, () => json({ result_json: JSON.stringify({ code: 0, success_items: [{ node_id: "fake-node", file_name: "fake.png" }] }) }))
const t = await fixture()
const { tool } = await MiniMaxCodeToolsPlugin({ directory: dirs.at(-1), client: t.client })
expect(Object.keys(tool)).toHaveLength(20)
expect(tool.web_fetch).toBeUndefined()
for (const def of Object.values(tool)) expect(JSON.stringify({ description: def.description, args: def.args })).not.toMatch(/magpie/i)
for (const name of ["generate_image", "submit_video_generation", "query_video_generation", "get_asset_url", "web_search"]) {
expect(typeof tool[name]?.execute).toBe("function")
expect(tool[name].args.type).toBe("object")
}
const result = await tool.generate_image.execute({ requests: [{ prompt: "fixture only" }] })
expect(result.success_items[0].node_id).toBe("fake-node")
expect(f.seen.at(-1).json).toMatchObject({ provider: "matrix", provider_tool_name: "matrix_generate_image", arguments_json: JSON.stringify({ requests: [{ prompt: "fixture only" }] }) })
})
test("cancelling during token rotation returns promptly while the shared refresh is saved", async () => {
f = fakeMiniMax()
let started, release
const arrived = new Promise(resolve => { started = resolve })
const gate = new Promise(resolve => { release = resolve })
f.route("POST /oauth2/token", async () => {
started()
await gate
return json({ access_token: "after-cancel", refresh_token: "rotated-after-cancel", expires_in: 3600 })
})
const t = await fixture({ "minimax-code": { ...auth(), expires: Date.now() - 1 } })
const controller = new AbortController()
const pending = t.request("minimax-code", path, {}, { signal: controller.signal }).catch(e => e.name)
await arrived
const rotating = [..._internal.renewing.values()][0]
try {
controller.abort()
expect(await Promise.race([pending, Bun.sleep(1000).then(() => "still waiting")])).toBe("AbortError")
expect(f.seen.some(r => r.path === path)).toBe(false)
} finally {
release()
await rotating
}
expect(t.saves[0].body.access).toBe("after-cancel")
})
test("native search normalizes both Matrix response envelopes and business errors", async () => {
f = fakeMiniMax()
const endpoint = "/mavis/api/v1/mcp/web_search"
const t = await fixture()
const { tool } = await MiniMaxCodeToolsPlugin({ directory: dirs.at(-1), client: t.client })
f.route("POST " + endpoint, () => json({ code: 0, message: "ok", organic: [{ title: "fixture", url: "https://example.com" }] }))
expect(await tool.web_search.execute({ query: "fixture", search_type: "news" })).toEqual({ organic: [{ title: "fixture", url: "https://example.com" }] })
expect(f.seen.at(-1).json).toEqual({ query: "fixture", search_type: "news" })
expect(f.seen.at(-1).headers.get("user-agent")).toBe("MiniMaxAgent")
for (const code of [402, "402"]) {
for (const envelope of [{ code, message: "insufficient credits" }, { code, message: "insufficient credits", base_resp: { status_code: 0, status_msg: "success" } }]) {
f.route("POST " + endpoint, () => json(envelope))
await expect(tool.web_search.execute({ query: "fixture" })).rejects.toThrow("insufficient credits")
}
}
f.route("POST " + endpoint, () => json({ code: "0", organic: [] }))
expect(await tool.web_search.execute({ query: "fixture" })).toEqual({ organic: [] })
})
+44
View File
@@ -0,0 +1,44 @@
// MiniMax's native search is separate from the Connector catalog.
const object = (v) => v !== null && typeof v === "object" && !Array.isArray(v)
const schema = (properties, required = []) => ({ type: "object", properties, required, additionalProperties: false })
const string = { type: "string", minLength: 1 }
const sites = ["minimax-code", "minimax-code-global"]
const freshness = ["noLimit", "day", "week", "month", "year"]
const searchTypes = ["search", "videos", "places", "news", "shopping"]
function args(value, allowed) {
if (!object(value)) throw new Error("arguments must be an object")
for (const key of Object.keys(value)) if (!allowed.includes(key)) throw new Error("unknown argument: " + key)
return value
}
function text(value, name) {
if (typeof value !== "string" || !value.trim()) throw new Error(name + " must be a non-empty string")
return value
}
export function createWebTools(request) {
return {
web_search: {
description: "Search the live web through MiniMax Code for facts, news, videos, places and shopping. Return the upstream sources and search metadata. Cite result URLs; use an available webpage-reading tool to read a source page.",
args: schema({
query: { ...string, description: "Search query" },
count: { type: "integer", minimum: 1, description: "Maximum results (server default 10)" },
freshness: { type: "string", enum: freshness },
search_type: { type: "string", enum: searchTypes },
site: { type: "string", enum: sites, default: "minimax-code" },
account: { ...string, description: "Full stored account key for the selected site, such as minimax-code#xxxxxx. Defaults to that site's first stored account." },
}, ["query"]),
async execute(value, ctx = {}) {
const { site = "minimax-code", account, ...input } = args(value, ["query", "count", "freshness", "search_type", "site", "account"])
text(input.query, "query")
if (!sites.includes(site)) throw new Error("unknown MiniMax Code site")
if (account !== undefined) text(account, "account")
if (input.count !== undefined && (!Number.isInteger(input.count) || input.count < 1)) throw new Error("count must be a positive integer")
if (input.freshness !== undefined && !freshness.includes(input.freshness)) throw new Error("invalid freshness")
if (input.search_type !== undefined && !searchTypes.includes(input.search_type)) throw new Error("invalid search_type")
ctx.abort?.throwIfAborted()
const { base_resp, ...payload } = await request(site, "/mavis/api/v1/mcp/web_search", input, { account, signal: ctx.abort, timeoutMs: 120000 })
return payload
},
},
}
}
+27
View File
@@ -0,0 +1,27 @@
import "./nonet.mjs"
import { expect, test } from "bun:test"
import { createWebTools } from "./web-tools.mjs"
test("native search forwards filters and account scope to its separate endpoint", async () => {
const calls = []
const abort = new AbortController().signal
const tools = createWebTools(async (...call) => { calls.push(call); return { base_resp: { status_code: 0 }, organic: [{ title: "Source", url: "https://example.com" }] } })
expect(await tools.web_search.execute({ query: "MiniMax", count: 3, freshness: "week", search_type: "news", site: "minimax-code-global", account: "minimax-code-global#second" }, { abort })).toEqual({ organic: [{ title: "Source", url: "https://example.com" }] })
expect(calls[0]).toEqual(["minimax-code-global", "/mavis/api/v1/mcp/web_search", { query: "MiniMax", count: 3, freshness: "week", search_type: "news" }, { account: "minimax-code-global#second", signal: abort, timeoutMs: 120000 }])
})
test("invalid search arguments and cancellation are caught before network", async () => {
let calls = 0
const tool = createWebTools(async () => { calls++; return {} }).web_search
for (const value of [null, {}, { query: " " }, { query: "x", count: 0 }, { query: "x", count: 1.5 }, { query: "x", freshness: "today" }, { query: "x", search_type: "image" }, { query: "x", site: "bad" }, { query: "x", headers: {} }]) {
await expect(tool.execute(value)).rejects.toThrow()
}
const controller = new AbortController()
controller.abort()
await expect(tool.execute({ query: "x" }, { abort: controller.signal })).rejects.toThrow()
expect(calls).toBe(0)
})
test("native web tools export only search", () => {
expect(Object.keys(createWebTools())).toEqual(["web_search"])
})
+1 -1
View File
@@ -44,7 +44,7 @@
{ "package": "@magpie-community/opencode-kiro-auth", "name": "Kiro", "icon": "kiro-color", "providers": ["kiro"], "community": true, "replaces": "kiro",
"summary": { "en": "Kiro Free, Pro, Pro+ and Power — Kiro's sign-in, kiro-cli's, or an API key.", "zh": "Kiro Free、Pro、Pro+ 与 Power:Kiro 登录、沿用 kiro-cli 的登录,或 API key。" } },
{ "package": "@magpie-community/opencode-minimax-auth", "name": "MiniMax Code", "icon": "minimax-color", "providers": ["minimax-code", "minimax-code-global"], "community": true,
"summary": { "en": "MiniMax Code account credits (daily check-in) and M Plan, with MiniMax Code's own device sign-in.", "zh": "用 MiniMax Code 账号的积分(每日签到)与 M Plan,使用 MiniMax Code 自己的设备登录。" } },
"summary": { "en": "MiniMax Code credits and M Plan with device sign-in, native web search, image/video generation and media tools through Magpie MCP.", "zh": "MiniMax Code 积分与 M Plan、设备登录,提供原生网络搜索、生图、生视频及多模态 MCP 工具。" } },
{ "package": "@magpie-community/opencode-workbuddy-auth", "name": "WorkBuddy", "icon": "workbuddy-color", "providers": ["workbuddy", "workbuddy-ai"], "community": true, "replaces": "workbuddy",
"summary": { "en": "WorkBuddy's China build (CodeBuddy plan) and its international build.", "zh": "WorkBuddy 国内版(CodeBuddy 套餐)与国际版。" } },
{ "package": "@magpie-community/opencode-cline-auth", "name": "Cline", "icon": "cline", "providers": ["cline"], "community": true,