Best Practices
40 minutes
advanced

Context Preservation Tools

Use MCPs, RAGs, and Skills to maintain domain knowledge across sessions and scale beyond context limits.

What you'll accomplish

Understand when and how to use external context tools to enhance AI coding capabilities.

Prerequisites

  • Understanding of system documents
  • Experience with Claude Code or similar tools

When Documents Aren't Enough

System documents work until your project exceeds context limits. At some point:

  • Your codebase is too large to reference entirely
  • Documentation spans thousands of pages
  • You need real-time data (database state, API responses)
  • Repetitive tasks need automation

Context preservation tools bridge this gap by connecting the AI to external systems.

The Three Tools

┌─────────────────────────────────────────────────────────────┐
│                                                             │
│   MCP Servers          RAG Systems           Skills         │
│   ────────────         ───────────           ──────         │
│   Connect to           Search large          Automate       │
│   live systems         knowledge bases       common tasks   │
│                                                             │
│   Database queries     Documentation         Code reviews   │
│   API access           Codebase search       Migrations     │
│   Internal tools       Historical data       Deployments    │
│                                                             │
└─────────────────────────────────────────────────────────────┘

MCP: Model Context Protocol

MCP servers give the AI access to external systems. Think of them as plugins.

Common Use Cases

Database Access

json
{
  "name": "postgres-readonly",
  "config": {
    "connectionString": "${POSTGRES_URL}",
    "allowedOperations": ["SELECT"]
  }
}

Now the AI can query production data:

"What users signed up in the last 24 hours?"
"Show me the order with the highest value this month."

API Documentation

json
{
  "name": "openapi-docs",
  "config": {
    "specUrl": "https://api.example.com/openapi.json"
  }
}

The AI understands your API structure without you explaining it.

Internal Tools

json
{
  "name": "deployment-status",
  "config": {
    "endpoint": "https://internal.example.com/deployments"
  }
}

Ask about deployment status, feature flags, or infrastructure state.

When to Use MCP

Use CaseExample
Live data needed"Check current user count"
External API integration"Generate code matching our API spec"
Infrastructure queries"What's deployed to staging?"
Dynamic configuration"What feature flags are enabled?"

Security Considerations

Warning

MCP servers run with your permissions. Always:

  • Use read-only access where possible
  • Limit scope to what's needed
  • Never expose secrets through MCP
  • Audit what the AI accesses

RAG: Retrieval-Augmented Generation

RAG systems let the AI search large knowledge bases. Instead of cramming everything into context, the AI queries for relevant information.

How RAG Works

1. User asks: "How does authentication work?"
2. RAG system searches indexed documents
3. Returns relevant chunks (auth docs, code examples)
4. AI uses those chunks to answer

Building a RAG System

Index your content:

typescript
// Example: Index codebase with embeddings
const documents = await glob('src/**/*.ts');

for (const doc of documents) {
  const content = await fs.readFile(doc, 'utf-8');
  const embedding = await embeddings.create(content);
  await vectorStore.upsert({
    id: doc,
    content,
    embedding,
    metadata: { path: doc, type: 'source' }
  });
}

Query on demand:

typescript
async function search(query: string) {
  const queryEmbedding = await embeddings.create(query);
  return vectorStore.query(queryEmbedding, { topK: 5 });
}

What to Index

Content TypeUse Case
Source code"How is X implemented?"
Documentation"What's the process for Y?"
Decision records"Why did we choose Z?"
Past conversations"What did we decide about X?"
API specs"What endpoints handle Y?"

RAG vs Full Context

RAG isn't always the answer:

Use full context when:

  • Document is small (< 50 pages)
  • All information is relevant
  • Context is tightly interconnected
  • Precision matters more than breadth

Use RAG when:

  • Content exceeds context limits
  • Only portions are relevant
  • Information is modular
  • Speed matters more than exhaustiveness

Start with full context. Add RAG when you hit limits.

Skills: Reusable Task Templates

Skills (also called prompts or slash commands) automate common AI tasks. They're saved instructions the AI can execute.

Anatomy of a Skill

markdown
# Skill: Code Review

## Trigger
/review or "review this code"

## Instructions
When reviewing code, check for:

1. **Security**
   - SQL injection
   - XSS vulnerabilities
   - Hardcoded secrets
   - Insecure deserialization

2. **Performance**
   - N+1 queries
   - Missing indexes
   - Unnecessary re-renders
   - Memory leaks

3. **Maintainability**
   - Clear naming
   - Single responsibility
   - Appropriate abstraction
   - Documentation for complex logic

4. **Edge Cases**
   - Null handling
   - Empty arrays
   - Concurrent access
   - Error states

## Output Format
Provide findings grouped by severity:
- 🔴 Critical: Must fix before merge
- 🟡 Warning: Should fix
- 🟢 Suggestion: Nice to have

Common Skills

Migration Procedure

markdown
# Skill: Database Migration

1. Create migration file: `npx prisma migrate dev --name {description}`
2. Review generated SQL
3. Test on local database
4. Update affected service methods
5. Add types for new fields
6. Run full test suite
7. Create PR with migration

Checklist:
- [ ] Migration is reversible
- [ ] Indexes added for new foreign keys
- [ ] Default values for new required columns
- [ ] Existing data migrated correctly

Deployment Workflow

markdown
# Skill: Deploy to Production

Pre-deployment:
1. Ensure all tests pass
2. Check for pending migrations
3. Review environment variables
4. Verify feature flags

Deployment:
1. Merge to main
2. Wait for CI to pass
3. Trigger deployment
4. Monitor error rates

Post-deployment:
1. Smoke test critical paths
2. Check logs for errors
3. Verify metrics are normal
4. Update status page

Bug Investigation

markdown
# Skill: Investigate Bug

1. Reproduce the issue
2. Check logs around the time of occurrence
3. Identify affected users/scope
4. Trace the code path
5. Identify root cause
6. Document findings

Template for bug report:
- **Symptoms**: What the user sees
- **Root Cause**: Why it happens
- **Impact**: Who is affected
- **Fix**: What to change
- **Prevention**: How to avoid recurrence

Creating Effective Skills

Be specific, not generic:

markdown
# Bad
Review the code for issues

# Good
Review this API endpoint for:
- Authentication/authorization gaps
- Input validation (use Zod schemas)
- Error handling (use ApiError class)
- Rate limiting compliance
- Logging (use our logger, not console.log)

Include context:

markdown
# Our conventions
- We use Prisma, not raw SQL
- Errors return { error: string, code: number }
- All endpoints require auth except /health
- Rate limits: 100/min for authenticated, 10/min for anonymous

Specify output format:

markdown
Output as:
## Summary
[One paragraph]

## Changes Required
- [ ] File: change needed
- [ ] File: change needed

## Testing
Commands to verify the fix works

Choosing the Right Tool

┌────────────────────────────────────────────────────────────┐
│                     Decision Tree                          │
├────────────────────────────────────────────────────────────┤
│                                                            │
│  Need live/dynamic data? ──────────────> MCP Server        │
│           │                                                │
│           No                                               │
│           │                                                │
│  Searching large corpus? ──────────────> RAG System        │
│           │                                                │
│           No                                               │
│           │                                                │
│  Repeating same task? ─────────────────> Skill             │
│           │                                                │
│           No                                               │
│           │                                                │
│  Use system documents (AGENTS.md, etc.)                    │
│                                                            │
└────────────────────────────────────────────────────────────┘

Combined Example

A production setup might use all three:

Project Setup:
├── AGENTS.md                    # Static context
├── docs/                        # System documents
├── .claude/
│   ├── settings.json            # MCP config
│   │   └── mcpServers:
│   │       ├── postgres         # Database access
│   │       └── sentry           # Error tracking
│   └── skills/
│       ├── review.md            # Code review
│       ├── deploy.md            # Deployment
│       └── investigate.md       # Bug investigation
└── .rag/
    ├── index/                   # Vector embeddings
    └── config.json              # RAG configuration

Workflow:

  1. Start session → AI reads AGENTS.md (static context)
  2. Ask about codebase → RAG retrieves relevant code
  3. Query production state → MCP connects to database
  4. Ready to deploy → Skill guides the process

Common Issues

Frequently Asked Questions

Check:

  1. Server is running and accessible
  2. Credentials are correct
  3. Network allows the connection
  4. Server logs for errors

Test connection independently before involving the AI.

Improve relevance by:

  1. Better chunking (smaller, focused chunks)
  2. Adding metadata (file paths, types, dates)
  3. Tuning similarity thresholds
  4. Re-indexing after major changes

Make skills more effective:

  1. Use clear, unambiguous language
  2. Include examples of expected output
  3. Reference specific files and patterns
  4. Test with edge cases

Start simple. Add tools when:

  • You're repeatedly re-explaining context
  • Documents exceed context limits
  • You need real-time data
  • Same tasks happen weekly or more often

Each tool has setup cost. Only invest when the payoff is clear.

Verify Your Understanding

You've completed this lesson if you can:

0/4

Next: Leveraging agentic workflows for implementation.