Context Engineering Intro Template

repository·main·Indexed 12 days ago

https://github.com/coleam00/context-engineering-intro

A template and guide for implementing 'Context Engineering' to provide AI coding assistants with structured documentation, rules, and examples. Includes detailed instructions for using Claude Code, managing CLAUDE.md files, configuring tool permissions, integrating MCP servers, and implementing the Product Requirements Prompt (PRP) framework for high-quality feature implementation.

Tokens
63.7K
Snippets
122
Records
221
Agent score
95%

What's inside Context Engineering Intro

  1. Understand the Pydantic AI Template Structure

    main

    The template is organized into the following key directories:

    • CLAUDE.md: Global development rules for Pydantic AI.
    • .claude/commands/: Slash commands used for the PRP workflow.
    • PRPs/: Contains requirement templates and initial requirement files.
    • examples/: Contains several reference implementations:
      • basic_chat_agent/: Simple conversational agents with memory.
      • tool_enabled_agent/: Agents using @agent.tool and RunContext for dependency injection.
      • structured_output_agent/: Agents using result_type for Pydantic-validated data.
      • testing_examples/: Patterns for TestModel, FunctionModel, and Agent.override().
  2. Analyze AI M&A Landscape and Strategic Targets

    main
    This document serves as a reference for analyzing the AI Merger and Acquisition (M&A) market. It provides data on transaction volumes, strategic buyer profiles (Big Tech vs. Enterprise Software), and specific analysis of prime acquisition targets across infrastructure, vertical solutions, and specialized technologies. Use this data to model market consolidation trends, such as horizontal platform consolidation or vertical industry-specific integration.
  3. Implement the Claude Agent SDK Session Manager project

    main

    This project is a full-stack application designed to solve the limitation where the Claude Agent SDK does not expose an API to fetch historical messages. The solution involves storing messages in a local SQLite database while using the SDK's session_id to resume context.

    Tech Stack

    • Frontend: React, TypeScript, Vite, Tailwind, shadcn/ui
    • Backend: Python, FastAPI, sse-starlette
    • Database: SQLite with aiosqlite
    • Agent SDK: claude-agent-sdk

    Project Structure

    agent-session-manager/
    ├── backend/
    │   ├── app/
    │   │   ├── main.py           # FastAPI app entry
    │   │   ├── database.py       # SQLite connection + queries
    │   │   ├── models.py         # Pydantic models
    │   │   ├── routes/
    │   │   │   ├── sessions.py   # Session CRUD
    │   │   │   └── chat.py       # Chat with SSE streaming
    │   │   └── sdk_client.py     # Claude Agent SDK wrapper
    │   ├── requirements.txt
    │   └── pyproject.toml
    ├── frontend/
    │   ├── src/
    │   │   ├── components/
    │   │   │   ├── SessionSidebar.tsx
    │   │   │   ├── ChatView.tsx
    │   │   │   ├── MessageList.tsx
    │   │   │   ├── MessageBlock.tsx
    │   │   │   ├── ToolUseCard.tsx
    │   │   │   └── NewSessionDialog.tsx
    │   │   ├── lib/
    │   │   │   ├── api.ts
    │   │   │   └── types.ts
    │   │   ├── App.tsx
    │   │   └── main.tsx
    │   ├── package.json
    │   ├── vite.config.ts
    │   └── tailwind.config.js
    └── README.md
  4. What is the WISC Framework?

    main

    WISC is a context engineering framework designed to manage AI context during coding sessions. It is based on four core strategies:

    • W - Write: Externalize agent memory to files (e.g., specs, handoff notes) so it survives context resets.
    • I - Isolate: Use sub-agents for research to prevent noise from polluting the main coding session.
    • S - Select: Load only the specific context required for the current task rather than the entire codebase.
    • C - Compress: When sessions become too long, use compaction or hand off to a fresh session to maintain focus.
  5. Define integration contracts for Agent Teams

    main

    To enable parallel development without integration failures, the lead must define explicit contracts between layers (e.g., Database $\rightarrow$ Backend $\rightarrow$ Frontend).

    Contract Requirements:

    • URLs: Must be exact, including trailing slash conventions (e.g., POST /api/sessions/ vs POST /api/sessions).
    • Data Shapes: Use explicit JSON structures, not prose descriptions (e.g., {"session": {...}, "messages": [...]}).
    • SSE (Server-Sent Events): Document exact event types and JSON formats.
    • Error Responses: Specify status codes and body formats (e.g., 404 or 422 error bodies).
    • Storage Semantics: Define how data is stored (e.g., whether streaming chunks are accumulated into one row or stored individually).

    Contract Chain Example:

    • Database $\rightarrow$ Backend: Function signatures, Pydantic models, data types.
    • Backend $\rightarrow$ Frontend: API contracts (URLs, response shapes, SSE format).
  6. Best Practices and Anti-Patterns for MCP Servers

    main

    To ensure a robust and secure MCP server, adhere to these guidelines:

    ✅ Best Practices

    • Input Validation: Always use Zod schemas to validate tool parameters.
    • Resource Management: Implement the cleanup() method in your MCP class to close database connections or other resources.
    • Security: Use existing patterns like validateSqlQuery and isWriteOperation for database interactions. Separate read vs write operations based on user permissions.
    • Error Handling: Use createErrorResponse for tool errors and formatDatabaseError for database-specific issues.

    ❌ Anti-Patterns to Avoid

    • Skipping Validation: Never skip Zod input validation.
    • Ignoring Cleanup: Do not forget to implement cleanup() for stateful components like Durable Objects.
    • Hardcoding Permissions: Avoid hardcoding user permissions; use a configurable permission system instead.
    • Guessing Config: Do not guess OAuth configurations; always test the full flow locally.
  7. Model Future Geopolitical AI Scenarios

    main

    When performing strategic forecasting, consider these three primary scenarios:

    1. Continued US Leadership (45% Probability): US maintains a technological edge via private innovation; China faces semiconductor restrictions; Europe focuses on regulation; USD remains the dominant transaction currency.
    2. Bipolar AI Competition (35% Probability): China achieves semiconductor independence; two separate, incompatible AI ecosystems emerge (US-led vs. China-led); global market fragmentation.
    3. Multipolar AI World (20% Probability): Europe develops independent capabilities; regional leaders emerge (India, Japan, South Korea); international cooperation frameworks enable technology sharing.
  8. PydanticAI Agent Development Patterns

    main

    The PydanticAI template is specialized for several core agent architectures. When building or using examples from this template, follow these patterns:

    • chat_agent_with_memory: Simple conversation management with state/memory.
    • tool_integrated_agent: Agents equipped with external tools (e.g., web search, calculators).
    • workflow_processing_agent: Agents designed for multi-step, complex task processing.
    • structured_output_agent: Agents that return data conforming to specific Pydantic models.

    Key Technical Concepts to Implement:

    • Tool Registration: Use @agent.tool or @agent.tool_plain patterns.
    • Context Management: Utilize RunContext and dependency injection for tool execution.
    • Testing: Use TestModel and FunctionModel for unit testing agent logic without making live API calls.
  9. Create and use subagents

    main

    Subagents are specialized AI assistants that operate in separate context windows to perform focused tasks (e.g., security auditing, documentation management).

    Creating a Subagent: Create a markdown file in .claude/agents/ with a YAML frontmatter header defining its name, description, and allowed tools.

    ---
    name: security-auditor
    description: "Security specialist. Proactively reviews code for vulnerabilities and suggests improvements."
    tools: Read, Grep, Glob
    ---
    
    You are a security auditing specialist...

    Best Practices:

    • Focused Expertise: Assign one clear specialty per agent.
    • Proactive Descriptions: Use the keyword "proactively" in the description to encourage the primary agent to invoke the subagent automatically.
    • Tool Limitation: Only grant the tools necessary for the task (e.g., use Read and Grep for review-only agents without Write access).
    • One-Shot Context: Remember that subagents receive a single prompt from the primary agent and do not have the full conversation history.
  10. PydanticAI Agent Development Anti-Patterns

    main

    Avoid these common mistakes when developing with PydanticAI:

    Agent Development

    • Skipping TestModel validation during development.
    • Hardcoding API keys (always use environment variables).
    • Ignoring async patterns (PydanticAI has specific async/sync requirements).
    • Creating overly complex tool chains (keep tools focused and composable).
    • Neglecting error handling (implement retries and fallbacks).

    Architecture

    • Mixing agent types (clearly separate chat, tool, workflow, and structured output patterns).
    • Ignoring dependency injection (use proper type-safe dependency management).
    • Skipping output validation (always use Pydantic models for structured responses).
    • Forgetting tool documentation (ensure all tools have proper descriptions and schemas).

    Security & Production

    • Exposing sensitive data in outputs or logs.
    • Skipping input validation (sanitize and validate all user inputs).
    • Ignoring rate limiting (implement throttling for external services).
    • Deploying without monitoring/observability.
  11. Identify AI Technology Export Controls and Restrictions

    main

    When modeling AI supply chains or regulatory risks, consider these three primary regimes of restriction:

    • US Export Control Regime: Targets semiconductor access (advanced AI chips), software/development tools, research collaboration limits, and investment screening via CFIUS.
    • China's Retaliatory Measures: Includes restrictions on rare earth materials, data localization requirements, technology transfer mandates (joint ventures), and academic collaboration limits.
    • European Digital Sovereignty: Driven by governance frameworks like GDPR and the Digital Markets Act, focusing on strategic autonomy and reducing dependence on non-European AI technologies.
  12. Automate Claude Code behavior with Hooks

    main

    Hooks allow you to execute deterministic shell commands at specific lifecycle events in Claude Code. This is useful for logging, security validations, or triggering builds automatically.

    Available Hook Events

    • PreToolUse: Before tool execution (can block operations)
    • PostToolUse: After successful tool completion
    • UserPromptSubmit: When user submits a prompt
    • SubagentStop: When a subagent completes its task
    • Stop: When the main agent finishes responding
    • SessionStart: At session initialization
    • PreCompact: Before context compaction
    • Notification: During system notifications

    Setup Steps

    1. Create your shell script in .claude/hooks/.
    2. Make the script executable: chmod +x your-hook.sh.
    3. Register the hook in .claude/settings.local.json using a matcher and the command type.
    {
      "hooks": {
        "PostToolUse": [
          {
            "matcher": ".*",
            "hooks": [
              {
                "type": "command",
                "command": ".claude/hooks/log-tool-usage.sh"
              }
            ]
          }
        ]
      }
    }