Skip to content

MCP Recipes

Pro

Optimize a Prompt in a Loop

Iteratively improve a prompt: A/B the current best against an agent-proposed variant, keep the winner, repeat, stopping at a quality target, a plateau, an iteration cap, or a cost cap. A closed optimization loop with the judge as the fitness function.

⚠

Agentic and programmatic use. Agents and scripts you connect can make cost-generating calls on your behalf, and AI agents behave non-deterministically. You are responsible for monitoring and bounding your own automation. See Terms for details.

Run it: paste into your MCP agent

Parts in double braces (like {{recipe_id}}) are placeholders. Replace them with your own values before (or after) copying.

Using the LLM Prover MCP tools, run a closed-loop optimization of a prompt. You are the optimizer; the scoring (gold standard or rubric) is the fitness function. This recipe COMPOSES scored evaluations with an agent-state note that holds the loop’s state so it can run across sessions. Keep status “running” until the loop ends.

Set up:

  1. Confirm the tools you need are available (list the tools): run_evaluation, poll_job, list_models, and the agent-state tools get_agent_notes, put_agent_note, update_agent_note. Any missing one is an EXTENDED tool – load it via list_tool_catalog -> request_tools and call through invoke(…); do not conclude it is unavailable.

  2. Read your notes: get_agent_notes(recipe_id="{{recipe_id}}"). If an active note exists, we are RESUMING a loop, so CAPTURE its note_id (every update this session targets that note_id) and read its data (iteration, cost_spent, best, history) AND its stop contract (the terminate and outcome blocks). BEFORE doing anything else, re-check the stop contract against the note’s current counters (same check as step 6): if a ceiling or the target was ALREADY crossed, do NOT resume the loop; go straight to STOP (step 6’s stop handling). This is the whole point of the structured contract: a loop someone forgot at iteration 25 must read its own limit and stop, not keep spending. Only if nothing is crossed do you continue from “LOOP”. If no active note, we are STARTING.

  3. Call list_models first (model IDs change as the registry updates, so never hardcode one from memory). Then ask me for: the starting prompt; the ONE model to optimize for; the scoring standard (expected_output gold answer, OR a saved rubric_id); and the STOP CONDITIONS, meaning a hard iteration CEILING and a hard COST CEILING (dollars), plus the SUCCESS target (a score to reach). Optionally a plateau threshold (minimum score improvement worth continuing). If I do not give budgets, propose sensible defaults and state them explicitly. NEVER run an unbounded loop.

  4. Record the loop state in a note BEFORE spending, including the STRUCTURED STOP CONTRACT so any session (including a forgetful future one) reads the loop’s own limits. put_agent_note CREATES the note and returns a note_id – CAPTURE it; every later change to this note uses update_agent_note(note_id, recipe_id, …), NEVER another put_agent_note (a second put creates a DUPLICATE note each iteration, exhausting your active-note cap and fragmenting the loop state). On resume, take the note_id from the active note get_agent_notes returned.

    put_agent_note(recipe_id="{{recipe_id}}", recipe="mcp-prompt-optimizer", status="running",
      intent="Optimize prompt for <model> toward <target>",
      data={ model, scoring:{expected_output|rubric_id}, plateau,
             iteration:0, cost_spent:0, best:{prompt:<starting prompt>, score:null, job_id:null},
             history:[],
             terminate:{ iterations:<the iteration ceiling>, cost_usd:<the cost ceiling> },
             outcome:{ target:{ metric:"quality_score", op:">=", value:<the target score> } } }).
    

    terminate = hard budget brakes (stop because you ran out); outcome = success (stop because you resolved). Both are OPTIONAL in the schema, but for THIS loop the terminate ceilings are mandatory, so never write a note without them.

Loop (each iteration):

  1. SCORE the current best (if not yet scored this iteration): run_evaluation(prompt=, models=, expected_output|rubric_id=). Async, so poll_job every 5 seconds to completion. Read EXACTLY results[].quality_score for the model (0-100).

  2. CHECK THE STOP CONTRACT against the note’s counters. Check OUTCOME FIRST, then TERMINATE; first condition to trip wins; do the comparison explicitly on the numbers.

    1. OUTCOME (success): if outcome.target is met (best.score value, e.g. best.score >= 90), STOP as SUCCESS. Go to REPORT, then at cleanup mark the note “completed” with data.stop_outcome = “target_reached”.
    2. TERMINATE (ceiling): if iteration >= terminate.iterations OR cost_spent >= terminate.cost_usd, STOP as CEILING. Go to REPORT, then at cleanup mark the note “completed” with data.stop_outcome = “halted_at_ceiling” and data.stop_detail naming which ceiling fired (e.g. “iterations: 25/25” or “cost: 3.01/3.00”).
    3. PLATEAU (optional, soft): if plateau is set and iteration > 0 and the score improved by less than plateau since last iteration, STOP; treat as a ceiling-style stop (stop_outcome “halted_at_ceiling”, stop_detail “plateau”).

    NEVER silently continue past a ceiling. Even with no human present, a ceiling hit goes TERMINAL (completed + stop_outcome), and does not become a zombie that keeps spending. If a ceiling is hit and I am present and want to go further, that is a NEW decision: you may raise terminate.iterations / terminate.cost_usd in the note only on my explicit approval, then continue.

  3. GENERATE one improved variant: propose a single, specific change to the best prompt, INFORMED by the judge’s reasoning on what the current best lost points for (read the breakdown/judge_reasoning). State the hypothesis (“adding an explicit format instruction should lift the structure score”). Change ONE thing, which keeps it a clean A/B.

  4. A/B: score the new variant the same way (run_evaluation, same model + scoring). Read its quality_score the same way (results[].quality_score).

  5. SELECT the winner: the higher quality_score of {current best, new variant}. If within the plateau threshold, treat as no improvement.

  6. UPDATE the note with update_agent_note(note_id=, recipe_id="{{recipe_id}}", status=“running”, data={…}) – NOT put_agent_note (that duplicates). This is the loop’s memory, so get it right: set iteration += 1; cost_spent += this iteration’s cost (sum the run costs); best = the winner {prompt, score, job_id}; append {iteration, variant, score, cost} to history. Then READ THE NOTE BACK (get_agent_notes) and confirm the written state matches what you intended; if it does not, correct it before continuing. Do NOT carry loop state only in your own working memory; the note is the source of truth.

  7. Go back to step 6 (re-check stop conditions, then iterate).

Report (when a stop condition fired):

  1. Tell me: the best prompt, its score, WHICH stop condition ended the loop and whether it was SUCCESS (target_reached) or a CEILING (halted_at_ceiling, and which ceiling), the full iteration history (score per iteration so I can see the trajectory), and total cost_spent.
  2. OVERFIT CHECK (important): a high judge score is not proof the prompt is genuinely better. An optimizer can learn to please the judge (verbose, judge-flattering output) rather than improve real quality. Show me the actual best response, not just the number, and recommend I eyeball it before adopting. Do NOT present the optimized prompt as definitively best on score alone.
  3. CLEANUP: update_agent_note(note_id=, recipe_id="{{recipe_id}}", status=“completed”, data={…stop_outcome…}) and stamp data.stop_outcome (and data.stop_detail for a ceiling) per step 6: “target_reached” for success, “halted_at_ceiling” for a budget stop. It then drops from the active list and frees a slot. Do NOT leave a note that hit a ceiling in “running”, because a terminal stop is terminal. (If I explicitly want to keep going, that is the raise-the-ceiling-on-approval path in step 6, not leaving it open.)

ON ANY FAILURE or clear mismatch (a run will not score, the note write did not read back correctly, you lost track of iteration state): STOP the loop and update_agent_note( note_id=, recipe_id="{{recipe_id}}", status=“failed”, data={ failure_stage, failure_reason, a one-line detail, the last good job_id}). Never keep spending in a loop whose state you cannot trust, and never report an optimized result you did not actually measure.

Goal

Improve a prompt by iterating, not guessing. The agent A/Bs the current best against a proposed improvement, keeps the winner, and repeats, converging toward a quality target within budgets you set. It is the agent acting as an optimizer with the scoring as its fitness function, and a durable note as its memory so the loop can run across sessions.

When to use

Reach for this when a prompt matters enough to tune properly and you want evidence-driven iteration rather than one-shot rewriting. Best when you have a clear scoring standard (a gold answer or a rubric) so “better” is a number, not an opinion.

How it works, and its limits (read this)

  • The loop lives in prose + a note. There is no special loop engine: the recipe steps are the control flow, the agent is the executor, and the agent-state note holds iteration, best, cost, and history so a fresh session resumes exactly where it left off. The note is the source of truth, so the agent writes it and reads it back each iteration to stay honest.
  • Hard stops are mandatory, and they live IN the note. The note carries a structured stop contract: a terminate block (hard ceilings on iteration count and cost) and an outcome block (the success target). Each iteration AND on resume, the agent checks outcome first, then terminate; the first to trip wins. Because the contract travels in the note, a loop a future session picks up reads its OWN limits, so a forgotten loop stops at its ceiling instead of spending on. A ceiling hit is terminal (note completed, stop_outcome: halted_at_ceiling); going further past a ceiling is a fresh, explicit decision, never automatic.
  • The judge is an imperfect fitness function. Optimizing to a score can produce prompts that please the judge without being genuinely better (Goodhart’s law). The recipe ends with a human checkpoint: look at the actual best output, not just the number, before adopting.
  • Cost is tracked and reported. Every iteration is scored runs that cost money; the loop reports cumulative spend against your cap and stops when it is hit.

Verification

  • The note carried a structured stop contract before any spend: a terminate block (iteration
    • cost ceilings) and an outcome block (target), checked outcome-first-then-terminate each iteration and on resume. A ceiling hit ended terminally with stop_outcome: halted_at_ceiling.
  • Each iteration updated the note and read it back; loop state did not live only in working memory.
  • The final report names the best prompt, its score, which stop condition fired, the per-iteration trajectory, and total cost.
  • A human checkpoint on the actual output (not just the score) was offered before adoption.
  • On a state or scoring failure, the loop stopped and the note was marked failed, so it did not keep spending.

Where this leads

Natural next recipes once you are comfortable with this one.