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

20.5 KB
Raw Blame
import { Property } from '@activepieces/pieces-framework';
import {
  getAccessTokenOrThrow,
  HttpMethod,
  HttpMessageBody,
  HttpResponse,
  httpClient,
  AuthenticationType,
} from '@activepieces/pieces-common';
import { ClickupTask, ClickupWorkspace } from './models';
import { clickupAuth } from '../auth';

export const clickupCommon = {
  workspace_id: (required = true) =>
    Property.Dropdown({
      auth: clickupAuth,
      description: 'The ClickUp workspace to work in.',
      displayName: 'Workspace',
      required,
      refreshers: [],
      options: async ({ auth }) => {
        if (!auth) {
          return {
            disabled: true,
            placeholder: 'Connect your account first',
            options: [],
          };
        }
        const accessToken = getAccessTokenOrThrow(auth);
        const response = (
          await callClickUpApi<{
            teams: {
              id: string;
              name: string;
            }[];
          }>(HttpMethod.GET, 'team', accessToken, undefined)
        ).body;
        return {
          disabled: false,
          options: response.teams.map((workspace) => {
            return {
              label: workspace.name,
              value: workspace.id,
            };
          }),
        };
      },
    }),
  space_id: (required = true, multi = false) => {
    const Dropdown = multi ? Property.MultiSelectDropdown : Property.Dropdown;
    return Dropdown({
      auth: clickupAuth,
      description: 'A space in the selected workspace.',
      displayName: 'Space',
      required,
      refreshers: ['workspace_id'],
      options: async ({ auth, workspace_id }) => {
        if (!auth) {
          return {
            disabled: true,
            placeholder: 'Connect your account first',
            options: [],
          };
        }
        if (!workspace_id) {
          return {
            disabled: true,
            placeholder: 'Select a workspace first',
            options: [],
          };
        }
        const accessToken = getAccessTokenOrThrow(auth);
        const response = await listSpaces(accessToken, workspace_id as string);
        return {
          disabled: false,
          options: response.spaces.map((space) => {
            return {
              label: space.name,
              value: space.id,
            };
          }),
        };
      },
    });
  },
  list_id: (required = true, multi = false) => {
    const Dropdown = multi ? Property.MultiSelectDropdown : Property.Dropdown;
    return Dropdown({
      auth: clickupAuth,
      description: 'Lists from every folder in the space are shown.',
      displayName: 'List',
      required,
      refreshers: ['space_id', 'workspace_id', 'folder_id'],
      options: async ({ auth, space_id }) => {
        if (!auth) {
          return {
            disabled: true,
            placeholder: 'Connect your account first',
            options: [],
          };
        }
        const spaceIds = toSpaceIds(space_id);
        if (spaceIds.length === 0) {
          return {
            disabled: true,
            placeholder: 'Select a space first',
            options: [],
          };
        }

        const accessToken = getAccessTokenOrThrow(auth);
        const listsPerSpace = await Promise.all(
          spaceIds.map((spaceId) => listAllLists(accessToken, spaceId))
        );
        const lists = listsPerSpace.flat();

        return {
          disabled: false,
          options: lists.map((list) => {
            return {
              label: list.name,
              value: list.id,
            };
          }),
        };
      },
    });
  },
  task_id: (required = true, label: string | undefined = undefined) =>
    Property.Dropdown({
      auth: clickupAuth,
      description: 'Open tasks in the selected list, up to the first 1,000.',
      displayName: label ?? 'Task',
      required,
      defaultValue: null,
      refreshers: ['space_id', 'list_id', 'workspace_id', 'folder_id'],
      options: async ({ auth, space_id, list_id }) => {
        if (!auth) {
          return {
            disabled: true,
            placeholder: 'Connect your account first',
            options: [],
          };
        }
        if (!space_id) {
          return {
            disabled: true,
            placeholder: 'Select a space first',
            options: [],
          };
        }
        if (!list_id) {
          return {
            disabled: true,
            placeholder: 'Select a list first',
            options: [],
          };
        }
        const accessToken = getAccessTokenOrThrow(auth);
        const response = await listTasks(accessToken, list_id as string);
        return {
          disabled: false,
          options: response.tasks.map((task) => {
            return {
              label: task.name,
              value: task.id,
            };
          }),
        };
      },
    }),
  folder_id: (required = false, multi = false) => {
    const Dropdown = multi ? Property.MultiSelectDropdown : Property.Dropdown;
    return Dropdown({
      auth: clickupAuth,
      description: 'A folder in the selected space.',
      displayName: 'Folder',
      refreshers: ['space_id', 'workspace_id'],
      required,
      options: async ({ auth, space_id, workspace_id }) => {
        if (!auth) {
          return {
            disabled: true,
            placeholder: 'Connect your account first',
            options: [],
          };
        }
        if (!workspace_id) {
          return {
            disabled: true,
            placeholder: 'Select a workspace first',
            options: [],
          };
        }
        const spaceIds = toSpaceIds(space_id);
        if (spaceIds.length === 0) {
          return {
            disabled: true,
            placeholder: 'Select a space first',
            options: [],
          };
        }
        const accessToken = getAccessTokenOrThrow(auth);
        const foldersPerSpace = await Promise.all(
          spaceIds.map((spaceId) => listFolders(accessToken, spaceId))
        );
        return {
          disabled: false,
          options: foldersPerSpace
            .flatMap((response) => response.folders)
            .map((folder) => {
              return {
                label: folder.name,
                value: folder.id,
              };
            }),
        };
      },
    });
  },
  field_id: (required = false) =>
    Property.Dropdown({
      auth: clickupAuth,
      displayName: 'Field',
      description: 'A custom field on the selected list.',
      refreshers: ['task_id', 'list_id'],
      defaultValue: null,
      required,
      options: async ({ auth, task_id, list_id }) => {
        if (!auth) {
          return {
            disabled: true,
            placeholder: 'Connect your account first',
            options: [],
          };
        }
        if (!task_id || !list_id) {
          return {
            disabled: true,
            placeholder: 'Select a list and task first',
            options: [],
          };
        }
        const accessToken = getAccessTokenOrThrow(auth);
        const response = await listAccessibleCustomFields(
          accessToken,
          list_id as string
        );
        return {
          disabled: false,
          options: response.fields.map((field) => {
            return {
              label: field.name,
              value: field.id,
            };
          }),
        };
      },
    }),
  status_id: (required = false, multi = false) => {
    const Dropdown = multi ? Property.MultiSelectDropdown : Property.Dropdown;
    return Dropdown({
      auth: clickupAuth,
      description: 'Statuses come from the selected list.',
      displayName: 'Status',
      refreshers: ['list_id'],
      required,
      options: async ({ auth, list_id }) => {
        if (!auth) {
          return {
            disabled: true,
            placeholder: 'Connect your account first',
            options: [],
          };
        }
        if (!list_id) {
          return {
            disabled: true,
            placeholder: 'Select a list first',
            options: [],
          };
        }
        const accessToken = getAccessTokenOrThrow(auth);
        const response = await getStatuses(accessToken, list_id as string);
        return {
          disabled: false,
          options: response.statuses.map((status) => {
            return {
              label: status.status,
              value: status.status,
            };
          }),
        };
      },
    });
  },
  priority_id: (required = false) =>
    Property.StaticDropdown({
      displayName: 'Priority',
      defaultValue: null,
      description: 'How urgent the task is.',
      required,
      options: {
        options: [
          {
            label: 'Urgent',
            value: 1,
          },
          {
            label: 'High',
            value: 2,
          },
          {
            label: 'Normal',
            value: 3,
          },
          {
            label: 'Low',
            value: 4,
          },
        ],
      },
    }),
  assignee_id: (
    required = false,
    displayName = 'Assignees',
    description: string
  ) =>
    Property.MultiSelectDropdown({
      auth: clickupAuth,
      displayName: displayName,
      description: description,
      required,
      refreshers: ['workspace_id'],
      options: async ({ auth, workspace_id }) => {
        if (!auth) {
          return {
            disabled: true,
            placeholder: 'Connect your account first',
            options: [],
          };
        }
        if (!workspace_id) {
          return {
            disabled: true,
            placeholder: 'Select a workspace first',
            options: [],
          };
        }
        const accessToken = getAccessTokenOrThrow(auth);
        const response = await listWorkspaceMembers(
          accessToken,
          workspace_id as string
        );
        return {
          disabled: false,
          options: response.map((member) => {
            return {
              label: member.user.username,
              value: member.user.id,
            };
          }),
        };
      },
    }),
  single_assignee_id: (
    required = false,
    displayName = 'Assignee',
    description: string
  ) =>
    Property.Dropdown({
      auth: clickupAuth,
      displayName: displayName,
      description: description,
      required,
      refreshers: ['workspace_id'],
      options: async ({ auth, workspace_id }) => {
        if (!auth) {
          return {
            disabled: true,
            placeholder: 'Connect your account first',
            options: [],
          };
        }
        if (!workspace_id) {
          return {
            disabled: true,
            placeholder: 'Select a workspace first',
            options: [],
          };
        }
        const accessToken = getAccessTokenOrThrow(auth);
        const response = await listWorkspaceMembers(
          accessToken,
          workspace_id as string
        );
        return {
          disabled: false,
          options: response.map((member) => {
            return {
              label: member.user.username,
              value: member.user.id,
            };
          }),
        };
      },
    }),
  template_id: (required = false) =>
    Property.Dropdown({
      auth: clickupAuth,
      displayName: 'Template',
      required,
      description: 'A task template saved in the workspace.',
      refreshers: ['workspace_id'],
      options: async ({ auth, workspace_id }) => {
        if (!auth) {
          return {
            disabled: true,
            placeholder: 'Connect your account first',
            options: [],
          };
        }
        if (!workspace_id) {
          return {
            disabled: true,
            placeholder: 'Select a workspace first',
            options: [],
          };
        }
        const accessToken = getAccessTokenOrThrow(auth);
        const response = await listWorkspaceTemplates(
          accessToken,
          workspace_id as string
        );
        return {
          disabled: false,
          options: response.templates.map((template) => {
            return {
              label: template.name,
              value: template.id,
            };
          }),
        };
      },
    }),
  channel_id: (required = false) =>
    Property.Dropdown({
      auth: clickupAuth,
      displayName: 'Channel',
      required,
      description: 'A chat channel in the selected workspace.',
      refreshers: ['workspace_id'],
      options: async ({ auth, workspace_id }) => {
        if (!auth) {
          return {
            disabled: true,
            placeholder: 'Connect your account first',
            options: [],
          };
        }
        if (!workspace_id) {
          return {
            disabled: true,
            placeholder: 'Select a workspace first',
            options: [],
          };
        }
        const accessToken = getAccessTokenOrThrow(auth);
        const response = await retrieveChannels(
          accessToken,
          workspace_id as string
        );
        return {
          disabled: false,
          options: response.data
            .filter((channel) => channel.name && channel.name !== '')
            .map((channel) => {
              return {
                label: channel.name,
                value: channel.id,
              };
            }),
        };
      },
    }),
  optionalBoolean: ({
    displayName,
    description,
  }: {
    displayName: string;
    description: string;
  }) =>
    Property.StaticDropdown<string, false>({
      displayName,
      description,
      required: false,
      options: {
        disabled: false,
        options: [
          { label: 'Yes', value: 'yes' },
          { label: 'No', value: 'no' },
          { label: 'Leave unchanged', value: 'unchanged' },
        ],
      },
    }),
  optionalBooleanValue,
};

function optionalBooleanValue(value: unknown): boolean | undefined {
  const normalized =
    typeof value === 'string' ? value.trim().toLowerCase() : value;
  if (normalized === true || normalized === 'yes' || normalized === 'true') {
    return true;
  }
  if (normalized === false || normalized === 'no' || normalized === 'false') {
    return false;
  }
  return undefined;
}

async function listWorkspaces(accessToken: string) {
  return (
    await callClickUpApi<{ teams: ClickupWorkspace[] }>(
      HttpMethod.GET,
      'team',
      accessToken,
      undefined
    )
  ).body;
}

async function getWorkspace(accessToken: string, workspaceId: string) {
  const { teams } = await listWorkspaces(accessToken);
  return teams.find((workspace) => workspace.id === workspaceId);
}

async function listWorkspaceMembers(accessToken: string, workspaceId: string) {
  const workspace = await getWorkspace(accessToken, workspaceId);
  return workspace?.members ?? [];
}

async function listWorkspaceTemplates(
  accessToken: string,
  workspaceId: string
) {
  return (
    await callClickUpApi<{
      templates: {
        id: string;
        name: string;
      }[];
    }>(
      HttpMethod.GET,
      `team/${workspaceId}/taskTemplate`,
      accessToken,
      undefined,
      { page: '0' }
    )
  ).body;
}

export async function listSpaces(accessToken: string, workspaceId: string) {
  return (
    await callClickUpApi<{
      spaces: {
        id: string;
        name: string;
      }[];
    }>(HttpMethod.GET, `team/${workspaceId}/space`, accessToken, undefined)
  ).body;
}

export async function listAllLists(accessToken: string, spaceId: string) {
  const responseFolders = await listFolders(accessToken, spaceId);
  const promises: Promise<{ lists: { id: string; name: string }[] }>[] = [
    listFolderlessList(accessToken, spaceId),
  ];
  for (let i = 0; i < responseFolders.folders.length; ++i) {
    promises.push(listLists(accessToken, responseFolders.folders[i].id));
  }
  const listsResponses = await Promise.all(promises);

  let lists: { name: string; id: string }[] = [];
  for (let i = 0; i < listsResponses.length; ++i) {
    lists = [...lists, ...listsResponses[i].lists];
  }

  return lists;
}

export async function listLists(accessToken: string, folderId: string) {
  return (
    await callClickUpApi<{
      lists: {
        id: string;
        name: string;
      }[];
    }>(HttpMethod.GET, `folder/${folderId}/list`, accessToken, undefined)
  ).body;
}
async function getStatuses(accessToken: string, listId: string) {
  return (
    await callClickUpApi<{
      statuses: {
        id: string;
        status: string;
      }[];
    }>(HttpMethod.GET, `list/${listId}`, accessToken, undefined)
  ).body;
}

export async function listFolders(accessToken: string, spaceId: string) {
  return (
    await callClickUpApi<{
      folders: {
        id: string;
        name: string;
      }[];
    }>(HttpMethod.GET, `space/${spaceId}/folder`, accessToken, undefined)
  ).body;
}

export async function listAccessibleCustomFields(
  accessToken: string,
  listId: string
) {
  return (
    await callClickUpApi<{
      fields: {
        id: string;
        name: string;
        type: string;
        type_config: Record<string, unknown>;
        date_created: string;
        hide_from_guests: false;
      }[];
    }>(HttpMethod.GET, `list/${listId}/field`, accessToken, undefined)
  ).body;
}

async function listFolderlessList(accessToken: string, spaceId: string) {
  return (
    await callClickUpApi<{
      lists: {
        id: string;
        name: string;
      }[];
    }>(HttpMethod.GET, `space/${spaceId}/list`, accessToken, undefined)
  ).body;
}

export async function listTags(accessToken: string, spaceId: string) {
  return (
    await callClickUpApi<{
      tags: {
        id: string;
        name: string;
      }[];
    }>(HttpMethod.GET, `space/${spaceId}/tag`, accessToken, undefined)
  ).body;
}

export async function listTasks(accessToken: string, listId: string) {
  const tasks = await listTaskPages({ accessToken, listId, page: 0 });
  return { tasks };
}

export async function retrieveChannels(
  accessToken: string,
  workspaceId: string
) {
  return (
    await callClickUpApi3<{
      data: {
        id: string;
        name: string;
      }[];
    }>(
      HttpMethod.GET,
      `workspaces/${workspaceId}/chat/channels`,
      accessToken,
      undefined
    )
  ).body;
}

export async function callClickupGetTask(accessToken: string, taskId: string) {
  return (
    await callClickUpApi<ClickupTask>(
      HttpMethod.GET,
      `task/${taskId}`,
      accessToken,
      undefined
    )
  ).body;
}

export async function callClickUpApi<T extends HttpMessageBody = any>(
  method: HttpMethod,
  apiUrl: string,
  accessToken: string,
  body: any | undefined,
  queryParams: any | undefined = undefined,
  headers: any | undefined = undefined
): Promise<HttpResponse<T>> {
  headers = {
    accept: 'application/json',
    ...headers,
  };

  return await httpClient.sendRequest<T>({
    method: method,
    url: `https://api.clickup.com/api/v2/${apiUrl}`,
    authentication: {
      type: AuthenticationType.BEARER_TOKEN,
      token: accessToken,
    },
    headers,
    body: method === 'GET' ? undefined : body,
    queryParams,
  });
}

export async function callClickUpApi3<T extends HttpMessageBody = any>(
  method: HttpMethod,
  apiUrl: string,
  accessToken: string,
  body: any | undefined,
  queryParams: any | undefined = undefined,
  headers: any | undefined = {}
): Promise<HttpResponse<T>> {
  headers = {
    accept: 'application/json',
    ...headers,
  };

  return await httpClient.sendRequest<T>({
    method: method,
    url: `https://api.clickup.com/api/v3/${apiUrl}`,
    authentication: {
      type: AuthenticationType.BEARER_TOKEN,
      token: accessToken,
    },
    headers,
    body: method === 'GET' ? undefined : body,
    queryParams,
  });
}

function toSpaceIds(spaceId: unknown): string[] {
  if (Array.isArray(spaceId)) {
    return spaceId.filter(
      (id): id is string => typeof id === 'string' && id !== ''
    );
  }
  if (typeof spaceId === 'string' && spaceId !== '') {
    return [spaceId];
  }
  return [];
}

async function listTaskPages({
  accessToken,
  listId,
  page,
}: {
  accessToken: string;
  listId: string;
  page: number;
}): Promise<TaskOption[]> {
  const { tasks, last_page } = (
    await callClickUpApi<{ tasks: TaskOption[]; last_page: boolean }>(
      HttpMethod.GET,
      `list/${listId}/task`,
      accessToken,
      undefined,
      { page: String(page) }
    )
  ).body;
  if (last_page || tasks.length === 0 || page + 1 >= MAX_TASK_PAGES) {
    return tasks;
  }
  const nextTasks = await listTaskPages({
    accessToken,
    listId,
    page: page + 1,
  });
  return [...tasks, ...nextTasks];
}

const MAX_TASK_PAGES = 10;

type TaskOption = {
  id: string;
  name: string;
};