Margo
Open menu

CrewAI integration

Give your CrewAI agent the ability to find local business leads

Margo gives CrewAI agents real-world prospecting capability: find local businesses, return emails and phones, filter by category and location, and deliver structured lead data to your crew.

CrewAI workflow ideas

SDR agent crew

A Researcher finds leads, a Writer drafts emails, and a Sender triggers outreach.

Market mapping agent

Map all businesses of a given type in a territory and summarise market saturation.

Lead scoring crew

Use a bounded batch, inspect available website and review signals, then shortlist records for human review.

Partnership research

Find potential local business partners and produce a shortlist with rationale.

Install and configure the tool

Install requests and crewai, set MARGO_API_KEY in your environment, and import find_leads into your agent’s tools list. Direct API access requires an eligible Business account, verified email and available quota. Start with a small reviewed category/country/state search.

The example makes one POST, then polls the returned job up to 60 times. It stops on HTTP errors, failed jobs, unknown responses or timeout. Do not blindly retry a search after an uncertain outcome. A missing contact field remains unknown; generated records are not guaranteed verified emails.

Download the Python example

Example CrewAI tool

"""Bounded Margo search for CrewAI. Requires requests and crewai.

Set MARGO_API_KEY in your environment. This example performs one search,
polls the existing job and returns a review receipt; it does not send outreach.
"""
import json
import os
import re
import time
import uuid
from urllib.parse import urljoin, urlsplit

import requests
from crewai.tools import tool

BASE = "https://www.margoleads.io"


def safe_poll_url(value):
    url = urljoin(BASE, value)
    parts = urlsplit(url)
    if (parts.scheme != "https" or parts.netloc != "www.margoleads.io"
            or not re.fullmatch(r"/api/v1/leads/jobs/[A-Za-z0-9_-]+", parts.path)
            or parts.query or parts.fragment):
        raise ValueError("Unexpected polling destination")
    return url


def search_leads(category, country, state, max_results=10, request_key=None):
    category, country, state = category.strip(), country.strip().upper(), state.strip()
    if not category or not state or not re.fullmatch(r"[A-Z]{2}", country):
        raise ValueError("Use a category, geography and two-letter country code")
    if not isinstance(max_results, int) or isinstance(max_results, bool) or not 1 <= max_results <= 100:
        raise ValueError("max_results must be an integer from 1 to 100")
    key = os.environ["MARGO_API_KEY"]
    headers = {"Authorization": f"Bearer {key}",
               "Idempotency-Key": request_key or str(uuid.uuid4())}
    # Do not automatically retry POST: the compatibility handler may not
    # honour idempotency. A timeout needs reconciliation, not another search.
    response = requests.post(BASE + "/api/v1/leads/generate", headers=headers,
        json={"source": "google_maps", "category": category,
              "country": country.upper(), "state": state, "maxResults": max_results},
        timeout=30, allow_redirects=False)
    for attempt in range(61):
        if not 200 <= response.status_code < 300:
            raise RuntimeError(f"Margo HTTP {response.status_code}; review access, quota or request before retrying")
        data = response.json()
        if not isinstance(data, dict):
            raise ValueError("Unexpected Margo response")
        job = data.get("job") or {}
        terminal = data.get("terminal") or {}
        status = str(terminal.get("status") or job.get("status") or data.get("status") or "").upper()
        if status in {"FAILED", "CANCELLED", "NEEDS_ATTENTION"}:
            raise RuntimeError(f"Margo job {status}; review the existing job")
        pending = status in {"QUEUED", "RUNNING"} or response.status_code == 202
        if pending:
            if attempt == 60:
                raise TimeoutError("Polling limit reached; inspect the existing job, do not resubmit")
            poll_url = data.get("pollUrl")
            if not isinstance(poll_url, str) or not poll_url:
                raise ValueError("Missing pollUrl for pending job")
            poll_url = safe_poll_url(poll_url)
            try:
                delay = max(2, min(60, int(response.headers.get("Retry-After", "2"))))
            except (ValueError, TypeError):
                delay = 2
            time.sleep(delay)
            response = requests.get(poll_url, headers={"Authorization": f"Bearer {key}"},
                                    timeout=30, allow_redirects=False)
            continue
        result = job.get("result") or data
        leads = result.get("leads") if isinstance(result, dict) else None
        # Compatibility responses have a top-level leads array and no terminal.
        if status not in {"", "COMPLETE", "PARTIAL", "EMPTY"} or not isinstance(leads, list):
            raise ValueError("Unknown terminal status or missing leads array")
        return {"status": status or "REVIEW", "deliveredCount": len(leads),
                "requestedCount": max_results, "stopReason": terminal.get("stopReason"),
                "limitations": data.get("limitations", []),
                "constraintCoverage": data.get("constraintCoverage", {}), "leads": leads}
    raise TimeoutError("Polling limit reached")


@tool("Margo Lead Finder")
def find_leads(category: str, country: str, state: str, max_results: int = 10) -> str:
    """Find local business prospects and return records plus limitations for review.

    country is an ISO two-letter code; state is the target city or region.
    An eligible Business API account and verified email are required.
    """
    return json.dumps(search_leads(category, country, state, max_results))

Frequently asked questions

What's the difference between LangChain and CrewAI integration?

They use the same REST API. CrewAI typically registers Margo through a @tool decorator while LangChain uses a Tool wrapper.

Can multiple agents call Margo?

Yes. Multiple agents can call Margo with the same API key. Rate limits depend on your plan.

Is there a CrewAI template?

A template is planned. The current API is simple enough to register as a CrewAI tool directly.

Illustration of structured lead data used by a CrewAI agent

Try now

Get verified leads without the manual work.

Start building with Margo
Margo + CrewAI: Lead Generation Tool for AI Agents | Margo