search1api 0.1.0: Search1API's six tools with API key or OAuth sign-in (#384)
Adds packages/search1api as @magpie-community/tools-search1api 0.1.0
(fatwang2, replacing #340). It has six tools: search, news, ask, crawl,
sitemap and trending. Sign-in is one account by API key or OAuth: PKCE
S256, dynamic client registration and a loopback callback. Tokens refresh
through auth.refresh and on a 401. scripts/check.mjs now accepts a tools
plugin with auth and no loader, as long as its config gives the provider
no npm and no models.
Run at 7cf6a5c merged onto main, in a sandbox HOME, with HTTPS_PROXY
pointed at a dead port:
- bun test packages/search1api scripts/check.test.mjs: 19 pass.
- node --test on the package's own tests: 16 pass.
- tests/host.integration.mjs against main magpie's host.js: 2 pass.
- bun test across the whole repo: 2647 pass, 0 fail. This needs 017f05c.
Before it, gcp-ai's fetch guard refused this package's loopback
fixtures in the shared bun process.
- bun scripts/check.mjs: all ok.
Broken by hand, each one red:
- Dropping the SAME_SESSION check before a refresh: 1 test.
- Never refreshing an expired token: 3 tests.
- Ignoring the apiKey option: 4 tests.
- Not red: dropping the second check, which catches a logout during an
in-flight refresh. The first check covers it in the logout test.
Real use:
- A sandbox magpie took the package with `plugin add`. `plugin list`
shows its 6 tools. `plugin login search1api 2` with a key showed
Providers as "Search1API · signed in as API key …-384 · no models
exposed".
- The search tool ran against the real api.search1api.com with a fake
key and got 401.
- OAuth discovery is live: oauth-protected-resource points to
clerk.s1.dev, which has a registration endpoint and S256.
Not tried:
- A real OAuth consent, or a search with a real key. There is no
Search1API account here.
Notes:
- The plugin reads the signed-in record from
`<directory>/plugin-auth.json` itself, since tools get no getAuth.
magpie writes that file by temp-and-rename, so a read never sees half a
write.
- magpie's login line says "its models are search1api/<model>" for a
provider with no models. That is magpie's wording, not this PR's.
This commit is contained in:
@@ -89,6 +89,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 |
|
||||
| [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
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
dist/
|
||||
node_modules
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Search1API
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,189 @@
|
||||
# Search1API for Magpie
|
||||
|
||||
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
|
||||
`@magpie-community/tools-search1api`. It uses native fetch with no runtime
|
||||
dependencies; request bodies and defaults match the original integration.
|
||||
|
||||
## Install
|
||||
|
||||
In Magpie, open **Plugins → Add plugin** and enter:
|
||||
|
||||
```text
|
||||
@magpie-community/tools-search1api
|
||||
```
|
||||
|
||||
Or use the terminal:
|
||||
|
||||
```sh
|
||||
magpie plugin add @magpie-community/tools-search1api
|
||||
```
|
||||
|
||||
The package includes its TypeScript source and an `index.mjs` entry. Magpie's
|
||||
Bun host loads it directly; installation and community packaging need no build.
|
||||
|
||||
## Sign in
|
||||
|
||||
### OAuth (recommended)
|
||||
|
||||
Choose **Search1API → Sign in to Search1API** in the plugin's sign-in controls,
|
||||
or run:
|
||||
|
||||
```sh
|
||||
magpie plugin login search1api oauth
|
||||
```
|
||||
|
||||
Magpie opens your browser. Sign in with your Search1API account and approve
|
||||
access, then return to Magpie. The plugin uses a dynamically registered public
|
||||
OAuth client, authorization code flow with PKCE S256, and a temporary loopback
|
||||
callback. No client secret or Search1API CLI is required.
|
||||
|
||||
The browser must run on the same computer as Magpie. For a remote or container
|
||||
installation, use an API key instead. The callback expires after five minutes.
|
||||
|
||||
Magpie saves access and refresh tokens in `plugin-auth.json` under its config
|
||||
directory (`~/.config/magpie`, or `$XDG_CONFIG_HOME/magpie`) with file mode
|
||||
`0600`. The plugin reads only its own `search1api` entry and saves refreshed
|
||||
tokens through Magpie's `client.auth.set`; it does not maintain a second token
|
||||
store. Tool calls refresh expiring tokens and retry once after an OAuth `401`.
|
||||
Refreshes are serialized across simultaneous calls and Magpie processes.
|
||||
|
||||
Search1API appears as a sign-in entry with **no chat models**. It authenticates
|
||||
the tools, not a model provider. One Search1API account is active at a time;
|
||||
signing in again replaces it.
|
||||
|
||||
To remove the saved sign-in:
|
||||
|
||||
```sh
|
||||
magpie plugin logout search1api
|
||||
```
|
||||
|
||||
This removes the local credentials. It does not revoke an authorization at the
|
||||
authorization server or remove API keys configured separately below.
|
||||
|
||||
### API key
|
||||
|
||||
Choose **Search1API API key** in the same sign-in controls, or run:
|
||||
|
||||
```sh
|
||||
magpie plugin login search1api api
|
||||
```
|
||||
|
||||
Magpie prompts privately for the key and saves it in its credential store.
|
||||
Get a key at [s1.dev](https://s1.dev/).
|
||||
|
||||
For automated deployments, the plugin also accepts an `apiKey` plugin option
|
||||
in Magpie's options editor, or `SEARCH1API_API_KEY` in the environment of the
|
||||
Magpie process. Precedence: plugin option → environment → Magpie sign-in.
|
||||
An option or environment key overrides a saved OAuth account. `SEARCH1API_KEY`
|
||||
and the CLI's `s1 login` session are not read.
|
||||
|
||||
`baseUrl` is an optional API base URL for a compatible deployment or local
|
||||
testing. It defaults to `https://api.search1api.com`. HTTPS is required, except
|
||||
for loopback test servers. OAuth discovery uses that API's protected-resource
|
||||
metadata and validates the issuer and endpoints.
|
||||
|
||||
## Connect your agent
|
||||
|
||||
In **Settings → Plugins**, copy the plugin tools MCP address, then add it to
|
||||
your agent's MCP configuration. The default address is:
|
||||
|
||||
```text
|
||||
http://127.0.0.1:3425/mcp/magpie/tools
|
||||
```
|
||||
|
||||
For Claude Code:
|
||||
|
||||
```sh
|
||||
claude mcp add --transport http magpie-tools \
|
||||
http://127.0.0.1:3425/mcp/magpie/tools
|
||||
```
|
||||
|
||||
Other agents use the same Streamable HTTP endpoint. Use the address Magpie
|
||||
shows if the port or host differs. Remote calls require a Magpie gateway key;
|
||||
this is separate from your Search1API credential.
|
||||
|
||||
Installing the plugin does not write your agent's MCP configuration or replace
|
||||
its built-in search tool. Magpie exposes tools from all enabled tool plugins
|
||||
on this endpoint.
|
||||
|
||||
## Tools
|
||||
|
||||
Magpie prefixes each tool with the plugin name. Use the names reported by
|
||||
your Magpie tools endpoint.
|
||||
|
||||
- `search`: web search, engine selection, site filters, date range and native
|
||||
pagination. Page selection works on engines that support it.
|
||||
- `news`: news search with optional article content.
|
||||
- `ask`: describe what to find; Search1API chooses engines and a time window
|
||||
and returns ranked results. Each completed call costs **5 credits**. It
|
||||
returns search results rather than a generated answer.
|
||||
- `crawl`: retrieve readable page content.
|
||||
- `sitemap`: discover site links.
|
||||
- `trending`: GitHub or Hacker News trends.
|
||||
|
||||
Tool parameters follow the existing OpenCode integration. Search and news
|
||||
preserve optional `published_date` and per-result `metadata`; Ask preserves
|
||||
`intent`, `source`, `relevance`, and `errors`. Attribute Grokipedia results as
|
||||
“Powered by xAI”. Results are returned as JSON text.
|
||||
|
||||
Magpie gives tools a 55-second deadline. Cancellation is forwarded to fetch.
|
||||
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.
|
||||
|
||||
## Development
|
||||
|
||||
From this folder, on Node 24 or later (or Bun for the tests):
|
||||
|
||||
```sh
|
||||
npm install --workspaces=false --ignore-scripts --package-lock=false
|
||||
npm run lint
|
||||
npm run typecheck
|
||||
npm run build
|
||||
npm test
|
||||
npm pack --dry-run --ignore-scripts
|
||||
```
|
||||
|
||||
The TypeScript build is a local verification artifact in `dist/`; the published
|
||||
package contains the reviewed source. `lint` checks the entry syntax and runs
|
||||
the strict TypeScript checks (including unused code and switch fallthrough).
|
||||
|
||||
From the repository root, run the same checks as community CI with a temporary
|
||||
home, as documented in `.github/workflows/pr.yml`:
|
||||
|
||||
```sh
|
||||
bun test
|
||||
bun scripts/check.mjs
|
||||
```
|
||||
|
||||
The fetch-stub tests replace every fetch with synthetic responses, covering
|
||||
all six wire bodies, defaults, validation, safe errors, OAuth discovery,
|
||||
refresh/retry limits and cancellation. Local loopback fixtures additionally
|
||||
exercise PKCE browser callbacks, key precedence, concurrent refreshes and
|
||||
logout without real accounts or paid API calls.
|
||||
|
||||
An optional integration test uses Magpie's actual Bun plugin host and the same
|
||||
local fixture. It is outside the default test filename pattern:
|
||||
|
||||
```sh
|
||||
MAGPIE_HOST_PATH=/path/to/magpie/internal/plugin/host.js \
|
||||
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
|
||||
requires manual verification on the machine running Magpie.
|
||||
|
||||
## Maintenance and license
|
||||
|
||||
Migrated from [Search1API for Magpie v0.1.0](https://github.com/superagents-lab/magpie-search1api/tree/v0.1.0),
|
||||
commit `89b9cd5fd1c1c105d603768c14404873d697941f`, under MIT. The original
|
||||
Search1API copyright and license are retained in `LICENSE`.
|
||||
|
||||
This replaces the external-package listing proposed in
|
||||
[#340](https://github.com/magpie-community/plugins/pull/340). Source changes
|
||||
are reviewed here and published by `@magpie-community` through this
|
||||
repository's existing publishing workflow; see the root README. This package
|
||||
does not publish from the original repository's release workflow.
|
||||
@@ -0,0 +1,2 @@
|
||||
// Bun loads the reviewed TypeScript source directly; packing needs no build.
|
||||
export { Search1APIPlugin } from "./src/index.ts";
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "@magpie-community/tools-search1api",
|
||||
"version": "0.1.0",
|
||||
"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",
|
||||
"files": ["index.mjs", "src", "README.md", "LICENSE"],
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/magpie-community/plugins.git",
|
||||
"directory": "packages/search1api"
|
||||
},
|
||||
"keywords": ["magpie", "magpie-tools", "opencode-plugin", "mcp", "search1api", "web-search", "oauth"],
|
||||
"scripts": {
|
||||
"lint": "node --check index.mjs && tsc -p tsconfig.json --noEmit",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"test": "node --test tests/*.test.mjs",
|
||||
"test:magpie": "node --test tests/host.integration.mjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
"typescript": "^5.9.0"
|
||||
},
|
||||
"engines": { "node": ">=24" }
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdir, open, readFile, stat, unlink } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
import { refreshToken } from "./oauth.ts";
|
||||
import {
|
||||
PROVIDER,
|
||||
type Options,
|
||||
type PluginInput,
|
||||
type StoredAuth,
|
||||
type StoredOAuth,
|
||||
} from "./types.ts";
|
||||
|
||||
const REFRESH_LEAD = 60_000;
|
||||
const SAME_SESSION = (a: StoredOAuth, b: StoredOAuth) =>
|
||||
a.access === b.access && a.refresh === b.refresh;
|
||||
const missing = () =>
|
||||
new Error(
|
||||
"Sign in with `magpie plugin login search1api`, configure apiKey in plugin options, or set SEARCH1API_API_KEY.",
|
||||
);
|
||||
|
||||
export class Credentials {
|
||||
private readonly authPath: string;
|
||||
private readonly lockPath: string;
|
||||
private input: PluginInput;
|
||||
private options: Options;
|
||||
constructor(input: PluginInput, options: Options) {
|
||||
this.input = input;
|
||||
this.options = options;
|
||||
this.authPath = join(input.directory, "plugin-auth.json");
|
||||
this.lockPath = join(input.directory, "search1api-refresh.lock");
|
||||
}
|
||||
|
||||
async stored(): Promise<StoredAuth | undefined> {
|
||||
let raw: string;
|
||||
try {
|
||||
raw = await readFile(this.authPath, "utf8");
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
|
||||
throw error;
|
||||
}
|
||||
let value: unknown;
|
||||
try {
|
||||
value = JSON.parse(raw);
|
||||
} catch {
|
||||
throw new Error(
|
||||
"Magpie's plugin-auth.json cannot be read. Restore it before signing in again.",
|
||||
);
|
||||
}
|
||||
if (!value || typeof value !== "object" || Array.isArray(value))
|
||||
throw new Error("Magpie's plugin-auth.json is invalid.");
|
||||
const auth = (value as Record<string, unknown>)[PROVIDER];
|
||||
if (!auth) return undefined;
|
||||
if (typeof auth !== "object")
|
||||
throw new Error("Invalid Search1API sign-in. Sign in again in Magpie.");
|
||||
const a = auth as StoredAuth;
|
||||
if (a.type === "api" && typeof a.key === "string" && a.key) return a;
|
||||
if (
|
||||
a.type === "oauth" &&
|
||||
typeof a.access === "string" &&
|
||||
a.access &&
|
||||
typeof a.refresh === "string" &&
|
||||
typeof a.expires === "number" &&
|
||||
Number.isFinite(a.expires) &&
|
||||
typeof a.clientId === "string" &&
|
||||
typeof a.tokenEndpoint === "string" &&
|
||||
typeof a.issuer === "string"
|
||||
)
|
||||
return a;
|
||||
throw new Error("Invalid Search1API sign-in. Sign in again in Magpie.");
|
||||
}
|
||||
|
||||
async token(
|
||||
signal?: AbortSignal,
|
||||
): Promise<{ token: string; oauth?: StoredOAuth }> {
|
||||
signal?.throwIfAborted();
|
||||
const override =
|
||||
this.options.apiKey?.trim() || process.env.SEARCH1API_API_KEY?.trim();
|
||||
if (override) return { token: override };
|
||||
const auth = await this.stored();
|
||||
if (auth?.type === "api") return { token: auth.key };
|
||||
if (auth?.type !== "oauth") throw missing();
|
||||
const oauth =
|
||||
auth.expires > 0 && auth.expires - REFRESH_LEAD <= Date.now()
|
||||
? await this.renew(auth, signal)
|
||||
: auth;
|
||||
return { token: oauth.access, oauth };
|
||||
}
|
||||
|
||||
// A separate lock serializes both tool-triggered and native auth.refresh
|
||||
// across Magpie's CLI, gateway and overlapping plugin-host restarts.
|
||||
private async lock(signal?: AbortSignal): Promise<() => Promise<void>> {
|
||||
await mkdir(this.input.directory, { recursive: true });
|
||||
const owner = JSON.stringify({ pid: process.pid, id: randomUUID() });
|
||||
const started = Date.now();
|
||||
while (true) {
|
||||
signal?.throwIfAborted();
|
||||
try {
|
||||
const handle = await open(this.lockPath, "wx", 0o600);
|
||||
try {
|
||||
await handle.writeFile(owner);
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
return async () => {
|
||||
try {
|
||||
if ((await readFile(this.lockPath, "utf8")) === owner)
|
||||
await unlink(this.lockPath);
|
||||
} catch {}
|
||||
};
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
||||
}
|
||||
try {
|
||||
const raw = await readFile(this.lockPath, "utf8");
|
||||
const age = Date.now() - (await stat(this.lockPath)).mtimeMs;
|
||||
let dead = false;
|
||||
try {
|
||||
const holder = JSON.parse(raw);
|
||||
if (Number.isInteger(holder.pid) && holder.pid > 0) {
|
||||
try {
|
||||
process.kill(holder.pid, 0);
|
||||
} catch (error) {
|
||||
dead = (error as NodeJS.ErrnoException).code === "ESRCH";
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
if (
|
||||
(dead || age > 60_000) &&
|
||||
(await readFile(this.lockPath, "utf8")) === raw
|
||||
) {
|
||||
await unlink(this.lockPath);
|
||||
continue;
|
||||
}
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
||||
}
|
||||
if (Date.now() - started > 20_000)
|
||||
throw new Error("Search1API session refresh is busy. Retry shortly.");
|
||||
await delay(25, undefined, { signal });
|
||||
}
|
||||
}
|
||||
|
||||
async renew(was: StoredOAuth, signal?: AbortSignal): Promise<StoredOAuth> {
|
||||
const unlock = await this.lock(signal);
|
||||
try {
|
||||
const now = await this.stored();
|
||||
if (now?.type !== "oauth") throw missing();
|
||||
if (!SAME_SESSION(now, was)) return now;
|
||||
const next = await refreshToken(now, signal);
|
||||
// A logout or a new login while the network request was in flight wins.
|
||||
const current = await this.stored();
|
||||
if (current?.type !== "oauth") throw missing();
|
||||
if (!SAME_SESSION(current, now)) return current;
|
||||
await this.input.client.auth.set({ path: { id: PROVIDER }, body: next });
|
||||
return next;
|
||||
} finally {
|
||||
await unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { Credentials } from "./auth.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";
|
||||
|
||||
export const Search1APIPlugin = async (input: PluginInput, options: Options = {}) => {
|
||||
if (options.apiKey !== undefined && typeof options.apiKey !== "string")
|
||||
throw new Error("apiKey must be a string.");
|
||||
const baseUrl = serviceURL(options.baseUrl ?? API_BASE).href.replace(/\/$/, "");
|
||||
const credentials = new Credentials(input, options);
|
||||
|
||||
function tool(
|
||||
name: string,
|
||||
description: string,
|
||||
properties: Record<string, Schema>,
|
||||
required: string[],
|
||||
body: (args: Record<string, unknown>) => Record<string, unknown>,
|
||||
) {
|
||||
const args: ArgumentsSchema = { type: "object", properties, required, additionalProperties: false };
|
||||
return {
|
||||
description,
|
||||
args,
|
||||
async execute(value: unknown, ctx: { abort: AbortSignal }) {
|
||||
const payload = body(validate(args, value));
|
||||
const signal = ctx.abort;
|
||||
let auth = await credentials.token(signal);
|
||||
signal.throwIfAborted();
|
||||
let result: unknown;
|
||||
try {
|
||||
result = await request(baseUrl, name, auth.token, payload, signal);
|
||||
} catch (error) {
|
||||
if (!(error instanceof AuthenticationError) || !auth.oauth) throw error;
|
||||
const renewed = await credentials.renew(auth.oauth, signal);
|
||||
auth = { token: renewed.access, oauth: renewed };
|
||||
result = await request(baseUrl, name, auth.token, payload, signal);
|
||||
}
|
||||
return JSON.stringify(result, null, 2);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
config: async (config: { provider?: Record<string, unknown> }) => {
|
||||
config.provider ??= {};
|
||||
// This entry supplies sign-in, not chat models.
|
||||
config.provider[PROVIDER] ??= { name: "Search1API", models: {} };
|
||||
},
|
||||
auth: {
|
||||
provider: PROVIDER,
|
||||
single: true,
|
||||
methods: [
|
||||
{ type: "oauth" as const, label: "Sign in to Search1API", authorize: () => startOAuth(baseUrl) },
|
||||
{ type: "api" as const, label: "Search1API API key" },
|
||||
],
|
||||
refreshLead: 60_000,
|
||||
refresh: (auth: StoredOAuth) => credentials.renew(auth),
|
||||
},
|
||||
tool: {
|
||||
search: tool("search",
|
||||
"Search the live web for current facts, research, documentation, people, companies and sources. Credit Grokipedia results as Powered by xAI.",
|
||||
{ query, ...filters,
|
||||
searchService: { type: "string", enum: ["google", "bing", "bingcn", "duckduckgo", "yahoo", "yandex", "x", "reddit", "github", "youtube", "arxiv", "wechat", "bilibili", "imdb", "wikipedia", "grokipedia", "baidu", "360", "quark"] },
|
||||
page: { type: "integer", minimum: 1, maximum: 100 },
|
||||
}, ["query"], (args) => searchBody(args, "google")),
|
||||
news: tool("news",
|
||||
"Search current news and optionally retrieve full article content.",
|
||||
{ query, ...filters, searchService: { type: "string", enum: ["google", "bing", "duckduckgo", "yahoo", "hackernews", "reuters"] } },
|
||||
["query"], (args) => searchBody(args, "bing")),
|
||||
ask: tool("ask",
|
||||
"Describe what to find in natural language. Search1API chooses engines and a time window and returns results ranked by relevance. Costs 5 credits; returns search results rather than a generated answer.",
|
||||
{ query: { ...query, maxLength: 500 } }, ["query"], ({ query }) => ({ query })),
|
||||
crawl: tool("crawl", "Retrieve clean readable content from a public URL.",
|
||||
{ url: { type: "string", format: "uri" } }, ["url"], ({ url }) => ({ url })),
|
||||
sitemap: tool("sitemap", "Discover links related to a public URL or domain.",
|
||||
{ url: { type: "string", format: "uri" } }, ["url"], ({ url }) => ({ url })),
|
||||
trending: tool("trending", "Find trending repositories on GitHub or stories on Hacker News.",
|
||||
{ service: { type: "string", enum: ["github", "hackernews"] }, maxResults },
|
||||
["service"], ({ service, maxResults }) => ({ search_service: service, max_results: maxResults ?? 10 })),
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,290 @@
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { createServer } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { serviceURL, type StoredOAuth } from "./types.ts";
|
||||
|
||||
const SCOPES = "openid profile email offline_access";
|
||||
const NETWORK_TIMEOUT = 15_000;
|
||||
const LOGIN_TIMEOUT = 5 * 60_000;
|
||||
|
||||
interface Metadata {
|
||||
issuer: string;
|
||||
authorization_endpoint: string;
|
||||
token_endpoint: string;
|
||||
registration_endpoint: string;
|
||||
code_challenge_methods_supported?: string[];
|
||||
}
|
||||
interface Tokens {
|
||||
access_token: string;
|
||||
refresh_token?: string;
|
||||
expires_in?: number;
|
||||
token_type?: string;
|
||||
}
|
||||
|
||||
async function json<T>(url: string, init: RequestInit = {}): Promise<T> {
|
||||
const timeout = AbortSignal.timeout(NETWORK_TIMEOUT);
|
||||
const response = await fetch(serviceURL(url), {
|
||||
...init,
|
||||
signal: init.signal ? AbortSignal.any([init.signal, timeout]) : timeout,
|
||||
});
|
||||
if (!response.ok) {
|
||||
// Never surface response bodies: token errors can contain private data.
|
||||
const expired = response.status === 400 || response.status === 401;
|
||||
throw Object.assign(
|
||||
new Error(
|
||||
`Search1API OAuth request failed (${response.status}). Sign in again if access was revoked.`,
|
||||
),
|
||||
expired ? { signIn: "expired" } : {},
|
||||
);
|
||||
}
|
||||
return (await response.json()) as T;
|
||||
}
|
||||
|
||||
export async function discover(baseUrl: string): Promise<Metadata> {
|
||||
const resource = await json<{ authorization_servers?: string[] }>(
|
||||
`${baseUrl}/.well-known/oauth-protected-resource`,
|
||||
);
|
||||
const issuer = resource.authorization_servers?.[0];
|
||||
if (!issuer)
|
||||
throw new Error(
|
||||
"Search1API did not advertise an OAuth authorization server.",
|
||||
);
|
||||
const issuerURL = serviceURL(issuer);
|
||||
const discoveryURL = new URL(issuerURL);
|
||||
discoveryURL.pathname = `/.well-known/oauth-authorization-server${issuerURL.pathname.replace(/\/$/, "")}`;
|
||||
const metadata = await json<Metadata>(discoveryURL.href);
|
||||
if (metadata.issuer?.replace(/\/$/, "") !== issuer.replace(/\/$/, ""))
|
||||
throw new Error("OAuth issuer mismatch.");
|
||||
for (const endpoint of [
|
||||
metadata.authorization_endpoint,
|
||||
metadata.token_endpoint,
|
||||
metadata.registration_endpoint,
|
||||
]) {
|
||||
if (!endpoint || serviceURL(endpoint).origin !== issuerURL.origin)
|
||||
throw new Error("Invalid Search1API OAuth endpoint.");
|
||||
}
|
||||
if (!metadata.code_challenge_methods_supported?.includes("S256"))
|
||||
throw new Error("Search1API OAuth requires PKCE S256.");
|
||||
return metadata;
|
||||
}
|
||||
|
||||
function credential(
|
||||
tokens: Tokens,
|
||||
clientId: string,
|
||||
metadata: Pick<Metadata, "issuer" | "token_endpoint">,
|
||||
priorRefresh = "",
|
||||
): StoredOAuth {
|
||||
if (
|
||||
typeof tokens.access_token !== "string" ||
|
||||
!tokens.access_token ||
|
||||
(tokens.token_type && tokens.token_type.toLowerCase() !== "bearer")
|
||||
) {
|
||||
throw new Error("Search1API OAuth returned an invalid access token.");
|
||||
}
|
||||
if (
|
||||
tokens.expires_in !== undefined &&
|
||||
(!Number.isFinite(tokens.expires_in) || tokens.expires_in <= 0)
|
||||
) {
|
||||
throw new Error("Search1API OAuth returned an invalid token lifetime.");
|
||||
}
|
||||
return {
|
||||
type: "oauth",
|
||||
access: tokens.access_token,
|
||||
refresh: tokens.refresh_token ?? priorRefresh,
|
||||
expires: tokens.expires_in ? Date.now() + tokens.expires_in * 1000 : 0,
|
||||
clientId,
|
||||
tokenEndpoint: metadata.token_endpoint,
|
||||
issuer: metadata.issuer,
|
||||
};
|
||||
}
|
||||
|
||||
export async function refreshToken(
|
||||
auth: StoredOAuth,
|
||||
signal?: AbortSignal,
|
||||
): Promise<StoredOAuth> {
|
||||
if (!auth.refresh)
|
||||
throw Object.assign(
|
||||
new Error("Search1API session expired. Sign in again in Magpie."),
|
||||
{ signIn: "expired" },
|
||||
);
|
||||
const issuer = serviceURL(auth.issuer);
|
||||
if (serviceURL(auth.tokenEndpoint).origin !== issuer.origin)
|
||||
throw new Error("OAuth token endpoint does not match its issuer.");
|
||||
const tokens = await json<Tokens>(auth.tokenEndpoint, {
|
||||
method: "POST",
|
||||
signal,
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams({
|
||||
grant_type: "refresh_token",
|
||||
refresh_token: auth.refresh,
|
||||
client_id: auth.clientId,
|
||||
}),
|
||||
});
|
||||
return credential(
|
||||
tokens,
|
||||
auth.clientId,
|
||||
{ issuer: auth.issuer, token_endpoint: auth.tokenEndpoint },
|
||||
auth.refresh,
|
||||
);
|
||||
}
|
||||
|
||||
export async function startOAuth(baseUrl: string, timeoutMs = LOGIN_TIMEOUT) {
|
||||
const metadata = await discover(baseUrl);
|
||||
const state = randomBytes(32).toString("base64url");
|
||||
const verifier = randomBytes(48).toString("base64url");
|
||||
const challenge = createHash("sha256").update(verifier).digest("base64url");
|
||||
let settle!: (value: { code?: string; error?: string }) => void;
|
||||
const result = new Promise<{ code?: string; error?: string }>((resolve) => {
|
||||
settle = resolve;
|
||||
});
|
||||
let accepted = false;
|
||||
const server = createServer((req, res) => {
|
||||
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
||||
res.setHeader("Content-Type", "text/plain; charset=utf-8");
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
res.setHeader("X-Content-Type-Options", "nosniff");
|
||||
if (req.method !== "GET" || url.pathname !== "/callback") {
|
||||
res.writeHead(404).end("Not found.");
|
||||
return;
|
||||
}
|
||||
// A stray request must not cancel the legitimate browser login.
|
||||
if (url.searchParams.get("state") !== state) {
|
||||
res.writeHead(400).end("Authorization state mismatch.");
|
||||
return;
|
||||
}
|
||||
if (
|
||||
url.searchParams.has("iss") &&
|
||||
url.searchParams.get("iss") !== metadata.issuer
|
||||
) {
|
||||
res.writeHead(400).end("OAuth issuer mismatch.");
|
||||
return;
|
||||
}
|
||||
if (accepted) {
|
||||
res.writeHead(409).end("Authorization was already received.");
|
||||
return;
|
||||
}
|
||||
const code = url.searchParams.get("code");
|
||||
const error = url.searchParams.get("error");
|
||||
if (!code && !error) {
|
||||
res.writeHead(400).end("Missing authorization code.");
|
||||
return;
|
||||
}
|
||||
accepted = true;
|
||||
settle(
|
||||
error
|
||||
? {
|
||||
error:
|
||||
"Search1API authorization was declined. Try signing in again.",
|
||||
}
|
||||
: { code: code! },
|
||||
);
|
||||
res.end(
|
||||
error
|
||||
? "Authorization declined. Return to Magpie."
|
||||
: "Authorization received. Return to Magpie to finish signing in.",
|
||||
);
|
||||
});
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(0, "127.0.0.1", resolve);
|
||||
});
|
||||
server.unref();
|
||||
const close = () => {
|
||||
server.close();
|
||||
server.closeAllConnections();
|
||||
};
|
||||
const timer = setTimeout(() => {
|
||||
settle({ error: "Search1API sign-in timed out. Try again in Magpie." });
|
||||
close();
|
||||
}, timeoutMs);
|
||||
timer.unref();
|
||||
try {
|
||||
const redirect = `http://127.0.0.1:${(server.address() as AddressInfo).port}/callback`;
|
||||
const registration = await json<{
|
||||
client_id: string;
|
||||
token_endpoint_auth_method?: string;
|
||||
}>(metadata.registration_endpoint, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
client_name: "Search1API for Magpie",
|
||||
application_type: "native",
|
||||
redirect_uris: [redirect],
|
||||
token_endpoint_auth_method: "none",
|
||||
grant_types: ["authorization_code", "refresh_token"],
|
||||
response_types: ["code"],
|
||||
scope: SCOPES,
|
||||
}),
|
||||
});
|
||||
if (
|
||||
!registration.client_id ||
|
||||
(registration.token_endpoint_auth_method &&
|
||||
registration.token_endpoint_auth_method !== "none")
|
||||
) {
|
||||
throw new Error("Search1API OAuth did not register a public client.");
|
||||
}
|
||||
const url = new URL(metadata.authorization_endpoint);
|
||||
for (const [key, value] of Object.entries({
|
||||
response_type: "code",
|
||||
client_id: registration.client_id,
|
||||
redirect_uri: redirect,
|
||||
scope: SCOPES,
|
||||
state,
|
||||
code_challenge: challenge,
|
||||
code_challenge_method: "S256",
|
||||
}))
|
||||
url.searchParams.set(key, value);
|
||||
let completed = false;
|
||||
return {
|
||||
url: url.href,
|
||||
instructions:
|
||||
"Sign in to Search1API in your browser, then return to Magpie. The browser must run on the same computer as Magpie.",
|
||||
method: "auto" as const,
|
||||
async callback() {
|
||||
if (completed)
|
||||
return {
|
||||
type: "failed" as const,
|
||||
error: "This sign-in was already completed. Start a new sign-in.",
|
||||
};
|
||||
completed = true;
|
||||
try {
|
||||
const response = await result;
|
||||
if (response.error)
|
||||
return { type: "failed" as const, error: response.error };
|
||||
const tokens = await json<Tokens>(metadata.token_endpoint, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams({
|
||||
grant_type: "authorization_code",
|
||||
code: response.code!,
|
||||
redirect_uri: redirect,
|
||||
client_id: registration.client_id,
|
||||
code_verifier: verifier,
|
||||
}),
|
||||
});
|
||||
const { type: _, ...auth } = credential(
|
||||
tokens,
|
||||
registration.client_id,
|
||||
metadata,
|
||||
);
|
||||
return { type: "success" as const, ...auth };
|
||||
} catch (error) {
|
||||
return {
|
||||
type: "failed" as const,
|
||||
error:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Search1API OAuth failed.",
|
||||
};
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
close();
|
||||
}
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
clearTimeout(timer);
|
||||
close();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { serviceURL } from "./types.ts";
|
||||
|
||||
export class AuthenticationError extends Error {}
|
||||
|
||||
// Only the six reviewed endpoints are exposed. Match the original client's
|
||||
// request bodies and deadlines without adding runtime npm dependencies.
|
||||
export async function request(
|
||||
baseUrl: string,
|
||||
name: string,
|
||||
token: string,
|
||||
body: Record<string, unknown>,
|
||||
signal: AbortSignal,
|
||||
): Promise<unknown> {
|
||||
signal.throwIfAborted();
|
||||
const response = await fetch(serviceURL(`${baseUrl}/${name}`), {
|
||||
method: "POST",
|
||||
redirect: "error",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
signal: AbortSignal.any([
|
||||
signal,
|
||||
AbortSignal.timeout(name === "ask" ? 45_000 : 30_000),
|
||||
]),
|
||||
});
|
||||
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}).`);
|
||||
}
|
||||
try {
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
signal.throwIfAborted();
|
||||
if (error instanceof Error && error.name === "TimeoutError") throw error;
|
||||
throw new Error(`Search1API returned invalid JSON for ${name}.`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
export interface Schema {
|
||||
type: "string" | "integer" | "array";
|
||||
description?: string;
|
||||
enum?: string[];
|
||||
minLength?: number;
|
||||
maxLength?: number;
|
||||
minimum?: number;
|
||||
maximum?: number;
|
||||
format?: "uri";
|
||||
items?: Schema;
|
||||
}
|
||||
export interface ArgumentsSchema {
|
||||
type: "object";
|
||||
properties: Record<string, Schema>;
|
||||
required: string[];
|
||||
additionalProperties: false;
|
||||
}
|
||||
|
||||
// Magpie forwards JSON Schema arguments unchanged, so validate on execute too.
|
||||
export function validate(schema: ArgumentsSchema, value: unknown): Record<string, unknown> {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value))
|
||||
throw new Error("Tool arguments must be an object.");
|
||||
const args = value as Record<string, unknown>;
|
||||
for (const key of schema.required) {
|
||||
if (args[key] === undefined) throw new Error(`${key} is required.`);
|
||||
}
|
||||
const result: Record<string, unknown> = {};
|
||||
for (const [key, value] of Object.entries(args)) {
|
||||
const field = schema.properties[key];
|
||||
if (!Object.hasOwn(schema.properties, key))
|
||||
throw new Error(`Unknown argument: ${key}.`);
|
||||
if (value === undefined) continue;
|
||||
if (field.type === "string") {
|
||||
if (typeof value !== "string") throw new Error(`${key} must be a string.`);
|
||||
const text = key === "query" ? value.trim() : value;
|
||||
if ((field.minLength !== undefined && text.length < field.minLength) ||
|
||||
(field.maxLength !== undefined && text.length > field.maxLength))
|
||||
throw new Error(`${key} has an invalid length.`);
|
||||
if (field.enum && !field.enum.includes(text))
|
||||
throw new Error(`${key} must be one of: ${field.enum.join(", ")}.`);
|
||||
if (field.format === "uri") {
|
||||
try { new URL(text); } catch { throw new Error(`${key} must be a URL.`); }
|
||||
}
|
||||
result[key] = text;
|
||||
} else if (field.type === "integer") {
|
||||
if (typeof value !== "number" || !Number.isInteger(value) ||
|
||||
(field.minimum !== undefined && value < field.minimum) ||
|
||||
(field.maximum !== undefined && value > field.maximum))
|
||||
throw new Error(`${key} must be an integer from ${field.minimum} to ${field.maximum}.`);
|
||||
result[key] = value;
|
||||
} else {
|
||||
if (!Array.isArray(value) || value.some((item) => typeof item !== "string"))
|
||||
throw new Error(`${key} must be an array of strings.`);
|
||||
result[key] = value;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export const query: Schema = { type: "string", minLength: 1, description: "Search query (trimmed)." };
|
||||
export const maxResults: Schema = { type: "integer", minimum: 1, maximum: 50 };
|
||||
export const filters: Record<string, Schema> = {
|
||||
maxResults,
|
||||
crawlResults: { type: "integer", minimum: 0, maximum: 50 },
|
||||
includeSites: { type: "array", items: { type: "string" } },
|
||||
excludeSites: { type: "array", items: { type: "string" } },
|
||||
timeRange: { type: "string", enum: ["day", "week", "month", "year"] },
|
||||
};
|
||||
|
||||
export function searchBody(args: Record<string, unknown>, service: string) {
|
||||
return {
|
||||
query: args.query,
|
||||
search_service: args.searchService ?? service,
|
||||
max_results: args.maxResults ?? 10,
|
||||
crawl_results: args.crawlResults ?? 0,
|
||||
...(args.page === undefined ? {} : { page: args.page }),
|
||||
...(args.includeSites === undefined ? {} : { include_sites: args.includeSites }),
|
||||
...(args.excludeSites === undefined ? {} : { exclude_sites: args.excludeSites }),
|
||||
...(args.timeRange === undefined ? {} : { time_range: args.timeRange }),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
export const PROVIDER = "search1api";
|
||||
export const API_BASE = "https://api.search1api.com";
|
||||
|
||||
export interface StoredOAuth {
|
||||
type: "oauth";
|
||||
access: string;
|
||||
refresh: string;
|
||||
expires: number;
|
||||
clientId: string;
|
||||
tokenEndpoint: string;
|
||||
issuer: string;
|
||||
}
|
||||
export interface StoredAPI {
|
||||
type: "api";
|
||||
key: string;
|
||||
}
|
||||
export type StoredAuth = StoredOAuth | StoredAPI;
|
||||
|
||||
export interface PluginInput {
|
||||
directory: string;
|
||||
client: {
|
||||
auth: {
|
||||
set(input: { path: { id: string }; body: StoredAuth }): Promise<unknown>;
|
||||
};
|
||||
};
|
||||
}
|
||||
export interface Options {
|
||||
apiKey?: string;
|
||||
baseUrl?: string;
|
||||
}
|
||||
|
||||
export function serviceURL(value: string): URL {
|
||||
const url = new URL(value);
|
||||
const loopback = ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname);
|
||||
if (
|
||||
(url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) ||
|
||||
url.username ||
|
||||
url.password
|
||||
) {
|
||||
throw new Error(
|
||||
"Search1API endpoints must use HTTPS (HTTP is allowed on loopback for local testing).",
|
||||
);
|
||||
}
|
||||
return url;
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtemp, readFile, 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";
|
||||
import { discover, refreshToken } from "../src/oauth.ts";
|
||||
import { context } from "./helpers.mjs";
|
||||
|
||||
const baseUrl = "https://search1api.invalid";
|
||||
const json = (value, status = 200) => new Response(JSON.stringify(value), { status });
|
||||
|
||||
// Every fetch is replaced, including unexpected URLs: no real API or OAuth
|
||||
// service can be reached, and all credentials and auth files are synthetic.
|
||||
async function stub(t, handler) {
|
||||
const directory = await mkdtemp(join(tmpdir(), "search1api-fetch-test-"));
|
||||
const authPath = join(directory, "plugin-auth.json");
|
||||
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 };
|
||||
calls.push(call);
|
||||
assert.equal(new URL(call.url).origin, baseUrl);
|
||||
return handler(call, calls.length);
|
||||
};
|
||||
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(authPath, JSON.stringify({ search1api: auth }), { mode: 0o600 });
|
||||
const input = {
|
||||
directory,
|
||||
client: { auth: { set: async ({ path, body }) => {
|
||||
assert.equal(path.id, "search1api");
|
||||
await save(body);
|
||||
} } },
|
||||
};
|
||||
return { calls, input, save, read: async () => JSON.parse(await readFile(authPath, "utf8")) };
|
||||
}
|
||||
|
||||
const oauth = () => ({
|
||||
type: "oauth", access: "fixture-access", refresh: "fixture-refresh",
|
||||
expires: Date.now() + 3600_000, clientId: "fixture-client",
|
||||
issuer: baseUrl, tokenEndpoint: `${baseUrl}/token`,
|
||||
});
|
||||
|
||||
test("fetch stub: all six tools preserve wire bodies, defaults and complete JSON responses", async (t) => {
|
||||
const payload = {
|
||||
query: "fixture", intent: { sources: ["github"], time_range: "week" },
|
||||
results: [{ source: "github", relevance: 0.9, published_date: "2026-10-23", metadata: { stars: 0 } }],
|
||||
errors: [], extra: { retained: true },
|
||||
};
|
||||
const f = await stub(t, () => json(payload));
|
||||
const plugin = await Search1APIPlugin(f.input, { baseUrl, apiKey: "fixture-key" });
|
||||
const cases = [
|
||||
["search", { query: " research ", searchService: "grokipedia", maxResults: 3, crawlResults: 2, page: 4, includeSites: ["example.com"], excludeSites: ["other.example"], timeRange: "week" },
|
||||
{ query: "research", search_service: "grokipedia", max_results: 3, crawl_results: 2, page: 4, include_sites: ["example.com"], exclude_sites: ["other.example"], time_range: "week" }],
|
||||
["search", { query: "default" }, { query: "default", search_service: "google", max_results: 10, crawl_results: 0 }],
|
||||
["news", { query: "default" }, { query: "default", search_service: "bing", max_results: 10, crawl_results: 0 }],
|
||||
["news", { query: "news", searchService: "reuters", crawlResults: 3, maxResults: 4, timeRange: "day", excludeSites: ["example.com"] },
|
||||
{ query: "news", search_service: "reuters", crawl_results: 3, max_results: 4, time_range: "day", exclude_sites: ["example.com"] }],
|
||||
["ask", { query: "research" }, { query: "research" }],
|
||||
["crawl", { url: "https://example.com/path" }, { url: "https://example.com/path" }],
|
||||
["sitemap", { url: "https://example.com" }, { url: "https://example.com" }],
|
||||
["trending", { service: "github", maxResults: 4 }, { search_service: "github", max_results: 4 }],
|
||||
["trending", { service: "hackernews" }, { search_service: "hackernews", max_results: 10 }],
|
||||
];
|
||||
for (const [name, args, body] of cases) {
|
||||
assert.deepEqual(JSON.parse(await plugin.tool[name].execute(args, context())), payload);
|
||||
const call = f.calls.at(-1);
|
||||
assert.equal(call.url, `${baseUrl}/${name}`);
|
||||
assert.equal(call.method, "POST");
|
||||
assert.equal(call.headers.Authorization, "Bearer fixture-key");
|
||||
assert.equal(call.headers["Content-Type"], "application/json");
|
||||
assert.equal(call.redirect, "error");
|
||||
assert.deepEqual(JSON.parse(call.body), body);
|
||||
}
|
||||
assert.equal(f.calls.length, cases.length);
|
||||
const cfg = {};
|
||||
await plugin.config(cfg);
|
||||
assert.deepEqual(cfg.provider, { search1api: { name: "Search1API", models: {} } });
|
||||
assert.equal(plugin.auth.single, true);
|
||||
assert.deepEqual(plugin.auth.methods.map((m) => m.type), ["oauth", "api"]);
|
||||
});
|
||||
|
||||
test("fetch stub: invalid arguments are refused before any request", async (t) => {
|
||||
const f = await stub(t, () => { throw new Error("must not fetch"); });
|
||||
const plugin = await Search1APIPlugin(f.input, { baseUrl, apiKey: "fixture-key" });
|
||||
const cases = [
|
||||
["search", {}], ["search", { query: " " }], ["search", { query: 4 }],
|
||||
["search", { query: "test", maxResults: 0 }], ["search", { query: "test", maxResults: 51 }],
|
||||
["search", { query: "test", maxResults: 1.5 }], ["search", { query: "test", page: 101 }],
|
||||
["search", { query: "test", crawlResults: -1 }], ["search", { query: "test", timeRange: "hour" }],
|
||||
["search", { query: "test", includeSites: [3] }], ["search", { query: "test", excludeSites: "x" }],
|
||||
["search", { query: "test", searchService: "sogou" }], ["news", { query: "test", searchService: "github" }],
|
||||
["ask", { query: "x".repeat(501) }], ["ask", { query: "test", maxResults: 3 }],
|
||||
["crawl", { url: "not a url" }], ["sitemap", { url: null }],
|
||||
["trending", { service: "reddit" }], ["search", []],
|
||||
];
|
||||
for (const [name, args] of cases) await assert.rejects(plugin.tool[name].execute(args, context()));
|
||||
assert.equal(f.calls.length, 0);
|
||||
});
|
||||
|
||||
test("fetch stub: OAuth 401 refreshes and persists once, while a second 401 stops", async (t) => {
|
||||
let toolCalls = 0;
|
||||
const f = await stub(t, (call) => {
|
||||
if (call.url.endsWith("/token")) {
|
||||
assert.deepEqual(Object.fromEntries(new URLSearchParams(call.body)), {
|
||||
grant_type: "refresh_token", refresh_token: "fixture-refresh", client_id: "fixture-client",
|
||||
});
|
||||
return json({ access_token: "fixture-new", refresh_token: "fixture-rotated", expires_in: 3600 });
|
||||
}
|
||||
toolCalls++;
|
||||
assert.equal(call.headers.Authorization, `Bearer ${toolCalls === 1 ? "fixture-access" : "fixture-new"}`);
|
||||
return json({ private: "never expose this" }, 401);
|
||||
});
|
||||
await f.save(oauth());
|
||||
const plugin = await Search1APIPlugin(f.input, { baseUrl });
|
||||
await assert.rejects(plugin.tool.search.execute({ query: "test" }, context()), /failed \(401\)/);
|
||||
assert.equal(toolCalls, 2);
|
||||
assert.equal(f.calls.length, 3);
|
||||
assert.equal((await f.read()).search1api.refresh, "fixture-rotated");
|
||||
});
|
||||
|
||||
test("fetch stub: API errors are safe and never retried, including API-key 401", async (t) => {
|
||||
let status = 401;
|
||||
const f = await stub(t, () => json({ error: "fixture-secret-must-not-leak" }, status));
|
||||
const plugin = await Search1APIPlugin(f.input, { baseUrl, apiKey: "fixture-key" });
|
||||
for (status of [400, 401, 402, 429, 500]) {
|
||||
const before = f.calls.length;
|
||||
await assert.rejects(plugin.tool.ask.execute({ query: "test" }, context()), (error) => {
|
||||
assert.match(error.message, new RegExp(String(status)));
|
||||
assert.doesNotMatch(error.message, /fixture-secret/);
|
||||
return true;
|
||||
});
|
||||
assert.equal(f.calls.length, before + 1);
|
||||
}
|
||||
});
|
||||
|
||||
test("fetch stub: cancellation reaches an in-flight request and prevents refresh/retry", async (t) => {
|
||||
let entered;
|
||||
const started = new Promise((resolve) => { entered = resolve; });
|
||||
const f = await stub(t, (call) => new Promise((resolve, reject) => {
|
||||
entered();
|
||||
call.signal.addEventListener("abort", () => reject(call.signal.reason), { once: true });
|
||||
}));
|
||||
await f.save(oauth());
|
||||
const plugin = await Search1APIPlugin(f.input, { baseUrl });
|
||||
const controller = new AbortController();
|
||||
const call = plugin.tool.search.execute({ query: "test" }, context(controller.signal));
|
||||
const rejected = assert.rejects(call, /fixture cancellation/);
|
||||
await started;
|
||||
controller.abort(new Error("fixture cancellation"));
|
||||
await rejected;
|
||||
assert.equal(f.calls.length, 1);
|
||||
await assert.rejects(plugin.tool.search.execute({ query: "test" }, context(controller.signal)));
|
||||
assert.equal(f.calls.length, 1);
|
||||
});
|
||||
|
||||
test("fetch stub: invalid JSON is reported without echoing response content", async (t) => {
|
||||
const f = await stub(t, () => new Response("fixture-private-content"));
|
||||
const plugin = await Search1APIPlugin(f.input, { baseUrl, apiKey: "fixture-key" });
|
||||
await assert.rejects(plugin.tool.search.execute({ query: "test" }, context()), /returned invalid JSON for search/);
|
||||
assert.equal(f.calls.length, 1);
|
||||
});
|
||||
|
||||
test("fetch stub: OAuth discovery validates issuer, endpoints and PKCE before sign-in", async (t) => {
|
||||
let change = {};
|
||||
const f = await stub(t, (call) => call.url.endsWith("oauth-protected-resource")
|
||||
? json({ authorization_servers: [baseUrl] })
|
||||
: json({ issuer: baseUrl, authorization_endpoint: `${baseUrl}/authorize`,
|
||||
token_endpoint: `${baseUrl}/token`, registration_endpoint: `${baseUrl}/register`,
|
||||
code_challenge_methods_supported: ["S256"], ...change }));
|
||||
assert.equal((await discover(baseUrl)).issuer, baseUrl);
|
||||
for (change of [
|
||||
{ issuer: "https://other.invalid" },
|
||||
{ token_endpoint: "https://other.invalid/token" },
|
||||
{ registration_endpoint: "http://search1api.invalid/register" },
|
||||
{ code_challenge_methods_supported: ["plain"] },
|
||||
]) await assert.rejects(discover(baseUrl));
|
||||
const before = f.calls.length;
|
||||
await assert.rejects(refreshToken({ ...oauth(), tokenEndpoint: "https://other.invalid/token" }));
|
||||
assert.equal(f.calls.length, before);
|
||||
});
|
||||
@@ -0,0 +1,191 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { createServer } from "node:http";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
export async function fixture(t) {
|
||||
const directory = await mkdtemp(join(tmpdir(), "magpie-search1api-test-"));
|
||||
const calls = [];
|
||||
const state = {
|
||||
refreshes: 0,
|
||||
grants: 0,
|
||||
decline: false,
|
||||
rejectRefresh: false,
|
||||
rejectAccess: false,
|
||||
refreshDelay: 0,
|
||||
};
|
||||
let registration;
|
||||
let authorization;
|
||||
let baseUrl;
|
||||
const server = createServer(async (req, res) => {
|
||||
const url = new URL(req.url, baseUrl);
|
||||
let raw = "";
|
||||
for await (const chunk of req) raw += chunk;
|
||||
const form = new URLSearchParams(raw);
|
||||
const json = (value, status = 200) => {
|
||||
res.writeHead(status, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify(value));
|
||||
};
|
||||
calls.push({
|
||||
path: url.pathname,
|
||||
method: req.method,
|
||||
headers: req.headers,
|
||||
raw,
|
||||
});
|
||||
if (url.pathname === "/.well-known/oauth-protected-resource")
|
||||
return json({ authorization_servers: [baseUrl] });
|
||||
if (url.pathname === "/.well-known/oauth-authorization-server")
|
||||
return json({
|
||||
issuer: baseUrl,
|
||||
authorization_endpoint: `${baseUrl}/authorize`,
|
||||
token_endpoint: `${baseUrl}/token`,
|
||||
registration_endpoint: `${baseUrl}/register`,
|
||||
code_challenge_methods_supported: ["S256"],
|
||||
});
|
||||
if (url.pathname === "/register") {
|
||||
registration = JSON.parse(raw);
|
||||
return json({
|
||||
client_id: "test-public-client",
|
||||
token_endpoint_auth_method: "none",
|
||||
});
|
||||
}
|
||||
if (url.pathname === "/authorize") {
|
||||
authorization = url;
|
||||
const redirect = new URL(url.searchParams.get("redirect_uri"));
|
||||
redirect.searchParams.set("state", url.searchParams.get("state"));
|
||||
redirect.searchParams.set("iss", baseUrl);
|
||||
redirect.searchParams.set(
|
||||
state.decline ? "error" : "code",
|
||||
state.decline ? "access_denied" : "test-authorization-code",
|
||||
);
|
||||
res.writeHead(302, { location: redirect.href }).end();
|
||||
return;
|
||||
}
|
||||
if (url.pathname === "/token") {
|
||||
if (form.get("grant_type") === "authorization_code") {
|
||||
if (
|
||||
form.get("client_id") !== "test-public-client" ||
|
||||
form.get("code") !== "test-authorization-code" ||
|
||||
form.get("redirect_uri") !== registration.redirect_uris[0] ||
|
||||
createHash("sha256")
|
||||
.update(form.get("code_verifier") ?? "")
|
||||
.digest("base64url") !==
|
||||
authorization.searchParams.get("code_challenge")
|
||||
) {
|
||||
return json({ error: "invalid_grant" }, 400);
|
||||
}
|
||||
state.grants++;
|
||||
return json({
|
||||
access_token: "test-access-0",
|
||||
refresh_token: "test-refresh-0",
|
||||
expires_in: 3600,
|
||||
token_type: "Bearer",
|
||||
});
|
||||
}
|
||||
if (state.refreshDelay)
|
||||
await new Promise((r) => setTimeout(r, state.refreshDelay));
|
||||
if (
|
||||
state.rejectRefresh ||
|
||||
form.get("client_id") !== "test-public-client" ||
|
||||
form.get("refresh_token") !== `test-refresh-${state.refreshes}`
|
||||
) {
|
||||
return json(
|
||||
{ error: "invalid_grant", private: "must-not-appear-in-errors" },
|
||||
400,
|
||||
);
|
||||
}
|
||||
state.refreshes++;
|
||||
return json({
|
||||
access_token: `test-access-${state.refreshes}`,
|
||||
refresh_token: `test-refresh-${state.refreshes}`,
|
||||
expires_in: 3600,
|
||||
});
|
||||
}
|
||||
if (
|
||||
state.rejectAccess &&
|
||||
req.headers.authorization === "Bearer test-access-0"
|
||||
)
|
||||
return json({ message: "expired" }, 401);
|
||||
return json({
|
||||
query: "fixture",
|
||||
intent: { sources: ["github"], time_range: "week" },
|
||||
results: [
|
||||
{
|
||||
title: "Example",
|
||||
link: "https://example.com",
|
||||
snippet: "Result",
|
||||
published_date: "2026-10-23",
|
||||
source: "github",
|
||||
relevance: 0.9,
|
||||
metadata: { stars: 0 },
|
||||
},
|
||||
],
|
||||
errors: [],
|
||||
});
|
||||
});
|
||||
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
baseUrl = `http://127.0.0.1:${server.address().port}`;
|
||||
t.after(async () => {
|
||||
server.closeAllConnections();
|
||||
await new Promise((resolve) => server.close(resolve));
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
});
|
||||
const authPath = join(directory, "plugin-auth.json");
|
||||
const readAuth = async () => {
|
||||
try {
|
||||
return JSON.parse(await readFile(authPath, "utf8"));
|
||||
} catch (e) {
|
||||
if (e.code === "ENOENT") return {};
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
const save = async (auth) => {
|
||||
const all = await readAuth();
|
||||
all.search1api = auth;
|
||||
await writeFile(authPath, JSON.stringify(all), { mode: 0o600 });
|
||||
};
|
||||
const input = {
|
||||
directory,
|
||||
client: {
|
||||
auth: {
|
||||
set: async ({ path, body }) => {
|
||||
const all = await readAuth();
|
||||
all[path.id] = body;
|
||||
await writeFile(authPath, JSON.stringify(all), { mode: 0o600 });
|
||||
return { data: true };
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
return {
|
||||
directory,
|
||||
input,
|
||||
calls,
|
||||
state,
|
||||
baseUrl,
|
||||
authPath,
|
||||
save,
|
||||
readAuth,
|
||||
oauth: () => ({
|
||||
type: "oauth",
|
||||
access: "test-access-0",
|
||||
refresh: "test-refresh-0",
|
||||
expires: Date.now() + 3600_000,
|
||||
clientId: "test-public-client",
|
||||
tokenEndpoint: `${baseUrl}/token`,
|
||||
issuer: baseUrl,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
export const context = (signal) => ({
|
||||
sessionID: "test",
|
||||
messageID: "test",
|
||||
agent: "test",
|
||||
directory: "",
|
||||
worktree: "",
|
||||
abort: signal ?? new AbortController().signal,
|
||||
metadata() {},
|
||||
async ask() {},
|
||||
});
|
||||
@@ -0,0 +1,174 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { spawn } from "node:child_process";
|
||||
import { stat, writeFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { createInterface } from "node:readline";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import test from "node:test";
|
||||
import { context, fixture } from "./helpers.mjs";
|
||||
|
||||
const root = fileURLToPath(new URL("../", import.meta.url));
|
||||
const hostPath = process.env.MAGPIE_HOST_PATH;
|
||||
const bun = process.env.MAGPIE_BUN_PATH ?? "bun";
|
||||
|
||||
async function host(t, f) {
|
||||
const child = spawn(bun, [resolve(hostPath)], {
|
||||
cwd: root,
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
env: { ...process.env, SEARCH1API_API_KEY: "" },
|
||||
});
|
||||
const pending = new Map();
|
||||
let next = 0;
|
||||
let errors = "";
|
||||
child.stderr.on("data", (data) => {
|
||||
errors += data;
|
||||
});
|
||||
createInterface({ input: child.stdout }).on("line", (line) => {
|
||||
const msg = JSON.parse(line);
|
||||
if (!("result" in msg) && !msg.error) return;
|
||||
const waiter = pending.get(msg.id);
|
||||
if (!waiter) return;
|
||||
pending.delete(msg.id);
|
||||
clearTimeout(waiter.timer);
|
||||
if (msg.error) waiter.reject(new Error(msg.error.message));
|
||||
else waiter.resolve(msg.result);
|
||||
});
|
||||
child.on("error", (error) => {
|
||||
for (const p of pending.values()) {
|
||||
clearTimeout(p.timer);
|
||||
p.reject(error);
|
||||
}
|
||||
pending.clear();
|
||||
});
|
||||
child.on("exit", (code) => {
|
||||
for (const p of pending.values()) {
|
||||
clearTimeout(p.timer);
|
||||
p.reject(new Error(`Host exited ${code}: ${errors}`));
|
||||
}
|
||||
pending.clear();
|
||||
});
|
||||
t.after(() => {
|
||||
child.kill();
|
||||
});
|
||||
const rpc = (method, params = {}) =>
|
||||
new Promise((resolve, reject) => {
|
||||
const id = ++next;
|
||||
const timer = setTimeout(() => {
|
||||
pending.delete(id);
|
||||
reject(new Error(`${method} timed out: ${errors}`));
|
||||
}, 15_000);
|
||||
pending.set(id, { resolve, reject, timer });
|
||||
child.stdin.write(JSON.stringify({ id, method, params }) + "\n");
|
||||
});
|
||||
const init = await rpc("init", {
|
||||
authPath: f.authPath,
|
||||
directory: f.directory,
|
||||
plugins: [
|
||||
{
|
||||
spec: "@magpie-community/tools-search1api",
|
||||
target: root,
|
||||
options: { baseUrl: f.baseUrl },
|
||||
},
|
||||
],
|
||||
});
|
||||
assert.equal(init.plugins[0].error, undefined, JSON.stringify(init));
|
||||
assert.equal(init.plugins[0].tools.length, 6);
|
||||
return rpc;
|
||||
}
|
||||
|
||||
test(
|
||||
"actual Magpie Bun host: native OAuth → saved account → tools → refresh → logout",
|
||||
{ timeout: 30_000 },
|
||||
async (t) => {
|
||||
assert.ok(
|
||||
hostPath,
|
||||
"Set MAGPIE_HOST_PATH to Magpie's internal/plugin/host.js (see README).",
|
||||
);
|
||||
const f = await fixture(t);
|
||||
const rpc = await host(t, f);
|
||||
const providers = await rpc("providers");
|
||||
assert.equal(providers[0].id, "search1api");
|
||||
assert.equal(providers[0].single, true);
|
||||
assert.deepEqual(providers[0].models, []);
|
||||
assert.deepEqual(
|
||||
providers[0].methods.map((m) => m.type),
|
||||
["oauth", "api"],
|
||||
);
|
||||
const signIn = await rpc("authorize", {
|
||||
provider: "search1api",
|
||||
method: 0,
|
||||
});
|
||||
assert.equal((await fetch(signIn.url)).status, 200);
|
||||
const saved = await rpc("callback", { session: signIn.session });
|
||||
assert.equal(saved.ok, true);
|
||||
assert.equal(saved.account, "search1api");
|
||||
assert.equal((await stat(f.authPath)).mode & 0o777, 0o600);
|
||||
const call = () =>
|
||||
rpc("tool", {
|
||||
spec: "@magpie-community/tools-search1api",
|
||||
name: "search",
|
||||
args: { query: "Bun", searchService: "github", timeRange: "week" },
|
||||
ms: 5000,
|
||||
agent: "test",
|
||||
});
|
||||
const result = await call();
|
||||
assert.equal(JSON.parse(result.text).results[0].metadata.stars, 0);
|
||||
await assert.rejects(
|
||||
rpc("tool", {
|
||||
spec: "@magpie-community/tools-search1api",
|
||||
name: "search",
|
||||
args: { query: " " },
|
||||
ms: 5000,
|
||||
}),
|
||||
/query|arguments are wrong/,
|
||||
);
|
||||
const all = await f.readAuth();
|
||||
all.search1api.expires = Date.now() - 1;
|
||||
await writeFile(f.authPath, JSON.stringify(all), { mode: 0o600 });
|
||||
const second = await host(t, f);
|
||||
await Promise.all([
|
||||
call(),
|
||||
second("tool", {
|
||||
spec: "@magpie-community/tools-search1api",
|
||||
name: "ask",
|
||||
args: { query: "Bun" },
|
||||
ms: 5000,
|
||||
}),
|
||||
]);
|
||||
assert.equal(
|
||||
f.state.refreshes,
|
||||
1,
|
||||
"rotating refresh tokens are shared safely across real Bun processes",
|
||||
);
|
||||
assert.equal((await f.readAuth()).search1api.access, "test-access-1");
|
||||
await rpc("signOut", { provider: "search1api" });
|
||||
await assert.rejects(call(), /Sign in/);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
"actual Magpie Bun host saves API keys using its native login path",
|
||||
{ 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-native-api-key",
|
||||
});
|
||||
assert.equal(saved.ok, true);
|
||||
const result = await rpc("tool", {
|
||||
spec: "@magpie-community/tools-search1api",
|
||||
name: "news",
|
||||
args: { query: "test" },
|
||||
ms: 5000,
|
||||
});
|
||||
assert.ok(JSON.parse(result.text).results.length);
|
||||
assert.equal(
|
||||
f.calls.at(-1).headers.authorization,
|
||||
"Bearer test-native-api-key",
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,40 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { startOAuth } from "../src/oauth.ts";
|
||||
import { fixture } from "./helpers.mjs";
|
||||
|
||||
test("browser OAuth uses PKCE S256, public registration, state and issuer checks", async (t) => {
|
||||
const f = await fixture(t);
|
||||
const login = await startOAuth(f.baseUrl, 1000);
|
||||
const authURL = new URL(login.url);
|
||||
assert.equal(authURL.searchParams.get("code_challenge_method"), "S256");
|
||||
const redirect = new URL(authURL.searchParams.get("redirect_uri"));
|
||||
redirect.searchParams.set("state", "wrong");
|
||||
redirect.searchParams.set("code", "wrong");
|
||||
assert.equal((await fetch(redirect)).status, 400);
|
||||
redirect.searchParams.set("state", authURL.searchParams.get("state"));
|
||||
redirect.searchParams.set("iss", "https://wrong.example");
|
||||
assert.equal((await fetch(redirect)).status, 400);
|
||||
const browser = await fetch(login.url);
|
||||
assert.equal(browser.status, 200);
|
||||
const response = await login.callback();
|
||||
assert.equal(response.type, "success");
|
||||
assert.equal(response.access, "test-access-0");
|
||||
assert.equal(response.refresh, "test-refresh-0");
|
||||
assert.equal(response.clientId, "test-public-client");
|
||||
assert.equal(f.state.grants, 1);
|
||||
assert.equal((await login.callback()).type, "failed");
|
||||
assert.equal(f.state.grants, 1);
|
||||
});
|
||||
|
||||
test("declined consent and abandoned sign-ins finish without leaking tokens or callback listeners", async (t) => {
|
||||
const f = await fixture(t);
|
||||
f.state.decline = true;
|
||||
const declined = await startOAuth(f.baseUrl, 1000);
|
||||
await fetch(declined.url);
|
||||
assert.match((await declined.callback()).error, /declined/);
|
||||
const abandoned = await startOAuth(f.baseUrl, 40);
|
||||
assert.match((await abandoned.callback()).error, /timed out/);
|
||||
const redirect = new URL(abandoned.url).searchParams.get("redirect_uri");
|
||||
await assert.rejects(fetch(redirect));
|
||||
});
|
||||
@@ -0,0 +1,218 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import test from "node:test";
|
||||
import { Search1APIPlugin } from "../index.mjs";
|
||||
import { fixture, context } from "./helpers.mjs";
|
||||
|
||||
test("all six tools forward arguments to the API and preserve result metadata", async (t) => {
|
||||
const f = await fixture(t);
|
||||
const plugin = await Search1APIPlugin(f.input, {
|
||||
apiKey: "test-option-key",
|
||||
baseUrl: f.baseUrl,
|
||||
});
|
||||
assert.deepEqual(Object.keys(plugin.tool), [
|
||||
"search",
|
||||
"news",
|
||||
"ask",
|
||||
"crawl",
|
||||
"sitemap",
|
||||
"trending",
|
||||
]);
|
||||
const cases = [
|
||||
[
|
||||
"search",
|
||||
{
|
||||
query: "Bun",
|
||||
searchService: "grokipedia",
|
||||
page: 2,
|
||||
timeRange: "week",
|
||||
maxResults: 3,
|
||||
includeSites: ["example.com"],
|
||||
crawlResults: 0,
|
||||
},
|
||||
{
|
||||
query: "Bun",
|
||||
search_service: "grokipedia",
|
||||
page: 2,
|
||||
time_range: "week",
|
||||
max_results: 3,
|
||||
include_sites: ["example.com"],
|
||||
crawl_results: 0,
|
||||
},
|
||||
],
|
||||
[
|
||||
"news",
|
||||
{
|
||||
query: "Bun",
|
||||
searchService: "reuters",
|
||||
timeRange: "day",
|
||||
excludeSites: ["example.com"],
|
||||
},
|
||||
{
|
||||
query: "Bun",
|
||||
search_service: "reuters",
|
||||
max_results: 10,
|
||||
crawl_results: 0,
|
||||
time_range: "day",
|
||||
exclude_sites: ["example.com"],
|
||||
},
|
||||
],
|
||||
["ask", { query: "Bun this week" }, { query: "Bun this week" }],
|
||||
["crawl", { url: "https://example.com" }, { url: "https://example.com" }],
|
||||
["sitemap", { url: "https://example.com" }, { url: "https://example.com" }],
|
||||
[
|
||||
"trending",
|
||||
{ service: "github", maxResults: 4 },
|
||||
{ search_service: "github", max_results: 4 },
|
||||
],
|
||||
];
|
||||
for (const [name, args, body] of cases) {
|
||||
const output = JSON.parse(await plugin.tool[name].execute(args, context()));
|
||||
const request = f.calls.at(-1);
|
||||
assert.equal(request.path, `/${name}`);
|
||||
assert.equal(request.headers.authorization, "Bearer test-option-key");
|
||||
assert.deepEqual(JSON.parse(request.raw), body);
|
||||
assert.deepEqual(output.results[0].metadata, { stars: 0 });
|
||||
assert.equal(output.results[0].relevance, 0.9);
|
||||
assert.deepEqual(output.errors, []);
|
||||
}
|
||||
assert.deepEqual(Object.keys(plugin.tool.ask.args.properties), ["query"]);
|
||||
await assert.rejects(plugin.tool.search.execute({ query: " " }, context()));
|
||||
await assert.rejects(plugin.tool.ask.execute({ query: "x".repeat(501) }, context()));
|
||||
await assert.rejects(plugin.tool.search.execute({ query: "test", searchService: "sogou" }, context()));
|
||||
await plugin.tool.search.execute({ query: "default search" }, context());
|
||||
assert.deepEqual(JSON.parse(f.calls.at(-1).raw), {
|
||||
query: "default search",
|
||||
max_results: 10,
|
||||
search_service: "google",
|
||||
crawl_results: 0,
|
||||
});
|
||||
await plugin.tool.news.execute({ query: "default news" }, context());
|
||||
assert.deepEqual(JSON.parse(f.calls.at(-1).raw), {
|
||||
query: "default news",
|
||||
max_results: 10,
|
||||
search_service: "bing",
|
||||
crawl_results: 0,
|
||||
});
|
||||
});
|
||||
|
||||
test("API key precedence and missing credentials leave plugin installation usable", async (t) => {
|
||||
const f = await fixture(t);
|
||||
const original = process.env.SEARCH1API_API_KEY;
|
||||
t.after(() => {
|
||||
if (original === undefined) delete process.env.SEARCH1API_API_KEY;
|
||||
else process.env.SEARCH1API_API_KEY = original;
|
||||
});
|
||||
delete process.env.SEARCH1API_API_KEY;
|
||||
const plugin = await Search1APIPlugin(f.input, { baseUrl: f.baseUrl });
|
||||
await assert.rejects(
|
||||
plugin.tool.search.execute({ query: "test" }, context()),
|
||||
/magpie plugin login search1api/,
|
||||
);
|
||||
await f.save({ type: "api", key: "test-native-key" });
|
||||
await plugin.tool.search.execute({ query: "test" }, context());
|
||||
assert.equal(f.calls.at(-1).headers.authorization, "Bearer test-native-key");
|
||||
process.env.SEARCH1API_API_KEY = "test-env-key";
|
||||
await plugin.tool.search.execute({ query: "test" }, context());
|
||||
assert.equal(f.calls.at(-1).headers.authorization, "Bearer test-env-key");
|
||||
const override = await Search1APIPlugin(f.input, {
|
||||
baseUrl: f.baseUrl,
|
||||
apiKey: "test-option-key",
|
||||
});
|
||||
await override.tool.search.execute({ query: "test" }, context());
|
||||
assert.equal(f.calls.at(-1).headers.authorization, "Bearer test-option-key");
|
||||
});
|
||||
|
||||
test("expired OAuth sessions refresh once across concurrent plugin instances and survive reload", async (t) => {
|
||||
const f = await fixture(t);
|
||||
await f.save({ ...f.oauth(), expires: Date.now() - 1 });
|
||||
const a = await Search1APIPlugin(f.input, { baseUrl: f.baseUrl });
|
||||
const b = await Search1APIPlugin(f.input, { baseUrl: f.baseUrl });
|
||||
await Promise.all(
|
||||
Array.from({ length: 8 }, (_, i) =>
|
||||
(i % 2 ? a : b).tool.search.execute({ query: "test" }, context()),
|
||||
),
|
||||
);
|
||||
assert.equal(f.state.refreshes, 1);
|
||||
assert.equal((await f.readAuth()).search1api.refresh, "test-refresh-1");
|
||||
const reload = await Search1APIPlugin(f.input, { baseUrl: f.baseUrl });
|
||||
await reload.tool.search.execute({ query: "test" }, context());
|
||||
assert.equal(f.state.refreshes, 1);
|
||||
assert.equal(f.calls.at(-1).headers.authorization, "Bearer test-access-1");
|
||||
});
|
||||
|
||||
test("a 401 renews an OAuth session once; API keys are not renewed or retried", async (t) => {
|
||||
const f = await fixture(t);
|
||||
await f.save(f.oauth());
|
||||
f.state.rejectAccess = true;
|
||||
const plugin = await Search1APIPlugin(f.input, { baseUrl: f.baseUrl });
|
||||
await plugin.tool.search.execute({ query: "test" }, context());
|
||||
assert.equal(f.state.refreshes, 1);
|
||||
assert.equal(f.calls.filter((c) => c.path === "/search").length, 2);
|
||||
const keyPlugin = await Search1APIPlugin(f.input, {
|
||||
baseUrl: f.baseUrl,
|
||||
apiKey: "test-access-0",
|
||||
});
|
||||
await assert.rejects(
|
||||
keyPlugin.tool.search.execute({ query: "test" }, context()),
|
||||
);
|
||||
assert.equal(f.state.refreshes, 1);
|
||||
assert.equal(f.calls.filter((c) => c.path === "/search").length, 3);
|
||||
});
|
||||
|
||||
test("revoked refresh tokens surface a safe sign-in error and do not alter other accounts", async (t) => {
|
||||
const f = await fixture(t);
|
||||
const auth = { ...f.oauth(), expires: Date.now() - 1 };
|
||||
await writeFile(
|
||||
f.authPath,
|
||||
JSON.stringify({
|
||||
other: { type: "api", key: "test-other-key" },
|
||||
search1api: auth,
|
||||
}),
|
||||
);
|
||||
f.state.rejectRefresh = true;
|
||||
const plugin = await Search1APIPlugin(f.input, { baseUrl: f.baseUrl });
|
||||
await assert.rejects(
|
||||
plugin.tool.search.execute({ query: "test" }, context()),
|
||||
(error) => {
|
||||
assert.match(error.message, /Sign in again/);
|
||||
assert.doesNotMatch(error.message, /must-not-appear/);
|
||||
return true;
|
||||
},
|
||||
);
|
||||
assert.equal((await f.readAuth()).other.key, "test-other-key");
|
||||
});
|
||||
|
||||
test("logout during refresh wins and no old session is resurrected", async (t) => {
|
||||
const f = await fixture(t);
|
||||
await f.save({ ...f.oauth(), expires: Date.now() - 1 });
|
||||
f.state.refreshDelay = 100;
|
||||
const plugin = await Search1APIPlugin(f.input, { baseUrl: f.baseUrl });
|
||||
const call = plugin.tool.search.execute({ query: "test" }, context());
|
||||
while (!f.calls.some((c) => c.path === "/token"))
|
||||
await new Promise((r) => setTimeout(r, 5));
|
||||
await writeFile(f.authPath, "{}");
|
||||
await assert.rejects(call, /Sign in/);
|
||||
assert.deepEqual(await f.readAuth(), {});
|
||||
});
|
||||
|
||||
test("already aborted calls make no upstream request; corrupt auth is never overwritten", async (t) => {
|
||||
const f = await fixture(t);
|
||||
const plugin = await Search1APIPlugin(f.input, {
|
||||
baseUrl: f.baseUrl,
|
||||
apiKey: "test-key",
|
||||
});
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
await assert.rejects(
|
||||
plugin.tool.search.execute({ query: "test" }, context(controller.signal)),
|
||||
);
|
||||
assert.equal(f.calls.length, 0);
|
||||
await writeFile(f.authPath, "broken auth");
|
||||
const native = await Search1APIPlugin(f.input, { baseUrl: f.baseUrl });
|
||||
await assert.rejects(
|
||||
native.tool.search.execute({ query: "test" }, context()),
|
||||
/cannot be read/,
|
||||
);
|
||||
assert.equal(await readFile(f.authPath, "utf8"), "broken auth");
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"strict": true,
|
||||
"declaration": true,
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"skipLibCheck": true,
|
||||
"rewriteRelativeImportExtensions": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["src/**/*.ts"]
|
||||
}
|
||||
@@ -70,6 +70,8 @@
|
||||
"summary": { "en": "Tuanjie Cowork (codely) on magpie's Agents page: pick one of magpie's models and Cowork chats with it, on the subscriptions magpie already holds.", "zh": "把团结 Cowork(codely)加到 magpie 的 Agent 页:给它选一个 magpie 的模型,它聊天就走那个模型,用的是 magpie 里已登录的那些订阅的额度。" } },
|
||||
{ "package": "@magpie-community/middleware-reserve", "name": "Reserve", "kind": "middleware", "community": true,
|
||||
"summary": { "en": "Two routings that keep something in reserve: fill accounts up to a ceiling of their allowance, or use subscriptions before API keys.", "zh": "两种留余量的路由:账号用到额度上限就换下一个,或订阅账号优先于 API key。" } },
|
||||
{ "package": "@magpie-community/tools-search1api", "name": "Search1API", "icon": "https://s1.dev/icon.png", "kind": "tools", "community": true,
|
||||
"summary": { "en": "Search1API web search, news, agentic search, page retrieval, sitemaps and trends through Magpie's tools MCP server. Sign in with OAuth or an API key.", "zh": "通过 Magpie 的工具 MCP 服务使用 Search1API 网页搜索、新闻、智能搜索、页面读取、站点链接和趋势;支持 OAuth 或 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 各复制一棵项目树。"}},
|
||||
|
||||
+11
-6
@@ -27,9 +27,9 @@ for (const name of readdirSync(root)) {
|
||||
const client = { app: { log: async () => {} }, auth: { set: async () => {} }, tui: { showToast: async () => {} }, config: { get: async () => ({ data: {} }) } }
|
||||
for (const fn of fns) {
|
||||
const hooks = await fn({ client, directory: process.cwd(), worktree: process.cwd(), $: undefined, project: {} })
|
||||
// a plugin of tools alone: each one a name an MCP client takes, a
|
||||
// description, arguments and an execute
|
||||
if (!hooks?.auth && hooks?.tool) {
|
||||
// Tools may also have an auth hook for their own API, without serving
|
||||
// chat models. Check their tools as well as their sign-in methods.
|
||||
if (hooks?.tool) {
|
||||
const tools = Object.entries(hooks.tool)
|
||||
if (!tools.length) problems.push(`${fn.name}: no tools`)
|
||||
for (const [n, t] of tools) {
|
||||
@@ -38,12 +38,12 @@ for (const name of readdirSync(root)) {
|
||||
if (typeof t?.description !== "string" || !t.description) problems.push(`${fn.name}: ${n} has no description`)
|
||||
if (!t?.args || typeof t.args !== "object") problems.push(`${fn.name}: ${n} has no args`)
|
||||
}
|
||||
continue
|
||||
if (!hooks.auth) continue
|
||||
}
|
||||
const auth = hooks?.auth
|
||||
if (!auth) { problems.push(`${fn.name}: no auth hook`); continue }
|
||||
if (typeof auth.provider !== "string" || !auth.provider) problems.push(`${fn.name}: auth.provider`)
|
||||
if (typeof auth.loader !== "function") problems.push(`${fn.name}: auth.loader`)
|
||||
let needsLoader = !hooks.tool
|
||||
if (!Array.isArray(auth.methods) || !auth.methods.length) problems.push(`${fn.name}: auth.methods`)
|
||||
for (const m of auth.methods ?? []) {
|
||||
if (!["oauth", "api"].includes(m.type)) problems.push(`${fn.name}: method type ${m.type}`)
|
||||
@@ -53,8 +53,13 @@ for (const name of readdirSync(root)) {
|
||||
const cfg = { provider: {} }
|
||||
await hooks.config(cfg)
|
||||
const p = cfg.provider[auth.provider]
|
||||
if (p && (!p.npm || !p.models || !Object.keys(p.models).length)) problems.push(`${fn.name}: config gives ${auth.provider} no npm or models`)
|
||||
const signInOnly = hooks.tool && p?.models && !Object.keys(p.models).length && !p.npm
|
||||
if (p && !signInOnly) {
|
||||
needsLoader = true
|
||||
if (!p.npm || !p.models || !Object.keys(p.models).length) problems.push(`${fn.name}: config gives ${auth.provider} no npm or models`)
|
||||
}
|
||||
}
|
||||
if ((needsLoader || auth.loader !== undefined) && typeof auth.loader !== "function") problems.push(`${fn.name}: auth.loader`)
|
||||
}
|
||||
} catch (e) {
|
||||
problems.push(String(e?.stack ?? e))
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import { copyFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
|
||||
// Exercise the checker in a tiny independent repository, without loading any
|
||||
// real plugin, credential file or network client.
|
||||
function check(source) {
|
||||
const dir = mkdtempSync(join(tmpdir(), "magpie-check-test-"))
|
||||
try {
|
||||
mkdirSync(join(dir, "scripts"))
|
||||
mkdirSync(join(dir, "packages", "fixture"), { recursive: true })
|
||||
copyFileSync(new URL("./check.mjs", import.meta.url), join(dir, "scripts", "check.mjs"))
|
||||
writeFileSync(join(dir, "packages", "fixture", "package.json"), JSON.stringify({ main: "index.mjs" }))
|
||||
writeFileSync(join(dir, "packages", "fixture", "index.mjs"), source)
|
||||
const result = Bun.spawnSync([process.execPath, join(dir, "scripts", "check.mjs")])
|
||||
return { code: result.exitCode, output: result.stdout.toString() + result.stderr.toString() }
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
const tool = `{search: {description: "Search the web", args: {type: "object"}, execute() {}}}`
|
||||
const auth = `{provider: "fixture", methods: [{type: "api", label: "API key"}]}`
|
||||
|
||||
test("check accepts tools with sign-in and no chat models or loader", () => {
|
||||
const result = check(`export const Plugin = async () => ({
|
||||
auth: ${auth}, tool: ${tool},
|
||||
config: async (cfg) => { cfg.provider.fixture = {name: "Fixture", models: {}} }
|
||||
})`)
|
||||
expect(result.code).toBe(0)
|
||||
expect(result.output).toContain("✓ fixture")
|
||||
})
|
||||
|
||||
test("check still checks tool definitions and auth methods together", () => {
|
||||
const result = check(`export const Plugin = async () => ({
|
||||
auth: {provider: "fixture", methods: [{type: "unknown"}]},
|
||||
tool: {search: {args: {type: "object"}}}
|
||||
})`)
|
||||
expect(result.code).toBe(1)
|
||||
expect(result.output).toContain("search has no execute")
|
||||
expect(result.output).toContain("search has no description")
|
||||
expect(result.output).toContain("method type unknown")
|
||||
})
|
||||
|
||||
test("check still requires loaders for providers, including providers with tools", () => {
|
||||
for (const tools of ["", `tool: ${tool},`]) {
|
||||
const result = check(`export const Plugin = async () => ({
|
||||
auth: ${auth}, ${tools}
|
||||
config: async (cfg) => { cfg.provider.fixture = {npm: "@ai-sdk/openai", models: {example: {}}} }
|
||||
})`)
|
||||
expect(result.code).toBe(1)
|
||||
expect(result.output).toContain("auth.loader")
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user