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

feat(magical-api): fetch timed-out jobs from AI agents and check connections for free (#16521)

Odai Ahmad671c11650620
diff --git a/bun.lock b/bun.lock
index 3d205c95937..6162096986a 100644
--- a/bun.lock
+++ b/bun.lock
@@ -5484,15 +5484,14 @@
},
"packages/pieces/community/magical-api": {
"name": "@activepieces/piece-magical-api",
- "version": "0.2.1",
+ "version": "0.3.0",
"dependencies": {
- "@activepieces/core-piece-types": "workspace:*",
- "@activepieces/core-utils": "workspace:*",
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
},
"devDependencies": {
- "tslib": "^2.3.0",
+ "tslib": "2.6.2",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/magicslides": {
diff --git a/packages/pieces/community/magical-api/package.json b/packages/pieces/community/magical-api/package.json
index 8b03ba71818..19be54a0791 100644
--- a/packages/pieces/community/magical-api/package.json
+++ b/packages/pieces/community/magical-api/package.json
@@ -1,21 +1,21 @@
{
"name": "@activepieces/piece-magical-api",
- "version": "0.2.1",
+ "version": "0.3.0",
"type": "commonjs",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
"dependencies": {
"@activepieces/pieces-common": "workspace:*",
- "@activepieces/pieces-framework": "workspace:*",
- "@activepieces/core-piece-types": "workspace:*",
- "@activepieces/core-utils": "workspace:*"
+ "@activepieces/pieces-framework": "workspace:*"
},
"devDependencies": {
- "tslib": "^2.3.0"
+ "tslib": "2.6.2",
+ "vitest": "3.2.6"
},
"scripts": {
"build": "tsc -p tsconfig.lib.json && cp package.json dist/",
"bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",
- "lint": "eslint 'src/**/*.ts'"
+ "lint": "eslint 'src/**/*.ts'",
+ "test": "vitest run"
}
}
diff --git a/packages/pieces/community/magical-api/src/i18n/translation.json b/packages/pieces/community/magical-api/src/i18n/translation.json
index 7c424fe753b..0ea9bd2420c 100644
--- a/packages/pieces/community/magical-api/src/i18n/translation.json
+++ b/packages/pieces/community/magical-api/src/i18n/translation.json
@@ -48,5 +48,11 @@
"PATCH": "PATCH",
"PUT": "PUT",
"DELETE": "DELETE",
- "HEAD": "HEAD"
-}
\ No newline at end of file
+ "HEAD": "HEAD",
+ "Get Job Result": "Get Job Result",
+ "Check a MagicalAPI job once by its Request ID and return its result if it is ready.": "Check a MagicalAPI job once by its Request ID and return its result if it is ready.",
+ "Service": "Service",
+ "The service that created the job.": "The service that created the job.",
+ "Request ID": "Request ID",
+ "The Request ID returned when the job was started.": "The Request ID returned when the job was started."
+}
diff --git a/packages/pieces/community/magical-api/src/index.ts b/packages/pieces/community/magical-api/src/index.ts
index f7fba841d85..753c168eb3e 100644
--- a/packages/pieces/community/magical-api/src/index.ts
+++ b/packages/pieces/community/magical-api/src/index.ts
@@ -1,5 +1,4 @@
-import { createPiece, PieceAuth } from '@activepieces/pieces-framework';
-import { PieceCategory } from '@activepieces/pieces-framework';
+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';
import { createCustomApiCallAction } from '@activepieces/pieces-common';
import { magicalApiAuth } from './lib/common/auth';
import { BASE_URL } from './lib/common/client';
@@ -8,12 +7,13 @@ import { parseResume } from './lib/actions/parse-resume';
import { getProfileData } from './lib/actions/get-profile-data';
import { getCompanyData } from './lib/actions/get-company-data';
import { scoreResume } from './lib/actions/score-resume';
+import { getJobResult } from './lib/actions/get-job-result';
export const magicalApi = createPiece({
displayName: 'Magical API',
description: 'Automate resume parsing, review, scoring, and LinkedIn profile/company data retrieval with Magical API.',
auth: magicalApiAuth,
- minimumSupportedRelease: '0.36.1',
+ minimumSupportedRelease: '0.88.2',
logoUrl: 'https://cdn.activepieces.com/pieces/magical-api.png',
authors: ['Pranith124', 'sanket-a11y'],
categories: [
@@ -27,6 +27,7 @@ export const magicalApi = createPiece({
getProfileData,
getCompanyData,
scoreResume,
+ getJobResult,
createCustomApiCallAction({
auth: magicalApiAuth,
baseUrl: () => BASE_URL,
diff --git a/packages/pieces/community/magical-api/src/lib/actions/get-company-data.ts b/packages/pieces/community/magical-api/src/lib/actions/get-company-data.ts
index 473f2f6c52b..6b6e3c3b2f9 100644
--- a/packages/pieces/community/magical-api/src/lib/actions/get-company-data.ts
+++ b/packages/pieces/community/magical-api/src/lib/actions/get-company-data.ts
@@ -1,90 +1,64 @@
-import { createAction, Property } from "@activepieces/pieces-framework";
-import { HttpMethod } from "@activepieces/pieces-common";
-import { magicalApiAuth } from "../common/auth";
-import { makeRequest } from "../common/client";
-
-const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { magicalApiAuth } from '../common/auth';
+import { runJob, normalizeRequestId } from '../common/poll';
+import { companyDataOutputSchema } from '../common/output-schemas';
export const getCompanyData = createAction({
- auth: magicalApiAuth,
- name: 'get_company_data',
- classification: 'READ',
- displayName: 'Get Company Data',
- description: 'Given a company name, LinkedIn username, or website, fetch comprehensive company info.',
- audience: 'both',
- aiMetadata: { description: 'Fetches comprehensive public company data from any one of three identifiers: a company name (e.g. "Microsoft"), its LinkedIn username slug (e.g. "microsoft"), or its website URL. Use to enrich a company record when you have any of those handles. At least one identifier is required; alternatively pass the Request ID from a prior timed-out run to retrieve that result. The call polls until data is ready. Idempotent: it is a read-only lookup returning the same company for the same identifier.', idempotent: true },
- props: {
- company_name: Property.ShortText({
- displayName: 'Company Name',
- description: "Provide the company's legal name (e.g., 'Microsoft').",
- required: false,
- }),
- company_username: Property.ShortText({
- displayName: 'Company LinkedIn Username',
- description: "Provide the username from the company's LinkedIn URL (e.g., 'microsoft').",
- required: false,
- }),
- company_website: Property.ShortText({
- displayName: 'Company Website',
- description: "Provide the company's official website URL.",
- required: false,
- }),
- request_id: Property.ShortText({
- displayName: 'Request ID (for retries)',
- description: "If a previous run timed out, paste the Request ID here to get the result.",
- required: false,
- }),
- },
- async run(context) {
- const { company_name, company_username, company_website, request_id } = context.propsValue;
- const apiKey = context.auth;
- const COMPANY_DATA_ENDPOINT = '/company-data';
- let requestIdToPoll = request_id;
- let response;
-
- if (!requestIdToPoll) {
- if (!company_name && !company_username && !company_website) {
- throw new Error("To start a new request, you must provide a Company Name, LinkedIn Username, or Website.");
- }
-
- const initialBody: { [key: string]: string } = {};
- if (company_name) initialBody['company_name'] = company_name;
- if (company_username) initialBody['company_username'] = company_username;
- if (company_website) initialBody['company_website'] = company_website;
-
- response = await makeRequest(apiKey, HttpMethod.POST, COMPANY_DATA_ENDPOINT, initialBody);
- } else {
- response = await makeRequest(apiKey, HttpMethod.POST, COMPANY_DATA_ENDPOINT, { request_id: requestIdToPoll });
- }
-
-
- if (response.data?.company_name) {
-
- return response.data;
- }
-
- requestIdToPoll = response.data?.request_id;
- if (!requestIdToPoll) {
- throw new Error('Failed to start or retrieve the request. The API did not return a request_id or the final data.');
- }
-
-
- const maxAttempts = 20;
- const pollInterval = 3000;
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
- await sleep(pollInterval);
- const pollResponse = await makeRequest(apiKey, HttpMethod.POST, COMPANY_DATA_ENDPOINT, { request_id: requestIdToPoll });
-
-
- if (pollResponse.data?.company_name) {
-
- return pollResponse.data;
- }
- }
-
-
- throw new Error(
- 'Timeout: The request is still processing. You can try again later with this Request ID: ' + requestIdToPoll
- );
- },
-});
\ No newline at end of file
+ auth: magicalApiAuth,
+ name: 'get_company_data',
+ classification: 'READ',
+ displayName: 'Get Company Data',
+ description: 'Given a company name, LinkedIn username, or website, fetch comprehensive company info.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Fetches public LinkedIn company data (name, tagline, about, website, industry, size, headquarters, founded year, followers, locations, funding, recent posts) from any one of: a company name (e.g. "Microsoft"), its LinkedIn username (the slug after /company/, e.g. "microsoft"), or its website URL. Use to enrich a company record. Each new lookup costs about 150 MagicalAPI credits. At least one identifier is required, or pass the Request ID from a prior timed-out run to fetch that result; the call polls up to 60 seconds. Idempotent: a read-only lookup (but every new lookup spends credits).',
+ idempotent: true,
+ },
+ props: {
+ company_name: Property.ShortText({
+ displayName: 'Company Name',
+ description: "Provide the company's legal name (e.g., 'Microsoft').",
+ required: false,
+ }),
+ company_username: Property.ShortText({
+ displayName: 'Company LinkedIn Username',
+ description: "Provide the username from the company's LinkedIn URL (e.g., 'microsoft').",
+ required: false,
+ }),
+ company_website: Property.ShortText({
+ displayName: 'Company Website',
+ description: "Provide the company's official website URL.",
+ required: false,
+ }),
+ request_id: Property.ShortText({
+ displayName: 'Request ID (for retries)',
+ description: 'If a previous run timed out, paste the Request ID here to get the result.',
+ required: false,
+ }),
+ },
+ outputSchema: companyDataOutputSchema,
+ async run(context) {
+ const { company_name, company_username, company_website, request_id: rawRequestId } = context.propsValue;
+ const request_id = normalizeRequestId(rawRequestId);
+ const input: Record<string, string> = {};
+ if (company_name?.trim()) {
+ input['company_name'] = company_name.trim();
+ }
+ if (company_username?.trim()) {
+ input['company_username'] = company_username.trim();
+ }
+ if (company_website?.trim()) {
+ input['company_website'] = company_website.trim();
+ }
+ if (!request_id && Object.keys(input).length === 0) {
+ throw new Error('To start a new request, you must provide a Company Name, LinkedIn Username, or Website.');
+ }
+ return runJob({
+ apiKey: context.auth.secret_text,
+ service: 'company_data',
+ input,
+ requestId: request_id,
+ });
+ },
+});
diff --git a/packages/pieces/community/magical-api/src/lib/actions/get-job-result.ts b/packages/pieces/community/magical-api/src/lib/actions/get-job-result.ts
new file mode 100644
index 00000000000..af42a4082f6
--- /dev/null
+++ b/packages/pieces/community/magical-api/src/lib/actions/get-job-result.ts
@@ -0,0 +1,57 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { magicalApiAuth } from '../common/auth';
+import { fetchJobResult, MagicalApiService } from '../common/poll';
+import { jobResultOutputSchema } from '../common/output-schemas';
+
+export const getJobResult = createAction({
+ auth: magicalApiAuth,
+ name: 'get_job_result',
+ classification: 'READ',
+ displayName: 'Get Job Result',
+ description: 'Check a MagicalAPI job once by its Request ID and return its result if it is ready.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Checks a MagicalAPI job once (no waiting) by its Request ID and returns status "ready" with the result in data, or status "processing". Use it after Parse Resume, Review Resume, Score Resume, Get Profile Data or Get Company Data timed out and reported a Request ID; pick the same service that created the job, since a Request ID only works with its own service (a mismatch returns 404). A finished result can be fetched only once: after it is returned (here or by the action that started the job) the Request ID returns 404. Checking costs no credits and does not start a new job. Not idempotent: once a result is returned, the same Request ID gives 404.',
+ idempotent: false,
+ },
+ props: {
+ service: Property.StaticDropdown({
+ displayName: 'Service',
+ description: 'The service that created the job.',
+ required: true,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Parse Resume', value: 'resume_parser' },
+ { label: 'Review Resume', value: 'resume_review' },
+ { label: 'Score Resume', value: 'resume_score' },
+ { label: 'Get Profile Data', value: 'profile_data' },
+ { label: 'Get Company Data', value: 'company_data' },
+ ],
+ },
+ }),
+ request_id: Property.ShortText({
+ displayName: 'Request ID',
+ description: 'The Request ID returned when the job was started.',
+ required: true,
+ }),
+ },
+ outputSchema: jobResultOutputSchema,
+ async run(context) {
+ const { service, request_id } = context.propsValue;
+ if (!isService(service)) {
+ throw new Error(`Unknown service "${service}". Use one of: ${SERVICE_VALUES.join(', ')}.`);
+ }
+ if (!request_id || request_id.trim().length === 0) {
+ throw new Error('Request ID is required.');
+ }
+ return fetchJobResult({ apiKey: context.auth.secret_text, service, requestId: request_id });
+ },
+});
+
+function isService(value: string): value is MagicalApiService {
+ return SERVICE_VALUES.some((candidate) => candidate === value);
+}
+
+const SERVICE_VALUES: MagicalApiService[] = ['resume_parser', 'resume_review', 'resume_score', 'profile_data', 'company_data'];
diff --git a/packages/pieces/community/magical-api/src/lib/actions/get-profile-data.ts b/packages/pieces/community/magical-api/src/lib/actions/get-profile-data.ts
index a0782a7ba69..36300615967 100644
--- a/packages/pieces/community/magical-api/src/lib/actions/get-profile-data.ts
+++ b/packages/pieces/community/magical-api/src/lib/actions/get-profile-data.ts
@@ -1,69 +1,54 @@
-import { createAction, Property } from "@activepieces/pieces-framework";
-import { HttpMethod } from "@activepieces/pieces-common";
-import { magicalApiAuth } from "../common/auth";
-import { makeRequest } from "../common/client";
-
-const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { magicalApiAuth } from '../common/auth';
+import { runJob, normalizeRequestId } from '../common/poll';
+import { profileDataOutputSchema } from '../common/output-schemas';
export const getProfileData = createAction({
- auth: magicalApiAuth,
- name: 'get_profile_data',
- classification: 'READ',
- displayName: 'Get Profile Data',
- description: 'Given a LinkedIn profile username, retrieve comprehensive profile data.',
- audience: 'both',
- aiMetadata: { description: 'Retrieves comprehensive public LinkedIn profile data (experience, education, headline, etc.) for a given profile username — the slug from the profile URL, e.g. "williamhgates", not a full URL or display name. Use to enrich a person record from their LinkedIn handle. Either supply the profile username to start a lookup, or pass the Request ID from a prior timed-out run to retrieve that result; the call polls until data is ready. Idempotent: it is a read-only lookup that returns the same profile for the same username.', idempotent: true },
- props: {
- profile_name: Property.ShortText({
- displayName: 'LinkedIn Profile Username',
- description: "Provide the username from the LinkedIn profile URL (e.g., 'williamhgates').",
- required: false,
- }),
- request_id: Property.ShortText({
- displayName: 'Request ID (for retries)',
- description: "If a previous run timed out, paste the Request ID here to get the result.",
- required: false,
- }),
- },
- async run(context) {
- const { profile_name, request_id } = context.propsValue;
- const apiKey = context.auth;
- const PROFILE_DATA_ENDPOINT = '/profile-data';
- let requestIdToPoll = request_id;
- let response;
-
- if (!requestIdToPoll) {
-
- if (!profile_name) {
- throw new Error("To start a new request, you must provide a LinkedIn Profile Username.");
- }
- response = await makeRequest(apiKey, HttpMethod.POST, PROFILE_DATA_ENDPOINT, { profile_name });
- } else {
-
- response = await makeRequest(apiKey, HttpMethod.POST, PROFILE_DATA_ENDPOINT, { request_id });
- }
-
- if (response.data?.profile) {
- return response.data;
- }
-
- requestIdToPoll = response.data?.request_id;
- if (!requestIdToPoll) {
- throw new Error('Failed to start or retrieve the request. The API did not return a request_id or the final data.');
- }
-
-
- const maxAttempts = 20;
- const pollInterval = 3000;
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
- await sleep(pollInterval);
- const pollResponse = await makeRequest(apiKey, HttpMethod.POST, PROFILE_DATA_ENDPOINT, { request_id: requestIdToPoll });
-
- if (pollResponse.data?.profile) {
- return pollResponse.data;
- }
- }
-
- throw new Error('Timeout: The request is still processing. You can try again later with this Request ID: ' + requestIdToPoll);
- },
-});
\ No newline at end of file
+ auth: magicalApiAuth,
+ name: 'get_profile_data',
+ classification: 'READ',
+ displayName: 'Get Profile Data',
+ description: 'Given a LinkedIn profile username, retrieve comprehensive profile data.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Retrieves public LinkedIn profile data (name, bio, location, experience, education, certifications, languages, skills-related sections) for a profile username: the slug after /in/ in the profile URL, e.g. "williamhgates". A full linkedin.com/in/ URL is also accepted and reduced to its slug; a display name is not. Use to enrich a person record. Each new lookup costs about 150 MagicalAPI credits. Either supply the username, or pass the Request ID from a prior timed-out run to fetch that result; the call polls up to 60 seconds. Idempotent: a read-only lookup (but every new lookup spends credits).',
+ idempotent: true,
+ },
+ props: {
+ profile_name: Property.ShortText({
+ displayName: 'LinkedIn Profile Username',
+ description: "Provide the username from the LinkedIn profile URL (e.g., 'williamhgates').",
+ required: false,
+ }),
+ request_id: Property.ShortText({
+ displayName: 'Request ID (for retries)',
+ description: 'If a previous run timed out, paste the Request ID here to get the result.',
+ required: false,
+ }),
+ },
+ outputSchema: profileDataOutputSchema,
+ async run(context) {
+ const { profile_name, request_id: rawRequestId } = context.propsValue;
+ const request_id = normalizeRequestId(rawRequestId);
+ const slug = profile_name ? toProfileSlug(profile_name) : '';
+ if (!request_id && !slug) {
+ throw new Error('To start a new request, you must provide a LinkedIn Profile Username.');
+ }
+ return runJob({
+ apiKey: context.auth.secret_text,
+ service: 'profile_data',
+ input: { profile_name: slug },
+ requestId: request_id,
+ });
+ },
+});
+
+export function toProfileSlug(value: string): string {
+ const trimmed = value.trim();
+ const match = /linkedin\.com\/in\/([^/?#]+)/i.exec(trimmed);
+ if (match) {
+ return decodeURIComponent(match[1]);
+ }
+ return trimmed.replace(/^@/, '').replace(/\/+$/, '');
+}
diff --git a/packages/pieces/community/magical-api/src/lib/actions/parse-resume.ts b/packages/pieces/community/magical-api/src/lib/actions/parse-resume.ts
index cd4dc62a3bc..86cacf77b14 100644
--- a/packages/pieces/community/magical-api/src/lib/actions/parse-resume.ts
+++ b/packages/pieces/community/magical-api/src/lib/actions/parse-resume.ts
@@ -1,73 +1,49 @@
-import { createAction, Property } from "@activepieces/pieces-framework";
-import { HttpMethod } from "@activepieces/pieces-common";
-import { magicalApiAuth } from "../common/auth";
-import { makeRequest } from "../common/client";
-
-const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { magicalApiAuth } from '../common/auth';
+import { isHttpUrl, runJob, normalizeRequestId } from '../common/poll';
+import { parseResumeOutputSchema } from '../common/output-schemas';
export const parseResume = createAction({
- auth: magicalApiAuth,
- name: 'parse_resume',
- classification: 'READ',
- displayName: 'Parse Resume',
- description: 'Extract structured data (name, email, experience, skills, etc.) from a resume file.',
- audience: 'both',
- aiMetadata: { description: 'Parses a publicly accessible resume file (PDF/DOC/DOCX) at a given URL into structured fields such as name, contact info, experience, education, and skills. Use to turn an unstructured resume into machine-readable data. Either supply the resume URL to start a job, or pass the Request ID from a prior timed-out run to retrieve that result instead; the call polls until parsing completes. Idempotent: re-running with the same URL re-parses the same document and yields the same data.', idempotent: true },
- props: {
- url: Property.ShortText({
- displayName: 'Resume URL',
- description: 'Provide the direct link to a publicly accessible resume file (PDF, DOC, or DOCX)',
- required: false,
- }),
- request_id: Property.ShortText({
- displayName: 'Request ID (for retries)',
- description: "If a previous run timed out, paste the Request ID here to get the result.",
- required: false,
- }),
- },
- async run(context) {
- const { url, request_id } = context.propsValue;
- const apiKey = context.auth;
- const RESUME_PARSER_ENDPOINT = '/resume-parser';
- let requestIdToPoll = request_id;
- let response;
-
-
- if (!requestIdToPoll) {
- if (!url) {
- throw new Error("To start a new request, you must provide a Resume URL.");
- }
- response = await makeRequest(apiKey, HttpMethod.POST, RESUME_PARSER_ENDPOINT, { url });
- } else {
-
- response = await makeRequest(apiKey, HttpMethod.POST, RESUME_PARSER_ENDPOINT, { request_id: requestIdToPoll });
- }
-
-
- if (response.data?.basic) {
- return response.data;
- }
-
- requestIdToPoll = response.data?.request_id;
- if (!requestIdToPoll) {
- throw new Error('Failed to start or retrieve the request. The API did not return a request_id or the final data.');
- }
-
-
- const maxAttempts = 20;
- const pollInterval = 3000;
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
- await sleep(pollInterval);
- const pollResponse = await makeRequest(apiKey, HttpMethod.POST, RESUME_PARSER_ENDPOINT, { request_id: requestIdToPoll });
-
- if (pollResponse.data?.basic) {
- return pollResponse.data;
- }
- }
-
-
- throw new Error(
- 'Timeout: Resume parsing is taking longer than expected. You can check the status later with this Request ID: ' + requestIdToPoll
- );
- },
-});
\ No newline at end of file
+ auth: magicalApiAuth,
+ name: 'parse_resume',
+ classification: 'READ',
+ displayName: 'Parse Resume',
+ description: 'Extract structured data (name, email, experience, skills, etc.) from a resume file.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Parses a publicly accessible resume file (PDF/DOC/DOCX, max 10 MB) at an http(s) URL into structured fields: basic contact info, summary, work experiences, education, certifications, languages and skills. Use to turn an unstructured resume into machine-readable data. Each new parse costs about 150 MagicalAPI credits. Either supply the resume URL to start a job, or pass the Request ID from a prior timed-out run to fetch that result at no new job cost; the call polls up to 60 seconds. Idempotent: re-running with the same URL yields the same data (but spends credits again).',
+ idempotent: true,
+ },
+ props: {
+ url: Property.ShortText({
+ displayName: 'Resume URL',
+ description: 'Provide the direct link to a publicly accessible resume file (PDF, DOC, or DOCX)',
+ required: false,
+ }),
+ request_id: Property.ShortText({
+ displayName: 'Request ID (for retries)',
+ description: 'If a previous run timed out, paste the Request ID here to get the result.',
+ required: false,
+ }),
+ },
+ outputSchema: parseResumeOutputSchema,
+ async run(context) {
+ const { url, request_id: rawRequestId } = context.propsValue;
+ const request_id = normalizeRequestId(rawRequestId);
+ if (!request_id) {
+ if (!url) {
+ throw new Error('To start a new request, you must provide a Resume URL.');
+ }
+ if (!isHttpUrl(url.trim())) {
+ throw new Error('Resume URL must be a public http(s) link to a PDF, DOC or DOCX file.');
+ }
+ }
+ return runJob({
+ apiKey: context.auth.secret_text,
+ service: 'resume_parser',
+ input: { url: (url ?? '').trim() },
+ requestId: request_id,
+ });
+ },
+});
diff --git a/packages/pieces/community/magical-api/src/lib/actions/review-resume.ts b/packages/pieces/community/magical-api/src/lib/actions/review-resume.ts
index 459a786051f..08ac1f446f7 100644
--- a/packages/pieces/community/magical-api/src/lib/actions/review-resume.ts
+++ b/packages/pieces/community/magical-api/src/lib/actions/review-resume.ts
@@ -1,75 +1,49 @@
-import { createAction, Property } from "@activepieces/pieces-framework";
-import { HttpMethod } from "@activepieces/pieces-common";
-import { magicalApiAuth } from "../common/auth";
-import { makeRequest } from "../common/client";
-
-const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { magicalApiAuth } from '../common/auth';
+import { isHttpUrl, runJob, normalizeRequestId } from '../common/poll';
+import { reviewResumeOutputSchema } from '../common/output-schemas';
export const reviewResume = createAction({
- auth: magicalApiAuth,
- name: 'review_resume',
- classification: 'READ',
- displayName: 'Review Resume',
- description: 'Analyze parsed resume using predefined criteria.',
- audience: 'both',
- aiMetadata: { description: 'Analyzes a publicly accessible resume file (PDF/DOC/DOCX) at a given URL against predefined review criteria, returning an assessment with a score. Use to evaluate resume quality without a specific job description. Either supply the resume URL to start a job, or pass the Request ID from a prior timed-out run to retrieve that result; the call polls until the review completes. Idempotent: re-running with the same URL re-evaluates the same resume.', idempotent: true },
- props: {
- url: Property.ShortText({
- displayName: 'Resume URL',
- description: 'Provide a direct URL to a publicly accessible resume file (PDF, DOC, or DOCX).',
- required: false,
- }),
- request_id: Property.ShortText({
- displayName: 'Request ID (for retries)',
- description: "If a previous run timed out, paste the Request ID here to get the result.",
- required: false,
- }),
- },
- async run(context) {
- const { url, request_id } = context.propsValue;
- const apiKey = context.auth;
- const REVIEW_RESUME_ENDPOINT = '/resume-review';
- let requestIdToPoll = request_id;
- let response;
-
-
- if (!requestIdToPoll) {
- if (!url) {
- throw new Error("To start a new request, you must provide a Resume URL.");
- }
- response = await makeRequest(apiKey, HttpMethod.POST, REVIEW_RESUME_ENDPOINT, { url });
- } else {
-
- response = await makeRequest(apiKey, HttpMethod.POST, REVIEW_RESUME_ENDPOINT, { request_id: requestIdToPoll });
- }
-
-
- if (response.data?.score !== undefined) {
- return response.data;
- }
-
- requestIdToPoll = response.data?.request_id;
- if (!requestIdToPoll) {
- throw new Error('Failed to start or retrieve the request. The API did not return a request_id or the final data.');
- }
-
-
- const maxAttempts = 20;
- const pollInterval = 3000;
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
- await sleep(pollInterval);
- const pollResponse = await makeRequest(apiKey, HttpMethod.POST, REVIEW_RESUME_ENDPOINT, { request_id: requestIdToPoll });
-
-
- if (pollResponse.data?.score !== undefined) {
-
- return pollResponse.data;
- }
- }
-
-
- throw new Error(
- 'Timeout: Resume review is taking longer than expected. You can check the status later with this Request ID: ' + requestIdToPoll
- );
- },
-});
\ No newline at end of file
+ auth: magicalApiAuth,
+ name: 'review_resume',
+ classification: 'READ',
+ displayName: 'Review Resume',
+ description: 'Analyze parsed resume using predefined criteria.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Reviews a publicly accessible resume file (PDF/DOC/DOCX) at an http(s) URL against predefined criteria and returns an overall score (0-100), pros and cons with tips per section (contact, experiences, educations, skills, summary, format) and a suggested summary. Use to judge resume quality without a job description; use Score Resume to compare against a specific job. Each new review costs about 250 MagicalAPI credits. Either supply the resume URL, or pass the Request ID from a prior timed-out run to fetch that result; the call polls up to 60 seconds. Idempotent in effect (no data changes), but every new job spends credits.',
+ idempotent: true,
+ },
+ props: {
+ url: Property.ShortText({
+ displayName: 'Resume URL',
+ description: 'Provide a direct URL to a publicly accessible resume file (PDF, DOC, or DOCX).',
+ required: false,
+ }),
+ request_id: Property.ShortText({
+ displayName: 'Request ID (for retries)',
+ description: 'If a previous run timed out, paste the Request ID here to get the result.',
+ required: false,
+ }),
+ },
+ outputSchema: reviewResumeOutputSchema,
+ async run(context) {
+ const { url, request_id: rawRequestId } = context.propsValue;
+ const request_id = normalizeRequestId(rawRequestId);
+ if (!request_id) {
+ if (!url) {
+ throw new Error('To start a new request, you must provide a Resume URL.');
+ }
+ if (!isHttpUrl(url.trim())) {
+ throw new Error('Resume URL must be a public http(s) link to a PDF, DOC or DOCX file.');
+ }
+ }
+ return runJob({
+ apiKey: context.auth.secret_text,
+ service: 'resume_review',
+ input: { url: (url ?? '').trim() },
+ requestId: request_id,
+ });
+ },
+});
diff --git a/packages/pieces/community/magical-api/src/lib/actions/score-resume.ts b/packages/pieces/community/magical-api/src/lib/actions/score-resume.ts
index 182d7b7fda3..42621d8049a 100644
--- a/packages/pieces/community/magical-api/src/lib/actions/score-resume.ts
+++ b/packages/pieces/community/magical-api/src/lib/actions/score-resume.ts
@@ -1,79 +1,54 @@
-import { createAction, Property } from "@activepieces/pieces-framework";
-import { HttpMethod } from "@activepieces/pieces-common";
-import { magicalApiAuth } from "../common/auth";
-import { makeRequest } from "../common/client";
-
-const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { magicalApiAuth } from '../common/auth';
+import { isHttpUrl, runJob, normalizeRequestId } from '../common/poll';
+import { scoreResumeOutputSchema } from '../common/output-schemas';
export const scoreResume = createAction({
- auth: magicalApiAuth,
- name: 'score_resume',
- classification: 'READ',
- displayName: 'Score Resume',
- description: 'Scores a resume against a job description and provides a reason.',
- audience: 'both',
- aiMetadata: { description: 'Scores how well a publicly accessible resume file (PDF/DOC/DOCX) at a given URL matches a supplied job description, returning a fit score with reasoning. Use to rank or screen candidates against a specific role. Both the resume URL and the job description are required to start a job; alternatively pass the Request ID from a prior timed-out run to retrieve that result. The call polls until scoring completes. Idempotent: re-running with the same resume and job description yields the same score.', idempotent: true },
- props: {
- url: Property.ShortText({
- displayName: 'Resume URL',
- description: 'Provide a direct URL to a publicly accessible resume file (PDF, DOC, or DOCX).',
- required: false,
- }),
- job_description: Property.LongText({
- displayName: 'Job Description',
- description: 'Provide the job description to score the resume against.',
- required: false,
- }),
- request_id: Property.ShortText({
- displayName: 'Request ID (for retries)',
- description: "If a previous run timed out, paste the Request ID here to get the result.",
- required: false,
- }),
- },
- async run(context) {
- const { url, job_description, request_id } = context.propsValue;
- const apiKey = context.auth;
- const RESUME_SCORE_ENDPOINT = '/resume-score';
- let requestIdToPoll = request_id;
- let response;
-
-
- if (!requestIdToPoll) {
- if (!url || !job_description) {
- throw new Error("To start a new request, you must provide both a Resume URL and a Job Description.");
- }
- response = await makeRequest(apiKey, HttpMethod.POST, RESUME_SCORE_ENDPOINT, { url, job_description });
- } else {
-
- response = await makeRequest(apiKey, HttpMethod.POST, RESUME_SCORE_ENDPOINT, { request_id: requestIdToPoll });
- }
-
-
- if (response.data?.score !== undefined) {
- return response.data;
- }
-
- requestIdToPoll = response.data?.request_id;
- if (!requestIdToPoll) {
- throw new Error('Failed to start or retrieve the request. The API did not return a request_id or the final data.');
- }
-
-
- const maxAttempts = 20;
- const pollInterval = 3000;
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
- await sleep(pollInterval);
- const pollResponse = await makeRequest(apiKey, HttpMethod.POST, RESUME_SCORE_ENDPOINT, { request_id: requestIdToPoll });
-
- if (pollResponse.data?.score !== undefined) {
-
- return pollResponse.data;
- }
- }
-
-
- throw new Error(
- 'Timeout: Resume scoring is taking longer than expected. You can check the status later with this Request ID: ' + requestIdToPoll
- );
- },
-});
\ No newline at end of file
+ auth: magicalApiAuth,
+ name: 'score_resume',
+ classification: 'READ',
+ displayName: 'Score Resume',
+ description: 'Scores a resume against a job description and provides a reason.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Scores how well a publicly accessible resume file (PDF/DOC/DOCX) at an http(s) URL matches a job description: overall score 0-100 (-1 if the resume is empty), summary, strengths, improvements, and job, skill and education match details. Use to rank or screen candidates for a specific role. Both the resume URL and the job description text are required to start a job; each new job costs about 250 MagicalAPI credits. Alternatively pass the Request ID from a prior timed-out run to fetch that result; the call polls up to 60 seconds. Idempotent in effect (no data changes), but every new job spends credits.',
+ idempotent: true,
+ },
+ props: {
+ url: Property.ShortText({
+ displayName: 'Resume URL',
+ description: 'Provide a direct URL to a publicly accessible resume file (PDF, DOC, or DOCX).',
+ required: false,
+ }),
+ job_description: Property.LongText({
+ displayName: 'Job Description',
+ description: 'Provide the job description to score the resume against.',
+ required: false,
+ }),
+ request_id: Property.ShortText({
+ displayName: 'Request ID (for retries)',
+ description: 'If a previous run timed out, paste the Request ID here to get the result.',
+ required: false,
+ }),
+ },
+ outputSchema: scoreResumeOutputSchema,
+ async run(context) {
+ const { url, job_description, request_id: rawRequestId } = context.propsValue;
+ const request_id = normalizeRequestId(rawRequestId);
+ if (!request_id) {
+ if (!url || !job_description || job_description.trim().length === 0) {
+ throw new Error('To start a new request, you must provide both a Resume URL and a Job Description.');
+ }
+ if (!isHttpUrl(url.trim())) {
+ throw new Error('Resume URL must be a public http(s) link to a PDF, DOC or DOCX file.');
+ }
+ }
+ return runJob({
+ apiKey: context.auth.secret_text,
+ service: 'resume_score',
+ input: { url: (url ?? '').trim(), job_description: job_description ?? '' },
+ requestId: request_id,
+ });
+ },
+});
diff --git a/packages/pieces/community/magical-api/src/lib/common/auth.ts b/packages/pieces/community/magical-api/src/lib/common/auth.ts
index 6dcef2e7188..ec5891edf0d 100644
--- a/packages/pieces/community/magical-api/src/lib/common/auth.ts
+++ b/packages/pieces/community/magical-api/src/lib/common/auth.ts
@@ -1,42 +1,41 @@
-import { PieceAuth } from "@activepieces/pieces-framework";
-import { makeRequest } from "./client";
-import { HttpMethod } from "@activepieces/pieces-common";
-import { AppConnectionType } from '@activepieces/pieces-framework';
+import { PieceAuth } from '@activepieces/pieces-framework';
+import { magicalApiRequest, MagicalApiError } from './client';
export const magicalApiAuth = PieceAuth.SecretText({
- displayName: "Magical API Key",
- description: "Enter your Magical API key from your MagicalAPI dashboard.",
+ displayName: 'Magical API Key',
+ description: 'Enter your Magical API key from your MagicalAPI dashboard.',
required: true,
- validate: async ({ auth }) => {
- if (!auth) {
- return {
- valid: false,
- error: "API Key is required.",
- };
- }
-
- try {
-
- const response = await makeRequest(
- {type: AppConnectionType.SECRET_TEXT, secret_text: auth},
- HttpMethod.POST,
- "/profile-data",
- { profile_name: "activepieces_validation" }
- );
-
- if (response && response.data?.request_id) {
- return { valid: true };
- }
+ validate: async ({ auth }) => validateMagicalApiKey({ apiKey: auth }),
+});
- return {
- valid: false,
- error: "Invalid API key.",
- };
- } catch (e: any) {
- return {
- valid: false,
- error: `Authentication failed: Invalid API key.`,
- };
+export async function validateMagicalApiKey({
+ apiKey,
+}: {
+ apiKey: string;
+}): Promise<{ valid: true } | { valid: false; error: string }> {
+ if (!apiKey || apiKey.trim().length === 0) {
+ return { valid: false, error: 'API Key is required.' };
+ }
+ try {
+ await magicalApiRequest({
+ apiKey,
+ path: VALIDATION_PATH,
+ body: { request_id: VALIDATION_REQUEST_ID },
+ });
+ return { valid: true };
+ } catch (error) {
+ if (!(error instanceof MagicalApiError)) {
+ return { valid: false, error: 'Could not reach MagicalAPI to check the API key. Try again later.' };
}
- },
-});
\ No newline at end of file
+ if (error.status === 401) {
+ return { valid: false, error: 'Invalid API key.' };
+ }
+ if (error.status === 404 || error.status === 400) {
+ return { valid: true };
+ }
+ return { valid: false, error: error.message };
+ }
+}
+
+const VALIDATION_PATH = '/resume-parser';
+const VALIDATION_REQUEST_ID = 'activepieces-connection-check';
diff --git a/packages/pieces/community/magical-api/src/lib/common/client.ts b/packages/pieces/community/magical-api/src/lib/common/client.ts
index b3beb64031b..fe26584569b 100644
--- a/packages/pieces/community/magical-api/src/lib/common/client.ts
+++ b/packages/pieces/community/magical-api/src/lib/common/client.ts
@@ -1,34 +1,136 @@
-import { HttpMethod, httpClient } from "@activepieces/pieces-common";
-import { AppConnectionValueForAuthProperty } from "@activepieces/pieces-framework";
-import { magicalApiAuth } from "./auth";
-
-export const BASE_URL = "https://gw.magicalapi.com";
-
-export async function makeRequest(
- apiKey: AppConnectionValueForAuthProperty<typeof magicalApiAuth>,
- method: HttpMethod,
- path: string,
- body?: any
-): Promise<any> {
- try {
- const headers: Record<string, string> = {
- "api-key": apiKey.secret_text,
- "Content-Type": "application/json",
- };
+import { HttpMethod, httpClient } from '@activepieces/pieces-common';
- const response = await httpClient.sendRequest({
- method,
+export async function magicalApiRequest({
+ apiKey,
+ path,
+ body,
+}: {
+ apiKey: string;
+ path: string;
+ body: Record<string, string>;
+}): Promise<MagicalApiResponse> {
+ try {
+ const response = await httpClient.sendRequest<MagicalApiResponseBody>({
+ method: HttpMethod.POST,
url: `${BASE_URL}${path}`,
- headers,
- body: body,
+ headers: {
+ 'api-key': apiKey.trim(),
+ 'Content-Type': 'application/json',
+ },
+ body,
+ });
+ return { status: response.status, body: response.body ?? {} };
+ } catch (error) {
+ throw toMagicalApiError(error);
+ }
+}
+
+export function toMagicalApiError(error: unknown): MagicalApiError {
+ if (error instanceof MagicalApiError) {
+ return error;
+ }
+ const { status, responseBody } = extractHttpFailure(error);
+ if (status === undefined) {
+ const reason = error instanceof Error ? error.message : String(error);
+ return new MagicalApiError({
+ status: 0,
+ message: `MagicalAPI request failed before a response was received: ${reason}`,
+ responseBody: undefined,
});
+ }
+ return new MagicalApiError({
+ status,
+ message: describeStatus({ status, vendorMessage: readVendorMessage(responseBody) }),
+ responseBody,
+ });
+}
+
+export class MagicalApiError extends Error {
+ readonly status: number;
+ readonly responseBody: unknown;
+
+ constructor({ status, message, responseBody }: { status: number; message: string; responseBody: unknown }) {
+ super(message);
+ this.name = 'MagicalApiError';
+ this.status = status;
+ this.responseBody = responseBody;
+ }
+}
+
+export const BASE_URL = 'https://gw.magicalapi.com';
- return response.body;
- } catch (error: any) {
- throw new Error(
- `MagicalAPI request failed: ${JSON.stringify(
- error.response?.body || error.message || error
- )}`
- );
+function extractHttpFailure(error: unknown): { status: number | undefined; responseBody: unknown } {
+ if (typeof error !== 'object' || error === null) {
+ return { status: undefined, responseBody: undefined };
}
-}
\ No newline at end of file
+ if ('errorMessage' in error && typeof error.errorMessage === 'function') {
+ const details: unknown = error.errorMessage();
+ const fromDetails = readResponse(details);
+ if (fromDetails.status !== undefined) {
+ return fromDetails;
+ }
+ }
+ return readResponse(error);
+}
+
+function readResponse(value: unknown): { status: number | undefined; responseBody: unknown } {
+ if (typeof value !== 'object' || value === null || !('response' in value)) {
+ return { status: undefined, responseBody: undefined };
+ }
+ const response = value.response;
+ if (typeof response !== 'object' || response === null) {
+ return { status: undefined, responseBody: undefined };
+ }
+ const status = 'status' in response && typeof response.status === 'number' ? response.status : undefined;
+ const responseBody = 'body' in response ? response.body : undefined;
+ return { status, responseBody };
+}
+
+function readVendorMessage(responseBody: unknown): string | undefined {
+ if (typeof responseBody === 'string' && responseBody.length > 0) {
+ return responseBody.slice(0, 500);
+ }
+ if (typeof responseBody === 'object' && responseBody !== null && 'message' in responseBody) {
+ const message = responseBody.message;
+ if (typeof message === 'string' && message.length > 0) {
+ return message;
+ }
+ }
+ return undefined;
+}
+
+function describeStatus({ status, vendorMessage }: { status: number; vendorMessage: string | undefined }): string {
+ const suffix = vendorMessage ? ` MagicalAPI says: "${vendorMessage}"` : '';
+ switch (status) {
+ case 400:
+ return `MagicalAPI rejected the request as invalid (400).${suffix}`;
+ case 401:
+ return `MagicalAPI rejected the API key (401). Check the key in your connection.${suffix}`;
+ case 402:
+ return `MagicalAPI account is out of credits or the plan does not include API access (402). Recharge credits or upgrade the plan in the MagicalAPI dashboard.${suffix}`;
+ case 403:
+ return `MagicalAPI does not allow this service with this API key (403).${suffix}`;
+ case 404:
+ if (vendorMessage?.toLowerCase().includes('request id')) {
+ return `MagicalAPI does not know this Request ID (404). A Request ID only works with the service that created it, and a finished result can be fetched only once.${suffix}`;
+ }
+ return `MagicalAPI could not find what was requested (404); no credits are charged for a lookup that finds nothing.${suffix}`;
+ case 429:
+ return `MagicalAPI rate limit reached (429). Wait a moment and try again.${suffix}`;
+ default:
+ if (status >= 500) {
+ return `MagicalAPI had a server error (${status}). Try again later.${suffix}`;
+ }
+ return `MagicalAPI request failed with status ${status}.${suffix}`;
+ }
+}
+
+export type MagicalApiResponseBody = {
+ data?: Record<string, unknown>;
+ usage?: { credits?: number };
+};
+
+export type MagicalApiResponse = {
+ status: number;
+ body: MagicalApiResponseBody;
+};
diff --git a/packages/pieces/community/magical-api/src/lib/common/output-schemas.ts b/packages/pieces/community/magical-api/src/lib/common/output-schemas.ts
new file mode 100644
index 00000000000..b2f32325148
--- /dev/null
+++ b/packages/pieces/community/magical-api/src/lib/common/output-schemas.ts
@@ -0,0 +1,319 @@
+import { OutputSchema, OutputSchemaField } from '@activepieces/pieces-framework';
+
+const yearMonthFields: OutputSchemaField[] = [
+ { key: 'year', label: 'Year', format: 'number' },
+ { key: 'month', label: 'Month', format: 'number' },
+];
+
+const durationFields: OutputSchemaField[] = [
+ { key: 'years', label: 'Years', format: 'number' },
+ { key: 'months', label: 'Months', format: 'number' },
+];
+
+const startEndDateFields: OutputSchemaField[] = [
+ { key: 'start_date', label: 'Start Date' },
+ { key: 'end_date', label: 'End Date' },
+];
+
+const sectionReviewFields: OutputSchemaField[] = [
+ { key: 'pros', label: 'Pros' },
+ {
+ key: 'cons',
+ label: 'Cons',
+ labelKey: 'message',
+ listItems: [
+ { key: 'message', label: 'Message' },
+ { key: 'tips', label: 'Tips' },
+ ],
+ },
+];
+
+const matchFeedbackFields: OutputSchemaField[] = [
+ { key: 'type', label: 'Type' },
+ { key: 'message', label: 'Message' },
+];
+
+const matchSectionFields: OutputSchemaField[] = [
+ { key: 'score', label: 'Score', format: 'number' },
+ { key: 'summary', label: 'Summary' },
+ { key: 'pros', label: 'Pros', labelKey: 'message', listItems: matchFeedbackFields },
+ { key: 'cons', label: 'Cons', labelKey: 'message', listItems: matchFeedbackFields },
+ { key: 'warns', label: 'Warnings', labelKey: 'message', listItems: matchFeedbackFields },
+];
+
+const textCategoryFields: OutputSchemaField[] = [
+ { key: 'text', label: 'Text' },
+ { key: 'category', label: 'Category' },
+];
+
+export const parseResumeOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'basic',
+ label: 'Basic Info',
+ children: [
+ { key: 'first_name', label: 'First Name' },
+ { key: 'last_name', label: 'Last Name' },
+ { key: 'job_title', label: 'Job Title' },
+ { key: 'email', label: 'Email', format: 'email' },
+ { key: 'phone_number', label: 'Phone Number' },
+ { key: 'location', label: 'Location' },
+ { key: 'birthday', label: 'Birthday' },
+ { key: 'portfolio_website_url', label: 'Portfolio Website', format: 'url' },
+ { key: 'linkedin_url', label: 'LinkedIn URL', format: 'url' },
+ { key: 'github_url', label: 'GitHub URL', format: 'url' },
+ { key: 'university', label: 'University' },
+ { key: 'graduation_year', label: 'Graduation Year' },
+ { key: 'majors', label: 'Majors' },
+ ],
+ },
+ { key: 'summary', label: 'Summary' },
+ {
+ key: 'work_experiences',
+ label: 'Work Experiences',
+ labelKey: 'title',
+ listItems: [
+ { key: 'title', label: 'Title' },
+ { key: 'company', label: 'Company' },
+ { key: 'location', label: 'Location' },
+ { key: 'summary', label: 'Summary' },
+ { key: 'achievements', label: 'Achievements' },
+ { key: 'start', label: 'Start', children: yearMonthFields },
+ { key: 'end', label: 'End', children: yearMonthFields },
+ { key: 'duration', label: 'Duration', children: durationFields },
+ ],
+ },
+ {
+ key: 'project_experiences',
+ label: 'Project Experiences',
+ labelKey: 'title',
+ listItems: [
+ { key: 'title', label: 'Title' },
+ { key: 'description', label: 'Description' },
+ ],
+ },
+ {
+ key: 'educations',
+ label: 'Educations',
+ labelKey: 'school',
+ listItems: [
+ { key: 'school', label: 'School' },
+ { key: 'degree', label: 'Degree' },
+ { key: 'field', label: 'Field of Study' },
+ { key: 'start', label: 'Start', children: yearMonthFields },
+ { key: 'end', label: 'End', children: yearMonthFields },
+ ],
+ },
+ {
+ key: 'certifications',
+ label: 'Certifications',
+ labelKey: 'title',
+ listItems: [
+ { key: 'title', label: 'Title' },
+ { key: 'provider', label: 'Provider' },
+ ],
+ },
+ { key: 'languages', label: 'Languages', labelKey: 'name', listItems: [{ key: 'name', label: 'Name' }] },
+ { key: 'interests', label: 'Interests', labelKey: 'name', listItems: [{ key: 'name', label: 'Name' }] },
+ { key: 'skills', label: 'Skills', labelKey: 'name', listItems: [{ key: 'name', label: 'Name' }] },
+ ],
+};
+
+export const reviewResumeOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'score', label: 'Score', format: 'number', description: 'Overall resume score out of 100.' },
+ {
+ key: 'result',
+ label: 'Review',
+ children: [
+ { key: 'contact', label: 'Contact', children: sectionReviewFields },
+ { key: 'experiences', label: 'Experiences', children: sectionReviewFields },
+ { key: 'educations', label: 'Educations', children: sectionReviewFields },
+ { key: 'skills', label: 'Skills', children: sectionReviewFields },
+ { key: 'summary', label: 'Summary', children: sectionReviewFields },
+ { key: 'format', label: 'Format', children: sectionReviewFields },
+ ],
+ },
+ {
+ key: 'suggested',
+ label: 'Suggested Content',
+ children: [
+ { key: 'summary', label: 'Summary', value: 'summary.content' },
+ { key: 'contact', label: 'Contact', value: 'contact.content' },
+ { key: 'experiences', label: 'Experiences', value: 'experiences.content' },
+ { key: 'educations', label: 'Educations', value: 'educations.content' },
+ ],
+ },
+ ],
+};
+
+export const scoreResumeOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'score', label: 'Score', format: 'number', description: 'Match score 0-100; -1 if the resume is empty.' },
+ { key: 'summary', label: 'Summary' },
+ { key: 'strengths', label: 'Strengths', labelKey: 'text', listItems: textCategoryFields },
+ { key: 'improvements', label: 'Improvements', labelKey: 'text', listItems: textCategoryFields },
+ { key: 'job_match', label: 'Job Match', children: matchSectionFields },
+ {
+ key: 'skill_match',
+ label: 'Skill Match',
+ children: [
+ { key: 'score', label: 'Score', format: 'number' },
+ { key: 'summary', label: 'Summary' },
+ { key: 'all_skills', label: 'All Job Skills', value: 'skills.all_skills' },
+ {
+ key: 'match_result',
+ label: 'Match Result',
+ children: [
+ { key: 'strong_match', label: 'Strong Match' },
+ { key: 'partial_match', label: 'Partial Match' },
+ { key: 'miss_match', label: 'Missing' },
+ ],
+ },
+ ],
+ },
+ { key: 'education_match', label: 'Education Match', children: matchSectionFields },
+ {
+ key: 'more_information',
+ label: 'More Information',
+ children: [
+ { key: 'region', label: 'Region' },
+ { key: 'overqualification_status', label: 'Overqualified', format: 'boolean' },
+ { key: 'qualification_reason', label: 'Qualification Reason' },
+ ],
+ },
+ ],
+};
+
+export const profileDataOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'url', label: 'Profile URL', format: 'url' },
+ { key: 'profile', label: 'Username' },
+ { key: 'name', label: 'Name' },
+ { key: 'headline', label: 'Headline' },
+ { key: 'description', label: 'Bio' },
+ { key: 'location', label: 'Location' },
+ { key: 'followers', label: 'Followers' },
+ { key: 'connections', label: 'Connections' },
+ { key: 'crawled_at', label: 'Crawled At' },
+ {
+ key: 'experience',
+ label: 'Experience',
+ labelKey: 'title',
+ listItems: [
+ { key: 'title', label: 'Title' },
+ { key: 'company_name', label: 'Company' },
+ { key: 'company_link', label: 'Company Link', format: 'url' },
+ { key: 'location', label: 'Location' },
+ { key: 'description', label: 'Description' },
+ {
+ key: 'date',
+ label: 'Date',
+ children: [...startEndDateFields, { key: 'duration', label: 'Duration', children: durationFields }],
+ },
+ ],
+ },
+ {
+ key: 'education',
+ label: 'Education',
+ labelKey: 'university_name',
+ listItems: [
+ { key: 'university_name', label: 'School' },
+ { key: 'university_link', label: 'School Link', format: 'url' },
+ { key: 'degree', label: 'Degree' },
+ { key: 'major', label: 'Major' },
+ { key: 'date', label: 'Date', children: startEndDateFields },
+ ],
+ },
+ {
+ key: 'certifications',
+ label: 'Certifications',
+ labelKey: 'title',
+ listItems: [
+ { key: 'title', label: 'Title' },
+ { key: 'issuer', label: 'Issuer' },
+ { key: 'issued_date', label: 'Issued Date' },
+ { key: 'credential', label: 'Credential ID' },
+ { key: 'course_link', label: 'Course Link', format: 'url' },
+ ],
+ },
+ {
+ key: 'languages',
+ label: 'Languages',
+ labelKey: 'name',
+ listItems: [
+ { key: 'name', label: 'Name' },
+ { key: 'description', label: 'Proficiency' },
+ ],
+ },
+ {
+ key: 'honors_and_awards',
+ label: 'Honors and Awards',
+ labelKey: 'title',
+ listItems: [
+ { key: 'title', label: 'Title' },
+ { key: 'issuer', label: 'Issuer' },
+ { key: 'issued_date', label: 'Issued Date' },
+ ],
+ },
+ ],
+};
+
+export const companyDataOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'url', label: 'LinkedIn URL', format: 'url' },
+ { key: 'company_name', label: 'LinkedIn Username' },
+ { key: 'name', label: 'Name' },
+ { key: 'tagline', label: 'Tagline' },
+ { key: 'about', label: 'About' },
+ { key: 'website', label: 'Website', format: 'url' },
+ { key: 'industry', label: 'Industry' },
+ { key: 'size', label: 'Company Size' },
+ { key: 'employees', label: 'Employees on LinkedIn' },
+ { key: 'followers', label: 'Followers' },
+ { key: 'headquarters', label: 'Headquarters' },
+ { key: 'organizationType', label: 'Organization Type' },
+ { key: 'foundedOn', label: 'Founded' },
+ { key: 'specialties', label: 'Specialties' },
+ { key: 'logo_url', label: 'Logo', format: 'image' },
+ { key: 'cover_image_url', label: 'Cover Image', format: 'image' },
+ { key: 'crawled_at', label: 'Crawled At' },
+ {
+ key: 'funding',
+ label: 'Funding',
+ children: [
+ {
+ key: 'last_round',
+ label: 'Last Round',
+ children: [
+ { key: 'date', label: 'Date' },
+ { key: 'type', label: 'Type' },
+ { key: 'raised_amount', label: 'Raised Amount' },
+ ],
+ },
+ { key: 'rounds_count', label: 'Rounds Count', format: 'number' },
+ { key: 'crunchbase_url', label: 'Crunchbase URL', format: 'url' },
+ ],
+ },
+ {
+ key: 'posts',
+ label: 'Recent Posts',
+ labelKey: 'text',
+ listItems: [
+ { key: 'text', label: 'Text' },
+ { key: 'post_url', label: 'Post URL', format: 'url' },
+ { key: 'time', label: 'Posted' },
+ { key: 'likes_count', label: 'Likes', format: 'number' },
+ { key: 'comments_count', label: 'Comments', format: 'number' },
+ ],
+ },
+ ],
+};
+
+export const jobResultOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'status', label: 'Status', description: '"ready" when the result is in data, "processing" otherwise.' },
+ { key: 'request_id', label: 'Request ID' },
+ { key: 'data', label: 'Result', description: 'The finished result; same shape as the action that started the job.' },
+ ],
+};
diff --git a/packages/pieces/community/magical-api/src/lib/common/poll.ts b/packages/pieces/community/magical-api/src/lib/common/poll.ts
new file mode 100644
index 00000000000..e7690ac9d9c
--- /dev/null
+++ b/packages/pieces/community/magical-api/src/lib/common/poll.ts
@@ -0,0 +1,149 @@
+import { magicalApiRequest } from './client';
+
+export async function fetchJobResult({
+ apiKey,
+ service,
+ requestId,
+}: {
+ apiKey: string;
+ service: MagicalApiService;
+ requestId: string;
+}): Promise<JobResult> {
+ const response = await magicalApiRequest({
+ apiKey,
+ path: SERVICES[service].path,
+ body: { request_id: requestId.trim() },
+ });
+ return toJobResult({ service, data: response.body.data, fallbackRequestId: requestId.trim() });
+}
+
+export async function runJob({
+ apiKey,
+ service,
+ input,
+ requestId,
+ sleep = defaultSleep,
+}: {
+ apiKey: string;
+ service: MagicalApiService;
+ input: Record<string, string>;
+ requestId: string | undefined;
+ sleep?: (ms: number) => Promise<void>;
+}): Promise<Record<string, unknown>> {
+ const trimmedRequestId = normalizeRequestId(requestId);
+ let result: JobResult;
+ if (trimmedRequestId) {
+ result = await fetchJobResult({ apiKey, service, requestId: trimmedRequestId });
+ } else {
+ const response = await magicalApiRequest({ apiKey, path: SERVICES[service].path, body: input });
+ result = toJobResult({ service, data: response.body.data, fallbackRequestId: undefined });
+ }
+ if (result.status === 'ready') {
+ return result.data;
+ }
+ const pendingId = result.request_id;
+ if (!pendingId) {
+ throw new Error(
+ `MagicalAPI did not return a Request ID or a finished result for ${SERVICES[service].label}. Response data: ${JSON.stringify(result.data).slice(0, 500)}`,
+ );
+ }
+ for (let attempt = 0; attempt < POLL_MAX_ATTEMPTS; attempt++) {
+ await sleep(POLL_INTERVAL_MS);
+ const polled = await fetchJobResult({ apiKey, service, requestId: pendingId });
+ if (polled.status === 'ready') {
+ return polled.data;
+ }
+ }
+ throw new Error(
+ `${SERVICES[service].label} is still processing after ${(POLL_MAX_ATTEMPTS * POLL_INTERVAL_MS) / 1000} seconds. Run the step again with Request ID ${pendingId} (or use Get Job Result) to get the result without starting (and paying for) a new job.`,
+ );
+}
+
+export function normalizeRequestId(requestId: string | null | undefined): string | undefined {
+ if (requestId === undefined || requestId === null || requestId === '') {
+ return undefined;
+ }
+ const trimmed = requestId.trim();
+ if (trimmed.length === 0) {
+ throw new Error(
+ 'Request ID is blank. Paste the Request ID from an earlier run to get its result, or clear the field to start a new (paid) request.',
+ );
+ }
+ return trimmed;
+}
+
+export function isHttpUrl(value: string): boolean {
+ try {
+ const parsed = new URL(value);
+ return parsed.protocol === 'http:' || parsed.protocol === 'https:';
+ } catch {
+ return false;
+ }
+}
+
+export const POLL_MAX_ATTEMPTS = 20;
+export const POLL_INTERVAL_MS = 3000;
+
+export const SERVICES: Record<MagicalApiService, ServiceDefinition> = {
+ resume_parser: {
+ path: '/resume-parser',
+ label: 'Resume parsing',
+ isReady: (data) => data['basic'] !== undefined,
+ },
+ resume_review: {
+ path: '/resume-review',
+ label: 'Resume review',
+ isReady: (data) => data['score'] !== undefined,
+ },
+ resume_score: {
+ path: '/resume-score',
+ label: 'Resume scoring',
+ isReady: (data) => data['score'] !== undefined,
+ },
+ profile_data: {
+ path: '/profile-data',
+ label: 'LinkedIn profile lookup',
+ isReady: (data) => data['profile'] !== undefined,
+ },
+ company_data: {
+ path: '/company-data',
+ label: 'LinkedIn company lookup',
+ isReady: (data) => data['company_name'] !== undefined,
+ },
+};
+
+function toJobResult({
+ service,
+ data,
+ fallbackRequestId,
+}: {
+ service: MagicalApiService;
+ data: Record<string, unknown> | undefined;
+ fallbackRequestId: string | undefined;
+}): JobResult {
+ const payload = data ?? {};
+ if (SERVICES[service].isReady(payload)) {
+ return { status: 'ready', request_id: fallbackRequestId ?? null, data: payload };
+ }
+ const returnedId = payload['request_id'];
+ const requestId = typeof returnedId === 'string' && returnedId.length > 0 ? returnedId : fallbackRequestId;
+ return { status: 'processing', request_id: requestId ?? null, data: payload };
+}
+
+function defaultSleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+export type MagicalApiService = 'resume_parser' | 'resume_review' | 'resume_score' | 'profile_data' | 'company_data';
+
+type ServiceDefinition = {
+ path: string;
+ label: string;
+ isReady: (data: Record<string, unknown>) => boolean;
+};
+
+export type JobResult = {
+ status: 'ready' | 'processing';
+ request_id: string | null;
+ data: Record<string, unknown>;
+};
diff --git a/packages/pieces/community/magical-api/test/magical-api.test.ts b/packages/pieces/community/magical-api/test/magical-api.test.ts
new file mode 100644
index 00000000000..971a9fa9dc3
--- /dev/null
+++ b/packages/pieces/community/magical-api/test/magical-api.test.ts
@@ -0,0 +1,267 @@
+/// <reference types="vitest/globals" />
+
+import { HttpError, HttpRequest, HttpResponse, httpClient } from '@activepieces/pieces-common';
+import { validateMagicalApiKey } from '../src/lib/common/auth';
+import { MagicalApiError, magicalApiRequest } from '../src/lib/common/client';
+import { fetchJobResult, runJob, POLL_MAX_ATTEMPTS } from '../src/lib/common/poll';
+import { toProfileSlug } from '../src/lib/actions/get-profile-data';
+import { magicalApi } from '../src/index';
+import { AppConnectionType, createMockActionContext } from '@activepieces/pieces-framework';
+import { parseResume } from '../src/lib/actions/parse-resume';
+import { reviewResume } from '../src/lib/actions/review-resume';
+import { scoreResume } from '../src/lib/actions/score-resume';
+import { getProfileData } from '../src/lib/actions/get-profile-data';
+import { getCompanyData } from '../src/lib/actions/get-company-data';
+
+let sendRequest: ReturnType<typeof vi.spyOn>;
+let requests: HttpRequest[];
+
+beforeEach(() => {
+ requests = [];
+ sendRequest = vi.spyOn(httpClient, 'sendRequest');
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+function respondWith(...responses: Array<{ status: number; body: unknown }>) {
+ let index = 0;
+ sendRequest.mockImplementation(async (request: HttpRequest): Promise<HttpResponse> => {
+ requests.push(request);
+ const next = responses[Math.min(index, responses.length - 1)];
+ index++;
+ if (next.status >= 400) {
+ throw new HttpError(request.body, { status: next.status, responseBody: next.body });
+ }
+ return { status: next.status, headers: {}, body: next.body };
+ });
+}
+
+const noSleep = async () => undefined;
+
+describe('magicalApiRequest', () => {
+ it('sends POST with api-key header and JSON body to the gateway', async () => {
+ respondWith({ status: 201, body: { data: { request_id: 'r1' } } });
+ await magicalApiRequest({ apiKey: ' key ', path: '/profile-data', body: { profile_name: 'williamhgates' } });
+ expect(requests[0]).toMatchObject({
+ method: 'POST',
+ url: 'https://gw.magicalapi.com/profile-data',
+ headers: { 'api-key': 'key', 'Content-Type': 'application/json' },
+ body: { profile_name: 'williamhgates' },
+ });
+ });
+
+ it.each([
+ [401, 'rejected the API key'],
+ [402, 'out of credits'],
+ [429, 'rate limit'],
+ [500, 'server error'],
+ ])('maps %i to MagicalApiError with status and responseBody', async (status, text) => {
+ const vendorBody = { message: 'vendor says no' };
+ respondWith({ status, body: vendorBody });
+ const error = await magicalApiRequest({ apiKey: 'k', path: '/resume-parser', body: { url: 'https://x.io/a.pdf' } }).catch(
+ (e: unknown) => e,
+ );
+ expect(error).toBeInstanceOf(MagicalApiError);
+ if (!(error instanceof MagicalApiError)) return;
+ expect(error.status).toBe(status);
+ expect(error.responseBody).toEqual(vendorBody);
+ expect(error.message).toContain(text);
+ expect(error.message).toContain('vendor says no');
+ expect(error).not.toHaveProperty('body');
+ });
+
+ it('reports network failures without a status', async () => {
+ sendRequest.mockRejectedValue(new Error('ECONNRESET'));
+ const error = await magicalApiRequest({ apiKey: 'k', path: '/x', body: {} }).catch((e: unknown) => e);
+ expect(error).toBeInstanceOf(MagicalApiError);
+ if (!(error instanceof MagicalApiError)) return;
+ expect(error.status).toBe(0);
+ expect(error.message).toContain('ECONNRESET');
+ });
+});
+
+describe('validateMagicalApiKey', () => {
+ it('uses a dummy request_id poll, never a billable job', async () => {
+ respondWith({ status: 404, body: { message: 'request id not found!' } });
+ await expect(validateMagicalApiKey({ apiKey: 'good' })).resolves.toEqual({ valid: true });
+ expect(requests).toHaveLength(1);
+ expect(requests[0].body).toEqual({ request_id: 'activepieces-connection-check' });
+ expect(Object.keys(requests[0].body ?? {})).toEqual(['request_id']);
+ });
+
+ it('reports invalid key only on 401', async () => {
+ respondWith({ status: 401, body: { message: 'Unauthorized!' } });
+ await expect(validateMagicalApiKey({ apiKey: 'bad' })).resolves.toEqual({ valid: false, error: 'Invalid API key.' });
+ });
+
+ it('surfaces 402 plan restriction honestly', async () => {
+ respondWith({ status: 402, body: { message: 'API access not available for this plan.' } });
+ const result = await validateMagicalApiKey({ apiKey: 'k' });
+ expect(result.valid).toBe(false);
+ if (result.valid) return;
+ expect(result.error).toContain('402');
+ expect(result.error).not.toBe('Invalid API key.');
+ });
+
+ it('surfaces 5xx as a non-auth failure', async () => {
+ respondWith({ status: 503, body: 'down' });
+ const result = await validateMagicalApiKey({ apiKey: 'k' });
+ expect(result.valid).toBe(false);
+ if (result.valid) return;
+ expect(result.error).toContain('server error');
+ });
+
+ it('rejects an empty key without a request', async () => {
+ await expect(validateMagicalApiKey({ apiKey: ' ' })).resolves.toMatchObject({ valid: false });
+ expect(requests).toHaveLength(0);
+ });
+});
+
+describe('runJob', () => {
+ it('returns immediately when the first response is finished', async () => {
+ respondWith({ status: 200, body: { data: { basic: { first_name: 'Ann' } } } });
+ const data = await runJob({ apiKey: 'k', service: 'resume_parser', input: { url: 'https://x.io/a.pdf' }, requestId: undefined, sleep: noSleep });
+ expect(data).toEqual({ basic: { first_name: 'Ann' } });
+ expect(requests[0].body).toEqual({ url: 'https://x.io/a.pdf' });
+ });
+
+ it('polls the same endpoint with the returned request_id until ready', async () => {
+ respondWith(
+ { status: 201, body: { data: { request_id: 'abc' } } },
+ { status: 200, body: { data: { request_id: 'abc' } } },
+ { status: 200, body: { data: { score: 80, summary: 's' } } },
+ );
+ const data = await runJob({ apiKey: 'k', service: 'resume_score', input: { url: 'u', job_description: 'jd' }, requestId: undefined, sleep: noSleep });
+ expect(data).toEqual({ score: 80, summary: 's' });
+ expect(requests.map((r) => r.url)).toEqual(Array(3).fill('https://gw.magicalapi.com/resume-score'));
+ expect(requests[1].body).toEqual({ request_id: 'abc' });
+ });
+
+ it('resumes with a given request_id without starting a new job', async () => {
+ respondWith({ status: 200, body: { data: { company_name: 'microsoft' } } });
+ await runJob({ apiKey: 'k', service: 'company_data', input: { company_name: 'Microsoft' }, requestId: ' r9 ', sleep: noSleep });
+ expect(requests).toHaveLength(1);
+ expect(requests[0].body).toEqual({ request_id: 'r9' });
+ });
+
+ it('rejects a whitespace-only request_id before any request', async () => {
+ respondWith({ status: 201, body: { data: { request_id: 'new-paid-job' } } });
+ await expect(
+ runJob({ apiKey: 'k', service: 'resume_parser', input: { url: 'https://x.io/a.pdf' }, requestId: ' ', sleep: noSleep }),
+ ).rejects.toThrow('Request ID is blank');
+ expect(requests).toHaveLength(0);
+ });
+
+ it('every new-job action rejects a whitespace-only request_id even with valid new-job inputs', async () => {
+ respondWith({ status: 201, body: { data: { request_id: 'new-paid-job' } } });
+ const auth: { type: AppConnectionType.SECRET_TEXT; secret_text: string } = { type: AppConnectionType.SECRET_TEXT, secret_text: 'k' };
+ const url = 'https://x.io/a.pdf';
+ const request_id = ' ';
+ const runs = [
+ () => parseResume.run({ ...createMockActionContext<typeof parseResume.props>({ propsValue: { url, request_id } }), auth }),
+ () => reviewResume.run({ ...createMockActionContext<typeof reviewResume.props>({ propsValue: { url, request_id } }), auth }),
+ () => scoreResume.run({ ...createMockActionContext<typeof scoreResume.props>({ propsValue: { url, job_description: 'jd', request_id } }), auth }),
+ () => getProfileData.run({ ...createMockActionContext<typeof getProfileData.props>({ propsValue: { profile_name: 'satyanadella', request_id } }), auth }),
+ () =>
+ getCompanyData.run({
+ ...createMockActionContext<typeof getCompanyData.props>({
+ propsValue: { company_name: 'Microsoft', company_username: undefined, company_website: undefined, request_id },
+ }),
+ auth,
+ }),
+ ];
+ for (const run of runs) {
+ await expect(run()).rejects.toThrow('Request ID is blank');
+ }
+ expect(requests).toHaveLength(0);
+ });
+
+ it('times out with the Request ID after the attempt budget', async () => {
+ respondWith({ status: 201, body: { data: { request_id: 'slow' } } });
+ await expect(
+ runJob({ apiKey: 'k', service: 'profile_data', input: { profile_name: 'x' }, requestId: undefined, sleep: noSleep }),
+ ).rejects.toThrow('Request ID slow');
+ expect(requests).toHaveLength(POLL_MAX_ATTEMPTS + 1);
+ });
+
+ it('fails clearly when neither request_id nor result comes back', async () => {
+ respondWith({ status: 200, body: { data: {} } });
+ await expect(
+ runJob({ apiKey: 'k', service: 'resume_review', input: { url: 'u' }, requestId: undefined, sleep: noSleep }),
+ ).rejects.toThrow('did not return a Request ID');
+ });
+
+ it('keeps vendor error status during polling', async () => {
+ respondWith({ status: 201, body: { data: { request_id: 'abc' } } }, { status: 500, body: { message: 'File format not Acceptable' } });
+ const error = await runJob({ apiKey: 'k', service: 'resume_parser', input: { url: 'u' }, requestId: undefined, sleep: noSleep }).catch((e: unknown) => e);
+ expect(error).toBeInstanceOf(MagicalApiError);
+ expect(String(error)).toContain('File format not Acceptable');
+ });
+});
+
+describe('fetchJobResult', () => {
+ it('reports processing with the request id', async () => {
+ respondWith({ status: 201, body: { data: { request_id: 'abc' } } });
+ await expect(fetchJobResult({ apiKey: 'k', service: 'profile_data', requestId: 'abc' })).resolves.toEqual({
+ status: 'processing',
+ request_id: 'abc',
+ data: { request_id: 'abc' },
+ });
+ expect(requests).toHaveLength(1);
+ });
+
+ it('reports ready with data', async () => {
+ respondWith({ status: 200, body: { data: { profile: 'williamhgates', name: 'Bill' } } });
+ const result = await fetchJobResult({ apiKey: 'k', service: 'profile_data', requestId: 'abc' });
+ expect(result).toEqual({ status: 'ready', request_id: 'abc', data: { profile: 'williamhgates', name: 'Bill' } });
+ });
+});
+
+describe('toProfileSlug', () => {
+ it.each([
+ ['williamhgates', 'williamhgates'],
+ ['https://www.linkedin.com/in/williamhgates/', 'williamhgates'],
+ ['linkedin.com/in/jane-doe?trk=x', 'jane-doe'],
+ [' @someone/ ', 'someone'],
+ ])('%s -> %s', (input, expected) => {
+ expect(toProfileSlug(input)).toBe(expected);
+ });
+});
+
+describe('piece metadata', () => {
+ it('every non-custom action has outputSchema, classification and aiMetadata', () => {
+ const actions = Object.values(magicalApi.actions());
+ const named = actions.filter((a) => a.name !== 'custom_api_call');
+ expect(named).toHaveLength(6);
+ for (const action of named) {
+ expect(action.outputSchema, action.name).toBeDefined();
+ expect(action.classification, action.name).toBeDefined();
+ expect(action.aiMetadata?.description, action.name).toBeTruthy();
+ }
+ expect(actions.find((a) => a.name === 'get_job_result')?.audience).toBe('ai');
+ });
+});
+
+describe('live-captured shapes', () => {
+ it('treats a 201 running poll as processing', async () => {
+ const running = { status: 'running', message: 'result is not ready yet, try again in a while.', request_id: 'abc' };
+ respondWith({ status: 201, body: { data: running, usage: { credits: 0 } } });
+ await expect(fetchJobResult({ apiKey: 'k', service: 'company_data', requestId: 'abc' })).resolves.toEqual({
+ status: 'processing',
+ request_id: 'abc',
+ data: running,
+ });
+ });
+
+ it('distinguishes an unknown Request ID from a lookup that found nothing', async () => {
+ respondWith({ status: 404, body: { message: 'request id not found!' } });
+ const unknown = await fetchJobResult({ apiKey: 'k', service: 'profile_data', requestId: 'x' }).catch((e: unknown) => e);
+ expect(String(unknown)).toContain('fetched only once');
+ respondWith({ status: 404, body: { message: 'LinkedIn page not found for this company!', usage: { credits: -150 } } });
+ const notFound = await fetchJobResult({ apiKey: 'k', service: 'company_data', requestId: 'x' }).catch((e: unknown) => e);
+ expect(String(notFound)).toContain('LinkedIn page not found');
+ expect(String(notFound)).not.toContain('fetched only once');
+ });
+});
diff --git a/packages/pieces/community/magical-api/vitest.config.ts b/packages/pieces/community/magical-api/vitest.config.ts
new file mode 100644
index 00000000000..ba8ade4a178
--- /dev/null
+++ b/packages/pieces/community/magical-api/vitest.config.ts
@@ -0,0 +1,17 @@
+import path from 'path'
+import { defineConfig } from 'vitest/config'
+
+const repoRoot = path.resolve(__dirname, '../../../..')
+
+export default defineConfig({
+ test: {
+ globals: true,
+ environment: 'node',
+ },
+ resolve: {
+ alias: {
+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),
+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),
+ },
+ },
+})