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

10.6 KB
Raw Blame
import {
  acceptsRequestBody,
  AuthenticationType,
  httpClient,
  HttpHeaders,
  HttpMessageBody,
  HttpMethod,
  HttpRequest,
  HttpResponse,
  QueryParams,
  toFailsafeOutput,
} from '@activepieces/pieces-common';
import { httpOauth2Auth } from '../..';
import {
  createAction,
  DynamicPropsValue,
  Property,
} from '@activepieces/pieces-framework';
import { assertNotNullOrUndefined, isNil } from '@activepieces/pieces-framework';
import FormData from 'form-data';
import { ProxyAgent } from 'undici';

export const httpOauth2RequestAction = createAction({
  audience: 'both',
  auth: httpOauth2Auth,
  name: 'send-oauth2-request',
  classification: 'WRITE',
  displayName: 'Send an OAuth2 Request',
  description: 'Call any URL with the OAuth2 token from your connection.',
  aiMetadata: { description: 'Calls any HTTP endpoint with an OAuth 2.0 bearer token injected from the connection, choosing the method (GET/POST/PUT/PATCH/DELETE) and body mode (none, JSON, raw, or form-data), optionally routing through an HTTP proxy or returning the error text instead of throwing when the failsafe option is on. Prefer it over the core HTTP piece Send HTTP Request action only when the target API needs a managed OAuth2 token that Activepieces refreshes; it requires an OAuth2 connection set up with the authorize URL, token URL, and scopes, plus a full request URL. Not idempotent in general: the effect depends on the chosen method, and non-GET calls can create or change data on each call.', idempotent: false },
  props: {
    url: Property.ShortText({
      displayName: 'URL',
      description: 'The full URL to call, including https:// or http://',
      placeholder: 'https://api.example.com/v1/users',
      required: true,
    }),
    method: Property.StaticDropdown({
      displayName: 'Method',
      description: 'GET reads data, POST creates it.',
      required: true,
      defaultValue: HttpMethod.GET,
      options: {
        options: [
          { value: HttpMethod.GET, label: 'GET' },
          { value: HttpMethod.POST, label: 'POST' },
          { value: HttpMethod.PUT, label: 'PUT' },
          { value: HttpMethod.PATCH, label: 'PATCH' },
          { value: HttpMethod.DELETE, label: 'DELETE' },
        ],
      },
    }),
    headers: Property.Object({
      displayName: 'Headers',
      description: 'Authorization headers are injected automatically from your connection.',
      required: false,
    }),
    queryParams: Property.Object({
      displayName: 'Query Parameters',
      description: 'Appended to the URL as ?key=value.',
      required: false,
    }),
    body_type: Property.Dropdown({
      displayName: 'Body Type',
      description: 'How to encode the request body.',
      required: false,
      defaultValue: 'none',
      auth: httpOauth2Auth,
      refreshers: ['method'],
      options: async ({ method }) => {
        if (!acceptsRequestBody(method as HttpMethod)) {
          return {
            disabled: true,
            placeholder: 'Not available for GET requests',
            options: [],
          };
        }
        return {
          disabled: false,
          options: [
            { label: 'None', value: 'none' },
            { label: 'JSON', value: 'json' },
            { label: 'Form Data', value: 'form_data' },
            { label: 'Raw', value: 'raw' },
          ],
        };
      },
    }),
    body: Property.DynamicProperties({
      displayName: 'Body',
      auth: httpOauth2Auth,
      refreshers: ['body_type', 'method'],
      required: false,
      props: async ({ body_type, method }) => {
        if (!body_type || !acceptsRequestBody(method as HttpMethod)) return {};

        const bodyTypeInput = body_type as unknown as string;

        const fields: DynamicPropsValue = {};

        switch (bodyTypeInput) {
          case 'none':
            break;
          case 'json':
            fields['data'] = Property.Json({
              displayName: 'JSON Body',
              required: true,
            });
            break;
          case 'raw':
            fields['data'] = Property.LongText({
              displayName: 'Raw Body',
              required: true,
            });
            break;
          case 'form_data':
            fields['data'] = Property.Object({
              displayName: 'Form Data',
              required: true,
            });
            break;
        }
        return fields;
      },
    }),
    use_proxy: Property.Checkbox({
      displayName: 'Use Proxy',
      defaultValue: false,
      description: 'Route this request through an HTTP proxy.',
      required: false,
      advanced: true,
    }),
    proxy_settings: Property.DynamicProperties({
      displayName: 'Proxy Settings',
      auth: httpOauth2Auth,
      refreshers: ['use_proxy'],
      required: false,
      advanced: true,
      props: async ({ use_proxy }) => {
        if (!use_proxy) return {};

        const fields: DynamicPropsValue = {};

        fields['proxy_host'] = Property.ShortText({
          displayName: 'Proxy Host',
          placeholder: 'proxy.example.com',
          required: true,
        });

        fields['proxy_port'] = Property.Number({
          displayName: 'Proxy Port',
          required: true,
        });

        fields['proxy_username'] = Property.ShortText({
          displayName: 'Proxy Username',
          required: false,
        });

        fields['proxy_password'] = Property.ShortText({
          displayName: 'Proxy Password',
          description: 'Stored in the flow and visible in exports.',
          required: false,
        });

        return fields;
      },
    }),
    failsafe: Property.Checkbox({
      displayName: 'Return Error as Output',
      description: 'On a failed request, output the error instead of failing the step.',
      required: false,
      advanced: true,
    }),
    timeout: Property.Number({
      displayName: 'Timeout',
      description: 'Seconds to wait for a response. Empty: up to the flow limit (10 min).',
      required: false,
      advanced: true,
    }),
  },
  propertyGroups: [
    {
      key: 'request',
      display: 'section',
      label: 'Request',
      icon: 'send',
      props: ['method', 'url', 'headers', 'queryParams'],
    },
    {
      key: 'payload',
      display: 'section',
      label: 'Data to send',
      icon: 'code',
      props: ['body_type', 'body'],
    },
  ],
  errorHandlingOptions: {
    continueOnFailure: { hide: true },
    retryOnFailure: { defaultValue: true },
  },
  async run(context) {
    const {
      method,
      url,
      headers,
      queryParams,
      body,
      body_type,
      timeout,
      failsafe,
      use_proxy,
    } = context.propsValue;
    const { auth } = context;

    assertNotNullOrUndefined(method, 'Method');
    assertNotNullOrUndefined(url, 'URL');

    const request: HttpRequest = {
      method,
      url,
      headers: headers as HttpHeaders,
      queryParams: queryParams as QueryParams,
      timeout: timeout ? timeout * 1000 : 0,
      authentication: {
        type: AuthenticationType.BEARER_TOKEN,
        token: auth.access_token,
      },
    };

    if (body) {
      const bodyInput = body['data'];
      if (body_type === 'form_data') {
        const formData = new FormData();
        for (const key in bodyInput) {
          formData.append(key, bodyInput[key]);
        }
        request.body = formData;
        request.headers = { ...request.headers, ...formData.getHeaders() };
      } else {
        request.body = bodyInput;
      }
    }

    try {
      if (use_proxy) {
        const proxySettings = context.propsValue.proxy_settings;
        assertNotNullOrUndefined(proxySettings, 'Proxy Settings');
        assertNotNullOrUndefined(proxySettings['proxy_host'], 'Proxy Host');
        assertNotNullOrUndefined(proxySettings['proxy_port'], 'Proxy Port');
        let proxyUrl;

        if (
          proxySettings['proxy_username'] &&
          proxySettings['proxy_password']
        ) {
          proxyUrl = `http://${proxySettings['proxy_username']}:${proxySettings['proxy_password']}@${proxySettings['proxy_host']}:${proxySettings['proxy_port']}`;
        } else {
          proxyUrl = `http://${proxySettings['proxy_host']}:${proxySettings['proxy_port']}`;
        }

        const proxyAgent = new ProxyAgent(proxyUrl);

        const proxyUrlWithParams = new URL(request.url);
        for (const [key, value] of Object.entries(
          (request.queryParams as Record<string, string>) ?? {}
        )) {
          proxyUrlWithParams.searchParams.append(key, value);
        }

        const proxyHeaders: Record<string, string> = {
          Authorization: `Bearer ${auth.access_token}`,
        };
        for (const [key, value] of Object.entries(request.headers ?? {})) {
          if (value !== undefined) {
            proxyHeaders[key] = Array.isArray(value) ? value.join(', ') : value;
          }
        }

        let proxyBody: BodyInit | undefined;
        if (
          request.method !== HttpMethod.GET &&
          request.method !== HttpMethod.HEAD &&
          !isNil(request.body)
        ) {
          if (request.body instanceof FormData) {
            proxyBody = request.body.getBuffer();
          } else if (typeof request.body === 'string') {
            proxyBody = request.body;
          } else {
            proxyBody = JSON.stringify(request.body);
            if (!('Content-Type' in proxyHeaders) && !('content-type' in proxyHeaders)) {
              proxyHeaders['Content-Type'] = 'application/json';
            }
          }
        }

        const proxiedResponse = await fetch(proxyUrlWithParams.toString(), {
          method: request.method.toString(),
          headers: proxyHeaders,
          body: proxyBody,
          dispatcher: proxyAgent,
          ...(request.timeout && request.timeout > 0
            ? { signal: AbortSignal.timeout(request.timeout) }
            : {}),
        } as RequestInit & { dispatcher: ProxyAgent });

        const proxyContentType = proxiedResponse.headers.get('content-type') ?? '';
        const proxyData = proxyContentType.includes('application/json')
          ? await proxiedResponse.json()
          : await proxiedResponse.text();
        return handleResponse(proxyData);
      }
      const response = await httpClient.sendRequest(request);
      return handleResponse(response);
    } catch (error) {
      if (failsafe) {
        return toFailsafeOutput({ error, requestBody: request.body });
      }

      throw error;
    }
  },
});

const handleResponse = (response: HttpResponse<HttpMessageBody>) => {
  if (
    response.headers &&
    response.headers['content-type'] === 'application/octet-stream'
  ) {
    return {
      ...response,
      bodyBase64: Buffer.from(response.body, 'binary').toString('base64'),
    };
  }
  return response;
};