Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

6.8 KB
Raw Blame
import {
  PropertyType,
  PiecePropertyMap,
  PieceProperty,
} from '@activepieces/pieces-framework';
import { FlowTrigger, McpPropertyType } from '@activepieces/shared';
import { t } from 'i18next';
import { useForm, useFormContext } from 'react-hook-form';

import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from '@/components/ui/dialog';
import { Form } from '@/components/ui/form';
import { ScrollArea } from '@/components/ui/scroll-area';

import { GenericPropertiesForm } from '../../piece-properties/generic-properties-form';
import { testStepHooks } from '../utils/test-step-hooks';

type McpToolTestingDialogProps = {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onTestingSuccess: () => void;
};

interface McpFormField {
  name: string;
  description?: string;
  required: boolean;
  type: McpPropertyType;
  defaultValue?: any;
}
function mapMcpTypeToPropertyType(mcpType: McpPropertyType): PropertyType {
  switch (mcpType) {
    case McpPropertyType.NUMBER:
      return PropertyType.NUMBER;
    case McpPropertyType.BOOLEAN:
      return PropertyType.CHECKBOX;
    case McpPropertyType.OBJECT:
      return PropertyType.OBJECT;
    case McpPropertyType.DATE:
      return PropertyType.DATE_TIME;
    case McpPropertyType.ARRAY:
      return PropertyType.ARRAY;
    case McpPropertyType.TEXT:
    default:
      return PropertyType.SHORT_TEXT;
  }
}

// toggling the dynamic (f(x)) input mode on the inputSchema array property
// replaces its form value with `{}`, so this must not assume the raw value is still an array
function toMcpFormFields(rawInputSchema: unknown): McpFormField[] {
  return Array.isArray(rawInputSchema) ? rawInputSchema : [];
}

function McpToolTestingDialog({
  open,
  onOpenChange,
  onTestingSuccess,
}: McpToolTestingDialogProps) {
  const form = useFormContext<FlowTrigger>();
  const formValues = form.getValues();
  const formProps = toMcpFormFields(formValues.settings.input.inputSchema);
  const { mutate: saveMockAsSampleData, isPending: isSavingMockdata } =
    testStepHooks.useSaveMockData({
      onSuccess: () => {
        onTestingSuccess();
        onOpenChange(false);
      },
    });

  const testingForm = useForm<Record<string, any>>({
    shouldFocusError: true,
    defaultValues: formProps
      .filter((field: McpFormField) => field.name.trim() !== '')
      .reduce((acc, field: McpFormField) => {
        acc[field.name] = field.type === McpPropertyType.BOOLEAN ? false : '';
        return acc;
      }, {} as Record<string, any>),
    resolver: (values) => {
      const errors = formProps.reduce((acc, field: McpFormField) => {
        if (
          field.required &&
          field.type !== McpPropertyType.BOOLEAN &&
          !values[field.name]
        ) {
          acc[field.name] = {
            type: 'required',
            message: t('{field} is required', { field: field.name }),
          };
        }
        return acc;
      }, {} as Record<string, { type: string; message: string }>);

      if (Object.keys(errors).length === 0) {
        return { values, errors: {} as Record<string, never> };
      }
      return {
        values: {} as Record<string, never>,
        errors,
      };
    },
    mode: 'onChange',
  });

  function fixProperty(key: string): string {
    return key.replace(/[\s/@-]+/g, '_');
  }

  const pieceProps = formProps.reduce((acc, field: McpFormField) => {
    const pieceProperty = {
      displayName: field.name,
      description: field.description || '',
      required: field.required,
      type: mapMcpTypeToPropertyType(field.type),
      defaultValue: field.defaultValue,
    } as PieceProperty;

    acc[field.name] = pieceProperty;
    return acc;
  }, {} as PiecePropertyMap);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="w-full max-w-xl flex flex-col max-h-[90vh]">
        <DialogHeader>
          <DialogTitle className="px-0.5">{t('Set Sample Data')}</DialogTitle>
          <DialogDescription className="px-0.5">
            {t('Provide sample values for testing this tool trigger.')}
          </DialogDescription>
        </DialogHeader>

        <Form {...testingForm}>
          <form
            className="grid space-y-4"
            onSubmit={testingForm.handleSubmit((data) => {
              const cleanedData = Object.fromEntries(
                Object.entries(data)
                  .filter(([key, _]) => key.trim() !== '')
                  .map(([key, value]) => [fixProperty(key), value]),
              );
              saveMockAsSampleData(cleanedData);
            })}
          >
            <ScrollArea className="flex-1 max-h-[50vh]">
              <div className="py-4">
                {Object.keys(pieceProps).length > 0 ? (
                  <div className="space-y-4">
                    {Object.entries(pieceProps).map(
                      ([fieldName, fieldProps]) => {
                        const fieldError =
                          testingForm.formState.errors[fieldName];

                        return (
                          <div
                            key={fieldName}
                            className="grid space-y-2 px-0.5"
                          >
                            <GenericPropertiesForm
                              props={{ [fieldName]: fieldProps }}
                              propertySettings={null}
                              dynamicPropsInfo={null}
                              prefixValue=""
                              useMentionTextInput={false}
                              disabled={false}
                            />

                            {fieldError && (
                              <p className="text-xs text-danger-11 font-medium">
                                {fieldError.message?.toString()}
                              </p>
                            )}
                          </div>
                        );
                      },
                    )}
                  </div>
                ) : (
                  <div className="p-4 rounded-xl text-center">
                    <p className="text-sm text-gray-11">
                      {t('No input fields defined in the schema')}
                    </p>
                  </div>
                )}
              </div>
            </ScrollArea>
            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={() => onOpenChange(false)}
                disabled={isSavingMockdata}
              >
                {t('Cancel')}
              </Button>
              <Button type="submit" loading={isSavingMockdata}>
                {t('Use Sample Data')}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}

export { McpToolTestingDialog, toMcpFormFields };