Skip to content

hashgraph-online/awesome-codex-plugins / plugins/aklofas/kicad-happy/skills/lcsc

Search LCSC Electronics for electronic components — find parts by LCSC number (Cxxxxx) or MPN, check stock/pricing, download datasheets, analyze specifications. Sister company to JLCPCB, same parts library. Sync and maintain a local datasheets directory for a KiCad project, or use batch MPN-list seeding (`--mpn-list`) for bulk workflows without a project. No API key needed — uses the free jlcsearch community API. Use this skill when the user mentions LCSC, JLCPCB parts library, JLCPCB assembly parts, production sourcing, Cxxxxx part numbers, needs to find LCSC equivalents for parts, is preparing a BOM for JLCPCB assembly, or wants to download datasheets and LCSC is available. For package cross-reference tables and BOM workflow, see the `bom` skill.

FileKindSize
SKILL.mdskill md11.9 KB
scripts/_core_path.pyscript697 B
scripts/fetch_datasheet_lcsc.pyscript6.5 KB
scripts/provider_lcsc.pyscript14.2 KB
scripts/search_lcsc.pyexecutablescript15.0 KB
scripts/sync_datasheets_lcsc.pyscript2.6 KB
scripts/test_search_lcsc.pyexecutablescript22.6 KB

scripts/provider_lcsc.py

View on GitHub
"""LCSC adapter: auth, search, response accessors, and the provider's sync_one_part strategy chain; the driver is distributor_core.sync. The adapter constants are the per-provider differences the driver reads."""

import json
import re
import sys
import time
import urllib.parse
import urllib.request
from datetime import datetime, timezone
from pathlib import Path

import _core_path  # noqa: F401
from distributor_core.download import (
    _USER_AGENT,
    normalize_url as _normalize_url,
    download_pdf as _download_pdf,
    note_transport_failure,
    try_alternative_sources,
)
from distributor_core.inputs import mpn_from_value
from distributor_core.verify import downloaded_entry, other_part, pick_requested
from distributor_core.manifest import friendly_filename

NAME = "lcsc"
DEFAULT_DELAY = 0.5
ID_KEYS = ("lcsc", "digikey", "mouser")
KEY_PRIORITY = ("lcsc", "digikey", "mouser")
SEARCH_KEY = "lcsc"  # the one distributor-specific number this provider can search with
RENAME_PRESENT = False
FAILED_DETAIL_WITH_URL = False
LABELS = {
    "found": "Found {n} unique parts with identifiers ({k} skipped without an MPN or LCSC part number)",
    "skipped_key": "skipped_no_identifier",
    "total_key": "total_identified_parts",
    "dry_skipped": "Skipped (no MPN or LCSC part number): {k}",
    "summary_skipped": "  Skipped (no MPN or LCSC part number): {k}",
}


def preflight(**kw):
    return {}


def authenticate():
    return {"ctx": None}


def report_tail(out_dir, downloaded, already_present, failed):
    return None


# This provider's datasheet URLs are used as given (no manufacturer redirect unwrapping).
def normalize_url(url):
    return _normalize_url(url, resolve_redirects=False)


def download_pdf(url, output_path):
    return _download_pdf(url, output_path, resolve_redirects=False)


def _parse_extra(component: dict) -> dict:
    """Parse the 'extra' field, which may be a JSON string or a dict."""
    extra = component.get("extra")
    if extra is None:
        return {}
    if isinstance(extra, str):
        try:
            parsed = json.loads(extra)
            component["extra"] = parsed
            return parsed if isinstance(parsed, dict) else {}
        except (json.JSONDecodeError, TypeError, RecursionError):
            return {}
    return extra if isinstance(extra, dict) else {}


def _text(v) -> str:
    return v if isinstance(v, str) else ""


def search_lcsc(query: str, allow_family: bool = False) -> dict | None:
    """Search jlcsearch API for a part. Returns first match with datasheet URL.

    Accepts MPN, LCSC code (Cxxxxx), or keyword search terms.
    """
    url = f"https://jlcsearch.tscircuit.com/api/search?q={urllib.parse.quote(query)}&limit=5&full=true"
    try:
        req = urllib.request.Request(url, headers={"User-Agent": _USER_AGENT})
        with urllib.request.urlopen(req, timeout=15) as resp:
            data = json.loads(resp.read())
    except Exception as e:
        note_transport_failure(e)
        print(f"[LCSC] Search failed: {e}", file=sys.stderr)
        return None

    components = data.get("components") if isinstance(data, dict) else None
    if not isinstance(components, list):
        return None
    components = [c for c in components if isinstance(c, dict)]
    if not components:
        return None

    query_upper = query.upper()

    # Parse extra for all components
    for c in components:
        _parse_extra(c)

    # Prefer the requested part (exact or ordering-suffix MPN), then an exact MPN or LCSC code
    hit = pick_requested(components, query, _get_mpn)
    if hit is not None:
        return hit
    for c in components:
        mpn = _get_mpn(c)
        extra = c.get("extra") or {}
        lcsc_num = _text(extra.get("number")) if isinstance(extra, dict) else ""
        if not lcsc_num:
            lcsc_num = f"C{c.get('lcsc', '')}"
        if mpn.upper() == query_upper or lcsc_num.upper() == query_upper:
            return c

    # For short queries (< 6 chars), fuzzy results are unreliable —
    # "1012C" might match "SI1012CR" which is a completely different part.
    # Only return fuzzy matches for longer, more specific queries.
    if len(query.strip()) < 6:
        return None

    hit = pick_requested(components, query, _get_mpn, allow_family=allow_family)
    if hit is not None:
        return hit

    # Return first result as fuzzy match
    return components[0]


def search_lcsc_direct(lcsc_code: str) -> dict | None:
    """Query LCSC's wmsc API directly for a part by LCSC code (Cxxxxx).

    This is a fallback when jlcsearch returns no results. The wmsc API
    is unauthenticated and returns product details including datasheet URLs.
    """
    if not re.match(r"^C\d+$", lcsc_code, re.IGNORECASE):
        return None

    url = f"https://wmsc.lcsc.com/ftps/wm/product/detail?productCode={lcsc_code.upper()}"
    try:
        req = urllib.request.Request(url, headers={
            "User-Agent": _USER_AGENT,
            "Accept": "application/json",
        })
        with urllib.request.urlopen(req, timeout=15) as resp:
            data = json.loads(resp.read())
    except Exception as e:
        note_transport_failure(e)
        print(f"[LCSC] Direct lookup failed for {lcsc_code}: {e}", file=sys.stderr)
        return None

    # {"result": null} is "no such product", not an empty one
    result = data.get("result") if isinstance(data, dict) and "result" in data else data
    if not isinstance(result, dict) or not result:
        return None

    # Normalize to jlcsearch-compatible dict format
    pdf_url = ""
    pdf_list = result.get("pdfUrl") or result.get("dataSheetUrl") or ""
    if isinstance(pdf_list, str) and pdf_list:
        pdf_url = pdf_list
    elif isinstance(pdf_list, list) and pdf_list:
        pdf_url = pdf_list[0] if isinstance(pdf_list[0], str) else ""

    # The code is the one LCSC answers with, so the identity guard can compare it with the request
    code = _text(result.get("productCode")).strip().upper()
    model = _text(result.get("productModel")) or _text(result.get("modelName"))
    desc = _text(result.get("productDescEn")) or _text(result.get("description"))
    component = {
        "mfr": model,
        "description": desc,
        "datasheet": pdf_url,
        "stock": result.get("stockNumber") or result.get("stockCount") or 0,
        "price": result.get("productPriceList"),
        "lcsc": code.lstrip("C"),
        "extra": {
            "number": code,
            "mpn": model,
            "description": desc,
            "manufacturer": {
                "name": _text(result.get("brandNameEn")) or _text(result.get("manufacturer")),
            },
            "datasheet": {
                "pdf": pdf_url,
            },
        },
    }

    return component


def enrich_with_wmsc(component: dict) -> dict:
    """Fill datasheet URL / MPN / manufacturer from LCSC's product-detail
    endpoint when a jlcsearch hit lacks them (jlcsearch dropped its `extra`
    block). Keeps jlcsearch's stock/price."""
    if not component or _get_datasheet_url(component):
        return component
    code = _get_lcsc_code(component)
    if not code:
        return component
    direct = search_lcsc_direct(code)
    if not direct:
        return component
    merged = dict(component)
    direct_extra = direct.get("extra") or {}
    component_extra = _parse_extra(component) or {}
    merged_extra = {**direct_extra, **component_extra}
    # The shallow merge above lets component_extra['datasheet'] clobber
    # wmsc's — including an empty {} block a stale jlcsearch hit carries.
    # Fall through to wmsc's datasheet block when the
    # component's own has no pdf URL.
    component_ds = component_extra.get("datasheet")
    if not (isinstance(component_ds, dict) and component_ds.get("pdf")):
        direct_ds = direct_extra.get("datasheet")
        if isinstance(direct_ds, dict) and direct_ds.get("pdf"):
            merged_extra["datasheet"] = direct_ds
    merged["extra"] = merged_extra
    if not merged.get("datasheet") and direct.get("datasheet"):
        merged["datasheet"] = direct["datasheet"]
    return merged


def _get_datasheet_url(component: dict) -> str:
    """Extract the best datasheet URL from a jlcsearch component.

    Prefers the direct PDF URL from extra.datasheet.pdf (wmsc.lcsc.com CDN),
    falls back to the top-level datasheet URL (lcsc.com redirect).
    """
    extra = _parse_extra(component)
    ds = extra.get("datasheet") or {}
    if isinstance(ds, dict):
        pdf_url = _text(ds.get("pdf"))
        if pdf_url:
            return pdf_url
    # Fallback to top-level
    return _text(component.get("datasheet"))


def _get_mpn(component: dict) -> str:
    """Extract MPN from component."""
    extra = _parse_extra(component)
    return _text(extra.get("mpn")) or _text(component.get("mfr"))


def _get_lcsc_code(component: dict) -> str:
    """Extract LCSC code (Cxxxxx) from component."""
    extra = _parse_extra(component)
    num = _text(extra.get("number"))
    if num:
        return num
    lcsc_id = component.get("lcsc", "")
    if not isinstance(lcsc_id, (int, str)) or isinstance(lcsc_id, bool):
        return ""
    return f"C{lcsc_id}" if lcsc_id else ""


def _get_manufacturer(component: dict) -> str:
    """Extract manufacturer name from component."""
    extra = _parse_extra(component)
    mfg = extra.get("manufacturer") or {}
    if isinstance(mfg, dict):
        return _text(mfg.get("name"))
    return ""


def _get_description(component: dict) -> str:
    """Extract description from component."""
    extra = _parse_extra(component)
    return _text(extra.get("description")) or _text(component.get("description"))


def sync_one_part(
    part: dict,
    output_dir: Path,
    delay: float,
    ctx,
) -> dict:
    """Download datasheet for one part. Returns updated manifest entry."""
    mpn = part["mpn"]
    lcsc_pn = part.get("lcsc", "")
    now = datetime.now(timezone.utc).isoformat()

    # Use MPN for display/filename if available, otherwise LCSC code
    display_pn = mpn or lcsc_pn

    desc = part.get("description", "")
    mfg = part.get("manufacturer", "")
    filename = friendly_filename(display_pn, desc, mfg) + ".pdf"
    output_path = output_dir / filename

    # Strategy 1: Try the datasheet URL from the schematic itself
    schematic_url = part.get("datasheet", "")
    if schematic_url and schematic_url != "~" and "://" in schematic_url:
        print(f"  Trying schematic URL...", file=sys.stderr)
        if download_pdf(schematic_url, str(output_path)):
            return downloaded_entry(part, output_path, filename, verify_pn=display_pn,
                                    manufacturer=mfg, description=desc, url=schematic_url,
                                    source="schematic", now=now)

    # Strategy 2: Search jlcsearch API
    # Prefer LCSC code (exact match) over MPN keyword search
    search_term = lcsc_pn or mpn
    time.sleep(delay)
    print(f"  Searching LCSC for '{search_term}'...", file=sys.stderr)
    family = mpn_from_value(part)
    component = search_lcsc(search_term, family and not lcsc_pn)
    component = enrich_with_wmsc(component)

    def _other(hit, by_pn):
        if hit is None:
            return ""
        return other_part(lcsc_pn if by_pn else mpn, _get_mpn(hit), [_get_lcsc_code(hit)],
                          by_pn=by_pn, allow_family=family, part_mpn=mpn)

    closest = _other(component, bool(lcsc_pn))
    if closest:
        component = None

    # jlcsearch does not list every LCSC code; LCSC's own product page does
    if component is None and lcsc_pn:
        time.sleep(delay)
        direct = search_lcsc_direct(lcsc_pn)
        mismatch = _other(direct, True)
        if mismatch:
            closest = closest or mismatch
        else:
            component = direct

    # If LCSC code search failed but we have an MPN, try that
    if component is None and lcsc_pn and mpn:
        time.sleep(delay)
        print(f"  LCSC code not found, trying MPN '{mpn}'...", file=sys.stderr)
        component = search_lcsc(mpn, family)
        component = enrich_with_wmsc(component)
        mismatch = _other(component, False)
        if mismatch:
            closest, component = mismatch, None

    if component is not None:
        ds_url = _get_datasheet_url(component)
        lcsc_mpn = _get_mpn(component)
        lcsc_mfg = _get_manufacturer(component) or mfg
        lcsc_desc = _get_description(component) or desc
        lcsc_code = _get_lcsc_code(component)

        # Use the richer LCSC data for filename
        effective_pn = lcsc_mpn or display_pn
        if lcsc_desc:
            filename = friendly_filename(effective_pn, lcsc_desc, lcsc_mfg) + ".pdf"
            output_path = output_dir / filename

        if ds_url:
            print(f"  Downloading from LCSC CDN...", file=sys.stderr)
            if download_pdf(ds_url, str(output_path)):
                return downloaded_entry(part, output_path, filename, verify_pn=mpn or effective_pn,
                                        manufacturer=lcsc_mfg, description=lcsc_desc, url=ds_url,
                                        source="lcsc", now=now, vendor_id=("lcsc", lcsc_code))

    # Strategy 3: Try alternative manufacturer sources
    if mpn:
        print(f"  Trying alternative sources...", file=sys.stderr)
        if try_alternative_sources(mpn, str(output_path)):
            return downloaded_entry(part, output_path, filename, verify_pn=mpn, manufacturer=mfg,
                                    description=desc, url="", source="alternative", now=now,
                                    warn=False)

    if component is None:
        return {
            "manufacturer": mfg,
            "description": desc,
            "value": part["value"],
            "references": part["references"],
            "status": "not_found",
            "error": (f"No matching LCSC result for '{search_term}'" if closest
                      else f"No LCSC results for '{search_term}'")
                     + (f" or '{mpn}'" if lcsc_pn and mpn else "")
                     + (f" (closest: '{closest}', a different part)" if closest else ""),
            "last_attempt": now,
        }

    return {
        "manufacturer": mfg,
        "description": desc,
        "value": part["value"],
        "references": part["references"],
        "status": "failed",
        "error": "No datasheet URL or all download methods failed",
        "last_attempt": now,
    }
brainstormingobra/superpowersYou MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation).Stars: 321kUpdated Claude CodeCodexVerifiedInstall
brand-guidelinesanthropics/skillsApplies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand colors or style guidelines, visual formatting, or company design standards apply.Stars: 197kUpdated Claude CodeCodexVerifiedInstall
frontend-designanthropics/skillsGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.Stars: 197kUpdated Claude CodeCodexVerifiedInstall
mcp-builderanthropics/skillsGuide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).Stars: 197kUpdated Claude CodeCodexVerifiedInstall