search1api 0.1.3: Search1API as a web search API in Settings (#1219)

search1api 0.1.3 adds Search1API to magpie's Settings as a web search API. A search goes out as the Search1API account magpie picked (OAuth or API key, renewed before each search). The option key or SEARCH1API_API_KEY is used only when the host gives no account. A refusal (401, 402, 429) keeps its status and Retry-After, so magpie rests that account for search only. Results map title, url, snippet and date.

Thanks @fatwang2.

Run at the reviewed head d4bcb9da (mote, HOME=$(mktemp -d)):
- node --test tests/*.test.mjs: 27 pass.
- bun test: 27 pass.
- bun scripts/check.mjs search1api: ok.

Broken by hand: b54f3636c's src/index.ts with this head's tests fails the account-over-option-key test (3 pass, 1 fail). An earlier round with the main code made websearch.test fail 4 of 4.

Not run: tests/host.integration.mjs, or a real Search1API account.
This commit is contained in:
wang2
2026-11-16 19:37:34 +08:00
committed by GitHub
parent bf47b85b56
commit e0369f59ba
9 changed files with 225 additions and 12 deletions
+1
View File
@@ -135,6 +135,7 @@ A tools package can also give magpie a web search API. It is listed in Settings
| Package | Search APIs |
|---|---|
| [search1api](packages/search1api) | Search1API, signed in with the plugin's Search1API OAuth or API key (no key of its own); also gives the tools above |
| [magpie-websearch](https://github.com/guotree/magpie-websearch) | AnySearch, Bocha, Jina, Kagi, Keenable, Linkup, Metaso, Moonshot, Moonshot CN, Ollama, Parallel, Perplexity, Querit, SerpApi, Serper, StepFun, TinyFish, Z.ai and Zhipu; published as `@guotree/magpie-websearch` and maintained in its own repository |
| [magpie-search-mix](https://github.com/mdwsk88/magpie-search-mix) | magpie-search-mix, which asks two (or more) of Tavily, Brave, Exa, Firecrawl, You.com, DeepSeek, Doubao Search, Yuanbao Search and SearXNG at once, the ones you name in its key field, and gives their pages in turn, deduplicated; published as `magpie-search-mix` and maintained in its own repository |
+18 -2
View File
@@ -2,7 +2,7 @@
Search1API web search, news, agentic search, page retrieval, sitemap discovery,
and trending tools in [Magpie](https://usemagpie.ai/), with browser OAuth and
API key sign-in. The source lives in this community repository and is published as
API key sign-in, plus Search1API as a web search API in Magpie's settings. The source lives in this community repository and is published as
`@magpie-community/tools-search1api`. It uses native fetch with no runtime
dependencies; request bodies and defaults match the original integration.
@@ -146,6 +146,22 @@ Automatic request retries are disabled to keep calls within that deadline; OAuth
authentication is retried once after refreshing. Other upstream errors return
to the calling agent.
## Web search for every model
The plugin also adds **Search1API** to Magpie's own web search APIs, in
**Settings → Models → Web search**, after the built-in ones. Magpie uses it
when a model can't search the web itself, and orders, switches off or mixes it
like any other search API there.
It takes no separate key: it searches as the Search1API account you signed in
to above (OAuth or API key), which Magpie renews before each search. An
`apiKey` option or `SEARCH1API_API_KEY` is not used here: a search always
goes out as the account Magpie picked, so a refusal rests that account. Each search
is a Search1API `search` call on Google with up to the number of results
Magpie asks for, without page content. A refused request (401, 402, 429)
keeps its status, so Magpie rests the account for search and asks the next
search API.
## Development
From this folder, on Node 24 or later (or Bun for the tests):
@@ -186,7 +202,7 @@ MAGPIE_BUN_PATH=/path/to/bun npm run test:magpie
```
The migrated integration was verified against Magpie host revision
`8ef9fc578ced531b7ca835a3133c37f608a70e6a`. Live-account OAuth consent still
`261f482260da435ecfa35004649955a5a2f749e9`. Live-account OAuth consent still
requires manual verification on the machine running Magpie.
## Maintenance and license
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/tools-search1api",
"version": "0.1.2",
"version": "0.1.3",
"description": "Search1API web search, news, agentic search, pages, sitemaps and trends for Magpie, with OAuth or API key sign-in",
"type": "module",
"main": "./index.mjs",
+6 -2
View File
@@ -71,12 +71,16 @@ export class Credentials {
throw new Error("Invalid Search1API sign-in. Sign in again in Magpie.");
}
// The plugin option or environment key, which wins over any sign-in.
override(): string | undefined {
return this.options.apiKey?.trim() || process.env.SEARCH1API_API_KEY?.trim() || undefined;
}
async token(
signal?: AbortSignal,
): Promise<{ token: string; oauth?: StoredOAuth }> {
signal?.throwIfAborted();
const override =
this.options.apiKey?.trim() || process.env.SEARCH1API_API_KEY?.trim();
const override = this.override();
if (override) return { token: override };
const auth = await this.stored();
if (auth?.type === "api") return { token: auth.key };
+37 -1
View File
@@ -4,7 +4,7 @@ import { CATEGORIES, DESCRIPTION, feedbackBody } from "./feedback.ts";
import { startOAuth } from "./oauth.ts";
import { AuthenticationError, request } from "./request.ts";
import { filters, maxResults, query, searchBody, validate, type ArgumentsSchema, type Schema } from "./tools.ts";
import { API_BASE, PROVIDER, serviceURL, type Options, type PluginInput, type StoredOAuth } from "./types.ts";
import { API_BASE, PROVIDER, serviceURL, type Options, type PluginInput, type StoredAuth, type StoredOAuth } from "./types.ts";
export const Search1APIPlugin = async (input: PluginInput, options: Options = {}) => {
if (options.apiKey !== undefined && typeof options.apiKey !== "string")
@@ -56,6 +56,39 @@ export const Search1APIPlugin = async (input: PluginInput, options: Options = {}
additionalProperties: false,
};
// magpie's web search (Settings › Models › Web search): the account magpie
// picked, already renewed, comes from ctx.getAuth(). Errors keep their HTTP
// status so magpie rests that account and asks the next search API.
async function webSearch(
{ query, count }: { query?: unknown; count?: unknown },
ctx: { abort: AbortSignal; getAuth?: () => Promise<StoredAuth | undefined> },
) {
if (typeof query !== "string" || !query.trim()) throw new Error("query is required.");
// The account magpie picked is the one sent, so a refusal rests the
// account that was refused. The option or environment key is used only
// where magpie gives no account (a host without getAuth).
let token: string | undefined;
if (ctx.getAuth) {
const auth = await ctx.getAuth();
if (auth?.type === "api" && auth.key) token = auth.key;
else if (auth?.type === "oauth" && auth.access) token = auth.access;
else throw new Error("Not signed in to Search1API.");
}
token ??= (await credentials.token(ctx.abort)).token;
const n = Math.trunc(Number(count));
const result = await request(baseUrl, "search", token, {
query: query.trim(),
search_service: "google",
max_results: n >= 1 ? Math.min(n, 50) : 10,
crawl_results: 0,
}, ctx.abort) as { results?: unknown };
const text = (v: unknown) => (typeof v === "string" ? v : "");
return (Array.isArray(result?.results) ? result.results : [])
.filter((r): r is Record<string, unknown> => !!r && typeof r === "object")
.map((r) => ({ title: text(r.title), url: text(r.link), text: text(r.snippet), age: text(r.published_date) }))
.filter((r) => r.url);
}
return {
config: async (config: { provider?: Record<string, unknown> }) => {
config.provider ??= {};
@@ -72,6 +105,9 @@ export const Search1APIPlugin = async (input: PluginInput, options: Options = {}
refreshLead: 60_000,
refresh: (auth: StoredOAuth) => credentials.renew(auth),
},
search: {
search1api: { name: "Search1API", auth: PROVIDER, execute: webSearch },
},
tool: {
search: tool("search",
"Search the live web for current facts, research, documentation, people, companies and sources. Credit Grokipedia results as Powered by xAI.",
+19 -4
View File
@@ -1,8 +1,19 @@
import { serviceURL, USER_AGENT } from "./types.ts";
export class AuthenticationError extends Error {}
// The status lets magpie's web search rest a refused account (401, 402, 429)
// and try the next search API; the message never carries the response body.
export class APIError extends Error {
status: number;
retryAfter?: string;
constructor(message: string, status: number, retryAfter?: string) {
super(message);
this.status = status;
if (retryAfter) this.retryAfter = retryAfter;
}
}
export class AuthenticationError extends APIError {}
// Only the reviewed endpoints (six tools and feedback) are exposed. Match the original client's
// Only the reviewed endpoints (six tools, web search and feedback) are exposed. Match the original client's
// request bodies and deadlines without adding runtime npm dependencies.
export async function request(
baseUrl: string,
@@ -30,8 +41,12 @@ export async function request(
if (!response.ok) {
// Error bodies can echo credentials. Expose only the endpoint and status.
await response.body?.cancel();
const ErrorType = response.status === 401 ? AuthenticationError : Error;
throw new ErrorType(`Search1API ${name} request failed (${response.status}).`);
const ErrorType = response.status === 401 ? AuthenticationError : APIError;
throw new ErrorType(
`Search1API ${name} request failed (${response.status}).`,
response.status,
response.headers.get("retry-after") ?? undefined,
);
}
try {
return await response.json();
+1 -1
View File
@@ -1,7 +1,7 @@
export const PROVIDER = "search1api";
export const API_BASE = "https://api.search1api.com";
// Identifies Magpie traffic to Search1API; keep in step with package.json.
export const USER_AGENT = "search1api-magpie/0.1.2";
export const USER_AGENT = "search1api-magpie/0.1.3";
export interface StoredOAuth {
type: "oauth";
+40 -1
View File
@@ -72,7 +72,10 @@ async function host(t, f) {
],
});
assert.equal(init.plugins[0].error, undefined, JSON.stringify(init));
assert.equal(init.plugins[0].tools.length, 6);
assert.equal(init.plugins[0].tools.length, 7);
assert.deepEqual(init.plugins[0].searches, [
{ id: "search1api", name: "Search1API", auth: "search1api" },
]);
return rpc;
}
@@ -172,3 +175,39 @@ test(
);
},
);
test(
"actual Magpie Bun host: web search signs in as the saved Search1API account",
{ timeout: 20_000 },
async (t) => {
assert.ok(hostPath, "Set MAGPIE_HOST_PATH.");
const f = await fixture(t);
const rpc = await host(t, f);
const saved = await rpc("apiKey", {
provider: "search1api",
method: 1,
key: "test-search-api-key",
});
assert.equal(saved.ok, true);
const result = await rpc("search", {
spec: "@magpie-community/tools-search1api",
id: "search1api",
query: "Bun",
count: 6,
account: "search1api",
ms: 5000,
});
assert.deepEqual(result.pages, [
{ title: "Example", url: "https://example.com", text: "Result", age: "2026-10-23" },
]);
const call = f.calls.at(-1);
assert.equal(call.path, "/search");
assert.equal(call.headers.authorization, "Bearer test-search-api-key");
assert.deepEqual(JSON.parse(call.raw), {
query: "Bun",
search_service: "google",
max_results: 6,
crawl_results: 0,
});
},
);
@@ -0,0 +1,102 @@
import assert from "node:assert/strict";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import { Search1APIPlugin } from "../index.mjs";
const baseUrl = "https://search1api.invalid";
// Every fetch is replaced: no real API is reached and every credential is synthetic.
async function stub(t, handler) {
const directory = await mkdtemp(join(tmpdir(), "search1api-websearch-test-"));
const originalFetch = globalThis.fetch;
const originalKey = process.env.SEARCH1API_API_KEY;
delete process.env.SEARCH1API_API_KEY;
const calls = [];
globalThis.fetch = async (url, init) => {
const call = { url: String(url), ...init, body: JSON.parse(init.body) };
calls.push(call);
assert.equal(new URL(call.url).origin, baseUrl);
return handler(call);
};
t.after(async () => {
globalThis.fetch = originalFetch;
if (originalKey === undefined) delete process.env.SEARCH1API_API_KEY;
else process.env.SEARCH1API_API_KEY = originalKey;
await rm(directory, { recursive: true, force: true });
});
const save = (auth) => writeFile(join(directory, "plugin-auth.json"), JSON.stringify({ search1api: auth }), { mode: 0o600 });
return { calls, save, input: { directory, client: { auth: { set: async () => {} } } } };
}
const found = () => new Response(JSON.stringify({
results: [
{ title: "Bun 1.3", link: "https://bun.com/blog/bun-v1.3", snippet: "Bun 1.3 adds", published_date: "2025-10-10" },
{ title: "No date", link: "https://example.com/a", snippet: "text" },
{ title: "No link", snippet: "dropped" },
null,
],
}));
const ctx = (auth) => ({ abort: new AbortController().signal, ...(auth && { getAuth: async () => auth }) });
test("web search is one entry that signs in as the plugin's own Search1API provider", async (t) => {
const f = await stub(t, found);
const plugin = await Search1APIPlugin(f.input, { baseUrl });
assert.deepEqual(Object.keys(plugin.search), ["search1api"]);
const entry = plugin.search.search1api;
assert.equal(entry.name, "Search1API");
assert.equal(entry.auth, plugin.auth.provider);
assert.equal(entry.keysURL, undefined);
});
test("web search asks /search with the account magpie chose and maps its pages", async (t) => {
const f = await stub(t, found);
const plugin = await Search1APIPlugin(f.input, { baseUrl });
const pages = await plugin.search.search1api.execute({ query: " bun 1.3 ", count: 6, key: "" }, ctx({ type: "api", key: "account-key" }));
assert.deepEqual(pages, [
{ title: "Bun 1.3", url: "https://bun.com/blog/bun-v1.3", text: "Bun 1.3 adds", age: "2025-10-10" },
{ title: "No date", url: "https://example.com/a", text: "text", age: "" },
]);
assert.equal(f.calls.length, 1);
assert.equal(f.calls[0].url, `${baseUrl}/search`);
assert.equal(f.calls[0].headers.Authorization, "Bearer account-key");
assert.deepEqual(f.calls[0].body, { query: "bun 1.3", search_service: "google", max_results: 6, crawl_results: 0 });
await plugin.search.search1api.execute({ query: "q" }, ctx({ type: "oauth", access: "oauth-access", refresh: "r", expires: Date.now() + 3600_000 }));
assert.equal(f.calls[1].headers.Authorization, "Bearer oauth-access");
assert.equal(f.calls[1].body.max_results, 10);
await plugin.search.search1api.execute({ query: "q", count: 500 }, ctx({ type: "api", key: "k" }));
assert.equal(f.calls[2].body.max_results, 50);
});
test("the account magpie picked is sent even with an option key; without getAuth the saved sign-in is used", async (t) => {
const f = await stub(t, found);
const keyed = await Search1APIPlugin(f.input, { baseUrl, apiKey: "option-key" });
await keyed.search.search1api.execute({ query: "q" }, ctx({ type: "api", key: "account-key" }));
assert.equal(f.calls[0].headers.Authorization, "Bearer account-key");
await assert.rejects(keyed.search.search1api.execute({ query: "q" }, ctx({ type: "wellknown" })), /Not signed in/);
assert.equal(f.calls.length, 1);
await f.save({ type: "api", key: "saved-key" });
const plain = await Search1APIPlugin(f.input, { baseUrl });
await plain.search.search1api.execute({ query: "q" }, ctx());
assert.equal(f.calls[1].headers.Authorization, "Bearer saved-key");
});
test("a refusal keeps its status and Retry-After for magpie, never the body", async (t) => {
let status = 429;
const f = await stub(t, () => new Response(JSON.stringify({ error: "fixture-secret-must-not-leak" }), { status, headers: { "Retry-After": "30" } }));
const plugin = await Search1APIPlugin(f.input, { baseUrl });
for (status of [401, 402, 429, 500]) {
await assert.rejects(plugin.search.search1api.execute({ query: "q" }, ctx({ type: "api", key: "k" })), (error) => {
assert.equal(error.status, status);
assert.equal(error.retryAfter, "30");
assert.doesNotMatch(error.message, /fixture-secret/);
return true;
});
}
await assert.rejects(plugin.search.search1api.execute({ query: " " }, ctx({ type: "api", key: "k" })), /query is required/);
assert.equal(f.calls.length, 4);
});