Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions docker-compose.cloud.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:-}
Expand Down
1 change: 1 addition & 0 deletions docs/deployment.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<serverId>`). `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 |
Expand Down
1 change: 1 addition & 0 deletions llms-full.txt

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

112 changes: 74 additions & 38 deletions packages/backend/src/mcp-server/dynamic-mcp-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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<string, unknown>,
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<ExecuteToolResult> {
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<string, unknown>,
context?: ExecuteToolContext,
): Promise<ExecuteToolResult> {
// Check license before executing tool (cloud mode only)
try {
await this.licenseGuard.checkLicenseActive(context?.organizationId);
Expand Down
Original file line number Diff line number Diff line change
@@ -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();
});
});
3 changes: 2 additions & 1 deletion packages/backend/src/mcp-server/mcp-server.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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 {}
Loading
Loading