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

7.4 KB
Raw Blame
import { createAction, Property } from '@activepieces/pieces-framework';
import { HttpMethod, httpClient, HttpRequest } from '@activepieces/pieces-common';
import { awsBedrockCombinedAuth } from '../auth';
import { getTemporaryCredentials, isOidcAuth } from '../common';
import { SignatureV4 } from '@smithy/signature-v4';
import { HttpRequest as AwsHttpRequest } from '@smithy/protocol-http';
import { Sha256 } from '@aws-crypto/sha256-js';

const AWS_BEDROCK_SERVICES = [
  { label: 'Bedrock (Control Plane)', value: 'bedrock' },
  { label: 'Bedrock Runtime (Inference)', value: 'bedrock-runtime' },
  { label: 'Bedrock Agent (Control Plane)', value: 'bedrock-agent' },
  {
    label: 'Bedrock Agent Runtime (Data Plane)',
    value: 'bedrock-agent-runtime',
  },
];

async function signAwsRequest({
  accessKeyId,
  secretAccessKey,
  sessionToken,
  region,
  service,
  method,
  url,
  headers,
  body,
}: {
  accessKeyId: string;
  secretAccessKey: string;
  sessionToken?: string;
  region: string;
  service: string;
  method: string;
  url: string;
  headers: Record<string, string>;
  body?: string;
}): Promise<{ headers: Record<string, string> }> {
  const parsedUrl = new URL(url);

  const awsRequest = new AwsHttpRequest({
    method,
    protocol: parsedUrl.protocol,
    hostname: parsedUrl.hostname,
    port: parsedUrl.port ? Number(parsedUrl.port) : undefined,
    path: parsedUrl.pathname,
    query: Object.fromEntries(parsedUrl.searchParams.entries()),
    headers: {
      ...headers,
      host: parsedUrl.hostname,
    },
    body: body ?? undefined,
  });

  const signer = new SignatureV4({
    credentials: { accessKeyId, secretAccessKey, sessionToken },
    region,
    service,
    sha256: Sha256,
  });

  const signedRequest = await signer.sign(awsRequest);

  return {
    headers: signedRequest.headers as Record<string, string>,
  };
}

export const customApiCall = createAction({
  audience: 'human',
  name: 'custom_api_call',
  classification: 'WRITE',
  displayName: 'Custom API Call',
  description:
    'Make a custom API call to any AWS Bedrock endpoint. Requests are automatically signed with AWS Signature V4.',
  aiMetadata: { description: 'Makes an arbitrary AWS SigV4-signed HTTP request to a chosen Bedrock endpoint - the Bedrock control plane, Bedrock Runtime, Bedrock Agent control plane, or Bedrock Agent Runtime - with your own method, path, query parameters, headers, and JSON body, optionally returning errors as output instead of failing the step. Use as an escape hatch for Bedrock operations this piece does not wrap, such as knowledge bases, guardrails, or agent invocation. Requires the service and path to match the AWS Bedrock API reference for the connected region. Idempotency depends on the call made: GET reads are safe to repeat, while model invocations and mutating writes are not.', idempotent: false },
  auth: awsBedrockCombinedAuth,
  requireAuth: true,
  props: {
    service: Property.StaticDropdown({
      displayName: 'Service',
      description:
        'Select the AWS Bedrock service endpoint to call. Use "Bedrock" for control plane operations (e.g., ListFoundationModels) and "Bedrock Runtime" for inference operations (e.g., InvokeModel).',
      required: true,
      defaultValue: 'bedrock',
      options: {
        disabled: false,
        options: AWS_BEDROCK_SERVICES,
      },
    }),
    method: Property.StaticDropdown({
      displayName: 'Method',
      description: 'HTTP method for the request. Use GET to fetch data, POST/PUT to create or update, DELETE to remove.',
      required: true,
      defaultValue: HttpMethod.GET,
      options: {
        disabled: false,
        options: Object.values(HttpMethod).map((v) => ({
          label: v,
          value: v,
        })),
      },
    }),
    path: Property.ShortText({
      displayName: 'Path',
      description:
        'The API path (e.g., /foundation-models, /model/{modelId}/invoke). See the AWS Bedrock API Reference for available endpoints.',
      required: true,
      defaultValue: '/foundation-models',
    }),
    headers: Property.Object({
      displayName: 'Headers',
      description:
        'Additional headers to include. Authorization headers are automatically added via AWS Signature V4.',
      required: false,
    }),
    queryParams: Property.Object({
      displayName: 'Query Parameters',
      description: 'Query parameters to include in the request URL.',
      required: false,
    }),
    body: Property.Json({
      displayName: 'Body',
      description: 'JSON body for POST/PUT requests.',
      required: false,
    }),
    failsafe: Property.Checkbox({
      displayName: 'Return Error as Output',
      description: 'When enabled, errors (e.g. 4xx/5xx responses) are returned as output instead of stopping the flow. Useful when you want to handle errors in a later step.',
      required: false,
      defaultValue: false,
    }),
    timeout: Property.Number({
      displayName: 'Timeout (in seconds)',
      description: 'How long to wait for a response before the request is cancelled. Defaults to 30 seconds.',
      required: false,
      defaultValue: 30,
    }),
  },
  async run(context) {
    const { service, method, path, headers, queryParams, body, failsafe, timeout } =
      context.propsValue;
    const authProps = context.auth.props;
    const region = authProps.region;

    let creds: { accessKeyId: string; secretAccessKey: string; sessionToken?: string };
    if (isOidcAuth(authProps)) {
      creds = await getTemporaryCredentials({ auth: authProps, server: context.server });
    } else {
      creds = { accessKeyId: authProps.accessKeyId, secretAccessKey: authProps.secretAccessKey, sessionToken: authProps.sessionToken };
    }

    const baseUrl = `https://${service}.${region}.amazonaws.com`;
    let fullUrl = `${baseUrl}${path.startsWith('/') ? path : `/${path}`}`;

    if (queryParams && Object.keys(queryParams).length > 0) {
      const params = new URLSearchParams();
      for (const [key, value] of Object.entries(queryParams)) {
        if (value !== undefined && value !== null) {
          params.append(key, String(value));
        }
      }
      const queryString = params.toString();
      if (queryString) {
        fullUrl += `?${queryString}`;
      }
    }

    const requestHeaders: Record<string, string> = {
      ...(headers as Record<string, string> ?? {}),
    };

    const bodyString = body ? JSON.stringify(body) : undefined;

    if (bodyString) {
      requestHeaders['content-type'] = requestHeaders['content-type'] ?? 'application/json';
    }

    const signed = await signAwsRequest({
      accessKeyId: creds.accessKeyId,
      secretAccessKey: creds.secretAccessKey,
      sessionToken: creds.sessionToken,
      region,
      service,
      method,
      url: fullUrl,
      headers: requestHeaders,
      body: bodyString,
    });

    const request: HttpRequest = {
      method,
      url: fullUrl,
      headers: signed.headers,
      body: bodyString ? JSON.parse(bodyString) : undefined,
      timeout: timeout ? timeout * 1000 : 30000,
    };

    try {
      const response = await httpClient.sendRequest(request);
      return {
        status: response.status,
        headers: response.headers,
        body: response.body,
      };
    } catch (error) {
      if (failsafe) {
        return {
          error: (error as any)?.message ?? 'Request failed',
          response: (error as any)?.response?.body ?? null,
        };
      }
      throw error;
    }
  },
});