goanyapi: GoAnyAPI tools plugin, dynamic MCP catalog (#472)

Adds the GoAnyAPI tools plugin: its live MCP catalog (35 tools plus catalog and call_dynamic) behind OAuth or an API key.

Reviewed at 02f69af53. Maintainer fixes in 19808db: offline loading, a cached failed read, isError propagation, one User-Agent.
Run at this head: bun scripts/check.mjs ok; packages/goanyapi bun test 8 pass.
The author ran a real sign-in through magpie on macOS: an OAuth sign-in, a tool call from Codex, a refresh after expiry, and an error path.
This commit is contained in:
Fantasy
2026-10-29 21:59:03 +08:00
committed by GitHub
parent 3f73907aac
commit 01f6c09100
11 changed files with 3077 additions and 1 deletions
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 GoAnyAPI Contributors
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.
+46
View File
@@ -0,0 +1,46 @@
# GoAnyAPI for Magpie
Official website: [goanyapi.com](https://goanyapi.com/)
GoAnyAPI's complete, publicly advertised **read-only MCP API catalog** as Magpie tools. No API selection list is maintained in this plugin. It supports OAuth login through GoAnyAPI's remote MCP server and API-key login through its REST API.
## Install
Use **Plugins → Discover → Tools for agents** or:
```sh
magpie plugin add @magpie-community/tools-goanyapi
```
Sign in with **GoAnyAPI → Sign in** (OAuth, recommended):
```sh
magpie plugin login goanyapi oauth
```
Alternatively choose **GoAnyAPI API key** or use `magpie plugin login goanyapi api`. Existing API keys can also be supplied with `GOANYAPI_API_KEY` in the Magpie gateway process or through the `apiKey` plugin option. OAuth credentials are kept in Magpie's sign-in storage, and requests use the remote `https://mcp.goanyapi.com/mcp` server; no privileged backend secret is distributed.
## Connecting to agents
Magpie exposes plugin tools at its local Streamable HTTP endpoint `http://127.0.0.1:3425/mcp/magpie/tools`. Add this endpoint to your agent's MCP configuration using the URL shown in Magpie's Plugins page. Installing the plugin alone does not modify an agent's configuration.
All current read-only API definitions come from the public `https://api.goanyapi.com/api/v1/mcp/catalog` JSON Schema directory, with GoAnyAPI's built-in catalog as a failover. New published APIs do **not** require a new PR or changes to this package. **Magpie captures the named tool set when its plugin host loads**; restart/reload the plugin to show newly added tools as individual names. The permanent `catalog` and `call_dynamic` tools read the live catalog at invocation time, allowing access to a newly published API without updating the plugin itself.
## Authentication and credits
- **OAuth**: browser consent and OAuth 2.1/PKCE through GoAnyAPI's authorization server. API calls are sent to the remote MCP server, which validates the user's token.
- **API key**: REST requests to GoAnyAPI API endpoints using the user's API key, no backend-only secrets.
- API calls may consume GoAnyAPI account credits. Tool discovery reads the public catalog and is free.
- Never put API keys, access tokens, refresh tokens, or server-only secrets into public source or issues.
## Development
```sh
node --check packages/goanyapi/index.mjs
bun scripts/check.mjs
bun test
```
Tests are in `packages/goanyapi/tests`. Authentication tests use stubs, not live user credentials.
Source of truth: [GoAnyAPI MCP](https://github.com/GoAnyAPI/goanyapi-mcp). Magpie community repository: [magpie-community/plugins](https://github.com/magpie-community/plugins).
+192
View File
@@ -0,0 +1,192 @@
import { join } from "node:path";
import { Credentials } from "./src/auth.ts";
import { startOAuth } from "./src/oauth.ts";
import { cachedCatalog, loadApiCatalog } from "./src/catalog.ts";
import { serviceURL, USER_AGENT } from "./src/types.ts";
const API = "https://api.goanyapi.com";
const MCP = "https://mcp.goanyapi.com";
const PROVIDER = "goanyapi";
const validName = /^goanyapi_[a-z0-9_]+$/;
const validPath = /^\/api\/v1\/[a-z0-9/_-]+$/;
const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
function safeBase(url, fallback) {
const u = serviceURL(url ?? fallback);
if (u.search || u.hash || u.username || u.password) throw new Error("Invalid GoAnyAPI endpoint");
return u.href.replace(/\/$/, "");
}
function check(schema, args) {
if (!isObject(args)) throw new Error("Expected object arguments");
const props = schema.properties ?? {};
for (const key of schema.required ?? []) if (args[key] === undefined || args[key] === null) throw new Error("Missing required argument: " + key);
for (const [key, value] of Object.entries(args)) {
if (!Object.hasOwn(props, key)) throw new Error("Unknown argument: " + key);
if (value === undefined || value === null) continue;
const s = props[key];
if (s.type === "integer" && (!Number.isInteger(value))) throw new Error("Invalid integer argument: " + key);
else if (s.type === "number" && (typeof value !== "number" || !Number.isFinite(value))) throw new Error("Invalid number argument: " + key);
else if (s.type === "string" && typeof value !== "string") throw new Error("Invalid string argument: " + key);
else if (s.type === "boolean" && typeof value !== "boolean") throw new Error("Invalid boolean argument: " + key);
else if (s.type === "array" && !Array.isArray(value)) throw new Error("Invalid array argument: " + key);
else if (s.type === "object" && !isObject(value)) throw new Error("Invalid object argument: " + key);
if (s.enum && !s.enum.includes(value)) throw new Error("Unsupported argument value: " + key);
}
return args;
}
function nameOf(def) {
if (!validName.test(def.mcpName) || !validPath.test(def.path) || def.method !== "GET" || def.readOnly !== true || !isObject(def.inputSchema) || def.inputSchema.type !== "object") return null;
const name = def.mcpName.slice("goanyapi_".length);
return name.length > 0 && name.length <= 48 ? name : null;
}
function encodeQuery(args) {
const params = new URLSearchParams();
for (const [key, value] of Object.entries(args)) {
if (value === undefined || value === null || value === "") continue;
params.set(key, Array.isArray(value) || isObject(value) ? JSON.stringify(value) : String(value));
}
return params;
}
async function resultJson(response, label) {
if (!response.ok) {
await response.body?.cancel();
throw new Error("GoAnyAPI " + label + " failed (HTTP " + response.status + ")");
}
try { return await response.json(); }
catch { throw new Error("GoAnyAPI " + label + " returned invalid JSON"); }
}
async function mcpCall(mcpBase, token, method, params, signal) {
const response = await fetch(mcpBase + "/mcp", {
method: "POST", redirect: "error",
headers: {
"Authorization": "Bearer " + token,
"Content-Type": "application/json",
"Accept": "application/json, text/event-stream",
"MCP-Protocol-Version": "2025-11-25",
"User-Agent": USER_AGENT
},
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
signal: AbortSignal.any([signal, AbortSignal.timeout(48_000)])
});
if (!response.ok) {
await response.body?.cancel();
const error = new Error("GoAnyAPI MCP request failed (HTTP " + response.status + ")");
error.status = response.status;
throw error;
}
const contentType = response.headers.get("content-type") ?? "";
let message;
if (contentType.includes("text/event-stream")) {
const text = await response.text();
const data = text.split(/\r?\n/).filter(x => x.startsWith("data:")).map(x => x.slice(5).trim()).filter(Boolean);
for (const item of data) { try { const parsed = JSON.parse(item); if (parsed.id === 1) message = parsed; } catch {} }
} else message = await resultJson(response, "MCP");
if (!message || message.jsonrpc !== "2.0") throw new Error("GoAnyAPI MCP response is invalid");
if (message.error) throw new Error("GoAnyAPI MCP returned an error (" + (message.error.code ?? "unknown") + ")");
// a tool that failed answers with a result marked isError, not a JSON-RPC
// error: it is the call's failure, with GoAnyAPI's own words
if (message.result?.isError === true) {
const said = (Array.isArray(message.result.content) ? message.result.content : [])
.filter(c => c?.type === "text" && typeof c.text === "string").map(c => c.text).join("\n").trim();
throw new Error("GoAnyAPI tool failed" + (said ? ": " + said.slice(0, 500) : ""));
}
return message.result;
}
export async function GoAnyAPITools(input, options = {}) {
const apiBase = safeBase(options.baseUrl, API);
const mcpBase = safeBase(options.mcpBaseUrl, MCP);
const credentials = new Credentials(input, options);
// The named tools come from what is kept (the last live read on disk, else
// the bundled copy), so loading never waits on the network: magpie loads
// its plugins one after another. The live read runs in the background and
// is kept for the next load; catalog and call_dynamic read it live.
const diskPath = input?.directory ? join(input.directory, "goanyapi-catalog.json") : undefined;
const definitions = cachedCatalog(apiBase, diskPath);
loadApiCatalog(apiBase, 0, diskPath).catch(() => {});
const byName = new Map();
const tool = {};
async function invoke(def, args, ctx) {
const name = nameOf(def);
if (!name) throw new Error("Unsupported GoAnyAPI tool definition");
const validated = check(def.inputSchema, args);
const auth = await credentials.token(ctx?.abort);
const signal = AbortSignal.any([ctx?.abort ?? new AbortController().signal, AbortSignal.timeout(48_000)]);
if (auth.oauth) {
let current = auth;
try { return await mcpCall(mcpBase, current.token, "tools/call", { name: def.mcpName, arguments: validated }, signal); }
catch (error) {
if (error.status !== 401) throw error;
const renewed = await credentials.renew(auth.oauth, signal);
current = { token: renewed.access, oauth: renewed };
return mcpCall(mcpBase, current.token, "tools/call", { name: def.mcpName, arguments: validated }, signal);
}
}
const u = new URL(apiBase + def.path);
u.search = encodeQuery(validated).toString();
return resultJson(await fetch(u, {
method: "GET", redirect: "error", signal,
headers: { authorization: "Bearer " + auth.token, accept: "application/json", "User-Agent": USER_AGENT }
}), name);
}
for (const def of definitions) {
const name = nameOf(def);
if (!name || byName.has(name)) continue;
byName.set(name, def);
tool[name] = {
description: def.description,
args: def.inputSchema,
async execute(args, ctx) { return invoke(def, args, ctx); }
};
}
if (!byName.size) throw new Error("GoAnyAPI returned no valid tool definitions");
tool.catalog = {
description: "Discover the current GoAnyAPI tool catalog; newly added tools can be invoked with call_dynamic without reinstalling this plugin. Catalog is public and does not consume API credits.",
args: { type: "object", properties: {}, additionalProperties: false },
async execute() {
const defs = await loadApiCatalog(apiBase, 0, diskPath);
return defs.filter(d => nameOf(d)).map(d => ({ name: d.mcpName, description: d.description, inputSchema: d.inputSchema }));
}
};
tool.call_dynamic = {
description: "Call any current read-only GoAnyAPI tool by its catalog name. First use catalog to discover the latest tools; this works before Magpie restarts after a tool is added.",
args: {
type: "object",
properties: {
name: { type: "string", description: "Full name from GoAnyAPI catalog, e.g. goanyapi_traffic" },
arguments: { type: "object", description: "Arguments conforming to the selected tool's inputSchema" }
},
required: ["name", "arguments"],
additionalProperties: false
},
async execute(value, ctx) {
if (!isObject(value) || typeof value.name !== "string" || !isObject(value.arguments)) throw new Error("Invalid dynamic call arguments");
const defs = await loadApiCatalog(apiBase, 0, diskPath);
const def = defs.find(x => x.mcpName === value.name && nameOf(x));
if (!def) throw new Error("Tool is not published in the current GoAnyAPI catalog");
return invoke(def, value.arguments, ctx);
}
};
return {
config: async config => { config.provider ??= {}; config.provider[PROVIDER] ??= { name: "GoAnyAPI", models: {} }; },
auth: {
provider: PROVIDER, single: true,
methods: [
{ type: "oauth", label: "Sign in to GoAnyAPI", authorize: () => startOAuth(mcpBase, undefined, join(input.directory, "goanyapi-oauth-client.json")) },
{ type: "api", label: "GoAnyAPI API key" }
],
refreshLead: 60_000,
refresh: auth => credentials.renew(auth)
},
tool
};
}
+36
View File
@@ -0,0 +1,36 @@
{
"name": "@magpie-community/tools-goanyapi",
"version": "0.1.0",
"description": "All GoAnyAPI SEO, ads and web intelligence tools, generated from its live MCP catalog, with OAuth or API key",
"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/goanyapi"
},
"magpie": {
"icon": "https://goanyapi.com/logo.png"
},
"keywords": [
"magpie",
"magpie-tools",
"opencode-plugin",
"mcp",
"seo",
"website-traffic",
"ads-intelligence",
"goanyapi"
],
"scripts": {
"test": "bun test tests",
"lint": "node --check index.mjs"
}
}
+161
View File
@@ -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 goanyapi`, configure apiKey in plugin options, or set GOANYAPI_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, "goanyapi-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 GoAnyAPI 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 GoAnyAPI 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.GOANYAPI_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("GoAnyAPI 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();
}
}
}
File diff suppressed because it is too large Load Diff
+163
View File
@@ -0,0 +1,163 @@
import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
import { dirname } from 'node:path';
import {
apiCatalog as fallbackCatalog,
type JsonSchema,
type PublicApiDefinition,
} from './catalog-fallback.ts';
const CATALOG_PATH = '/api/v1/mcp/catalog';
const DEFAULT_CACHE_TTL_MS = 5 * 60 * 1000;
const REQUEST_TIMEOUT_MS = 10_000;
// After a failed read, the next ones answer at once from what is kept
// instead of each waiting out the timeout again.
const RETRY_AFTER_FAILURE_MS = 60_000;
type CatalogState = {
catalog?: readonly PublicApiDefinition[];
fetchedAt: number;
failedAt: number;
};
const catalogState = new Map<string, CatalogState>();
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function isJsonSchema(value: unknown): value is JsonSchema {
if (!isRecord(value)) return false;
if (
value.type !== 'object' &&
value.type !== 'string' &&
value.type !== 'integer' &&
value.type !== 'number' &&
value.type !== 'boolean' &&
value.type !== 'array'
) {
return false;
}
if (value.type === 'object' && value.properties !== undefined) {
if (!isRecord(value.properties)) return false;
if (!Object.values(value.properties).every(isJsonSchema)) return false;
}
if (value.type === 'array' && value.items !== undefined && !isJsonSchema(value.items)) {
return false;
}
return true;
}
function isPublicDefinition(value: unknown): value is PublicApiDefinition {
if (!isRecord(value)) return false;
return (
value.method === 'GET' &&
typeof value.id === 'string' &&
typeof value.path === 'string' &&
/^\/api\/v1\/[a-z0-9/_-]+$/.test(value.path) &&
typeof value.mcpName === 'string' &&
/^goanyapi_[a-z0-9_]+$/.test(value.mcpName) &&
typeof value.description === 'string' &&
value.readOnly === true &&
isJsonSchema(value.inputSchema)
);
}
// The valid entries of a catalog payload; an invalid entry is dropped, not
// the whole catalog. A payload with none is an error.
function parseApis(data: unknown): readonly PublicApiDefinition[] {
if (!isRecord(data) || data.schemaVersion !== 1 || !Array.isArray(data.apis)) {
throw new Error('Catalog response has an unsupported schema version.');
}
const catalog = data.apis.filter(isPublicDefinition);
if (catalog.length === 0) throw new Error('Catalog response has no valid API definition.');
return catalog;
}
function parseCatalog(value: unknown): readonly PublicApiDefinition[] {
if (!isRecord(value) || value.code !== 'ok' || !isRecord(value.data)) {
throw new Error('Catalog response has an invalid envelope.');
}
return parseApis(value.data);
}
async function fetchCatalog(baseUrl: string): Promise<readonly PublicApiDefinition[]> {
const response = await fetch(`${baseUrl}${CATALOG_PATH}`, {
headers: { accept: 'application/json' },
redirect: 'error',
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
});
const text = await response.text();
if (!response.ok) throw new Error(`Catalog request failed with status ${response.status}.`);
return parseCatalog(text ? JSON.parse(text) : null);
}
function normalize(baseUrl: string) {
return baseUrl.replace(/\/$/, '');
}
// The catalog the last live read left on disk, for this base only.
function readDisk(baseUrl: string, diskPath?: string): readonly PublicApiDefinition[] | undefined {
if (!diskPath) return undefined;
try {
const kept = JSON.parse(readFileSync(diskPath, 'utf8'));
if (!isRecord(kept) || kept.base !== baseUrl) return undefined;
return parseApis(kept);
} catch {
return undefined;
}
}
// Written to a temp file and renamed over the old one, so a reader never
// sees half of it.
function writeDisk(baseUrl: string, diskPath: string | undefined, catalog: readonly PublicApiDefinition[]) {
if (!diskPath) return;
const temp = `${diskPath}.${process.pid}.tmp`;
try {
mkdirSync(dirname(diskPath), { recursive: true });
writeFileSync(temp, JSON.stringify({ schemaVersion: 1, base: baseUrl, apis: catalog }), { mode: 0o600 });
renameSync(temp, diskPath);
} catch {}
}
// cachedCatalog answers without the network: the last live read in this
// process, else the one kept on disk, else the bundled copy.
export function cachedCatalog(baseUrl: string, diskPath?: string): readonly PublicApiDefinition[] {
const base = normalize(baseUrl);
return catalogState.get(base)?.catalog ?? readDisk(base, diskPath) ?? fallbackCatalog;
}
// loadApiCatalog reads the live catalog unless one read less than
// maxAgeMs ago is kept (0: always read). While a read failed less than a
// minute ago it answers from cachedCatalog at once.
export async function loadApiCatalog(
baseUrl: string,
maxAgeMs = DEFAULT_CACHE_TTL_MS,
diskPath?: string
): Promise<readonly PublicApiDefinition[]> {
const base = normalize(baseUrl);
const state = catalogState.get(base) ?? { fetchedAt: 0, failedAt: 0 };
catalogState.set(base, state);
const now = Date.now();
if (state.catalog && now - state.fetchedAt < maxAgeMs) return state.catalog;
if (state.failedAt && now - state.failedAt < RETRY_AFTER_FAILURE_MS) {
return cachedCatalog(base, diskPath);
}
try {
const catalog = await fetchCatalog(base);
state.catalog = catalog;
state.fetchedAt = Date.now();
state.failedAt = 0;
writeDisk(base, diskPath, catalog);
return catalog;
} catch (error) {
state.failedAt = Date.now();
console.warn('Unable to load the remote GoAnyAPI catalog; using the last one kept.', String(error));
return cachedCatalog(base, diskPath);
}
}
export function clearCatalogCache() {
catalogState.clear();
}
export { fallbackCatalog };
+364
View File
@@ -0,0 +1,364 @@
import { createHash, randomBytes } from "node:crypto";
import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import { dirname } from "node:path";
import { serviceURL, type StoredOAuth } from "./types.ts";
const SCOPES = "mcp:invoke";
const NETWORK_TIMEOUT = 15_000;
const LOGIN_TIMEOUT = 5 * 60_000;
// Lets GoAnyAPI attribute sign-ups to Magpie; authorization ignores it.
const SOURCE = "magpie";
const CALLBACK = /^http:\/\/127\.0\.0\.1:(\d{1,5})\/callback$/;
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(
`GoAnyAPI 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(
"GoAnyAPI 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 GoAnyAPI OAuth endpoint.");
}
if (!metadata.code_challenge_methods_supported?.includes("S256"))
throw new Error("GoAnyAPI 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("GoAnyAPI OAuth returned an invalid access token.");
}
if (
tokens.expires_in !== undefined &&
(!Number.isFinite(tokens.expires_in) || tokens.expires_in <= 0)
) {
throw new Error("GoAnyAPI 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("GoAnyAPI 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,
);
}
interface SavedClient {
issuer: string;
clientId: string;
redirectUri: string;
}
// The registered public client and its loopback callback are reused, so each
// sign-in does not register another OAuth application at GoAnyAPI.
async function savedClient(
file: string | undefined,
issuer: string,
): Promise<SavedClient | undefined> {
if (!file) return undefined;
try {
const value = JSON.parse(await readFile(file, "utf8")) as SavedClient;
if (
value?.issuer === issuer &&
typeof value.clientId === "string" &&
value.clientId &&
typeof value.redirectUri === "string" &&
CALLBACK.test(value.redirectUri)
)
return value;
} catch {}
return undefined;
}
function listen(server: Server, port: number) {
return new Promise<void>((resolve, reject) => {
const failed = (error: Error) => reject(error);
server.once("error", failed);
server.listen(port, "127.0.0.1", () => {
server.off("error", failed);
resolve();
});
});
}
export async function startOAuth(
baseUrl: string,
timeoutMs = LOGIN_TIMEOUT,
clientFile?: string,
) {
const metadata = await discover(baseUrl);
let saved = await savedClient(clientFile, metadata.issuer);
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:
"GoAnyAPI 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.",
);
});
try {
await listen(server, saved ? Number(CALLBACK.exec(saved.redirectUri)![1]) : 0);
} catch (error) {
// Its port is taken: sign in through a new client instead.
if (!saved) throw error;
saved = undefined;
await listen(server, 0);
}
server.unref();
const close = () => {
server.close();
server.closeAllConnections();
};
const timer = setTimeout(() => {
settle({ error: "GoAnyAPI 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`;
let clientId = saved?.clientId;
if (!clientId) {
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: "GoAnyAPI 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("GoAnyAPI OAuth did not register a public client.");
}
clientId = registration.client_id;
if (clientFile) {
const record: SavedClient = {
issuer: metadata.issuer,
clientId,
redirectUri: redirect,
};
// The client is public: losing this file costs one registration.
await mkdir(dirname(clientFile), { recursive: true })
.then(() =>
writeFile(clientFile, JSON.stringify(record), { mode: 0o600 }),
)
.catch(() => {});
}
}
const url = new URL(metadata.authorization_endpoint);
for (const [key, value] of Object.entries({
response_type: "code",
client_id: clientId,
redirect_uri: redirect,
scope: SCOPES,
state,
code_challenge: challenge,
code_challenge_method: "S256",
utm_source: SOURCE,
}))
url.searchParams.set(key, value);
let completed = false;
// A reused client the server no longer knows fails in the browser, so a
// sign-in that does not finish registers afresh next time.
const forget = async () => {
if (saved && clientFile) await unlink(clientFile).catch(() => {});
};
return {
url: url.href,
instructions:
"Sign in to GoAnyAPI 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) {
await forget();
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: clientId,
code_verifier: verifier,
}),
});
const { type: _, ...auth } = credential(tokens, clientId, metadata);
return { type: "success" as const, ...auth };
} catch (error) {
await forget();
return {
type: "failed" as const,
error:
error instanceof Error
? error.message
: "GoAnyAPI OAuth failed.",
};
} finally {
clearTimeout(timer);
close();
}
},
};
} catch (error) {
clearTimeout(timer);
close();
throw error;
}
}
+49
View File
@@ -0,0 +1,49 @@
export const PROVIDER = "goanyapi";
export const API_BASE = "https://api.goanyapi.com";
export const MCP_BASE = "https://mcp.goanyapi.com";
// Identifies Magpie traffic to GoAnyAPI; keep in step with package.json.
export const USER_AGENT = "goanyapi-magpie/0.1.0";
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;
mcpBaseUrl?: 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(
"GoAnyAPI endpoints must use HTTPS (HTTP is allowed on loopback for local testing).",
);
}
return url;
}
+120
View File
@@ -0,0 +1,120 @@
import { test, afterEach } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { GoAnyAPITools } from "../index.mjs";
import { clearCatalogCache, fallbackCatalog } from "../src/catalog.ts";
const traffic = {id:"traffic",method:"GET",path:"/api/v1/traffic",mcpName:"goanyapi_traffic",description:"Traffic",readOnly:true,inputSchema:{type:"object",properties:{domain:{type:"string"}},required:["domain"],additionalProperties:false}};
const added = {id:"new",method:"GET",path:"/api/v1/new",mcpName:"goanyapi_new",description:"New",readOnly:true,inputSchema:{type:"object",properties:{},required:[],additionalProperties:false}};
const dirs = [];
const previous = globalThis.fetch;
function home() { const d = mkdtempSync(join(tmpdir(), "goanyapi-")); dirs.push(d); return d; }
function input(directory = home()) { return {directory,client:{auth:{set:async()=>{}}}}; }
const ctx = () => ({abort:new AbortController().signal});
afterEach(() => { globalThis.fetch = previous; clearCatalogCache(); for (const d of dirs.splice(0)) rmSync(d, {recursive:true,force:true}); });
function fixture() {
let catalog = [traffic];
const calls = [];
let catalogReads = 0;
const fetcher = async (input, init={}) => {
const url = new URL(input);
if (url.pathname === "/api/v1/mcp/catalog") { catalogReads++; return Response.json({code:"ok",data:{schemaVersion:1,apis:catalog}}); }
calls.push({url:url.href,init});
return Response.json({code:"ok",domain:url.searchParams.get("domain")});
};
globalThis.fetch = fetcher;
return {calls,get catalogReads(){return catalogReads},get catalog(){return catalog},set catalog(value){catalog=value}};
}
// the background read that loading starts
const settle = () => new Promise(r => setTimeout(r, 20));
test("every catalog tool is mapped and API key goes to REST", async () => {
const f = fixture();
const plugin = await GoAnyAPITools(input(), {apiKey:"private-test",baseUrl:"http://127.0.0.1:9091"});
assert.ok(plugin.tool.traffic);assert.ok(plugin.tool.catalog);assert.ok(plugin.tool.call_dynamic);
const output = await plugin.tool.traffic.execute({domain:"example.com"}, ctx());
assert.equal(output.domain,"example.com"); assert.equal(f.calls.length,1);assert.equal(f.calls[0].init.headers.authorization,"Bearer private-test");
assert.match(f.calls[0].init.headers["User-Agent"], /^goanyapi-magpie\//);
await assert.rejects(()=>plugin.tool.traffic.execute({other:"x"}, ctx()), /Missing required|Unknown argument/);
assert.ok(!JSON.stringify(output).includes("private-test"));
});
test("new tools become available through live catalog without a PR", async () => {
const f = fixture();
const plugin = await GoAnyAPITools(input(), {apiKey:"private-test",baseUrl:"http://127.0.0.1:9092"});
await settle();
f.catalog = [...f.catalog, added];
const names = await plugin.tool.catalog.execute({});
assert.equal(names.length,2); assert.equal(plugin.tool.new,undefined);
await plugin.tool.call_dynamic.execute({name:"goanyapi_new",arguments:{}},ctx());
assert.ok(f.calls.some(c=>c.url.includes("/api/v1/new")));
await assert.rejects(()=>plugin.tool.call_dynamic.execute({name:"goanyapi_hidden",arguments:{}},ctx()), /not published/);
});
test("loading never waits on the catalog read", async () => {
globalThis.fetch = (_url, init={}) => new Promise((_, reject) => init.signal?.addEventListener("abort", () => reject(init.signal.reason)));
const started = Date.now();
const plugin = await GoAnyAPITools(input(), {apiKey:"k",baseUrl:"http://127.0.0.1:9093"});
assert.ok(Date.now() - started < 1000, "load waited on the network");
// the named tools are the bundled catalog's
assert.equal(Object.keys(plugin.tool).length, fallbackCatalog.length + 2);
});
test("the last live catalog is kept on disk and named at the next load", async () => {
const f = fixture();
const directory = home();
f.catalog = [traffic, added];
await GoAnyAPITools(input(directory), {apiKey:"k",baseUrl:"http://127.0.0.1:9094"});
await settle();
const kept = JSON.parse(readFileSync(join(directory, "goanyapi-catalog.json"), "utf8"));
assert.equal(kept.apis.length, 2);
clearCatalogCache();
globalThis.fetch = async () => { throw new Error("offline"); };
const plugin = await GoAnyAPITools(input(directory), {apiKey:"k",baseUrl:"http://127.0.0.1:9094"});
assert.ok(plugin.tool.new);
// another base doesn't take this one's catalog
const other = await GoAnyAPITools(input(directory), {apiKey:"k",baseUrl:"http://127.0.0.1:9095"});
assert.equal(other.tool.new, undefined);
});
test("a failed read is not retried by every call for a minute", async () => {
let reads = 0;
globalThis.fetch = async () => { reads++; throw new Error("offline"); };
const plugin = await GoAnyAPITools(input(), {apiKey:"k",baseUrl:"http://127.0.0.1:9096"});
await settle();
const list = await plugin.tool.catalog.execute({});
await plugin.tool.catalog.execute({});
assert.equal(reads, 1);
assert.equal(list.length, fallbackCatalog.length);
});
test("one invalid entry drops that entry, not the catalog", async () => {
const f = fixture();
f.catalog = [traffic, added, {...added, mcpName:"bad name"}];
const plugin = await GoAnyAPITools(input(), {apiKey:"k",baseUrl:"http://127.0.0.1:9097"});
const names = await plugin.tool.catalog.execute({});
assert.deepEqual(names.map(n => n.name), ["goanyapi_traffic","goanyapi_new"]);
});
test("the bundled catalog passes the same checks as a live one", async () => {
globalThis.fetch = async () => { throw new Error("offline"); };
const plugin = await GoAnyAPITools(input(), {apiKey:"k",baseUrl:"http://127.0.0.1:9098"});
for (const def of fallbackCatalog) assert.ok(plugin.tool[def.mcpName.slice("goanyapi_".length)], def.mcpName);
});
test("an MCP tool result marked isError fails the call", async () => {
const directory = home();
const { writeFileSync } = await import("node:fs");
writeFileSync(join(directory, "plugin-auth.json"), JSON.stringify({goanyapi:{type:"oauth",access:"a",refresh:"r",expires:Date.now()+3600e3,clientId:"c",tokenEndpoint:"https://mcp.goanyapi.com/token",issuer:"https://mcp.goanyapi.com"}}));
globalThis.fetch = async (url) => {
const u = new URL(url);
if (u.pathname === "/api/v1/mcp/catalog") return Response.json({code:"ok",data:{schemaVersion:1,apis:[traffic]}});
return Response.json({jsonrpc:"2.0",id:1,result:{isError:true,content:[{type:"text",text:"Insufficient credits"}]}});
};
const plugin = await GoAnyAPITools(input(directory), {baseUrl:"http://127.0.0.1:9099",mcpBaseUrl:"http://127.0.0.1:9100"});
await assert.rejects(() => plugin.tool.traffic.execute({domain:"example.com"}, ctx()), /GoAnyAPI tool failed: Insufficient credits/);
});
+3 -1
View File
@@ -116,6 +116,8 @@
{ "package": "@hoptoper/magpie-agent-citebox", "name": "CiteBox", "kind": "agent",
"summary": { "en": "CiteBox on magpie's Agents page: pick one of magpie's models for its text AI, set reasoning effort in Settings, and switch it off to put its config back. Needs CiteBox 0.38.0 or later.", "zh": "把 CiteBox 加到 magpie 的 Agent 页:给它的文本 AI 选 magpie 的模型,在设置里调整思考强度,关掉即恢复原来的配置。需要 CiteBox 0.38.0 或更新版本。" } },
{ "package": "@hoptoper/magpie-agent-wisp-science", "name": "Wisp Science", "kind": "agent",
"summary": { "en": "Wisp Science on magpie's Agents page: pick one of magpie's models, set reasoning effort in the composer, and switch it off to put its config back. Needs Wisp Science 1.23.0 or later.", "zh": "把 Wisp Science 加到 magpie 的 Agent 页:选择 magpie 的模型,在输入框里设置思考强度,关掉即恢复原来的配置。需要 Wisp Science 1.23.0 或更新版本。" } }
"summary": { "en": "Wisp Science on magpie's Agents page: pick one of magpie's models, set reasoning effort in the composer, and switch it off to put its config back. Needs Wisp Science 1.23.0 or later.", "zh": "把 Wisp Science 加到 magpie 的 Agent 页:选择 magpie 的模型,在输入框里设置思考强度,关掉即恢复原来的配置。需要 Wisp Science 1.23.0 或更新版本。" } },
{ "package": "@magpie-community/tools-goanyapi", "name": "GoAnyAPI", "icon": "https://goanyapi.com/logo.png", "kind": "tools", "community": true,
"summary": { "en": "All GoAnyAPI website traffic, SEO, SERP, backlinks and ads intelligence tools from a live MCP catalog. Supports OAuth or API key sign-in.", "zh": "自动接入 GoAnyAPI 动态目录中的全部网站流量、SEO、SERP、外链和广告情报工具,支持 OAuth 或 API Key 登录。" } }
]
}