Skip to content

Open source alternative to Semrush and Ahrefs

Mark mcpConnected when an API key is created, not on every MCP request (#981)

Carter Smith1c6fce865a30
diff --git a/src/lib/auth.ts b/src/lib/auth.ts
index dcc260da..b85e1504 100644
--- a/src/lib/auth.ts
+++ b/src/lib/auth.ts
@@ -1,6 +1,6 @@
import { env } from "cloudflare:workers";
import { betterAuth } from "better-auth";
-import { APIError } from "better-auth/api";
+import { APIError, createAuthMiddleware } from "better-auth/api";
import { captcha } from "better-auth/plugins";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { tanstackStartCookies } from "better-auth/tanstack-start";
@@ -28,6 +28,7 @@ import {
productUpdatesOnByDefault,
requestPrivacyChoices,
} from "@/shared/privacy-choices";
+import { markOnboardingMilestone } from "@/server/email/onboarding-drip";
import {
sendHostedPasswordResetEmail,
sendHostedVerificationEmail,
@@ -45,6 +46,8 @@ const hostedBaseUrlSchema = z
);
}, "BETTER_AUTH_URL must use https or localhost");
+const createdApiKeySchema = z.object({ referenceId: z.string() });
+
function createAuth() {
// Hosted needs the real configured URL (cookies, callbacks, /api/auth routes
// all use it). Self-hosted only builds this instance to mint/refresh Search
@@ -213,6 +216,25 @@ function createAuth() {
: []),
tanstackStartCookies(),
],
+ hooks: {
+ // Marked when the user creates an MCP API key, the API-key counterpart
+ // of OAuth's authorize step. Not on each /mcp request: isolates share no
+ // memory, so every one would re-send it and hit Loops' team-wide rate
+ // limit.
+ after: createAuthMiddleware(async (ctx) => {
+ if (ctx.path !== "/api-key/create") return;
+ const created = createdApiKeySchema.safeParse(ctx.context.returned);
+ if (!created.success) return;
+ const user = await AuthRepository.getHostedUser(
+ created.data.referenceId,
+ );
+ if (!user) return;
+ await markOnboardingMilestone(
+ { userId: user.id, userEmail: user.email },
+ "mcpConnected",
+ );
+ }),
+ },
databaseHooks: {
user: {
create: {
diff --git a/src/server/email/onboarding-drip.ts b/src/server/email/onboarding-drip.ts
index b619b5cc..efebfa5b 100644
--- a/src/server/email/onboarding-drip.ts
+++ b/src/server/email/onboarding-drip.ts
@@ -56,9 +56,9 @@ export async function sendCreditsExhaustedEvent(
);
}
-// Some callers are hot paths (every API-key MCP request, every request
-// refused for credits), and Loops rate-limits the whole team, transactional
-// emails included. So each isolate sends each update once.
+// Some callers are hot paths (every request refused for credits), and Loops
+// rate-limits the whole team, transactional emails included. So each isolate
+// sends each update once.
const sentKeys = new Set<string>();
async function sendOnce(
diff --git a/src/server/mcp/api-key-auth.test.ts b/src/server/mcp/api-key-auth.test.ts
index df5244d1..beb8ba7f 100644
--- a/src/server/mcp/api-key-auth.test.ts
+++ b/src/server/mcp/api-key-auth.test.ts
@@ -37,9 +37,6 @@ vi.mock("@/server/features/activation/mcpActivation", () => ({
recordMcpAuthorized: mocks.recordMcpAuthorized,
}));
-vi.mock("@/server/email/onboarding-drip", () => ({
- markOnboardingMilestone: vi.fn(),
-}));
vi.mock("@/server/mcp/transport", () => ({
handleAuthenticatedOpenSeoMcpRequest:
mocks.handleAuthenticatedOpenSeoMcpRequest,
diff --git a/src/server/mcp/api-key-auth.ts b/src/server/mcp/api-key-auth.ts
index 8772d9df..001b24a1 100644
--- a/src/server/mcp/api-key-auth.ts
+++ b/src/server/mcp/api-key-auth.ts
@@ -4,7 +4,6 @@ import { MCP_OAUTH_SCOPES } from "@/lib/oauth-resource";
import { resolveExistingActiveHostedOrganization } from "@/server/auth/default-hosted-organization";
import { AuthRepository } from "@/server/auth/repositories/AuthRepository";
import { recordMcpAuthorized } from "@/server/features/activation/mcpActivation";
-import { markOnboardingMilestone } from "@/server/email/onboarding-drip";
import { createWorkersOAuthMcpProps, MCP_ROUTE } from "@/server/mcp/context";
function getApiKey(request: Request) {
@@ -155,10 +154,6 @@ export async function handleMcpApiKeyRequest(
});
await recordMcpAuthorized(organizationId);
- await markOnboardingMilestone(
- { userId, userEmail: user.email },
- "mcpConnected",
- );
const { handleAuthenticatedOpenSeoMcpRequest } =
await import("@/server/mcp/transport");