From 80975a251e4b21f3f4070f50c56b9ef8ef12723f Mon Sep 17 00:00:00 2001 From: "helpcode.ai" Date: Sat, 5 Dec 2026 21:34:50 +0100 Subject: [PATCH 1/2] Count tool calls per workspace against plan limits (dry-run) --- .env.example | 3 + docker-compose.cloud.yml | 3 + docs/deployment.md | 1 + llms-full.txt | 1 + .../src/mcp-server/dynamic-mcp-tools.ts | 112 ++++--- ...dynamic-mcp-tools.workspace-limits.spec.ts | 55 ++++ .../src/mcp-server/mcp-server.module.ts | 3 +- .../mcp-server/workspace-call-limits.spec.ts | 165 ++++++++++ .../src/mcp-server/workspace-call-limits.ts | 311 ++++++++++++++++++ 9 files changed, 615 insertions(+), 39 deletions(-) create mode 100644 packages/backend/src/mcp-server/dynamic-mcp-tools.workspace-limits.spec.ts create mode 100644 packages/backend/src/mcp-server/workspace-call-limits.spec.ts create mode 100644 packages/backend/src/mcp-server/workspace-call-limits.ts diff --git a/.env.example b/.env.example index 0c3014dc9..67841a147 100644 --- a/.env.example +++ b/.env.example @@ -174,6 +174,9 @@ SERVER_URL=http://localhost:4000 # ── MCP Rate Limiting ────────────────────────────────────────────────────── # Max requests per minute per client (by API key or IP). Only enforced when Redis is available. MCP_RATE_LIMIT_PER_MINUTE=60 +# Per-workspace tool-call limits by plan: off | dry-run | on. +# Default: dry-run on Cloud (DEPLOYMENT_MODE=cloud), off when self-hosted. +# MCP_WORKSPACE_LIMITS=off # ── Per-user values for connectors (Enterprise, optional) ──────────────────── # Lets a connector that signs in with a key, a token or a password ask every diff --git a/docker-compose.cloud.yml b/docker-compose.cloud.yml index ed485ab11..88f958e65 100644 --- a/docker-compose.cloud.yml +++ b/docker-compose.cloud.yml @@ -202,6 +202,9 @@ x-backend: &backend # unset = dry-run (log only), on = enforce, off = neither. It was never # passed to the container, so it could not be switched from the .env. - PLAN_CAPS_ENFORCE=${PLAN_CAPS_ENFORCE:-} + # Per-workspace tool-call limits (workspace-call-limits.ts). Empty = dry-run + # on Cloud; set to `on` in .env to refuse calls over the plan's limits. + - MCP_WORKSPACE_LIMITS=${MCP_WORKSPACE_LIMITS:-} # The connection grant on a server's own URL (docs/deployment.md): # unset = enforce, report = log only, off = no check. - MCP_GRANT_SERVER_SCOPE=${MCP_GRANT_SERVER_SCOPE:-} diff --git a/docs/deployment.md b/docs/deployment.md index 29f6cb996..331589b1d 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -407,6 +407,7 @@ curl -s http://localhost:4000/api/mcp-api-keys \ | `MCP_API_KEY` | No | API key for legacy MCP auth | | `SERVER_URL` | No | Server URL for OAuth2 metadata (default: `http://localhost:4000`) | | `MCP_RATE_LIMIT_PER_MINUTE` | No | Rate limit per client (default: 60) | +| `MCP_WORKSPACE_LIMITS` | No | Per-workspace tool-call limits by plan (calls per minute, per hour, at once): `off`, `dry-run` (count and log only) or `on` (refuse). Default: `dry-run` on Cloud, `off` self-hosted | | `MCP_GRANT_SERVER_SCOPE` | No | Whether what a person allowed an AI client while connecting it also limits which MCP servers that client opens by their own URL (`/mcp/`). `enforce` (default): a client connected to one server, or to the servers picked on the authorization page, gets a 401 on any other server of the workspace and runs the authorization again for that URL; allowing it adds the server to what the client may reach. `report`: nothing is refused, the backend logs one warning (`MCP grant scope (report only)…`) for each client, user and server it would refuse, at most once in ten minutes. `off`: no check. It applies to OAuth connections only: API keys, the static credentials and connections without a stored choice (made before September 2026, or through single sign-on before this version) are not affected. Same on Cloud and self-hosted; a change needs a restart of the backend. | | `TOOL_MAX_RESPONSE_BYTES` | No | Largest upstream response body, in bytes after decompression, that one tool call reads from a REST, JSON-RPC, OData, GraphQL or SOAP API (default: `10485760`, 10 MB, on Cloud and self-hosted). A bigger response fails the call with code `TOOL_RESPONSE_TOO_LARGE` and a message that asks the model to narrow the request. The same limit applies to the text sent to the MCP client, for every connector type (database and MCP connectors too): a result over it is sent as compact JSON, and if that is still too big the call fails with the same code | | `DISPOSABLE_EMAIL_CHECK` | No | `on` / `off`: refuse throwaway inboxes (yopmail, mailinator and the rest of the vendored [disposable-email-domains](https://github.com/disposable-email-domains/disposable-email-domains) list) when a new account is created: sign-up, a new account from an invitation and, on Cloud, social sign-in. Forwarding services that deliver to a real inbox (Apple Hide My Email, SimpleLogin, Firefox Relay, DuckDuckGo) are not on the list. Default: `on` on Cloud, `off` on self-hosted | diff --git a/llms-full.txt b/llms-full.txt index a7b85b701..71b32c90f 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -685,6 +685,7 @@ curl -s http://localhost:4000/api/mcp-api-keys \ | `MCP_API_KEY` | No | API key for legacy MCP auth | | `SERVER_URL` | No | Server URL for OAuth2 metadata (default: `http://localhost:4000`) | | `MCP_RATE_LIMIT_PER_MINUTE` | No | Rate limit per client (default: 60) | +| `MCP_WORKSPACE_LIMITS` | No | Per-workspace tool-call limits by plan (calls per minute, per hour, at once): `off`, `dry-run` (count and log only) or `on` (refuse). Default: `dry-run` on Cloud, `off` self-hosted | | `MCP_GRANT_SERVER_SCOPE` | No | Whether what a person allowed an AI client while connecting it also limits which MCP servers that client opens by their own URL (`/mcp/`). `enforce` (default): a client connected to one server, or to the servers picked on the authorization page, gets a 401 on any other server of the workspace and runs the authorization again for that URL; allowing it adds the server to what the client may reach. `report`: nothing is refused, the backend logs one warning (`MCP grant scope (report only)…`) for each client, user and server it would refuse, at most once in ten minutes. `off`: no check. It applies to OAuth connections only: API keys, the static credentials and connections without a stored choice (made before September 2026, or through single sign-on before this version) are not affected. Same on Cloud and self-hosted; a change needs a restart of the backend. | | `TOOL_MAX_RESPONSE_BYTES` | No | Largest upstream response body, in bytes after decompression, that one tool call reads from a REST, JSON-RPC, OData, GraphQL or SOAP API (default: `10485760`, 10 MB, on Cloud and self-hosted). A bigger response fails the call with code `TOOL_RESPONSE_TOO_LARGE` and a message that asks the model to narrow the request. The same limit applies to the text sent to the MCP client, for every connector type (database and MCP connectors too): a result over it is sent as compact JSON, and if that is still too big the call fails with the same code | | `DISPOSABLE_EMAIL_CHECK` | No | `on` / `off`: refuse throwaway inboxes (yopmail, mailinator and the rest of the vendored [disposable-email-domains]() list) when a new account is created: sign-up, a new account from an invitation and, on Cloud, social sign-in. Forwarding services that deliver to a real inbox (Apple Hide My Email, SimpleLogin, Firefox Relay, DuckDuckGo) are not on the list. Default: `on` on Cloud, `off` on self-hosted | diff --git a/packages/backend/src/mcp-server/dynamic-mcp-tools.ts b/packages/backend/src/mcp-server/dynamic-mcp-tools.ts index 34a2a021f..a6e3ad438 100644 --- a/packages/backend/src/mcp-server/dynamic-mcp-tools.ts +++ b/packages/backend/src/mcp-server/dynamic-mcp-tools.ts @@ -83,6 +83,7 @@ import { userVariablePlacementProblem, } from '../connectors/user-variable-switch.util'; import { ToolRateLimitService } from './tool-rate-limit.service'; +import { WorkspaceCallLimiter } from './workspace-call-limits'; import { connectorErrorWhen, connectorLargeIntegers } from '../connectors/error-when.util'; import { isBinaryBody, @@ -179,6 +180,48 @@ const REFUSAL_COUNT_TTL_S = 14 * 24 * 60 * 60; const REFUSAL_EMAIL_KEY = 'cred_refused_mail:'; const REFUSAL_EMAIL_PAUSE_S = 7 * 24 * 60 * 60; +/** Who is calling executeTool, and through which endpoint. */ +export interface ExecuteToolContext { + userId?: string; + userEmail?: string; + organizationId?: string; + authMethod?: string; + apiKeyName?: string; + /** Set when the caller used an operator's support key (support-keys.ts). */ + supportKeyId?: string; + mcpServerId?: string; + mcpServerName?: string; + connectorIds?: string[]; + intent?: string; + /** The caller contributes to skill learning (stamped on the log row). */ + learnable?: boolean; + /** + * The caller's allowed tool ids in this org (null = unrestricted), as the + * controllers already resolve via RolesService. A code tool in `invoker` + * mode re-checks this before every inner call; when it is undefined for an + * identified user the code tool fails closed (denies inner calls) rather + * than guess. Plain tool calls ignore it (their role is gated upstream). + */ + allowedToolIds?: string[] | null; + /** Set on calls made from inside a code run, so a code tool cannot be + * reached from within another (no recursion). */ + inCodeRun?: boolean; + /** The OAuth client the caller's access token was issued to, if any. */ + oauthClientId?: string; +} + +/** What executeTool returns. */ +export interface ExecuteToolResult { + content: ToolResultContent; + isError?: boolean; + /** + * The result as an object, before it was serialized into `content[0].text`. + * Lets the MCP endpoint build structuredContent without re-parsing the text + * — which silently produced `{}` for any tool with a followUp hint. + */ + structured?: unknown; +} + @Injectable() export class DynamicMcpTools { private readonly logger = new Logger(DynamicMcpTools.name); @@ -210,6 +253,7 @@ export class DynamicMcpTools { // Required by Nest (no @Optional); older manually built test fixtures may omit it. @Inject(ToolRateLimitService) private readonly toolRateLimits?: ToolRateLimitService, @Optional() private readonly authStatus?: ConnectorAuthStatusService, + @Optional() private readonly workspaceLimits?: WorkspaceCallLimiter, ) { this.blockedCalls = new TrialBlockedCallRecorder(prisma, productEvents); } @@ -392,48 +436,40 @@ export class DynamicMcpTools { /** * Execute a tool by name with the given parameters. * Handles caching, audit logging, env interpolation, and engine dispatch. + * + * Every call first passes the per-workspace limits (workspace-call-limits.ts): + * counted in `dry-run`, refused only in `on`. */ async executeTool( toolName: string, params: Record, - context?: { - userId?: string; - userEmail?: string; - organizationId?: string; - authMethod?: string; - apiKeyName?: string; - /** Set when the caller used an operator's support key (support-keys.ts). */ - supportKeyId?: string; - mcpServerId?: string; - mcpServerName?: string; - connectorIds?: string[]; - intent?: string; - /** The caller contributes to skill learning (stamped on the log row). */ - learnable?: boolean; - /** - * The caller's allowed tool ids in this org (null = unrestricted), as the - * controllers already resolve via RolesService. A code tool in `invoker` - * mode re-checks this before every inner call; when it is undefined for an - * identified user the code tool fails closed (denies inner calls) rather - * than guess. Plain tool calls ignore it (their role is gated upstream). - */ - allowedToolIds?: string[] | null; - /** Set on calls made from inside a code run, so a code tool cannot be - * reached from within another (no recursion). */ - inCodeRun?: boolean; - /** The OAuth client the caller's access token was issued to, if any. */ - oauthClientId?: string; - }, - ): Promise<{ - content: ToolResultContent; - isError?: boolean; - /** - * The result as an object, before it was serialized into `content[0].text`. - * Lets the MCP endpoint build structuredContent without re-parsing the text - * — which silently produced `{}` for any tool with a followUp hint. - */ - structured?: unknown; - }> { + context?: ExecuteToolContext, + ): Promise { + const admission = this.workspaceLimits + ? await this.workspaceLimits.admit(context?.organizationId) + : null; + if (admission && !admission.allowed && admission.refusal) { + const result: { content: ToolResultContent; isError: true } = { + content: [{ type: 'text', text: JSON.stringify(admission.refusal) }], + isError: true, + }; + const tool = this.resolveTool(toolName, context); + if (tool) await this.logRateLimited(tool, params, context, admission.refusal.error, result); + return result; + } + this.workspaceLimits?.noteRepeat(context?.organizationId, toolName, params); + try { + return await this.executeToolUnlimited(toolName, params, context); + } finally { + admission?.release(); + } + } + + private async executeToolUnlimited( + toolName: string, + params: Record, + context?: ExecuteToolContext, + ): Promise { // Check license before executing tool (cloud mode only) try { await this.licenseGuard.checkLicenseActive(context?.organizationId); diff --git a/packages/backend/src/mcp-server/dynamic-mcp-tools.workspace-limits.spec.ts b/packages/backend/src/mcp-server/dynamic-mcp-tools.workspace-limits.spec.ts new file mode 100644 index 000000000..57780aed8 --- /dev/null +++ b/packages/backend/src/mcp-server/dynamic-mcp-tools.workspace-limits.spec.ts @@ -0,0 +1,55 @@ +import { DynamicMcpTools } from './dynamic-mcp-tools'; + +// executeTool is a thin wrapper: admit the call against the workspace limits, +// run it, release the slot. The tool logic itself is covered by the other +// dynamic-mcp-tools specs, so it is stubbed here. +function makeTools(admission: any) { + const tools: any = Object.create(DynamicMcpTools.prototype); + tools.workspaceLimits = { + admit: jest.fn().mockResolvedValue(admission), + noteRepeat: jest.fn(), + }; + tools.executeToolUnlimited = jest.fn().mockResolvedValue({ content: [{ type: 'text', text: '{"ok":true}' }] }); + tools.resolveTool = jest.fn().mockReturnValue({ id: 't1', name: 'x_tool' }); + tools.logRateLimited = jest.fn().mockResolvedValue(undefined); + return tools as any; +} + +describe('DynamicMcpTools.executeTool workspace limits', () => { + it('runs an admitted call and releases its slot', async () => { + const release = jest.fn(); + const tools = makeTools({ allowed: true, release }); + const res = await tools.executeTool('x_tool', { a: 1 }, { organizationId: 'org1' }); + expect(res.content[0]).toEqual({ type: 'text', text: '{"ok":true}' }); + expect(tools.workspaceLimits.admit).toHaveBeenCalledWith('org1'); + expect(tools.workspaceLimits.noteRepeat).toHaveBeenCalledWith('org1', 'x_tool', { a: 1 }); + expect(release).toHaveBeenCalledTimes(1); + }); + + it('releases the slot when the call throws', async () => { + const release = jest.fn(); + const tools = makeTools({ allowed: true, release }); + tools.executeToolUnlimited.mockRejectedValue(new Error('boom')); + await expect(tools.executeTool('x_tool', {}, { organizationId: 'org1' })).rejects.toThrow('boom'); + expect(release).toHaveBeenCalledTimes(1); + }); + + it('refuses a call over the limit without running it, and logs it', async () => { + const refusal = { error: 'Too many tool calls from this workspace', retryAfter: 30 }; + const tools = makeTools({ allowed: false, refusal, release: jest.fn() }); + const res = await tools.executeTool('x_tool', {}, { organizationId: 'org1' }); + expect(res.isError).toBe(true); + expect(JSON.parse((res.content[0] as any).text)).toEqual(refusal); + expect(tools.executeToolUnlimited).not.toHaveBeenCalled(); + expect(tools.logRateLimited).toHaveBeenCalledWith( + { id: 't1', name: 'x_tool' }, {}, { organizationId: 'org1' }, refusal.error, res, + ); + }); + + it('works without the limiter (older fixtures)', async () => { + const tools = makeTools({ allowed: true, release: jest.fn() }); + tools.workspaceLimits = undefined; + const res = await tools.executeTool('x_tool', {}, {}); + expect(res.isError).toBeUndefined(); + }); +}); diff --git a/packages/backend/src/mcp-server/mcp-server.module.ts b/packages/backend/src/mcp-server/mcp-server.module.ts index 2ea75232c..86e9f7446 100644 --- a/packages/backend/src/mcp-server/mcp-server.module.ts +++ b/packages/backend/src/mcp-server/mcp-server.module.ts @@ -3,6 +3,7 @@ import { McpServerService } from './mcp-server.service'; import { ToolRegistry } from './tool-registry'; import { DynamicMcpTools } from './dynamic-mcp-tools'; import { ToolRateLimitService } from './tool-rate-limit.service'; +import { WorkspaceCallLimiter } from './workspace-call-limits'; import { CodeExecutorService } from './code-executor.service'; import { McpEndpointController } from './mcp-endpoint.controller'; import { WellKnownOAuthController } from './well-known-oauth.controller'; @@ -47,7 +48,7 @@ const ENGINES = [ @Module({ imports: [McpServersModule, LicenseModule, SettingsModule, FileSearchCoreModule], controllers: [McpEndpointController, WellKnownOAuthController, RegistryCatchUpController], - providers: [ToolRateLimitService, SharedSetupRegistry, McpClientSeenRegistry, McpServerService, ToolRegistry, DynamicMcpTools, CodeExecutorService, McpCombinedAuthGuard, McpPrincipalRateLimitGuard, OAuth2TokenService, LoginTokenService, ConnectorAuthStatusService, BearerTokenRenewalService, ShopeeTokenService, TikTokShopTokenService, IopTokenService, SheinTokenService, UserCredentialsService, GraphqlSchemaService, WebhookEventsService, ...ENGINES], + providers: [ToolRateLimitService, WorkspaceCallLimiter, SharedSetupRegistry, McpClientSeenRegistry, McpServerService, ToolRegistry, DynamicMcpTools, CodeExecutorService, McpCombinedAuthGuard, McpPrincipalRateLimitGuard, OAuth2TokenService, LoginTokenService, ConnectorAuthStatusService, BearerTokenRenewalService, ShopeeTokenService, TikTokShopTokenService, IopTokenService, SheinTokenService, UserCredentialsService, GraphqlSchemaService, WebhookEventsService, ...ENGINES], exports: [McpServerService, ToolRegistry, SharedSetupRegistry, McpClientSeenRegistry, DynamicMcpTools, CodeExecutorService, OAuth2TokenService, LoginTokenService, ConnectorAuthStatusService, BearerTokenRenewalService, ShopeeTokenService, TikTokShopTokenService, IopTokenService, SheinTokenService, UserCredentialsService, WebhookEventsService], }) export class McpServerModule {} diff --git a/packages/backend/src/mcp-server/workspace-call-limits.spec.ts b/packages/backend/src/mcp-server/workspace-call-limits.spec.ts new file mode 100644 index 000000000..6b01facb4 --- /dev/null +++ b/packages/backend/src/mcp-server/workspace-call-limits.spec.ts @@ -0,0 +1,165 @@ +import { + WorkspaceCallLimiter, + workspaceCallLimitsForPlan, + workspaceLimitsMode, +} from './workspace-call-limits'; + +function makeLimiter(mode: string | undefined, plan: string | null = 'trial', isCloud = true) { + const prev = process.env.MCP_WORKSPACE_LIMITS; + if (mode === undefined) delete process.env.MCP_WORKSPACE_LIMITS; + else process.env.MCP_WORKSPACE_LIMITS = mode; + const licenseGuard = { codeRunPlanForOrg: jest.fn().mockResolvedValue(plan) }; + const deployment = { isCloud: () => isCloud }; + const limiter = new WorkspaceCallLimiter(licenseGuard as any, deployment as any); + if (prev === undefined) delete process.env.MCP_WORKSPACE_LIMITS; + else process.env.MCP_WORKSPACE_LIMITS = prev; + return { limiter, licenseGuard }; +} + +// 12:00:00.000 UTC on a fixed day: minute and hour windows start here. +const T0 = Date.UTC(2026, 11, 5, 12, 0, 0, 0); + +describe('workspaceLimitsMode', () => { + it('defaults to dry-run on Cloud and off on self-hosted', () => { + expect(workspaceLimitsMode({}, true)).toBe('dry-run'); + expect(workspaceLimitsMode({}, false)).toBe('off'); + }); + + it('accepts off, dry-run and on, and ignores anything else', () => { + expect(workspaceLimitsMode({ MCP_WORKSPACE_LIMITS: 'on' }, false)).toBe('on'); + expect(workspaceLimitsMode({ MCP_WORKSPACE_LIMITS: ' OFF ' }, true)).toBe('off'); + expect(workspaceLimitsMode({ MCP_WORKSPACE_LIMITS: 'dry-run' }, false)).toBe('dry-run'); + expect(workspaceLimitsMode({ MCP_WORKSPACE_LIMITS: 'yes' }, true)).toBe('dry-run'); + }); +}); + +describe('workspaceCallLimitsForPlan', () => { + it('limits trial, starter, team and business; not enterprise or no licence', () => { + expect(workspaceCallLimitsForPlan('trial')).toEqual({ perMinute: 120, perHour: 1000, concurrent: 10 }); + expect(workspaceCallLimitsForPlan('team')?.perHour).toBe(5000); + expect(workspaceCallLimitsForPlan('enterprise')).toBeNull(); + expect(workspaceCallLimitsForPlan('community')).toBeNull(); + expect(workspaceCallLimitsForPlan(null)).toBeNull(); + }); +}); + +describe('WorkspaceCallLimiter', () => { + it('counts nothing when off', async () => { + const { limiter, licenseGuard } = makeLimiter('off'); + const a = await limiter.admit('org1', T0); + expect(a.allowed).toBe(true); + expect(licenseGuard.codeRunPlanForOrg).not.toHaveBeenCalled(); + expect(limiter.stateOf('org1')).toBeUndefined(); + }); + + it('lets calls without a workspace through', async () => { + const { limiter } = makeLimiter('on'); + expect((await limiter.admit(undefined, T0)).allowed).toBe(true); + }); + + it('never refuses in dry-run, but counts and logs once per window', async () => { + const { limiter } = makeLimiter('dry-run'); + const warn = jest.spyOn((limiter as any).logger, 'warn').mockImplementation(() => undefined); + for (let i = 0; i < 130; i++) { + const a = await limiter.admit('org1', T0 + i); + expect(a.allowed).toBe(true); + a.release(); + } + expect(limiter.stateOf('org1')?.minute).toBe(130); + expect(warn).toHaveBeenCalledTimes(1); + expect(warn.mock.calls[0][0]).toContain('[workspace limits dry-run] org …org1 (trial): more than 120 tool calls in a minute'); + + // The next minute reports how many would have been refused. + await limiter.admit('org1', T0 + 60_000); + expect(warn.mock.calls[1][0]).toContain('would have refused 10 calls over the per-minute limit'); + }); + + it('refuses over the per-minute limit when on, without using quota, and resets next minute', async () => { + const { limiter } = makeLimiter('on'); + jest.spyOn((limiter as any).logger, 'warn').mockImplementation(() => undefined); + for (let i = 0; i < 120; i++) (await limiter.admit('org1', T0 + i)).release(); + const refused = await limiter.admit('org1', T0 + 30_000); + expect(refused.allowed).toBe(false); + expect(refused.refusal?.retryAfter).toBe(30); + expect(refused.refusal?.error).toContain('more than 120 tool calls in a minute on the trial plan'); + expect(limiter.stateOf('org1')?.minute).toBe(120); + + expect((await limiter.admit('org1', T0 + 60_000)).allowed).toBe(true); + }); + + it('refuses over the per-hour limit when on', async () => { + const { limiter } = makeLimiter('on'); + jest.spyOn((limiter as any).logger, 'warn').mockImplementation(() => undefined); + // 100 calls a minute stays under the minute limit; 10 minutes reach 1,000. + for (let m = 0; m < 10; m++) { + for (let i = 0; i < 100; i++) (await limiter.admit('org1', T0 + m * 60_000 + i)).release(); + } + const refused = await limiter.admit('org1', T0 + 10 * 60_000); + expect(refused.allowed).toBe(false); + expect(refused.refusal?.retryAfter).toBe(50 * 60); + expect((await limiter.admit('org1', T0 + 3_600_000)).allowed).toBe(true); + }); + + it('limits calls running at once and frees a slot on release, once', async () => { + const { limiter } = makeLimiter('on'); + jest.spyOn((limiter as any).logger, 'warn').mockImplementation(() => undefined); + const running = []; + for (let i = 0; i < 10; i++) running.push(await limiter.admit('org1', T0 + i)); + const refused = await limiter.admit('org1', T0 + 20); + expect(refused.allowed).toBe(false); + expect(refused.refusal?.error).toContain('more than 10 tool calls running at once'); + + running[0].release(); + running[0].release(); + expect(limiter.stateOf('org1')?.inflight).toBe(9); + expect((await limiter.admit('org1', T0 + 30)).allowed).toBe(true); + }); + + it('keeps workspaces apart', async () => { + const { limiter } = makeLimiter('on'); + jest.spyOn((limiter as any).logger, 'warn').mockImplementation(() => undefined); + for (let i = 0; i < 120; i++) (await limiter.admit('org1', T0 + i)).release(); + expect((await limiter.admit('org1', T0 + 200)).allowed).toBe(false); + expect((await limiter.admit('org2', T0 + 200)).allowed).toBe(true); + }); + + it('does not limit enterprise or workspaces without a licence', async () => { + for (const plan of ['enterprise', 'community', null]) { + const { limiter } = makeLimiter('on', plan); + for (let i = 0; i < 200; i++) expect((await limiter.admit('org1', T0 + i)).allowed).toBe(true); + } + }); + + it('lets the call through when the plan lookup fails, and asks again next time', async () => { + const { limiter, licenseGuard } = makeLimiter('on'); + jest.spyOn((limiter as any).logger, 'warn').mockImplementation(() => undefined); + licenseGuard.codeRunPlanForOrg.mockRejectedValueOnce(new Error('db down')); + expect((await limiter.admit('org1', T0)).allowed).toBe(true); + expect((await limiter.admit('org1', T0 + 1)).allowed).toBe(true); + expect(licenseGuard.codeRunPlanForOrg).toHaveBeenCalledTimes(2); + }); + + it('caches the plan for a minute', async () => { + const { limiter, licenseGuard } = makeLimiter('dry-run'); + await limiter.admit('org1', T0); + await limiter.admit('org1', T0 + 59_000); + expect(licenseGuard.codeRunPlanForOrg).toHaveBeenCalledTimes(1); + await limiter.admit('org1', T0 + 61_000); + expect(licenseGuard.codeRunPlanForOrg).toHaveBeenCalledTimes(2); + }); + + it('logs identical calls within 10 s once an hour', () => { + const { limiter } = makeLimiter('dry-run'); + const log = jest.spyOn((limiter as any).logger, 'log').mockImplementation(() => undefined); + limiter.noteRepeat('org1', 'deribit_ticker', { instrument: 'BTC' }, T0); + limiter.noteRepeat('org1', 'deribit_ticker', { instrument: 'BTC' }, T0 + 5_000); + limiter.noteRepeat('org1', 'deribit_ticker', { instrument: 'ETH' }, T0 + 6_000); + limiter.noteRepeat('org2', 'deribit_ticker', { instrument: 'BTC' }, T0 + 7_000); + limiter.noteRepeat('org1', 'deribit_ticker', { instrument: 'BTC' }, T0 + 30_000); + expect(log).not.toHaveBeenCalled(); + limiter.noteRepeat('org1', 'x', {}, T0 + 3_600_000); + expect(log).toHaveBeenCalledWith( + '[workspace limits] repeats in the last hour: 1 of 5 tool calls repeated the same tool and arguments within 10 s (top: deribit_ticker=1)', + ); + }); +}); diff --git a/packages/backend/src/mcp-server/workspace-call-limits.ts b/packages/backend/src/mcp-server/workspace-call-limits.ts new file mode 100644 index 000000000..ffc85fe6f --- /dev/null +++ b/packages/backend/src/mcp-server/workspace-call-limits.ts @@ -0,0 +1,311 @@ +import { createHash } from 'node:crypto'; +import { Injectable, Logger, Optional } from '@nestjs/common'; +import { DeploymentService } from '../common/deployment.service'; +import { LicenseGuardService } from '../license/license-guard.service'; + +/** + * Per-workspace limits on tool calls (Cloud). + * + * The existing limits do not stop one workspace from loading the shared + * backend for hours: McpPrincipalRateLimitGuard allows 1,000 MCP requests a + * minute per caller, and per-tool limits exist only where an admin set them on + * a role. On 2026-12-05 one trial workspace made 25,000 calls in a day, more + * than 4,000 in some hours, and the backend was slowest in exactly those hours. + * + * Three limits per workspace, by plan (workspaceCallLimitsForPlan): + * - calls per minute: bursts (agents in a loop); + * - calls per hour: sustained polling; + * - calls running at the same time: one workspace holding many slow calls. + * + * Modes (MCP_WORKSPACE_LIMITS): + * - `off`: nothing is counted. + * - `dry-run`: counted and logged ("[workspace limits dry-run] ..."), never + * refused. The default on Cloud, so the limits can be checked against real + * traffic before anyone is refused. + * - `on`: a call over a limit is refused with a tool error that says when to + * retry. A refused call uses no quota. + * Self-hosted defaults to `off`: it has no plans, and one tenant. + * + * Counters live in this process, not in Redis: no network round trip is added + * to every tool call, and Cloud runs one backend process (blue/green overlaps + * for a few minutes per release, which can let a workspace briefly use the + * budget twice). If the backend is ever scaled out, move them to Redis. + * Anything unexpected (no plan, an error) lets the call through. + */ + +export type WorkspaceLimitsMode = 'off' | 'dry-run' | 'on'; + +export function workspaceLimitsMode( + env: NodeJS.ProcessEnv = process.env, + isCloud = false, +): WorkspaceLimitsMode { + const raw = (env.MCP_WORKSPACE_LIMITS ?? '').trim().toLowerCase(); + if (raw === 'off' || raw === 'dry-run' || raw === 'on') return raw; + return isCloud ? 'dry-run' : 'off'; +} + +export interface WorkspaceCallLimits { + perMinute: number; + perHour: number; + concurrent: number; +} + +/** + * Limits by the plan LicenseGuardService.codeRunPlanForOrg returns: `trial` is + * a trial without a card, a card trial counts as `team`. Set from the peaks of + * 2026-11-28 to 12-05: per minute only a few trial bursts went over, per hour a + * handful of workspaces (most of them the polling this is for). Enterprise, + * `community` (no licence) and unknown plans have no limit. + */ +const LIMITS: Record = { + trial: { perMinute: 120, perHour: 1_000, concurrent: 10 }, + starter: { perMinute: 240, perHour: 2_000, concurrent: 15 }, + team: { perMinute: 480, perHour: 5_000, concurrent: 30 }, + business: { perMinute: 1_000, perHour: 15_000, concurrent: 60 }, +}; + +export function workspaceCallLimitsForPlan(plan: string | null | undefined): WorkspaceCallLimits | null { + if (!plan) return null; + return LIMITS[plan] ?? null; +} + +export interface WorkspaceAdmission { + allowed: boolean; + /** Set when refused (mode `on` only): the tool error body. */ + refusal?: { error: string; retryAfter: number }; + /** Call when the tool call ends. Safe to call more than once. */ + release: () => void; +} + +type LimitKind = 'minute' | 'hour' | 'concurrent'; + +interface WorkspaceState { + minuteStart: number; + minute: number; + hourStart: number; + hour: number; + inflight: number; + /** Calls that would have been refused in the current window (dry-run). */ + overMinute: number; + overHour: number; + overConcurrent: number; + plan: string; +} + +const MINUTE = 60_000; +const HOUR = 3_600_000; +const PLAN_TTL_MS = 60_000; +const MAX_WORKSPACES = 20_000; +const REPEAT_WINDOW_MS = 10_000; +const MAX_REPEAT_KEYS = 50_000; +const NOOP = () => {}; + +@Injectable() +export class WorkspaceCallLimiter { + private readonly logger = new Logger(WorkspaceCallLimiter.name); + readonly mode: WorkspaceLimitsMode; + private readonly plans = new Map; expiresAt: number }>(); + private readonly states = new Map(); + + // Identical calls (same workspace, tool and arguments) within 10 s: logged + // once an hour, to size a default response cache for repeated reads. + private readonly lastSeen = new Map(); + private repeatHourStart = 0; + private repeatCalls = 0; + private repeatHits = 0; + private readonly repeatByTool = new Map(); + + constructor( + private readonly licenseGuard: LicenseGuardService, + @Optional() deployment?: DeploymentService, + ) { + this.mode = workspaceLimitsMode(process.env, deployment?.isCloud() ?? false); + if (this.mode !== 'off') this.logger.log(`Workspace tool-call limits: ${this.mode}`); + } + + /** Admit one tool call for a workspace. Never throws. */ + async admit(organizationId: string | undefined, now = Date.now()): Promise { + if (this.mode === 'off' || !organizationId) return { allowed: true, release: NOOP }; + let plan: string | null; + try { + plan = await this.planFor(organizationId, now); + } catch (e) { + this.logger.warn(`workspace limits: plan lookup failed: ${(e as Error)?.message ?? e}`); + return { allowed: true, release: NOOP }; + } + const limits = workspaceCallLimitsForPlan(plan); + if (!plan || !limits) return { allowed: true, release: NOOP }; + + const st = this.stateFor(organizationId, plan, now); + const over: LimitKind | null = + st.inflight >= limits.concurrent ? 'concurrent' + : st.minute >= limits.perMinute ? 'minute' + : st.hour >= limits.perHour ? 'hour' + : null; + + if (over) { + const first = this.countOver(st, over) === 1; + if (first) this.warnOver(organizationId, plan, over, limits); + if (this.mode === 'on') { + return { allowed: false, refusal: this.refusal(over, limits, st, now), release: NOOP }; + } + } + + st.minute += 1; + st.hour += 1; + st.inflight += 1; + let released = false; + return { + allowed: true, + release: () => { + if (released) return; + released = true; + st.inflight = Math.max(0, st.inflight - 1); + }, + }; + } + + /** Count an identical call within 10 s (statistics only). Never throws. */ + noteRepeat(organizationId: string | undefined, toolName: string, params: unknown, now = Date.now()): void { + if (this.mode === 'off' || !organizationId) return; + try { + this.rollRepeatHour(now); + const hash = createHash('sha1').update(JSON.stringify(params ?? null)).digest('base64url'); + const key = `${organizationId}\u0000${toolName}\u0000${hash}`; + const last = this.lastSeen.get(key); + this.repeatCalls += 1; + if (last !== undefined && now - last <= REPEAT_WINDOW_MS) { + this.repeatHits += 1; + this.repeatByTool.set(toolName, (this.repeatByTool.get(toolName) ?? 0) + 1); + } + if (this.lastSeen.size >= MAX_REPEAT_KEYS) this.lastSeen.clear(); + this.lastSeen.set(key, now); + } catch { + // Statistics must never affect a call. + } + } + + /** Test hook: the state of one workspace. */ + stateOf(organizationId: string): Readonly | undefined { + return this.states.get(organizationId); + } + + private planFor(organizationId: string, now: number): Promise { + const cached = this.plans.get(organizationId); + if (cached && cached.expiresAt > now) return cached.plan; + if (this.plans.size >= MAX_WORKSPACES) this.plans.clear(); + const plan = this.licenseGuard.codeRunPlanForOrg(organizationId).catch((e) => { + // Do not cache a failure: drop it so the next call asks again. + this.plans.delete(organizationId); + throw e; + }); + this.plans.set(organizationId, { plan, expiresAt: now + PLAN_TTL_MS }); + return plan; + } + + private stateFor(organizationId: string, plan: string, now: number): WorkspaceState { + const minuteStart = now - (now % MINUTE); + const hourStart = now - (now % HOUR); + let st = this.states.get(organizationId); + if (!st) { + if (this.states.size >= MAX_WORKSPACES) this.prune(hourStart); + st = { + minuteStart, minute: 0, hourStart, hour: 0, inflight: 0, + overMinute: 0, overHour: 0, overConcurrent: 0, plan, + }; + this.states.set(organizationId, st); + return st; + } + st.plan = plan; + if (st.minuteStart !== minuteStart) { + this.reportWindow(organizationId, st, 'minute'); + st.minuteStart = minuteStart; + st.minute = 0; + st.overMinute = 0; + // Concurrency refusals are reported per minute too. + this.reportWindow(organizationId, st, 'concurrent'); + st.overConcurrent = 0; + } + if (st.hourStart !== hourStart) { + this.reportWindow(organizationId, st, 'hour'); + st.hourStart = hourStart; + st.hour = 0; + st.overHour = 0; + } + return st; + } + + /** Drop idle workspaces from earlier hours; keep any with calls running. */ + private prune(hourStart: number): void { + for (const [org, st] of this.states) { + if (st.inflight === 0 && st.hourStart < hourStart) this.states.delete(org); + } + } + + private countOver(st: WorkspaceState, kind: LimitKind): number { + if (kind === 'minute') return ++st.overMinute; + if (kind === 'hour') return ++st.overHour; + return ++st.overConcurrent; + } + + private label(organizationId: string): string { + return `org …${organizationId.slice(-6)}`; + } + + private describe(kind: LimitKind, limits: WorkspaceCallLimits): string { + if (kind === 'minute') return `more than ${limits.perMinute} tool calls in a minute`; + if (kind === 'hour') return `more than ${limits.perHour} tool calls in an hour`; + return `more than ${limits.concurrent} tool calls running at once`; + } + + private warnOver(organizationId: string, plan: string, kind: LimitKind, limits: WorkspaceCallLimits): void { + const prefix = this.mode === 'on' ? '[workspace limits]' : '[workspace limits dry-run]'; + this.logger.warn(`${prefix} ${this.label(organizationId)} (${plan}): ${this.describe(kind, limits)}`); + } + + /** When a window closes, say how many calls went over its limit. */ + private reportWindow(organizationId: string, st: WorkspaceState, kind: LimitKind): void { + const n = kind === 'minute' ? st.overMinute : kind === 'hour' ? st.overHour : st.overConcurrent; + if (n === 0) return; + const verb = this.mode === 'on' ? 'refused' : 'would have refused'; + const window = kind === 'hour' ? 'hour' : 'minute'; + const what = kind === 'concurrent' ? 'calls over the concurrency limit' : `calls over the per-${window} limit`; + this.logger.warn( + `[workspace limits${this.mode === 'on' ? '' : ' dry-run'}] ${this.label(organizationId)} (${st.plan}): ` + + `${verb} ${n} ${what} in the ${window} that just ended`, + ); + } + + private refusal(kind: LimitKind, limits: WorkspaceCallLimits, st: WorkspaceState, now: number) { + const retryAfter = + kind === 'minute' ? Math.max(1, Math.ceil((st.minuteStart + MINUTE - now) / 1000)) + : kind === 'hour' ? Math.max(1, Math.ceil((st.hourStart + HOUR - now) / 1000)) + : 2; + return { + error: + `Too many tool calls from this workspace: ${this.describe(kind, limits)} on the ${st.plan} plan. ` + + `Retry in ${retryAfter} s. If you read the same data repeatedly, reuse the earlier result instead of calling again.`, + retryAfter, + }; + } + + private rollRepeatHour(now: number): void { + const hourStart = now - (now % HOUR); + if (hourStart === this.repeatHourStart) return; + if (this.repeatCalls > 0) { + const top = [...this.repeatByTool.entries()] + .sort((a, b) => b[1] - a[1]) + .slice(0, 5) + .map(([t, n]) => `${t}=${n}`) + .join(', '); + this.logger.log( + `[workspace limits] repeats in the last hour: ${this.repeatHits} of ${this.repeatCalls} tool calls ` + + `repeated the same tool and arguments within ${REPEAT_WINDOW_MS / 1000} s` + (top ? ` (top: ${top})` : ''), + ); + } + this.repeatHourStart = hourStart; + this.repeatCalls = 0; + this.repeatHits = 0; + this.repeatByTool.clear(); + } +} From bd61cc1b11e05fbac5ffab3f35db8afc93996a5a Mon Sep 17 00:00:00 2001 From: "helpcode.ai" Date: Sat, 5 Dec 2026 21:35:24 +0100 Subject: [PATCH 2/2] Skip repeat statistics for large tool arguments --- .../backend/src/mcp-server/workspace-call-limits.spec.ts | 5 ++++- packages/backend/src/mcp-server/workspace-call-limits.ts | 8 ++++++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/packages/backend/src/mcp-server/workspace-call-limits.spec.ts b/packages/backend/src/mcp-server/workspace-call-limits.spec.ts index 6b01facb4..3f75763e5 100644 --- a/packages/backend/src/mcp-server/workspace-call-limits.spec.ts +++ b/packages/backend/src/mcp-server/workspace-call-limits.spec.ts @@ -157,9 +157,12 @@ describe('WorkspaceCallLimiter', () => { limiter.noteRepeat('org2', 'deribit_ticker', { instrument: 'BTC' }, T0 + 7_000); limiter.noteRepeat('org1', 'deribit_ticker', { instrument: 'BTC' }, T0 + 30_000); expect(log).not.toHaveBeenCalled(); + // Large arguments count as calls but are not compared. + limiter.noteRepeat('org1', 'upload', { file: 'x'.repeat(30_000) }, T0 + 40_000); + limiter.noteRepeat('org1', 'upload', { file: 'x'.repeat(30_000) }, T0 + 41_000); limiter.noteRepeat('org1', 'x', {}, T0 + 3_600_000); expect(log).toHaveBeenCalledWith( - '[workspace limits] repeats in the last hour: 1 of 5 tool calls repeated the same tool and arguments within 10 s (top: deribit_ticker=1)', + '[workspace limits] repeats in the last hour: 1 of 7 tool calls repeated the same tool and arguments within 10 s (top: deribit_ticker=1)', ); }); }); diff --git a/packages/backend/src/mcp-server/workspace-call-limits.ts b/packages/backend/src/mcp-server/workspace-call-limits.ts index ffc85fe6f..f4843ceb8 100644 --- a/packages/backend/src/mcp-server/workspace-call-limits.ts +++ b/packages/backend/src/mcp-server/workspace-call-limits.ts @@ -98,6 +98,7 @@ const PLAN_TTL_MS = 60_000; const MAX_WORKSPACES = 20_000; const REPEAT_WINDOW_MS = 10_000; const MAX_REPEAT_KEYS = 50_000; +const MAX_REPEAT_ARGS_CHARS = 20_000; const NOOP = () => {}; @Injectable() @@ -170,10 +171,13 @@ export class WorkspaceCallLimiter { if (this.mode === 'off' || !organizationId) return; try { this.rollRepeatHour(now); - const hash = createHash('sha1').update(JSON.stringify(params ?? null)).digest('base64url'); + this.repeatCalls += 1; + const args = JSON.stringify(params ?? null); + // Large arguments (file contents) are never repeated reads worth caching. + if (args.length > MAX_REPEAT_ARGS_CHARS) return; + const hash = createHash('sha1').update(args).digest('base64url'); const key = `${organizationId}\u0000${toolName}\u0000${hash}`; const last = this.lastSeen.get(key); - this.repeatCalls += 1; if (last !== undefined && now - last <= REPEAT_WINDOW_MS) { this.repeatHits += 1; this.repeatByTool.set(toolName, (this.repeatByTool.get(toolName) ?? 0) + 1);