diff --git a/packages/goanyapi/LICENSE b/packages/goanyapi/LICENSE new file mode 100644 index 0000000..0c531d3 --- /dev/null +++ b/packages/goanyapi/LICENSE @@ -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. diff --git a/packages/goanyapi/README.md b/packages/goanyapi/README.md new file mode 100644 index 0000000..3a15dcc --- /dev/null +++ b/packages/goanyapi/README.md @@ -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). diff --git a/packages/goanyapi/index.mjs b/packages/goanyapi/index.mjs new file mode 100644 index 0000000..d110f74 --- /dev/null +++ b/packages/goanyapi/index.mjs @@ -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 + }; +} diff --git a/packages/goanyapi/package.json b/packages/goanyapi/package.json new file mode 100644 index 0000000..d08afea --- /dev/null +++ b/packages/goanyapi/package.json @@ -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" + } +} diff --git a/packages/goanyapi/src/auth.ts b/packages/goanyapi/src/auth.ts new file mode 100644 index 0000000..d873838 --- /dev/null +++ b/packages/goanyapi/src/auth.ts @@ -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 { + 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)[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> { + 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 { + 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(); + } + } +} diff --git a/packages/goanyapi/src/catalog-fallback.ts b/packages/goanyapi/src/catalog-fallback.ts new file mode 100644 index 0000000..b71a432 --- /dev/null +++ b/packages/goanyapi/src/catalog-fallback.ts @@ -0,0 +1,1922 @@ +/** + * The bundled copy of GoAnyAPI's public catalog + * (https://api.goanyapi.com/api/v1/mcp/catalog, schemaVersion 1), used + * until a live read succeeds: when magpie's plugin host loads the plugin + * (the named tools come from it, or from the copy the last live read left + * on disk), and while api.goanyapi.com can't be reached. + * + * Generated from the live catalog on 2026-10-29 (35 entries). Regenerate it + * from that URL when GoAnyAPI adds or renames an API, so an agent sees the + * same tool names whether or not the live read worked. + */ + +export type JsonSchema = { + type: 'object' | 'string' | 'integer' | 'number' | 'boolean' | 'array'; + title?: string; + description?: string; + properties?: Record; + required?: string[]; + enum?: Array; + items?: JsonSchema; + default?: string | number | boolean; + additionalProperties?: boolean; + // the live catalog also carries pattern, minLength, examples, oneOf, … + [keyword: string]: unknown; +}; + +export interface PublicApiDefinition { + readonly id: string; + readonly method: 'GET' | 'POST'; + readonly path: `/api/v1/${string}`; + readonly inputSchema: JsonSchema; + readonly mcpName: `goanyapi_${string}`; + readonly description: string; + readonly readOnly: true; + readonly docsPath?: string; +} + +export const apiCatalog: readonly PublicApiDefinition[] = [ + { + "id": "capcut-most-used-times", + "method": "GET", + "path": "/api/v1/capcut-most-used/times", + "mcpName": "goanyapi_capcut_most_used_times", + "description": "List available successful CapCut Most Used snapshot hours for a required YYYYMMDD day in Asia/Shanghai (UTC+8). Returns hours as integers 0–23 in data.times. Free; authentication required. Historical snapshots are retained for 30 days; unavailable days return an empty array. This endpoint is free and does not consume credits.", + "readOnly": true, + "docsPath": "/docs/tiktok-capcut-trending-templates-api", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "day": { + "type": "string", + "pattern": "^[0-9]{8}$", + "minLength": 8, + "maxLength": 8, + "description": "Required valid calendar date YYYYMMDD in Asia/Shanghai (UTC+8). Snapshots retained for 30 days; unavailable dates return no results.", + "examples": [ + "20261027" + ] + } + }, + "required": [ + "day" + ] + } + }, + { + "id": "capcut-most-used-history", + "method": "GET", + "path": "/api/v1/capcut-most-used/history", + "mcpName": "goanyapi_capcut_most_used_history", + "description": "Read a CapCut Most Used snapshot for required day (YYYYMMDD) and time (integer hour 0–23, Asia/Shanghai). First call goanyapi_capcut_most_used_times for available hours. page defaults to 0, range 0–19. Preserve day/time when following nextPage; stop when nextPage is null. Returns template IDs as strings, titles, covers, preview videos, usage estimates and historical positions. Duplicates and order are preserved; page size varies. Snapshots retained for 30 days. Non-empty successful pages use the configured rate; empty lists and failures are not charged. With the current configuration, each successful request costs 2 credits.", + "readOnly": true, + "docsPath": "/docs/tiktok-capcut-trending-templates-api", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "day": { + "type": "string", + "pattern": "^[0-9]{8}$", + "minLength": 8, + "maxLength": 8, + "description": "Required valid calendar date YYYYMMDD in Asia/Shanghai (UTC+8). Snapshots retained for 30 days; unavailable dates return no results.", + "examples": [ + "20261027" + ] + }, + "time": { + "type": "integer", + "minimum": 0, + "maximum": 23, + "description": "Required hour in Asia/Shanghai, chosen from the times response for the same day.", + "examples": [ + 10 + ] + }, + "page": { + "type": "integer", + "minimum": 0, + "maximum": 19, + "default": 0, + "description": "Zero-based page. Use nextPage from the preceding response; stop when null. Page size varies; duplicates are preserved.", + "examples": [ + 0, + 1 + ] + } + }, + "required": [ + "day", + "time" + ] + } + }, + { + "id": "capcut-most-used-realtime", + "method": "GET", + "path": "/api/v1/capcut-most-used/realtime", + "mcpName": "goanyapi_capcut_most_used_realtime", + "description": "Read one current CapCut Most Used template page. page defaults to 0, range 0–19. Follow returned nextPage until null; results may change between requests. Returns string template IDs, titles, template links, covers, preview videos and usage estimates. Duplicates and order are preserved; count includes duplicate cards and page size varies. Non-empty successful pages use the configured rate; empty lists and failures are not charged. With the current configuration, each successful request costs 2 credits.", + "readOnly": true, + "docsPath": "/docs/tiktok-capcut-trending-templates-api", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "page": { + "type": "integer", + "minimum": 0, + "maximum": 19, + "default": 0, + "description": "Zero-based page. Use nextPage from the preceding response; stop when null. Page size varies; duplicates are preserved.", + "examples": [ + 0, + 1 + ] + } + }, + "required": [] + } + }, + { + "id": "taaft-tools-api", + "method": "GET", + "path": "/api/v1/taaft-tools", + "mcpName": "goanyapi_taaft_tools_api", + "description": "Browse the TAAFT AI tools catalog by zero-based page (default 0). Returns items with name, nullable version, description, category, domain, pricingText, releasedAt and links. Returns total, page, pageSize and totalPages; use nextPage while hasMore is true. nextPage is null on the last page or an empty catalog. Optional year selects releases for an entire year; optional month requires year and selects that month. Future years and months are rejected in Asia/Shanghai. Returns nullable numeric views, saves and averageRating. No pageSize input. Non-empty successful pages use the configured credit rate; empty lists and failures are not charged. With the current configuration, each successful request costs 2 credits.", + "readOnly": true, + "docsPath": "/docs/taaft-tools-api", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "page": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "default": 0, + "description": "Zero-based page. Omit for page 0. Use nextPage while hasMore is true and keep the same year/month filters; an empty items array is valid. No pageSize input.", + "examples": [ + 0, + 1 + ] + }, + "year": { + "type": "integer", + "minimum": 2015, + "maximum": 2026, + "description": "Optional release year in Asia/Shanghai. Omit year and month for all releases; year alone selects the entire year.", + "examples": [ + 2025, + 2026 + ] + }, + "month": { + "type": "integer", + "minimum": 1, + "maximum": 12, + "description": "Optional release month; requires year. For year 2026, maximum month is 10. Omit for the entire selected year.", + "examples": [ + 1 + ] + } + }, + "required": [], + "oneOf": [ + { + "type": "object", + "not": { + "type": "object", + "anyOf": [ + { + "type": "object", + "required": [ + "year" + ] + }, + { + "type": "object", + "required": [ + "month" + ] + } + ] + } + }, + { + "type": "object", + "required": [ + "year" + ], + "not": { + "type": "object", + "required": [ + "month" + ] + } + }, + { + "type": "object", + "required": [ + "year", + "month" + ], + "properties": { + "year": { + "type": "integer", + "maximum": 2025 + }, + "month": { + "type": "integer", + "maximum": 12 + } + } + }, + { + "type": "object", + "required": [ + "year", + "month" + ], + "properties": { + "year": { + "type": "integer", + "enum": [ + 2026 + ] + }, + "month": { + "type": "integer", + "maximum": 10 + } + } + } + ] + } + }, + { + "id": "taaft-just-released-api", + "method": "GET", + "path": "/api/v1/taaft-just-released-api", + "mcpName": "goanyapi_taaft_just_released_api", + "description": "List tools from the Just Released section of There's An AI For That (TAAFT, theresanaiforthat.com), an AI tools directory. This endpoint covers TAAFT listings only, not other AI directories or all AI tool launches. Optional day is YYYYMMDD in Asia/Shanghai (UTC+8), defaults to today, and must be within the latest 30 calendar days including today. Returns day and the available items for that date, including name, description, category, domain, pricingText, releasedAt and links. No pagination. Non-empty successful results use the configured credit rate; empty lists and failures are not charged. With the current configuration, each successful request costs 2 credits.", + "readOnly": true, + "docsPath": "/docs/taaft-just-released-api", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "day": { + "type": "string", + "pattern": "^[0-9]{8}$", + "enum": [ + "20261029", + "20261028", + "20261027", + "20261026", + "20261025", + "20261024", + "20261023", + "20261022", + "20261021", + "20261020", + "20261019", + "20261018", + "20261017", + "20261016", + "20261015", + "20261014", + "20261013", + "20261012", + "20261011", + "20261010", + "20261009", + "20261008", + "20261007", + "20261006", + "20261005", + "20261004", + "20261003", + "20261002", + "20261001", + "20260930" + ], + "default": "20261029", + "description": "Optional YYYYMMDD date in Asia/Shanghai (UTC+8). Omit for today. Accepts the latest 30 calendar days including today (20260930–20261029); future dates are rejected. Returns all items for that date; no pagination.", + "examples": [ + "20261029", + "20260930" + ] + } + }, + "required": [] + } + }, + { + "id": "tiktok-creator", + "method": "GET", + "path": "/api/v1/tiktok-creator", + "mcpName": "goanyapi_tiktok_creator", + "description": "List CapCut creator templates with TikTok Creator API. Provide exactly one of profileId or url. type=video (default) lists video templates; type=image lists image templates. cursor defaults to 0; use new_cursor for the next page while has_more is true. Each page contains up to 20 templates, fixed. Each non-empty page uses the configured credit rate; empty lists and failures are not charged. With the current configuration, each successful request costs 3 credits.", + "readOnly": true, + "docsPath": "/docs/tiktok-creator-api", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "profileId": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{1,202}$", + "description": "CapCut creator profile ID containing letters, digits, underscores or hyphens; a p- prefix is not required. Provide exactly one of profileId or url.", + "examples": [ + "p-kYX4pYJcVgN831-fvSPFbjrcI__F_99soyLmN877o" + ] + }, + "url": { + "type": "string", + "pattern": "^https://(www\\.)?capcut\\.com/profile/[A-Za-z0-9_-]{1,202}/?(\\?[^#]*)?(#.*)?$", + "maxLength": 2048, + "description": "HTTPS CapCut /profile/{profileId} URL, parsed locally. Mutually exclusive with profileId.", + "examples": [ + "https://www.capcut.com/profile/p-kYX4pYJcVgN831-fvSPFbjrcI__F_99soyLmN877o" + ] + }, + "type": { + "type": "string", + "enum": [ + "video", + "image" + ], + "default": "video", + "description": "video lists video templates; image lists image templates." + }, + "cursor": { + "type": "string", + "pattern": "^[0-9]{1,20}$", + "default": "0", + "description": "Start with 0. For the next page, pass new_cursor from the preceding response unchanged. Stop when has_more is false.", + "examples": [ + "0", + "1733081486000" + ] + } + }, + "oneOf": [ + { + "type": "object", + "required": [ + "profileId" + ], + "not": { + "type": "object", + "required": [ + "url" + ] + } + }, + { + "type": "object", + "required": [ + "url" + ], + "not": { + "type": "object", + "required": [ + "profileId" + ] + } + } + ] + } + }, + { + "id": "html-to-markdown-api", + "method": "GET", + "path": "/api/v1/html-to-markdown-api", + "mcpName": "goanyapi_html_to_markdown_api", + "description": "Convert a public web page to Markdown. Provide url; optionally choose image and link retention or a CSS selector for the target content. A successful request for https://google.com is free; other successful requests use the configured credit price.", + "readOnly": true, + "docsPath": "/docs/html-to-markdown-api", + "inputSchema": { + "type": "object", + "properties": { + "url": { + "type": "string", + "pattern": "^[Hh][Tt][Tt][Pp][Ss]?://", + "maxLength": 2048, + "description": "Public HTTP or HTTPS page URL. https://google.com is a free live demo; local and private addresses are not accepted.", + "examples": [ + "https://google.com" + ] + }, + "retainImages": { + "type": "string", + "enum": [ + "all", + "alt", + "none" + ], + "default": "all", + "description": "all keeps images, alt keeps alt text only, none removes images." + }, + "retainLinks": { + "type": "string", + "enum": [ + "all", + "text", + "none" + ], + "default": "all", + "description": "all keeps links, text keeps link text only, none removes links." + }, + "targetSelector": { + "type": "string", + "minLength": 1, + "maxLength": 200, + "description": "Optional CSS selector for the content to extract, for example article.", + "examples": [ + "article" + ] + } + }, + "required": [ + "url" + ], + "additionalProperties": false + } + }, + { + "id": "trustmrr-api", + "method": "GET", + "path": "/api/v1/trustmrr-api", + "mcpName": "goanyapi_trustmrr_api", + "description": "List TrustMRR projects and revenue with zero-based pagination. page defaults to 0; pageSize is fixed at 10. Returns items, total, page, pageSize and totalPages. Replaces the former domain lookup; use page instead of domain.", + "readOnly": true, + "docsPath": "/docs/trustmrr-api", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "page": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "default": 0, + "description": "Zero-based page index. Example: 0 for the first page.", + "examples": [ + 0, + 1 + ] + }, + "pageSize": { + "type": "integer", + "enum": [ + 10 + ], + "default": 10, + "description": "Fixed at 10 items per page." + } + }, + "required": [] + } + }, + { + "id": "chrome-web-store-reviews", + "method": "GET", + "path": "/api/v1/chrome-web-store-reviews", + "mcpName": "goanyapi_chrome_web_store_reviews", + "description": "Fetch Chrome Web Store reviews with cursor pagination.", + "readOnly": true, + "docsPath": "/docs/chrome-web-store-reviews-api", + "inputSchema": { + "type": "object", + "properties": { + "extensionId": { + "type": "string", + "minLength": 32, + "maxLength": 2048, + "description": "A 32-character Chrome extension ID or a Chrome Web Store URL.", + "examples": [ + "hldjnlbobkdkghfidgoecgmklcemanhm", + "https://chromewebstore.google.com/detail/hldjnlbobkdkghfidgoecgmklcemanhm" + ] + }, + "cursor": { + "type": "string", + "maxLength": 4096, + "description": "Opaque cursor returned by the previous response; omit it for the first page." + } + }, + "required": [ + "extensionId" + ], + "additionalProperties": false + } + }, + { + "id": "traffic", + "method": "GET", + "path": "/api/v1/traffic", + "mcpName": "goanyapi_traffic", + "description": "Query website traffic, ranking, and traffic sources for a domain.", + "readOnly": true, + "docsPath": "/docs/traffic-api", + "inputSchema": { + "type": "object", + "properties": { + "domain": { + "type": "string", + "description": "Domain name, for example example.com" + }, + "month": { + "type": "integer", + "enum": [ + 3, + 6, + 12 + ], + "default": 3, + "description": "Traffic history range in months" + } + }, + "required": [ + "domain" + ], + "additionalProperties": false + } + }, + { + "id": "dr", + "method": "GET", + "path": "/api/v1/dr", + "mcpName": "goanyapi_domain_rating", + "description": "Query the domain rating for a domain.", + "readOnly": true, + "docsPath": "/docs/dr-api", + "inputSchema": { + "type": "object", + "properties": { + "domain": { + "type": "string", + "description": "Domain name, for example example.com" + } + }, + "required": [ + "domain" + ], + "additionalProperties": false + } + }, + { + "id": "dr-history", + "method": "GET", + "path": "/api/v1/dr-history", + "mcpName": "goanyapi_domain_rating_history", + "description": "Query monthly Domain Rating history. Ratings may contain decimals. Set includeDr=false to preview the available months and exact required credits without a deduction, or includeDr=true to return ratings and charge the current Domain Rating credit cost for each returned month. An empty history returns an empty list and costs 0 credits. Both modes require enough credits for the full result; insufficient balance returns HTTP 402 without history data.", + "readOnly": true, + "docsPath": "/docs/domain-rating-history-api", + "inputSchema": { + "type": "object", + "properties": { + "domain": { + "type": "string", + "description": "Domain name, for example example.com" + }, + "includeDr": { + "type": "boolean", + "default": false, + "description": "Whether to return Domain Rating values. Defaults to false. false returns only months plus the exact required credits and deducts 0 credits; true returns month and dr values and deducts the current Domain Rating credit cost for each returned month. Both modes return HTTP 402 without history data when the balance is insufficient." + } + }, + "required": [ + "domain" + ], + "additionalProperties": false, + "examples": [ + { + "domain": "kviku.com", + "includeDr": false + }, + { + "domain": "kviku.com", + "includeDr": true + } + ] + } + }, + { + "id": "backlink", + "method": "GET", + "path": "/api/v1/backlink", + "mcpName": "goanyapi_backlinks", + "description": "Query backlink data for a domain.", + "readOnly": true, + "docsPath": "/docs/backlink-api", + "inputSchema": { + "type": "object", + "properties": { + "domain": { + "type": "string", + "description": "Domain name, for example example.com" + } + }, + "required": [ + "domain" + ], + "additionalProperties": false + } + }, + { + "id": "keyword-difficulty", + "method": "GET", + "path": "/api/v1/keyword-difficulty", + "mcpName": "goanyapi_keyword_difficulty", + "description": "Query keyword difficulty and related search metrics.", + "readOnly": true, + "docsPath": "/docs/keyword-difficulty-api", + "inputSchema": { + "type": "object", + "properties": { + "keyword": { + "type": "string", + "description": "Search keyword" + }, + "country": { + "type": "string", + "description": "Two-letter country code, for example us" + } + }, + "required": [ + "keyword" + ], + "additionalProperties": false + } + }, + { + "id": "keyword-generator", + "method": "GET", + "path": "/api/v1/keyword-generator", + "mcpName": "goanyapi_keyword_generator", + "description": "Generate related keyword ideas for a keyword.", + "readOnly": true, + "docsPath": "/docs/keyword-generator-api", + "inputSchema": { + "type": "object", + "properties": { + "keyword": { + "type": "string", + "description": "Search keyword" + }, + "country": { + "type": "string", + "description": "Two-letter country code, for example us" + } + }, + "required": [ + "keyword" + ], + "additionalProperties": false + } + }, + { + "id": "keyword-suggestions", + "method": "GET", + "path": "/api/v1/keyword-suggestions", + "mcpName": "goanyapi_keyword_suggestions", + "description": "Get paginated keyword suggestions before querying an exact keyword with the Keyword Search Volume API.", + "readOnly": true, + "docsPath": "/docs/keyword-suggestions-api", + "inputSchema": { + "type": "object", + "properties": { + "keyword": { + "type": "string", + "minLength": 1, + "maxLength": 200, + "description": "Keyword fragment used to find suggestions, from 1 to 200 characters." + }, + "page": { + "type": "integer", + "minimum": 0, + "maximum": 100000, + "default": 0, + "description": "Zero-based results page. Defaults to 0." + } + }, + "required": [ + "keyword" + ], + "additionalProperties": false, + "examples": [ + { + "keyword": "ai", + "page": 0 + } + ] + } + }, + { + "id": "keyword-search-volume", + "method": "GET", + "path": "/api/v1/keyword-search-volume", + "mcpName": "goanyapi_keyword_search_volume", + "description": "First call Keyword Suggestions API, then pass an exact value from its data.keywords results.", + "readOnly": true, + "docsPath": "/docs/keyword-search-volume-api", + "inputSchema": { + "type": "object", + "properties": { + "keyword": { + "type": "string", + "minLength": 1, + "maxLength": 200, + "description": "Exact keyword to query, from 1 to 200 characters." + } + }, + "required": [ + "keyword" + ], + "additionalProperties": false, + "examples": [ + { + "keyword": "ai image" + } + ] + } + }, + { + "id": "google-autocomplete", + "method": "GET", + "path": "/api/v1/google-autocomplete", + "mcpName": "goanyapi_google_autocomplete", + "description": "Get Google autocomplete suggestions for a query.", + "readOnly": true, + "docsPath": "/docs/google-autocomplete-api", + "inputSchema": { + "type": "object", + "properties": { + "q": { + "type": "string", + "minLength": 1, + "maxLength": 200, + "description": "Search query. Google queries are trimmed before sending." + }, + "domain": { + "type": "string", + "enum": [ + "www.google.com", + "www.google.com.hk" + ], + "default": "www.google.com", + "description": "Optional Google country domain." + }, + "hl": { + "type": "string", + "default": "en", + "pattern": "^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$", + "description": "Optional language code, for example en or zh-CN." + } + }, + "required": [ + "q" + ], + "additionalProperties": false, + "examples": [ + { + "q": "ai image", + "domain": "www.google.com", + "hl": "en" + } + ] + } + }, + { + "id": "bing-autocomplete", + "method": "GET", + "path": "/api/v1/bing-autocomplete", + "mcpName": "goanyapi_bing_autocomplete", + "description": "Get Bing autocomplete suggestions for a query.", + "readOnly": true, + "docsPath": "/docs/bing-autocomplete-api", + "inputSchema": { + "type": "object", + "properties": { + "q": { + "type": "string", + "minLength": 1, + "maxLength": 200, + "description": "Search query. Leading and trailing spaces are preserved." + }, + "mkt": { + "type": "string", + "default": "en-US", + "pattern": "^[a-z]{2}-[A-Z]{2}$", + "description": "Optional search market, for example en-US." + } + }, + "required": [ + "q" + ], + "additionalProperties": false, + "examples": [ + { + "q": "ai image", + "mkt": "en-US" + } + ] + } + }, + { + "id": "duckduckgo-autocomplete", + "method": "GET", + "path": "/api/v1/duckduckgo-autocomplete", + "mcpName": "goanyapi_duckduckgo_autocomplete", + "description": "Get DuckDuckGo autocomplete suggestions for a query with an optional regional setting.", + "readOnly": true, + "docsPath": "/docs/duckduckgo-autocomplete-api", + "inputSchema": { + "type": "object", + "properties": { + "q": { + "type": "string", + "minLength": 1, + "maxLength": 200, + "description": "Search query. Leading and trailing spaces are preserved." + }, + "kl": { + "type": "string", + "default": "wt-wt", + "pattern": "^[A-Za-z]{2}-[A-Za-z]{2,3}$", + "description": "Optional DuckDuckGo region code, for example wt-wt. Region reference: https://duckduckgo.com/duckduckgo-help-pages/settings/params" + } + }, + "required": [ + "q" + ], + "additionalProperties": false, + "examples": [ + { + "q": "ai image", + "kl": "wt-wt" + } + ] + } + }, + { + "id": "naver-autocomplete", + "method": "GET", + "path": "/api/v1/naver-autocomplete", + "mcpName": "goanyapi_naver_autocomplete", + "description": "Get Naver autocomplete suggestions for a query.", + "readOnly": true, + "docsPath": "/docs/naver-autocomplete-api", + "inputSchema": { + "type": "object", + "properties": { + "q": { + "type": "string", + "minLength": 1, + "maxLength": 200, + "description": "Search query. Leading and trailing spaces are preserved." + } + }, + "required": [ + "q" + ], + "additionalProperties": false, + "examples": [ + { + "q": "ai image" + } + ] + } + }, + { + "id": "coccoc-autocomplete", + "method": "GET", + "path": "/api/v1/coccoc-autocomplete", + "mcpName": "goanyapi_coccoc_autocomplete", + "description": "Get Coc Coc autocomplete suggestions for a query.", + "readOnly": true, + "docsPath": "/docs/coccoc-autocomplete-api", + "inputSchema": { + "type": "object", + "properties": { + "q": { + "type": "string", + "minLength": 1, + "maxLength": 200, + "description": "Search query. Leading and trailing spaces are preserved." + } + }, + "required": [ + "q" + ], + "additionalProperties": false, + "examples": [ + { + "q": "ai image" + } + ] + } + }, + { + "id": "yandex-autocomplete", + "method": "GET", + "path": "/api/v1/yandex-autocomplete", + "mcpName": "goanyapi_yandex_autocomplete", + "description": "Get Yandex autocomplete suggestions for a query with an optional interface language.", + "readOnly": true, + "docsPath": "/docs/yandex-autocomplete-api", + "inputSchema": { + "type": "object", + "properties": { + "q": { + "type": "string", + "minLength": 1, + "maxLength": 200, + "description": "Search query. Leading and trailing spaces are preserved." + }, + "uil": { + "type": "string", + "default": "en", + "pattern": "^[A-Za-z]{2,3}$", + "description": "Optional two- or three-letter interface language code, for example en or ru." + } + }, + "required": [ + "q" + ], + "additionalProperties": false, + "examples": [ + { + "q": "ai image", + "uil": "en" + } + ] + } + }, + { + "id": "youtube-autocomplete", + "method": "GET", + "path": "/api/v1/youtube-autocomplete", + "mcpName": "goanyapi_youtube_autocomplete", + "description": "Get localized YouTube search suggestions for a query.", + "readOnly": true, + "docsPath": "/docs/youtube-autocomplete-api", + "inputSchema": { + "type": "object", + "properties": { + "q": { + "type": "string", + "minLength": 1, + "maxLength": 200, + "description": "Search query. Leading and trailing spaces are preserved." + }, + "hl": { + "type": "string", + "default": "en", + "pattern": "^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$", + "description": "Optional YouTube suggestion language, for example en or zh-CN." + }, + "gl": { + "type": "string", + "default": "US", + "pattern": "^[A-Za-z]{2}$", + "description": "Optional two-letter country code, for example US or CN." + } + }, + "required": [ + "q" + ], + "additionalProperties": false, + "examples": [ + { + "q": "ai image", + "hl": "en", + "gl": "US" + } + ] + } + }, + { + "id": "yahoo-autocomplete", + "method": "GET", + "path": "/api/v1/yahoo-autocomplete", + "mcpName": "goanyapi_yahoo_autocomplete", + "description": "Get Yahoo US search suggestions for a query.", + "readOnly": true, + "docsPath": "/docs/yahoo-autocomplete-api", + "inputSchema": { + "type": "object", + "properties": { + "q": { + "type": "string", + "minLength": 1, + "maxLength": 200, + "description": "Search query. Leading and trailing spaces are preserved." + } + }, + "required": [ + "q" + ], + "additionalProperties": false, + "examples": [ + { + "q": "ai image" + } + ] + } + }, + { + "id": "serp", + "method": "GET", + "path": "/api/v1/serp", + "mcpName": "goanyapi_google_serp", + "description": "Query structured Google search results.", + "readOnly": true, + "docsPath": "/docs/serp-api", + "inputSchema": { + "type": "object", + "properties": { + "q": { + "type": "string", + "description": "Search keyword" + }, + "filter": { + "type": "string", + "description": "Similar-result filtering: 0 or 1" + }, + "cr": { + "type": "string", + "description": "Result country restriction, e.g. countryUS" + }, + "lr": { + "type": "string", + "description": "Result language restriction, e.g. lang_en" + }, + "nfpr": { + "type": "string", + "description": "Automatic correction control: 0 or 1" + }, + "gl": { + "type": "string", + "description": "Two-letter country code, for example us" + }, + "hl": { + "type": "string", + "description": "Optional interface language, e.g. en or zh-cn" + }, + "start": { + "type": "integer", + "description": "Result offset" + }, + "device": { + "type": "string", + "description": "Optional desktop or mobile device" + }, + "browser": { + "type": "string", + "description": "Optional browser name" + }, + "safe": { + "type": "string", + "description": "Optional safe-search mode" + }, + "tbs": { + "type": "string", + "description": "Optional advanced time filter, e.g. qdr:w" + }, + "search_type": { + "type": "string", + "description": "Optional search vertical" + } + }, + "required": [ + "q" + ], + "additionalProperties": false + } + }, + { + "id": "bing-serp", + "method": "GET", + "path": "/api/v1/bing-serp", + "mcpName": "goanyapi_bing_serp", + "description": "Query structured Bing search results with pagination and localization options.", + "readOnly": true, + "docsPath": "/docs/bing-serp-api", + "inputSchema": { + "type": "object", + "properties": { + "q": { + "type": "string", + "description": "Search keyword" + }, + "cc": { + "type": "string", + "description": "Optional lowercase two-letter country code" + }, + "setLang": { + "type": "string", + "description": "Optional language-country code such as en-US" + }, + "first": { + "type": "integer", + "description": "Pagination start from the previous response" + }, + "device": { + "type": "string", + "description": "Optional desktop, mobile, ios, ipad, android, or tablet device" + }, + "brd_browser": { + "type": "string", + "description": "Optional chrome, safari, or firefox browser" + } + }, + "required": [ + "q" + ], + "additionalProperties": false + } + }, + { + "id": "google-intitle", + "method": "GET", + "path": "/api/v1/google-intitle", + "mcpName": "goanyapi_google_intitle", + "description": "Find Google results whose titles contain the requested text.", + "readOnly": true, + "docsPath": "/docs/google-intitle-api", + "inputSchema": { + "type": "object", + "properties": { + "intitle": { + "type": "string", + "description": "Search keyword" + }, + "qdr": { + "type": "string", + "description": "Optional date range filter" + }, + "filter": { + "type": "string", + "description": "Similar-result filtering: 0 or 1" + }, + "cr": { + "type": "string", + "description": "Result country restriction, e.g. countryUS" + }, + "lr": { + "type": "string", + "description": "Result language restriction, e.g. lang_en" + }, + "nfpr": { + "type": "string", + "description": "Automatic correction control: 0 or 1" + }, + "start": { + "type": "integer", + "description": "Result offset from 0 to 990" + }, + "tbs": { + "type": "string", + "description": "Advanced time filter, e.g. qdr:w; cannot combine with qdr" + }, + "gl": { + "type": "string", + "description": "Two-letter country code, for example us" + }, + "hl": { + "type": "string", + "description": "Optional interface language, e.g. en or zh-cn" + }, + "device": { + "type": "string", + "description": "Optional desktop, mobile, or platform device" + }, + "browser": { + "type": "string", + "description": "Optional chrome, safari, or firefox browser" + }, + "safe": { + "type": "string", + "description": "Optional safe-search mode" + } + }, + "required": [ + "intitle" + ], + "additionalProperties": false + } + }, + { + "id": "google-site-search", + "method": "GET", + "path": "/api/v1/google-site-search", + "mcpName": "goanyapi_google_site_search", + "description": "Search Google results limited to a specified website.", + "readOnly": true, + "docsPath": "/docs/google-site-search-api", + "inputSchema": { + "type": "object", + "properties": { + "site": { + "type": "string", + "description": "Domain name, for example example.com" + }, + "qdr": { + "type": "string", + "description": "Optional date range filter" + }, + "filter": { + "type": "string", + "description": "Similar-result filtering: 0 or 1" + }, + "cr": { + "type": "string", + "description": "Result country restriction, e.g. countryUS" + }, + "lr": { + "type": "string", + "description": "Result language restriction, e.g. lang_en" + }, + "nfpr": { + "type": "string", + "description": "Automatic correction control: 0 or 1" + }, + "start": { + "type": "integer", + "description": "Result offset from 0 to 990" + }, + "tbs": { + "type": "string", + "description": "Advanced time filter, e.g. qdr:w; cannot combine with qdr" + }, + "gl": { + "type": "string", + "description": "Two-letter country code, for example us" + }, + "hl": { + "type": "string", + "description": "Optional interface language, e.g. en or zh-cn" + }, + "device": { + "type": "string", + "description": "Optional desktop, mobile, or platform device" + }, + "browser": { + "type": "string", + "description": "Optional chrome, safari, or firefox browser" + }, + "safe": { + "type": "string", + "description": "Optional safe-search mode" + } + }, + "required": [ + "site" + ], + "additionalProperties": false + } + }, + { + "id": "google-trends", + "method": "GET", + "path": "/api/v1/google-trends", + "mcpName": "goanyapi_google_trends", + "description": "Query Google Trends interest over time, related topics, or related queries. TIMESERIES accepts up to 5 keywords. Billing is calculated per keyword, including successful empty results.", + "readOnly": true, + "docsPath": "/docs/google-trends-api", + "inputSchema": { + "type": "object", + "properties": { + "q": { + "type": "string", + "minLength": 1, + "maxLength": 504, + "description": "Search query. TIMESERIES accepts up to 5 comma-separated queries; RELATED_TOPICS and RELATED_QUERIES accept exactly one query." + }, + "date": { + "type": "string", + "enum": [ + "now 1-H", + "now 4-H", + "now 1-d", + "now 7-d", + "today 1-m", + "today 3-m", + "today 12-m", + "today 5-y", + "all" + ], + "default": "today 12-m", + "description": "Google Trends time range." + }, + "geo": { + "type": "string", + "pattern": "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$", + "maxLength": 64, + "description": "Optional single region code shared by all queries." + }, + "data_type": { + "type": "string", + "enum": [ + "TIMESERIES", + "RELATED_TOPICS", + "RELATED_QUERIES" + ], + "default": "TIMESERIES", + "description": "TIMESERIES returns interest over time; RELATED_TOPICS returns related topics; RELATED_QUERIES returns related queries." + } + }, + "required": [ + "q" + ], + "additionalProperties": false, + "oneOf": [ + { + "type": "object", + "properties": { + "data_type": { + "type": "string", + "enum": [ + "TIMESERIES" + ] + } + }, + "required": [ + "q", + "data_type" + ] + }, + { + "type": "object", + "properties": { + "data_type": { + "type": "string", + "enum": [ + "RELATED_TOPICS", + "RELATED_QUERIES" + ] + }, + "q": { + "type": "string", + "pattern": "^[^,]+$" + } + }, + "required": [ + "q", + "data_type" + ] + }, + { + "type": "object", + "required": [ + "q" + ], + "not": { + "type": "object", + "required": [ + "data_type" + ] + } + } + ], + "examples": [ + { + "q": "ai video,chatgpt", + "data_type": "TIMESERIES" + }, + { + "q": "ai video", + "data_type": "RELATED_TOPICS" + }, + { + "q": "ai video", + "data_type": "RELATED_QUERIES" + } + ] + } + }, + { + "id": "adsense", + "method": "GET", + "path": "/api/v1/adsense", + "mcpName": "goanyapi_adsense", + "description": "Query Reverse AdSense data in exactly one mode: find publisher IDs associated with a domain, or reverse lookup domains associated with a publisher ID.", + "readOnly": true, + "docsPath": "/docs/adsense-api", + "inputSchema": { + "type": "object", + "properties": { + "domain": { + "type": "string", + "minLength": 1, + "pattern": "^(?=.{1,253}$)(?!-)(?:[A-Za-z0-9-]{1,63}\\.)+[A-Za-z0-9-]{2,63}$", + "description": "Domain mode: query publisher IDs associated with a domain. Use a hostname such as example.com and provide this parameter alone." + }, + "pubId": { + "type": "string", + "minLength": 1, + "pattern": "^[pP][uU][bB]-\\d+$", + "description": "Publisher ID mode: reverse lookup associated domains. Use the pub- followed by digits format and provide this parameter alone." + } + }, + "additionalProperties": false, + "description": "Choose exactly one query mode: domain or pubId. Do not provide both parameters.", + "oneOf": [ + { + "type": "object", + "required": [ + "domain" + ] + }, + { + "type": "object", + "required": [ + "pubId" + ] + } + ], + "examples": [ + { + "domain": "example.com" + }, + { + "pubId": "pub-3661441281163245" + } + ] + } + }, + { + "id": "transparency", + "method": "GET", + "path": "/api/v1/transparency", + "mcpName": "goanyapi_google_ads_transparency", + "description": "Query Google Ads transparency data in exactly one mode: search advertiser and domain suggestions by keyword, find advertisers associated with a domain, or reverse lookup domains by creative IDs.", + "readOnly": true, + "docsPath": "/docs/transparency-api", + "inputSchema": { + "type": "object", + "properties": { + "keyword": { + "type": "string", + "minLength": 1, + "description": "Keyword mode: search advertiser and domain suggestions. Provide this parameter alone." + }, + "domain": { + "type": "string", + "minLength": 1, + "description": "Domain mode: find advertisers associated with a domain. Provide this parameter alone." + }, + "creativeIds": { + "type": "string", + "minLength": 1, + "description": "Creative lookup mode: find associated domains from comma-separated creative IDs. Provide this parameter alone." + } + }, + "additionalProperties": false, + "description": "Choose exactly one query mode: keyword, domain, or creativeIds.", + "oneOf": [ + { + "type": "object", + "required": [ + "keyword" + ] + }, + { + "type": "object", + "required": [ + "domain" + ] + }, + { + "type": "object", + "required": [ + "creativeIds" + ] + } + ], + "examples": [ + { + "keyword": "ai image" + }, + { + "domain": "example.com" + }, + { + "creativeIds": "AR02586610982767820801,AR04020344870890635265" + } + ] + } + }, + { + "id": "ads-statistics", + "method": "GET", + "path": "/api/v1/ads-statistics", + "mcpName": "goanyapi_google_ads_transparency_statistics", + "description": "Query Google Ads transparency statistics across advertiser, domain, title, country, and image-ad actions. Multi-step actions describe the prerequisite action and exact response fields to reuse in their conditional input Schema.", + "readOnly": true, + "docsPath": "/docs/ads-statistics-api", + "inputSchema": { + "type": "object", + "properties": { + "action": { + "type": "string", + "enum": [ + "advertiserSearch", + "domainSearch", + "advertiserStatistics", + "domainStatistics", + "titleSearch", + "googleAdsTitleSearch", + "domainTitles", + "hostTitleSearch", + "domainImageAds", + "domainTitleCountries", + "domainTitleImageAds" + ], + "description": "Select one statistics action. advertiserSearch: Search advertisers by keyword; domainSearch: Search domains by keyword; advertiserStatistics: Query weekly advertiser statistics. First call advertiserSearch, then pass an exact data.result[].id value as advertiserId.; domainStatistics: Query weekly domain statistics. First call domainSearch, then pass an exact data.result[].id value as hostId.; titleSearch: Search domains by ad title keyword; googleAdsTitleSearch: Find relevant ads through keywords.; domainTitles: Query titles under a domain. First call domainSearch, then pass an exact data.result[].id value as hostId.; hostTitleSearch: Page through titles under a domain. First call domainSearch, then pass an exact data.result[].id value as hostId.; domainImageAds: Query image ads under a domain. First call domainSearch, then pass an exact data.result[].id value as hostId.; domainTitleCountries: Query country distribution for one domain title ad. First call domainTitles and pass the same data.result[] item's hostId and exact title; alternatively call hostTitleSearch and use one data.result.items[] item's hostId and exact title.; domainTitleImageAds: Query image ads for one domain title. First call domainTitles and pass the same data.result[] item's hostId and exact title; alternatively call hostTitleSearch and use one data.result.items[] item's hostId and exact title.." + }, + "keyword": { + "type": "string", + "minLength": 1, + "description": "Search keyword or optional title filter. Required for: advertiserSearch, domainSearch, titleSearch, googleAdsTitleSearch. Optional for: hostTitleSearch." + }, + "advertiserId": { + "type": "string", + "pattern": "^\\d+$", + "description": "Plain numeric advertiser ID from advertiserSearch data.result[].id. Required for: advertiserStatistics." + }, + "hostId": { + "type": "string", + "pattern": "^\\d+$", + "description": "Plain numeric domain host ID from domainSearch or a title result. Required for: domainStatistics, domainTitles, hostTitleSearch, domainImageAds, domainTitleCountries, domainTitleImageAds." + }, + "title": { + "type": "string", + "minLength": 1, + "description": "Raw ad title returned by a title query. Required for: domainTitleCountries, domainTitleImageAds." + }, + "startDay": { + "type": "string", + "pattern": "^(?:\\d{4}-\\d{2}-\\d{2}|\\d{8})$", + "description": "Inclusive start date in YYYY-MM-DD or YYYYMMDD format. Required for: advertiserStatistics, domainStatistics, titleSearch, googleAdsTitleSearch, domainTitles, hostTitleSearch, domainImageAds, domainTitleCountries, domainTitleImageAds." + }, + "endDay": { + "type": "string", + "pattern": "^(?:\\d{4}-\\d{2}-\\d{2}|\\d{8})$", + "description": "Inclusive end date in YYYY-MM-DD or YYYYMMDD format. Required for: advertiserStatistics, domainStatistics, titleSearch, googleAdsTitleSearch, domainTitles, hostTitleSearch, domainImageAds, domainTitleCountries, domainTitleImageAds." + }, + "page": { + "type": "integer", + "default": 0, + "minimum": 0, + "description": "Zero-based result page. Optional for: titleSearch, googleAdsTitleSearch, hostTitleSearch." + }, + "size": { + "type": "integer", + "minimum": 1, + "maximum": 100, + "description": "Results per page, from 1 to 100. titleSearch and googleAdsTitleSearch default to 10; other paginated actions retain their documented defaults. Optional for: titleSearch, googleAdsTitleSearch, hostTitleSearch." + } + }, + "required": [ + "action" + ], + "additionalProperties": false, + "description": "Select one action and provide every parameter required by that action.", + "oneOf": [ + { + "type": "object", + "description": "Search advertisers by keyword", + "properties": { + "action": { + "type": "string", + "enum": [ + "advertiserSearch" + ] + } + }, + "required": [ + "action", + "keyword" + ] + }, + { + "type": "object", + "description": "Search domains by keyword", + "properties": { + "action": { + "type": "string", + "enum": [ + "domainSearch" + ] + } + }, + "required": [ + "action", + "keyword" + ] + }, + { + "type": "object", + "description": "Query weekly advertiser statistics. First call advertiserSearch, then pass an exact data.result[].id value as advertiserId.", + "properties": { + "action": { + "type": "string", + "enum": [ + "advertiserStatistics" + ] + } + }, + "required": [ + "action", + "advertiserId", + "startDay", + "endDay" + ] + }, + { + "type": "object", + "description": "Query weekly domain statistics. First call domainSearch, then pass an exact data.result[].id value as hostId.", + "properties": { + "action": { + "type": "string", + "enum": [ + "domainStatistics" + ] + } + }, + "required": [ + "action", + "hostId", + "startDay", + "endDay" + ] + }, + { + "type": "object", + "description": "Search domains by ad title keyword", + "properties": { + "action": { + "type": "string", + "enum": [ + "titleSearch" + ] + } + }, + "required": [ + "action", + "keyword", + "startDay", + "endDay" + ] + }, + { + "type": "object", + "description": "Find relevant ads through keywords.", + "properties": { + "action": { + "type": "string", + "enum": [ + "googleAdsTitleSearch" + ] + } + }, + "required": [ + "action", + "keyword", + "startDay", + "endDay" + ] + }, + { + "type": "object", + "description": "Query titles under a domain. First call domainSearch, then pass an exact data.result[].id value as hostId.", + "properties": { + "action": { + "type": "string", + "enum": [ + "domainTitles" + ] + } + }, + "required": [ + "action", + "hostId", + "startDay", + "endDay" + ] + }, + { + "type": "object", + "description": "Page through titles under a domain. First call domainSearch, then pass an exact data.result[].id value as hostId.", + "properties": { + "action": { + "type": "string", + "enum": [ + "hostTitleSearch" + ] + } + }, + "required": [ + "action", + "hostId", + "startDay", + "endDay" + ] + }, + { + "type": "object", + "description": "Query image ads under a domain. First call domainSearch, then pass an exact data.result[].id value as hostId.", + "properties": { + "action": { + "type": "string", + "enum": [ + "domainImageAds" + ] + } + }, + "required": [ + "action", + "hostId", + "startDay", + "endDay" + ] + }, + { + "type": "object", + "description": "Query country distribution for one domain title ad. First call domainTitles and pass the same data.result[] item's hostId and exact title; alternatively call hostTitleSearch and use one data.result.items[] item's hostId and exact title.", + "properties": { + "action": { + "type": "string", + "enum": [ + "domainTitleCountries" + ] + } + }, + "required": [ + "action", + "hostId", + "title", + "startDay", + "endDay" + ] + }, + { + "type": "object", + "description": "Query image ads for one domain title. First call domainTitles and pass the same data.result[] item's hostId and exact title; alternatively call hostTitleSearch and use one data.result.items[] item's hostId and exact title.", + "properties": { + "action": { + "type": "string", + "enum": [ + "domainTitleImageAds" + ] + } + }, + "required": [ + "action", + "hostId", + "title", + "startDay", + "endDay" + ] + } + ], + "examples": [ + { + "action": "advertiserSearch", + "keyword": "ai" + }, + { + "action": "domainSearch", + "keyword": "ai" + }, + { + "action": "advertiserStatistics", + "advertiserId": "39687", + "startDay": "2026-03-01", + "endDay": "2026-03-31" + }, + { + "action": "domainStatistics", + "hostId": "53293", + "startDay": "2026-03-01", + "endDay": "2026-03-31" + }, + { + "action": "titleSearch", + "keyword": "ai", + "startDay": "20260122", + "endDay": "20260321", + "page": 0, + "size": 10 + }, + { + "action": "googleAdsTitleSearch", + "keyword": "adidas", + "startDay": "20261001", + "endDay": "20261008", + "page": 0, + "size": 10 + }, + { + "action": "domainTitles", + "hostId": "598", + "startDay": "20260301", + "endDay": "20260331" + }, + { + "action": "hostTitleSearch", + "hostId": "598", + "keyword": "ai", + "startDay": "20260301", + "endDay": "20260331", + "page": 0, + "size": 30 + }, + { + "action": "domainImageAds", + "hostId": "598", + "startDay": "20260301", + "endDay": "20260331" + }, + { + "action": "domainTitleCountries", + "hostId": "132", + "title": "AI image tools", + "startDay": "2026-03-08", + "endDay": "2026-03-31" + }, + { + "action": "domainTitleImageAds", + "hostId": "132", + "title": "AI image tools", + "startDay": "2026-03-08", + "endDay": "2026-03-31" + } + ] + } + }, + { + "id": "activity-credits", + "method": "GET", + "path": "/api/v1/activity-credits", + "mcpName": "goanyapi_activity_credits", + "description": "Query the authenticated account credit activity.", + "readOnly": true, + "inputSchema": { + "type": "object", + "properties": { + "page": { + "type": "integer", + "default": 1, + "minimum": 1, + "description": "One-based result page" + }, + "size": { + "type": "integer", + "default": 20, + "minimum": 1, + "maximum": 100, + "description": "Results per page, from 1 to 100" + }, + "type": { + "type": "string", + "enum": [ + "grant", + "consume" + ], + "description": "Optional credit transaction type" + }, + "requestStatus": { + "type": "string", + "enum": [ + "empty", + "failed" + ], + "description": "Optional API request result filter" + } + }, + "additionalProperties": false + } + }, + { + "id": "credits-balance", + "method": "GET", + "path": "/api/v1/credits/balance", + "mcpName": "goanyapi_credits_balance", + "description": "Query the authenticated account credit balance.", + "readOnly": true, + "docsPath": "/docs/credit-balance-api", + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": false + } + } +] as const; diff --git a/packages/goanyapi/src/catalog.ts b/packages/goanyapi/src/catalog.ts new file mode 100644 index 0000000..c3212ff --- /dev/null +++ b/packages/goanyapi/src/catalog.ts @@ -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(); + +function isRecord(value: unknown): value is Record { + 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 { + 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 { + 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 }; diff --git a/packages/goanyapi/src/oauth.ts b/packages/goanyapi/src/oauth.ts new file mode 100644 index 0000000..8946655 --- /dev/null +++ b/packages/goanyapi/src/oauth.ts @@ -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(url: string, init: RequestInit = {}): Promise { + 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 { + 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(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, + 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 { + 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(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 { + 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((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(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; + } +} diff --git a/packages/goanyapi/src/types.ts b/packages/goanyapi/src/types.ts new file mode 100644 index 0000000..adf256d --- /dev/null +++ b/packages/goanyapi/src/types.ts @@ -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; + }; + }; +} +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; +} diff --git a/packages/goanyapi/tests/plugin.test.mjs b/packages/goanyapi/tests/plugin.test.mjs new file mode 100644 index 0000000..30b5b53 --- /dev/null +++ b/packages/goanyapi/tests/plugin.test.mjs @@ -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/); +}); diff --git a/registry.json b/registry.json index f5f9741..c4761b3 100644 --- a/registry.json +++ b/registry.json @@ -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 登录。" } } ] }