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
+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;
}