From 79dc41dbf4101f670cdec833699446a593cb93a5 Mon Sep 17 00:00:00 2001 From: Ramkumar Ethiraj <64294490+rmkr-dev@users.noreply.github.com> Date: Mon, 16 Nov 2026 05:06:28 +0000 Subject: [PATCH 1/2] Add LLM agent tool execution guardrails skill --- skillbook/skills.json | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/skillbook/skills.json b/skillbook/skills.json index fa317b7..7f38615 100644 --- a/skillbook/skills.json +++ b/skillbook/skills.json @@ -1180,6 +1180,26 @@ ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/llm-rollout.instructions.md` with applyTo for `**/gateway/**`, `**/llm/**`, `**/prompts/**`, `**/rollouts/**`, and `**/infra/**/*.bicep`. Optional on-demand procedure at `.github/skills/llm-model-prompt-rollout-guardrails/SKILL.md`. Claude Code: `.claude/skills/llm-model-prompt-rollout-guardrails/SKILL.md` plus a CLAUDE.md fact that routes point at immutable bundle IDs and prompts are never edited at runtime. Codex: a short \"LLM rollouts\" brief in root `AGENTS.md` (bundle config path, prompt folder, model inventory file, rollout plan folder, rollback command); the procedure can live in `.agents/skills/llm-model-prompt-rollout-guardrails/SKILL.md`. Pair with llm-eval-ci-regression-gate for the offline stage, llm-gateway-routing-fallback-guardrails for target order, llm-cost-latency-budget-guardrails for the shadow budget, llm-tracing-observability-guardrails for the bundle attribute, llm-gateway-caching-guardrails for bundle-aware cache keys, and rag-ingestion-index-lifecycle-guardrails for embedding model changes. This skill owns the release bundle, version pinning and retirement tracking, the prompt registry, shadow and canary stages, rollout criteria, and rollback.", "body": "# Skill: LLM Model and Prompt Rollout Guardrails\n\n## Goal\n\nA new model version, a provider switch, a prompt template edit, or a change to decoding parameters or tool schemas reaches production the way a risky code change does: as one pinned, versioned release, proven offline, watched on mirrored traffic, exposed to a small sticky cohort, and promoted or rolled back by criteria written down before the rollout started. Nothing changes model behavior in production without a diff, and the way back is a config flip that has already been exercised.\n\nTypical failures this skill prevents:\n\n1. **Unscheduled upgrades.** A deployment or router alias silently re-points to a newer model snapshot (provider auto-upgrade, `latest`-style alias), and output format, refusal rate, or tool-call behavior changes with no release on your side.\n2. **Retirement outages.** A pinned model version reaches its retirement date, the deployment starts returning errors, and nobody owned the date.\n3. **Version skew.** The model is rolled back but the prompt tuned for the new model stays, so production now runs a combination nobody ever tested.\n4. **Prompts edited in place.** A template changed in a database row or a portal, with no review, no version ID in telemetry, and no way to tell which answers came from which text.\n5. **Canaries that prove nothing.** Random per-request assignment that flips one user between styles mid-conversation, too little traffic to see the failing segment, and thresholds invented after the metric moved.\n6. **Shadow runs with side effects.** The candidate is mirrored real traffic and its tool calls send emails or write records.\n\nScoring a change against a golden set stays in **llm-eval-ci-regression-gate** and **rag-retrieval-eval-guardrails**. Target order and failover stay in **llm-gateway-routing-fallback-guardrails**. Token caps and price tables stay in **llm-cost-latency-budget-guardrails**. Span and metric names stay in **llm-tracing-observability-guardrails**. Re-embedding and index aliases stay in **rag-ingestion-index-lifecycle-guardrails**. This skill owns the release unit, model version pinning and retirement tracking, the prompt registry, shadow and canary stages, promotion and rollback criteria, and the tests for the switch.\n\n## When to apply\n\n- Upgrading a model version, moving to a new model family or variant, or switching provider for an existing route\n- Changing a system prompt, template, few-shot set, decoding parameters, or a tool or output schema used in production\n- A provider announces a retirement or a new default version for a deployment you use\n- Setting up Azure OpenAI (Foundry) deployments, or reviewing their upgrade policy\n- Reviewing a gateway where prompts live in code strings, a database, or a portal without versions\n\n## The release unit\n\nTreat these as one immutable bundle with an ID, e.g. `support-answer@2026-11-15.2`:\n\n- provider, deployment name, and exact model version or dated snapshot (never a floating alias)\n- prompt template IDs and content hashes (system, user, few-shot)\n- decoding parameters (temperature, max output tokens, reasoning effort, stop sequences)\n- tool definitions and output schema versions\n- retrieval settings the prompt depends on (index alias, top-k, re-ranker), by reference\n- guardrail and redaction policy versions\n\nRules:\n\n1. **One bundle per route, resolved at request time from config.** The gateway route points at a bundle ID; changing the bundle is a reviewed diff in Git (or a config store that records author and change), not a code redeploy and not a portal edit.\n2. **Bundles are immutable.** A fix is a new bundle ID. The previous bundle stays deployable until the new one has run at 100% for the agreed soak period.\n3. **Record the bundle ID everywhere.** Response header or metadata, trace attribute (`llm.gateway.bundle`), usage store row, eval run, and any cached entry key. Without it you cannot compare cohorts or invalidate caches.\n4. **Rollback restores the whole bundle**, never just the model or just the prompt.\n\n## Model version pinning and retirement\n\n1. **Pin dated versions.** On Azure OpenAI deployments set the model version explicitly and set `versionUpgradeOption` on purpose. `OnceNewDefaultVersionAvailable` moves you within about two weeks of a new default, which is an unscheduled release; `OnceCurrentVersionExpired` (also what an unset value means) upgrades only at retirement; `NoAutoUpgrade` keeps the version until retirement and then the deployment stops working. For production routes, prefer `NoAutoUpgrade` or `OnceCurrentVersionExpired` together with a tracked retirement date, and declare the choice in Bicep or the deployment script so it is reviewed. Provisioned (PTU) deployments are never auto-upgraded, so migration is always your job.\n2. **Other providers and routers:** request dated snapshot IDs rather than family aliases; record the `response.model` the provider returns and alert when it differs from the bundle's expected value. An unexpected model name is a rollout you did not schedule.\n3. **Model inventory as code.** A checked-in file listing each deployment, provider, model, version, upgrade policy, region, deployment type, retirement date, replacement candidate, owner, and the routes that use it.\n4. **Retirement is a dated task.** A scheduled CI job reads the inventory (and, where available, the provider's models or deprecation API) and fails or opens an issue when a retirement is within 90 days with no candidate bundle, and within 30 days with no completed canary. Subscribe owners to the provider's retirement notices (for Azure: Service Health alerts on Azure OpenAI Service).\n5. **Embedding models are not swapped in place.** A new embedding version means a re-index behind an alias (see rag-ingestion-index-lifecycle-guardrails), never a bundle edit.\n\n## Prompt registry\n\n- Prompts live as files in the repo (or a registry that is versioned and reviewed), one file per template with an ID, version, owner, intended model, variables, and output schema reference.\n- Load by ID and version; compute and log the content hash at startup. Fail startup if a referenced template or variable is missing.\n- No runtime edits in production. Emergency changes still go through a bundle and a fast-path review.\n- Templates are tested: render with fixture variables, check required sections and that untrusted input stays inside its delimiters (prompt-injection rules stay in llm-app-prompt-injection-guardrails).\n\n## Stages\n\nEvery change moves through stages, each with entry and exit criteria committed in a rollout plan file beside the bundle **before** the stage starts:\n\n1. **Offline eval.** The candidate bundle runs the golden set in CI against the current bundle (llm-eval-ci-regression-gate). Required for every change; a failed gate stops the rollout.\n2. **Shadow.** A sampled, stratified slice of live requests is sent to the candidate in the background. Users only see the current bundle's answer. Tool calls in the candidate are stubbed, dry-run, or sent to an isolated environment; never real side effects. Shadow output and comparisons follow the same redaction and retention rules as production content; store references and scores, not raw prompts, unless policy allows. Shadow runs on its own budget and quota so it can never throttle real traffic, and it is dropped first under load. Compare: schema validity, refusal and empty-answer rate, tool-call validity, output length, latency (TTFT and total), cost per request, and a paired judge score where calibrated. Use shadow for model and provider changes; small prompt-only edits may skip to canary if offline eval is strong.\n3. **Canary.** A small share of real traffic (start at 1 to 5 percent) on the candidate. Assignment is **sticky** by a stable hash of tenant or user (and conversation once started), so one conversation never switches bundles. Exclude or require approval for routes with irreversible actions. Ramp in steps (for example 5, 25, 50, 100), holding each step long enough to cover peak hours and the smallest segment you care about.\n4. **General availability.** The candidate becomes the route's bundle; the guard metrics stay as live alerts; the previous bundle stays deployable for the soak period, then its deployment can be removed.\n\n## Promotion and rollback criteria\n\n- Write them as data: metric, comparison against the control cohort (not last week), threshold, window, minimum sample size, and segments (tenant tier, language, route, tool).\n- Typical guard metrics: error and timeout rate, schema or parse failure rate, refusal and content-filter rate, tool-call error rate, p95 latency and TTFT, cost per successful request, fallback rate, user feedback or escalation rate, and eval sample scores on live traffic.\n- One guard breach halts the ramp and alerts the owner; a severe or repeated breach rolls back automatically to the previous bundle without waiting for a human.\n- Changing a threshold mid-rollout is a reviewed diff, never a dashboard edit.\n- A canary that has not reached the minimum sample in its window is \"hold\", not \"pass\".\n\n## Rollback\n\n- One command or config change sets the route back to the previous bundle ID; it takes effect without a redeploy and within a minute across replicas.\n- Exercise the rollback during the shadow or early canary stage, so it has been proven before anyone depends on it.\n- Caches keyed by bundle (or by model plus prompt version) do not serve the rolled-back bundle's answers to the restored bundle.\n- After rollback, keep the candidate's shadow and canary data for the postmortem.\n\n## Tests\n\n- Bundle resolution: a route resolves to exactly the pinned deployment, model version, prompt hash, parameters, and schema versions; an unknown bundle ID fails startup.\n- Sticky assignment: the same tenant or user hash lands in the same cohort across replicas and restarts; a conversation keeps its bundle when the percentage changes.\n- Shadow isolation: candidate tool calls never reach real executors; shadow failures and timeouts never affect the user response or its latency budget.\n- Drift alarm: a stubbed provider returning a different `model` value raises the mismatch metric.\n- Rollback: flipping the route config switches new requests to the previous bundle without restart.\n- Inventory check: the retirement job fails on a fixture deployment retiring in 20 days without a completed canary.\n\n## Review checklist\n\n- [ ] Each production route points at an immutable bundle ID covering model version, prompt hashes, parameters, tool and output schemas\n- [ ] No floating model aliases; Azure `versionUpgradeOption` set deliberately and declared in IaC\n- [ ] Model inventory with retirement dates, owners, and a scheduled check\n- [ ] Prompts versioned in the repo, loaded by ID, hash logged; no runtime edits\n- [ ] Bundle ID in headers, traces, usage rows, eval runs, and cache keys\n- [ ] Offline eval, shadow (no side effects, own budget), sticky canary, then GA\n- [ ] Promotion and rollback criteria committed before each stage; automatic rollback on severe breach\n- [ ] Rollback flips the whole bundle by config and has been exercised\n\n## Copy-paste brief for instruction files\n\n```\nLLM rollouts: every production route points at an immutable bundle (provider deployment + dated model version, prompt IDs and hashes, decoding params, tool and output schema versions). No floating model aliases; set Azure OpenAI versionUpgradeOption deliberately in IaC and keep a model inventory with retirement dates and a scheduled check. Prompts are versioned files loaded by ID; no runtime edits. Record the bundle ID in headers, traces, usage rows, eval runs, and cache keys. A change goes offline eval -> shadow (stubbed tools, own budget, no user impact) -> sticky canary (hash of tenant or user, ramp in steps) -> GA, with promotion and rollback criteria committed before each stage. Rollback flips the whole bundle by config, without redeploy, and is exercised before the canary.\n```\n" + }, + { + "id": "llm-agent-tool-execution-guardrails", + "title": "LLM Agent Tool Execution Guardrails", + "whenToUse": "Adding or reviewing tool or function calling in a Spring AI, LangChain4j, or MCP-based agent or assistant — one tool registry with risk classes and closed argument schemas, narrow tools instead of shell, SQL, or URL tools, per-user tool filtering, tools that run as the user with tenant and identity from context rather than model arguments, irreversible writes held as pending actions until an approval bound to the exact argument hash, idempotency keys on writes, MCP annotations treated as hints with pinned tool definitions, and caps on turns, tool calls, time, and tokens.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "llm", + "agents", + "security", + "authorization", + "spring-boot", + "mcp" + ], + "formatNotes": "All three. Copilot: path-scoped `.github/instructions/agent-tools.instructions.md` with applyTo for `**/agent/**`, `**/tools/**`, `**/llm/**`, and `**/mcp/**`. Optional on-demand procedure at `.github/skills/llm-agent-tool-execution-guardrails/SKILL.md`. Claude Code: `.claude/skills/llm-agent-tool-execution-guardrails/SKILL.md` plus a CLAUDE.md fact that every tool is declared in the tool registry and irreversible writes go through the approval service. Codex: a short \"Agent tools\" brief in root `AGENTS.md` (registry path, approval service path, tool test command); the procedure can live in `.agents/skills/llm-agent-tool-execution-guardrails/SKILL.md`. Pair with llm-app-prompt-injection-guardrails for untrusted text, coding-agent-mcp-server-guardrails for developer-machine MCP config, llm-structured-output-guardrails for argument validation, api-idempotency-key-guardrails for the downstream key store, entra-id-spring-service-auth-guardrails for on-behalf-of calls, and llm-tracing-observability-guardrails for execute_tool spans. This skill owns the tool catalog and risk classes, execution-time authorization, the approval protocol, side-effect safety, loop limits, and their tests.", + "body": "# Skill: LLM Agent Tool Execution Guardrails\n\n## Goal\n\nA Java/Spring Boot agent, assistant, or gateway that lets a model call tools can only do what the signed-in user could do, only through narrow tools the team chose, and never takes a write, send, payment, or delete action that a person did not approve for those exact arguments. A hallucinated call, a prompt-injected instruction inside a retrieved document, or a confused retry loop ends in a refused or pending call, not in a changed record.\n\nTypical failures this skill prevents:\n\n1. **Excessive functionality.** The agent gets a generic `runSql`, `httpGet(url)`, or `shell` tool when it needed `findOrderById`, so one injected sentence reaches anything the service account can reach.\n2. **Excessive permissions.** Tools run with the service's own credentials, so a user can read or change another tenant's data by asking for it.\n3. **Excessive autonomy.** Writes run as soon as the model asks, with no confirmation, no limit, and no record of who approved what.\n4. **Approval that approves the wrong thing.** The user clicks \"yes\" on a summary, the model then changes an argument, and the changed call runs under the old approval; or one approval is replayed for every later call.\n5. **Duplicate side effects.** The model or the framework retries a tool call after a timeout and the refund, email, or ticket happens twice.\n6. **Runaway loops.** The agent calls tools in a loop until the token budget, a rate limit, or the downstream system gives out.\n\nPrompt-injection handling of untrusted text stays in **llm-app-prompt-injection-guardrails**. Coding-agent and MCP client configuration on developer machines stays in **coding-agent-mcp-server-guardrails**. Validation of model output against a schema stays in **llm-structured-output-guardrails**. Idempotency-Key storage for HTTP APIs stays in **api-idempotency-key-guardrails**. Span names stay in **llm-tracing-observability-guardrails**. Token caps stay in **llm-cost-latency-budget-guardrails**. This skill owns the tool catalog and risk classes, identity and authorization at execution time, the approval protocol, side-effect safety, loop limits, and the tests for them.\n\n## When to apply\n\n- Adding tool or function calling to a Spring AI, LangChain4j, or hand-rolled agent, or exposing an internal API to a model\n- Building or reviewing an MCP server or client that a production assistant uses\n- A tool can write, send, pay, delete, change access, or reach the open internet\n- A review finds generic tools, service-account credentials in tools, or writes without confirmation\n- Moving an agent from internal demo to real users or real tenants\n\n## Tool catalog and risk classes\n\nEvery tool the model can see is declared in one reviewed place (a registry class or a checked-in file) with:\n\n- name, one-line purpose, owner\n- **risk class**: `read` (no state change, bounded data), `sensitive-read` (personal, financial, or cross-record data), `write-reversible` (create or update that can be undone), `write-irreversible` (send, pay, delete, grant access, deploy), `open-world` (fetches or sends outside your trust boundary)\n- argument schema (closed: `additionalProperties: false`, enums and patterns instead of free strings, size limits)\n- required user scopes or roles, and the tenant field it acts on\n- idempotency behavior and timeout\n- whether it needs approval, and the approval text template\n\nRules:\n\n1. **Narrow tools beat generic ones.** `createSupportTicket(customerId, category, summary)` instead of `callApi(method, url, body)`. No shell, SQL, arbitrary URL, or file path tools in a user-facing agent.\n2. **Offer the smallest tool set per route and per user.** Filter the catalog before the request by route, tenant, and the user's scopes; a tool the user cannot run is not sent to the model at all.\n3. **Annotations are hints, not controls.** MCP `readOnlyHint`, `destructiveHint`, `idempotentHint`, and `openWorldHint` help choose friction, but they come from the server; trust only your own registry's risk class for servers you do not control, and treat a missing annotation as destructive and open-world.\n4. **Pin reviewed tool definitions.** Hash each tool's full definition (description, input and output schema, annotations) and fail or alert when a remote MCP server's definitions change without review.\n\n## Identity and authorization at execution time\n\n- Tools run **as the user** (on-behalf-of token, or the user's identity passed to a downstream policy check), never with a broad service credential that bypasses the user's permissions.\n- Tenant, user ID, and scopes come from the authenticated request, passed out of band (in Spring AI, `ToolContext`; in LangChain4j, an invocation context or memory ID mapped server-side), never from model-generated arguments. A `tenantId` argument from the model is ignored or must match the context.\n- Authorize every call inside the tool or the downstream API, not only when choosing which tools to offer. Re-check object ownership for IDs the model supplies.\n- Results returned to the model are trimmed to what the user may see and what the task needs; secrets, tokens, and internal URLs never go into tool results.\n\n## Approval protocol for side effects\n\nFor `write-irreversible` tools, and `write-reversible` tools above an agreed limit:\n\n1. The model's tool call is **not executed**. The agent stores a **pending action**: action ID, tool name, canonical arguments, argument hash, user, tenant, conversation, created time, expiry (minutes, not hours).\n2. The user sees a confirmation rendered from the **canonical arguments by your code** (recipient, amount, record, change), not the model's paraphrase.\n3. Approval is a separate authenticated request carrying the action ID. The server checks the same user, not expired, not used, and that the stored argument hash still matches, then executes once and marks the action used. Any argument change creates a new pending action and a new approval.\n4. Decline, timeout, or expiry tells the model the action did not run, so it does not claim success.\n5. Store approvals as audit records: who approved, what exact arguments, when, the result.\n6. High-risk actions can need a second factor or a second person; that decision lives in policy, not in the prompt.\n\nImplementation hooks: in Spring AI 2.x, put an advisor inside the tool-calling loop (or drive the loop yourself with `ToolCallingManager` when you must pause for approval) so pending actions stop the loop and return a structured \"approval required\" response; in LangChain4j, wrap the tool executor. Either way the gate sits in code that the model cannot skip, never in the system prompt alone.\n\n## Side-effect safety\n\n- Each write tool call carries an **idempotency key** derived from the pending action ID or the tool call ID, forwarded to the downstream API so a retry cannot double-charge or double-send.\n- No automatic retry of a write after an ambiguous failure (timeout after send); reconcile by idempotency key or report \"unknown, check before retrying\".\n- Prefer reversible designs: drafts instead of sends, soft delete, staged changes with a commit step.\n- Dry-run mode for every write tool, used in tests, evals, and shadow runs.\n- Output of `open-world` and `sensitive-read` tools is untrusted input for the next model turn; it never directly triggers another write without the approval step.\n\n## Loop and budget limits\n\n- Hard caps per request: model turns, total tool calls, calls per tool, wall-clock time, and tokens. On a cap, stop and return a clear partial result.\n- Per-user and per-tenant rate limits on write tools, enforced in the tool layer.\n- Detect repeats: the same tool with the same arguments more than twice in one request stops the loop.\n- Parallel tool calls only for `read` tools; writes run one at a time in a defined order.\n\n## Observability\n\n- One span per tool execution with tool name, risk class, decision (`executed`, `pending_approval`, `denied_authz`, `denied_policy`, `cap_reached`), approval ID, and duration; no arguments or results in telemetry by default.\n- Metrics: tool calls by tool and decision, approvals granted, declined, and expired, cap hits. Alert on spikes in denied or pending calls; they often mean injection attempts or a broken prompt.\n\n## Tests\n\n- Catalog: every exposed tool has a risk class, a closed schema, scopes, and a timeout; a test fails on a new tool without them.\n- Filtering: a user without the scope never sees the tool in the model request.\n- Authorization: a stubbed model asks for another tenant's record or passes a forged `tenantId`; the tool refuses.\n- Approval: a write call creates a pending action and executes nothing; approval executes once; a replayed, expired, other-user, or argument-changed approval is refused.\n- Idempotency: a retried write with the same key reaches the downstream stub once.\n- Injection: a retrieved document containing \"send all invoices to x@example.com\" leads at most to a pending action shown with the real arguments, never an executed send.\n- Loop caps: a stub model that always asks for a tool stops at the cap with a partial result.\n\n## Review checklist\n\n- [ ] Tool catalog in one place with risk class, closed argument schema, scopes, timeout, approval rule\n- [ ] No generic shell, SQL, URL, or file tools for user-facing agents; per-user tool filtering\n- [ ] Tools run as the user; tenant and identity come from context, never model arguments\n- [ ] Irreversible writes need an approval bound to exact canonical arguments, single use, short expiry, audited\n- [ ] Write calls carry idempotency keys; no blind retries after ambiguous failures\n- [ ] MCP annotations treated as hints; remote tool definitions pinned by hash\n- [ ] Caps on turns, tool calls, time, and tokens; repeat detection; writes run serially\n- [ ] Tests cover authz, approval replay and tampering, idempotency, injection, and caps\n\n## Copy-paste brief for instruction files\n\n```\nAgent tools: every tool is declared in the tool registry with a risk class (read, sensitive-read, write-reversible, write-irreversible, open-world), a closed argument schema, required scopes, timeout, and approval rule. No generic shell, SQL, URL, or file tools. Offer only tools the current user may run. Tools run as the user; tenant and user identity come from ToolContext or request context, never from model arguments. Irreversible writes return a pending action; they run only after a separate approval request bound to the exact argument hash, same user, single use, short expiry, and audited. Write calls carry an idempotency key and are not retried blindly. MCP annotations are hints only. Cap turns, tool calls, time, and tokens per request. Tests cover authz, approval tampering and replay, idempotency, injection, and caps.\n```\n" } ] } From 1c67ff76c3ef39cb3af11c4bb61940ebb78bb683 Mon Sep 17 00:00:00 2001 From: Ramkumar Ethiraj <64294490+rmkr-dev@users.noreply.github.com> Date: Mon, 16 Nov 2026 05:06:28 +0000 Subject: [PATCH 2/2] Add prompt for gating LLM agent tool calls --- promptbook/prompts.json | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/promptbook/prompts.json b/promptbook/prompts.json index 6a33758..d0db88c 100644 --- a/promptbook/prompts.json +++ b/promptbook/prompts.json @@ -1182,6 +1182,26 @@ ], "formatNotes": "All three. Point the tool at the gateway route config, provider clients, prompt templates, Azure OpenAI Bicep or Terraform, the eval job, and the test folder. Copilot: llm-rollout path instructions plus those files in agent mode (or save the prompt as `.github/prompts/roll-out-llm-model-or-prompt-change.prompt.md`). Claude Code: the llm-model-prompt-rollout-guardrails skill plus those files. Codex: the AGENTS.md LLM rollouts section, then the diff. Leave golden-set scoring, routing order, budgets, tracing names, and re-indexing to their own skills.", "body": "Task: Put the LLM route or gateway I specify on versioned, staged releases so that a model version upgrade, provider switch, or prompt and parameter change ships as one pinned bundle through offline eval, shadow, and a sticky canary, with criteria committed up front and a tested one-step rollback. Finish with a minimal diff, config, and tests.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Service: {{APP_NAME}} at {{APP_PATH}}\n- Stack: {{STACK}} (Spring Boot version; Spring AI | LangChain4j | hand-rolled HTTP clients; config source: application.yaml | App Configuration | database)\n- Routes and providers: {{ROUTES}} (route names, Azure OpenAI deployments, Bedrock, OpenAI-compatible routers; where prompts live today)\n- Change to ship: {{CHANGE}} (new model version or family, provider switch, prompt edit, parameter or schema change, forced retirement)\n- Deployment config: {{IAC}} (Bicep or Terraform files declaring Azure OpenAI deployments; versionUpgradeOption today)\n- Eval gate: {{EVAL}} (existing golden-set job and command, judge setup)\n- Guard metrics source: {{METRICS}} (usage store, OpenTelemetry backend, feedback signal)\n- Risky routes: {{SIDE_EFFECTS}} (routes or tools with irreversible actions)\n\nRequirements:\n\n1. Inventory\n - Table: route | provider deployment | model and version requested | model returned | upgrade policy | retirement date | prompt location and versioning | parameters source | bundle ID today? | rollback path today\n - Flag floating aliases, unset or auto-upgrading versions on production routes, prompts edited at runtime, missing version IDs in telemetry, and any retirement within 90 days\n\n2. Release bundle\n - Define an immutable bundle per route: deployment, dated model version, prompt template IDs and hashes, decoding parameters, tool and output schema versions, retrieval settings by reference, guardrail policy versions\n - Route config points at a bundle ID; resolution happens at request time; unknown IDs fail startup\n - Bundle ID in response metadata, `llm.gateway.bundle` span attribute, usage rows, eval runs, and cache keys\n\n3. Model pinning and retirement\n - Set `versionUpgradeOption` explicitly in {{IAC}} for every Azure OpenAI deployment and explain the choice; note PTU deployments never auto-upgrade\n - Use dated snapshot IDs for other providers; emit a mismatch metric when the returned model differs from the bundle\n - Add a checked-in model inventory and a scheduled job that opens an issue or fails at 90 days to retirement without a candidate bundle and at 30 days without a completed canary\n\n4. Prompt registry\n - Move templates to versioned files (ID, version, owner, intended model, variables, schema reference); load by ID; log the content hash; no runtime edits\n - Render tests with fixture variables, checking required sections and that untrusted input stays delimited\n\n5. Stages and criteria\n - Rollout plan file per change: stages (offline eval, shadow, canary steps, GA), and per stage the metric, comparison to the control cohort, threshold, window, minimum sample, segments, and action (hold, halt, roll back)\n - Offline: wire the candidate bundle into {{EVAL}}\n - Shadow: sampled and stratified mirror, user sees only the current answer, candidate tools stubbed or isolated, separate budget and quota, dropped first under load, content handled under the same redaction and retention rules\n - Canary: sticky assignment by stable hash of tenant or user, conversation pinned to its bundle, {{SIDE_EFFECTS}} excluded or approval-gated, stepwise ramp\n - Automatic rollback on severe or repeated breach; insufficient sample means hold\n\n6. Rollback\n - One config change returns the route to the previous bundle without redeploy; propagate to all replicas within a minute\n - Run it once during shadow or early canary and record the result\n\n7. Tests\n - Bundle resolution and startup failure on unknown IDs; sticky cohorts stable across replicas and restarts and when the percentage changes; shadow never executes real tools and never affects user latency or errors; model mismatch metric fires on a stubbed different `model`; rollback switches new requests without restart; retirement job fails on a fixture deployment near retirement\n\n8. Verification\n - Updated inventory table, the bundle and rollout plan for {{CHANGE}}, a sample shadow comparison report (scores and IDs only, no content), and the rollback drill result\n\nConstraints:\n- Minimal diff. Reuse the existing gateway routing, config source, eval job, and telemetry; no new platform.\n- Never run candidate side effects in shadow. Never loosen eval thresholds or delete tests to pass a stage.\n- Leave golden-set scoring, routing and fallback order, budgets and prices, tracing names, and re-indexing to their existing skills; call their hooks.\n- Copilot, Claude Code, and Codex: concrete diffs, the inventory table, the rollout plan file, and a checklist. Do not paste this prompt into AGENTS.md.\n\nOutput format:\n1. Inventory table with the gaps found\n2. Bundle definition, route config, and IaC diff (upgrade policy included)\n3. Prompt registry layout and loader diff\n4. Rollout plan file, shadow and canary wiring, and rollback switch\n5. Tests added and what each asserts\n\nStart from {{APP_PATH}}. Pin versions and stop unscheduled upgrades first, then introduce bundles and the registry, then shadow, canary, and the rollback drill.\n" + }, + { + "id": "gate-llm-agent-tool-calls", + "title": "Gate LLM Agent Tool Calls with Authorization and Approvals", + "whenToUse": "Harden a tool-calling agent or assistant before real users — tool inventory, registry with risk classes and closed schemas, narrow tools in place of generic ones, per-user filtering, user identity from context, on-behalf-of downstream calls, pending actions with argument-bound single-use approvals, idempotency keys, loop caps, tool spans, and tests for authz, approval tampering, injection, and caps.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "llm", + "agents", + "security", + "authorization", + "spring-boot", + "mcp" + ], + "formatNotes": "All three. Point the tool at the agent loop, tool classes or MCP client config, auth config, downstream clients, and the test folder. Copilot: agent-tools path instructions plus those files in agent mode (or save the prompt as `.github/prompts/gate-llm-agent-tool-calls.prompt.md`). Claude Code: the llm-agent-tool-execution-guardrails skill plus those files. Codex: the AGENTS.md Agent tools section, then the diff. Leave injection text handling, output schemas, idempotency storage, tracing names, and budgets to their own skills.", + "body": "Task: Put the tool-calling agent or assistant I specify behind execution guardrails so that the model can only call narrow, authorized tools as the signed-in user, and no irreversible write runs without an approval bound to its exact arguments. Finish with a minimal diff, config, and tests.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Service: {{APP_NAME}} at {{APP_PATH}}\n- Stack: {{STACK}} (Spring Boot version; Spring AI 2.x ChatClient | LangChain4j AiServices | hand-rolled loop; MCP client or server?)\n- Tools today: {{TOOLS}} (where they are defined; local beans, MCP servers, HTTP APIs)\n- Identity: {{IDENTITY}} (Entra ID or other OIDC; how user, tenant, and scopes reach the service; on-behalf-of available?)\n- High-impact actions: {{ACTIONS}} (sends, payments, deletes, access changes, deployments, limits that need approval)\n- Approval surface: {{APPROVAL_UI}} (web UI, chat card, Teams or Slack button, API client)\n- Downstream idempotency: {{IDEMPOTENCY}} (which APIs accept an Idempotency-Key)\n- Limits: {{LIMITS}} (max turns, tool calls, time, tokens per request; rate limits per user)\n\nRequirements:\n\n1. Inventory\n - Table: tool | source (bean, MCP server, API) | what it does | state change? | reversible? | credential used | tenant and user source | argument schema (open or closed) | approval today | idempotent? | timeout\n - Flag generic tools (shell, SQL, arbitrary URL, file path), service-account credentials, identity taken from model arguments, writes without approval, open schemas, and missing timeouts\n\n2. Tool registry\n - One registry declaring each tool with risk class (read, sensitive-read, write-reversible, write-irreversible, open-world), closed argument schema (additionalProperties false, enums, patterns, size limits), required scopes, tenant field, timeout, idempotency behavior, and approval rule with a confirmation template\n - Replace generic tools with narrow ones for the cases actually used\n - Filter the tool list per route and per user scopes before each model request\n - For MCP servers: treat annotations as hints, map each remote tool to a registry risk class (missing means destructive and open-world), and pin full tool definitions by hash with an alert on change\n\n3. Identity and authorization\n - Pass user, tenant, and scopes out of band (Spring AI ToolContext or the framework equivalent); ignore or reject model-supplied identity fields\n - Call downstream APIs as the user (on-behalf-of) or with a policy check that uses the user's identity\n - Re-check ownership of every ID in arguments; trim results to what the user may see; no secrets in results\n\n4. Approval protocol\n - Write-irreversible calls (and {{ACTIONS}} over the agreed limits) create a pending action with ID, canonical arguments, argument hash, user, tenant, conversation, and short expiry, and execute nothing\n - Render the confirmation from canonical arguments in code via {{APPROVAL_UI}}\n - Separate authenticated approve and decline endpoints: same user, unexpired, unused, hash match; execute once; record the audit entry\n - Tell the model clearly when an action is pending, declined, or expired\n - Put the gate in code inside the tool loop (Spring AI advisor in the loop, or a user-driven loop with ToolCallingManager; LangChain4j tool executor wrapper), never only in the system prompt\n\n5. Side-effect safety\n - Idempotency key per write from the pending action ID or tool call ID, forwarded to {{IDEMPOTENCY}}\n - No automatic retry after ambiguous write failures; report unknown outcome\n - Dry-run mode for every write tool; drafts or staged changes where the domain allows\n - Output of open-world and sensitive-read tools is untrusted for the next turn and cannot trigger a write without approval\n\n6. Limits\n - Enforce {{LIMITS}}: turns, total tool calls, per-tool calls, wall-clock time, tokens; stop with a partial result on a cap\n - Repeat detection for the same tool and arguments; writes run serially; per-user and per-tenant rate limits on write tools\n\n7. Observability\n - Span per tool execution with tool name, risk class, decision (executed, pending_approval, denied_authz, denied_policy, cap_reached), approval ID, duration; no arguments or results by default\n - Metrics and alerts for denied and pending spikes, approvals by outcome, and cap hits\n\n8. Tests\n - Registry completeness; per-user filtering; cross-tenant and forged-identity calls refused; pending action executes nothing; approval executes once; replayed, expired, other-user, and argument-changed approvals refused; idempotent retry hits the downstream stub once; injected instruction in a retrieved document yields at most a pending action with real arguments; caps stop a looping stub model\n\n9. Verification\n - Updated inventory table, the registry diff, one sample pending action and its confirmation text, and the test run summary\n\nConstraints:\n- Minimal diff. Reuse the existing auth, HTTP clients, idempotency store, and telemetry; no new agent framework.\n- Never weaken approval to make a test pass; never use real recipients, payment details, or customer data in fixtures.\n- Leave prompt-injection text handling, output schema validation, idempotency storage design, tracing names, and token budgets to their existing skills; call their hooks.\n- Copilot, Claude Code, and Codex: concrete diffs, the inventory table, and a checklist. Do not paste this prompt into AGENTS.md.\n\nOutput format:\n1. Inventory table with the gaps found\n2. Tool registry and filtering diff\n3. Identity and authorization changes\n4. Approval protocol, endpoints, and loop gate diff\n5. Idempotency, limits, observability, and tests added\n\nStart from {{APP_PATH}}. Remove generic tools and model-supplied identity first, then gate irreversible writes behind approvals, then idempotency, limits, and tests.\n" } ] }