diff --git a/README.md b/README.md index 0ecf581..6df0902 100644 --- a/README.md +++ b/README.md @@ -108,6 +108,7 @@ These give tools to every agent magpie connects. magpie serves them on its MCP s | Package | Tools | |---|---| | [search1api](packages/search1api) | Web search, news, agentic search, page retrieval, sitemaps and trends, with Search1API OAuth or an API key | +| [specstream](packages/specstream) | `web_search` (live web answers with the source page of each value) and `extract` (page text from up to 20 URLs a call), with a SpecStream API key; also listed under Web search | | [calc](packages/calc) | `eval` exact arithmetic in fractions, `convert` units (data, time, length, mass, angle, temperature), `date` calendar date math across time zones and DST. No network, no key | ```sh diff --git a/packages/specstream/README.md b/packages/specstream/README.md new file mode 100644 index 0000000..2b65da8 --- /dev/null +++ b/packages/specstream/README.md @@ -0,0 +1,18 @@ +# @magpie-community/tools-specstream + +[SpecStream](https://specstream.ai) Search API and Extract API for every agent magpie connects, and as a web search API in Settings > Models > Web search. + +- `web_search`: `GET https://api.specstream.ai/v1/web-search`, $5 per 1,000 searches of up to 10 sources; `count` is sent as `num` (1 to 100), and each started block of 10 more sources adds $0.006 to the call. Returns an answer when the evidence supports one, the rows found with the page each value was read from, and the sources in rank order. +- `extract`: `POST https://api.specstream.ai/v1/extract`, up to 20 URLs a call, $0.80 per 1,000 pages. Returns each page's text as markdown or plain text, with its title and the date it says it was published. A page with no text is not charged. + +```sh +magpie plugin add @magpie-community/tools-specstream +``` + +Set `SPECSTREAM_API_KEY` for the tools (a key from [Agents & API](https://specstream.ai/workspace/agents?tab=keys) in a SpecStream workspace). The web search entry uses only the key magpie keeps for it, asks for the `count` magpie passes, and trims the sources to it. + +A call that succeeds returns `{"data": {...}}`, and one that stops returns `{"error": {"code", "message"}}`. The package reads `data` and, when there is none, raises `error.message` with the HTTP status. A missing or unknown key (401), an empty balance (402) and a spending limit (403) rest the key in magpie's key rotation. SpecStream signals its per-minute limit with 503 and `Retry-After`, not 429, so magpie counts that as a plain failure and asks the next search API; the key is not rested. + +API reference: [search-api.md](https://specstream.ai/docs/search-api.md) and [extract-api.md](https://specstream.ai/docs/extract-api.md); `num` is in [agents.md](https://specstream.ai/agents.md). + +Test: `bun test packages/specstream`. The tests use mocked replies and never call the API. diff --git a/packages/specstream/index.mjs b/packages/specstream/index.mjs new file mode 100644 index 0000000..e72102e --- /dev/null +++ b/packages/specstream/index.mjs @@ -0,0 +1,62 @@ +// SpecStream's Search API and Extract API, as tools for every agent and as a +// web search API in magpie's Settings. The tools read SPECSTREAM_API_KEY; the +// search entry uses the key magpie keeps for it. +import { extract, search } from "./specstream.mjs" + +const envKey = () => { + const k = (process.env.SPECSTREAM_API_KEY || "").trim() + if (!k) throw new Error("SpecStream needs an API key: set SPECSTREAM_API_KEY") + return k +} + +const sources = (data) => + (data.sources || []).map((s) => ({ title: s.title || s.site || s.url, url: s.url, text: s.snippet, age: s.published })) + +export const SpecStreamTools = async () => ({ + tool: { + web_search: { + description: + "Searches the live web with SpecStream and returns an answer when the evidence supports one, the rows found with the page each value was read from, and the sources in rank order.", + args: { + type: "object", + properties: { + query: { type: "string", description: "the question or request in everyday words, 1 to 2,000 characters" }, + count: { type: "number", description: "how many sources to return, 1 to 100 (10 when left out; more than 10 costs more)" }, + }, + required: ["query"], + }, + async execute(args, ctx) { + if (typeof args.query !== "string" || !args.query.trim()) throw new Error("query is a string") + const d = await search({ query: args.query, count: args.count, key: envKey(), signal: ctx?.abort }) + return { answer: d.answer ?? null, rows: d.rows ?? [], sources: d.sources ?? [] } + }, + }, + extract: { + description: + "Reads the main text of up to 20 web pages with SpecStream, as markdown or plain text, with each page's title and the date it says it was published.", + args: { + type: "object", + properties: { + urls: { type: "array", items: { type: "string" }, description: "1 to 20 http or https addresses" }, + format: { type: "string", enum: ["markdown", "text"], description: "markdown (default) or text" }, + }, + required: ["urls"], + }, + async execute(args, ctx) { + const d = await extract({ urls: args.urls, format: args.format, key: envKey(), signal: ctx?.abort }) + return { results: d.results ?? [] } + }, + }, + }, + search: { + specstream: { + name: "SpecStream", + keysURL: "https://specstream.ai/workspace/agents?tab=keys", + async execute({ query, count, key }, ctx) { + const found = sources(await search({ query, count, key, signal: ctx?.abort })) + const n = Math.trunc(Number(count)) + return n >= 1 ? found.slice(0, n) : found + }, + }, + }, +}) diff --git a/packages/specstream/package.json b/packages/specstream/package.json new file mode 100644 index 0000000..939b2bc --- /dev/null +++ b/packages/specstream/package.json @@ -0,0 +1,11 @@ +{ + "name": "@magpie-community/tools-specstream", + "version": "0.1.0", + "description": "SpecStream Search API and Extract API for every agent: live web answers with a source page for each value, and page text from up to 20 URLs a call", + "type": "module", + "main": "./index.mjs", + "files": ["index.mjs", "specstream.mjs", "README.md"], + "keywords": ["magpie", "magpie-tools", "mcp", "opencode", "opencode-plugin", "web-search", "extract", "specstream"], + "license": "MIT", + "repository": { "type": "git", "url": "git+https://github.com/magpie-community/plugins.git", "directory": "packages/specstream" } +} diff --git a/packages/specstream/specstream.mjs b/packages/specstream/specstream.mjs new file mode 100644 index 0000000..3b30394 --- /dev/null +++ b/packages/specstream/specstream.mjs @@ -0,0 +1,45 @@ +// The two SpecStream calls. A reply is {data: {...}}, or {error: {code, message}} when the call stops. +const BASE = "https://api.specstream.ai" + +// Only the key the caller gives: the tools pass SPECSTREAM_API_KEY, the search entry the key magpie keeps. +export const keyOf = (key) => { + const k = typeof key === "string" ? key.trim() : "" + if (!k) throw new Error("SpecStream needs an API key") + return k +} + +// Reads a reply: its `data`, or an error carrying error.message and the HTTP status. +export async function unwrap(r) { + let body = null + try { + body = await r.json() + } catch {} + if (!r.ok || !body || body.data == null) { + const message = body?.error?.message || `SpecStream answered ${r.status}` + throw Object.assign(new Error(message), { status: r.status, code: body?.error?.code }) + } + return body.data +} + +export async function search({ query, count, key, signal }) { + const params = new URLSearchParams({ q: String(query).slice(0, 2000) }) + // num, 1 to 100: how many sources come back (https://specstream.ai/agents.md, "num and page") + const n = Math.trunc(Number(count)) + if (n >= 1) params.set("num", String(Math.min(100, n))) + const r = await fetch(`${BASE}/v1/web-search?${params}`, { + headers: { authorization: `Bearer ${keyOf(key)}` }, + signal, + }) + return unwrap(r) +} + +export async function extract({ urls, format = "markdown", key, signal }) { + if (!Array.isArray(urls) || urls.length < 1 || urls.length > 20) throw new Error("urls is a list of 1 to 20 addresses") + const r = await fetch(`${BASE}/v1/extract`, { + method: "POST", + headers: { authorization: `Bearer ${keyOf(key)}`, "content-type": "application/json" }, + body: JSON.stringify({ urls, format: format === "text" ? "text" : "markdown" }), + signal, + }) + return unwrap(r) +} diff --git a/packages/specstream/specstream.test.mjs b/packages/specstream/specstream.test.mjs new file mode 100644 index 0000000..d56f30f --- /dev/null +++ b/packages/specstream/specstream.test.mjs @@ -0,0 +1,86 @@ +import { expect, test } from "bun:test" +import { SpecStreamTools } from "./index.mjs" + +const { tool, search } = await SpecStreamTools({}) +const ctx = { agent: "test", abort: AbortSignal.timeout(5000) } +const seen = {} +const reply = (status, body) => async (url, init) => { + seen.url = String(url) + seen.init = init + return new Response(JSON.stringify(body), { status }) +} +const withFetch = async (impl, fn) => { + const real = globalThis.fetch + globalThis.fetch = impl + process.env.SPECSTREAM_API_KEY = "sk_test" + try { + return await fn() + } finally { + globalThis.fetch = real + } +} + +test("offers both tools and the search hook", () => { + expect(Object.keys(tool).sort()).toEqual(["extract", "web_search"]) + for (const t of Object.values(tool)) expect(t.args.type).toBe("object") + expect(typeof search.specstream.execute).toBe("function") +}) + +test("web_search reads data", async () => { + const body = { data: { answer: { value: "Paris" }, rows: [], sources: [{ url: "https://a.test", title: "A" }] } } + const out = await withFetch(reply(200, body), () => tool.web_search.execute({ query: "capital of France", count: 5 }, ctx)) + expect(out.answer.value).toBe("Paris") + expect(out.sources[0].url).toBe("https://a.test") + expect(seen.url).toContain("/v1/web-search?q=capital+of+France&num=5") + expect(seen.init.headers.authorization).toBe("Bearer sk_test") +}) + +test("the search hook gives title, url, text", async () => { + const body = { data: { sources: [{ url: "https://a.test", title: "A", snippet: "s", published: "2026-01-01" }] } } + const out = await withFetch(reply(200, body), () => search.specstream.execute({ query: "x", count: 3, key: "k" }, ctx)) + expect(out).toEqual([{ title: "A", url: "https://a.test", text: "s", age: "2026-01-01" }]) + expect(seen.init.headers.authorization).toBe("Bearer k") +}) + +test("the search hook trims the sources to count", async () => { + const body = { data: { sources: [1, 2, 3].map((i) => ({ url: `https://${i}.test`, title: String(i) })) } } + const out = await withFetch(reply(200, body), () => search.specstream.execute({ query: "x", count: 2, key: "k" }, ctx)) + expect(out.map((s) => s.title)).toEqual(["1", "2"]) + expect(seen.url).toEndWith("?q=x&num=2") +}) + +test("a count that is no number sends no num", async () => { + const body = { data: { sources: [{ url: "https://a.test", title: "A" }] } } + for (const count of ["many", NaN, 0, undefined]) { + const out = await withFetch(reply(200, body), () => search.specstream.execute({ query: "x", count, key: "k" }, ctx)) + expect(out.length).toBe(1) + expect(seen.url).toEndWith("/v1/web-search?q=x") + } +}) + +test("the search hook uses only the key magpie gives", async () => { + let asked = false + const impl = async () => ((asked = true), new Response("{}")) + await expect(withFetch(impl, () => search.specstream.execute({ query: "x" }, ctx))).rejects.toThrow("needs an API key") + expect(asked).toBe(false) +}) + +test("extract posts the urls and reads data.results", async () => { + const body = { data: { results: [{ url: "https://a.test", status: "ok", text: "hello" }] } } + const out = await withFetch(reply(200, body), () => tool.extract.execute({ urls: ["https://a.test"], format: "text" }, ctx)) + expect(out.results[0].text).toBe("hello") + expect(JSON.parse(seen.init.body)).toEqual({ urls: ["https://a.test"], format: "text" }) +}) + +test("an error reply raises error.message with the status", async () => { + const body = { error: { code: "insufficient_balance", message: "Balance is empty" } } + const err = await withFetch(reply(402, body), () => search.specstream.execute({ query: "x", key: "k" }, ctx)).catch((e) => e) + expect(err.message).toBe("Balance is empty") + expect(err.status).toBe(402) +}) + +test("extract refuses more than 20 urls and a missing key", async () => { + await expect(tool.extract.execute({ urls: Array(21).fill("https://a.test") }, ctx)).rejects.toThrow("1 to 20") + delete process.env.SPECSTREAM_API_KEY + await expect(tool.web_search.execute({ query: "x" }, ctx)).rejects.toThrow("SPECSTREAM_API_KEY") +}) diff --git a/registry.json b/registry.json index baa9155..60a8692 100644 --- a/registry.json +++ b/registry.json @@ -139,6 +139,8 @@ "summary": { "en": "Mixes the search APIs you name in its key field (Tavily, Brave, Exa, Firecrawl, You.com, DeepSeek, Doubao Search, Yuanbao Search, SearXNG): asks two at once, a failing one replaced by the next, and gives their pages in turn, deduplicated.", "zh": "混合搜索:从你在密钥栏里指定的搜索 API(Tavily、Brave、Exa、Firecrawl、You.com、DeepSeek、豆包搜索、元宝搜索、SearXNG)中同时问两家,失败的由下一家顶上,结果去重后交替合并。" } }, { "package": "magpie-comfyui-link", "name": "ComfyUI", "kind": "tools", "community": true, "summary": { "en": "A bridge between Magpie agents and locally hosted ComfyUI models, exposing native workflows, model resources and generated images through Magpie's tools MCP endpoint.", "zh": "连接 Magpie Agent 与本地 ComfyUI 模型的桥接层,通过 Magpie 工具 MCP 入口提供原生工作流、模型资源和生成图片。" } }, + { "package": "@magpie-community/tools-specstream", "name": "SpecStream", "kind": "tools", "community": true, + "summary": { "en": "SpecStream web search and page extraction for every agent: answers with the source page of each value, and the text of up to 20 URLs a call. Needs a SpecStream API key.", "zh": "给每个 agent 的 SpecStream 网页搜索和网页提取:每个值都带来源页面,一次最多读取 20 个网址的正文。需要 SpecStream API key。" } }, { "package": "@magpie-community/tools-calc", "name": "Calc", "kind": "tools", "community": true, "summary": { "en": "Exact arithmetic, unit conversion and calendar date math as tools for every agent: no network, no key.", "zh": "给每个 agent 的精确计算、单位换算和日历日期计算工具:不联网,不需要 key。" } }, {"package": "@magpie-community/tools-layerfs", "name": "LayerFS", "kind": "tools", "community": true, "summary": {"en": "LayerFS workspaces for every agent: deduplicated checkpoints and branches behind stable filesystem paths, instead of a fresh copy of the tree for every agent.", "zh": "给每个 agent 的 LayerFS 工作区:稳定的文件系统路径背后是可去重的检查点与分支,而不是每个 agent 各复制一棵项目树。"}},