Skip to content

Open source alternative to Semrush and Ahrefs

Show trial credits for new MCP accounts (EVE-377) (#810)

Ben Senescu031d2ee18fa0
diff --git a/plugins/openseo/.claude-plugin/plugin.json b/plugins/openseo/.claude-plugin/plugin.json
index 80124743..b5cfe203 100644
--- a/plugins/openseo/.claude-plugin/plugin.json
+++ b/plugins/openseo/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "openseo",
"displayName": "OpenSEO",
- "version": "1.0.12",
+ "version": "1.0.13",
"description": "Research keywords and competitors, audit sites, track rankings, and use connected Search Console data from your AI assistant.",
"author": {
"name": "OpenSEO",
diff --git a/plugins/openseo/.codex-plugin/plugin.json b/plugins/openseo/.codex-plugin/plugin.json
index 746150f5..0edf05c7 100644
--- a/plugins/openseo/.codex-plugin/plugin.json
+++ b/plugins/openseo/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "openseo",
- "version": "1.0.12",
+ "version": "1.0.13",
"description": "Research keywords and competitors, audit sites, track rankings, and use connected Search Console data from your AI assistant.",
"author": {
"name": "OpenSEO",
diff --git a/plugins/openseo/.cursor-plugin/plugin.json b/plugins/openseo/.cursor-plugin/plugin.json
index 231dabf2..abbcde2b 100644
--- a/plugins/openseo/.cursor-plugin/plugin.json
+++ b/plugins/openseo/.cursor-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "openseo",
- "version": "1.0.12",
+ "version": "1.0.13",
"description": "Research keywords and competitors, audit sites, track rankings, and use connected Search Console data from your AI assistant.",
"author": {
"name": "Every App, Inc",
diff --git a/src/server/billing/subscription.ts b/src/server/billing/subscription.ts
index 2fc98303..d4164b23 100644
--- a/src/server/billing/subscription.ts
+++ b/src/server/billing/subscription.ts
@@ -139,6 +139,15 @@ export async function getUsageCreditsRemaining(customerId: string): Promise<{
);
}
+ // A missing optional top-up denies access; allowed with no balance is the
+ // SDK's fail-open response, so the total is unknown rather than base-only.
+ if (topupCheck.allowed && !topupCheck.balance) {
+ throw new AppError(
+ "INTERNAL_ERROR",
+ `Autumn check returned no ${AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID} balance for customer ${customerId}`,
+ );
+ }
+
return {
monthlyRemaining: monthlyBalance.remaining,
topupRemaining: topupCheck.balance?.remaining ?? 0,
diff --git a/src/server/mcp/tools/whoami.test.ts b/src/server/mcp/tools/whoami.test.ts
new file mode 100644
index 00000000..c938a9cb
--- /dev/null
+++ b/src/server/mcp/tools/whoami.test.ts
@@ -0,0 +1,148 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,
+ AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,
+} from "@/shared/billing";
+import { whoamiTool } from "./whoami";
+import { makeToolContext, textContent } from "./tool-test-support";
+
+const mocks = vi.hoisted(() => ({
+ check: vi.fn<(args: { featureId: string }) => Promise<unknown>>(),
+ getOrCreate: vi.fn(),
+ kvGet: vi.fn(),
+ kvPut: vi.fn(),
+ isHosted: vi.fn(),
+}));
+
+vi.mock("cloudflare:workers", () => ({
+ env: { KV: { get: mocks.kvGet, put: mocks.kvPut } },
+}));
+vi.mock("@/server/billing/autumn", () => ({
+ autumn: {
+ check: mocks.check,
+ customers: { getOrCreate: mocks.getOrCreate },
+ },
+}));
+vi.mock("@/server/lib/runtime-env", () => ({
+ isHostedServerAuthMode: mocks.isHosted,
+}));
+vi.mock("@/server/lib/posthog", () => ({ captureServerEvent: vi.fn() }));
+
+const context = makeToolContext({ orgScope: "user" });
+
+beforeEach(() => {
+ mocks.isHosted.mockResolvedValue(true);
+ mocks.kvGet.mockResolvedValue(null);
+ mocks.kvPut.mockResolvedValue(undefined);
+ mocks.getOrCreate.mockResolvedValue({ id: context.auth.organizationId });
+ mocks.check.mockImplementation(async ({ featureId }) =>
+ featureId === AUTUMN_SEO_DATA_BALANCE_FEATURE_ID
+ ? { allowed: true, balance: { remaining: 500 } }
+ : { allowed: false, balance: null },
+ );
+});
+
+describe("whoami", () => {
+ it("initializes a fresh hosted billing customer before reading its trial balance", async () => {
+ const result = await whoamiTool.handler({}, context);
+
+ expect(mocks.getOrCreate).toHaveBeenCalledWith({
+ customerId: context.auth.organizationId,
+ email: context.auth.userEmail,
+ });
+ expect(mocks.getOrCreate).toHaveBeenCalledBefore(mocks.check);
+ expect(mocks.check).toHaveBeenCalledWith({
+ customerId: context.auth.organizationId,
+ featureId: AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,
+ });
+ expect(result.structuredContent.creditsRemaining).toBe(500);
+ expect(result._meta?.creditsRemaining).toBe(500);
+ expect(textContent(result)).toContain("Credits remaining: 500");
+ });
+
+ it.each([
+ { monthly: 0, topup: null, expected: 0 },
+ { monthly: 200, topup: 75, expected: 275 },
+ { monthly: 0, topup: 75, expected: 75 },
+ ])(
+ "reports $expected credits for $monthly base and $topup top-up",
+ async ({ monthly, topup, expected }) => {
+ mocks.check.mockImplementation(async ({ featureId }) => {
+ const remaining =
+ featureId === AUTUMN_SEO_DATA_BALANCE_FEATURE_ID ? monthly : topup;
+ return {
+ allowed: remaining != null && remaining > 0,
+ balance: remaining == null ? null : { remaining },
+ };
+ });
+
+ const result = await whoamiTool.handler({}, context);
+
+ expect(result.structuredContent.creditsRemaining).toBe(expected);
+ },
+ );
+
+ it.each([
+ {
+ name: "missing base balance",
+ featureId: AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,
+ throws: false,
+ },
+ {
+ name: "failed base lookup",
+ featureId: AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,
+ throws: true,
+ },
+ {
+ name: "failed top-up lookup",
+ featureId: AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,
+ throws: true,
+ },
+ {
+ name: "fail-open top-up lookup",
+ featureId: AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,
+ throws: false,
+ },
+ ])("reports unknown for a $name", async ({ featureId, throws }) => {
+ mocks.check.mockImplementation(async (args) => {
+ if (args.featureId === featureId) {
+ if (throws) throw new Error("Billing unavailable");
+ return { allowed: true, balance: null };
+ }
+ return { allowed: true, balance: { remaining: 75 } };
+ });
+
+ const result = await whoamiTool.handler({}, context);
+
+ expect(result.structuredContent.creditsRemaining).toBeNull();
+ expect(result._meta).toBeUndefined();
+ expect(textContent(result)).toContain("Credits remaining: unknown");
+ });
+
+ it("keeps account identity available when billing initialization fails", async () => {
+ mocks.getOrCreate.mockRejectedValue(new Error("Billing unavailable"));
+
+ const result = await whoamiTool.handler({}, context);
+
+ expect(result.structuredContent).toMatchObject({
+ userEmail: context.auth.userEmail,
+ scopes: context.auth.scopes,
+ mode: "hosted",
+ creditsRemaining: null,
+ });
+ expect(mocks.check).not.toHaveBeenCalled();
+ });
+
+ it("avoids Autumn in self-hosted mode", async () => {
+ mocks.isHosted.mockResolvedValue(false);
+
+ const result = await whoamiTool.handler({}, context);
+
+ expect(result.structuredContent).toMatchObject({
+ mode: "self-hosted",
+ creditsRemaining: null,
+ });
+ expect(mocks.getOrCreate).not.toHaveBeenCalled();
+ expect(mocks.check).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/server/mcp/tools/whoami.ts b/src/server/mcp/tools/whoami.ts
index 45492e4e..5d7d9e1f 100644
--- a/src/server/mcp/tools/whoami.ts
+++ b/src/server/mcp/tools/whoami.ts
@@ -1,29 +1,19 @@
-import { autumn } from "@/server/billing/autumn";
import {
- AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,
- AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,
-} from "@/shared/billing";
+ getOrCreateOrganizationCustomer,
+ getUsageCreditsRemaining,
+} from "@/server/billing/subscription";
import { mcpResponse } from "@/server/mcp/formatters";
import { type ToolContext } from "@/server/mcp/context";
import { isHostedServerAuthMode } from "@/server/lib/runtime-env";
import { optionalMetaOutputSchema } from "@/server/mcp/output-schemas";
import { z } from "zod";
-async function checkBalance(featureId: string, customerId: string) {
- try {
- const result = await autumn.check({ customerId, featureId });
- return result.balance?.remaining ?? null;
- } catch {
- return null;
- }
-}
-
export const whoamiTool = {
name: "whoami",
config: {
title: "Who am I",
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.",
+ "Confirms the connected OpenSEO account, server mode, token scopes, and current credit balance when the user asks to check their account or connection. Initializes billing for new hosted accounts. Uses no credits — does not call DataForSEO. Returns creditsRemaining: null when the balance is unavailable.",
inputSchema: {} as Record<string, never>,
outputSchema: z.looseObject({
userEmail: z.string(),
@@ -33,7 +23,8 @@ export const whoamiTool = {
...optionalMetaOutputSchema,
}),
annotations: {
- readOnlyHint: true,
+ readOnlyHint: false,
+ idempotentHint: true,
openWorldHint: false,
destructiveHint: false,
},
@@ -43,14 +34,14 @@ export const whoamiTool = {
const isHosted = await isHostedServerAuthMode();
let creditsRemaining: number | null = null;
if (isHosted) {
- const [base, topup] = await Promise.all([
- checkBalance(AUTUMN_SEO_DATA_BALANCE_FEATURE_ID, auth.organizationId),
- checkBalance(
- AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,
- auth.organizationId,
- ),
- ]);
- creditsRemaining = (base ?? 0) + (topup ?? 0);
+ try {
+ const customer = await getOrCreateOrganizationCustomer(auth);
+ const { monthlyRemaining, topupRemaining } =
+ await getUsageCreditsRemaining(customer.id);
+ creditsRemaining = monthlyRemaining + topupRemaining;
+ } catch {
+ // Account identity is still available when billing is unavailable.
+ }
}
const lines = [
`Account: ${auth.userEmail}`,