Files
plugins/packages/search1api/src/tools.ts
T
wang2 6188ab5be7 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.
2026-10-25 17:53:00 +08:00

82 lines
3.4 KiB
TypeScript

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 }),
};
}