context-injection
Place trusted contextual information into prompts or agent state using explicit boundaries, provenance, and templates. Use when relevant context has already been selected and must be inserted safely; use context-retrieval to find it or context-optimization to choose and order it.
git clone --depth 1 https://github.com/seb1n/awesome-ai-agent-skills /tmp/context-injection && cp -r /tmp/context-injection/context-engineering/context-injection ~/.claude/skills/context-injectionSKILL.md
# Context Injection
Context injection is the practice of dynamically inserting relevant information — documents, data, examples, or tool outputs — into an AI prompt so the model has the knowledge it needs to produce accurate, grounded responses. Effective injection is about more than pasting text; it requires deliberate placement, formatting, and token budget allocation to maximize the model's ability to use the injected material.
## Workflow
1. **Identify the Context Need**: Analyze the task to determine what types of external information the model requires. A code review needs the source file; a support question needs product documentation; a personalized reply needs the user's profile. Clearly categorize each need as document grounding, few-shot examples, tool output, or metadata.
2. **Gather the Context**: Retrieve the necessary information from its source — a database, file system, API response, vector store, or prior conversation. Apply any necessary compression or truncation before injection so the material fits within the allocated token budget.
3. **Select an Injection Strategy**: Choose the appropriate injection method based on the context type and the model's attention patterns:
- *System prompt injection* — persistent context like role definitions, rules, and user preferences go in the system message.
- *Document grounding* — retrieved documents or files are inserted in the user message, typically before the question.
- *Few-shot examples* — input/output pairs demonstrating the desired format are placed between the system prompt and the user query.
- *Tool output injection* — results from function calls or API invocations are injected as assistant/tool messages in the conversation.
4. **Format and Delimit the Context**: Wrap injected content in clear delimiters (XML tags, markdown headers, or triple-backtick fences) so the model can distinguish instructions from context from the user's query. Label each section explicitly (e.g., `<retrieved_document>`, `<user_profile>`, `<code_file>`).
5. **Assemble the Prompt**: Combine the system prompt, injected context blocks, conversation history, and the current user query into the final prompt. Place the most critical context closest to the user's query (recency bias) and the most stable context (rules, persona) in the system message.
6. **Validate Token Allocation**: Confirm the total prompt fits within the model's context window with enough headroom for the expected generation length. If over budget, compress or remove the lowest-priority context blocks first.
## Key Concepts
- **Context Placement**: Where context appears in the prompt matters. Models exhibit a "lost in the middle" effect — they attend most strongly to the beginning and end of the context window. Place the highest-priority information at the start of the context block or immediately before the query.
- **Token Budget Allocation**: A well-designed prompt allocates tokens deliberately: ~10–15% for system instructions, ~50–70% for injected context, ~5–10% for conversation history, and ~15–25% reserved for the model's response.
- **Delimiters and Labeling**: Clear delimiters (XML tags, markdown fences) help the model parse injected sections. Without them, the model may confuse context content with instructions, especially in long prompts.
- **Few-Shot Examples**: Injecting 2–3 input/output examples dramatically improves format compliance and task understanding. Place examples after the system prompt and before the actual query.
## Usage
Use this skill whenever an AI model needs external information to complete a task accurately. Provide the raw context, the task description, and optionally a prompt template. The skill assembles a well-structured prompt with the context injected in the optimal position.
## Examples
### Example 1: Injecting a Code File for a Code Review Task
**Prompt Template:**
```
<system>
You are a senior software engineer performing a code review. Identify bugs,
security issues, and style violations. Be specific and cite line numbers.
</system>
<code_file path="src/api/users.py">
import sqlite3
from flask import Flask, request, jsonify
app = Flask(__name__)
def get_db():
return sqlite3.connect("users.db")
@app.route("/users", methods=["GET"])
def list_users():
db = get_db()
query = f"SELECT * FROM users WHERE role = '{request.args.get('role')}'"
results = db.execute(query).fetchall()
return jsonify(results)
@app.route("/users/<int:user_id>", methods=["DELETE"])
def delete_user(user_id):
db = get_db()
db.execute(f"DELETE FROM users WHERE id = {user_id}")
db.commit()
return "", 204
</code_file>
Review the above code file. List all issues found.
```
**Model Output:**
> 1. **SQL Injection (critical)** — Lines 12–13: User input from `request.args.get('role')` is interpolated directly into the SQL query. Use parameterized queries: `db.execute("SELECT * FROM users WHERE role = ?", (role,))`.
> 2. **SQL Injection** — Line 19: `user_id` is interpolated into the DELETE query. Use a parameterized query.
> 3. **No connection cleanup** — `get_db()` opens a connection but it is never closed. Use a context manager or Flask's `teardown_appcontext`.
> 4. **No authentication/authorization** — The DELETE endpoint has no access control. Any caller can delete any user.
### Example 2: Injecting User Profile Data for Personalized Responses
**Prompt Template:**
```
<system>
You are a helpful fitness assistant. Use the user's profile to personalize
your recommendations. Be encouraging and specific.
</system>
<user_profile>
Name: Sarah
Age: 34
Fitness level: Intermediate
Goals: Lose 10 lbs, improve 5K time
Injuries: Mild left knee tendinitis
Preferred activities: Running, yoga, swimming
Available equipment: Dumbbells (5-30 lbs), resistance bands, yoga mat
Schedule: Can train 4 days/week, 45 min per session
</user_profile>
Sarah asks: "Can you suggest a weekly workout plan for me?"
```
**Model Output:**Design reproducible evaluations for AI agents with representative task sets, explicit rubrics, appropriate graders, baselines, regression gates, and failure analysis. Use when defining agent quality, comparing prompts or models, validating a release, measuring tool-use reliability, investigating regressions, or deciding whether an agent is ready for production.
Design privacy-aware observability for AI agents using traces, spans, structured events, metrics, cost attribution, dashboards, alerts, and investigation workflows. Use when instrumenting an agent, debugging intermittent tool or model failures, defining service-level objectives, analyzing latency or spend, auditing agent decisions, or preparing production monitoring.
Design and verify auditable human oversight, approval gates, escalation paths, and safe state transitions for AI agent workflows. Use when deciding which agent actions require review, adding approve/reject or dual-control flows, preventing unauthorized autonomous effects, creating decision records, reducing rubber-stamping, or recovering safely from rejected, expired, or failed actions.
Design, implement, harden, and verify Model Context Protocol (MCP) servers with precise tool contracts, least-privilege authorization, safe transports, structured errors, and interoperability tests. Use when creating a new MCP server, exposing an API or data source through MCP, reviewing an MCP server design, adding or revising MCP tools, or preparing an MCP server for production.
Design and operate bounded multi-agent workflows with task decomposition, dependency graphs, ownership, handoff contracts, shared-state controls, approvals, recovery, and synthesis. Use when a task contains genuinely independent workstreams, specialized roles, parallel research or implementation, reviewer-worker loops, or coordination problems that one agent should not execute sequentially.
Design and validate model-facing tool definitions with clear names, action-oriented descriptions, bounded JSON Schema parameters, explicit side effects, safe defaults, idempotency, errors, and realistic tests. Use when creating function-calling tools, MCP tools, agent actions, structured tool inputs, or when a model selects the wrong tool, invents arguments, or causes unsafe side effects.
Plan, execute, document, and retest authorized security assessments of AI agents and multi-agent workflows using safe adversarial cases, synthetic identities, canaries, and evidence-based findings. Use when defining red-team rules of engagement, assessing prompt injection or excessive agency, testing tool and identity boundaries, evaluating memory or cross-agent attacks, scoring a campaign, or verifying remediation in an approved environment.
Threat-model and harden AI agents, RAG systems, assistants, and tool-using workflows against direct, indirect, stored, cross-agent, and multimodal prompt injection. Use when reviewing an agent architecture, isolating untrusted content, constraining tools and egress, protecting secrets, adding injection-focused tests, investigating a suspected injection incident, or documenting residual prompt-injection risk.