Skip to content

The open alternative to Salesforce, designed for AI.

fix(mcp): support per-option grouping for multi-select fields (#26787)

Wael Antared775d4be387
diff --git a/packages/twenty-server/src/engine/api/common/common-args-processors/group-by-arg-processor/utils/__tests__/validate-and-transform-group-by-fields-or-throw.util.spec.ts b/packages/twenty-server/src/engine/api/common/common-args-processors/group-by-arg-processor/utils/__tests__/validate-and-transform-group-by-fields-or-throw.util.spec.ts
new file mode 100644
index 00000000000..35cb531ccfd
--- /dev/null
+++ b/packages/twenty-server/src/engine/api/common/common-args-processors/group-by-arg-processor/utils/__tests__/validate-and-transform-group-by-fields-or-throw.util.spec.ts
@@ -0,0 +1,184 @@
+import {
+ FieldMetadataType,
+ ObjectRecordGroupByDateGranularity,
+} from 'twenty-shared/types';
+
+import { validateAndTransformGroupByFieldsOrThrow } from 'src/engine/api/common/common-args-processors/group-by-arg-processor/utils/validate-and-transform-group-by-fields-or-throw.util';
+import { CommonQueryRunnerExceptionCode } from 'src/engine/api/common/common-query-runners/errors/common-query-runner.exception';
+import { type ObjectRecordGroupBy } from 'src/engine/api/graphql/workspace-query-builder/interfaces/object-record.interface';
+import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';
+import { getFlatFieldMetadataMock } from 'src/engine/metadata-modules/flat-field-metadata/__mocks__/get-flat-field-metadata.mock';
+import { type OrmFlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/types/orm-flat-field-metadata.type';
+import { getFlatObjectMetadataMock } from 'src/engine/metadata-modules/flat-object-metadata/__mocks__/get-flat-object-metadata.mock';
+import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
+
+describe('validateAndTransformGroupByFieldsOrThrow unnest', () => {
+ const objectMetadataId = 'company-object-id';
+ const objectUniversalIdentifier = 'company-object-universal-id';
+ const fields = [
+ { name: 'tags', type: FieldMetadataType.MULTI_SELECT },
+ { name: 'aliases', type: FieldMetadataType.ARRAY },
+ { name: 'name', type: FieldMetadataType.TEXT },
+ { name: 'contactName', type: FieldMetadataType.FULL_NAME },
+ { name: 'startedAt', type: FieldMetadataType.DATE_TIME },
+ ].map(({ name, type }) =>
+ getFlatFieldMetadataMock({
+ id: `company-${name}-field-id`,
+ universalIdentifier: `company-${name}-field-universal-id`,
+ objectMetadataId,
+ name,
+ type,
+ }),
+ );
+ const flatObjectMetadata = getFlatObjectMetadataMock({
+ id: objectMetadataId,
+ universalIdentifier: objectUniversalIdentifier,
+ nameSingular: 'company',
+ namePlural: 'companies',
+ fieldIds: fields.map((field) => field.id),
+ fieldUniversalIdentifiers: fields.map((field) => field.universalIdentifier),
+ });
+ const flatFieldMetadataMaps: FlatEntityMaps<OrmFlatFieldMetadata> = {
+ byUniversalIdentifier: Object.fromEntries(
+ fields.map((field) => [field.universalIdentifier, field]),
+ ),
+ universalIdentifierById: Object.fromEntries(
+ fields.map((field) => [field.id, field.universalIdentifier]),
+ ),
+ universalIdentifiersByApplicationId: {},
+ };
+ const flatObjectMetadataMaps: FlatEntityMaps<FlatObjectMetadata> = {
+ byUniversalIdentifier: {
+ [objectUniversalIdentifier]: flatObjectMetadata,
+ },
+ universalIdentifierById: {
+ [objectMetadataId]: objectUniversalIdentifier,
+ },
+ universalIdentifiersByApplicationId: {},
+ };
+
+ const validateGroupBy = (groupBy: ObjectRecordGroupBy) =>
+ validateAndTransformGroupByFieldsOrThrow({
+ groupBy,
+ flatObjectMetadata,
+ flatObjectMetadataMaps,
+ flatFieldMetadataMaps,
+ });
+
+ it.each(['tags', 'aliases'])(
+ 'allows explicit unnest on the multi-value field %s',
+ (fieldName) => {
+ expect(
+ validateGroupBy([{ [fieldName]: { unnest: true } }]),
+ ).toMatchObject([
+ { fieldMetadata: { name: fieldName }, shouldUnnest: true },
+ ]);
+ },
+ );
+
+ it.each(['tags', 'aliases'])(
+ 'preserves whole-array grouping for %s',
+ (fieldName) => {
+ const groupByFields = validateGroupBy([{ [fieldName]: true }]);
+
+ expect(groupByFields).toMatchObject([
+ { fieldMetadata: { name: fieldName } },
+ ]);
+ expect(groupByFields[0]).not.toHaveProperty('shouldUnnest');
+ },
+ );
+
+ it('allows one unnested field alongside a whole-array grouping', () => {
+ expect(
+ validateGroupBy([{ tags: { unnest: true } }, { aliases: true }]),
+ ).toMatchObject([
+ { fieldMetadata: { name: 'tags' }, shouldUnnest: true },
+ { fieldMetadata: { name: 'aliases' } },
+ ]);
+ });
+
+ it('preserves composite and date grouping definitions', () => {
+ expect(
+ validateGroupBy([
+ { contactName: { firstName: true } },
+ {
+ startedAt: {
+ granularity: ObjectRecordGroupByDateGranularity.MONTH,
+ timeZone: 'UTC',
+ },
+ },
+ ]),
+ ).toMatchObject([
+ { fieldMetadata: { name: 'contactName' }, subFieldName: 'firstName' },
+ {
+ fieldMetadata: { name: 'startedAt' },
+ dateGranularity: ObjectRecordGroupByDateGranularity.MONTH,
+ timeZone: 'UTC',
+ },
+ ]);
+ });
+
+ it.each([
+ { unnest: false },
+ { unnest: 'true' },
+ { unnest: null },
+ { unnest: undefined },
+ { unnest: true, extra: true },
+ ])('rejects invalid runtime unnest input %j', (definition) => {
+ expect(() =>
+ validateGroupBy([{ tags: definition }] as unknown as ObjectRecordGroupBy),
+ ).toThrow(
+ expect.objectContaining({
+ code: CommonQueryRunnerExceptionCode.INVALID_QUERY_INPUT,
+ message: expect.stringContaining('{"tags": {"unnest": true}}'),
+ }),
+ );
+ });
+
+ it.each(['name', 'contactName', 'startedAt'])(
+ 'rejects unnest on the non-array field %s',
+ (fieldName) => {
+ expect(() =>
+ validateGroupBy([{ [fieldName]: { unnest: true } }]),
+ ).toThrow(
+ expect.objectContaining({
+ code: CommonQueryRunnerExceptionCode.INVALID_QUERY_INPUT,
+ message: expect.stringContaining(
+ `{"${fieldName}": {"unnest": true}}`,
+ ),
+ }),
+ );
+ },
+ );
+
+ it('rejects unnest even when a date definition also contains a granularity', () => {
+ expect(() =>
+ validateGroupBy([
+ {
+ startedAt: {
+ unnest: true,
+ granularity: ObjectRecordGroupByDateGranularity.MONTH,
+ },
+ },
+ ] as unknown as ObjectRecordGroupBy),
+ ).toThrow(
+ expect.objectContaining({
+ code: CommonQueryRunnerExceptionCode.INVALID_QUERY_INPUT,
+ message: expect.stringContaining('{"startedAt": {"unnest": true}}'),
+ }),
+ );
+ });
+
+ it.each([
+ [{ tags: { unnest: true } }, { aliases: { unnest: true } }],
+ [{ aliases: { unnest: true } }, { tags: { unnest: true } }],
+ [{ tags: { unnest: true } }, { tags: { unnest: true } }],
+ ])('rejects more than one unnested grouping entry: %j', (...groupBy) => {
+ expect(() => validateGroupBy(groupBy)).toThrow(
+ expect.objectContaining({
+ code: CommonQueryRunnerExceptionCode.INVALID_QUERY_INPUT,
+ message: 'Only one groupBy field can use unnest',
+ }),
+ );
+ });
+});
diff --git a/packages/twenty-server/src/engine/api/common/common-args-processors/group-by-arg-processor/utils/validate-and-transform-group-by-fields-or-throw.util.ts b/packages/twenty-server/src/engine/api/common/common-args-processors/group-by-arg-processor/utils/validate-and-transform-group-by-fields-or-throw.util.ts
index d2e064ec34a..c6587763cc8 100644
--- a/packages/twenty-server/src/engine/api/common/common-args-processors/group-by-arg-processor/utils/validate-and-transform-group-by-fields-or-throw.util.ts
+++ b/packages/twenty-server/src/engine/api/common/common-args-processors/group-by-arg-processor/utils/validate-and-transform-group-by-fields-or-throw.util.ts
@@ -1,6 +1,7 @@
import { FieldMetadataType } from 'twenty-shared/types';
import {
isDefined,
+ isFieldMetadataArrayKind,
isFieldMetadataSupportedInGroupBy,
isPlainObject,
} from 'twenty-shared/utils';
@@ -160,6 +161,35 @@ const validateAndTransformSingleGroupByFieldOrThrow = ({
const fieldGroupByDefinition = fieldNames[fieldName];
const isObjectFieldGroupByDefinition = isPlainObject(fieldGroupByDefinition);
+
+ if (isObjectFieldGroupByDefinition && 'unnest' in fieldGroupByDefinition) {
+ const errorMessage = `Invalid unnest groupBy for field "${fieldName}". Use {"${fieldName}": {"unnest": true}} on ARRAY or MULTI_SELECT fields.`;
+
+ validateSingleKeyForGroupByOrThrow({
+ groupByKeys: Object.keys(fieldGroupByDefinition),
+ errorMessage,
+ });
+
+ if (
+ fieldGroupByDefinition.unnest !== true ||
+ !isFieldMetadataArrayKind(fieldMetadata.type)
+ ) {
+ throw new CommonQueryRunnerException(
+ errorMessage,
+ CommonQueryRunnerExceptionCode.INVALID_QUERY_INPUT,
+ { userFriendlyMessage: STANDARD_ERROR_MESSAGE },
+ );
+ }
+
+ groupByFields.push({
+ fieldMetadata,
+ subFieldName: undefined,
+ shouldUnnest: true,
+ });
+
+ return;
+ }
+
const isGroupByRelationField =
isMorphOrRelationFlatFieldMetadata(fieldMetadata) &&
isObjectFieldGroupByDefinition &&
@@ -201,16 +231,6 @@ const validateAndTransformSingleGroupByFieldOrThrow = ({
return;
}
- if (isObjectFieldGroupByDefinition && 'unnest' in fieldGroupByDefinition) {
- groupByFields.push({
- fieldMetadata,
- subFieldName: undefined,
- shouldUnnest: true,
- });
-
- return;
- }
-
if (fieldGroupByDefinition === true) {
groupByFields.push({
fieldMetadata,
@@ -281,5 +301,18 @@ export const validateAndTransformGroupByFieldsOrThrow = ({
}
}
+ const unnestedGroupByFields = groupByFields.filter(
+ (groupByField) =>
+ 'shouldUnnest' in groupByField && groupByField.shouldUnnest,
+ );
+
+ if (unnestedGroupByFields.length > 1) {
+ throw new CommonQueryRunnerException(
+ 'Only one groupBy field can use unnest',
+ CommonQueryRunnerExceptionCode.INVALID_QUERY_INPUT,
+ { userFriendlyMessage: STANDARD_ERROR_MESSAGE },
+ );
+ }
+
return groupByFields;
};
diff --git a/packages/twenty-server/src/engine/core-modules/record-crud/services/group-by-records.service.ts b/packages/twenty-server/src/engine/core-modules/record-crud/services/group-by-records.service.ts
index 610f1b4d6dd..ddeb4ed633e 100644
--- a/packages/twenty-server/src/engine/core-modules/record-crud/services/group-by-records.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-crud/services/group-by-records.service.ts
@@ -17,6 +17,7 @@ import {
import { CommonApiContextBuilderService } from 'src/engine/core-modules/record-crud/services/common-api-context-builder.service';
import { type GroupByRecordsParams } from 'src/engine/core-modules/record-crud/types/group-by-records-params.type';
import { type GroupByRecordsResult } from 'src/engine/core-modules/record-crud/types/group-by-records-result.type';
+import { getGroupByDimensionLabel } from 'src/engine/core-modules/record-crud/utils/get-group-by-dimension-label.util';
import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';
@Injectable()
@@ -115,9 +116,7 @@ export class GroupByRecordsService {
queryRunnerContext,
);
- const dimensionLabels = groupBy.map((entry) =>
- this.getDimensionLabelFromGroupByEntry(entry),
- );
+ const dimensionLabels = groupBy.map(getGroupByDimensionLabel);
this.logger.log(
`Grouped ${objectName} by ${dimensionLabels.join(', ')}: ${results.length} groups`,
@@ -155,42 +154,4 @@ export class GroupByRecordsService {
};
}
}
-
- private getDimensionLabelFromGroupByEntry(
- entry: GroupByRecordsParams['groupBy'][number],
- ): string {
- const fieldEntries = Object.entries(entry);
-
- if (fieldEntries.length === 0) {
- return '';
- }
-
- const [fieldName, fieldDefinition] = fieldEntries[0];
-
- if (fieldDefinition === true) {
- return fieldName;
- }
-
- if (typeof fieldDefinition !== 'object' || fieldDefinition === null) {
- return fieldName;
- }
-
- const nestedEntries = Object.entries(fieldDefinition);
-
- if (nestedEntries.length !== 1) {
- return fieldName;
- }
-
- const [nestedFieldName, nestedFieldDefinition] = nestedEntries[0];
-
- if (nestedFieldDefinition !== true) {
- return fieldName;
- }
-
- if (nestedFieldName === 'id' && fieldName.endsWith('Id')) {
- return fieldName;
- }
-
- return `${fieldName}.${nestedFieldName}`;
- }
}
diff --git a/packages/twenty-server/src/engine/core-modules/record-crud/utils/__tests__/get-group-by-dimension-label.util.spec.ts b/packages/twenty-server/src/engine/core-modules/record-crud/utils/__tests__/get-group-by-dimension-label.util.spec.ts
new file mode 100644
index 00000000000..22fd53f3e26
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/record-crud/utils/__tests__/get-group-by-dimension-label.util.spec.ts
@@ -0,0 +1,32 @@
+import { ObjectRecordGroupByDateGranularity } from 'twenty-shared/types';
+
+import { type ObjectRecordGroupBy } from 'src/engine/api/graphql/workspace-query-builder/interfaces/object-record.interface';
+import { getGroupByDimensionLabel } from 'src/engine/core-modules/record-crud/utils/get-group-by-dimension-label.util';
+
+describe('getGroupByDimensionLabel', () => {
+ const cases: Array<{
+ entry: ObjectRecordGroupBy[number];
+ expected: string;
+ }> = [
+ { entry: { tags: true }, expected: 'tags' },
+ { entry: { tags: { unnest: true } }, expected: 'tags' },
+ { entry: { aliases: { unnest: true } }, expected: 'aliases' },
+ { entry: { name: true }, expected: 'name' },
+ { entry: { name: { firstName: true } }, expected: 'name.firstName' },
+ { entry: { companyId: true }, expected: 'companyId' },
+ { entry: { companyId: { id: true } }, expected: 'companyId' },
+ {
+ entry: {
+ createdAt: {
+ granularity: ObjectRecordGroupByDateGranularity.MONTH,
+ timeZone: 'UTC',
+ },
+ },
+ expected: 'createdAt',
+ },
+ ];
+
+ it.each(cases)('labels $entry as $expected', ({ entry, expected }) => {
+ expect(getGroupByDimensionLabel(entry)).toBe(expected);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/record-crud/utils/get-group-by-dimension-label.util.ts b/packages/twenty-server/src/engine/core-modules/record-crud/utils/get-group-by-dimension-label.util.ts
new file mode 100644
index 00000000000..fe4e4ca8735
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/record-crud/utils/get-group-by-dimension-label.util.ts
@@ -0,0 +1,45 @@
+import { isPlainObject } from 'twenty-shared/utils';
+
+import { type ObjectRecordGroupBy } from 'src/engine/api/graphql/workspace-query-builder/interfaces/object-record.interface';
+
+export const getGroupByDimensionLabel = (
+ entry: ObjectRecordGroupBy[number],
+): string => {
+ const fieldEntries = Object.entries(entry);
+
+ if (fieldEntries.length === 0) {
+ return '';
+ }
+
+ const [fieldName, fieldDefinition] = fieldEntries[0];
+
+ if (fieldDefinition === true) {
+ return fieldName;
+ }
+
+ if (!isPlainObject(fieldDefinition)) {
+ return fieldName;
+ }
+
+ const nestedEntries = Object.entries(fieldDefinition);
+
+ if (nestedEntries.length !== 1) {
+ return fieldName;
+ }
+
+ const [nestedFieldName, nestedFieldDefinition] = nestedEntries[0];
+
+ if (nestedFieldDefinition !== true) {
+ return fieldName;
+ }
+
+ if (nestedFieldName === 'unnest') {
+ return fieldName;
+ }
+
+ if (nestedFieldName === 'id' && fieldName.endsWith('Id')) {
+ return fieldName;
+ }
+
+ return `${fieldName}.${nestedFieldName}`;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/record-crud/zod-schemas/__tests__/group-by-tool.zod-schema.spec.ts b/packages/twenty-server/src/engine/core-modules/record-crud/zod-schemas/__tests__/group-by-tool.zod-schema.spec.ts
new file mode 100644
index 00000000000..6f68f3804a8
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/record-crud/zod-schemas/__tests__/group-by-tool.zod-schema.spec.ts
@@ -0,0 +1,175 @@
+import { FieldMetadataType } from 'twenty-shared/types';
+
+import { type ObjectMetadataForToolSchema } from 'src/engine/core-modules/record-crud/types/object-metadata-for-tool-schema.type';
+import { toToolJsonSchema } from 'src/engine/core-modules/record-crud/utils/to-tool-json-schema.util';
+import { generateGroupByToolInputSchema } from 'src/engine/core-modules/record-crud/zod-schemas/group-by-tool.zod-schema';
+
+const buildObjectMetadata = (): ObjectMetadataForToolSchema => {
+ return {
+ fields: [
+ {
+ id: 'field-id-tags',
+ name: 'tags',
+ type: FieldMetadataType.MULTI_SELECT,
+ isSystem: false,
+ options: [{ value: 'RADIUS' }, { value: 'PAM' }],
+ },
+ {
+ id: 'field-id-aliases',
+ name: 'aliases',
+ type: FieldMetadataType.ARRAY,
+ isSystem: false,
+ },
+ {
+ id: 'field-id-name',
+ name: 'name',
+ type: FieldMetadataType.TEXT,
+ isSystem: false,
+ },
+ ],
+ } as unknown as ObjectMetadataForToolSchema;
+};
+
+describe('generateGroupByToolInputSchema multi-value unnest', () => {
+ it.each(['tags', 'aliases'])(
+ 'accepts whole-array grouping on %s',
+ (fieldName) => {
+ const schema = generateGroupByToolInputSchema(buildObjectMetadata());
+
+ expect(schema).not.toBeNull();
+ expect(schema!.parse({ groupBy: [{ [fieldName]: true }] })).toMatchObject(
+ {
+ groupBy: [{ [fieldName]: true }],
+ },
+ );
+ },
+ );
+
+ it.each(['tags', 'aliases'])(
+ 'accepts the unnest opt-in on %s',
+ (fieldName) => {
+ const schema = generateGroupByToolInputSchema(buildObjectMetadata());
+
+ expect(schema).not.toBeNull();
+ expect(
+ schema!.parse({ groupBy: [{ [fieldName]: { unnest: true } }] }),
+ ).toMatchObject({
+ groupBy: [{ [fieldName]: { unnest: true } }],
+ });
+ },
+ );
+
+ it('accepts unnest together with a second grouping dimension', () => {
+ const schema = generateGroupByToolInputSchema(buildObjectMetadata());
+
+ expect(
+ schema!.parse({
+ groupBy: [{ tags: { unnest: true } }, { name: true }],
+ }),
+ ).toMatchObject({
+ groupBy: [{ tags: { unnest: true } }, { name: true }],
+ });
+ });
+
+ it.each([{ unnest: false }, { unnest: true, extra: true }])(
+ 'rejects an invalid advertised unnest shape: %j',
+ (definition) => {
+ const schema = generateGroupByToolInputSchema(buildObjectMetadata());
+
+ expect(
+ schema!.safeParse({ groupBy: [{ tags: definition }] }).success,
+ ).toBe(false);
+ },
+ );
+
+ it('omits unreadable fields from the advertised grouping choices', () => {
+ const schema = generateGroupByToolInputSchema(buildObjectMetadata(), {
+ 'field-id-tags': { canRead: false },
+ });
+
+ expect(schema).not.toBeNull();
+ expect(toToolJsonSchema(schema!)).toMatchObject({
+ properties: {
+ groupBy: {
+ items: {
+ anyOf: expect.not.arrayContaining([
+ expect.objectContaining({
+ properties: { tags: expect.anything() },
+ }),
+ ]),
+ },
+ },
+ },
+ });
+ });
+
+ it.each(['tags', 'aliases'])(
+ 'publishes whole-array and strict unnest shapes for %s',
+ (fieldName) => {
+ const schema = generateGroupByToolInputSchema(buildObjectMetadata());
+
+ expect(schema).not.toBeNull();
+ expect(toToolJsonSchema(schema!)).toMatchObject({
+ properties: {
+ groupBy: {
+ items: {
+ anyOf: expect.arrayContaining([
+ expect.objectContaining({
+ properties: {
+ [fieldName]: {
+ anyOf: expect.arrayContaining([
+ expect.objectContaining({
+ type: 'boolean',
+ const: true,
+ }),
+ expect.objectContaining({
+ type: 'object',
+ properties: {
+ unnest: { type: 'boolean', const: true },
+ },
+ required: ['unnest'],
+ additionalProperties: false,
+ }),
+ ]),
+ },
+ },
+ }),
+ ]),
+ },
+ },
+ },
+ });
+ },
+ );
+
+ it('describes the single-unnest rule and overlapping group counts', () => {
+ const schema = generateGroupByToolInputSchema(buildObjectMetadata());
+ const jsonSchema = toToolJsonSchema(schema!);
+
+ expect(jsonSchema).toMatchObject({
+ properties: {
+ groupBy: {
+ description: expect.stringContaining(
+ 'At most one entry can use unnest.',
+ ),
+ },
+ },
+ });
+ expect(jsonSchema).toMatchObject({
+ properties: {
+ groupBy: {
+ description: expect.stringContaining(
+ 'totals can exceed the record count',
+ ),
+ },
+ },
+ });
+ expect(jsonSchema).toMatchObject({
+ properties: {
+ groupBy: {
+ description: expect.stringContaining('aliases (multi-value,'),
+ },
+ },
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/record-crud/zod-schemas/group-by-tool.zod-schema.ts b/packages/twenty-server/src/engine/core-modules/record-crud/zod-schemas/group-by-tool.zod-schema.ts
index 357e4d32aa7..dc97fdfa01b 100644
--- a/packages/twenty-server/src/engine/core-modules/record-crud/zod-schemas/group-by-tool.zod-schema.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-crud/zod-schemas/group-by-tool.zod-schema.ts
@@ -7,6 +7,7 @@ import {
type RestrictedFieldsPermissions,
} from 'twenty-shared/types';
import {
+ isFieldMetadataArrayKind,
isFieldMetadataDateKind,
isFieldMetadataSupportedInGroupBy,
} from 'twenty-shared/utils';
@@ -114,6 +115,23 @@ const buildGroupByEntriesAndDescriptions = (
continue;
}
+ if (isFieldMetadataArrayKind(field.type)) {
+ groupByEntries.push(
+ z
+ .object({
+ [field.name]: z.union([
+ z.literal(true),
+ z.object({ unnest: z.literal(true) }).strict(),
+ ]),
+ })
+ .strict(),
+ );
+ fieldNameDescriptions.push(
+ `${field.name} (multi-value, {"${field.name}": {"unnest": true}} counts each value)`,
+ );
+ continue;
+ }
+
groupByEntries.push(z.object({ [field.name]: z.literal(true) }).strict());
fieldNameDescriptions.push(field.name);
}
@@ -181,7 +199,7 @@ export const generateGroupByToolInputSchema = (
.min(1)
.max(2)
.describe(
- `Fields to group by (max 2). Each entry must be an object with exactly one field key. Examples: {"status": true}, {"companyId": true}, {"createdAt": {"granularity": "MONTH", "timeZone": "UTC"}}. Available: ${fieldNameDescriptions.join(', ')}.`,
+ `Fields to group by (max 2). Each entry must be an object with exactly one field key. At most one entry can use unnest. A record with several values is counted in each group, so totals can exceed the record count. Examples: {"status": true}, {"companyId": true}, {"createdAt": {"granularity": "MONTH", "timeZone": "UTC"}}. Available: ${fieldNameDescriptions.join(', ')}.`,
),
aggregateOperation: z
.enum(Object.keys(AggregateOperations) as [string, ...string[]])
diff --git a/packages/twenty-server/test/integration/ai/suites/mcp-tool-execution.integration-spec.ts b/packages/twenty-server/test/integration/ai/suites/mcp-tool-execution.integration-spec.ts
index 996cc20bdd1..302e75a1630 100644
--- a/packages/twenty-server/test/integration/ai/suites/mcp-tool-execution.integration-spec.ts
+++ b/packages/twenty-server/test/integration/ai/suites/mcp-tool-execution.integration-spec.ts
@@ -11,6 +11,7 @@ const TOOL_NAMES = {
createNote: 'create_one_note',
createNoteTarget: 'create_one_note_target',
groupByNoteTargets: 'group_by_note_targets',
+ groupByCompanies: 'group_by_companies',
} as const;
type McpToolCallResult = {
@@ -374,4 +375,91 @@ describe('MCP tool execution (integration)', () => {
expect(countsByCompany[createdCompanyBId as string]).toBe(1);
});
});
+
+ describe('group_by_companies (multi-select work policy)', () => {
+ const createdCompanyIds: string[] = [];
+ const createdCompanyNames: string[] = [];
+
+ type GroupByResult = {
+ groups: Array<{ dimensions: unknown[]; value: string | number }>;
+ dimensionLabels: string[];
+ aggregation: string;
+ groupCount: number;
+ };
+
+ beforeAll(async () => {
+ const workPolicies = [
+ ['ON_SITE', 'HYBRID'],
+ ['HYBRID'],
+ ['REMOTE_WORK'],
+ [],
+ ];
+
+ for (const workPolicy of workPolicies) {
+ const name = `mcp-group-by-work-policy-${randomUUID()}`;
+ const company = await executeWorkspaceTool<CreatedRecord>(
+ TOOL_NAMES.createCompany,
+ { name, workPolicy },
+ );
+
+ createdCompanyIds.push(company.id);
+ createdCompanyNames.push(name);
+ }
+ });
+
+ afterAll(async () => {
+ if (createdCompanyIds.length > 0) {
+ await deleteRecordsByIds('company', createdCompanyIds);
+ }
+ });
+
+ it('counts each selected value and preserves the empty-array null group', async () => {
+ const result = await executeWorkspaceTool<GroupByResult>(
+ TOOL_NAMES.groupByCompanies,
+ {
+ groupBy: [{ workPolicy: { unnest: true } }],
+ aggregateOperation: 'COUNT',
+ name: { in: createdCompanyNames },
+ },
+ );
+
+ expect(result.dimensionLabels).toEqual(['workPolicy']);
+ expect(result.aggregation).toBe('COUNT');
+ expect(result.groupCount).toBe(4);
+ expect(result.groups).toHaveLength(4);
+
+ const countsByWorkPolicy = Object.fromEntries(
+ result.groups.map((group) => [
+ String(group.dimensions[0]),
+ Number(group.value),
+ ]),
+ );
+
+ expect(countsByWorkPolicy).toEqual({
+ HYBRID: 2,
+ ON_SITE: 1,
+ REMOTE_WORK: 1,
+ null: 1,
+ });
+ });
+
+ it('keeps whole-array grouping as the default', async () => {
+ const result = await executeWorkspaceTool<GroupByResult>(
+ TOOL_NAMES.groupByCompanies,
+ {
+ groupBy: [{ workPolicy: true }],
+ aggregateOperation: 'COUNT',
+ name: { in: createdCompanyNames },
+ },
+ );
+
+ expect(result.dimensionLabels).toEqual(['workPolicy']);
+ expect(result.aggregation).toBe('COUNT');
+ expect(result.groupCount).toBe(4);
+ expect(result.groups).toHaveLength(4);
+ expect(result.groups.map((group) => Number(group.value))).toEqual([
+ 1, 1, 1, 1,
+ ]);
+ });
+ });
});