Generated banner for Primer Design
Generated logo for Primer Design

Primer Design

K-DenseCommunityCreated by K-Dense Inc.

  • Skill
  • Tool integration
  • Science and research
  • MIT
  • Low risk
  • Has scripts

From the author

Designs and audits PCR and RT-qPCR primers with Primer3, explicit thermodynamic conditions, reference-based off-target amplification searches, and traceable sequence coordinates. Use for designing primer pairs, checking existing primers, exon-junction or isoform-specific assays, variant masking, cloning tails, multiplex compatibility, and interpreting Primer-BLAST results. Includes bounded local in-silico PCR and BLAST screening; distinguishes computational candidates from experimentally validated assays.
— the description by K-Dense Inc.

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured, reproducible workflow for the design and specificity assessment of PCR and RT-qPCR primers. It integrates Primer3 for thermodynamic design and local BLAST or exhaustive search tools for off-target amplification screening. The workflow emphasizes rigorous input contracts, explicit thermodynamic assumptions, and the generation of traceable evidence reports, ensuring that all design decisions are documented and verifiable without relying on external web-based services.

What it does

  • Designs PCR and RT-qPCR primer pairs based on user-defined templates and thermodynamic constraints.
  • Audits existing primer pairs for thermodynamic stability and potential off-target amplification.
  • Performs exhaustive local in-silico PCR and BLAST-based specificity screening.
  • Supports advanced assay requirements including exon-junction targeting, multiplexing, and cloning tails.
  • Generates standardized JSON reports and assay documentation for experimental validation.
  • Enforces strict input validation to prevent silent failures or incorrect assumptions.

When to use it

  • When you need to design new primers for genomic PCR, RT-qPCR, or cloning applications.
  • When you must verify the specificity and thermodynamic properties of existing primer sequences.
  • When working in environments requiring local-only processing of sensitive or proprietary sequence data.
  • When you need to document the full rationale, assumptions, and evidence for a primer design project.

Advantages

  • Ensures reproducibility by requiring explicit configuration, reference versions, and chemistry settings.
  • Provides local, offline screening capabilities to maintain data privacy and control.
  • Includes robust checks for off-target products and multiplex interactions.
  • Facilitates systematic validation by separating computational candidates from experimental requirements.

Usage examples

“Design a new qPCR primer pair for the target sequence in demo-template.fasta using the qpcr preset.”
The agent executes the design script with the specified template and configuration, producing a JSON report of candidate pairs and their associated thermodynamic properties.
“Check the specificity of an existing primer pair against my local reference genome.”
The agent runs the specificity screening tool against the provided reference, identifying potential off-target binding sites and reporting product lengths and mismatch counts.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/k-dense-ai/primer-design/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip primer-design.zip -d .agents/skills

Documentation by K-Dense Inc.

Primer design and specificity

Produce candidate oligos in 5-prime-to-3-prime orientation, with the exact template, chemistry, intended products, and search scope behind each conclusion. Calculate sequence-dependent quantities with the supplied tools. A familiar gene name, good Primer3 penalty, or a single BLAST alignment cannot establish primer specificity.

Choose the workflow

RequestStart here
New genomic PCR or RT-qPCR pairDefine the assay and reference; design; assess thermodynamics; screen products.
Check an existing pairPrepare pair TSV; assess both full oligos and annealing cores; screen with explicit intended coordinates.
Exon junction, transcript isoform, allele discriminationRead design-workflows.md; supply sequence annotation before imposing constraints.
Cloning/adaptor-tailed primersDesign annealing cores, append declared 5-prime tails, reassess full oligos, reconstruct the final product.
Multiplex panelEnable --multiplex in both thermodynamics and specificity tools to assess oligo interactions and cross-pair products.
Degenerate, bisulfite, probe, or modified-base assayUse the specialized workflow in design-workflows.md; the bundled ordinary-DNA model is insufficient.

The local tooling supports paired primers with unambiguous ACGT cores. Advanced assay types have substantive design and validation guidance, but are not silently reduced to ordinary PCR. This skill designs assays; expression normalization, experimental diagnostic validation, and guide-RNA design are separate tasks.

Establish the assay contract

Obtain what changes the result; use explicit provisional assumptions for an exploratory design, and identify them in the report:

  • Purpose and template: genomic DNA, cDNA, plasmid, or another defined substrate; target organism, accession with version, assembly/transcript release, strand, desired isoforms, and product-size range. Name wanted and unwanted templates.

  • Sequence evidence: local FASTA plus source/retrieval date and its SHA-256 hash. A locus excerpt uses local coordinates; record its mapping to the full reference. Include relevant paralogs, pseudogenes, alternate contigs, transcript isoforms, vector backbone, and host sequence in the appropriate screen.

  • Reaction conditions: polymerase/buffer, monovalent salt, total divalent salt, total dNTP, and oligo concentrations. Primer3 uses mM for salts/dNTP and nM for DNA. Record the initial reaction concentration separately from Primer3's effective annealing-oligo concentration parameter. Engine defaults are assumptions.

  • Constraints: target interval, allowed/excluded binding regions, junctions, variant exclusions and their source, fixed primers, tails, or multiplex membership. Do not guess exon boundaries or silently substitute another assembly.

  • Definition of an acceptable result: relevant off-target references, amplicon lengths, mismatch search limits, controls, and experimental validation appropriate to the assay. There is no universal thermodynamic cutoff that validates all PCRs.

Use input-contract.md for file schemas and coordinate examples. Copy assay-report-template.md into the analysis directory to collect evidence. Reference retrieval may be manual or through an established sequence API; preserve accession/version and verify the returned sequence. The supplied scripts use local files and do not submit sequences online.

Install and verify

Set SKILL_DIR to this skill's actual installed directory. Work in a separate analysis directory so environments, reference databases, and results do not enter the skill.

uv venv --python 3.13 .venv-primer
uv pip install --python .venv-primer/bin/python -r "$SKILL_DIR/assets/requirements.txt"
.venv-primer/bin/python "$SKILL_DIR/scripts/design_primers.py" --help

Use the environment's Scripts/python.exe on Windows. The design/thermodynamic examples target primer3-py 2.3.1, tested with Python 3.13. For the optional BLAST engine, install NCBI BLAST+ from its official distribution and check:

blastn -version
makeblastdb -version

Local integration checks also exercise BLAST+ 2.17.0; other releases require checking their output and search behavior before claiming equivalent coverage.

Read sources.md when updating dependencies or API assumptions. The scripts record engine versions and effective settings in their JSON reports.

1. Design candidates

For an initial functional demonstration, use the bundled synthetic sequence. It is nonbiological example input, not an experimentally validated assay:

.venv-primer/bin/python "$SKILL_DIR/scripts/design_primers.py" \
  --template "$SKILL_DIR/assets/demo-template.fasta" \
  --preset qpcr --config "$SKILL_DIR/assets/qpcr-config.json" \
  --output design.json --pairs-out pairs.tsv --expected-out expected.tsv

For actual work, substitute the reviewed target FASTA and constraints. A multi-record FASTA requires --record with its exact ID. The pcr preset requests 100–1000 bp; qpcr requests 70–200 bp. Override these starting ranges in the configuration. The example overrides its range to 90–180 bp and includes a specific target interval. Multiple SEQUENCE_TARGET intervals are alternatives: Primer3 flanks at least one. To require coverage of every interval, supply one enclosing target and verify the returned product; separate assays require separate design runs.

The tool:

  • Passes validated sequence_args and global_args to Primer3. Unsupported or misspelled tags fail rather than silently changing the task.

  • Converts ambiguous template positions to N and forbids ambiguous primer bases. It does not interpret lowercase sequence as a repeat mask; use explicit exclusions.

  • Optionally imports --mask-bed exclusions in the supplied template's coordinates. Use BED intervals for variant/repeat masking only after validating the reference mapping; it does not infer allele frequencies or convert arbitrary VCFs.

  • Verifies returned forward and reverse sequences against the template and checks product lengths. Primer3's right-primer position is converted into a half-open binding interval; the reverse primer is already in ordering orientation.

  • Optionally appends --forward-tail and --reverse-tail to cores. The design score and core Tm do not include those tails; step 2 checks complete oligos.

Inspect engine_explanations when no candidates are found. Change a biologically justified constraint and rerun; do not silently relax all constraints or return an invented sequence. Preserve previous reports when comparing parameter choices.

expected.tsv describes intended products on the design template. If screening another reference, map these coordinates to its exact record IDs and orientation. A cDNA product cannot be relabeled as a genomic interval across introns.

2. Assess thermodynamics

Use the same chemistry as the design. The following explicit values match the bundled design defaults; replace them together when the actual conditions differ:

.venv-primer/bin/python "$SKILL_DIR/scripts/check_thermodynamics.py" \
  --pairs pairs.tsv --mv-conc 50 --dv-conc 1.5 --dntp-conc 0.6 \
  --dna-conc 50 --temp-c 37 --output thermodynamics.json

The report contains core Tm, core and full-oligo hairpins/homodimers, full-oligo heterodimers, self 3-prime end stability, and both directional inter-oligo 3-prime end-stability calculations. Delta-G and delta-H are reported in kcal/mol; delta-S in cal/(mol K). --temp-c controls the temperature for delta-G, not a recommended PCR annealing temperature.

If design used different Tm/salt models, also set --tm-method and --salt-corrections-method to match; see the mapping in the input contract.

For a panel, add --multiplex to examine all unordered oligo combinations, including forward/forward and reverse/reverse between different pairs. Distinguish a panel to be combined from alternative candidates that will be tested separately.

Read thermodynamics.md before interpreting these values. Full oligos longer than 60 bases are reported as unresolved; they are never silently truncated. Modified bases and degenerate mixtures require a suitable model. Thermodynamic predictions support ranking and experimental planning, not a blanket claim of primer quality. Nonfinite Tm or a Tm at/below absolute zero is rejected as a calculation/input failure; such a result must not be ranked as an ordinary low-Tm primer.

3. Screen amplification products

Read specificity.md before making a specificity claim. Search each primer on both strands and pair inward-facing binding sites. A binding hit alone is not an amplicon; absence of a reported hit is not proof of absence.

.venv-primer/bin/python "$SKILL_DIR/scripts/screen_specificity.py" \
  --pairs pairs.tsv --reference "$SKILL_DIR/assets/demo-template.fasta" \
  --expected expected.tsv --engine exhaustive \
  --min-product 40 --max-product 1000 --max-mismatches 2 \
  --three-prime-bases 5 --max-three-prime-mismatches 0 \
  --output specificity.json

This enumerates full-length, ungapped binding sites in a bounded local reference and checks F/R, R/F, F/F, and R/R products for each pair. Reference ambiguity is treated conservatively as unresolved sequence; it cannot establish a clean result. The mismatch limits are a search model, not a validated polymerase discrimination rule. Tight 3-prime thresholds can exclude amplifiable mismatched sites; broaden the search when evaluating that uncertainty.

Use --circular RECORD_ID for a circular molecule. Wrapped products use canonical start coordinates and unwrapped ends greater than the reference length; only products spanning at most one molecule are considered. Caps on comparisons, hits, and products prevent unbounded work; hitting a cap makes the result incomplete.

.venv-primer/bin/python "$SKILL_DIR/scripts/screen_specificity.py" \
  --pairs pairs.tsv --reference "$SKILL_DIR/assets/demo-template.fasta" \
  --expected expected.tsv --engine blast \
  --min-product 40 --max-product 1000 --max-mismatches 2 \
  --three-prime-bases 5 --max-three-prime-mismatches 0 \
  --output specificity-blast.json

The script builds a temporary local BLAST database, runs short-query alignment, rechecks complete primer-length candidate sites, and records commands and versions. It checks configured hit limits and tool failures. BLAST discovery is heuristic: successful execution and unsaturated limits do not establish exhaustive coverage. The reference is loaded in memory; plan memory and search bounds for large genomes. The small example verifies execution, not human-genome sensitivity or scalability.

For broader public-reference screening, follow the official NCBI Primer-BLAST workflow in specificity.md, choosing the organism, database, intended templates, maximum product length, and mismatch policy deliberately. Submitting a sequence sends it to NCBI; keep local-only work local. Primer-BLAST is not a documented REST API implemented by these scripts.

Interpret the result
  • potential_off_target: inspect every unexpected product, including its orientation, length, mismatch positions, and reference identity; redesign or justify its relevance.

  • intended_target_not_found: resolve mapping, reference, sequence, and search problems before drawing specificity conclusions.

  • no_expected_target: results are a product inventory, without a target-specific conclusion. Supply all intended product intervals for the assay.

  • incomplete: reference uncertainty, resource limits, or failed computation leaves the conclusion unresolved. Inspect the reported reason and repeat appropriately.

  • no_off_target_found_within_search_scope: state the exact reference and search model. Check the report's exhaustive/heuristic flags; this is not empirical validation.

For a multiplex reaction, add --multiplex to the specificity command as well as the thermodynamics command. The specificity tool then searches every cross-pair oligo combination, retaining the original oligo identities and tails. It treats cross-pair products as unintended; intentionally shared-primer designs require explicit standalone combinations with reviewed expected products. The --max-panel-combinations cap defaults to 10,000 and is checked before expansion. Thermodynamic --multiplex checks structures; specificity --multiplex checks reference products. Both are necessary for this panel assessment.

4. Validate the assay and deliver evidence

Select candidates using assay purpose, coverage, specificity evidence, and chemistry, not just the lowest Primer3 penalty. Preserve multiple candidates when uncertainty remains. Follow design-workflows.md for the relevant experimental checks: expected product identity/size, negative and no-template controls, genomic contamination controls for RT-qPCR, and efficiency/dynamic-range assessment when quantification is intended. A single melt peak alone does not prove identity.

Deliver the completed report template, pair TSV, design/thermodynamic/specificity JSON, and source manifest. Include:

  1. Exact ordering sequences, separated annealing cores and tails, primer lengths, intended product coordinates/size, and any relevant transcript/junction mapping.

  2. Chemistry and model settings; engine versions; reference accession/release, source, retrieval date, and file hashes; explicit exclusions and rationale.

  3. Intended and potential unintended products; uncertainty from unknown bases, incomplete references, heuristic searches, caps, and unsupported assay chemistry.

  4. Experimental evidence actually obtained, outstanding validation, and the reason for each recommended candidate. Label untested candidates accurately.

Validation and limits of this implementation

The repository suite at tests/primer-design/ exercises actual Primer3 calculations, orientation and coordinate reconstruction, masking, tails, concentration handling, off-target product geometry, mismatch/ambiguity behavior, failure states, and local BLAST integration when its executables are installed. Synthetic fixtures establish software behavior; they do not validate a biological assay or prove genome-wide recall.

Tools return 0 when their computation completes, 1 for a completed design with no candidates or incomplete long-oligo thermodynamics, and 2 for invalid input or tool failure. Read the JSON scientific status even after exit 0: finding an off-target is a successfully completed calculation. See the input contract for screen-specific exits.

Citing Scientific Agent Skills

If used in published work, cite the upstream methods in sources.md and Scientific Agent Skills. Report the software versions and assay-specific settings required to reproduce the actual analysis.

Files

scripts/design_primers.py

#!/usr/bin/env python3
"""Design paired PCR primers with Primer3 and export auditable coordinates."""
from __future__ import annotations

import argparse
import csv
import json
import sys
from pathlib import Path

sys.dont_write_bytecode = True
from _common import (PAIR_FIELDS, check_output_paths, dna, finite_number, integer,
                     load_primer3, read_fasta, revcomp, sha256_file, write_json)

# A deliberately explicit supported interface prevents misspelled tags being
# silently ignored by Primer3. More advanced Primer3 tasks use its native API.
GLOBAL_KEYS = set("""
PRIMER_NUM_RETURN PRIMER_MIN_SIZE PRIMER_OPT_SIZE PRIMER_MAX_SIZE
PRIMER_MIN_TM PRIMER_OPT_TM PRIMER_MAX_TM PRIMER_PAIR_MAX_DIFF_TM
PRIMER_MIN_GC PRIMER_OPT_GC_PERCENT PRIMER_MAX_GC PRIMER_MAX_POLY_X
PRIMER_GC_CLAMP PRIMER_MAX_END_GC PRIMER_MAX_END_STABILITY
PRIMER_MAX_SELF_ANY_TH PRIMER_MAX_SELF_END_TH PRIMER_MAX_HAIRPIN_TH
PRIMER_PAIR_MAX_COMPL_ANY_TH PRIMER_PAIR_MAX_COMPL_END_TH
PRIMER_SALT_MONOVALENT PRIMER_SALT_DIVALENT PRIMER_DNTP_CONC
PRIMER_DNA_CONC PRIMER_TM_FORMULA PRIMER_SALT_CORRECTIONS
PRIMER_PRODUCT_SIZE_RANGE PRIMER_MIN_5_PRIME_OVERLAP_OF_JUNCTION
PRIMER_MIN_3_PRIME_OVERLAP_OF_JUNCTION PRIMER_MAX_NS_ACCEPTED
PRIMER_WT_TM_GT PRIMER_WT_TM_LT PRIMER_WT_SIZE_GT PRIMER_WT_SIZE_LT
PRIMER_PAIR_WT_DIFF_TM PRIMER_PAIR_WT_PR_PENALTY
PRIMER_MIN_QUALITY PRIMER_MIN_END_QUALITY PRIMER_QUALITY_RANGE_MIN
PRIMER_QUALITY_RANGE_MAX PRIMER_WT_SEQ_QUAL PRIMER_WT_END_QUAL
""".split())
SEQUENCE_KEYS = set("""
SEQUENCE_TARGET SEQUENCE_INCLUDED_REGION SEQUENCE_EXCLUDED_REGION
SEQUENCE_PRIMER_PAIR_OK_REGION_LIST SEQUENCE_OVERLAP_JUNCTION_LIST
SEQUENCE_PRIMER SEQUENCE_PRIMER_REVCOMP SEQUENCE_QUALITY
""".split())


def region(value, length, name):
    if not isinstance(value, list) or len(value) != 2:
        raise ValueError(f"{name} requires [start, length]")
    start, size = value
    integer(start, name + ' start')
    integer(size, name + ' length', 1)
    if start + size > length:
        raise ValueError(f"{name} lies outside the selected FASTA record")


def validate_config(config, length):
    if not isinstance(config, dict) or set(config) - {"sequence_args", "global_args"}:
        raise ValueError("Config accepts only sequence_args and global_args mappings")
    sequence, global_args = config.get("sequence_args", {}), config.get("global_args", {})
    if not isinstance(sequence, dict) or not isinstance(global_args, dict):
        raise ValueError("sequence_args and global_args must be JSON objects")
    for values, allowed, label in [(sequence, SEQUENCE_KEYS, "sequence_args"), (global_args, GLOBAL_KEYS, "global_args")]:
        if set(values) - allowed:
            raise ValueError(f"Unsupported {label}: {sorted(set(values) - allowed)}; see input-contract.md")
    for key in ("SEQUENCE_TARGET", "SEQUENCE_EXCLUDED_REGION"):
        if key in sequence:
            if not isinstance(sequence[key], list):
                raise ValueError(f"{key} must be a list of [start, length] intervals")
            for value in sequence[key]:
                region(value, length, key)
    if "SEQUENCE_INCLUDED_REGION" in sequence:
        region(sequence["SEQUENCE_INCLUDED_REGION"], length, "SEQUENCE_INCLUDED_REGION")
    for key in ("SEQUENCE_PRIMER", "SEQUENCE_PRIMER_REVCOMP"):
        if key in sequence:
            sequence[key] = dna(sequence[key], key)
            if not 15 <= len(sequence[key]) <= 36:
                raise ValueError(f"{key}: supported annealing core length is 15..36")
    if "SEQUENCE_OVERLAP_JUNCTION_LIST" in sequence:
        junctions = sequence["SEQUENCE_OVERLAP_JUNCTION_LIST"]
        if not isinstance(junctions, list):
            raise ValueError("SEQUENCE_OVERLAP_JUNCTION_LIST must be a list")
        for value in junctions:
            integer(value, "junction")
            if value >= length - 1:
                raise ValueError("Junction must name the base immediately left of an internal template boundary")
    if "SEQUENCE_QUALITY" in sequence:
        quality = sequence["SEQUENCE_QUALITY"]
        if not isinstance(quality, list) or len(quality) != length:
            raise ValueError("SEQUENCE_QUALITY needs one integer per template base")
        for value in quality:
            integer(value, "quality")
    if "SEQUENCE_PRIMER_PAIR_OK_REGION_LIST" in sequence:
        rows = sequence["SEQUENCE_PRIMER_PAIR_OK_REGION_LIST"]
        if not isinstance(rows, list):
            raise ValueError("SEQUENCE_PRIMER_PAIR_OK_REGION_LIST must be a list")
        for row in rows:
            if not isinstance(row, list) or len(row) != 4:
                raise ValueError("OK region requires [left_start,left_length,right_start,right_length]")
            for value in (row[:2], row[2:]):
                if value != [-1, -1]:
                    region(value, length, "OK region")
    for key, value in global_args.items():
        if key == "PRIMER_PRODUCT_SIZE_RANGE":
            if not isinstance(value, list) or not value:
                raise ValueError("Product ranges must be a nonempty list of [minimum,maximum]")
            for limits in value:
                if not isinstance(limits, list) or len(limits) != 2:
                    raise ValueError("Product range requires [minimum,maximum]")
                integer(limits[0], "minimum product", 1)
                integer(limits[1], "maximum product", limits[0])
        else:
            finite_number(value, key)
    if global_args.get("PRIMER_MAX_NS_ACCEPTED", 0) != 0:
        raise ValueError("This workflow requires unambiguous primers; PRIMER_MAX_NS_ACCEPTED must be 0")
    return sequence, global_args


def bed_exclusions(path, records, record_id):
    exclusions = []
    with Path(path).open(encoding="utf-8") as handle:
        for number, raw in enumerate(handle, 1):
            if not raw.strip() or raw.startswith(("#", "track ", "browser ")):
                continue
            parts = raw.rstrip().split("\t")
            if len(parts) < 3 or parts[0] not in records:
                raise ValueError(f"BED line {number}: unknown record or fewer than 3 tab-separated columns")
            start, end = int(parts[1]), int(parts[2])
            region([start, end - start], len(records[parts[0]]), "BED interval")
            if parts[0] == record_id:
                exclusions.append([start, end - start])
    return exclusions


def design(args):
    records = read_fasta(args.template)
    record_id = args.record or (next(iter(records)) if len(records) == 1 else None)
    if record_id not in records:
        raise ValueError("Choose --record from the FASTA IDs when the template has multiple records")
    original = records[record_id]
    # Primer3's sequence alphabet is narrower than IUPAC. Unknown positions are
    # made explicitly unavailable, never guessed into a concrete nucleotide.
    template = "".join(base if base in "ACGT" else "N" for base in original)
    config = json.loads(Path(args.config).read_text()) if args.config else {}
    sequence_args, overrides = validate_config(config, len(template))
    global_args = {
        "PRIMER_TASK": "generic", "PRIMER_PICK_LEFT_PRIMER": 1,
        "PRIMER_PICK_RIGHT_PRIMER": 1, "PRIMER_PICK_INTERNAL_OLIGO": 0,
        "PRIMER_FIRST_BASE_INDEX": 0, "PRIMER_EXPLAIN_FLAG": 1,
        "PRIMER_THERMODYNAMIC_OLIGO_ALIGNMENT": 1,
        "PRIMER_NUM_RETURN": 5, "PRIMER_MIN_SIZE": 18, "PRIMER_OPT_SIZE": 20,
        "PRIMER_MAX_SIZE": 25, "PRIMER_MIN_TM": 57.0, "PRIMER_OPT_TM": 60.0,
        "PRIMER_MAX_TM": 63.0, "PRIMER_PAIR_MAX_DIFF_TM": 3.0,
        "PRIMER_MIN_GC": 20.0, "PRIMER_MAX_GC": 80.0,
        "PRIMER_MAX_POLY_X": 4, "PRIMER_MAX_NS_ACCEPTED": 0,
        "PRIMER_SALT_MONOVALENT": 50.0, "PRIMER_SALT_DIVALENT": 1.5,
        "PRIMER_DNTP_CONC": 0.6, "PRIMER_DNA_CONC": 50.0,
        "PRIMER_TM_FORMULA": 1, "PRIMER_SALT_CORRECTIONS": 1,
        "PRIMER_PRODUCT_SIZE_RANGE": [[70, 200]] if args.preset == "qpcr" else [[100, 1000]],
    }
    global_args.update(overrides)
    for key in ("PRIMER_NUM_RETURN", "PRIMER_MIN_SIZE", "PRIMER_OPT_SIZE", "PRIMER_MAX_SIZE", "PRIMER_MAX_POLY_X", "PRIMER_GC_CLAMP", "PRIMER_MAX_END_GC", "PRIMER_TM_FORMULA", "PRIMER_SALT_CORRECTIONS", "PRIMER_MIN_5_PRIME_OVERLAP_OF_JUNCTION", "PRIMER_MIN_3_PRIME_OVERLAP_OF_JUNCTION", "PRIMER_MAX_NS_ACCEPTED", "PRIMER_MIN_QUALITY", "PRIMER_MIN_END_QUALITY", "PRIMER_QUALITY_RANGE_MIN", "PRIMER_QUALITY_RANGE_MAX"):
        if key in global_args:
            integer(global_args[key], key)
    if global_args["PRIMER_TM_FORMULA"] not in (0, 1):
        raise ValueError("PRIMER_TM_FORMULA must be 0 (Breslauer) or 1 (SantaLucia)")
    if global_args["PRIMER_SALT_CORRECTIONS"] not in (0, 1, 2):
        raise ValueError("PRIMER_SALT_CORRECTIONS must be 0 (Schildkraut), 1 (SantaLucia), or 2 (Owczarzy)")
    if not 1 <= global_args["PRIMER_NUM_RETURN"] <= 100:
        raise ValueError("PRIMER_NUM_RETURN must be 1..100")
    if not 15 <= global_args["PRIMER_MIN_SIZE"] <= global_args["PRIMER_OPT_SIZE"] <= global_args["PRIMER_MAX_SIZE"] <= 36:
        raise ValueError("Require 15 <= MIN_SIZE <= OPT_SIZE <= MAX_SIZE <= 36")
    if not global_args["PRIMER_MIN_TM"] <= global_args["PRIMER_OPT_TM"] <= global_args["PRIMER_MAX_TM"]:
        raise ValueError("Require MIN_TM <= OPT_TM <= MAX_TM")
    if not 0 <= global_args["PRIMER_MIN_GC"] <= global_args["PRIMER_MAX_GC"] <= 100:
        raise ValueError("Require 0 <= MIN_GC <= MAX_GC <= 100")
    finite_number(global_args["PRIMER_DNA_CONC"], "PRIMER_DNA_CONC", positive=True)
    if args.mask_bed:
        sequence_args.setdefault("SEQUENCE_EXCLUDED_REGION", []).extend(bed_exclusions(args.mask_bed, records, record_id))
    sequence_args.update(SEQUENCE_ID=record_id, SEQUENCE_TEMPLATE=template)
    tails = {name: dna(getattr(args, name), name, empty=True) for name in ("forward_tail", "reverse_tail")}
    p3 = load_primer3()
    result = p3.bindings.design_primers(sequence_args, global_args)
    if result.get("PRIMER_ERROR"):
        raise ValueError(result["PRIMER_ERROR"])
    pairs = []
    for i in range(result.get("PRIMER_PAIR_NUM_RETURNED", 0)):
        left, left_length = result[f"PRIMER_LEFT_{i}"]
        right, right_length = result[f"PRIMER_RIGHT_{i}"]
        forward, reverse = result[f"PRIMER_LEFT_{i}_SEQUENCE"], result[f"PRIMER_RIGHT_{i}_SEQUENCE"]
        if template[left:left + left_length] != forward or revcomp(template[right - right_length + 1:right + 1]) != reverse:
            raise ValueError("Primer3 output failed template/orientation verification")
        product = template[left:right + 1]
        if len(product) != result[f"PRIMER_PAIR_{i}_PRODUCT_SIZE"]:
            raise ValueError("Primer3 output failed product-length verification")
        pairs.append({
            "pair_id": f"pair_{i + 1}", "forward": forward, "reverse": reverse, **tails,
            "forward_order_sequence": tails["forward_tail"] + forward,
            "reverse_order_sequence": tails["reverse_tail"] + reverse,
            "record_id": record_id, "forward_interval": [left, left + left_length],
            "reverse_interval": [right - right_length + 1, right + 1],
            "product_interval": [left, right + 1], "product_size": len(product),
            "tailed_product_size": len(product) + sum(map(len, tails.values())),
            "product_sequence": product,
            "tailed_product_sequence": tails["forward_tail"] + product + revcomp(tails["reverse_tail"]),
            "forward_tm_c": result[f"PRIMER_LEFT_{i}_TM"],
            "reverse_tm_c": result[f"PRIMER_RIGHT_{i}_TM"],
            "penalty": result[f"PRIMER_PAIR_{i}_PENALTY"],
            "specificity_status": "not_screened",
        })
    report = {
        "schema_version": "1.0", "status": "candidates_generated" if pairs else "no_candidates",
        "coordinate_system": "0-based half-open on supplied FASTA record; reverse oligos are 5-prime to 3-prime",
        "provenance": {"template_file": str(args.template), "template_sha256": sha256_file(args.template),
                       "record_id": record_id, "template_length": len(template),
                       "primer3_py_version": p3.__version__,
                       "libprimer3_version": p3.thermoanalysis.get_libprimer3_version(),
                       "python_version": sys.version.split()[0],
                       "config_sha256": sha256_file(args.config) if args.config else None,
                       "mask_bed_sha256": sha256_file(args.mask_bed) if args.mask_bed else None},
        "settings": {"preset": args.preset, "sequence_args": sequence_args, "global_args": global_args, "tails": tails},
        "ambiguous_template_bases_masked": sum(c not in "ACGT" for c in original),
        "pairs": pairs,
        "engine_explanations": {key: value for key, value in result.items() if key.endswith("EXPLAIN") or key in ("PRIMER_WARNING", "PRIMER_ERROR")},
        "limitations": ["Primer3 penalty is a design ranking, not experimental validation or genomic specificity.",
                        "Coordinates refer to the supplied template, not a genome unless the FASTA itself is that reference.",
                        "Defaults are starting conditions; record the actual polymerase/buffer and validate experimentally.",
                        "Tails were appended after design; assess full oligos separately for secondary structures."],
    }
    write_json(args.output, report)
    for path in (args.pairs_out, args.expected_out):
        if path:
            Path(path).parent.mkdir(parents=True, exist_ok=True)
    if args.pairs_out:
        with Path(args.pairs_out).open("w", newline="", encoding="utf-8") as handle:
            writer = csv.DictWriter(handle, fieldnames=PAIR_FIELDS, delimiter="\t", extrasaction="ignore")
            writer.writeheader()
            writer.writerows(pairs)
    if args.expected_out:
        with Path(args.expected_out).open("w", newline="", encoding="utf-8") as handle:
            writer = csv.writer(handle, delimiter="\t")
            writer.writerow(["pair_id", "record_id", "start", "end"])
            writer.writerows([p["pair_id"], record_id, *p["product_interval"]] for p in pairs)
    return 0 if pairs else 1


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--template", required=True, type=Path, help="Local FASTA; no remote retrieval")
    parser.add_argument("--record", help="Exact FASTA ID; required for multi-record input")
    parser.add_argument("--preset", choices=("pcr", "qpcr"), default="pcr")
    parser.add_argument("--config", type=Path, help="JSON sequence_args/global_args overrides")
    parser.add_argument("--mask-bed", type=Path, help="Exclude primer binding in BED intervals in template coordinates")
    parser.add_argument("--forward-tail", default="", help="5-prime tail appended to forward core")
    parser.add_argument("--reverse-tail", default="", help="5-prime tail appended to reverse core")
    parser.add_argument("--output", required=True, type=Path, help="JSON design report")
    parser.add_argument("--pairs-out", type=Path, help="TSV for downstream thermodynamics/screening")
    parser.add_argument("--expected-out", type=Path, help="TSV intended product coordinates on this template")
    args = parser.parse_args(argv)
    try:
        check_output_paths([args.template, args.config, args.mask_bed], [args.output, args.pairs_out, args.expected_out])
        return design(args)
    except (ValueError, OSError, RuntimeError, TypeError, OverflowError) as exc:
        print(f"error: {exc}", file=sys.stderr)
        return 2


if __name__ == "__main__":
    raise SystemExit(main())

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs Python

The author says: Requires Python 3.11+ and primer3-py 2.3.1 for design and thermodynamics. Local exhaustive screening uses the standard library; BLAST screening additionally needs blastn and makeblastdb on PATH. Network access is needed only for installation, reference retrieval, or external Primer-BLAST.

Security

What our scanner noticed· Low risk

  • Instructions that use the network
  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
K-Dense Inc.
Publisher
K-Dense (Community)
Source
K-Dense-AI/scientific-agent-skills · skills/primer-design · commit a25cf9e
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE.md)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by K-Dense Inc. or K-Dense.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download primer-design.zip