Skip to content

Commit 292c7ef

Browse files
committed
fix(mcp): count per-tool rate limits per user, not per API key (#983)
Any member can create MCP API keys, so a budget per key name let a limited user multiply it by creating more keys. The counter is now keyed on workspace, tool and user, shared by sessions and all API keys.
1 parent fdb9884 commit 292c7ef

5 files changed

Lines changed: 18 additions & 21 deletions

File tree

‎docs/api-reference.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -444,8 +444,8 @@ grant deletes its policy. System roles cannot be modified. Configuration is
444444
restricted to grants and tools in the administrator's workspace.
445445

446446
Limits are **per principal and tool within a workspace**, shared across MCP
447-
servers: a user session has its own budget, and each user/API-key name has its
448-
own budget, using the same identity as the principal limiter. They are not
447+
servers. Each user has one budget per tool, shared by their sessions and all of
448+
their API keys, so creating another key does not raise it. Limits are not
449449
shared by every member of a role. Nested Code Mode `amcp.run` calls use the
450450
same budget as direct calls. A saved code tool can also have its own limit.
451451

‎llms-full.txt‎

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎packages/backend/src/mcp-server/tool-rate-limit.service.spec.ts‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -43,28 +43,29 @@ describe('per-tool rate-limit admission', () => {
4343
expect(results.filter((value) => value === null)).toHaveLength(2);
4444
});
4545

46-
it('isolates organizations, tools, users and API-key names', async () => {
46+
it('isolates organizations, tools and users', async () => {
4747
const { service, roles } = build();
4848
roles.getToolRateLimits.mockResolvedValue({ callsPerMinute: 1, callsPerHour: null });
4949
await service.check(tool, context);
5050
expect(await service.check(tool, context)).not.toBeNull();
5151
for (const other of [
5252
{ ...context, organizationId: 'other-org' },
5353
{ ...context, userId: 'other-user' },
54-
{ ...context, authMethod: 'mcp_api_key', apiKeyName: 'agent-a' },
55-
{ ...context, authMethod: 'mcp_api_key', apiKeyName: 'agent-b' },
5654
]) {
5755
expect(await service.check(tool, other)).toBeNull();
5856
expect(await service.check(tool, other)).not.toBeNull();
5957
}
6058
expect(await service.check({ ...tool, id: 'other-tool' }, context)).toBeNull();
6159
});
6260

63-
it('uses the same 80-character API-key name bucket as the principal guard', async () => {
61+
it('gives a user one budget across sessions and all of their API keys', async () => {
6462
const { service, roles } = build();
65-
roles.getToolRateLimits.mockResolvedValue({ callsPerMinute: 1, callsPerHour: null });
66-
await service.check(tool, { ...context, authMethod: 'mcp_api_key', apiKeyName: 'a'.repeat(80) + 'x' });
67-
expect(await service.check(tool, { ...context, authMethod: 'mcp_api_key', apiKeyName: 'a'.repeat(80) + 'y' })).not.toBeNull();
63+
roles.getToolRateLimits.mockResolvedValue({ callsPerMinute: 3, callsPerHour: null });
64+
expect(await service.check(tool, { ...context, authMethod: 'jwt' })).toBeNull();
65+
expect(await service.check(tool, { ...context, authMethod: 'mcp_api_key', apiKeyName: 'agent-a' })).toBeNull();
66+
expect(await service.check(tool, { ...context, authMethod: 'mcp_api_key', apiKeyName: 'agent-b' })).toBeNull();
67+
// A new key does not bring a new budget.
68+
expect(await service.check(tool, { ...context, authMethod: 'mcp_api_key', apiKeyName: 'agent-c' })).not.toBeNull();
6869
});
6970

7071
it('does not count unrestricted callers, operator calls, or unlimited grants', async () => {

‎packages/backend/src/mcp-server/tool-rate-limit.service.ts‎

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import { Injectable, Logger } from '@nestjs/common';
22
import { RedisService } from '../common/redis.service';
3-
import { McpPrincipalRateLimitGuard } from '../auth/mcp-principal-rate-limit.guard';
43
import { RolesService, type ToolRateLimits } from '../roles/roles.service';
54

65
export interface ToolRateLimitContext {
@@ -60,14 +59,11 @@ export class ToolRateLimitService {
6059
const limits = await this.roles.getToolRateLimits(context.userId, context.organizationId, tool.id);
6160
if (!limits || (limits.callsPerMinute === null && limits.callsPerHour === null)) return null;
6261

63-
// Use precisely the principal guard's identity, including its key-name
64-
// truncation. Encode the whole tuple to avoid delimiter/hash-slot collisions.
65-
// These are IDs and key labels, never authentication key values; this is
66-
// a counter identifier, not credential storage. Never log the identifier.
67-
const bucket = McpPrincipalRateLimitGuard.bucketFor({
68-
user: { sub: context.userId, authMethod: context.authMethod, apiKeyName: context.apiKeyName },
69-
});
70-
const key = Buffer.from(JSON.stringify([context.organizationId, tool.id, bucket]), 'utf8').toString('base64url');
62+
// One budget per user, tool and workspace, whatever key, session or
63+
// client the call arrives with. Keying on the API-key name let a limited
64+
// member multiply the budget by creating more keys (any member can).
65+
// Encode the tuple to avoid delimiter and hash-slot collisions.
66+
const key = Buffer.from(JSON.stringify([context.organizationId, tool.id, context.userId]), 'utf8').toString('base64url');
7167

7268
if (this.redis.isConfigured) {
7369
if (!this.redis.isConnected) {

‎packages/backend/src/roles/roles.controller.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,7 @@ export class RolesController {
207207
@Put(':id/tools/:toolId/rate-limit')
208208
@ApiOperation({
209209
summary: 'Set rate limits on an existing role/tool grant (ADMIN)',
210-
description: 'Positive integer calls per minute/hour, per user or user/API-key name. Null clears a window; omitted fields are preserved. Across granting roles each window uses its highest value, with null meaning unlimited. System roles cannot be modified.',
210+
description: 'Positive integer calls per minute/hour, per user, shared across their sessions and API keys. Null clears a window; omitted fields are preserved. Across granting roles each window uses its highest value, with null meaning unlimited. System roles cannot be modified.',
211211
})
212212
@ApiBody({ type: SetToolRateLimitsDto })
213213
async setToolRateLimits(

0 commit comments

Comments
 (0)