Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
Load the MCP stack lazily to fix worker startup CPU limit failures (#911)
Ben Senescu0175aa4ce60f
diff --git a/src/server.ts b/src/server.tsindex 9f3ea5ca..8184756c 100644--- a/src/server.ts+++ b/src/server.ts@@ -17,7 +17,6 @@ import {} from "@/server/mcp/oauth-provider";import { requestWithPublicOrigin } from "@/server/mcp/public-origin";import { MCP_ROUTE } from "@/server/mcp/context";-import { handleSelfHostedOpenSeoMcpRequest } from "@/server/mcp/transport";import { withPgClient } from "@/db";import {AUTUMN_WEBHOOK_PATH,@@ -176,7 +175,10 @@ function handleFetch((authMode === "cloudflare_access" || authMode === "local_noauth") &&pathname === MCP_ROUTE) {- return handleSelfHostedOpenSeoMcpRequest(publicRequest, authMode, env, ctx);+ return import("@/server/mcp/transport").then(+ ({ handleSelfHostedOpenSeoMcpRequest }) =>+ handleSelfHostedOpenSeoMcpRequest(publicRequest, authMode, env, ctx),+ );}return appFetch(request);diff --git a/src/server/features/sam/SamChatAgent.ts b/src/server/features/sam/SamChatAgent.tsindex 80ecceaf..34010797 100644--- a/src/server/features/sam/SamChatAgent.ts+++ b/src/server/features/sam/SamChatAgent.ts@@ -26,7 +26,6 @@ import {import { SamSessionRepository } from "@/server/features/sam/SamSessionRepository";import { ProjectContextService } from "@/server/features/project-context/services/ProjectContextService";import { ProjectRepository } from "@/server/features/projects/repositories/ProjectRepository";-import { buildSamMcpTools } from "@/server/features/sam/samChatTools";import { buildSamSkillSource } from "@/server/features/sam/samSkills";import { buildSamSystemPrompt } from "@/server/features/sam/samSystemPrompt";import {@@ -379,8 +378,10 @@ export class SamChatAgent extends Think {scopes: [MCP_SCOPE],};+ // Loaded per turn, not at startup: the tool schemas are costly to build.+ const samTools = await import("@/server/features/sam/samChatTools");return {- tools: buildSamMcpTools(authContext, ctx.project, turn.turnId),+ tools: samTools.buildSamMcpTools(authContext, ctx.project, turn.turnId),// SAM runs complex multi-step work in one turn (site-read intake plus// a full research chain, multi-competitor sweeps), so the step budget// is generous; cost is bounded by per-step metering and the modeldiff --git a/src/server/mcp/api-key-auth.ts b/src/server/mcp/api-key-auth.tsindex 8529ffcf..001b24a1 100644--- a/src/server/mcp/api-key-auth.ts+++ b/src/server/mcp/api-key-auth.ts@@ -5,7 +5,6 @@ import { resolveExistingActiveHostedOrganization } from "@/server/auth/default-himport { AuthRepository } from "@/server/auth/repositories/AuthRepository";import { recordMcpAuthorized } from "@/server/features/activation/mcpActivation";import { createWorkersOAuthMcpProps, MCP_ROUTE } from "@/server/mcp/context";-import { handleAuthenticatedOpenSeoMcpRequest } from "@/server/mcp/transport";function getApiKey(request: Request) {// Both branches require the oseo_ prefix: anything else (a Cloudflare OAuth@@ -156,6 +155,8 @@ export async function handleMcpApiKeyRequest(await recordMcpAuthorized(organizationId);+ const { handleAuthenticatedOpenSeoMcpRequest } =+ await import("@/server/mcp/transport");return await handleAuthenticatedOpenSeoMcpRequest(request, props, env, ctx);} catch (error) {// Without this, a throw here surfaces as a bare platform 500 with no logdiff --git a/src/server/mcp/context.ts b/src/server/mcp/context.tsindex 875df96a..019b8887 100644--- a/src/server/mcp/context.ts+++ b/src/server/mcp/context.ts@@ -1,7 +1,4 @@-import {- CLIENT_INFO_META_KEY,- type ServerContext,-} from "@modelcontextprotocol/server";+import type { ServerContext } from "@modelcontextprotocol/server";import { z } from "zod";import type { BillingCustomerContext } from "@/server/billing/subscription";import { resolveClientLabel } from "@/server/mcp/client-label";@@ -103,6 +100,11 @@ export function createWorkersOAuthMcpProps(// `mcpReq.envelope` before any handler runs — so the envelope is the only place// to look. It is client-supplied and typed as an open envelope, so parse it// rather than reaching into it.+//+// The SDK's CLIENT_INFO_META_KEY, spelled out: a value import from+// @modelcontextprotocol/server would evaluate the whole SDK, protocol schemas+// included, at worker startup, and this module is on the eager path.+const CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo";const clientInfoMetaSchema = z.object({[CLIENT_INFO_META_KEY]: z.object({ title: z.string().optional() }).optional(),});diff --git a/src/server/mcp/oauth-provider.ts b/src/server/mcp/oauth-provider.tsindex b0e32546..803fbd47 100644--- a/src/server/mcp/oauth-provider.ts+++ b/src/server/mcp/oauth-provider.ts@@ -25,7 +25,6 @@ import {} from "@/server/mcp/context";import { normalizeClientRegistrationRequest } from "@/server/mcp/oauth-registration";import { getPublicOrigin } from "@/server/mcp/public-origin";-import { handleAuthenticatedOpenSeoMcpRequest } from "@/server/mcp/transport";import { resolveHostedContext } from "@/middleware/ensure-user/hosted";import { handleMcpApiKeyRequest } from "@/server/mcp/api-key-auth";@@ -395,6 +394,8 @@ function createDefaultHandler(const mcpApiHandler: ExportedHandlerWithFetch<OpenSeoOAuthEnv> = {async fetch(request, env, ctx) {+ const { handleAuthenticatedOpenSeoMcpRequest } =+ await import("@/server/mcp/transport");return handleAuthenticatedOpenSeoMcpRequest(request, ctx.props, env, ctx);},};diff --git a/vite-plugin-lean-worker-bundle.ts b/vite-plugin-lean-worker-bundle.tsindex 60d17e3a..fe2236e2 100644--- a/vite-plugin-lean-worker-bundle.ts+++ b/vite-plugin-lean-worker-bundle.ts@@ -44,6 +44,17 @@ const EAGER_DENYLIST: Array<{ pattern: RegExp; expected: string }> = ["replaced with an en-only barrel via the load hook below (we never " +"localize zod errors)",},+ {+ // Startup CPU, not memory: every tool's zod input/output schemas and the+ // SDK's protocol schemas are built at module scope, which pushed the main+ // worker toward the 400 ms startup CPU limit.+ pattern:+ /node_modules\/@modelcontextprotocol\/server\/|\/src\/server\/mcp\/(server|transport|tools\/)/,+ expected:+ "lazy-loaded behind the dynamic imports of src/server/mcp/transport.ts " ++ "(server.ts, oauth-provider.ts, api-key-auth.ts) and samChatTools.ts " ++ "(SamChatAgent.beforeTurn)",+ },{// Pre-existing boundary from the site-audit engine, guarded here too.pattern: /node_modules\/cheerio\//,