dataforseo-mcp-server
Version:
CLI and MCP server for DataForSEO API — browse documentation and make authenticated API requests
148 lines • 6.22 kB
JavaScript
import { z } from "zod";
import { API_BASE_URL } from "../../config/index.js";
import { applyFieldConfigurationToResponse } from "../config/field-configuration.js";
import { applyAiModePath } from "../api/path.js";
import { makeApiRequest } from "../api/client.js";
import { apiRequestMiddlewarePipeline } from "../middleware/api-request/api-request-middleware-pipeline.js";
import { buildRequestBody, collectParam } from "../api/request-body.js";
import { printError } from "../cli/error.js";
import { printToolResult } from "../cli/output.js";
import { DEFAULT_API_TOOL_ANNOTATIONS } from "./tool-annotations.js";
import { BaseTool } from "./base-tool.js";
import { bodyResult, errorResult } from "./types.js";
export const HTTP_METHODS = ["GET", "POST", "PUT", "DELETE"];
export const apiRequestMcpInputSchema = z.object({
method: z.enum(HTTP_METHODS).describe("HTTP method"),
path: z
.string()
.optional()
.describe("API path (e.g. /v3/serp/google/organic/live/regular)"),
url: z.string().optional().describe("Full API URL (alternative to path)"),
data: z
.any()
.optional()
.describe("Request body as JSON object or array of task objects"),
noAiMode: z
.boolean()
.optional()
.default(false)
.describe("Disable the .ai path suffix and return the full response schema instead of the AI-optimized subset. Can increase context size significantly. Default: false."),
});
export const apiRequestCliInputSchema = apiRequestMcpInputSchema.extend({
params: z
.record(z.string(), z.unknown())
.optional()
.describe("Request body fields merged into the first task object"),
});
export class ApiRequestTool extends BaseTool {
authHeader;
constructor(authHeader) {
super();
this.authHeader = authHeader;
}
name = "api_request";
title = "API Request";
description = "Make an authenticated request to the DataForSEO API";
schema = apiRequestMcpInputSchema;
getAnnotations() {
return DEFAULT_API_TOOL_ANNOTATIONS;
}
async execute(input) {
return this.performRequest(input, { params: {} });
}
async invokeCli(args) {
try {
const input = apiRequestCliInputSchema.parse(args);
return await this.performRequest(input, {
params: input.params ?? {},
});
}
catch (error) {
if (error instanceof z.ZodError) {
const details = error.issues
.map((issue) => `${issue.path.join(".")}: ${issue.message}`)
.join("; ");
return errorResult(`Invalid input: ${details}`);
}
const message = error instanceof Error ? error.message : String(error);
return errorResult(message);
}
}
registerCli(program) {
program
.command("request")
.description("Make an authenticated request to the DataForSEO API")
.addHelpText("after", `
See SKILL.md in the project root for full LLM agent guide. Run commands with: npx dataforseo-mcp-server
`)
.requiredOption("-X, --method <method>", "HTTP method (GET, POST, PUT, DELETE)")
.option("-p, --path <path>", "API path (e.g. /v3/serp/google/organic/live/regular)")
.option("-u, --url <url>", "Full API URL (alternative to --path)")
.option("--param <key=value>", "Request field as key=value (repeatable; same key builds an array; use [item] or [a|b] for arrays in shells that strip quotes)", collectParam, {})
.option("-d, --data <json>", "Request body as JSON string (merged with --param; --param values override JSON)")
.option("--no-ai-mode", "Disable the .ai path suffix and return the full response schema instead of the AI-optimized subset. Can increase context size significantly.")
.action(async (options) => {
try {
const result = await this.invokeCli({
method: options.method,
path: options.path,
url: options.url,
params: options.param,
data: options.data,
noAiMode: !(options.aiMode ?? true),
});
printToolResult(result);
}
catch (error) {
printError(error);
}
});
}
async performRequest(input, options) {
const target = input.url ?? input.path;
if (!target) {
throw new Error("Either path or url is required.");
}
if (target.startsWith("http") && !target.startsWith(`${API_BASE_URL}/`)) {
throw new Error(`Domain does not match: only ${API_BASE_URL} requests are allowed, received ${target}`);
}
const requestPath = applyAiModePath(target, !(input.noAiMode ?? false));
const body = buildRequestBody(input.data, options.params);
const middlewareResult = apiRequestMiddlewarePipeline.apply({
method: input.method,
path: requestPath,
body,
});
const response = await makeApiRequest({
method: input.method,
path: requestPath,
body: middlewareResult.body,
...(this.authHeader ? { authHeader: this.authHeader } : {}),
});
let parsedBody = response.body;
try {
parsedBody = JSON.parse(response.body);
}
catch {
// keep as string
}
if (typeof parsedBody !== "string") {
parsedBody = applyFieldConfigurationToResponse(parsedBody, requestPath);
}
const result = bodyResult(parsedBody, response.status >= 400);
if (middlewareResult.warnings.length === 0) {
return result;
}
return {
...result,
content: [
...middlewareResult.warnings.map((text) => ({
type: "text",
text,
})),
...result.content,
],
};
}
}
//# sourceMappingURL=api-request-tool.js.map