Skip to content

The open alternative to Salesforce, designed for AI.

Gate @DefineTool tools with their own permission flags and serve the catalog from one method (#28416)

Paul Rastoin2428fe43165c
diff --git a/packages/twenty-server/src/engine/api/mcp/services/mcp-protocol.service.ts b/packages/twenty-server/src/engine/api/mcp/services/mcp-protocol.service.ts
index 54a086c9695..d02ae59a0e9 100644
--- a/packages/twenty-server/src/engine/api/mcp/services/mcp-protocol.service.ts
+++ b/packages/twenty-server/src/engine/api/mcp/services/mcp-protocol.service.ts
@@ -533,10 +533,10 @@ export class McpProtocolService {
return Sentry.startSpan(
{ name: 'mcp list registry tools', op: 'mcp.tools', onlyIfParent: true },
async () => {
- const descriptors = await this.toolRegistry.getDescriptorsByCategories(
- toolContext,
- { excludeTools: [...MCP_EXCLUDED_TOOL_NAMES] },
- );
+ const descriptors = await this.toolRegistry.getCatalog(toolContext, {
+ excludeTools: MCP_EXCLUDED_TOOL_NAMES,
+ includeSchemas: true,
+ });
const registryTools = this.toolRegistry.hydrateToolSet(
descriptors,
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/decorators/__tests__/define-tool.decorator.spec.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/decorators/__tests__/define-tool.decorator.spec.ts
index 066974d62e5..cc0c4201331 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/decorators/__tests__/define-tool.decorator.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/decorators/__tests__/define-tool.decorator.spec.ts
@@ -1,6 +1,7 @@
import { INJECTABLE_WATERMARK } from '@nestjs/common/constants';
import { ToolCategory } from 'twenty-shared/ai';
+import { PermissionFlagType } from 'twenty-shared/constants';
import { z } from 'zod';
import { DEFINE_TOOL_METADATA_KEY } from 'src/engine/core-modules/tool-provider/constants/define-tool-metadata-key.constant';
@@ -14,6 +15,7 @@ const RENAME_WEBHOOK_OPTIONS = {
name: 'rename_webhook',
category: ToolCategory.WEBHOOK,
description: 'Rename a webhook.',
+ requiredPermissionFlags: [PermissionFlagType.API_KEYS_AND_WEBHOOKS],
};
describe('DefineTool', () => {
@@ -36,6 +38,22 @@ describe('DefineTool', () => {
});
it('should only compile tools that follow the BaseTool contract', () => {
+ // @ts-expect-error every tool states its permission flags, an empty array when it needs none
+ @DefineTool({
+ name: 'rename_webhook',
+ category: ToolCategory.WEBHOOK,
+ description: 'Rename a webhook.',
+ })
+ class ToolWithoutPermissionFlag extends BaseTool<
+ typeof renameWebhookInputSchema
+ > {
+ readonly inputSchema = renameWebhookInputSchema;
+
+ async execute(): Promise<ToolOutput> {
+ return { success: true, message: 'Done' };
+ }
+ }
+
// @ts-expect-error DefineTool only decorates classes extending BaseTool
@DefineTool(RENAME_WEBHOOK_OPTIONS)
class NotATool {}
@@ -88,12 +106,13 @@ describe('DefineTool', () => {
}
expect([
+ ToolWithoutPermissionFlag,
NotATool,
LookAlikeTool,
ToolWithNarrowedInput,
ToolWithoutExecute,
ToolWithMismatchedInput,
ToolWithScalarInput,
- ]).toHaveLength(6);
+ ]).toHaveLength(7);
});
});
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/interfaces/tool-retrieval-options.type.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/interfaces/tool-retrieval-options.type.ts
index 65e205093fa..9a93eb35c77 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/interfaces/tool-retrieval-options.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/interfaces/tool-retrieval-options.type.ts
@@ -1,8 +1,6 @@
-import { type ToolCategory } from 'twenty-shared/ai';
+import { type ToolCatalogOptions } from 'src/engine/core-modules/tool-provider/types/tool-catalog-options.type';
-export type ToolRetrievalOptions = {
- categories?: ToolCategory[];
- excludeTools?: string[];
+export type ToolRetrievalOptions = ToolCatalogOptions & {
// Apply output compaction (strip nulls/empty values) to dispatch results
// before returning. Chat enables this to reduce token usage in the
// conversation context; MCP and workflow agents leave raw output intact.
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/services/__tests__/defined-tool-registry.service.spec.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/services/__tests__/defined-tool-registry.service.spec.ts
new file mode 100644
index 00000000000..04f49bb1fc6
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/services/__tests__/defined-tool-registry.service.spec.ts
@@ -0,0 +1,99 @@
+import { type DiscoveryService } from '@nestjs/core';
+
+import { ToolCategory } from 'twenty-shared/ai';
+import { PermissionFlagType } from 'twenty-shared/constants';
+import { z } from 'zod';
+
+import { DefineTool } from 'src/engine/core-modules/tool-provider/decorators/define-tool.decorator';
+import { BaseTool } from 'src/engine/core-modules/tool-provider/interfaces/base-tool.interface';
+import { type ToolProviderContext } from 'src/engine/core-modules/tool-provider/interfaces/tool-provider-context.type';
+import { DefinedToolRegistryService } from 'src/engine/core-modules/tool-provider/services/defined-tool-registry.service';
+import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';
+import { type PermissionsService } from 'src/engine/metadata-modules/permissions/permissions.service';
+import { jestExpectToBeDefined } from 'test/utils/jest-expect-to-be-defined.util.test';
+
+const webhookId = '2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e';
+
+const context: ToolProviderContext = {
+ workspaceId: 'workspace-id',
+ rolePermissionConfig: {
+ intersectionOf: { userWorkspaceRoleId: 'member-role-id' },
+ },
+};
+
+const renameWebhookInputSchema = z.object({ id: z.uuid() });
+
+@DefineTool({
+ name: 'rename_webhook',
+ category: ToolCategory.WEBHOOK,
+ description: 'Rename a webhook.',
+ requiredPermissionFlags: [PermissionFlagType.API_KEYS_AND_WEBHOOKS],
+})
+class RenameWebhookTool extends BaseTool<typeof renameWebhookInputSchema> {
+ readonly inputSchema = renameWebhookInputSchema;
+
+ async execute(
+ input: z.infer<typeof renameWebhookInputSchema>,
+ ): Promise<ToolOutput> {
+ return { success: true, message: `Webhook ${input.id} renamed` };
+ }
+}
+
+const buildRenameWebhookTool = ({ isGranted }: { isGranted: boolean }) => {
+ const tool = new RenameWebhookTool();
+ const definedToolRegistryService = new DefinedToolRegistryService(
+ {
+ getProviders: () => [{ instance: tool, metatype: RenameWebhookTool }],
+ } as unknown as DiscoveryService,
+ {
+ checkRolesPermissions: jest.fn().mockResolvedValue(isGranted),
+ } as unknown as PermissionsService,
+ );
+
+ definedToolRegistryService.onModuleInit();
+
+ const definedTool =
+ definedToolRegistryService.findDefinedTool('rename_webhook');
+
+ jestExpectToBeDefined(definedTool);
+
+ return { definedToolRegistryService, definedTool, tool };
+};
+
+describe('DefinedToolRegistryService', () => {
+ describe('execute', () => {
+ it('should run the tool with its parsed input when every flag is granted', async () => {
+ const { definedToolRegistryService, definedTool } =
+ buildRenameWebhookTool({ isGranted: true });
+
+ const output = await definedToolRegistryService.execute(
+ definedTool,
+ { id: webhookId },
+ context,
+ );
+
+ expect(output).toEqual({
+ success: true,
+ message: `Webhook ${webhookId} renamed`,
+ });
+ });
+
+ it('should refuse the tool when a flag is no longer granted at call time', async () => {
+ const { definedToolRegistryService, definedTool, tool } =
+ buildRenameWebhookTool({ isGranted: false });
+ const executeSpy = jest.spyOn(tool, 'execute');
+
+ const output = await definedToolRegistryService.execute(
+ definedTool,
+ { id: webhookId },
+ context,
+ );
+
+ expect(output).toMatchObject({
+ success: false,
+ message: 'Tool "rename_webhook" is not available',
+ });
+ expect(executeSpy).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/services/__tests__/tool-registry.service.spec.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/services/__tests__/tool-registry.service.spec.ts
new file mode 100644
index 00000000000..0746a93bf96
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/services/__tests__/tool-registry.service.spec.ts
@@ -0,0 +1,65 @@
+import { ToolCategory } from 'twenty-shared/ai';
+
+import { type ExceptionHandlerService } from 'src/engine/core-modules/exception-handler/exception-handler.service';
+import { type ToolProviderContext } from 'src/engine/core-modules/tool-provider/interfaces/tool-provider-context.type';
+import { type DefinedToolRegistryService } from 'src/engine/core-modules/tool-provider/services/defined-tool-registry.service';
+import { type ToolExecutorService } from 'src/engine/core-modules/tool-provider/services/tool-executor.service';
+import { ToolRegistryService } from 'src/engine/core-modules/tool-provider/services/tool-registry.service';
+import { type ToolOutputSpillService } from 'src/engine/core-modules/tool/services/tool-output-spill.service';
+
+const workspaceId = 'workspace-id';
+const agentRoleId = 'agent-role-id';
+
+const buildToolRegistryService = () => {
+ const generateDescriptors = jest.fn().mockResolvedValue([]);
+ const definedToolRegistryService = {
+ getAvailableDescriptors: jest.fn().mockResolvedValue([]),
+ findDefinedTool: jest.fn(),
+ };
+
+ const toolRegistryService = new ToolRegistryService(
+ [
+ {
+ category: ToolCategory.DATABASE_CRUD,
+ isAvailable: jest.fn().mockResolvedValue(true),
+ generateDescriptors,
+ executeStaticTool: jest.fn(),
+ },
+ ],
+ definedToolRegistryService as unknown as DefinedToolRegistryService,
+ {} as ToolExecutorService,
+ {} as ToolOutputSpillService,
+ {} as ExceptionHandlerService,
+ );
+
+ return { toolRegistryService, generateDescriptors };
+};
+
+describe('ToolRegistryService', () => {
+ describe('getCatalog', () => {
+ it('should keep the explicit object grants when the context resolves to a fresh one', async () => {
+ const { toolRegistryService, generateDescriptors } =
+ buildToolRegistryService();
+ const resolvedContext: ToolProviderContext = {
+ workspaceId,
+ rolePermissionConfig: {
+ intersectionOf: { userWorkspaceRoleId: 'member-role-id' },
+ },
+ };
+
+ await toolRegistryService.getCatalog({
+ workspaceId,
+ rolePermissionConfig: {
+ intersectionOf: { userWorkspaceRoleId: 'member-role-id' },
+ },
+ explicitObjectGrantsRoleId: agentRoleId,
+ resolveExecutionContext: async () => resolvedContext,
+ });
+
+ expect(generateDescriptors).toHaveBeenCalledWith(
+ expect.objectContaining({ explicitObjectGrantsRoleId: agentRoleId }),
+ expect.anything(),
+ );
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/services/defined-tool-registry.service.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/services/defined-tool-registry.service.ts
index fb5cc0a344d..68d59067e3b 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/services/defined-tool-registry.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/services/defined-tool-registry.service.ts
@@ -1,24 +1,24 @@
-import { Inject, Injectable, type OnModuleInit } from '@nestjs/common';
+import { Injectable, type OnModuleInit } from '@nestjs/common';
import { DiscoveryService } from '@nestjs/core';
import { type ToolCategory } from 'twenty-shared/ai';
+import { type PermissionFlagType } from 'twenty-shared/constants';
import { isDefined } from 'twenty-shared/utils';
import { DEFINE_TOOL_METADATA_KEY } from 'src/engine/core-modules/tool-provider/constants/define-tool-metadata-key.constant';
-import { TOOL_PROVIDERS } from 'src/engine/core-modules/tool-provider/constants/tool-providers.token';
import { BaseTool } from 'src/engine/core-modules/tool-provider/interfaces/base-tool.interface';
-import { type GenerateDescriptorOptions } from 'src/engine/core-modules/tool-provider/interfaces/generate-descriptor-options.type';
import { type ToolProviderContext } from 'src/engine/core-modules/tool-provider/interfaces/tool-provider-context.type';
-import { type ToolProvider } from 'src/engine/core-modules/tool-provider/interfaces/tool-provider.interface';
import { type DefineToolOptions } from 'src/engine/core-modules/tool-provider/types/define-tool-options.type';
import { type DefinedTool } from 'src/engine/core-modules/tool-provider/types/defined-tool.type';
import { type ToolDescriptor } from 'src/engine/core-modules/tool-provider/types/tool-descriptor.type';
import { type ToolIndexEntry } from 'src/engine/core-modules/tool-provider/types/tool-index-entry.type';
import { buildInvalidToolArgumentsOutput } from 'src/engine/core-modules/tool-provider/utils/build-invalid-tool-arguments-output.util';
import { buildToolInputJsonSchemaOrThrow } from 'src/engine/core-modules/tool-provider/utils/build-tool-input-json-schema-or-throw.util';
+import { buildToolNotAvailableOutput } from 'src/engine/core-modules/tool-provider/utils/build-tool-not-available-output.util';
import { isSnakeCaseToolName } from 'src/engine/core-modules/tool-provider/utils/is-snake-case-tool-name.util';
import { humanizeToolName } from 'src/engine/core-modules/tool-provider/utils/tool-set-to-descriptors.util';
import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';
+import { PermissionsService } from 'src/engine/metadata-modules/permissions/permissions.service';
@Injectable()
export class DefinedToolRegistryService implements OnModuleInit {
@@ -26,8 +26,7 @@ export class DefinedToolRegistryService implements OnModuleInit {
constructor(
private readonly discoveryService: DiscoveryService,
- @Inject(TOOL_PROVIDERS)
- private readonly providers: ToolProvider[],
+ private readonly permissionsService: PermissionsService,
) {}
onModuleInit() {
@@ -51,20 +50,32 @@ export class DefinedToolRegistryService implements OnModuleInit {
return this.definedToolsByName.get(toolName);
}
- getDescriptors(
- category: ToolCategory,
- options?: GenerateDescriptorOptions,
- ): (ToolIndexEntry | ToolDescriptor)[] {
- const includeSchemas = options?.includeSchemas ?? true;
-
- return [...this.definedToolsByName.values()]
- .filter(
- (definedTool) =>
- definedTool.options.category === category &&
- (!isDefined(options?.toolNames) ||
- options.toolNames.has(definedTool.options.name)),
- )
- .map(({ options: { name, description }, inputJsonSchema }) => {
+ async getAvailableDescriptors(
+ context: ToolProviderContext,
+ {
+ categories,
+ includeSchemas,
+ }: { categories?: ToolCategory[]; includeSchemas: boolean },
+ ): Promise<(ToolIndexEntry | ToolDescriptor)[]> {
+ const requestedTools = [...this.definedToolsByName.values()].filter(
+ ({ options }) =>
+ !isDefined(categories) || categories.includes(options.category),
+ );
+
+ const grantedByPermissionFlag = new Map<
+ PermissionFlagType,
+ Promise<boolean>
+ >();
+
+ const isAvailableByTool = await Promise.all(
+ requestedTools.map((definedTool) =>
+ this.isAvailable(definedTool, context, grantedByPermissionFlag),
+ ),
+ );
+
+ return requestedTools
+ .filter((_, index) => isAvailableByTool[index])
+ .map(({ options: { name, description, category }, inputJsonSchema }) => {
const entry: ToolIndexEntry = {
name,
label: humanizeToolName(name),
@@ -80,10 +91,16 @@ export class DefinedToolRegistryService implements OnModuleInit {
}
async execute(
- { options, tool }: DefinedTool,
+ definedTool: DefinedTool,
args: Record<string, unknown>,
context: ToolProviderContext,
): Promise<ToolOutput> {
+ const { options, tool } = definedTool;
+
+ if (!(await this.isAvailable(definedTool, context))) {
+ return buildToolNotAvailableOutput(options.name);
+ }
+
const parsedInput = await tool.inputSchema.safeParseAsync(args);
if (!parsedInput.success) {
@@ -96,8 +113,36 @@ export class DefinedToolRegistryService implements OnModuleInit {
return tool.execute(parsedInput.data, context);
}
+ private async isAvailable(
+ { options: { requiredPermissionFlags } }: DefinedTool,
+ context: ToolProviderContext,
+ grantedByPermissionFlag = new Map<PermissionFlagType, Promise<boolean>>(),
+ ): Promise<boolean> {
+ const grants = await Promise.all(
+ requiredPermissionFlags.map((permissionFlag) => {
+ const cachedGrant = grantedByPermissionFlag.get(permissionFlag);
+
+ if (isDefined(cachedGrant)) {
+ return cachedGrant;
+ }
+
+ const grant = this.permissionsService.checkRolesPermissions(
+ context.rolePermissionConfig,
+ context.workspaceId,
+ permissionFlag,
+ );
+
+ grantedByPermissionFlag.set(permissionFlag, grant);
+
+ return grant;
+ }),
+ );
+
+ return grants.every((isGranted) => isGranted);
+ }
+
private register(options: DefineToolOptions, instance: unknown): void {
- const { name, category } = options;
+ const { name } = options;
if (!(instance instanceof BaseTool)) {
throw new Error(
@@ -115,12 +160,6 @@ export class DefinedToolRegistryService implements OnModuleInit {
throw new Error(`@DefineTool "${name}" is declared more than once`);
}
- if (!this.providers.some((provider) => provider.category === category)) {
- throw new Error(
- `@DefineTool "${name}" uses category "${category}", which no ToolProvider gates, so it would never be listed`,
- );
- }
-
const inputJsonSchema = buildToolInputJsonSchemaOrThrow({
toolName: name,
inputSchema: instance.inputSchema,
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/services/tool-executor.service.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/services/tool-executor.service.ts
index 09342f5bbe7..f599f6e806c 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/services/tool-executor.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/services/tool-executor.service.ts
@@ -30,6 +30,7 @@ import { type ToolExecutionRef } from 'src/engine/core-modules/tool-provider/typ
import { type ToolIndexEntry } from 'src/engine/core-modules/tool-provider/types/tool-index-entry.type';
import { buildRequiredToolAuthContext } from 'src/engine/core-modules/tool-provider/utils/build-required-tool-auth-context.util';
import { buildToolExecutionFailure } from 'src/engine/core-modules/tool-provider/utils/build-tool-execution-failure.util';
+import { buildToolNotAvailableOutput } from 'src/engine/core-modules/tool-provider/utils/build-tool-not-available-output.util';
import { withResolvedToolAuthContext } from 'src/engine/core-modules/tool-provider/utils/with-resolved-tool-auth-context.util';
import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';
import { UserEntity } from 'src/engine/core-modules/user/user.entity';
@@ -321,6 +322,18 @@ export class ToolExecutorService {
throw new Error('Expected static executionRef');
}
+ const definedTool = this.definedToolRegistryService.findDefinedTool(
+ descriptor.executionRef.toolId,
+ );
+
+ if (isDefined(definedTool)) {
+ return this.definedToolRegistryService.execute(
+ definedTool,
+ args,
+ context,
+ );
+ }
+
const provider = this.providers.find(
(candidate) => candidate.category === descriptor.category,
);
@@ -333,23 +346,7 @@ export class ToolExecutorService {
// Defense-in-depth: re-verify at dispatch whatever path the descriptor came from.
if (!(await provider.isAvailable(context))) {
- return {
- success: false,
- message: `Tool "${descriptor.name}" is not available`,
- error: `Tool "${descriptor.name}" is not available in this context. Use get_tool_catalog to see available tools.`,
- };
- }
-
- const definedTool = this.definedToolRegistryService.findDefinedTool(
- descriptor.executionRef.toolId,
- );
-
- if (isDefined(definedTool)) {
- return this.definedToolRegistryService.execute(
- definedTool,
- args,
- context,
- );
+ return buildToolNotAvailableOutput(descriptor.name);
}
return provider.executeStaticTool(
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/services/tool-registry.service.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/services/tool-registry.service.ts
index 60aa7099ea2..14814551e93 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/services/tool-registry.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/services/tool-registry.service.ts
@@ -19,6 +19,7 @@ import { normalizeToolOutputToJsonValues } from 'src/engine/core-modules/tool-pr
import { DefinedToolRegistryService } from 'src/engine/core-modules/tool-provider/services/defined-tool-registry.service';
import { ToolExecutorService } from 'src/engine/core-modules/tool-provider/services/tool-executor.service';
import { type LearnToolsAspect } from 'src/engine/core-modules/tool-provider/tools/learn-tools.tool';
+import { type ToolCatalogOptions } from 'src/engine/core-modules/tool-provider/types/tool-catalog-options.type';
import { type ToolContext } from 'src/engine/core-modules/tool-provider/types/tool-context.type';
import { type ToolDescriptor } from 'src/engine/core-modules/tool-provider/types/tool-descriptor.type';
import { type ToolIndexEntry } from 'src/engine/core-modules/tool-provider/types/tool-index-entry.type';
@@ -41,35 +42,39 @@ export class ToolRegistryService {
private readonly exceptionHandlerService: ExceptionHandlerService,
) {}
+ getCatalog(
+ context: ToolProviderContext,
+ options: ToolCatalogOptions & { includeSchemas: true },
+ ): Promise<ToolDescriptor[]>;
+ getCatalog(
+ context: ToolProviderContext,
+ options?: ToolCatalogOptions & { includeSchemas?: false },
+ ): Promise<ToolIndexEntry[]>;
async getCatalog(
context: ToolProviderContext,
- options?: { categories?: ToolCategory[]; excludeTools?: Set<string> },
- ): Promise<ToolIndexEntry[]> {
- const executionContext = await (context.resolveExecutionContext?.() ??
- context);
- const categorySet = options?.categories
- ? new Set(options.categories)
- : undefined;
-
- const results = await Promise.all(
- this.providers.map(async (provider) => {
- if (categorySet && !categorySet.has(provider.category)) {
- return [];
- }
-
- if (await provider.isAvailable(executionContext)) {
- return this.generateProviderDescriptors(provider, executionContext, {
- includeSchemas: false,
- });
- }
+ {
+ categories,
+ excludeTools,
+ includeSchemas = false,
+ }: ToolCatalogOptions & { includeSchemas?: boolean } = {},
+ ): Promise<(ToolIndexEntry | ToolDescriptor)[]> {
+ const executionContext = await this.resolveExecutionContext(context);
- return [];
+ const [providerDescriptors, definedToolDescriptors] = await Promise.all([
+ this.listProviderDescriptors({
+ context: executionContext,
+ categories,
+ includeSchemas,
}),
- );
-
- const excludeTools = options?.excludeTools;
+ this.definedToolRegistryService.getAvailableDescriptors(
+ executionContext,
+ { categories, includeSchemas },
+ ),
+ ]);
- return results.flat().filter((entry) => !excludeTools?.has(entry.name));
+ return [...providerDescriptors, ...definedToolDescriptors].filter(
+ (entry) => !excludeTools?.has(entry.name),
+ );
}
async resolveSchemas({
@@ -81,24 +86,32 @@ export class ToolRegistryService {
context: ToolProviderContext;
precomputedCatalog?: ToolIndexEntry[];
}): Promise<Map<string, object>> {
- const executionContext = await (context.resolveExecutionContext?.() ??
- context);
+ const executionContext = await this.resolveExecutionContext(context);
const index =
precomputedCatalog ?? (await this.getCatalog(executionContext));
const nameSet = new Set(toolNames);
const matchingEntries = index.filter((entry) => nameSet.has(entry.name));
+ const schemas = new Map<string, object>();
const byCategory = new Map<string, ToolIndexEntry[]>();
for (const entry of matchingEntries) {
+ const definedTool = this.definedToolRegistryService.findDefinedTool(
+ entry.name,
+ );
+
+ if (isDefined(definedTool)) {
+ schemas.set(entry.name, definedTool.inputJsonSchema);
+
+ continue;
+ }
+
const existing = byCategory.get(entry.category) ?? [];
existing.push(entry);
byCategory.set(entry.category, existing);
}
- const schemas = new Map<string, object>();
-
for (const [category, entries] of byCategory) {
const provider = this.providers.find(
(providerItem) => providerItem.category === category,
@@ -110,11 +123,11 @@ export class ToolRegistryService {
const entryNameSet = new Set(entries.map((entry) => entry.name));
- const descriptors = await this.generateProviderDescriptors(
+ const descriptors = await this.generateProviderDescriptors({
provider,
- executionContext,
- { includeSchemas: true, toolNames: entryNameSet },
- );
+ context: executionContext,
+ options: { includeSchemas: true, toolNames: entryNameSet },
+ });
for (const descriptor of descriptors) {
if (
@@ -408,9 +421,10 @@ export class ToolRegistryService {
const { categories, excludeTools, compactOutput, spillLargeOutput } =
options;
- const descriptors = await this.getDescriptorsByCategories(context, {
+ const descriptors = await this.getCatalog(context, {
categories,
excludeTools,
+ includeSchemas: true,
});
const toolSet = this.hydrateToolSet(descriptors, context, {
@@ -425,50 +439,44 @@ export class ToolRegistryService {
return toolSet;
}
- // MCP and the workflow agent need full schemas.
- async getDescriptorsByCategories(
- context: ToolProviderContext,
- options: Pick<ToolRetrievalOptions, 'categories' | 'excludeTools'> = {},
- ): Promise<ToolDescriptor[]> {
- const { categories, excludeTools } = options;
- const categorySet = categories ? new Set(categories) : undefined;
-
- const results = await Promise.all(
+ private async listProviderDescriptors({
+ context,
+ categories,
+ includeSchemas,
+ }: {
+ context: ToolProviderContext;
+ categories: ToolCategory[] | undefined;
+ includeSchemas: boolean;
+ }): Promise<(ToolIndexEntry | ToolDescriptor)[]> {
+ const descriptorsByProvider = await Promise.all(
this.providers
.filter(
- (provider) => !categorySet || categorySet.has(provider.category),
+ (provider) =>
+ !isDefined(categories) || categories.includes(provider.category),
)
- .map(async (provider) => {
- if (await provider.isAvailable(context)) {
- return this.generateProviderDescriptors(provider, context, {
- includeSchemas: true,
- });
- }
-
- return [];
- }),
+ .map(async (provider) =>
+ (await provider.isAvailable(context))
+ ? this.generateProviderDescriptors({
+ provider,
+ context,
+ options: { includeSchemas },
+ })
+ : [],
+ ),
);
- const descriptors = results.flat() as ToolDescriptor[];
-
- let filteredDescriptors = descriptors;
-
- if (excludeTools?.length) {
- const excludeSet = new Set(excludeTools);
-
- filteredDescriptors = filteredDescriptors.filter(
- (descriptor) => !excludeSet.has(descriptor.name),
- );
- }
-
- return filteredDescriptors;
+ return descriptorsByProvider.flat();
}
- private generateProviderDescriptors(
- provider: ToolProvider,
- context: ToolProviderContext,
- options: GenerateDescriptorOptions,
- ): Promise<(ToolIndexEntry | ToolDescriptor)[]> {
+ private generateProviderDescriptors({
+ provider,
+ context,
+ options,
+ }: {
+ provider: ToolProvider;
+ context: ToolProviderContext;
+ options: GenerateDescriptorOptions;
+ }): Promise<(ToolIndexEntry | ToolDescriptor)[]> {
return Sentry.startSpan(
{
name: `tool provider ${provider.category} descriptors`,
@@ -488,20 +496,12 @@ export class ToolRegistryService {
options,
);
- const descriptors = [
- ...providerDescriptors.filter(
- (descriptor) =>
- !isDefined(
- this.definedToolRegistryService.findDefinedTool(
- descriptor.name,
- ),
- ),
- ),
- ...this.definedToolRegistryService.getDescriptors(
- provider.category,
- options,
- ),
- ];
+ const descriptors = providerDescriptors.filter(
+ (descriptor) =>
+ !isDefined(
+ this.definedToolRegistryService.findDefinedTool(descriptor.name),
+ ),
+ );
span.setAttribute('tool.descriptor_count', descriptors.length);
@@ -510,6 +510,20 @@ export class ToolRegistryService {
);
}
+ // Resolvers rebuild the caller's authorization and know nothing of an agent's explicit grants
+ private async resolveExecutionContext(
+ context: ToolProviderContext,
+ ): Promise<ToolProviderContext> {
+ if (!isDefined(context.resolveExecutionContext)) {
+ return context;
+ }
+
+ return {
+ ...(await context.resolveExecutionContext()),
+ explicitObjectGrantsRoleId: context.explicitObjectGrantsRoleId,
+ };
+ }
+
private buildContextFromToolContext(
context: ToolContext,
): ToolProviderContext {
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/types/define-tool-options.type.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/types/define-tool-options.type.ts
index 9ffc7e7cb6c..def7a689742 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/types/define-tool-options.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/types/define-tool-options.type.ts
@@ -1,7 +1,9 @@
import { type ToolCategory } from 'twenty-shared/ai';
+import { type PermissionFlagType } from 'twenty-shared/constants';
export type DefineToolOptions = {
name: string;
category: ToolCategory;
description: string;
+ requiredPermissionFlags: PermissionFlagType[];
};
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/types/tool-catalog-options.type.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/types/tool-catalog-options.type.ts
new file mode 100644
index 00000000000..c7d143f01bb
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/types/tool-catalog-options.type.ts
@@ -0,0 +1,6 @@
+import { type ToolCategory } from 'twenty-shared/ai';
+
+export type ToolCatalogOptions = {
+ categories?: ToolCategory[];
+ excludeTools?: Set<string>;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/utils/build-tool-not-available-output.util.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/utils/build-tool-not-available-output.util.ts
new file mode 100644
index 00000000000..137612840eb
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/utils/build-tool-not-available-output.util.ts
@@ -0,0 +1,7 @@
+import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';
+
+export const buildToolNotAvailableOutput = (toolName: string): ToolOutput => ({
+ success: false,
+ message: `Tool "${toolName}" is not available`,
+ error: `Tool "${toolName}" is not available in this context.`,
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-toolset.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-toolset.service.ts
index 24d26b7caa3..e717da84e92 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-toolset.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-toolset.service.ts
@@ -20,7 +20,7 @@ import {
} from 'src/engine/core-modules/tool-provider/tools';
import { type ToolContext } from 'src/engine/core-modules/tool-provider/types/tool-context.type';
import { type ToolIndexEntry } from 'src/engine/core-modules/tool-provider/types/tool-index-entry.type';
-import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';
+import { buildToolNotAvailableOutput } from 'src/engine/core-modules/tool-provider/utils/build-tool-not-available-output.util';
import { resolveProposedToolCall } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/resolve-proposed-tool-call.util';
import { createProposeToolCallTool } from 'src/engine/metadata-modules/ai/ai-agent-execution/tools/propose-tool-call.tool';
import { createAskQuestionTool } from 'src/engine/metadata-modules/ai/ai-chat/tools/ask-question.tool';
@@ -79,12 +79,6 @@ type RegistryToolset = {
isToolAllowed: (toolName: string) => boolean;
};
-const buildUnavailableToolOutput = (toolName: string): ToolOutput => ({
- success: false,
- message: `Tool "${toolName}" is not available`,
- error: `Tool "${toolName}" is not available to this agent.`,
-});
-
@Injectable()
export class AgentToolsetService {
constructor(
@@ -123,7 +117,7 @@ export class AgentToolsetService {
executeTool: async ({ toolName, args }) =>
isToolAllowed(toolName)
? this.toolRegistry.resolveAndExecute(toolName, args, toolContext)
- : buildUnavailableToolOutput(toolName),
+ : buildToolNotAvailableOutput(toolName),
});
const pausingTools: ToolSet = {
@@ -253,7 +247,7 @@ export class AgentToolsetService {
},
{
categories: [...registryAccess.categories],
- excludeTools: [...registryAccess.excludedToolNames],
+ excludeTools: new Set(registryAccess.excludedToolNames),
},
);
// the context lacks the explicit grants the tools were built with, so calls stay within them
diff --git a/packages/twenty-server/src/engine/metadata-modules/webhook/tools/delete-webhook.tool.ts b/packages/twenty-server/src/engine/metadata-modules/webhook/tools/delete-webhook.tool.ts
index a5dc4b4ce79..cfb62a156e8 100644
--- a/packages/twenty-server/src/engine/metadata-modules/webhook/tools/delete-webhook.tool.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/webhook/tools/delete-webhook.tool.ts
@@ -1,4 +1,5 @@
import { ToolCategory } from 'twenty-shared/ai';
+import { PermissionFlagType } from 'twenty-shared/constants';
import { z } from 'zod';
import { DefineTool } from 'src/engine/core-modules/tool-provider/decorators/define-tool.decorator';
@@ -14,6 +15,7 @@ const deleteWebhookInputSchema = z.object({
@DefineTool({
name: 'delete_webhook',
category: ToolCategory.WEBHOOK,
+ requiredPermissionFlags: [PermissionFlagType.API_KEYS_AND_WEBHOOKS],
description: `Delete a webhook by id. Use list_webhooks first if you don't know the id.`,
})
export class DeleteWebhookTool extends BaseTool<
diff --git a/packages/twenty-server/test/integration/ai/suites/failing-mcp-webhook-tools-permission.integration-spec.ts b/packages/twenty-server/test/integration/ai/suites/failing-mcp-webhook-tools-permission.integration-spec.ts
new file mode 100644
index 00000000000..71eda9bdb5a
--- /dev/null
+++ b/packages/twenty-server/test/integration/ai/suites/failing-mcp-webhook-tools-permission.integration-spec.ts
@@ -0,0 +1,100 @@
+import { randomUUID } from 'node:crypto';
+
+import { executeToolThroughMcp } from 'test/integration/ai/utils/execute-tool-through-mcp.util';
+import { listWebhookIdsThroughMcp } from 'test/integration/ai/utils/list-webhook-ids-through-mcp.util';
+import { callMcpTool } from 'test/integration/graphql/suites/application-role-intersection/utils/call-mcp-tool.util';
+import { getMcpToolCatalog } from 'test/integration/graphql/suites/application-role-intersection/utils/get-mcp-tool-catalog.util';
+import { ToolCategory } from 'twenty-shared/ai';
+import {
+ type EachTestingContext,
+ eachTestingContextFilter,
+} from 'twenty-shared/testing';
+
+type WebhookToolCallTestContext = {
+ toolName: string;
+ toolArguments: Record<string, unknown>;
+};
+
+const webhookToolCallTestCases: EachTestingContext<WebhookToolCallTestContext>[] =
+ [
+ {
+ title: 'list_webhooks',
+ context: { toolName: 'list_webhooks', toolArguments: {} },
+ },
+ {
+ title: 'create_webhook',
+ context: {
+ toolName: 'create_webhook',
+ toolArguments: {
+ targetUrl: 'https://example.com/twenty-webhook',
+ operations: [{ kind: 'record', object: 'person', event: 'created' }],
+ },
+ },
+ },
+ {
+ title: 'update_webhook',
+ context: {
+ toolName: 'update_webhook',
+ toolArguments: { id: randomUUID(), description: 'Updated' },
+ },
+ },
+ {
+ title: 'delete_webhook',
+ context: {
+ toolName: 'delete_webhook',
+ toolArguments: { id: randomUUID() },
+ },
+ },
+ ];
+
+// The seeded member role lacks API_KEYS_AND_WEBHOOKS, which every webhook tool requires
+describe('MCP webhook tools for a member without API_KEYS_AND_WEBHOOKS (integration)', () => {
+ let webhookIdsBefore: string[];
+
+ beforeAll(async () => {
+ webhookIdsBefore = await listWebhookIdsThroughMcp();
+ });
+
+ afterAll(async () => {
+ const leakedWebhookIds = (await listWebhookIdsThroughMcp()).filter(
+ (id) => !webhookIdsBefore.includes(id),
+ );
+
+ for (const id of leakedWebhookIds) {
+ await executeToolThroughMcp({
+ toolName: 'delete_webhook',
+ toolArguments: { id },
+ });
+ }
+ });
+
+ it('should not list the webhook tools', async () => {
+ const catalog = await getMcpToolCatalog({
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ });
+
+ expect(Object.keys(catalog)).not.toContain(ToolCategory.WEBHOOK);
+ expect(Object.keys(catalog).length).toBeGreaterThan(0);
+ });
+
+ it.each(eachTestingContextFilter(webhookToolCallTestCases))(
+ 'should refuse $title',
+ async ({ context: { toolName, toolArguments } }) => {
+ const result = await callMcpTool({
+ toolName: 'execute_tool',
+ toolArguments: { toolName, arguments: toolArguments },
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ });
+
+ expect(result.isError).toBe(true);
+ expect(JSON.parse(result.content[0].text)).toMatchObject({
+ success: false,
+ message: `Tool "${toolName}" not found`,
+ });
+ },
+ );
+
+ it('should leave the webhooks unchanged', async () => {
+ expect(await listWebhookIdsThroughMcp()).toEqual(webhookIdsBefore);
+ });
+});
diff --git a/packages/twenty-server/test/integration/ai/suites/mcp-webhook-tools.integration-spec.ts b/packages/twenty-server/test/integration/ai/suites/mcp-webhook-tools.integration-spec.ts
index 77fd9a2bcff..c988b1ac671 100644
--- a/packages/twenty-server/test/integration/ai/suites/mcp-webhook-tools.integration-spec.ts
+++ b/packages/twenty-server/test/integration/ai/suites/mcp-webhook-tools.integration-spec.ts
@@ -1,29 +1,19 @@
import { executeToolThroughMcp } from 'test/integration/ai/utils/execute-tool-through-mcp.util';
+import { listWebhookIdsThroughMcp } from 'test/integration/ai/utils/list-webhook-ids-through-mcp.util';
import { callMcpTool } from 'test/integration/graphql/suites/application-role-intersection/utils/call-mcp-tool.util';
import { jestExpectToBeDefined } from 'test/utils/jest-expect-to-be-defined.util.test';
const TARGET_URL = 'https://example.com/twenty-webhook';
-const listWebhookIds = async (): Promise<string[]> => {
- const output = await executeToolThroughMcp<{ webhooks: { id: string }[] }>({
- toolName: 'list_webhooks',
- toolArguments: {},
- });
-
- expect(output.success).toBe(true);
-
- return (output.result?.webhooks ?? []).map((webhook) => webhook.id);
-};
-
describe('MCP webhook tools (integration)', () => {
let webhookIdsBefore: string[];
beforeAll(async () => {
- webhookIdsBefore = await listWebhookIds();
+ webhookIdsBefore = await listWebhookIdsThroughMcp();
});
afterAll(async () => {
- const leakedWebhookIds = (await listWebhookIds()).filter(
+ const leakedWebhookIds = (await listWebhookIdsThroughMcp()).filter(
(id) => !webhookIdsBefore.includes(id),
);
@@ -64,7 +54,7 @@ describe('MCP webhook tools (integration)', () => {
const webhookId = created.result?.id;
jestExpectToBeDefined(webhookId);
- expect(await listWebhookIds()).toContain(webhookId);
+ expect(await listWebhookIdsThroughMcp()).toContain(webhookId);
const deleted = await executeToolThroughMcp({
toolName: 'delete_webhook',
@@ -76,7 +66,7 @@ describe('MCP webhook tools (integration)', () => {
message: `Webhook ${webhookId} deleted`,
result: { deletedWebhookId: webhookId, targetUrl: TARGET_URL },
});
- expect(await listWebhookIds()).not.toContain(webhookId);
+ expect(await listWebhookIdsThroughMcp()).not.toContain(webhookId);
});
it('should refuse delete_webhook with an id that is not a UUID', async () => {
diff --git a/packages/twenty-server/test/integration/ai/utils/list-webhook-ids-through-mcp.util.ts b/packages/twenty-server/test/integration/ai/utils/list-webhook-ids-through-mcp.util.ts
new file mode 100644
index 00000000000..326a6ff4b9e
--- /dev/null
+++ b/packages/twenty-server/test/integration/ai/utils/list-webhook-ids-through-mcp.util.ts
@@ -0,0 +1,12 @@
+import { executeToolThroughMcp } from 'test/integration/ai/utils/execute-tool-through-mcp.util';
+
+export const listWebhookIdsThroughMcp = async (): Promise<string[]> => {
+ const output = await executeToolThroughMcp<{ webhooks: { id: string }[] }>({
+ toolName: 'list_webhooks',
+ toolArguments: {},
+ });
+
+ expect(output.success).toBe(true);
+
+ return (output.result?.webhooks ?? []).map((webhook) => webhook.id);
+};
diff --git a/packages/twenty-server/test/integration/graphql/suites/application-role-intersection/successful-delegated-application-tool-narrowing.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/application-role-intersection/successful-delegated-application-tool-narrowing.integration-spec.ts
index 10f63500f49..950125ea9f0 100644
--- a/packages/twenty-server/test/integration/graphql/suites/application-role-intersection/successful-delegated-application-tool-narrowing.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/application-role-intersection/successful-delegated-application-tool-narrowing.integration-spec.ts
@@ -1,5 +1,7 @@
+import { callMcpTool } from 'test/integration/graphql/suites/application-role-intersection/utils/call-mcp-tool.util';
import { getMcpToolCatalog } from 'test/integration/graphql/suites/application-role-intersection/utils/get-mcp-tool-catalog.util';
import { getToolIndex } from 'test/integration/graphql/suites/application-role-intersection/utils/get-tool-index.util';
+import { listDirectModeMcpToolNames } from 'test/integration/graphql/suites/application-role-intersection/utils/list-direct-mode-mcp-tool-names.util';
import {
cleanupDelegatedApplications,
type DelegatedApplications,
@@ -9,7 +11,21 @@ import { ToolCategory } from 'twenty-shared/ai';
// The seeded admin holds every settings flag, so a category gated on one the
// application's role lacks can only disappear through the intersection.
-const NARROWED_CATEGORY = ToolCategory.ROLE;
+const NARROWED_CATEGORIES = [ToolCategory.ROLE, ToolCategory.WEBHOOK];
+
+const WEBHOOK_TOOL_NAMES = [
+ 'list_webhooks',
+ 'create_webhook',
+ 'update_webhook',
+ 'delete_webhook',
+];
+
+const executeListWebhooksThroughMcp = (token: string) =>
+ callMcpTool({
+ toolName: 'execute_tool',
+ toolArguments: { toolName: 'list_webhooks', arguments: {} },
+ token,
+ });
describe('Tool listings narrow to the delegated application role', () => {
let delegatedApplications: DelegatedApplications;
@@ -23,42 +39,112 @@ describe('Tool listings narrow to the delegated application role', () => {
}, 120000);
describe('the MCP tool catalog', () => {
- it('should list the settings-gated category for the admin session', async () => {
+ it.each(NARROWED_CATEGORIES)(
+ 'should list the settings-gated %s category for the admin session',
+ async (category) => {
+ const catalog = await getMcpToolCatalog({
+ token: APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ });
+
+ expect(Object.keys(catalog)).toContain(category);
+ },
+ );
+
+ it.each(NARROWED_CATEGORIES)(
+ 'should hide the %s category from an application whose role holds no flag',
+ async (category) => {
+ const catalog = await getMcpToolCatalog({
+ token: delegatedApplications.noFlagApplicationToken,
+ });
+
+ expect(Object.keys(catalog)).not.toContain(category);
+ },
+ );
+
+ it('should hide only the webhook tools from an application whose role holds ROLES but not API_KEYS_AND_WEBHOOKS', async () => {
const catalog = await getMcpToolCatalog({
- token: APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ token: delegatedApplications.flaggedApplicationToken,
});
- expect(Object.keys(catalog)).toContain(NARROWED_CATEGORY);
+ expect(Object.keys(catalog)).toContain(ToolCategory.ROLE);
+ expect(Object.keys(catalog)).not.toContain(ToolCategory.WEBHOOK);
});
+ });
- it('should hide it from an application whose role holds no flag', async () => {
- const catalog = await getMcpToolCatalog({
- token: delegatedApplications.noFlagApplicationToken,
+ describe('the MCP direct-mode tool list', () => {
+ it('should list the webhook tools for the admin session', async () => {
+ const toolNames = await listDirectModeMcpToolNames({
+ token: APPLE_JANE_ADMIN_ACCESS_TOKEN,
});
- expect(Object.keys(catalog)).not.toContain(NARROWED_CATEGORY);
+ expect(toolNames).toEqual(expect.arrayContaining(WEBHOOK_TOOL_NAMES));
});
+
+ it.each([
+ ['holds no flag', 'noFlagApplicationToken'],
+ ['holds ROLES but not API_KEYS_AND_WEBHOOKS', 'flaggedApplicationToken'],
+ ] as const)(
+ 'should hide the webhook tools from an application whose role %s',
+ async (_, tokenKey) => {
+ const toolNames = await listDirectModeMcpToolNames({
+ token: delegatedApplications[tokenKey],
+ });
+
+ expect(
+ toolNames.filter((toolName) => WEBHOOK_TOOL_NAMES.includes(toolName)),
+ ).toEqual([]);
+ expect(toolNames.length).toBeGreaterThan(0);
+ },
+ );
});
describe('getToolIndex', () => {
- it('should list the settings-gated category for the admin session', async () => {
- const { data } = await getToolIndex({ expectToFail: false });
+ it.each(NARROWED_CATEGORIES)(
+ 'should list the settings-gated %s category for the admin session',
+ async (category) => {
+ const { data } = await getToolIndex({ expectToFail: false });
+
+ expect(data.getToolIndex.map((entry) => entry.category)).toContain(
+ category,
+ );
+ },
+ );
+
+ it.each(NARROWED_CATEGORIES)(
+ 'should hide the %s category from an application whose role holds no flag',
+ async (category) => {
+ const { data } = await getToolIndex({
+ token: delegatedApplications.noFlagApplicationToken,
+ expectToFail: false,
+ });
+
+ expect(data.getToolIndex.map((entry) => entry.category)).not.toContain(
+ category,
+ );
+ expect(data.getToolIndex.length).toBeGreaterThan(0);
+ },
+ );
+ });
- expect(data.getToolIndex.map((entry) => entry.category)).toContain(
- NARROWED_CATEGORY,
+ describe('MCP tool execution', () => {
+ it('should run a webhook tool for the admin session', async () => {
+ const result = await executeListWebhooksThroughMcp(
+ APPLE_JANE_ADMIN_ACCESS_TOKEN,
);
- });
- it('should hide it from an application whose role holds no flag', async () => {
- const { data } = await getToolIndex({
- token: delegatedApplications.noFlagApplicationToken,
- expectToFail: false,
- });
+ expect(result.isError).toBe(false);
+ });
- expect(data.getToolIndex.map((entry) => entry.category)).not.toContain(
- NARROWED_CATEGORY,
+ it('should refuse a webhook tool to an application whose role holds no flag', async () => {
+ const result = await executeListWebhooksThroughMcp(
+ delegatedApplications.noFlagApplicationToken,
);
- expect(data.getToolIndex.length).toBeGreaterThan(0);
+
+ expect(result.isError).toBe(true);
+ expect(JSON.parse(result.content[0].text)).toMatchObject({
+ success: false,
+ message: 'Tool "list_webhooks" not found',
+ });
});
});
});
diff --git a/packages/twenty-server/test/integration/graphql/suites/application-role-intersection/utils/list-direct-mode-mcp-tool-names.util.ts b/packages/twenty-server/test/integration/graphql/suites/application-role-intersection/utils/list-direct-mode-mcp-tool-names.util.ts
new file mode 100644
index 00000000000..6c85a2bb38c
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/application-role-intersection/utils/list-direct-mode-mcp-tool-names.util.ts
@@ -0,0 +1,20 @@
+import request from 'supertest';
+
+// Direct mode lists every registry tool with its input schema, unlike get_tool_catalog
+export const listDirectModeMcpToolNames = async ({
+ token,
+}: {
+ token: string;
+}): Promise<string[]> => {
+ const response = await request(`http://localhost:${APP_PORT}`)
+ .post('/mcp?mode=direct')
+ .set('Authorization', `Bearer ${token}`)
+ .set('Content-Type', 'application/json')
+ .set('Accept', 'application/json')
+ .send(JSON.stringify({ jsonrpc: '2.0', method: 'tools/list', id: 1 }))
+ .expect(200);
+
+ const tools: { name: string }[] = response.body.result.tools;
+
+ return tools.map(({ name }) => name);
+};