Skip to content

Open source alternative to Semrush and Ahrefs

Allow MCP output schemas to accept added fields (#638)

Ben Senescuc22770aa65b3
diff --git a/src/server/mcp/output-schema-contract.test.ts b/src/server/mcp/output-schema-contract.test.ts
new file mode 100644
index 00000000..55b986b2
--- /dev/null
+++ b/src/server/mcp/output-schema-contract.test.ts
@@ -0,0 +1,155 @@
+import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
+import { describe, expect, it, vi } from "vitest";
+import { createWorkersOAuthMcpProps } from "./context";
+import { createOpenSeoMcpServer } from "./server";
+
+vi.mock("cloudflare:workers", () => ({
+ env: {},
+ waitUntil: vi.fn(),
+ DurableObject: class {
+ readonly ctx = null;
+ },
+}));
+
+// Walk schema keywords, not arbitrary JSON: examples/defaults and property
+// names can contain the same words without imposing a schema constraint.
+function closedOutputPaths(schema: unknown, path: string): string[] {
+ if (typeof schema !== "object" || schema === null) return [];
+ const failures: string[] = [];
+ const entries: [string, unknown][] = Object.entries(schema);
+ for (const [key, value] of entries) {
+ if (
+ (key === "additionalProperties" || key === "unevaluatedProperties") &&
+ value === false
+ ) {
+ failures.push(`${path}.${key}`);
+ }
+ if (
+ [
+ "properties",
+ "patternProperties",
+ "$defs",
+ "definitions",
+ "dependentSchemas",
+ ].includes(key) &&
+ typeof value === "object" &&
+ value !== null
+ ) {
+ for (const [name, child] of Object.entries(value)) {
+ failures.push(...closedOutputPaths(child, `${path}.${key}.${name}`));
+ }
+ } else if (
+ [
+ "items",
+ "prefixItems",
+ "anyOf",
+ "oneOf",
+ "allOf",
+ "contains",
+ "additionalProperties",
+ "unevaluatedProperties",
+ "not",
+ "if",
+ "then",
+ "else",
+ "propertyNames",
+ ].includes(key)
+ ) {
+ const children = Array.isArray(value) ? value : [value];
+ children.forEach((child, index) => {
+ failures.push(...closedOutputPaths(child, `${path}.${key}[${index}]`));
+ });
+ }
+ }
+ return failures;
+}
+
+describe("published MCP output schemas", () => {
+ it("allows added fields in every registered tool, including nested objects", async () => {
+ const server = createOpenSeoMcpServer(
+ createWorkersOAuthMcpProps({
+ userId: "user_test",
+ userEmail: "[email protected]",
+ organizationId: "org_test",
+ baseUrl: "https://open-seo.test",
+ clientId: "client_test",
+ scopes: ["mcp"],
+ }),
+ );
+ const client = new Client({ name: "output-schema-contract", version: "1" });
+ const [clientTransport, serverTransport] =
+ InMemoryTransport.createLinkedPair();
+ try {
+ await server.connect(serverTransport);
+ await client.connect(clientTransport);
+ const { tools } = await client.listTools();
+ expect(tools.length).toBeGreaterThan(0);
+ const failures = tools.flatMap((tool) => {
+ expect(
+ tool.outputSchema,
+ `${tool.name} must publish an output schema`,
+ ).toBeDefined();
+ return closedOutputPaths(tool.outputSchema, tool.name);
+ });
+ expect(
+ failures,
+ "Use z.looseObject() or .passthrough() for these MCP output objects; cached clients must accept added fields.",
+ ).toEqual([]);
+ } finally {
+ await client.close();
+ await server.close();
+ }
+ });
+
+ it("finds constraints inside arrays, unions, and referenced definitions", () => {
+ expect(
+ closedOutputPaths(
+ {
+ properties: {
+ rows: {
+ items: { anyOf: [{ $ref: "#/$defs/row" }, { type: "null" }] },
+ },
+ },
+ $defs: { row: { type: "object", additionalProperties: false } },
+ allOf: [{ unevaluatedProperties: false }],
+ },
+ "tool",
+ ),
+ ).toEqual([
+ "tool.$defs.row.additionalProperties",
+ "tool.allOf[0].unevaluatedProperties",
+ ]);
+ expect(
+ closedOutputPaths(
+ {
+ properties: {
+ rows: {
+ items: {
+ anyOf: [
+ { type: "object", additionalProperties: false },
+ { type: "null" },
+ ],
+ },
+ },
+ },
+ },
+ "tool",
+ ),
+ ).toEqual(["tool.properties.rows.items[0].anyOf[0].additionalProperties"]);
+ });
+
+ it("ignores example data and property names that resemble schema keywords", () => {
+ expect(
+ closedOutputPaths(
+ {
+ properties: {
+ additionalProperties: { type: "boolean", const: false },
+ },
+ examples: [{ additionalProperties: false }],
+ default: { unevaluatedProperties: false },
+ },
+ "tool",
+ ),
+ ).toEqual([]);
+ });
+});
diff --git a/src/server/mcp/server.ts b/src/server/mcp/server.ts
index cd5018ab..9a1f9c01 100644
--- a/src/server/mcp/server.ts
+++ b/src/server/mcp/server.ts
@@ -111,6 +111,9 @@ function registerOpenSeoTool<Input extends ToolSchema>(
tool: OpenSeoToolDefinition<Input>,
authProps: McpProps,
) {
+ // Output objects must allow added fields, including nested objects. The
+ // tools/list contract test checks every registered tool for cached-client
+ // compatibility; input schemas keep their existing validation rules.
const outputSchema = objectSchema(tool.config.outputSchema);
const handler = instrumentMcpToolHandler(
tool.name,
diff --git a/src/server/mcp/tools/add-rank-tracking-keywords.ts b/src/server/mcp/tools/add-rank-tracking-keywords.ts
index fdc1d6f5..f5525c6c 100644
--- a/src/server/mcp/tools/add-rank-tracking-keywords.ts
+++ b/src/server/mcp/tools/add-rank-tracking-keywords.ts
@@ -50,7 +50,7 @@ export const addRankTrackingKeywordsTool = {
added: z.number(),
addedIds: z.array(z.string()),
scheduledEstimate: z
- .object({
+ .looseObject({
scheduleInterval: z.enum(["daily", "weekly", "monthly"]),
costUsd: z.number(),
costCredits: z.number(),
diff --git a/src/server/mcp/tools/create-project.ts b/src/server/mcp/tools/create-project.ts
index 3af27b14..cdf66ece 100644
--- a/src/server/mcp/tools/create-project.ts
+++ b/src/server/mcp/tools/create-project.ts
@@ -105,7 +105,7 @@ export const createProjectTool = {
description:
"Create a new project in the user's organization. Uses no credits — does not call DataForSEO. Provide a name, and optionally a domain and default market (locationCode/languageCode; a languageCode requires a locationCode). Returns the created {id, name, domain, locationCode, languageCode, url}; pass the returned `id` as `projectId` to other OpenSEO tools. Call list_projects first to avoid creating a duplicate.",
inputSchema,
- outputSchema: {
+ outputSchema: z.looseObject({
project: z
.object({
id: z.string(),
@@ -117,7 +117,7 @@ export const createProjectTool = {
})
.passthrough(),
...optionalMetaOutputSchema,
- },
+ }),
annotations: {
readOnlyHint: false,
openWorldHint: false,
diff --git a/src/server/mcp/tools/dataforseo-research-tools.ts b/src/server/mcp/tools/dataforseo-research-tools.ts
index 72b22080..38453546 100644
--- a/src/server/mcp/tools/dataforseo-research-tools.ts
+++ b/src/server/mcp/tools/dataforseo-research-tools.ts
@@ -785,13 +785,13 @@ export const getRankedKeywordsTool = {
description:
"Returns market-specific keyword, URL, rank, search volume, CPC, intent, and traffic rows for a domain or page. Accepts country-level DataForSEO Labs location/language codes. Use this for strategy evidence; use get_domain_overview for aggregate domain footprint. Charges credits.",
inputSchema: getRankedKeywordsInputSchema,
- outputSchema: {
+ outputSchema: z.looseObject({
keywords: z.array(looseObjectOutputSchema),
totalCount: z.number().nullable(),
target: z.string().optional(),
scope: researchScopeSchema.optional(),
...optionalMetaOutputSchema,
- },
+ }),
annotations: {
readOnlyHint: false,
openWorldHint: false,
@@ -867,10 +867,10 @@ export const searchLocalBusinessesTool = {
description:
"Searches local business listings near a coordinate, with optional rating, review-count, and claimed-status filters. Use this to find local business candidates, nearby competitors, or unclaimed listings; it does not run Maps rank checks or Q&A. Returns a compact row per business (identity, contact, rating, claim status); use get_business_profile for one business's full profile. Charges credits.",
inputSchema: searchLocalBusinessesInputSchema,
- outputSchema: {
+ outputSchema: z.looseObject({
businesses: z.array(looseObjectOutputSchema),
...optionalMetaOutputSchema,
- },
+ }),
annotations: {
readOnlyHint: false,
openWorldHint: false,
@@ -914,10 +914,10 @@ export const getLocalSerpResultsTool = {
description:
"Fetches one Google Maps or Local Finder SERP near a coordinate. Returns trimmed provider rows (identity, rank, rating, categories, hours) with rank fields intact; callers decide how to match a target business. Charges credits.",
inputSchema: getLocalSerpResultsInputSchema,
- outputSchema: {
+ outputSchema: z.looseObject({
results: z.array(looseObjectOutputSchema),
...optionalMetaOutputSchema,
- },
+ }),
annotations: {
readOnlyHint: false,
openWorldHint: false,
@@ -960,10 +960,10 @@ export const getGoogleBusinessQuestionsTool = {
description:
"Fetches Google Business Profile questions and answers for one business (by businessName, cid, or placeId) near a coordinate. Run this only when Q&A evidence is needed. Charges credits.",
inputSchema: getGoogleBusinessQuestionsInputSchema,
- outputSchema: {
+ outputSchema: z.looseObject({
questions: z.array(looseObjectOutputSchema),
...optionalMetaOutputSchema,
- },
+ }),
annotations: {
readOnlyHint: false,
openWorldHint: false,
@@ -1003,10 +1003,10 @@ export const findSerpCompetitorsTool = {
description:
"Compares domains competing in Google results for a supplied keyword set in a country-level DataForSEO Labs market. Accepts location/language codes; not radius-based local SEO. Charges credits.",
inputSchema: findSerpCompetitorsInputSchema,
- outputSchema: {
+ outputSchema: z.looseObject({
competitors: z.array(looseObjectOutputSchema),
...optionalMetaOutputSchema,
- },
+ }),
annotations: {
readOnlyHint: false,
openWorldHint: false,
@@ -1062,10 +1062,10 @@ export const getKeywordMetricsTool = {
description:
"Hydrate up to 700 known keywords with search volume, keyword difficulty (KD), search intent, CPC, competition, and monthly trends in a single call. Use it to score candidate or known keywords — including Search Console striking-distance queries — by real demand and ranking difficulty. For countries served from Google Ads data (e.g. Iceland), KD and intent are null. Charges credits.",
inputSchema: getKeywordMetricsInputSchema,
- outputSchema: {
+ outputSchema: z.looseObject({
keywords: z.array(looseObjectOutputSchema),
...optionalMetaOutputSchema,
- },
+ }),
annotations: {
readOnlyHint: false,
openWorldHint: false,
diff --git a/src/server/mcp/tools/estimate-rank-tracker-cost.ts b/src/server/mcp/tools/estimate-rank-tracker-cost.ts
index 45797fce..b1d33caa 100644
--- a/src/server/mcp/tools/estimate-rank-tracker-cost.ts
+++ b/src/server/mcp/tools/estimate-rank-tracker-cost.ts
@@ -44,7 +44,7 @@ export const estimateRankTrackerCostTool = {
existingKeywordCount: z.number(),
additionalKeywordCount: z.number(),
scheduledEstimate: z
- .object({
+ .looseObject({
scheduleInterval: z.enum(["daily", "weekly", "monthly"]),
costUsd: z.number(),
costCredits: z.number(),
diff --git a/src/server/mcp/tools/get-backlinks-overview.ts b/src/server/mcp/tools/get-backlinks-overview.ts
index e29c1ed7..d61a30e6 100644
--- a/src/server/mcp/tools/get-backlinks-overview.ts
+++ b/src/server/mcp/tools/get-backlinks-overview.ts
@@ -61,14 +61,14 @@ export const getBacklinksOverviewTool = {
description:
"Returns a backlinks profile summary (total backlinks, referring domains, top referring domains). Charges credits (~50 typical for a domain, ~25 for a single page). Note: bare domains default to scope 'subdomains'; pass scope 'domain' to exclude subdomains from the totals. Targets with a path default to 'subfolder', whose counts come from filtered backlink totals (no rank/trends/referring-domain breakdown). Trend data always includes subdomains (provider limitation). Self-hosted deployments need the Backlinks API enabled on their DataForSEO account.",
inputSchema,
- outputSchema: {
+ outputSchema: z.looseObject({
target: z.string(),
scope: researchScopeSchema,
scopeNote: z.string().optional(),
overview: looseObjectOutputSchema,
referringDomains: looseObjectOutputSchema.optional(),
...optionalMetaOutputSchema,
- },
+ }),
annotations: {
readOnlyHint: false,
openWorldHint: false,
diff --git a/src/server/mcp/tools/get-backlinks-profile.ts b/src/server/mcp/tools/get-backlinks-profile.ts
index 0511c04c..bdaaff5d 100644
--- a/src/server/mcp/tools/get-backlinks-profile.ts
+++ b/src/server/mcp/tools/get-backlinks-profile.ts
@@ -125,12 +125,12 @@ export const getBacklinksProfileTool = {
description:
"Returns one bounded page of detailed backlink rows for a domain or page: linking URLs, target URLs, anchors, dofollow/nofollow, authority/spam signals, and lost/broken status. Supports filters, sorting, one_per_domain/as_is mode, and pagination. Charges credits (~30 per page typical). Self-hosted deployments need the Backlinks API enabled on their DataForSEO account.",
inputSchema,
- outputSchema: {
+ outputSchema: z.looseObject({
target: z.string(),
scope: researchScopeSchema,
backlinks: backlinksProfileOutputSchema,
...optionalMetaOutputSchema,
- },
+ }),
annotations: {
readOnlyHint: false,
openWorldHint: false,
diff --git a/src/server/mcp/tools/get-domain-keyword-suggestions.ts b/src/server/mcp/tools/get-domain-keyword-suggestions.ts
index c69bb21f..1e0bb51e 100644
--- a/src/server/mcp/tools/get-domain-keyword-suggestions.ts
+++ b/src/server/mcp/tools/get-domain-keyword-suggestions.ts
@@ -60,12 +60,12 @@ export const getDomainKeywordSuggestionsTool = {
description:
"Returns the organic keywords a domain ranks for, including position and available metrics. Use after get_domain_overview when you want the detailed keyword opportunity list for a competitor or reference domain. Charges credits (~100-300 typical). Cached for 12 hours.",
inputSchema,
- outputSchema: {
+ outputSchema: z.looseObject({
keywords: z.array(looseObjectOutputSchema),
target: z.string().optional(),
scope: researchScopeSchema.optional(),
...optionalMetaOutputSchema,
- },
+ }),
annotations: {
readOnlyHint: false,
openWorldHint: false,
diff --git a/src/server/mcp/tools/get-rank-tracker.ts b/src/server/mcp/tools/get-rank-tracker.ts
index bded4424..698ba5c3 100644
--- a/src/server/mcp/tools/get-rank-tracker.ts
+++ b/src/server/mcp/tools/get-rank-tracker.ts
@@ -84,6 +84,9 @@ export const getRankTrackerTool = {
status: z.enum(["pending", "running", "completed", "failed"]),
errorMessage: z.string().nullable(),
})
+ // Cached client schemas must tolerate new run fields too;
+ // passthrough on the parent results object is not recursive.
+ .passthrough()
.nullable(),
})
.passthrough()
diff --git a/src/server/mcp/tools/get-serp-results.ts b/src/server/mcp/tools/get-serp-results.ts
index 70e140e1..66a8bf0c 100644
--- a/src/server/mcp/tools/get-serp-results.ts
+++ b/src/server/mcp/tools/get-serp-results.ts
@@ -67,7 +67,7 @@ export const getSerpResultsTool = {
description:
"Fetch live Google organic search results for 1-10 keywords. Use this to inspect who ranks for a query, verify competitors, compare SERPs across keywords, or gather source URLs before content planning. Returns the top `depth` result rows per keyword (default 20). Charges credits per keyword: ~5 each at the default depth 20, and each additional 10 of depth adds ~2.5. Does not save results to OpenSEO. Per-keyword errors don't fail the batch.",
inputSchema,
- outputSchema: {
+ outputSchema: z.looseObject({
results: z.array(
z.union([
z
@@ -98,7 +98,7 @@ export const getSerpResultsTool = {
]),
),
...optionalMetaOutputSchema,
- },
+ }),
annotations: {
readOnlyHint: false,
openWorldHint: false,
diff --git a/src/server/mcp/tools/list-projects.ts b/src/server/mcp/tools/list-projects.ts
index 8be9ca4a..ae0b76fb 100644
--- a/src/server/mcp/tools/list-projects.ts
+++ b/src/server/mcp/tools/list-projects.ts
@@ -43,7 +43,7 @@ export const listProjectsTool = {
description:
"Lists the user's projects. Uses no credits — does not call DataForSEO. Use this whenever you need a `projectId` for another OpenSEO tool. Returns an array of {id, name, domain, locationCode, languageCode}; pass the `id` value as `projectId`. locationCode/languageCode are the project's default market — tools fall back to them when a call omits location/language args. When the user belongs to several organizations, each project is labeled with its organization and organizationId (pass that to create_project).",
inputSchema: {} as Record<string, never>,
- outputSchema: {
+ outputSchema: z.looseObject({
projects: z.array(
z
.object({
@@ -59,7 +59,7 @@ export const listProjectsTool = {
.passthrough(),
),
...optionalMetaOutputSchema,
- },
+ }),
annotations: {
readOnlyHint: true,
openWorldHint: false,
diff --git a/src/server/mcp/tools/list-saved-keywords.ts b/src/server/mcp/tools/list-saved-keywords.ts
index 277f12da..d69bb6cb 100644
--- a/src/server/mcp/tools/list-saved-keywords.ts
+++ b/src/server/mcp/tools/list-saved-keywords.ts
@@ -10,7 +10,7 @@ import type { SavedKeywordRow, SavedKeywordTagSummary } from "@/types/keywords";
// The app reads the full SavedKeywordRow through its own server functions. The
// MCP row keeps only what an agent acts on: ids, timestamps, tag colors, and the
// monthly trend array were ~60% of the bytes and never used.
-const savedKeywordOutputSchema = z.object({
+const savedKeywordOutputSchema = z.looseObject({
keyword: z.string(),
searchVolume: z.number().nullable(),
keywordDifficulty: z.number().nullable(),
@@ -64,12 +64,14 @@ export const listSavedKeywordsTool = {
description:
"Lists keywords saved to a project (with cached metrics like search volume, difficulty, CPC, and tags if available). Uses no credits — reads from OpenSEO's database, no DataForSEO call. Use tag filters when the user asks for a saved segment; multiple tags match ANY tag.",
inputSchema,
- outputSchema: {
+ outputSchema: z.looseObject({
rows: z.array(savedKeywordOutputSchema),
totalCount: z.number(),
- tags: z.array(z.object({ name: z.string(), keywordCount: z.number() })),
+ tags: z.array(
+ z.looseObject({ name: z.string(), keywordCount: z.number() }),
+ ),
...optionalMetaOutputSchema,
- },
+ }),
annotations: {
readOnlyHint: true,
openWorldHint: false,
diff --git a/src/server/mcp/tools/local-seo-tools.ts b/src/server/mcp/tools/local-seo-tools.ts
index 9d1bc429..36062b3c 100644
--- a/src/server/mcp/tools/local-seo-tools.ts
+++ b/src/server/mcp/tools/local-seo-tools.ts
@@ -220,10 +220,10 @@ export const getBusinessProfileTool = {
description:
"Reads one Google Business Profile: categories, rating and review count, rating breakdown, address, phone, website, claimed status, opening hours, and photo count. Use it to audit your own profile or to compare a competitor's. Charges credits.",
inputSchema: getBusinessProfileInputSchema,
- outputSchema: {
+ outputSchema: z.looseObject({
profile: looseObjectOutputSchema.nullable(),
...optionalMetaOutputSchema,
- },
+ }),
annotations: {
readOnlyHint: false,
openWorldHint: false,
@@ -366,13 +366,13 @@ export const getBusinessReviewsTool = {
description:
"Collects Google reviews for a business, with rating, author, text, and whether the owner replied. Use it for review-gap analysis against competitors and to spot unanswered reviews. Usually completes within this call; if the queued job is still running you get status 'processing' plus a taskId — call again with that taskId in 30-60 seconds to collect the result at no extra cost. Charges credits.",
inputSchema: getBusinessReviewsInputSchema,
- outputSchema: {
+ outputSchema: z.looseObject({
status: z.enum(["completed", "processing"]),
taskId: z.string(),
reviews: z.array(looseObjectOutputSchema).optional(),
totals: looseObjectOutputSchema.nullable().optional(),
...optionalMetaOutputSchema,
- },
+ }),
annotations: {
readOnlyHint: false,
openWorldHint: false,
@@ -507,12 +507,12 @@ export const getBusinessUpdatesTool = {
description:
"Collects the posts (updates, offers, events) published on a Google Business Profile. Use it to check posting activity and recency on your profile or a competitor's. Usually completes within this call; a 'processing' response returns a taskId to call back with in 30-60 seconds at no extra cost. Charges credits.",
inputSchema: getBusinessUpdatesInputSchema,
- outputSchema: {
+ outputSchema: z.looseObject({
status: z.enum(["completed", "processing"]),
taskId: z.string(),
updates: z.array(looseObjectOutputSchema).optional(),
...optionalMetaOutputSchema,
- },
+ }),
annotations: {
readOnlyHint: false,
openWorldHint: false,
@@ -615,15 +615,15 @@ export const listBusinessCategoriesTool = {
description:
"Lists the Google Business categories DataForSEO recognizes, ranked by how many businesses use them. Use it to find valid category slugs for search_local_businesses (e.g. 'pizza_restaurant'). Uses no credits (the full list is cached for 7 days).",
inputSchema: listBusinessCategoriesInputSchema,
- outputSchema: {
+ outputSchema: z.looseObject({
categories: z.array(
- z.object({
+ z.looseObject({
category: z.string(),
businessCount: z.number().nullable(),
}),
),
...optionalMetaOutputSchema,
- },
+ }),
annotations: {
readOnlyHint: true,
openWorldHint: false,
@@ -872,9 +872,9 @@ export const getLocalRankGridTool = {
description:
"Runs one Google Maps search per point of a square grid around a coordinate and reports where the target business ranks at each point — plus each point's result count and #1 business — revealing how far its Maps visibility reaches. Cost scales with the grid: gridSize squared SERP calls (3x3 = 9, the sensible default; 5x5 = 25). Charges credits per grid point.",
inputSchema: getLocalRankGridInputSchema,
- outputSchema: {
+ outputSchema: z.looseObject({
grid: z.array(
- z.object({
+ z.looseObject({
row: z.number(),
col: z.number(),
latitude: z.number(),
@@ -882,7 +882,7 @@ export const getLocalRankGridTool = {
rank: z.number().nullable(),
resultsCount: z.number().optional(),
topResult: z
- .object({
+ .looseObject({
title: z.string().nullable(),
cid: z.string().nullable(),
})
@@ -891,7 +891,7 @@ export const getLocalRankGridTool = {
error: z.boolean().optional(),
}),
),
- summary: z.object({
+ summary: z.looseObject({
pointsSearched: z.number(),
pointsFound: z.number(),
averageRank: z.number().nullable(),
@@ -899,14 +899,14 @@ export const getLocalRankGridTool = {
top10Count: z.number(),
}),
matchedBusiness: z
- .object({
+ .looseObject({
title: z.string().nullable(),
cid: z.string().nullable(),
placeId: z.string().nullable(),
})
.nullable(),
...optionalMetaOutputSchema,
- },
+ }),
annotations: {
readOnlyHint: false,
openWorldHint: false,
diff --git a/src/server/mcp/tools/output-schema-validation.test.ts b/src/server/mcp/tools/output-schema-validation.test.ts
index a86668d5..bbd7fdf5 100644
--- a/src/server/mcp/tools/output-schema-validation.test.ts
+++ b/src/server/mcp/tools/output-schema-validation.test.ts
@@ -1,9 +1,16 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
+import { Ajv } from "@modelcontextprotocol/client/validators/ajv";
+import { z } from "zod";
import { AppError } from "@/server/lib/errors";
import { objectSchema } from "@/server/mcp/output-schemas";
import * as researchTools from "./dataforseo-research-tools";
import * as localSeoTools from "./local-seo-tools";
import { getBacklinksProfileTool } from "./get-backlinks-profile";
+import { getRankTrackerTool } from "./get-rank-tracker";
+import {
+ getProjectContextTool,
+ updateProjectContextTool,
+} from "./project-context";
import { getSearchConsolePerformanceTool } from "./search-console-tools";
import { runSiteAuditTool } from "./site-audit-tools";
import { makeToolContext } from "./tool-test-support";
@@ -181,6 +188,65 @@ describe("MCP output schemas with expected missing fields", () => {
});
});
+describe("MCP output compatibility across deployments", () => {
+ // Clients cache the JSON Schema from tools/list. Zod's safeParse alone
+ // misses this regression: it strips unknown fields, while its exported
+ // output schema rejects them unless the object allows additional fields.
+ const validator = new Ajv({ strict: false });
+
+ it.each([getProjectContextTool, updateProjectContextTool])(
+ "$name accepts new context fields while validating known fields",
+ (tool) => {
+ const validate = validator.compile(
+ z.toJSONSchema(objectSchema(tool.config.outputSchema), {
+ target: "draft-7",
+ }),
+ );
+ const context = {
+ sections: [],
+ missingSections: [],
+ customSections: [],
+ competitors: [],
+ keyPages: [],
+ researchLog: [],
+ reportTemplates: [],
+ futureContextField: [],
+ };
+
+ expect(validate(context)).toBe(true);
+ expect(validate({ ...context, sections: "invalid" })).toBe(false);
+ const { sections: _sections, ...missingSections } = context;
+ expect(validate(missingSections)).toBe(false);
+ },
+ );
+
+ it("get_rank_tracker accepts new run fields while validating known fields", () => {
+ const validate = validator.compile(
+ z.toJSONSchema(getRankTrackerTool.config.outputSchema, {
+ target: "draft-7",
+ }),
+ );
+ const run = {
+ id: "run_1",
+ lastCheckedAt: null,
+ completedAt: "2026-09-17T00:00:00.000Z",
+ status: "completed",
+ errorMessage: null,
+ futureRunField: 1,
+ };
+ const detail = { config: {}, results: { rows: [], run } };
+
+ expect(validate(detail)).toBe(true);
+ expect(validate({ configs: [] })).toBe(true);
+ expect(validate({ results: { rows: [], run: null } })).toBe(true);
+ expect(
+ validate({ results: { rows: [], run: { ...run, status: "invalid" } } }),
+ ).toBe(false);
+ const { completedAt: _completedAt, ...incompleteRun } = run;
+ expect(validate({ results: { rows: [], run: incompleteRun } })).toBe(false);
+ });
+});
+
describe("get_backlinks_profile MCP tool", () => {
it("returns paginated backlink rows and honors filters, sorting, and mode", async () => {
mocks.profileBacklinksPage.mockResolvedValue(backlinkPage);
diff --git a/src/server/mcp/tools/project-context.ts b/src/server/mcp/tools/project-context.ts
index 6d72b6ad..090f45bd 100644
--- a/src/server/mcp/tools/project-context.ts
+++ b/src/server/mcp/tools/project-context.ts
@@ -16,16 +16,20 @@ import {
// Both tools return the whole context, so they share one output shape. Every
// MCP client pays for these schemas on tools/list, so the rows stay loose
// objects — the rendered markdown in `text` is where the detail lives.
-const contextOutputSchema = {
- sections: z.array(looseObjectOutputSchema),
- missingSections: z.array(z.string()),
- customSections: z.array(looseObjectOutputSchema),
- competitors: z.array(looseObjectOutputSchema),
- keyPages: z.array(looseObjectOutputSchema),
- researchLog: z.array(looseObjectOutputSchema),
- reportTemplates: z.array(looseObjectOutputSchema),
- ...optionalMetaOutputSchema,
-} as const;
+// Clients cache this schema across deployments; new context fields must not
+// invalidate a response for clients still using the previous tools/list.
+const contextOutputSchema = z
+ .object({
+ sections: z.array(looseObjectOutputSchema),
+ missingSections: z.array(z.string()),
+ customSections: z.array(looseObjectOutputSchema),
+ competitors: z.array(looseObjectOutputSchema),
+ keyPages: z.array(looseObjectOutputSchema),
+ researchLog: z.array(looseObjectOutputSchema),
+ reportTemplates: z.array(looseObjectOutputSchema),
+ ...optionalMetaOutputSchema,
+ })
+ .passthrough();
const contextPath = (projectId: string) => `/p/${projectId}/context`;
diff --git a/src/server/mcp/tools/report-template-tools.ts b/src/server/mcp/tools/report-template-tools.ts
index c9721a3e..d14bafc2 100644
--- a/src/server/mcp/tools/report-template-tools.ts
+++ b/src/server/mcp/tools/report-template-tools.ts
@@ -29,11 +29,11 @@ const templatesPath = (projectId: string) =>
const listInputSchema = { projectId: projectIdSchema } as const;
-const listOutputSchema = {
+const listOutputSchema = z.looseObject({
templates: z.array(looseObjectOutputSchema),
remaining: z.number(),
...optionalMetaOutputSchema,
-} as const;
+});
export const listReportTemplatesTool = {
name: "list_report_templates",
@@ -119,13 +119,13 @@ const saveInputSchema = {
),
} as const;
-const saveOutputSchema = {
+const saveOutputSchema = z.looseObject({
templateId: z.string(),
name: z.string(),
created: z.boolean(),
url: z.string(),
...optionalMetaOutputSchema,
-} as const;
+});
export const saveReportTemplateTool = {
name: "save_report_template",
diff --git a/src/server/mcp/tools/report-tools.ts b/src/server/mcp/tools/report-tools.ts
index 2a5453c6..264ce43e 100644
--- a/src/server/mcp/tools/report-tools.ts
+++ b/src/server/mcp/tools/report-tools.ts
@@ -101,14 +101,14 @@ const saveInputSchema = {
),
} as const;
-const saveOutputSchema = {
+const saveOutputSchema = z.looseObject({
reportId: z.string(),
title: z.string(),
created: z.boolean(),
htmlBytes: z.number(),
url: z.string(),
...optionalMetaOutputSchema,
-} as const;
+});
export const saveReportTool = {
name: "save_report",
@@ -205,13 +205,13 @@ const listInputSchema = {
.describe("Rows to skip. Omit for the first page."),
} as const;
-const listOutputSchema = {
+const listOutputSchema = z.looseObject({
reports: z.array(looseObjectOutputSchema),
totalCount: z.number(),
rowCount: z.number(),
remaining: z.number(),
...optionalMetaOutputSchema,
-} as const;
+});
export const listReportsTool = {
name: "list_reports",
@@ -296,10 +296,10 @@ const getInputSchema = {
),
} as const;
-const getOutputSchema = {
+const getOutputSchema = z.looseObject({
report: looseObjectOutputSchema,
...optionalMetaOutputSchema,
-} as const;
+});
export const getReportTool = {
name: "get_report",
diff --git a/src/server/mcp/tools/research-keywords.ts b/src/server/mcp/tools/research-keywords.ts
index c40aa6e0..cb757a20 100644
--- a/src/server/mcp/tools/research-keywords.ts
+++ b/src/server/mcp/tools/research-keywords.ts
@@ -88,7 +88,7 @@ export const researchKeywordsTool = {
description:
"Research keyword data (search volume, difficulty, CPC, related ideas) for 1-5 seed keywords in one call. Charges credits per seed (~30-100 credits each, varies by source; flat ~96 for countries served from Google Ads data, where difficulty/intent are unavailable). Returns per-seed results — a single bad seed won't fail the batch.",
inputSchema,
- outputSchema: {
+ outputSchema: z.looseObject({
results: z.array(
z.union([
z
@@ -111,7 +111,7 @@ export const researchKeywordsTool = {
]),
),
...optionalMetaOutputSchema,
- },
+ }),
annotations: {
readOnlyHint: false,
openWorldHint: false,
diff --git a/src/server/mcp/tools/save-keywords.ts b/src/server/mcp/tools/save-keywords.ts
index f91877ed..c81faa7b 100644
--- a/src/server/mcp/tools/save-keywords.ts
+++ b/src/server/mcp/tools/save-keywords.ts
@@ -52,7 +52,7 @@ export const saveKeywordsTool = {
description:
"Save keywords to a project's saved-keywords list. Uses no credits — does not call DataForSEO. Idempotent: re-saving an existing keyword is a no-op. If tags are provided, missing tags may be created. By default tags are appended; set tagMode=replace to remove existing tags from these saved keywords before applying the provided tags, which is useful for reorganizing keywords into page/topic clusters. Ask the user for confirmation before applying or replacing tags broadly.",
inputSchema,
- outputSchema: {
+ outputSchema: z.looseObject({
projectId: z.string(),
savedCount: z.number(),
keywords: z.array(z.string()),
@@ -61,7 +61,7 @@ export const saveKeywordsTool = {
locationCode: z.number(),
languageCode: z.string(),
...optionalMetaOutputSchema,
- },
+ }),
annotations: {
readOnlyHint: false,
openWorldHint: false,
diff --git a/src/server/mcp/tools/search-console-tools.ts b/src/server/mcp/tools/search-console-tools.ts
index d0e1397f..8f95dc30 100644
--- a/src/server/mcp/tools/search-console-tools.ts
+++ b/src/server/mcp/tools/search-console-tools.ts
@@ -252,7 +252,7 @@ export const getSearchConsolePerformanceTool = {
description:
"Query the connected Search Console property's Search Analytics: clicks, impressions, CTR, and average position by query/page/country/device/date. First-party data — use it for what already ranks, near-ranking queries, and pages with real demand. Google sorts by clicks and can't filter by position, so minPosition/maxPosition/minImpressions are applied server-side over the top 1000 rows of the window — use them instead of fetching everything. ctr is a 0-1 fraction; position is a 1-based average and is omitted from rows when type is 'discover' or 'googleNews' (Google does not report it there — treat it as unavailable, not a failure); dates are Pacific Time; the last ~3 days may be incomplete. Read-only; uses no credits.",
inputSchema: perfInputSchema,
- outputSchema: {
+ outputSchema: z.looseObject({
ok: z.boolean(),
reason: z.string().optional(),
connectUrl: z.string().optional(),
@@ -281,7 +281,7 @@ export const getSearchConsolePerformanceTool = {
hasMore: z.boolean().optional(),
nextStartRow: z.number().optional(),
...optionalMetaOutputSchema,
- },
+ }),
annotations: {
readOnlyHint: true,
openWorldHint: false,
@@ -426,7 +426,7 @@ export const inspectUrlsTool = {
description:
"Run Google Search Console's URL Inspection on up to 10 URLs of the connected property: index/coverage state, last crawl time, Google-selected vs declared canonical, and mobile/rich-results verdicts. Use it to answer 'is this page indexed? why not?'. Per-URL failures are reported inline. Read-only; uses no credits.",
inputSchema: inspectInputSchema,
- outputSchema: {
+ outputSchema: z.looseObject({
ok: z.boolean(),
reason: z.string().optional(),
connectUrl: z.string().optional(),
@@ -444,7 +444,7 @@ export const inspectUrlsTool = {
)
.optional(),
...optionalMetaOutputSchema,
- },
+ }),
annotations: {
readOnlyHint: true,
openWorldHint: false,
diff --git a/src/server/mcp/tools/search-serp-locations.ts b/src/server/mcp/tools/search-serp-locations.ts
index 4b3cd20f..9247b6f6 100644
--- a/src/server/mcp/tools/search-serp-locations.ts
+++ b/src/server/mcp/tools/search-serp-locations.ts
@@ -25,16 +25,16 @@ export const searchSerpLocationsTool = {
description:
"Find the exact DataForSEO location name for local rank tracking. Returns up to 10 matches; pass the chosen `locationName` verbatim to create_rank_tracker. Uses no credits.",
inputSchema,
- outputSchema: {
+ outputSchema: z.looseObject({
locations: z.array(
- z.object({
+ z.looseObject({
locationName: z.string(),
locationCode: z.number(),
locationType: z.string(),
}),
),
...optionalMetaOutputSchema,
- },
+ }),
annotations: {
readOnlyHint: true,
openWorldHint: false,
diff --git a/src/server/mcp/tools/whoami.ts b/src/server/mcp/tools/whoami.ts
index 472c9f02..45492e4e 100644
--- a/src/server/mcp/tools/whoami.ts
+++ b/src/server/mcp/tools/whoami.ts
@@ -25,13 +25,13 @@ export const whoamiTool = {
description:
"Confirms the connected OpenSEO account, server mode, token scopes, and current credit balance when the user asks to check their account or connection. Uses no credits — does not call DataForSEO.",
inputSchema: {} as Record<string, never>,
- outputSchema: {
+ outputSchema: z.looseObject({
userEmail: z.string(),
scopes: z.array(z.string()),
mode: z.enum(["hosted", "self-hosted"]),
creditsRemaining: z.number().nullable(),
...optionalMetaOutputSchema,
- },
+ }),
annotations: {
readOnlyHint: true,
openWorldHint: false,