The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Validate static tool arguments against their input schema (#28202)
Paul Rastoin934f9f998e54
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/providers/__tests__/role-tool.provider.spec.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/providers/__tests__/role-tool.provider.spec.tsindex b07225ca9ca..dc7f8560b92 100644--- a/packages/twenty-server/src/engine/core-modules/tool-provider/providers/__tests__/role-tool.provider.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/providers/__tests__/role-tool.provider.spec.ts@@ -15,6 +15,13 @@ import { type UserRoleService } from 'src/engine/metadata-modules/user-role/userconst workspaceId = 'workspace-id';const callerRoleId = 'caller-role-id';const callerUserWorkspaceId = 'caller-user-workspace-id';+const otherRoleId = '0f1e2d3c-4b5a-4968-8776-655443322110';+const supportRoleId = '1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d';+const targetMemberId = '2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e';+const objectMetadataId = '3c4d5e6f-7a8b-4c9d-8e1f-2a3b4c5d6e7f';+const ownerFieldMetadataId = '4d5e6f7a-8b9c-4d0e-9f2a-3b4c5d6e7f80';+const workspaceMemberIdFieldMetadataId = '5e6f7a8b-9c0d-4e1f-8a3b-4c5d6e7f8091';+const predicateGroupId = '6f7a8b9c-0d1e-4f2a-9b4c-5d6e7f8091a2';const buildProvider = (options?: { hasRolesPermission?: boolean }) => {const roleService = {@@ -26,7 +33,7 @@ const buildProvider = (options?: { hasRolesPermission?: boolean }) => {const userRoleService = {assignRoleToWorkspaceMember: jest.fn().mockResolvedValue({workspaceMember: {- id: 'target-member-id',+ id: targetMemberId,userId: 'target-user-id',name: { firstName: 'Jane', lastName: 'Doe' },},@@ -283,14 +290,14 @@ describe('RoleToolProvider', () => {const { provider, roleService } = buildProvider();roleService.updateRole.mockResolvedValue({- id: 'other-role-id',+ id: otherRoleId,label: 'Support L1',});const output = await provider.executeStaticTool('update_role',{- roleId: 'other-role-id',+ roleId: otherRoleId,update: { canUpdateAllSettings: false, label: 'Support L1' },},context,@@ -300,7 +307,7 @@ describe('RoleToolProvider', () => {expect(roleService.updateRole).toHaveBeenCalledWith({workspaceId,input: {- id: 'other-role-id',+ id: otherRoleId,update: { canUpdateAllSettings: false, label: 'Support L1' },},actingRoleIds: [callerRoleId],@@ -310,11 +317,11 @@ describe('RoleToolProvider', () => {it('forwards every role of the caller config for lockout protection', async () => {const { provider, roleService } = buildProvider();- roleService.updateRole.mockResolvedValue({ id: 'other-role-id' });+ roleService.updateRole.mockResolvedValue({ id: otherRoleId });await provider.executeStaticTool('update_role',- { roleId: 'other-role-id', update: { canUpdateAllSettings: false } },+ { roleId: otherRoleId, update: { canUpdateAllSettings: false } },{...context,rolePermissionConfig: {@@ -337,11 +344,11 @@ describe('RoleToolProvider', () => {it('forwards no caller role when the config bypasses permission checks', async () => {const { provider, roleService } = buildProvider();- roleService.updateRole.mockResolvedValue({ id: 'other-role-id' });+ roleService.updateRole.mockResolvedValue({ id: otherRoleId });await provider.executeStaticTool('update_role',- { roleId: 'other-role-id', update: { canUpdateAllSettings: false } },+ { roleId: otherRoleId, update: { canUpdateAllSettings: false } },{...context,rolePermissionConfig: { shouldBypassPermissionChecks: true },@@ -360,19 +367,19 @@ describe('RoleToolProvider', () => {const { provider, roleService } = buildProvider();roleService.deleteRole.mockResolvedValue({- id: 'other-role-id',+ id: otherRoleId,label: 'Support',});const output = await provider.executeStaticTool('delete_role',- { roleId: 'other-role-id' },+ { roleId: otherRoleId },context,);expect(output.success).toBe(true);expect(roleService.deleteRole).toHaveBeenCalledWith({- roleId: 'other-role-id',+ roleId: otherRoleId,workspaceId,actingRoleIds: [callerRoleId],});@@ -385,15 +392,15 @@ describe('RoleToolProvider', () => {const output = await provider.executeStaticTool('assign_role_to_workspace_member',- { workspaceMemberId: 'target-member-id', roleId: 'other-role-id' },+ { workspaceMemberId: targetMemberId, roleId: otherRoleId },context,);expect(output.success).toBe(true);expect(userRoleService.assignRoleToWorkspaceMember).toHaveBeenCalledWith({workspaceId,- workspaceMemberId: 'target-member-id',- roleId: 'other-role-id',+ workspaceMemberId: targetMemberId,+ roleId: otherRoleId,actingUserWorkspaceId: callerUserWorkspaceId,});});@@ -405,7 +412,7 @@ describe('RoleToolProvider', () => {objectPermissionService.upsertObjectPermissions.mockResolvedValue([{- objectMetadataId: 'object-metadata-id',+ objectMetadataId: objectMetadataId,canReadObjectRecords: true,canUpdateObjectRecords: false,canSoftDeleteObjectRecords: false,@@ -416,10 +423,10 @@ describe('RoleToolProvider', () => {const output = await provider.executeStaticTool('upsert_object_permissions',{- roleId: 'support-role-id',+ roleId: supportRoleId,objectPermissions: [{- objectMetadataId: 'object-metadata-id',+ objectMetadataId: objectMetadataId,canReadObjectRecords: true,canUpdateObjectRecords: false,canSoftDeleteObjectRecords: false,@@ -436,10 +443,10 @@ describe('RoleToolProvider', () => {).toHaveBeenCalledWith({workspaceId,input: {- roleId: 'support-role-id',+ roleId: supportRoleId,objectPermissions: [{- objectMetadataId: 'object-metadata-id',+ objectMetadataId: objectMetadataId,canReadObjectRecords: true,canUpdateObjectRecords: false,canSoftDeleteObjectRecords: false,@@ -458,18 +465,17 @@ describe('RoleToolProvider', () => {const output = await provider.executeStaticTool('upsert_row_level_permission_rules',{- roleId: 'support-role-id',- objectMetadataId: 'object-metadata-id',+ roleId: supportRoleId,+ objectMetadataId: objectMetadataId,predicates: [{- fieldMetadataId: 'owner-field-metadata-id',+ fieldMetadataId: ownerFieldMetadataId,operand: 'IS',- workspaceMemberFieldMetadataId:- 'workspace-member-id-field-metadata-id',- rowLevelPermissionPredicateGroupId: 'group-id',+ workspaceMemberFieldMetadataId: workspaceMemberIdFieldMetadataId,+ rowLevelPermissionPredicateGroupId: predicateGroupId,},],- predicateGroups: [{ id: 'group-id', logicalOperator: 'AND' }],+ predicateGroups: [{ id: predicateGroupId, logicalOperator: 'AND' }],},context,);@@ -480,13 +486,13 @@ describe('RoleToolProvider', () => {).toHaveBeenCalledWith({workspaceId,input: expect.objectContaining({- roleId: 'support-role-id',- objectMetadataId: 'object-metadata-id',+ roleId: supportRoleId,+ objectMetadataId: objectMetadataId,predicateGroups: [expect.objectContaining({- id: 'group-id',+ id: predicateGroupId,logicalOperator: 'AND',- objectMetadataId: 'object-metadata-id',+ objectMetadataId: objectMetadataId,}),],}),diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/utils/__tests__/execute-tool-from-tool-set.util.spec.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/utils/__tests__/execute-tool-from-tool-set.util.spec.tsnew file mode 100644index 00000000000..b9d0f88b773--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/utils/__tests__/execute-tool-from-tool-set.util.spec.ts@@ -0,0 +1,83 @@+import { jsonSchema, type ToolSet } from 'ai';+import { ToolCategory } from 'twenty-shared/ai';+import { z } from 'zod';++import { executeToolFromToolSet } from 'src/engine/core-modules/tool-provider/utils/execute-tool-from-tool-set.util';++const SUCCESS_OUTPUT = { success: true, message: 'Done' };++const buildToolSet = (tool: ToolSet[string]): ToolSet => ({+ create_agent: tool,+});++describe('executeToolFromToolSet', () => {+ it('should pass the parsed arguments to the tool', async () => {+ const execute = jest.fn().mockResolvedValue(SUCCESS_OUTPUT);++ const output = await executeToolFromToolSet(+ buildToolSet({+ inputSchema: z.object({+ label: z.string(),+ modelId: z.string().default('default-model'),+ }),+ execute,+ }),+ 'create_agent',+ { label: 'Support agent', unknownKey: 'dropped' },+ ToolCategory.AGENT,+ );++ expect(output).toEqual(SUCCESS_OUTPUT);+ expect(execute).toHaveBeenCalledTimes(1);+ expect(execute).toHaveBeenCalledWith(+ { label: 'Support agent', modelId: 'default-model' },+ expect.anything(),+ );+ });++ it('should refuse arguments that do not match the input schema', async () => {+ const execute = jest.fn();++ const output = await executeToolFromToolSet(+ buildToolSet({+ inputSchema: z.object({ label: z.string(), roleId: z.uuid() }),+ execute,+ }),+ 'create_agent',+ { label: 42, roleId: 'not-a-uuid' },+ ToolCategory.AGENT,+ );++ expect(execute).not.toHaveBeenCalled();+ expect(output.success).toBe(false);+ expect(output.message).toBe('Invalid arguments for create_agent');+ expect(output.error).toContain('label');+ expect(output.error).toContain('roleId');+ });++ it('should pass the arguments unchanged when the schema has no validator', async () => {+ const execute = jest.fn().mockResolvedValue(SUCCESS_OUTPUT);+ const args = { label: 42 };++ await executeToolFromToolSet(+ buildToolSet({+ inputSchema: jsonSchema({ type: 'object' }),+ execute,+ }),+ 'create_agent',+ args,+ ToolCategory.AGENT,+ );++ expect(execute).toHaveBeenCalledTimes(1);+ expect(execute).toHaveBeenCalledWith(args, expect.anything());+ });++ it('should throw when the tool is not in the tool set', async () => {+ await expect(+ executeToolFromToolSet({}, 'create_agent', {}, ToolCategory.AGENT),+ ).rejects.toThrow(+ 'Tool "create_agent" not found in ToolSet for category "AGENT"',+ );+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/utils/execute-tool-from-tool-set.util.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/utils/execute-tool-from-tool-set.util.tsindex 862e1fb94eb..1b6654e19c8 100644--- a/packages/twenty-server/src/engine/core-modules/tool-provider/utils/execute-tool-from-tool-set.util.ts+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/utils/execute-tool-from-tool-set.util.ts@@ -1,5 +1,7 @@-import { type ToolExecuteFunction, type ToolSet } from 'ai';+import { asSchema, type ToolExecuteFunction, type ToolSet } from 'ai';import { type ToolCategory } from 'twenty-shared/ai';+import { isDefined } from 'twenty-shared/utils';+import { z } from 'zod';import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';@@ -18,14 +20,29 @@ export const executeToolFromToolSet = async ();}+ // The AI SDK only validates input for tools it calls itself, not for registry dispatch.+ const validation = await asSchema(tool.inputSchema).validate?.(args);++ if (isDefined(validation) && !validation.success) {+ return {+ success: false,+ message: `Invalid arguments for ${toolName}`,+ error: `The arguments do not match the input schema of ${toolName}: ${+ validation.error instanceof z.ZodError+ ? z.prettifyError(validation.error)+ : validation.error.message+ }`,+ };+ }+// ToolSet widens execute to a union no argument satisfies; these tools take no per-tool context.const execute = tool.execute as ToolExecuteFunction<- Record<string, unknown>,+ unknown,ToolOutput,undefined>;- return execute(args, {+ return execute(isDefined(validation) ? validation.value : args, {toolCallId: '',messages: [],context: undefined,diff --git a/packages/twenty-server/test/integration/ai/suites/__snapshots__/mcp-static-tool-input-validation.integration-spec.ts.snap b/packages/twenty-server/test/integration/ai/suites/__snapshots__/mcp-static-tool-input-validation.integration-spec.ts.snapnew file mode 100644index 00000000000..b3ba2f8c03f--- /dev/null+++ b/packages/twenty-server/test/integration/ai/suites/__snapshots__/mcp-static-tool-input-validation.integration-spec.ts.snap@@ -0,0 +1,28 @@+// Jest Snapshot v1, https://goo.gl/fbAQLP++exports[`MCP static tool input validation (integration) should refuse create_agent with a label of the wrong type without creating an agent 1`] = `+{+ "error": "The arguments do not match the input schema of create_agent: ✖ Invalid input: expected string, received number+ → at label",+ "message": "Invalid arguments for create_agent",+ "success": false,+}+`;++exports[`MCP static tool input validation (integration) should refuse create_agent with a role id that is not a UUID without creating an agent 1`] = `+{+ "error": "The arguments do not match the input schema of create_agent: ✖ Invalid UUID+ → at roleId",+ "message": "Invalid arguments for create_agent",+ "success": false,+}+`;++exports[`MCP static tool input validation (integration) should refuse delete_role with a role id that is not a UUID 1`] = `+{+ "error": "The arguments do not match the input schema of delete_role: ✖ Invalid UUID+ → at roleId",+ "message": "Invalid arguments for delete_role",+ "success": false,+}+`;diff --git a/packages/twenty-server/test/integration/ai/suites/mcp-static-tool-input-validation.integration-spec.ts b/packages/twenty-server/test/integration/ai/suites/mcp-static-tool-input-validation.integration-spec.tsnew file mode 100644index 00000000000..2d91d882c77--- /dev/null+++ b/packages/twenty-server/test/integration/ai/suites/mcp-static-tool-input-validation.integration-spec.ts@@ -0,0 +1,65 @@+import { executeToolThroughMcp } from 'test/integration/ai/utils/execute-tool-through-mcp.util';++const listAgentIds = async (): Promise<string[]> => {+ const output = await executeToolThroughMcp<{ agents: { id: string }[] }>({+ toolName: 'list_agents',+ toolArguments: {},+ });++ expect(output.success).toBe(true);++ return (output.result?.agents ?? []).map((agent) => agent.id);+};++describe('MCP static tool input validation (integration)', () => {+ let agentIdsBefore: string[];++ beforeAll(async () => {+ agentIdsBefore = await listAgentIds();+ });++ afterAll(async () => {+ const leakedAgentIds = (await listAgentIds()).filter(+ (id) => !agentIdsBefore.includes(id),+ );++ for (const id of leakedAgentIds) {+ await executeToolThroughMcp({+ toolName: 'delete_agent',+ toolArguments: { id },+ });+ }+ });++ it.each([+ ['a label of the wrong type', { label: 42, prompt: 'Watch new deals.' }],+ [+ 'a role id that is not a UUID',+ {+ label: 'Deal watcher',+ prompt: 'Watch new deals.',+ roleId: 'not-a-uuid',+ },+ ],+ ])(+ 'should refuse create_agent with %s without creating an agent',+ async (_, toolArguments) => {+ const output = await executeToolThroughMcp({+ toolName: 'create_agent',+ toolArguments,+ });++ expect(output).toMatchSnapshot();+ expect(await listAgentIds()).toEqual(agentIdsBefore);+ },+ );++ it('should refuse delete_role with a role id that is not a UUID', async () => {+ const output = await executeToolThroughMcp({+ toolName: 'delete_role',+ toolArguments: { roleId: 'not-a-uuid' },+ });++ expect(output).toMatchSnapshot();+ });+});diff --git a/packages/twenty-server/test/integration/ai/utils/execute-tool-through-mcp.util.ts b/packages/twenty-server/test/integration/ai/utils/execute-tool-through-mcp.util.tsnew file mode 100644index 00000000000..e6c7800cbb7--- /dev/null+++ b/packages/twenty-server/test/integration/ai/utils/execute-tool-through-mcp.util.ts@@ -0,0 +1,38 @@+import { randomUUID } from 'node:crypto';++import request from 'supertest';+import { jestExpectToBeDefined } from 'test/utils/jest-expect-to-be-defined.util.test';++import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';++export const executeToolThroughMcp = async <TResult = object>({+ toolName,+ toolArguments,+}: {+ toolName: string;+ toolArguments: Record<string, unknown>;+}): Promise<ToolOutput<TResult>> => {+ const response = await request(`http://localhost:${APP_PORT}`)+ .post('/mcp')+ .set('Authorization', `Bearer ${API_KEY_ACCESS_TOKEN}`)+ .set('Content-Type', 'application/json')+ .set('Accept', 'application/json')+ .send(+ JSON.stringify({+ jsonrpc: '2.0',+ method: 'tools/call',+ id: `call-${randomUUID()}`,+ params: {+ name: 'execute_tool',+ arguments: { toolName, arguments: toolArguments },+ },+ }),+ )+ .expect(200);++ const text = response.body.result?.content?.[0]?.text;++ jestExpectToBeDefined(text);++ return JSON.parse(text) as ToolOutput<TResult>;+};