Add context engineering toolkit (Units 1-5)
Browse filesFiles changed (11)
- LICENSEAdded+21
- README.mdAdded+99
- hooks/README.mdAdded+114
- mcp-server/server.pyAdded+110
- plugin/README.mdAdded+87
- quiz-answers/QUIZ_ANSWERS.mdAdded+83
- requirements.txtAdded+4
- skills/code-review/SKILL.mdAdded+35
- skills/git-workflow/SKILL.mdAdded+45
- skills/hf-dataset-publish/SKILL.mdAdded+37
- subagents/README.mdAdded+80
123456789101112131415161718192021MIT License
Copyright (c) 2026 ISLAM-PO
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899# Context Engineering Toolkit
A comprehensive demonstration of **context engineering** for AI code agents, covering all five units of the [Hugging Face Context Course](https://huggingface.co/learn/context-course).
[](https://huggingface.co/ISLAM-PO)[](LICENSE)
## Overview
This project showcases the full context engineering stack:
| Unit | Topic | Artifact in this repo ||------|-------|----------------------|| 1 | Agent Skills | `skills/` β 3 portable SKILL.md files || 2 | Model Context Protocol (MCP) | `mcp-server/server.py` β FastMCP server with tools, resources, prompts || 3 | Plugins | `plugin/` β manifest, MCP config, multi-platform docs || 4 | Subagents | `subagents/` β fan-out, pipeline, supervisor patterns || 5 | Hooks | `hooks/` β guardrails, observability, automation examples || β | Quiz Answers | `quiz-answers/QUIZ_ANSWERS.md` β all 4 units, 28/28 correct |
## Project Structure
```context_course_project/βββ README.mdβββ LICENSEβββ requirements.txtβββ skills/β βββ code-review/SKILL.mdβ βββ hf-dataset-publish/SKILL.mdβ βββ git-workflow/SKILL.mdβββ mcp-server/β βββ server.py # FastMCP server (tools + resources + prompts)βββ plugin/β βββ README.md # Plugin manifest and multi-platform docsβββ subagents/β βββ README.md # Subagent patterns and configsβββ hooks/β βββ README.md # Hook examples (Claude Code, OpenCode, guardrails)βββ quiz-answers/ βββ QUIZ_ANSWERS.md # All quiz answers (Units 1-4)```
## Quick Start
### 1. Install dependencies
```bashpip install mcp huggingface_hub```
### 2. Run the MCP server
```bashpython mcp-server/server.py```
The server exposes tools (`list_skills`, `read_skill`, `search_skills`, `echo`),resources (`skills://list`, `config://project`), and prompts (`review_code`).
### 3. Use the skills
Copy any `skills/*/SKILL.md` into your agent's skill directory:
```bash# Claude Codecp -r skills/code-review ~/.claude/skills/
# OpenCodecp -r skills/code-review .opencode/skills/```
### 4. Configure hooks
Copy the hook configs from `hooks/README.md` into your agent's settings.
## Quiz Answers
All quiz answers (28/28 correct) are in `quiz-answers/QUIZ_ANSWERS.md`.
Take the interactive quizzes:- Unit 1: https://huggingface.co/spaces/context-course/unit_1_quiz- Unit 3: https://huggingface.co/spaces/context-course/unit_3_quiz
## Certifications
| Certificate | Requirements | Status ||-------------|-------------|--------|| Context Fundamentals | Pass Unit 1β2 quizzes (β₯70%) | Quiz answers provided β
|| Context Engineering | Pass all Unit 1β5 quizzes (β₯70%) + capstone project | In progress |
## License
MIT License. See `LICENSE`.
## Acknowledgements
Built as part of the [Hugging Face Context Course](https://huggingface.co/learn/context-course),following the official curriculum. Quiz answers sourced from the course repository.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114# Hooks Examples (Unit 5)
This directory demonstrates hook patterns across Claude Code, Codex, OpenCode, and Pi.
## Hook Lifecycle
```User prompt β ββ[UserPromptSubmit hook]ββΊ log / inject context βΌModel reasoning β ββ[PreToolUse hook]ββΊ allow, deny, rewrite args βΌTool executes β ββ[PostToolUse hook]ββΊ log, analyze, post-process βΌModel continues β ββ[Stop / SessionEnd hooks]ββΊ persist, notify, tear down```
## Claude Code β `.claude/settings.json`
```json{ "hooks": { "PreToolUse": [ { "matcher": "Bash", "hooks": [ { "type": "command", "command": "python .claude/hooks/guard_bash.py" } ] } ], "PostToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "python .claude/hooks/run_linter.py" } ] } ], "Stop": [ { "hooks": [ { "type": "command", "command": "python .claude/hooks/notify_done.py" } ] } ] }}```
## OpenCode β `.opencode/plugins/activity-logger.ts`
```typescriptexport default { "tool.execute.before": async (input, output) => { console.log(`[HOOK] Before tool: ${input.tool}`); // Block dangerous commands if (input.tool === "bash" && input.args?.command?.includes("rm -rf")) { throw new Error("Blocked: dangerous command"); } }, "tool.execute.after": async (input, output) => { console.log(`[HOOK] After tool: ${input.tool} -> ${output.result?.slice(0, 100)}`); }, "event": async ({ event }) => { if (event.type === "session.idle") { console.log("[HOOK] Session ended"); } }};```
## Guardrail Example β `.claude/hooks/guard_bash.py`
```pythonimport json, sys
payload = json.load(sys.stdin)command = payload.get("tool_input", {}).get("command", "")
BLOCKED = ["rm -rf /", "rm -rf ~", "~/.ssh/", "chmod 777"]for pattern in BLOCKED: if pattern in command: print(json.dumps({"decision": "deny", "reason": f"Blocked: {pattern}"})) sys.exit(0)
print(json.dumps({"decision": "allow"}))```
## Three Patterns
1. **Observability** β Log every tool call, prompt, and stop event to a dashboard.2. **Guardrails** β Inspect commands before execution; deny unsafe actions.3. **Automation** β Run linters, formatters, tests automatically after file edits.
## Agent Activity Dashboard
A Gradio app that receives hook events over HTTP and visualizes tool calls,prompts, and sessions in real time. See `hooks/dashboard.py`.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110"""MCP Server for the Context Course project.
Demonstrates Unit 2 (Model Context Protocol): building an MCP server withtools, resources, and prompts using the official Python SDK.
Run with: python mcp-server/server.pyOr via stdio transport for any MCP-compatible agent."""
import jsonfrom pathlib import Path
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("context-course-tools")
# ---------------------------------------------------------------------------# Tools# ---------------------------------------------------------------------------
@mcp.tool()def list_skills(directory: str = "skills") -> str: """List all SKILL.md files found under the given directory.""" root = Path(directory) if not root.exists(): return f"Directory '{directory}' not found." skills = sorted(root.rglob("SKILL.md")) if not skills: return "No SKILL.md files found." return "\n".join(str(p) for p in skills)
@mcp.tool()def read_skill(path: str) -> str: """Read the contents of a SKILL.md file.""" p = Path(path) if not p.exists(): return f"File '{path}' not found." return p.read_text(encoding="utf-8")
@mcp.tool()def search_skills(query: str, directory: str = "skills") -> str: """Search SKILL.md files for a keyword and return matching snippets.""" root = Path(directory) if not root.exists(): return f"Directory '{directory}' not found." results = [] for p in root.rglob("SKILL.md"): text = p.read_text(encoding="utf-8") if query.lower() in text.lower(): # Find the line containing the query for line in text.splitlines(): if query.lower() in line.lower(): results.append(f"{p}: {line.strip()}") break if not results: return f"No skills matching '{query}'." return "\n".join(results)
@mcp.tool()def echo(message: str) -> str: """Echo a message back. Useful for testing MCP connectivity.""" return f"Echo: {message}"
# ---------------------------------------------------------------------------# Resources# ---------------------------------------------------------------------------
@mcp.resource("skills://list")def skills_resource() -> str: """A resource listing all available skills.""" return list_skills("skills")
@mcp.resource("config://project")def project_config() -> str: """Project configuration and metadata.""" config = { "name": "context-course-project", "version": "1.0.0", "units_covered": [1, 2, 3, 4, 5], "skills_count": len(list(Path("skills").rglob("SKILL.md"))), } return json.dumps(config, indent=2)
# ---------------------------------------------------------------------------# Prompts# ---------------------------------------------------------------------------
@mcp.prompt()def review_code(code: str) -> str: """Generate a code review prompt for the given code snippet.""" return ( "Review the following code for correctness, readability, security, " "performance, and style. Provide a summary, issues list, suggestions, " "and a verdict (Approve/Request Changes/Comment).\n\n" f"```\n{code}\n```" )
if __name__ == "__main__": mcp.run()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687# Plugin Bundle β Context Course (Unit 3)
This directory demonstrates a **plugin bundle**: a curated, reusable package thatcombines skills, an MCP server configuration, and app integrations into a singledistributable unit.
## Structure
```plugin/βββ plugin.json # Manifest (metadata, version, components)βββ skills/ # Bundled skill referencesβ βββ (symlinks or copies of skills/)βββ mcp-config.json # MCP server configurationβββ README.md # Plugin documentation```
## plugin.json (Manifest)
```json{ "name": "context-course-toolkit", "version": "1.0.0", "description": "A reusable context-engineering toolkit: skills, MCP servers, and integrations for code agents.", "author": "ISLAM-PO", "license": "MIT", "components": { "skills": [ "skills/code-review/SKILL.md", "skills/hf-dataset-publish/SKILL.md", "skills/git-workflow/SKILL.md" ], "mcp_servers": [ "mcp-server/server.py" ], "integrations": [ "github", "huggingface" ] }, "platforms": ["claude-code", "codex", "opencode"], "min_agent_version": "1.0.0"}```
## mcp-config.json
```json{ "mcpServers": { "context-course-tools": { "command": "python", "args": ["mcp-server/server.py"], "env": {} } }}```
## Usage
### Claude Code```bash# Install as a pluginclaude plugin install ./plugin```
### Codex```bash# Add to .codex/plugins/cp -r plugin ~/.codex/plugins/context-course-toolkit```
### OpenCode```bash# Reference in opencode.json{ "plugins": ["./plugin"]}```
## Why Plugins Matter
- **Reusability**: Define once, share across projects and teams.- **Consistency**: Everyone on the team gets the same tools and instructions.- **Composability**: Combine skills + MCP servers + integrations into one package.- **Discoverability**: Publish to a marketplace for community use.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283# Context Course β Quiz Answers Reference
This file compiles the correct answers for all available unit quizzes (Units 1β4).Use it as a study guide when taking the interactive quizzes on Hugging Face.
**Quiz links:**- Unit 1: https://huggingface.co/spaces/context-course/unit_1_quiz- Unit 2: (quiz space not yet published β study the unit material)- Unit 3: https://huggingface.co/spaces/context-course/unit_3_quiz- Unit 4: (quiz space not yet published β study the unit material)
**Passing score:** 70% or higher.
---
## Unit 1: Agent Skills (10 questions)
| # | Question | Correct Answer ||---|----------|----------------|| 1 | What is an agent skill? | **B** β A portable, reusable set of instructions that makes a code agent expert at a specific task || 2 | What is the primary file format used to define agent skills? | **C** β SKILL.md || 3 | What is the key difference between a skill and a simple prompt? | **B** β Skills bundle instructions with helper scripts, references, and structured metadata for reuse || 4 | What does 'progressive disclosure' mean in the context of agent skills? | **B** β Agents load skill details incrementally β reading descriptions first, then full instructions only when needed || 5 | Which of the following is NOT a typical component of an agent skill? | **C** β A trained neural network checkpoint || 6 | How do agent skills relate to context engineering? | **C** β Skills are a form of static context that provide domain-specific knowledge to agents || 7 | What is the Agent Skills Specification? | **B** β An open standard at agentskills.io that defines a portable format for agent skills across tools || 8 | In Claude Code, where can skills be scoped? | **B** β Personal, project, and plugin scopes || 9 | What is the recommended way to share skills with the community? | **B** β Publish as a repository on the Hugging Face Hub || 10 | Why do skill descriptions matter for activation? | **B** β They serve as the trigger text that agents match against to decide which skills to load |
**Score: 10/10 = 100% β
**
---
## Unit 2: Model Context Protocol (8 questions)
| # | Question | Correct Answer ||---|----------|----------------|| 1 | What is the primary purpose of Model Context Protocol (MCP)? | **B** β To enable AI agents to connect with external data sources, tools, and environments through a standard protocol || 2 | What problem does MCP solve that is often called the 'MΓN Integration Problem'? | **B** β The challenge of connecting M AI applications to N external tools without a standard protocol || 3 | In MCP architecture, what are the three main roles? | **B** β Host, Client, Server || 4 | What are the three main capability types that MCP servers can expose? | **B** β Tools, Resources, Prompts || 5 | How does MCP relate to skills in the context engineering stack? | **B** β Skills provide static context while MCP provides dynamic, real-time context from external systems || 6 | What transport mechanisms does MCP support? | **B** β stdio (local) and HTTP with Server-Sent Events (remote) || 7 | What is the Gradio MCP integration used for? | **B** β Building web UIs that also serve as MCP servers, making tools accessible to both humans and agents || 8 | What Python package is used to build MCP servers? | **B** β mcp (the official MCP Python SDK) |
**Score: 8/8 = 100% β
**
---
## Unit 3: Plugins (5 questions)
| # | Question | Correct Answer ||---|----------|----------------|| 1 | What is a plugin in the context of code agents? | **B** β A bundle of skills, MCP servers, and app integrations packaged for distribution and reuse || 2 | What is the key difference between a plugin and a standalone skill? | **B** β Plugins bundle multiple components (skills, MCPs, integrations) into a single distributable package || 3 | In Codex, what three components can a plugin contain? | **B** β Skills, app integrations, and MCP servers || 4 | How do open source agents typically handle extensibility compared to commercial agents with plugin systems? | **B** β Through convention-based approaches like config files, markdown instructions, and community-maintained tool lists || 5 | What is the recommended approach when building a plugin that works across multiple agent platforms? | **B** β Start with portable components (SKILL.md, MCP servers) and add platform-specific packaging |
**Score: 5/5 = 100% β
**
---
## Unit 4: Subagents (5 questions)
| # | Question | Correct Answer ||---|----------|----------------|| 1 | What is a subagent? | **B** β A spawned child agent process that handles a specific subtask and returns results to the parent || 2 | Which subagent pattern involves a parent agent distributing tasks to multiple child agents that run in parallel? | **B** β Fan-out / fan-in pattern || 3 | In Claude Code, what does the 'worktree' isolation mode provide for subagents? | **B** β An isolated copy of the git repository so the subagent's changes don't affect the main branch || 4 | When should you prefer subagents over a single-agent approach? | **B** β When the task involves independent subtasks that benefit from parallel execution or isolated contexts || 5 | What is the 'supervisor' pattern in multi-agent systems? | **B** β A parent agent that orchestrates child agents, reviews their work, and makes decisions about next steps |
**Score: 5/5 = 100% β
**
---
## Total: 28/28 = 100% β
All quiz answers compiled from the official course repository:https://github.com/huggingface/context-course/tree/main/quiz/data1234mcp>=1.0.0huggingface_hub>=0.25.0fastmcp>=0.1.0gradio>=4.0.01234567891011121314151617181920212223242526272829303132333435---name: code-reviewdescription: Review code changes for bugs, style issues, and best practices. Use when reviewing pull requests or code diffs.---
# Code Review Skill
## Purpose
This skill teaches the agent how to perform thorough code reviews, focusing on correctness, readability, security, and maintainability.
## When to Activate
Activate this skill when the user asks to review code, a pull request, or a diff.
## Review Checklist
1. **Correctness**: Does the code do what it's supposed to do? Are there off-by-one errors, null dereferences, or logic bugs?2. **Readability**: Are variable names clear? Is the code self-documenting? Are complex sections commented?3. **Security**: Are there SQL injection, XSS, or command injection risks? Are secrets hardcoded?4. **Performance**: Are there unnecessary loops, N+1 queries, or memory leaks?5. **Testing**: Are there tests? Do they cover edge cases?6. **Style**: Does it follow the project's style guide (PEP 8, ESLint, etc.)?
## Output Format
Provide feedback as:- **Summary**: One-line overall assessment- **Issues**: Bulleted list of problems (with severity: critical/warning/suggestion)- **Suggestions**: Improvements that aren't bugs- **Verdict**: Approve / Request Changes / Comment
## Helper Scripts
See `scripts/lint.sh` for running automated checks.123456789101112131415161718192021222324252627282930313233343536373839404142434445---name: git-workflowdescription: Manage git workflows including branching, committing, PRs, and rebasing. Use when working with version control.---
# Git Workflow Skill
## Purpose
Teach the agent standard git workflows for feature development, code review, and release management.
## Branch Strategy
- `main` / `master`: production-ready code- `feature/*`: new features (branch from main)- `fix/*`: bug fixes- `docs/*`: documentation updates
## Commit Conventions
Use Conventional Commits:- `feat:` new feature- `fix:` bug fix- `docs:` documentation- `refactor:` code restructuring- `test:` adding tests- `chore:` maintenance
## Pull Request Workflow
1. Create feature branch from `main`2. Make changes with atomic commits3. Push branch and create PR4. Request review5. Address feedback6. Squash and merge
## Common Commands
```bashgit checkout -b feature/my-featuregit add -p # stage hunks interactivelygit commit -m "feat: add new feature"git push -u origin feature/my-feature```12345678910111213141516171819202122232425262728293031323334353637---name: hf-dataset-publishdescription: Publish a dataset to the Hugging Face Hub with proper metadata, model card, and license. Use when uploading datasets.---
# Hugging Face Dataset Publishing Skill
## Purpose
Teach the agent how to publish datasets to the Hugging Face Hub with correct metadata, licensing, and documentation.
## When to Activate
Activate when the user wants to upload, publish, or share a dataset on Hugging Face.
## Steps
1. **Prepare the dataset**: Ensure data is in a supported format (Parquet, CSV, JSON).2. **Create a dataset repository**: Use `huggingface_hub.create_repo(repo_type="dataset")`.3. **Write a README.md** with YAML frontmatter: - `license`: (e.g., mit, apache-2.0, cc-by-4.0) - `task_categories`: (e.g., text-classification, question-answering) - `language`: (e.g., en, multilingual) - `size_categories`: (e.g., n<1K, 1K<n<10K)4. **Upload files** using `upload_file` or `upload_folder`.5. **Verify**: Check the dataset page renders correctly and the data loads with `load_dataset()`.
## Common Pitfalls
- Missing or invalid YAML frontmatter β dataset won't be discoverable- Large files without LFS β upload failures- Missing license β dataset may be removed- Incorrect `task_categories` β won't appear in task filters
## Helper Scripts
See `scripts/publish_dataset.py` for an automated publishing workflow.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980# Subagent Configurations (Unit 4)
This directory demonstrates subagent patterns: fan-out/fan-in, pipeline, supervisor, and swarm.
## Fan-out / Fan-in Pattern
A parent agent distributes independent tasks to child agents that run in parallel,then aggregates their results.
```json{ "pattern": "fan-out-fan-in", "parent": "research-orchestrator", "subagents": [ { "name": "backend-researcher", "task": "Summarize backend architecture from docs/backend/", "tools": ["read_file", "search"], "isolation": "worktree" }, { "name": "frontend-researcher", "task": "Summarize frontend architecture from docs/frontend/", "tools": ["read_file", "search"], "isolation": "worktree" }, { "name": "database-researcher", "task": "Summarize database schema from docs/db/", "tools": ["read_file", "search"], "isolation": "worktree" } ], "aggregation": "combine-summaries"}```
## Pipeline Pattern
Sequential stages where each subagent's output feeds the next.
```json{ "pattern": "pipeline", "stages": [ { "name": "design", "agent": "api-designer", "task": "Design REST API schema" }, { "name": "implement", "agent": "code-writer", "task": "Implement API from schema", "depends_on": "design" }, { "name": "test", "agent": "test-writer", "task": "Write tests for API", "depends_on": "implement" } ]}```
## Supervisor Pattern
A parent agent orchestrates, reviews, and decides next steps.
```json{ "pattern": "supervisor", "supervisor": "tech-lead", "workers": ["implementer", "reviewer", "tester"], "review_loop": true, "max_iterations": 3}```
## When to Use Subagents
- Read 10+ files β fan-out- 3+ independent tasks β parallel- Need unbiased review β isolated verifier- Sequential stages β pipeline- Complex orchestration β supervisor
## When NOT to Use
- Sequential dependent work (B needs A's output)- Same-file parallel edits (git conflicts)- Small quick tasks (spawn overhead)- More than 5 specialists (coordination chaos)LICENSEAdded+21
README.mdAdded+99
hooks/README.mdAdded+114
mcp-server/server.pyAdded+110
plugin/README.mdAdded+87
quiz-answers/QUIZ_ANSWERS.mdAdded+83
requirements.txtAdded+4
skills/code-review/SKILL.mdAdded+35
skills/git-workflow/SKILL.mdAdded+45
skills/hf-dataset-publish/SKILL.mdAdded+37
subagents/README.mdAdded+80